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->getSubExpr(); 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(const ASTContext &Ctx, const 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 bool isStdFunction() const { 599 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 600 if (DC->isStdNamespace()) 601 return true; 602 return false; 603 } 604 }; 605 606 /// Temporarily override 'this'. 607 class ThisOverrideRAII { 608 public: 609 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 610 : Frame(Frame), OldThis(Frame.This) { 611 if (Enable) 612 Frame.This = NewThis; 613 } 614 ~ThisOverrideRAII() { 615 Frame.This = OldThis; 616 } 617 private: 618 CallStackFrame &Frame; 619 const LValue *OldThis; 620 }; 621 } 622 623 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 624 const LValue &This, QualType ThisType); 625 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 626 APValue::LValueBase LVBase, APValue &Value, 627 QualType T); 628 629 namespace { 630 /// A cleanup, and a flag indicating whether it is lifetime-extended. 631 class Cleanup { 632 llvm::PointerIntPair<APValue*, 1, bool> Value; 633 APValue::LValueBase Base; 634 QualType T; 635 636 public: 637 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 638 bool IsLifetimeExtended) 639 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {} 640 641 bool isLifetimeExtended() const { return Value.getInt(); } 642 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 643 if (RunDestructors) { 644 SourceLocation Loc; 645 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 646 Loc = VD->getLocation(); 647 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 648 Loc = E->getExprLoc(); 649 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 650 } 651 *Value.getPointer() = APValue(); 652 return true; 653 } 654 655 bool hasSideEffect() { 656 return T.isDestructedType(); 657 } 658 }; 659 660 /// A reference to an object whose construction we are currently evaluating. 661 struct ObjectUnderConstruction { 662 APValue::LValueBase Base; 663 ArrayRef<APValue::LValuePathEntry> Path; 664 friend bool operator==(const ObjectUnderConstruction &LHS, 665 const ObjectUnderConstruction &RHS) { 666 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 667 } 668 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 669 return llvm::hash_combine(Obj.Base, Obj.Path); 670 } 671 }; 672 enum class ConstructionPhase { 673 None, 674 Bases, 675 AfterBases, 676 Destroying, 677 DestroyingBases 678 }; 679 } 680 681 namespace llvm { 682 template<> struct DenseMapInfo<ObjectUnderConstruction> { 683 using Base = DenseMapInfo<APValue::LValueBase>; 684 static ObjectUnderConstruction getEmptyKey() { 685 return {Base::getEmptyKey(), {}}; } 686 static ObjectUnderConstruction getTombstoneKey() { 687 return {Base::getTombstoneKey(), {}}; 688 } 689 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 690 return hash_value(Object); 691 } 692 static bool isEqual(const ObjectUnderConstruction &LHS, 693 const ObjectUnderConstruction &RHS) { 694 return LHS == RHS; 695 } 696 }; 697 } 698 699 namespace { 700 /// A dynamically-allocated heap object. 701 struct DynAlloc { 702 /// The value of this heap-allocated object. 703 APValue Value; 704 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 705 /// or a CallExpr (the latter is for direct calls to operator new inside 706 /// std::allocator<T>::allocate). 707 const Expr *AllocExpr = nullptr; 708 709 enum Kind { 710 New, 711 ArrayNew, 712 StdAllocator 713 }; 714 715 /// Get the kind of the allocation. This must match between allocation 716 /// and deallocation. 717 Kind getKind() const { 718 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 719 return NE->isArray() ? ArrayNew : New; 720 assert(isa<CallExpr>(AllocExpr)); 721 return StdAllocator; 722 } 723 }; 724 725 struct DynAllocOrder { 726 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 727 return L.getIndex() < R.getIndex(); 728 } 729 }; 730 731 /// EvalInfo - This is a private struct used by the evaluator to capture 732 /// information about a subexpression as it is folded. It retains information 733 /// about the AST context, but also maintains information about the folded 734 /// expression. 735 /// 736 /// If an expression could be evaluated, it is still possible it is not a C 737 /// "integer constant expression" or constant expression. If not, this struct 738 /// captures information about how and why not. 739 /// 740 /// One bit of information passed *into* the request for constant folding 741 /// indicates whether the subexpression is "evaluated" or not according to C 742 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 743 /// evaluate the expression regardless of what the RHS is, but C only allows 744 /// certain things in certain situations. 745 class EvalInfo : public interp::State { 746 public: 747 ASTContext &Ctx; 748 749 /// EvalStatus - Contains information about the evaluation. 750 Expr::EvalStatus &EvalStatus; 751 752 /// CurrentCall - The top of the constexpr call stack. 753 CallStackFrame *CurrentCall; 754 755 /// CallStackDepth - The number of calls in the call stack right now. 756 unsigned CallStackDepth; 757 758 /// NextCallIndex - The next call index to assign. 759 unsigned NextCallIndex; 760 761 /// StepsLeft - The remaining number of evaluation steps we're permitted 762 /// to perform. This is essentially a limit for the number of statements 763 /// we will evaluate. 764 unsigned StepsLeft; 765 766 /// Force the use of the experimental new constant interpreter, bailing out 767 /// with an error if a feature is not supported. 768 bool ForceNewConstInterp; 769 770 /// Enable the experimental new constant interpreter. 771 bool EnableNewConstInterp; 772 773 /// BottomFrame - The frame in which evaluation started. This must be 774 /// initialized after CurrentCall and CallStackDepth. 775 CallStackFrame BottomFrame; 776 777 /// A stack of values whose lifetimes end at the end of some surrounding 778 /// evaluation frame. 779 llvm::SmallVector<Cleanup, 16> CleanupStack; 780 781 /// EvaluatingDecl - This is the declaration whose initializer is being 782 /// evaluated, if any. 783 APValue::LValueBase EvaluatingDecl; 784 785 enum class EvaluatingDeclKind { 786 None, 787 /// We're evaluating the construction of EvaluatingDecl. 788 Ctor, 789 /// We're evaluating the destruction of EvaluatingDecl. 790 Dtor, 791 }; 792 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 793 794 /// EvaluatingDeclValue - This is the value being constructed for the 795 /// declaration whose initializer is being evaluated, if any. 796 APValue *EvaluatingDeclValue; 797 798 /// Set of objects that are currently being constructed. 799 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 800 ObjectsUnderConstruction; 801 802 /// Current heap allocations, along with the location where each was 803 /// allocated. We use std::map here because we need stable addresses 804 /// for the stored APValues. 805 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 806 807 /// The number of heap allocations performed so far in this evaluation. 808 unsigned NumHeapAllocs = 0; 809 810 struct EvaluatingConstructorRAII { 811 EvalInfo &EI; 812 ObjectUnderConstruction Object; 813 bool DidInsert; 814 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 815 bool HasBases) 816 : EI(EI), Object(Object) { 817 DidInsert = 818 EI.ObjectsUnderConstruction 819 .insert({Object, HasBases ? ConstructionPhase::Bases 820 : ConstructionPhase::AfterBases}) 821 .second; 822 } 823 void finishedConstructingBases() { 824 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 825 } 826 ~EvaluatingConstructorRAII() { 827 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 828 } 829 }; 830 831 struct EvaluatingDestructorRAII { 832 EvalInfo &EI; 833 ObjectUnderConstruction Object; 834 bool DidInsert; 835 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 836 : EI(EI), Object(Object) { 837 DidInsert = EI.ObjectsUnderConstruction 838 .insert({Object, ConstructionPhase::Destroying}) 839 .second; 840 } 841 void startedDestroyingBases() { 842 EI.ObjectsUnderConstruction[Object] = 843 ConstructionPhase::DestroyingBases; 844 } 845 ~EvaluatingDestructorRAII() { 846 if (DidInsert) 847 EI.ObjectsUnderConstruction.erase(Object); 848 } 849 }; 850 851 ConstructionPhase 852 isEvaluatingCtorDtor(APValue::LValueBase Base, 853 ArrayRef<APValue::LValuePathEntry> Path) { 854 return ObjectsUnderConstruction.lookup({Base, Path}); 855 } 856 857 /// If we're currently speculatively evaluating, the outermost call stack 858 /// depth at which we can mutate state, otherwise 0. 859 unsigned SpeculativeEvaluationDepth = 0; 860 861 /// The current array initialization index, if we're performing array 862 /// initialization. 863 uint64_t ArrayInitIndex = -1; 864 865 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 866 /// notes attached to it will also be stored, otherwise they will not be. 867 bool HasActiveDiagnostic; 868 869 /// Have we emitted a diagnostic explaining why we couldn't constant 870 /// fold (not just why it's not strictly a constant expression)? 871 bool HasFoldFailureDiagnostic; 872 873 /// Whether or not we're in a context where the front end requires a 874 /// constant value. 875 bool InConstantContext; 876 877 /// Whether we're checking that an expression is a potential constant 878 /// expression. If so, do not fail on constructs that could become constant 879 /// later on (such as a use of an undefined global). 880 bool CheckingPotentialConstantExpression = false; 881 882 /// Whether we're checking for an expression that has undefined behavior. 883 /// If so, we will produce warnings if we encounter an operation that is 884 /// always undefined. 885 bool CheckingForUndefinedBehavior = false; 886 887 enum EvaluationMode { 888 /// Evaluate as a constant expression. Stop if we find that the expression 889 /// is not a constant expression. 890 EM_ConstantExpression, 891 892 /// Evaluate as a constant expression. Stop if we find that the expression 893 /// is not a constant expression. Some expressions can be retried in the 894 /// optimizer if we don't constant fold them here, but in an unevaluated 895 /// context we try to fold them immediately since the optimizer never 896 /// gets a chance to look at it. 897 EM_ConstantExpressionUnevaluated, 898 899 /// Fold the expression to a constant. Stop if we hit a side-effect that 900 /// we can't model. 901 EM_ConstantFold, 902 903 /// Evaluate in any way we know how. Don't worry about side-effects that 904 /// can't be modeled. 905 EM_IgnoreSideEffects, 906 } EvalMode; 907 908 /// Are we checking whether the expression is a potential constant 909 /// expression? 910 bool checkingPotentialConstantExpression() const override { 911 return CheckingPotentialConstantExpression; 912 } 913 914 /// Are we checking an expression for overflow? 915 // FIXME: We should check for any kind of undefined or suspicious behavior 916 // in such constructs, not just overflow. 917 bool checkingForUndefinedBehavior() const override { 918 return CheckingForUndefinedBehavior; 919 } 920 921 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 922 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 923 CallStackDepth(0), NextCallIndex(1), 924 StepsLeft(C.getLangOpts().ConstexprStepLimit), 925 ForceNewConstInterp(C.getLangOpts().ForceNewConstInterp), 926 EnableNewConstInterp(ForceNewConstInterp || 927 C.getLangOpts().EnableNewConstInterp), 928 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 929 EvaluatingDecl((const ValueDecl *)nullptr), 930 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 931 HasFoldFailureDiagnostic(false), InConstantContext(false), 932 EvalMode(Mode) {} 933 934 ~EvalInfo() { 935 discardCleanups(); 936 } 937 938 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 939 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 940 EvaluatingDecl = Base; 941 IsEvaluatingDecl = EDK; 942 EvaluatingDeclValue = &Value; 943 } 944 945 bool CheckCallLimit(SourceLocation Loc) { 946 // Don't perform any constexpr calls (other than the call we're checking) 947 // when checking a potential constant expression. 948 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 949 return false; 950 if (NextCallIndex == 0) { 951 // NextCallIndex has wrapped around. 952 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 953 return false; 954 } 955 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 956 return true; 957 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 958 << getLangOpts().ConstexprCallDepth; 959 return false; 960 } 961 962 std::pair<CallStackFrame *, unsigned> 963 getCallFrameAndDepth(unsigned CallIndex) { 964 assert(CallIndex && "no call index in getCallFrameAndDepth"); 965 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 966 // be null in this loop. 967 unsigned Depth = CallStackDepth; 968 CallStackFrame *Frame = CurrentCall; 969 while (Frame->Index > CallIndex) { 970 Frame = Frame->Caller; 971 --Depth; 972 } 973 if (Frame->Index == CallIndex) 974 return {Frame, Depth}; 975 return {nullptr, 0}; 976 } 977 978 bool nextStep(const Stmt *S) { 979 if (!StepsLeft) { 980 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 981 return false; 982 } 983 --StepsLeft; 984 return true; 985 } 986 987 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 988 989 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 990 Optional<DynAlloc*> Result; 991 auto It = HeapAllocs.find(DA); 992 if (It != HeapAllocs.end()) 993 Result = &It->second; 994 return Result; 995 } 996 997 /// Information about a stack frame for std::allocator<T>::[de]allocate. 998 struct StdAllocatorCaller { 999 unsigned FrameIndex; 1000 QualType ElemType; 1001 explicit operator bool() const { return FrameIndex != 0; }; 1002 }; 1003 1004 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1005 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1006 Call = Call->Caller) { 1007 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1008 if (!MD) 1009 continue; 1010 const IdentifierInfo *FnII = MD->getIdentifier(); 1011 if (!FnII || !FnII->isStr(FnName)) 1012 continue; 1013 1014 const auto *CTSD = 1015 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1016 if (!CTSD) 1017 continue; 1018 1019 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1020 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1021 if (CTSD->isInStdNamespace() && ClassII && 1022 ClassII->isStr("allocator") && TAL.size() >= 1 && 1023 TAL[0].getKind() == TemplateArgument::Type) 1024 return {Call->Index, TAL[0].getAsType()}; 1025 } 1026 1027 return {}; 1028 } 1029 1030 void performLifetimeExtension() { 1031 // Disable the cleanups for lifetime-extended temporaries. 1032 CleanupStack.erase( 1033 std::remove_if(CleanupStack.begin(), CleanupStack.end(), 1034 [](Cleanup &C) { return C.isLifetimeExtended(); }), 1035 CleanupStack.end()); 1036 } 1037 1038 /// Throw away any remaining cleanups at the end of evaluation. If any 1039 /// cleanups would have had a side-effect, note that as an unmodeled 1040 /// side-effect and return false. Otherwise, return true. 1041 bool discardCleanups() { 1042 for (Cleanup &C : CleanupStack) { 1043 if (C.hasSideEffect() && !noteSideEffect()) { 1044 CleanupStack.clear(); 1045 return false; 1046 } 1047 } 1048 CleanupStack.clear(); 1049 return true; 1050 } 1051 1052 private: 1053 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1054 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1055 1056 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1057 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1058 1059 void setFoldFailureDiagnostic(bool Flag) override { 1060 HasFoldFailureDiagnostic = Flag; 1061 } 1062 1063 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1064 1065 ASTContext &getCtx() const override { return Ctx; } 1066 1067 // If we have a prior diagnostic, it will be noting that the expression 1068 // isn't a constant expression. This diagnostic is more important, 1069 // unless we require this evaluation to produce a constant expression. 1070 // 1071 // FIXME: We might want to show both diagnostics to the user in 1072 // EM_ConstantFold mode. 1073 bool hasPriorDiagnostic() override { 1074 if (!EvalStatus.Diag->empty()) { 1075 switch (EvalMode) { 1076 case EM_ConstantFold: 1077 case EM_IgnoreSideEffects: 1078 if (!HasFoldFailureDiagnostic) 1079 break; 1080 // We've already failed to fold something. Keep that diagnostic. 1081 LLVM_FALLTHROUGH; 1082 case EM_ConstantExpression: 1083 case EM_ConstantExpressionUnevaluated: 1084 setActiveDiagnostic(false); 1085 return true; 1086 } 1087 } 1088 return false; 1089 } 1090 1091 unsigned getCallStackDepth() override { return CallStackDepth; } 1092 1093 public: 1094 /// Should we continue evaluation after encountering a side-effect that we 1095 /// couldn't model? 1096 bool keepEvaluatingAfterSideEffect() { 1097 switch (EvalMode) { 1098 case EM_IgnoreSideEffects: 1099 return true; 1100 1101 case EM_ConstantExpression: 1102 case EM_ConstantExpressionUnevaluated: 1103 case EM_ConstantFold: 1104 // By default, assume any side effect might be valid in some other 1105 // evaluation of this expression from a different context. 1106 return checkingPotentialConstantExpression() || 1107 checkingForUndefinedBehavior(); 1108 } 1109 llvm_unreachable("Missed EvalMode case"); 1110 } 1111 1112 /// Note that we have had a side-effect, and determine whether we should 1113 /// keep evaluating. 1114 bool noteSideEffect() { 1115 EvalStatus.HasSideEffects = true; 1116 return keepEvaluatingAfterSideEffect(); 1117 } 1118 1119 /// Should we continue evaluation after encountering undefined behavior? 1120 bool keepEvaluatingAfterUndefinedBehavior() { 1121 switch (EvalMode) { 1122 case EM_IgnoreSideEffects: 1123 case EM_ConstantFold: 1124 return true; 1125 1126 case EM_ConstantExpression: 1127 case EM_ConstantExpressionUnevaluated: 1128 return checkingForUndefinedBehavior(); 1129 } 1130 llvm_unreachable("Missed EvalMode case"); 1131 } 1132 1133 /// Note that we hit something that was technically undefined behavior, but 1134 /// that we can evaluate past it (such as signed overflow or floating-point 1135 /// division by zero.) 1136 bool noteUndefinedBehavior() override { 1137 EvalStatus.HasUndefinedBehavior = true; 1138 return keepEvaluatingAfterUndefinedBehavior(); 1139 } 1140 1141 /// Should we continue evaluation as much as possible after encountering a 1142 /// construct which can't be reduced to a value? 1143 bool keepEvaluatingAfterFailure() const override { 1144 if (!StepsLeft) 1145 return false; 1146 1147 switch (EvalMode) { 1148 case EM_ConstantExpression: 1149 case EM_ConstantExpressionUnevaluated: 1150 case EM_ConstantFold: 1151 case EM_IgnoreSideEffects: 1152 return checkingPotentialConstantExpression() || 1153 checkingForUndefinedBehavior(); 1154 } 1155 llvm_unreachable("Missed EvalMode case"); 1156 } 1157 1158 /// Notes that we failed to evaluate an expression that other expressions 1159 /// directly depend on, and determine if we should keep evaluating. This 1160 /// should only be called if we actually intend to keep evaluating. 1161 /// 1162 /// Call noteSideEffect() instead if we may be able to ignore the value that 1163 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1164 /// 1165 /// (Foo(), 1) // use noteSideEffect 1166 /// (Foo() || true) // use noteSideEffect 1167 /// Foo() + 1 // use noteFailure 1168 LLVM_NODISCARD bool noteFailure() { 1169 // Failure when evaluating some expression often means there is some 1170 // subexpression whose evaluation was skipped. Therefore, (because we 1171 // don't track whether we skipped an expression when unwinding after an 1172 // evaluation failure) every evaluation failure that bubbles up from a 1173 // subexpression implies that a side-effect has potentially happened. We 1174 // skip setting the HasSideEffects flag to true until we decide to 1175 // continue evaluating after that point, which happens here. 1176 bool KeepGoing = keepEvaluatingAfterFailure(); 1177 EvalStatus.HasSideEffects |= KeepGoing; 1178 return KeepGoing; 1179 } 1180 1181 class ArrayInitLoopIndex { 1182 EvalInfo &Info; 1183 uint64_t OuterIndex; 1184 1185 public: 1186 ArrayInitLoopIndex(EvalInfo &Info) 1187 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1188 Info.ArrayInitIndex = 0; 1189 } 1190 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1191 1192 operator uint64_t&() { return Info.ArrayInitIndex; } 1193 }; 1194 }; 1195 1196 /// Object used to treat all foldable expressions as constant expressions. 1197 struct FoldConstant { 1198 EvalInfo &Info; 1199 bool Enabled; 1200 bool HadNoPriorDiags; 1201 EvalInfo::EvaluationMode OldMode; 1202 1203 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1204 : Info(Info), 1205 Enabled(Enabled), 1206 HadNoPriorDiags(Info.EvalStatus.Diag && 1207 Info.EvalStatus.Diag->empty() && 1208 !Info.EvalStatus.HasSideEffects), 1209 OldMode(Info.EvalMode) { 1210 if (Enabled) 1211 Info.EvalMode = EvalInfo::EM_ConstantFold; 1212 } 1213 void keepDiagnostics() { Enabled = false; } 1214 ~FoldConstant() { 1215 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1216 !Info.EvalStatus.HasSideEffects) 1217 Info.EvalStatus.Diag->clear(); 1218 Info.EvalMode = OldMode; 1219 } 1220 }; 1221 1222 /// RAII object used to set the current evaluation mode to ignore 1223 /// side-effects. 1224 struct IgnoreSideEffectsRAII { 1225 EvalInfo &Info; 1226 EvalInfo::EvaluationMode OldMode; 1227 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1228 : Info(Info), OldMode(Info.EvalMode) { 1229 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1230 } 1231 1232 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1233 }; 1234 1235 /// RAII object used to optionally suppress diagnostics and side-effects from 1236 /// a speculative evaluation. 1237 class SpeculativeEvaluationRAII { 1238 EvalInfo *Info = nullptr; 1239 Expr::EvalStatus OldStatus; 1240 unsigned OldSpeculativeEvaluationDepth; 1241 1242 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1243 Info = Other.Info; 1244 OldStatus = Other.OldStatus; 1245 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1246 Other.Info = nullptr; 1247 } 1248 1249 void maybeRestoreState() { 1250 if (!Info) 1251 return; 1252 1253 Info->EvalStatus = OldStatus; 1254 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1255 } 1256 1257 public: 1258 SpeculativeEvaluationRAII() = default; 1259 1260 SpeculativeEvaluationRAII( 1261 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1262 : Info(&Info), OldStatus(Info.EvalStatus), 1263 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1264 Info.EvalStatus.Diag = NewDiag; 1265 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1266 } 1267 1268 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1269 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1270 moveFromAndCancel(std::move(Other)); 1271 } 1272 1273 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1274 maybeRestoreState(); 1275 moveFromAndCancel(std::move(Other)); 1276 return *this; 1277 } 1278 1279 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1280 }; 1281 1282 /// RAII object wrapping a full-expression or block scope, and handling 1283 /// the ending of the lifetime of temporaries created within it. 1284 template<bool IsFullExpression> 1285 class ScopeRAII { 1286 EvalInfo &Info; 1287 unsigned OldStackSize; 1288 public: 1289 ScopeRAII(EvalInfo &Info) 1290 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1291 // Push a new temporary version. This is needed to distinguish between 1292 // temporaries created in different iterations of a loop. 1293 Info.CurrentCall->pushTempVersion(); 1294 } 1295 bool destroy(bool RunDestructors = true) { 1296 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1297 OldStackSize = -1U; 1298 return OK; 1299 } 1300 ~ScopeRAII() { 1301 if (OldStackSize != -1U) 1302 destroy(false); 1303 // Body moved to a static method to encourage the compiler to inline away 1304 // instances of this class. 1305 Info.CurrentCall->popTempVersion(); 1306 } 1307 private: 1308 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1309 unsigned OldStackSize) { 1310 assert(OldStackSize <= Info.CleanupStack.size() && 1311 "running cleanups out of order?"); 1312 1313 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1314 // for a full-expression scope. 1315 bool Success = true; 1316 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1317 if (!(IsFullExpression && 1318 Info.CleanupStack[I - 1].isLifetimeExtended())) { 1319 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1320 Success = false; 1321 break; 1322 } 1323 } 1324 } 1325 1326 // Compact lifetime-extended cleanups. 1327 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1328 if (IsFullExpression) 1329 NewEnd = 1330 std::remove_if(NewEnd, Info.CleanupStack.end(), 1331 [](Cleanup &C) { return !C.isLifetimeExtended(); }); 1332 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1333 return Success; 1334 } 1335 }; 1336 typedef ScopeRAII<false> BlockScopeRAII; 1337 typedef ScopeRAII<true> FullExpressionRAII; 1338 } 1339 1340 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1341 CheckSubobjectKind CSK) { 1342 if (Invalid) 1343 return false; 1344 if (isOnePastTheEnd()) { 1345 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1346 << CSK; 1347 setInvalid(); 1348 return false; 1349 } 1350 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1351 // must actually be at least one array element; even a VLA cannot have a 1352 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1353 return true; 1354 } 1355 1356 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1357 const Expr *E) { 1358 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1359 // Do not set the designator as invalid: we can represent this situation, 1360 // and correct handling of __builtin_object_size requires us to do so. 1361 } 1362 1363 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1364 const Expr *E, 1365 const APSInt &N) { 1366 // If we're complaining, we must be able to statically determine the size of 1367 // the most derived array. 1368 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1369 Info.CCEDiag(E, diag::note_constexpr_array_index) 1370 << N << /*array*/ 0 1371 << static_cast<unsigned>(getMostDerivedArraySize()); 1372 else 1373 Info.CCEDiag(E, diag::note_constexpr_array_index) 1374 << N << /*non-array*/ 1; 1375 setInvalid(); 1376 } 1377 1378 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1379 const FunctionDecl *Callee, const LValue *This, 1380 APValue *Arguments) 1381 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1382 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1383 Info.CurrentCall = this; 1384 ++Info.CallStackDepth; 1385 } 1386 1387 CallStackFrame::~CallStackFrame() { 1388 assert(Info.CurrentCall == this && "calls retired out of order"); 1389 --Info.CallStackDepth; 1390 Info.CurrentCall = Caller; 1391 } 1392 1393 static bool isRead(AccessKinds AK) { 1394 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1395 } 1396 1397 static bool isModification(AccessKinds AK) { 1398 switch (AK) { 1399 case AK_Read: 1400 case AK_ReadObjectRepresentation: 1401 case AK_MemberCall: 1402 case AK_DynamicCast: 1403 case AK_TypeId: 1404 return false; 1405 case AK_Assign: 1406 case AK_Increment: 1407 case AK_Decrement: 1408 case AK_Construct: 1409 case AK_Destroy: 1410 return true; 1411 } 1412 llvm_unreachable("unknown access kind"); 1413 } 1414 1415 static bool isAnyAccess(AccessKinds AK) { 1416 return isRead(AK) || isModification(AK); 1417 } 1418 1419 /// Is this an access per the C++ definition? 1420 static bool isFormalAccess(AccessKinds AK) { 1421 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1422 } 1423 1424 namespace { 1425 struct ComplexValue { 1426 private: 1427 bool IsInt; 1428 1429 public: 1430 APSInt IntReal, IntImag; 1431 APFloat FloatReal, FloatImag; 1432 1433 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1434 1435 void makeComplexFloat() { IsInt = false; } 1436 bool isComplexFloat() const { return !IsInt; } 1437 APFloat &getComplexFloatReal() { return FloatReal; } 1438 APFloat &getComplexFloatImag() { return FloatImag; } 1439 1440 void makeComplexInt() { IsInt = true; } 1441 bool isComplexInt() const { return IsInt; } 1442 APSInt &getComplexIntReal() { return IntReal; } 1443 APSInt &getComplexIntImag() { return IntImag; } 1444 1445 void moveInto(APValue &v) const { 1446 if (isComplexFloat()) 1447 v = APValue(FloatReal, FloatImag); 1448 else 1449 v = APValue(IntReal, IntImag); 1450 } 1451 void setFrom(const APValue &v) { 1452 assert(v.isComplexFloat() || v.isComplexInt()); 1453 if (v.isComplexFloat()) { 1454 makeComplexFloat(); 1455 FloatReal = v.getComplexFloatReal(); 1456 FloatImag = v.getComplexFloatImag(); 1457 } else { 1458 makeComplexInt(); 1459 IntReal = v.getComplexIntReal(); 1460 IntImag = v.getComplexIntImag(); 1461 } 1462 } 1463 }; 1464 1465 struct LValue { 1466 APValue::LValueBase Base; 1467 CharUnits Offset; 1468 SubobjectDesignator Designator; 1469 bool IsNullPtr : 1; 1470 bool InvalidBase : 1; 1471 1472 const APValue::LValueBase getLValueBase() const { return Base; } 1473 CharUnits &getLValueOffset() { return Offset; } 1474 const CharUnits &getLValueOffset() const { return Offset; } 1475 SubobjectDesignator &getLValueDesignator() { return Designator; } 1476 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1477 bool isNullPointer() const { return IsNullPtr;} 1478 1479 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1480 unsigned getLValueVersion() const { return Base.getVersion(); } 1481 1482 void moveInto(APValue &V) const { 1483 if (Designator.Invalid) 1484 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1485 else { 1486 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1487 V = APValue(Base, Offset, Designator.Entries, 1488 Designator.IsOnePastTheEnd, IsNullPtr); 1489 } 1490 } 1491 void setFrom(ASTContext &Ctx, const APValue &V) { 1492 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1493 Base = V.getLValueBase(); 1494 Offset = V.getLValueOffset(); 1495 InvalidBase = false; 1496 Designator = SubobjectDesignator(Ctx, V); 1497 IsNullPtr = V.isNullPointer(); 1498 } 1499 1500 void set(APValue::LValueBase B, bool BInvalid = false) { 1501 #ifndef NDEBUG 1502 // We only allow a few types of invalid bases. Enforce that here. 1503 if (BInvalid) { 1504 const auto *E = B.get<const Expr *>(); 1505 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1506 "Unexpected type of invalid base"); 1507 } 1508 #endif 1509 1510 Base = B; 1511 Offset = CharUnits::fromQuantity(0); 1512 InvalidBase = BInvalid; 1513 Designator = SubobjectDesignator(getType(B)); 1514 IsNullPtr = false; 1515 } 1516 1517 void setNull(ASTContext &Ctx, QualType PointerTy) { 1518 Base = (Expr *)nullptr; 1519 Offset = 1520 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1521 InvalidBase = false; 1522 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1523 IsNullPtr = true; 1524 } 1525 1526 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1527 set(B, true); 1528 } 1529 1530 std::string toString(ASTContext &Ctx, QualType T) const { 1531 APValue Printable; 1532 moveInto(Printable); 1533 return Printable.getAsString(Ctx, T); 1534 } 1535 1536 private: 1537 // Check that this LValue is not based on a null pointer. If it is, produce 1538 // a diagnostic and mark the designator as invalid. 1539 template <typename GenDiagType> 1540 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1541 if (Designator.Invalid) 1542 return false; 1543 if (IsNullPtr) { 1544 GenDiag(); 1545 Designator.setInvalid(); 1546 return false; 1547 } 1548 return true; 1549 } 1550 1551 public: 1552 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1553 CheckSubobjectKind CSK) { 1554 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1555 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1556 }); 1557 } 1558 1559 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1560 AccessKinds AK) { 1561 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1562 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1563 }); 1564 } 1565 1566 // Check this LValue refers to an object. If not, set the designator to be 1567 // invalid and emit a diagnostic. 1568 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1569 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1570 Designator.checkSubobject(Info, E, CSK); 1571 } 1572 1573 void addDecl(EvalInfo &Info, const Expr *E, 1574 const Decl *D, bool Virtual = false) { 1575 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1576 Designator.addDeclUnchecked(D, Virtual); 1577 } 1578 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1579 if (!Designator.Entries.empty()) { 1580 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1581 Designator.setInvalid(); 1582 return; 1583 } 1584 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1585 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1586 Designator.FirstEntryIsAnUnsizedArray = true; 1587 Designator.addUnsizedArrayUnchecked(ElemTy); 1588 } 1589 } 1590 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1591 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1592 Designator.addArrayUnchecked(CAT); 1593 } 1594 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1595 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1596 Designator.addComplexUnchecked(EltTy, Imag); 1597 } 1598 void clearIsNullPointer() { 1599 IsNullPtr = false; 1600 } 1601 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1602 const APSInt &Index, CharUnits ElementSize) { 1603 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1604 // but we're not required to diagnose it and it's valid in C++.) 1605 if (!Index) 1606 return; 1607 1608 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1609 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1610 // offsets. 1611 uint64_t Offset64 = Offset.getQuantity(); 1612 uint64_t ElemSize64 = ElementSize.getQuantity(); 1613 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1614 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1615 1616 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1617 Designator.adjustIndex(Info, E, Index); 1618 clearIsNullPointer(); 1619 } 1620 void adjustOffset(CharUnits N) { 1621 Offset += N; 1622 if (N.getQuantity()) 1623 clearIsNullPointer(); 1624 } 1625 }; 1626 1627 struct MemberPtr { 1628 MemberPtr() {} 1629 explicit MemberPtr(const ValueDecl *Decl) : 1630 DeclAndIsDerivedMember(Decl, false), Path() {} 1631 1632 /// The member or (direct or indirect) field referred to by this member 1633 /// pointer, or 0 if this is a null member pointer. 1634 const ValueDecl *getDecl() const { 1635 return DeclAndIsDerivedMember.getPointer(); 1636 } 1637 /// Is this actually a member of some type derived from the relevant class? 1638 bool isDerivedMember() const { 1639 return DeclAndIsDerivedMember.getInt(); 1640 } 1641 /// Get the class which the declaration actually lives in. 1642 const CXXRecordDecl *getContainingRecord() const { 1643 return cast<CXXRecordDecl>( 1644 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1645 } 1646 1647 void moveInto(APValue &V) const { 1648 V = APValue(getDecl(), isDerivedMember(), Path); 1649 } 1650 void setFrom(const APValue &V) { 1651 assert(V.isMemberPointer()); 1652 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1653 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1654 Path.clear(); 1655 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1656 Path.insert(Path.end(), P.begin(), P.end()); 1657 } 1658 1659 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1660 /// whether the member is a member of some class derived from the class type 1661 /// of the member pointer. 1662 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1663 /// Path - The path of base/derived classes from the member declaration's 1664 /// class (exclusive) to the class type of the member pointer (inclusive). 1665 SmallVector<const CXXRecordDecl*, 4> Path; 1666 1667 /// Perform a cast towards the class of the Decl (either up or down the 1668 /// hierarchy). 1669 bool castBack(const CXXRecordDecl *Class) { 1670 assert(!Path.empty()); 1671 const CXXRecordDecl *Expected; 1672 if (Path.size() >= 2) 1673 Expected = Path[Path.size() - 2]; 1674 else 1675 Expected = getContainingRecord(); 1676 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1677 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1678 // if B does not contain the original member and is not a base or 1679 // derived class of the class containing the original member, the result 1680 // of the cast is undefined. 1681 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1682 // (D::*). We consider that to be a language defect. 1683 return false; 1684 } 1685 Path.pop_back(); 1686 return true; 1687 } 1688 /// Perform a base-to-derived member pointer cast. 1689 bool castToDerived(const CXXRecordDecl *Derived) { 1690 if (!getDecl()) 1691 return true; 1692 if (!isDerivedMember()) { 1693 Path.push_back(Derived); 1694 return true; 1695 } 1696 if (!castBack(Derived)) 1697 return false; 1698 if (Path.empty()) 1699 DeclAndIsDerivedMember.setInt(false); 1700 return true; 1701 } 1702 /// Perform a derived-to-base member pointer cast. 1703 bool castToBase(const CXXRecordDecl *Base) { 1704 if (!getDecl()) 1705 return true; 1706 if (Path.empty()) 1707 DeclAndIsDerivedMember.setInt(true); 1708 if (isDerivedMember()) { 1709 Path.push_back(Base); 1710 return true; 1711 } 1712 return castBack(Base); 1713 } 1714 }; 1715 1716 /// Compare two member pointers, which are assumed to be of the same type. 1717 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1718 if (!LHS.getDecl() || !RHS.getDecl()) 1719 return !LHS.getDecl() && !RHS.getDecl(); 1720 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1721 return false; 1722 return LHS.Path == RHS.Path; 1723 } 1724 } 1725 1726 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1727 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1728 const LValue &This, const Expr *E, 1729 bool AllowNonLiteralTypes = false); 1730 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1731 bool InvalidBaseOK = false); 1732 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1733 bool InvalidBaseOK = false); 1734 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1735 EvalInfo &Info); 1736 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1737 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1738 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1739 EvalInfo &Info); 1740 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1741 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1742 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1743 EvalInfo &Info); 1744 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1745 1746 /// Evaluate an integer or fixed point expression into an APResult. 1747 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1748 EvalInfo &Info); 1749 1750 /// Evaluate only a fixed point expression into an APResult. 1751 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1752 EvalInfo &Info); 1753 1754 //===----------------------------------------------------------------------===// 1755 // Misc utilities 1756 //===----------------------------------------------------------------------===// 1757 1758 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1759 /// preserving its value (by extending by up to one bit as needed). 1760 static void negateAsSigned(APSInt &Int) { 1761 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1762 Int = Int.extend(Int.getBitWidth() + 1); 1763 Int.setIsSigned(true); 1764 } 1765 Int = -Int; 1766 } 1767 1768 template<typename KeyT> 1769 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1770 bool IsLifetimeExtended, LValue &LV) { 1771 unsigned Version = getTempVersion(); 1772 APValue::LValueBase Base(Key, Index, Version); 1773 LV.set(Base); 1774 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1775 assert(Result.isAbsent() && "temporary created multiple times"); 1776 1777 // If we're creating a temporary immediately in the operand of a speculative 1778 // evaluation, don't register a cleanup to be run outside the speculative 1779 // evaluation context, since we won't actually be able to initialize this 1780 // object. 1781 if (Index <= Info.SpeculativeEvaluationDepth) { 1782 if (T.isDestructedType()) 1783 Info.noteSideEffect(); 1784 } else { 1785 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended)); 1786 } 1787 return Result; 1788 } 1789 1790 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1791 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1792 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1793 return nullptr; 1794 } 1795 1796 DynamicAllocLValue DA(NumHeapAllocs++); 1797 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1798 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1799 std::forward_as_tuple(DA), std::tuple<>()); 1800 assert(Result.second && "reused a heap alloc index?"); 1801 Result.first->second.AllocExpr = E; 1802 return &Result.first->second.Value; 1803 } 1804 1805 /// Produce a string describing the given constexpr call. 1806 void CallStackFrame::describe(raw_ostream &Out) { 1807 unsigned ArgIndex = 0; 1808 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1809 !isa<CXXConstructorDecl>(Callee) && 1810 cast<CXXMethodDecl>(Callee)->isInstance(); 1811 1812 if (!IsMemberCall) 1813 Out << *Callee << '('; 1814 1815 if (This && IsMemberCall) { 1816 APValue Val; 1817 This->moveInto(Val); 1818 Val.printPretty(Out, Info.Ctx, 1819 This->Designator.MostDerivedType); 1820 // FIXME: Add parens around Val if needed. 1821 Out << "->" << *Callee << '('; 1822 IsMemberCall = false; 1823 } 1824 1825 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1826 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1827 if (ArgIndex > (unsigned)IsMemberCall) 1828 Out << ", "; 1829 1830 const ParmVarDecl *Param = *I; 1831 const APValue &Arg = Arguments[ArgIndex]; 1832 Arg.printPretty(Out, Info.Ctx, Param->getType()); 1833 1834 if (ArgIndex == 0 && IsMemberCall) 1835 Out << "->" << *Callee << '('; 1836 } 1837 1838 Out << ')'; 1839 } 1840 1841 /// Evaluate an expression to see if it had side-effects, and discard its 1842 /// result. 1843 /// \return \c true if the caller should keep evaluating. 1844 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1845 APValue Scratch; 1846 if (!Evaluate(Scratch, Info, E)) 1847 // We don't need the value, but we might have skipped a side effect here. 1848 return Info.noteSideEffect(); 1849 return true; 1850 } 1851 1852 /// Should this call expression be treated as a string literal? 1853 static bool IsStringLiteralCall(const CallExpr *E) { 1854 unsigned Builtin = E->getBuiltinCallee(); 1855 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1856 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1857 } 1858 1859 static bool IsGlobalLValue(APValue::LValueBase B) { 1860 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1861 // constant expression of pointer type that evaluates to... 1862 1863 // ... a null pointer value, or a prvalue core constant expression of type 1864 // std::nullptr_t. 1865 if (!B) return true; 1866 1867 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1868 // ... the address of an object with static storage duration, 1869 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1870 return VD->hasGlobalStorage(); 1871 // ... the address of a function, 1872 return isa<FunctionDecl>(D); 1873 } 1874 1875 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1876 return true; 1877 1878 const Expr *E = B.get<const Expr*>(); 1879 switch (E->getStmtClass()) { 1880 default: 1881 return false; 1882 case Expr::CompoundLiteralExprClass: { 1883 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1884 return CLE->isFileScope() && CLE->isLValue(); 1885 } 1886 case Expr::MaterializeTemporaryExprClass: 1887 // A materialized temporary might have been lifetime-extended to static 1888 // storage duration. 1889 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1890 // A string literal has static storage duration. 1891 case Expr::StringLiteralClass: 1892 case Expr::PredefinedExprClass: 1893 case Expr::ObjCStringLiteralClass: 1894 case Expr::ObjCEncodeExprClass: 1895 case Expr::CXXUuidofExprClass: 1896 return true; 1897 case Expr::ObjCBoxedExprClass: 1898 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1899 case Expr::CallExprClass: 1900 return IsStringLiteralCall(cast<CallExpr>(E)); 1901 // For GCC compatibility, &&label has static storage duration. 1902 case Expr::AddrLabelExprClass: 1903 return true; 1904 // A Block literal expression may be used as the initialization value for 1905 // Block variables at global or local static scope. 1906 case Expr::BlockExprClass: 1907 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1908 case Expr::ImplicitValueInitExprClass: 1909 // FIXME: 1910 // We can never form an lvalue with an implicit value initialization as its 1911 // base through expression evaluation, so these only appear in one case: the 1912 // implicit variable declaration we invent when checking whether a constexpr 1913 // constructor can produce a constant expression. We must assume that such 1914 // an expression might be a global lvalue. 1915 return true; 1916 } 1917 } 1918 1919 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1920 return LVal.Base.dyn_cast<const ValueDecl*>(); 1921 } 1922 1923 static bool IsLiteralLValue(const LValue &Value) { 1924 if (Value.getLValueCallIndex()) 1925 return false; 1926 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1927 return E && !isa<MaterializeTemporaryExpr>(E); 1928 } 1929 1930 static bool IsWeakLValue(const LValue &Value) { 1931 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1932 return Decl && Decl->isWeak(); 1933 } 1934 1935 static bool isZeroSized(const LValue &Value) { 1936 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1937 if (Decl && isa<VarDecl>(Decl)) { 1938 QualType Ty = Decl->getType(); 1939 if (Ty->isArrayType()) 1940 return Ty->isIncompleteType() || 1941 Decl->getASTContext().getTypeSize(Ty) == 0; 1942 } 1943 return false; 1944 } 1945 1946 static bool HasSameBase(const LValue &A, const LValue &B) { 1947 if (!A.getLValueBase()) 1948 return !B.getLValueBase(); 1949 if (!B.getLValueBase()) 1950 return false; 1951 1952 if (A.getLValueBase().getOpaqueValue() != 1953 B.getLValueBase().getOpaqueValue()) { 1954 const Decl *ADecl = GetLValueBaseDecl(A); 1955 if (!ADecl) 1956 return false; 1957 const Decl *BDecl = GetLValueBaseDecl(B); 1958 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1959 return false; 1960 } 1961 1962 return IsGlobalLValue(A.getLValueBase()) || 1963 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1964 A.getLValueVersion() == B.getLValueVersion()); 1965 } 1966 1967 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1968 assert(Base && "no location for a null lvalue"); 1969 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1970 if (VD) 1971 Info.Note(VD->getLocation(), diag::note_declared_at); 1972 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1973 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 1974 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 1975 // FIXME: Produce a note for dangling pointers too. 1976 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 1977 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 1978 diag::note_constexpr_dynamic_alloc_here); 1979 } 1980 // We have no information to show for a typeid(T) object. 1981 } 1982 1983 enum class CheckEvaluationResultKind { 1984 ConstantExpression, 1985 FullyInitialized, 1986 }; 1987 1988 /// Materialized temporaries that we've already checked to determine if they're 1989 /// initializsed by a constant expression. 1990 using CheckedTemporaries = 1991 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 1992 1993 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 1994 EvalInfo &Info, SourceLocation DiagLoc, 1995 QualType Type, const APValue &Value, 1996 Expr::ConstExprUsage Usage, 1997 SourceLocation SubobjectLoc, 1998 CheckedTemporaries &CheckedTemps); 1999 2000 /// Check that this reference or pointer core constant expression is a valid 2001 /// value for an address or reference constant expression. Return true if we 2002 /// can fold this expression, whether or not it's a constant expression. 2003 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2004 QualType Type, const LValue &LVal, 2005 Expr::ConstExprUsage Usage, 2006 CheckedTemporaries &CheckedTemps) { 2007 bool IsReferenceType = Type->isReferenceType(); 2008 2009 APValue::LValueBase Base = LVal.getLValueBase(); 2010 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2011 2012 // Check that the object is a global. Note that the fake 'this' object we 2013 // manufacture when checking potential constant expressions is conservatively 2014 // assumed to be global here. 2015 if (!IsGlobalLValue(Base)) { 2016 if (Info.getLangOpts().CPlusPlus11) { 2017 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2018 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2019 << IsReferenceType << !Designator.Entries.empty() 2020 << !!VD << VD; 2021 NoteLValueLocation(Info, Base); 2022 } else { 2023 Info.FFDiag(Loc); 2024 } 2025 // Don't allow references to temporaries to escape. 2026 return false; 2027 } 2028 assert((Info.checkingPotentialConstantExpression() || 2029 LVal.getLValueCallIndex() == 0) && 2030 "have call index for global lvalue"); 2031 2032 if (Base.is<DynamicAllocLValue>()) { 2033 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2034 << IsReferenceType << !Designator.Entries.empty(); 2035 NoteLValueLocation(Info, Base); 2036 return false; 2037 } 2038 2039 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 2040 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 2041 // Check if this is a thread-local variable. 2042 if (Var->getTLSKind()) 2043 // FIXME: Diagnostic! 2044 return false; 2045 2046 // A dllimport variable never acts like a constant. 2047 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 2048 // FIXME: Diagnostic! 2049 return false; 2050 } 2051 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 2052 // __declspec(dllimport) must be handled very carefully: 2053 // We must never initialize an expression with the thunk in C++. 2054 // Doing otherwise would allow the same id-expression to yield 2055 // different addresses for the same function in different translation 2056 // units. However, this means that we must dynamically initialize the 2057 // expression with the contents of the import address table at runtime. 2058 // 2059 // The C language has no notion of ODR; furthermore, it has no notion of 2060 // dynamic initialization. This means that we are permitted to 2061 // perform initialization with the address of the thunk. 2062 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 2063 FD->hasAttr<DLLImportAttr>()) 2064 // FIXME: Diagnostic! 2065 return false; 2066 } 2067 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2068 Base.dyn_cast<const Expr *>())) { 2069 if (CheckedTemps.insert(MTE).second) { 2070 QualType TempType = getType(Base); 2071 if (TempType.isDestructedType()) { 2072 Info.FFDiag(MTE->getExprLoc(), 2073 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) 2074 << TempType; 2075 return false; 2076 } 2077 2078 APValue *V = MTE->getOrCreateValue(false); 2079 assert(V && "evasluation result refers to uninitialised temporary"); 2080 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2081 Info, MTE->getExprLoc(), TempType, *V, 2082 Usage, SourceLocation(), CheckedTemps)) 2083 return false; 2084 } 2085 } 2086 2087 // Allow address constant expressions to be past-the-end pointers. This is 2088 // an extension: the standard requires them to point to an object. 2089 if (!IsReferenceType) 2090 return true; 2091 2092 // A reference constant expression must refer to an object. 2093 if (!Base) { 2094 // FIXME: diagnostic 2095 Info.CCEDiag(Loc); 2096 return true; 2097 } 2098 2099 // Does this refer one past the end of some object? 2100 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2101 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2102 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2103 << !Designator.Entries.empty() << !!VD << VD; 2104 NoteLValueLocation(Info, Base); 2105 } 2106 2107 return true; 2108 } 2109 2110 /// Member pointers are constant expressions unless they point to a 2111 /// non-virtual dllimport member function. 2112 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2113 SourceLocation Loc, 2114 QualType Type, 2115 const APValue &Value, 2116 Expr::ConstExprUsage Usage) { 2117 const ValueDecl *Member = Value.getMemberPointerDecl(); 2118 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2119 if (!FD) 2120 return true; 2121 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2122 !FD->hasAttr<DLLImportAttr>(); 2123 } 2124 2125 /// Check that this core constant expression is of literal type, and if not, 2126 /// produce an appropriate diagnostic. 2127 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2128 const LValue *This = nullptr) { 2129 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2130 return true; 2131 2132 // C++1y: A constant initializer for an object o [...] may also invoke 2133 // constexpr constructors for o and its subobjects even if those objects 2134 // are of non-literal class types. 2135 // 2136 // C++11 missed this detail for aggregates, so classes like this: 2137 // struct foo_t { union { int i; volatile int j; } u; }; 2138 // are not (obviously) initializable like so: 2139 // __attribute__((__require_constant_initialization__)) 2140 // static const foo_t x = {{0}}; 2141 // because "i" is a subobject with non-literal initialization (due to the 2142 // volatile member of the union). See: 2143 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2144 // Therefore, we use the C++1y behavior. 2145 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2146 return true; 2147 2148 // Prvalue constant expressions must be of literal types. 2149 if (Info.getLangOpts().CPlusPlus11) 2150 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2151 << E->getType(); 2152 else 2153 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2154 return false; 2155 } 2156 2157 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2158 EvalInfo &Info, SourceLocation DiagLoc, 2159 QualType Type, const APValue &Value, 2160 Expr::ConstExprUsage Usage, 2161 SourceLocation SubobjectLoc, 2162 CheckedTemporaries &CheckedTemps) { 2163 if (!Value.hasValue()) { 2164 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2165 << true << Type; 2166 if (SubobjectLoc.isValid()) 2167 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2168 return false; 2169 } 2170 2171 // We allow _Atomic(T) to be initialized from anything that T can be 2172 // initialized from. 2173 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2174 Type = AT->getValueType(); 2175 2176 // Core issue 1454: For a literal constant expression of array or class type, 2177 // each subobject of its value shall have been initialized by a constant 2178 // expression. 2179 if (Value.isArray()) { 2180 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2181 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2182 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2183 Value.getArrayInitializedElt(I), Usage, 2184 SubobjectLoc, CheckedTemps)) 2185 return false; 2186 } 2187 if (!Value.hasArrayFiller()) 2188 return true; 2189 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2190 Value.getArrayFiller(), Usage, SubobjectLoc, 2191 CheckedTemps); 2192 } 2193 if (Value.isUnion() && Value.getUnionField()) { 2194 return CheckEvaluationResult( 2195 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2196 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2197 CheckedTemps); 2198 } 2199 if (Value.isStruct()) { 2200 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2201 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2202 unsigned BaseIndex = 0; 2203 for (const CXXBaseSpecifier &BS : CD->bases()) { 2204 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2205 Value.getStructBase(BaseIndex), Usage, 2206 BS.getBeginLoc(), CheckedTemps)) 2207 return false; 2208 ++BaseIndex; 2209 } 2210 } 2211 for (const auto *I : RD->fields()) { 2212 if (I->isUnnamedBitfield()) 2213 continue; 2214 2215 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2216 Value.getStructField(I->getFieldIndex()), 2217 Usage, I->getLocation(), CheckedTemps)) 2218 return false; 2219 } 2220 } 2221 2222 if (Value.isLValue() && 2223 CERK == CheckEvaluationResultKind::ConstantExpression) { 2224 LValue LVal; 2225 LVal.setFrom(Info.Ctx, Value); 2226 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2227 CheckedTemps); 2228 } 2229 2230 if (Value.isMemberPointer() && 2231 CERK == CheckEvaluationResultKind::ConstantExpression) 2232 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2233 2234 // Everything else is fine. 2235 return true; 2236 } 2237 2238 /// Check that this core constant expression value is a valid value for a 2239 /// constant expression. If not, report an appropriate diagnostic. Does not 2240 /// check that the expression is of literal type. 2241 static bool 2242 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2243 const APValue &Value, 2244 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2245 CheckedTemporaries CheckedTemps; 2246 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2247 Info, DiagLoc, Type, Value, Usage, 2248 SourceLocation(), CheckedTemps); 2249 } 2250 2251 /// Check that this evaluated value is fully-initialized and can be loaded by 2252 /// an lvalue-to-rvalue conversion. 2253 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2254 QualType Type, const APValue &Value) { 2255 CheckedTemporaries CheckedTemps; 2256 return CheckEvaluationResult( 2257 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2258 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2259 } 2260 2261 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2262 /// "the allocated storage is deallocated within the evaluation". 2263 static bool CheckMemoryLeaks(EvalInfo &Info) { 2264 if (!Info.HeapAllocs.empty()) { 2265 // We can still fold to a constant despite a compile-time memory leak, 2266 // so long as the heap allocation isn't referenced in the result (we check 2267 // that in CheckConstantExpression). 2268 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2269 diag::note_constexpr_memory_leak) 2270 << unsigned(Info.HeapAllocs.size() - 1); 2271 } 2272 return true; 2273 } 2274 2275 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2276 // A null base expression indicates a null pointer. These are always 2277 // evaluatable, and they are false unless the offset is zero. 2278 if (!Value.getLValueBase()) { 2279 Result = !Value.getLValueOffset().isZero(); 2280 return true; 2281 } 2282 2283 // We have a non-null base. These are generally known to be true, but if it's 2284 // a weak declaration it can be null at runtime. 2285 Result = true; 2286 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2287 return !Decl || !Decl->isWeak(); 2288 } 2289 2290 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2291 switch (Val.getKind()) { 2292 case APValue::None: 2293 case APValue::Indeterminate: 2294 return false; 2295 case APValue::Int: 2296 Result = Val.getInt().getBoolValue(); 2297 return true; 2298 case APValue::FixedPoint: 2299 Result = Val.getFixedPoint().getBoolValue(); 2300 return true; 2301 case APValue::Float: 2302 Result = !Val.getFloat().isZero(); 2303 return true; 2304 case APValue::ComplexInt: 2305 Result = Val.getComplexIntReal().getBoolValue() || 2306 Val.getComplexIntImag().getBoolValue(); 2307 return true; 2308 case APValue::ComplexFloat: 2309 Result = !Val.getComplexFloatReal().isZero() || 2310 !Val.getComplexFloatImag().isZero(); 2311 return true; 2312 case APValue::LValue: 2313 return EvalPointerValueAsBool(Val, Result); 2314 case APValue::MemberPointer: 2315 Result = Val.getMemberPointerDecl(); 2316 return true; 2317 case APValue::Vector: 2318 case APValue::Array: 2319 case APValue::Struct: 2320 case APValue::Union: 2321 case APValue::AddrLabelDiff: 2322 return false; 2323 } 2324 2325 llvm_unreachable("unknown APValue kind"); 2326 } 2327 2328 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2329 EvalInfo &Info) { 2330 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2331 APValue Val; 2332 if (!Evaluate(Val, Info, E)) 2333 return false; 2334 return HandleConversionToBool(Val, Result); 2335 } 2336 2337 template<typename T> 2338 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2339 const T &SrcValue, QualType DestType) { 2340 Info.CCEDiag(E, diag::note_constexpr_overflow) 2341 << SrcValue << DestType; 2342 return Info.noteUndefinedBehavior(); 2343 } 2344 2345 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2346 QualType SrcType, const APFloat &Value, 2347 QualType DestType, APSInt &Result) { 2348 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2349 // Determine whether we are converting to unsigned or signed. 2350 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2351 2352 Result = APSInt(DestWidth, !DestSigned); 2353 bool ignored; 2354 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2355 & APFloat::opInvalidOp) 2356 return HandleOverflow(Info, E, Value, DestType); 2357 return true; 2358 } 2359 2360 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2361 QualType SrcType, QualType DestType, 2362 APFloat &Result) { 2363 APFloat Value = Result; 2364 bool ignored; 2365 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2366 APFloat::rmNearestTiesToEven, &ignored); 2367 return true; 2368 } 2369 2370 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2371 QualType DestType, QualType SrcType, 2372 const APSInt &Value) { 2373 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2374 // Figure out if this is a truncate, extend or noop cast. 2375 // If the input is signed, do a sign extend, noop, or truncate. 2376 APSInt Result = Value.extOrTrunc(DestWidth); 2377 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2378 if (DestType->isBooleanType()) 2379 Result = Value.getBoolValue(); 2380 return Result; 2381 } 2382 2383 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2384 QualType SrcType, const APSInt &Value, 2385 QualType DestType, APFloat &Result) { 2386 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2387 Result.convertFromAPInt(Value, Value.isSigned(), 2388 APFloat::rmNearestTiesToEven); 2389 return true; 2390 } 2391 2392 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2393 APValue &Value, const FieldDecl *FD) { 2394 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2395 2396 if (!Value.isInt()) { 2397 // Trying to store a pointer-cast-to-integer into a bitfield. 2398 // FIXME: In this case, we should provide the diagnostic for casting 2399 // a pointer to an integer. 2400 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2401 Info.FFDiag(E); 2402 return false; 2403 } 2404 2405 APSInt &Int = Value.getInt(); 2406 unsigned OldBitWidth = Int.getBitWidth(); 2407 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2408 if (NewBitWidth < OldBitWidth) 2409 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2410 return true; 2411 } 2412 2413 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2414 llvm::APInt &Res) { 2415 APValue SVal; 2416 if (!Evaluate(SVal, Info, E)) 2417 return false; 2418 if (SVal.isInt()) { 2419 Res = SVal.getInt(); 2420 return true; 2421 } 2422 if (SVal.isFloat()) { 2423 Res = SVal.getFloat().bitcastToAPInt(); 2424 return true; 2425 } 2426 if (SVal.isVector()) { 2427 QualType VecTy = E->getType(); 2428 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2429 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2430 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2431 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2432 Res = llvm::APInt::getNullValue(VecSize); 2433 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2434 APValue &Elt = SVal.getVectorElt(i); 2435 llvm::APInt EltAsInt; 2436 if (Elt.isInt()) { 2437 EltAsInt = Elt.getInt(); 2438 } else if (Elt.isFloat()) { 2439 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2440 } else { 2441 // Don't try to handle vectors of anything other than int or float 2442 // (not sure if it's possible to hit this case). 2443 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2444 return false; 2445 } 2446 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2447 if (BigEndian) 2448 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2449 else 2450 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2451 } 2452 return true; 2453 } 2454 // Give up if the input isn't an int, float, or vector. For example, we 2455 // reject "(v4i16)(intptr_t)&a". 2456 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2457 return false; 2458 } 2459 2460 /// Perform the given integer operation, which is known to need at most BitWidth 2461 /// bits, and check for overflow in the original type (if that type was not an 2462 /// unsigned type). 2463 template<typename Operation> 2464 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2465 const APSInt &LHS, const APSInt &RHS, 2466 unsigned BitWidth, Operation Op, 2467 APSInt &Result) { 2468 if (LHS.isUnsigned()) { 2469 Result = Op(LHS, RHS); 2470 return true; 2471 } 2472 2473 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2474 Result = Value.trunc(LHS.getBitWidth()); 2475 if (Result.extend(BitWidth) != Value) { 2476 if (Info.checkingForUndefinedBehavior()) 2477 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2478 diag::warn_integer_constant_overflow) 2479 << Result.toString(10) << E->getType(); 2480 else 2481 return HandleOverflow(Info, E, Value, E->getType()); 2482 } 2483 return true; 2484 } 2485 2486 /// Perform the given binary integer operation. 2487 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2488 BinaryOperatorKind Opcode, APSInt RHS, 2489 APSInt &Result) { 2490 switch (Opcode) { 2491 default: 2492 Info.FFDiag(E); 2493 return false; 2494 case BO_Mul: 2495 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2496 std::multiplies<APSInt>(), Result); 2497 case BO_Add: 2498 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2499 std::plus<APSInt>(), Result); 2500 case BO_Sub: 2501 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2502 std::minus<APSInt>(), Result); 2503 case BO_And: Result = LHS & RHS; return true; 2504 case BO_Xor: Result = LHS ^ RHS; return true; 2505 case BO_Or: Result = LHS | RHS; return true; 2506 case BO_Div: 2507 case BO_Rem: 2508 if (RHS == 0) { 2509 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2510 return false; 2511 } 2512 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2513 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2514 // this operation and gives the two's complement result. 2515 if (RHS.isNegative() && RHS.isAllOnesValue() && 2516 LHS.isSigned() && LHS.isMinSignedValue()) 2517 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2518 E->getType()); 2519 return true; 2520 case BO_Shl: { 2521 if (Info.getLangOpts().OpenCL) 2522 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2523 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2524 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2525 RHS.isUnsigned()); 2526 else if (RHS.isSigned() && RHS.isNegative()) { 2527 // During constant-folding, a negative shift is an opposite shift. Such 2528 // a shift is not a constant expression. 2529 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2530 RHS = -RHS; 2531 goto shift_right; 2532 } 2533 shift_left: 2534 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2535 // the shifted type. 2536 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2537 if (SA != RHS) { 2538 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2539 << RHS << E->getType() << LHS.getBitWidth(); 2540 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) { 2541 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2542 // operand, and must not overflow the corresponding unsigned type. 2543 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2544 // E1 x 2^E2 module 2^N. 2545 if (LHS.isNegative()) 2546 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2547 else if (LHS.countLeadingZeros() < SA) 2548 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2549 } 2550 Result = LHS << SA; 2551 return true; 2552 } 2553 case BO_Shr: { 2554 if (Info.getLangOpts().OpenCL) 2555 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2556 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2557 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2558 RHS.isUnsigned()); 2559 else if (RHS.isSigned() && RHS.isNegative()) { 2560 // During constant-folding, a negative shift is an opposite shift. Such a 2561 // shift is not a constant expression. 2562 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2563 RHS = -RHS; 2564 goto shift_left; 2565 } 2566 shift_right: 2567 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2568 // shifted type. 2569 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2570 if (SA != RHS) 2571 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2572 << RHS << E->getType() << LHS.getBitWidth(); 2573 Result = LHS >> SA; 2574 return true; 2575 } 2576 2577 case BO_LT: Result = LHS < RHS; return true; 2578 case BO_GT: Result = LHS > RHS; return true; 2579 case BO_LE: Result = LHS <= RHS; return true; 2580 case BO_GE: Result = LHS >= RHS; return true; 2581 case BO_EQ: Result = LHS == RHS; return true; 2582 case BO_NE: Result = LHS != RHS; return true; 2583 case BO_Cmp: 2584 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2585 } 2586 } 2587 2588 /// Perform the given binary floating-point operation, in-place, on LHS. 2589 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2590 APFloat &LHS, BinaryOperatorKind Opcode, 2591 const APFloat &RHS) { 2592 switch (Opcode) { 2593 default: 2594 Info.FFDiag(E); 2595 return false; 2596 case BO_Mul: 2597 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2598 break; 2599 case BO_Add: 2600 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2601 break; 2602 case BO_Sub: 2603 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2604 break; 2605 case BO_Div: 2606 // [expr.mul]p4: 2607 // If the second operand of / or % is zero the behavior is undefined. 2608 if (RHS.isZero()) 2609 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2610 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2611 break; 2612 } 2613 2614 // [expr.pre]p4: 2615 // If during the evaluation of an expression, the result is not 2616 // mathematically defined [...], the behavior is undefined. 2617 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2618 if (LHS.isNaN()) { 2619 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2620 return Info.noteUndefinedBehavior(); 2621 } 2622 return true; 2623 } 2624 2625 /// Cast an lvalue referring to a base subobject to a derived class, by 2626 /// truncating the lvalue's path to the given length. 2627 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2628 const RecordDecl *TruncatedType, 2629 unsigned TruncatedElements) { 2630 SubobjectDesignator &D = Result.Designator; 2631 2632 // Check we actually point to a derived class object. 2633 if (TruncatedElements == D.Entries.size()) 2634 return true; 2635 assert(TruncatedElements >= D.MostDerivedPathLength && 2636 "not casting to a derived class"); 2637 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2638 return false; 2639 2640 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2641 const RecordDecl *RD = TruncatedType; 2642 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2643 if (RD->isInvalidDecl()) return false; 2644 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2645 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2646 if (isVirtualBaseClass(D.Entries[I])) 2647 Result.Offset -= Layout.getVBaseClassOffset(Base); 2648 else 2649 Result.Offset -= Layout.getBaseClassOffset(Base); 2650 RD = Base; 2651 } 2652 D.Entries.resize(TruncatedElements); 2653 return true; 2654 } 2655 2656 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2657 const CXXRecordDecl *Derived, 2658 const CXXRecordDecl *Base, 2659 const ASTRecordLayout *RL = nullptr) { 2660 if (!RL) { 2661 if (Derived->isInvalidDecl()) return false; 2662 RL = &Info.Ctx.getASTRecordLayout(Derived); 2663 } 2664 2665 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2666 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2667 return true; 2668 } 2669 2670 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2671 const CXXRecordDecl *DerivedDecl, 2672 const CXXBaseSpecifier *Base) { 2673 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2674 2675 if (!Base->isVirtual()) 2676 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2677 2678 SubobjectDesignator &D = Obj.Designator; 2679 if (D.Invalid) 2680 return false; 2681 2682 // Extract most-derived object and corresponding type. 2683 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2684 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2685 return false; 2686 2687 // Find the virtual base class. 2688 if (DerivedDecl->isInvalidDecl()) return false; 2689 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2690 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2691 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2692 return true; 2693 } 2694 2695 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2696 QualType Type, LValue &Result) { 2697 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2698 PathE = E->path_end(); 2699 PathI != PathE; ++PathI) { 2700 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2701 *PathI)) 2702 return false; 2703 Type = (*PathI)->getType(); 2704 } 2705 return true; 2706 } 2707 2708 /// Cast an lvalue referring to a derived class to a known base subobject. 2709 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2710 const CXXRecordDecl *DerivedRD, 2711 const CXXRecordDecl *BaseRD) { 2712 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2713 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2714 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2715 llvm_unreachable("Class must be derived from the passed in base class!"); 2716 2717 for (CXXBasePathElement &Elem : Paths.front()) 2718 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2719 return false; 2720 return true; 2721 } 2722 2723 /// Update LVal to refer to the given field, which must be a member of the type 2724 /// currently described by LVal. 2725 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2726 const FieldDecl *FD, 2727 const ASTRecordLayout *RL = nullptr) { 2728 if (!RL) { 2729 if (FD->getParent()->isInvalidDecl()) return false; 2730 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2731 } 2732 2733 unsigned I = FD->getFieldIndex(); 2734 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2735 LVal.addDecl(Info, E, FD); 2736 return true; 2737 } 2738 2739 /// Update LVal to refer to the given indirect field. 2740 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2741 LValue &LVal, 2742 const IndirectFieldDecl *IFD) { 2743 for (const auto *C : IFD->chain()) 2744 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2745 return false; 2746 return true; 2747 } 2748 2749 /// Get the size of the given type in char units. 2750 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2751 QualType Type, CharUnits &Size) { 2752 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2753 // extension. 2754 if (Type->isVoidType() || Type->isFunctionType()) { 2755 Size = CharUnits::One(); 2756 return true; 2757 } 2758 2759 if (Type->isDependentType()) { 2760 Info.FFDiag(Loc); 2761 return false; 2762 } 2763 2764 if (!Type->isConstantSizeType()) { 2765 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2766 // FIXME: Better diagnostic. 2767 Info.FFDiag(Loc); 2768 return false; 2769 } 2770 2771 Size = Info.Ctx.getTypeSizeInChars(Type); 2772 return true; 2773 } 2774 2775 /// Update a pointer value to model pointer arithmetic. 2776 /// \param Info - Information about the ongoing evaluation. 2777 /// \param E - The expression being evaluated, for diagnostic purposes. 2778 /// \param LVal - The pointer value to be updated. 2779 /// \param EltTy - The pointee type represented by LVal. 2780 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2781 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2782 LValue &LVal, QualType EltTy, 2783 APSInt Adjustment) { 2784 CharUnits SizeOfPointee; 2785 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2786 return false; 2787 2788 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2789 return true; 2790 } 2791 2792 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2793 LValue &LVal, QualType EltTy, 2794 int64_t Adjustment) { 2795 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2796 APSInt::get(Adjustment)); 2797 } 2798 2799 /// Update an lvalue to refer to a component of a complex number. 2800 /// \param Info - Information about the ongoing evaluation. 2801 /// \param LVal - The lvalue to be updated. 2802 /// \param EltTy - The complex number's component type. 2803 /// \param Imag - False for the real component, true for the imaginary. 2804 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2805 LValue &LVal, QualType EltTy, 2806 bool Imag) { 2807 if (Imag) { 2808 CharUnits SizeOfComponent; 2809 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2810 return false; 2811 LVal.Offset += SizeOfComponent; 2812 } 2813 LVal.addComplex(Info, E, EltTy, Imag); 2814 return true; 2815 } 2816 2817 /// Try to evaluate the initializer for a variable declaration. 2818 /// 2819 /// \param Info Information about the ongoing evaluation. 2820 /// \param E An expression to be used when printing diagnostics. 2821 /// \param VD The variable whose initializer should be obtained. 2822 /// \param Frame The frame in which the variable was created. Must be null 2823 /// if this variable is not local to the evaluation. 2824 /// \param Result Filled in with a pointer to the value of the variable. 2825 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2826 const VarDecl *VD, CallStackFrame *Frame, 2827 APValue *&Result, const LValue *LVal) { 2828 2829 // If this is a parameter to an active constexpr function call, perform 2830 // argument substitution. 2831 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2832 // Assume arguments of a potential constant expression are unknown 2833 // constant expressions. 2834 if (Info.checkingPotentialConstantExpression()) 2835 return false; 2836 if (!Frame || !Frame->Arguments) { 2837 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2838 return false; 2839 } 2840 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2841 return true; 2842 } 2843 2844 // If this is a local variable, dig out its value. 2845 if (Frame) { 2846 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2847 : Frame->getCurrentTemporary(VD); 2848 if (!Result) { 2849 // Assume variables referenced within a lambda's call operator that were 2850 // not declared within the call operator are captures and during checking 2851 // of a potential constant expression, assume they are unknown constant 2852 // expressions. 2853 assert(isLambdaCallOperator(Frame->Callee) && 2854 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2855 "missing value for local variable"); 2856 if (Info.checkingPotentialConstantExpression()) 2857 return false; 2858 // FIXME: implement capture evaluation during constant expr evaluation. 2859 Info.FFDiag(E->getBeginLoc(), 2860 diag::note_unimplemented_constexpr_lambda_feature_ast) 2861 << "captures not currently allowed"; 2862 return false; 2863 } 2864 return true; 2865 } 2866 2867 // Dig out the initializer, and use the declaration which it's attached to. 2868 const Expr *Init = VD->getAnyInitializer(VD); 2869 if (!Init || Init->isValueDependent()) { 2870 // If we're checking a potential constant expression, the variable could be 2871 // initialized later. 2872 if (!Info.checkingPotentialConstantExpression()) 2873 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2874 return false; 2875 } 2876 2877 // If we're currently evaluating the initializer of this declaration, use that 2878 // in-flight value. 2879 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2880 Result = Info.EvaluatingDeclValue; 2881 return true; 2882 } 2883 2884 // Never evaluate the initializer of a weak variable. We can't be sure that 2885 // this is the definition which will be used. 2886 if (VD->isWeak()) { 2887 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2888 return false; 2889 } 2890 2891 // Check that we can fold the initializer. In C++, we will have already done 2892 // this in the cases where it matters for conformance. 2893 SmallVector<PartialDiagnosticAt, 8> Notes; 2894 if (!VD->evaluateValue(Notes)) { 2895 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2896 Notes.size() + 1) << VD; 2897 Info.Note(VD->getLocation(), diag::note_declared_at); 2898 Info.addNotes(Notes); 2899 return false; 2900 } else if (!VD->checkInitIsICE()) { 2901 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2902 Notes.size() + 1) << VD; 2903 Info.Note(VD->getLocation(), diag::note_declared_at); 2904 Info.addNotes(Notes); 2905 } 2906 2907 Result = VD->getEvaluatedValue(); 2908 return true; 2909 } 2910 2911 static bool IsConstNonVolatile(QualType T) { 2912 Qualifiers Quals = T.getQualifiers(); 2913 return Quals.hasConst() && !Quals.hasVolatile(); 2914 } 2915 2916 /// Get the base index of the given base class within an APValue representing 2917 /// the given derived class. 2918 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2919 const CXXRecordDecl *Base) { 2920 Base = Base->getCanonicalDecl(); 2921 unsigned Index = 0; 2922 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2923 E = Derived->bases_end(); I != E; ++I, ++Index) { 2924 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2925 return Index; 2926 } 2927 2928 llvm_unreachable("base class missing from derived class's bases list"); 2929 } 2930 2931 /// Extract the value of a character from a string literal. 2932 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2933 uint64_t Index) { 2934 assert(!isa<SourceLocExpr>(Lit) && 2935 "SourceLocExpr should have already been converted to a StringLiteral"); 2936 2937 // FIXME: Support MakeStringConstant 2938 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2939 std::string Str; 2940 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2941 assert(Index <= Str.size() && "Index too large"); 2942 return APSInt::getUnsigned(Str.c_str()[Index]); 2943 } 2944 2945 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2946 Lit = PE->getFunctionName(); 2947 const StringLiteral *S = cast<StringLiteral>(Lit); 2948 const ConstantArrayType *CAT = 2949 Info.Ctx.getAsConstantArrayType(S->getType()); 2950 assert(CAT && "string literal isn't an array"); 2951 QualType CharType = CAT->getElementType(); 2952 assert(CharType->isIntegerType() && "unexpected character type"); 2953 2954 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2955 CharType->isUnsignedIntegerType()); 2956 if (Index < S->getLength()) 2957 Value = S->getCodeUnit(Index); 2958 return Value; 2959 } 2960 2961 // Expand a string literal into an array of characters. 2962 // 2963 // FIXME: This is inefficient; we should probably introduce something similar 2964 // to the LLVM ConstantDataArray to make this cheaper. 2965 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 2966 APValue &Result, 2967 QualType AllocType = QualType()) { 2968 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 2969 AllocType.isNull() ? S->getType() : AllocType); 2970 assert(CAT && "string literal isn't an array"); 2971 QualType CharType = CAT->getElementType(); 2972 assert(CharType->isIntegerType() && "unexpected character type"); 2973 2974 unsigned Elts = CAT->getSize().getZExtValue(); 2975 Result = APValue(APValue::UninitArray(), 2976 std::min(S->getLength(), Elts), Elts); 2977 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2978 CharType->isUnsignedIntegerType()); 2979 if (Result.hasArrayFiller()) 2980 Result.getArrayFiller() = APValue(Value); 2981 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2982 Value = S->getCodeUnit(I); 2983 Result.getArrayInitializedElt(I) = APValue(Value); 2984 } 2985 } 2986 2987 // Expand an array so that it has more than Index filled elements. 2988 static void expandArray(APValue &Array, unsigned Index) { 2989 unsigned Size = Array.getArraySize(); 2990 assert(Index < Size); 2991 2992 // Always at least double the number of elements for which we store a value. 2993 unsigned OldElts = Array.getArrayInitializedElts(); 2994 unsigned NewElts = std::max(Index+1, OldElts * 2); 2995 NewElts = std::min(Size, std::max(NewElts, 8u)); 2996 2997 // Copy the data across. 2998 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2999 for (unsigned I = 0; I != OldElts; ++I) 3000 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3001 for (unsigned I = OldElts; I != NewElts; ++I) 3002 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3003 if (NewValue.hasArrayFiller()) 3004 NewValue.getArrayFiller() = Array.getArrayFiller(); 3005 Array.swap(NewValue); 3006 } 3007 3008 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3009 /// conversion. If it's of class type, we may assume that the copy operation 3010 /// is trivial. Note that this is never true for a union type with fields 3011 /// (because the copy always "reads" the active member) and always true for 3012 /// a non-class type. 3013 static bool isReadByLvalueToRvalueConversion(QualType T) { 3014 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3015 if (!RD || (RD->isUnion() && !RD->field_empty())) 3016 return true; 3017 if (RD->isEmpty()) 3018 return false; 3019 3020 for (auto *Field : RD->fields()) 3021 if (isReadByLvalueToRvalueConversion(Field->getType())) 3022 return true; 3023 3024 for (auto &BaseSpec : RD->bases()) 3025 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3026 return true; 3027 3028 return false; 3029 } 3030 3031 /// Diagnose an attempt to read from any unreadable field within the specified 3032 /// type, which might be a class type. 3033 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3034 QualType T) { 3035 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3036 if (!RD) 3037 return false; 3038 3039 if (!RD->hasMutableFields()) 3040 return false; 3041 3042 for (auto *Field : RD->fields()) { 3043 // If we're actually going to read this field in some way, then it can't 3044 // be mutable. If we're in a union, then assigning to a mutable field 3045 // (even an empty one) can change the active member, so that's not OK. 3046 // FIXME: Add core issue number for the union case. 3047 if (Field->isMutable() && 3048 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3049 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3050 Info.Note(Field->getLocation(), diag::note_declared_at); 3051 return true; 3052 } 3053 3054 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3055 return true; 3056 } 3057 3058 for (auto &BaseSpec : RD->bases()) 3059 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3060 return true; 3061 3062 // All mutable fields were empty, and thus not actually read. 3063 return false; 3064 } 3065 3066 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3067 APValue::LValueBase Base, 3068 bool MutableSubobject = false) { 3069 // A temporary we created. 3070 if (Base.getCallIndex()) 3071 return true; 3072 3073 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3074 if (!Evaluating) 3075 return false; 3076 3077 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3078 3079 switch (Info.IsEvaluatingDecl) { 3080 case EvalInfo::EvaluatingDeclKind::None: 3081 return false; 3082 3083 case EvalInfo::EvaluatingDeclKind::Ctor: 3084 // The variable whose initializer we're evaluating. 3085 if (BaseD) 3086 return declaresSameEntity(Evaluating, BaseD); 3087 3088 // A temporary lifetime-extended by the variable whose initializer we're 3089 // evaluating. 3090 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3091 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3092 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3093 return false; 3094 3095 case EvalInfo::EvaluatingDeclKind::Dtor: 3096 // C++2a [expr.const]p6: 3097 // [during constant destruction] the lifetime of a and its non-mutable 3098 // subobjects (but not its mutable subobjects) [are] considered to start 3099 // within e. 3100 // 3101 // FIXME: We can meaningfully extend this to cover non-const objects, but 3102 // we will need special handling: we should be able to access only 3103 // subobjects of such objects that are themselves declared const. 3104 if (!BaseD || 3105 !(BaseD->getType().isConstQualified() || 3106 BaseD->getType()->isReferenceType()) || 3107 MutableSubobject) 3108 return false; 3109 return declaresSameEntity(Evaluating, BaseD); 3110 } 3111 3112 llvm_unreachable("unknown evaluating decl kind"); 3113 } 3114 3115 namespace { 3116 /// A handle to a complete object (an object that is not a subobject of 3117 /// another object). 3118 struct CompleteObject { 3119 /// The identity of the object. 3120 APValue::LValueBase Base; 3121 /// The value of the complete object. 3122 APValue *Value; 3123 /// The type of the complete object. 3124 QualType Type; 3125 3126 CompleteObject() : Value(nullptr) {} 3127 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3128 : Base(Base), Value(Value), Type(Type) {} 3129 3130 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3131 // In C++14 onwards, it is permitted to read a mutable member whose 3132 // lifetime began within the evaluation. 3133 // FIXME: Should we also allow this in C++11? 3134 if (!Info.getLangOpts().CPlusPlus14) 3135 return false; 3136 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3137 } 3138 3139 explicit operator bool() const { return !Type.isNull(); } 3140 }; 3141 } // end anonymous namespace 3142 3143 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3144 bool IsMutable = false) { 3145 // C++ [basic.type.qualifier]p1: 3146 // - A const object is an object of type const T or a non-mutable subobject 3147 // of a const object. 3148 if (ObjType.isConstQualified() && !IsMutable) 3149 SubobjType.addConst(); 3150 // - A volatile object is an object of type const T or a subobject of a 3151 // volatile object. 3152 if (ObjType.isVolatileQualified()) 3153 SubobjType.addVolatile(); 3154 return SubobjType; 3155 } 3156 3157 /// Find the designated sub-object of an rvalue. 3158 template<typename SubobjectHandler> 3159 typename SubobjectHandler::result_type 3160 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3161 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3162 if (Sub.Invalid) 3163 // A diagnostic will have already been produced. 3164 return handler.failed(); 3165 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3166 if (Info.getLangOpts().CPlusPlus11) 3167 Info.FFDiag(E, Sub.isOnePastTheEnd() 3168 ? diag::note_constexpr_access_past_end 3169 : diag::note_constexpr_access_unsized_array) 3170 << handler.AccessKind; 3171 else 3172 Info.FFDiag(E); 3173 return handler.failed(); 3174 } 3175 3176 APValue *O = Obj.Value; 3177 QualType ObjType = Obj.Type; 3178 const FieldDecl *LastField = nullptr; 3179 const FieldDecl *VolatileField = nullptr; 3180 3181 // Walk the designator's path to find the subobject. 3182 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3183 // Reading an indeterminate value is undefined, but assigning over one is OK. 3184 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3185 (O->isIndeterminate() && handler.AccessKind != AK_Construct && 3186 handler.AccessKind != AK_Assign && 3187 handler.AccessKind != AK_ReadObjectRepresentation)) { 3188 if (!Info.checkingPotentialConstantExpression()) 3189 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3190 << handler.AccessKind << O->isIndeterminate(); 3191 return handler.failed(); 3192 } 3193 3194 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3195 // const and volatile semantics are not applied on an object under 3196 // {con,de}struction. 3197 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3198 ObjType->isRecordType() && 3199 Info.isEvaluatingCtorDtor( 3200 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3201 Sub.Entries.begin() + I)) != 3202 ConstructionPhase::None) { 3203 ObjType = Info.Ctx.getCanonicalType(ObjType); 3204 ObjType.removeLocalConst(); 3205 ObjType.removeLocalVolatile(); 3206 } 3207 3208 // If this is our last pass, check that the final object type is OK. 3209 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3210 // Accesses to volatile objects are prohibited. 3211 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3212 if (Info.getLangOpts().CPlusPlus) { 3213 int DiagKind; 3214 SourceLocation Loc; 3215 const NamedDecl *Decl = nullptr; 3216 if (VolatileField) { 3217 DiagKind = 2; 3218 Loc = VolatileField->getLocation(); 3219 Decl = VolatileField; 3220 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3221 DiagKind = 1; 3222 Loc = VD->getLocation(); 3223 Decl = VD; 3224 } else { 3225 DiagKind = 0; 3226 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3227 Loc = E->getExprLoc(); 3228 } 3229 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3230 << handler.AccessKind << DiagKind << Decl; 3231 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3232 } else { 3233 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3234 } 3235 return handler.failed(); 3236 } 3237 3238 // If we are reading an object of class type, there may still be more 3239 // things we need to check: if there are any mutable subobjects, we 3240 // cannot perform this read. (This only happens when performing a trivial 3241 // copy or assignment.) 3242 if (ObjType->isRecordType() && 3243 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3244 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3245 return handler.failed(); 3246 } 3247 3248 if (I == N) { 3249 if (!handler.found(*O, ObjType)) 3250 return false; 3251 3252 // If we modified a bit-field, truncate it to the right width. 3253 if (isModification(handler.AccessKind) && 3254 LastField && LastField->isBitField() && 3255 !truncateBitfieldValue(Info, E, *O, LastField)) 3256 return false; 3257 3258 return true; 3259 } 3260 3261 LastField = nullptr; 3262 if (ObjType->isArrayType()) { 3263 // Next subobject is an array element. 3264 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3265 assert(CAT && "vla in literal type?"); 3266 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3267 if (CAT->getSize().ule(Index)) { 3268 // Note, it should not be possible to form a pointer with a valid 3269 // designator which points more than one past the end of the array. 3270 if (Info.getLangOpts().CPlusPlus11) 3271 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3272 << handler.AccessKind; 3273 else 3274 Info.FFDiag(E); 3275 return handler.failed(); 3276 } 3277 3278 ObjType = CAT->getElementType(); 3279 3280 if (O->getArrayInitializedElts() > Index) 3281 O = &O->getArrayInitializedElt(Index); 3282 else if (!isRead(handler.AccessKind)) { 3283 expandArray(*O, Index); 3284 O = &O->getArrayInitializedElt(Index); 3285 } else 3286 O = &O->getArrayFiller(); 3287 } else if (ObjType->isAnyComplexType()) { 3288 // Next subobject is a complex number. 3289 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3290 if (Index > 1) { 3291 if (Info.getLangOpts().CPlusPlus11) 3292 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3293 << handler.AccessKind; 3294 else 3295 Info.FFDiag(E); 3296 return handler.failed(); 3297 } 3298 3299 ObjType = getSubobjectType( 3300 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3301 3302 assert(I == N - 1 && "extracting subobject of scalar?"); 3303 if (O->isComplexInt()) { 3304 return handler.found(Index ? O->getComplexIntImag() 3305 : O->getComplexIntReal(), ObjType); 3306 } else { 3307 assert(O->isComplexFloat()); 3308 return handler.found(Index ? O->getComplexFloatImag() 3309 : O->getComplexFloatReal(), ObjType); 3310 } 3311 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3312 if (Field->isMutable() && 3313 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3314 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3315 << handler.AccessKind << Field; 3316 Info.Note(Field->getLocation(), diag::note_declared_at); 3317 return handler.failed(); 3318 } 3319 3320 // Next subobject is a class, struct or union field. 3321 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3322 if (RD->isUnion()) { 3323 const FieldDecl *UnionField = O->getUnionField(); 3324 if (!UnionField || 3325 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3326 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3327 // Placement new onto an inactive union member makes it active. 3328 O->setUnion(Field, APValue()); 3329 } else { 3330 // FIXME: If O->getUnionValue() is absent, report that there's no 3331 // active union member rather than reporting the prior active union 3332 // member. We'll need to fix nullptr_t to not use APValue() as its 3333 // representation first. 3334 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3335 << handler.AccessKind << Field << !UnionField << UnionField; 3336 return handler.failed(); 3337 } 3338 } 3339 O = &O->getUnionValue(); 3340 } else 3341 O = &O->getStructField(Field->getFieldIndex()); 3342 3343 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3344 LastField = Field; 3345 if (Field->getType().isVolatileQualified()) 3346 VolatileField = Field; 3347 } else { 3348 // Next subobject is a base class. 3349 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3350 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3351 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3352 3353 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3354 } 3355 } 3356 } 3357 3358 namespace { 3359 struct ExtractSubobjectHandler { 3360 EvalInfo &Info; 3361 const Expr *E; 3362 APValue &Result; 3363 const AccessKinds AccessKind; 3364 3365 typedef bool result_type; 3366 bool failed() { return false; } 3367 bool found(APValue &Subobj, QualType SubobjType) { 3368 Result = Subobj; 3369 if (AccessKind == AK_ReadObjectRepresentation) 3370 return true; 3371 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3372 } 3373 bool found(APSInt &Value, QualType SubobjType) { 3374 Result = APValue(Value); 3375 return true; 3376 } 3377 bool found(APFloat &Value, QualType SubobjType) { 3378 Result = APValue(Value); 3379 return true; 3380 } 3381 }; 3382 } // end anonymous namespace 3383 3384 /// Extract the designated sub-object of an rvalue. 3385 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3386 const CompleteObject &Obj, 3387 const SubobjectDesignator &Sub, APValue &Result, 3388 AccessKinds AK = AK_Read) { 3389 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3390 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3391 return findSubobject(Info, E, Obj, Sub, Handler); 3392 } 3393 3394 namespace { 3395 struct ModifySubobjectHandler { 3396 EvalInfo &Info; 3397 APValue &NewVal; 3398 const Expr *E; 3399 3400 typedef bool result_type; 3401 static const AccessKinds AccessKind = AK_Assign; 3402 3403 bool checkConst(QualType QT) { 3404 // Assigning to a const object has undefined behavior. 3405 if (QT.isConstQualified()) { 3406 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3407 return false; 3408 } 3409 return true; 3410 } 3411 3412 bool failed() { return false; } 3413 bool found(APValue &Subobj, QualType SubobjType) { 3414 if (!checkConst(SubobjType)) 3415 return false; 3416 // We've been given ownership of NewVal, so just swap it in. 3417 Subobj.swap(NewVal); 3418 return true; 3419 } 3420 bool found(APSInt &Value, QualType SubobjType) { 3421 if (!checkConst(SubobjType)) 3422 return false; 3423 if (!NewVal.isInt()) { 3424 // Maybe trying to write a cast pointer value into a complex? 3425 Info.FFDiag(E); 3426 return false; 3427 } 3428 Value = NewVal.getInt(); 3429 return true; 3430 } 3431 bool found(APFloat &Value, QualType SubobjType) { 3432 if (!checkConst(SubobjType)) 3433 return false; 3434 Value = NewVal.getFloat(); 3435 return true; 3436 } 3437 }; 3438 } // end anonymous namespace 3439 3440 const AccessKinds ModifySubobjectHandler::AccessKind; 3441 3442 /// Update the designated sub-object of an rvalue to the given value. 3443 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3444 const CompleteObject &Obj, 3445 const SubobjectDesignator &Sub, 3446 APValue &NewVal) { 3447 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3448 return findSubobject(Info, E, Obj, Sub, Handler); 3449 } 3450 3451 /// Find the position where two subobject designators diverge, or equivalently 3452 /// the length of the common initial subsequence. 3453 static unsigned FindDesignatorMismatch(QualType ObjType, 3454 const SubobjectDesignator &A, 3455 const SubobjectDesignator &B, 3456 bool &WasArrayIndex) { 3457 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3458 for (/**/; I != N; ++I) { 3459 if (!ObjType.isNull() && 3460 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3461 // Next subobject is an array element. 3462 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3463 WasArrayIndex = true; 3464 return I; 3465 } 3466 if (ObjType->isAnyComplexType()) 3467 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3468 else 3469 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3470 } else { 3471 if (A.Entries[I].getAsBaseOrMember() != 3472 B.Entries[I].getAsBaseOrMember()) { 3473 WasArrayIndex = false; 3474 return I; 3475 } 3476 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3477 // Next subobject is a field. 3478 ObjType = FD->getType(); 3479 else 3480 // Next subobject is a base class. 3481 ObjType = QualType(); 3482 } 3483 } 3484 WasArrayIndex = false; 3485 return I; 3486 } 3487 3488 /// Determine whether the given subobject designators refer to elements of the 3489 /// same array object. 3490 static bool AreElementsOfSameArray(QualType ObjType, 3491 const SubobjectDesignator &A, 3492 const SubobjectDesignator &B) { 3493 if (A.Entries.size() != B.Entries.size()) 3494 return false; 3495 3496 bool IsArray = A.MostDerivedIsArrayElement; 3497 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3498 // A is a subobject of the array element. 3499 return false; 3500 3501 // If A (and B) designates an array element, the last entry will be the array 3502 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3503 // of length 1' case, and the entire path must match. 3504 bool WasArrayIndex; 3505 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3506 return CommonLength >= A.Entries.size() - IsArray; 3507 } 3508 3509 /// Find the complete object to which an LValue refers. 3510 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3511 AccessKinds AK, const LValue &LVal, 3512 QualType LValType) { 3513 if (LVal.InvalidBase) { 3514 Info.FFDiag(E); 3515 return CompleteObject(); 3516 } 3517 3518 if (!LVal.Base) { 3519 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3520 return CompleteObject(); 3521 } 3522 3523 CallStackFrame *Frame = nullptr; 3524 unsigned Depth = 0; 3525 if (LVal.getLValueCallIndex()) { 3526 std::tie(Frame, Depth) = 3527 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3528 if (!Frame) { 3529 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3530 << AK << LVal.Base.is<const ValueDecl*>(); 3531 NoteLValueLocation(Info, LVal.Base); 3532 return CompleteObject(); 3533 } 3534 } 3535 3536 bool IsAccess = isAnyAccess(AK); 3537 3538 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3539 // is not a constant expression (even if the object is non-volatile). We also 3540 // apply this rule to C++98, in order to conform to the expected 'volatile' 3541 // semantics. 3542 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3543 if (Info.getLangOpts().CPlusPlus) 3544 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3545 << AK << LValType; 3546 else 3547 Info.FFDiag(E); 3548 return CompleteObject(); 3549 } 3550 3551 // Compute value storage location and type of base object. 3552 APValue *BaseVal = nullptr; 3553 QualType BaseType = getType(LVal.Base); 3554 3555 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3556 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3557 // In C++11, constexpr, non-volatile variables initialized with constant 3558 // expressions are constant expressions too. Inside constexpr functions, 3559 // parameters are constant expressions even if they're non-const. 3560 // In C++1y, objects local to a constant expression (those with a Frame) are 3561 // both readable and writable inside constant expressions. 3562 // In C, such things can also be folded, although they are not ICEs. 3563 const VarDecl *VD = dyn_cast<VarDecl>(D); 3564 if (VD) { 3565 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3566 VD = VDef; 3567 } 3568 if (!VD || VD->isInvalidDecl()) { 3569 Info.FFDiag(E); 3570 return CompleteObject(); 3571 } 3572 3573 // Unless we're looking at a local variable or argument in a constexpr call, 3574 // the variable we're reading must be const. 3575 if (!Frame) { 3576 if (Info.getLangOpts().CPlusPlus14 && 3577 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3578 // OK, we can read and modify an object if we're in the process of 3579 // evaluating its initializer, because its lifetime began in this 3580 // evaluation. 3581 } else if (isModification(AK)) { 3582 // All the remaining cases do not permit modification of the object. 3583 Info.FFDiag(E, diag::note_constexpr_modify_global); 3584 return CompleteObject(); 3585 } else if (VD->isConstexpr()) { 3586 // OK, we can read this variable. 3587 } else if (BaseType->isIntegralOrEnumerationType()) { 3588 // In OpenCL if a variable is in constant address space it is a const 3589 // value. 3590 if (!(BaseType.isConstQualified() || 3591 (Info.getLangOpts().OpenCL && 3592 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3593 if (!IsAccess) 3594 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3595 if (Info.getLangOpts().CPlusPlus) { 3596 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3597 Info.Note(VD->getLocation(), diag::note_declared_at); 3598 } else { 3599 Info.FFDiag(E); 3600 } 3601 return CompleteObject(); 3602 } 3603 } else if (!IsAccess) { 3604 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3605 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3606 // We support folding of const floating-point types, in order to make 3607 // static const data members of such types (supported as an extension) 3608 // more useful. 3609 if (Info.getLangOpts().CPlusPlus11) { 3610 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3611 Info.Note(VD->getLocation(), diag::note_declared_at); 3612 } else { 3613 Info.CCEDiag(E); 3614 } 3615 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3616 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3617 // Keep evaluating to see what we can do. 3618 } else { 3619 // FIXME: Allow folding of values of any literal type in all languages. 3620 if (Info.checkingPotentialConstantExpression() && 3621 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3622 // The definition of this variable could be constexpr. We can't 3623 // access it right now, but may be able to in future. 3624 } else if (Info.getLangOpts().CPlusPlus11) { 3625 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3626 Info.Note(VD->getLocation(), diag::note_declared_at); 3627 } else { 3628 Info.FFDiag(E); 3629 } 3630 return CompleteObject(); 3631 } 3632 } 3633 3634 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3635 return CompleteObject(); 3636 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 3637 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 3638 if (!Alloc) { 3639 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 3640 return CompleteObject(); 3641 } 3642 return CompleteObject(LVal.Base, &(*Alloc)->Value, 3643 LVal.Base.getDynamicAllocType()); 3644 } else { 3645 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3646 3647 if (!Frame) { 3648 if (const MaterializeTemporaryExpr *MTE = 3649 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3650 assert(MTE->getStorageDuration() == SD_Static && 3651 "should have a frame for a non-global materialized temporary"); 3652 3653 // Per C++1y [expr.const]p2: 3654 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3655 // - a [...] glvalue of integral or enumeration type that refers to 3656 // a non-volatile const object [...] 3657 // [...] 3658 // - a [...] glvalue of literal type that refers to a non-volatile 3659 // object whose lifetime began within the evaluation of e. 3660 // 3661 // C++11 misses the 'began within the evaluation of e' check and 3662 // instead allows all temporaries, including things like: 3663 // int &&r = 1; 3664 // int x = ++r; 3665 // constexpr int k = r; 3666 // Therefore we use the C++14 rules in C++11 too. 3667 // 3668 // Note that temporaries whose lifetimes began while evaluating a 3669 // variable's constructor are not usable while evaluating the 3670 // corresponding destructor, not even if they're of const-qualified 3671 // types. 3672 if (!(BaseType.isConstQualified() && 3673 BaseType->isIntegralOrEnumerationType()) && 3674 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 3675 if (!IsAccess) 3676 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3677 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3678 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3679 return CompleteObject(); 3680 } 3681 3682 BaseVal = MTE->getOrCreateValue(false); 3683 assert(BaseVal && "got reference to unevaluated temporary"); 3684 } else { 3685 if (!IsAccess) 3686 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3687 APValue Val; 3688 LVal.moveInto(Val); 3689 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3690 << AK 3691 << Val.getAsString(Info.Ctx, 3692 Info.Ctx.getLValueReferenceType(LValType)); 3693 NoteLValueLocation(Info, LVal.Base); 3694 return CompleteObject(); 3695 } 3696 } else { 3697 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3698 assert(BaseVal && "missing value for temporary"); 3699 } 3700 } 3701 3702 // In C++14, we can't safely access any mutable state when we might be 3703 // evaluating after an unmodeled side effect. 3704 // 3705 // FIXME: Not all local state is mutable. Allow local constant subobjects 3706 // to be read here (but take care with 'mutable' fields). 3707 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3708 Info.EvalStatus.HasSideEffects) || 3709 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3710 return CompleteObject(); 3711 3712 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3713 } 3714 3715 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3716 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3717 /// glvalue referred to by an entity of reference type. 3718 /// 3719 /// \param Info - Information about the ongoing evaluation. 3720 /// \param Conv - The expression for which we are performing the conversion. 3721 /// Used for diagnostics. 3722 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3723 /// case of a non-class type). 3724 /// \param LVal - The glvalue on which we are attempting to perform this action. 3725 /// \param RVal - The produced value will be placed here. 3726 /// \param WantObjectRepresentation - If true, we're looking for the object 3727 /// representation rather than the value, and in particular, 3728 /// there is no requirement that the result be fully initialized. 3729 static bool 3730 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 3731 const LValue &LVal, APValue &RVal, 3732 bool WantObjectRepresentation = false) { 3733 if (LVal.Designator.Invalid) 3734 return false; 3735 3736 // Check for special cases where there is no existing APValue to look at. 3737 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3738 3739 AccessKinds AK = 3740 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 3741 3742 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3743 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3744 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3745 // initializer until now for such expressions. Such an expression can't be 3746 // an ICE in C, so this only matters for fold. 3747 if (Type.isVolatileQualified()) { 3748 Info.FFDiag(Conv); 3749 return false; 3750 } 3751 APValue Lit; 3752 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3753 return false; 3754 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 3755 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 3756 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3757 // Special-case character extraction so we don't have to construct an 3758 // APValue for the whole string. 3759 assert(LVal.Designator.Entries.size() <= 1 && 3760 "Can only read characters from string literals"); 3761 if (LVal.Designator.Entries.empty()) { 3762 // Fail for now for LValue to RValue conversion of an array. 3763 // (This shouldn't show up in C/C++, but it could be triggered by a 3764 // weird EvaluateAsRValue call from a tool.) 3765 Info.FFDiag(Conv); 3766 return false; 3767 } 3768 if (LVal.Designator.isOnePastTheEnd()) { 3769 if (Info.getLangOpts().CPlusPlus11) 3770 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 3771 else 3772 Info.FFDiag(Conv); 3773 return false; 3774 } 3775 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 3776 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 3777 return true; 3778 } 3779 } 3780 3781 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 3782 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 3783 } 3784 3785 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3786 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3787 QualType LValType, APValue &Val) { 3788 if (LVal.Designator.Invalid) 3789 return false; 3790 3791 if (!Info.getLangOpts().CPlusPlus14) { 3792 Info.FFDiag(E); 3793 return false; 3794 } 3795 3796 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3797 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3798 } 3799 3800 namespace { 3801 struct CompoundAssignSubobjectHandler { 3802 EvalInfo &Info; 3803 const Expr *E; 3804 QualType PromotedLHSType; 3805 BinaryOperatorKind Opcode; 3806 const APValue &RHS; 3807 3808 static const AccessKinds AccessKind = AK_Assign; 3809 3810 typedef bool result_type; 3811 3812 bool checkConst(QualType QT) { 3813 // Assigning to a const object has undefined behavior. 3814 if (QT.isConstQualified()) { 3815 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3816 return false; 3817 } 3818 return true; 3819 } 3820 3821 bool failed() { return false; } 3822 bool found(APValue &Subobj, QualType SubobjType) { 3823 switch (Subobj.getKind()) { 3824 case APValue::Int: 3825 return found(Subobj.getInt(), SubobjType); 3826 case APValue::Float: 3827 return found(Subobj.getFloat(), SubobjType); 3828 case APValue::ComplexInt: 3829 case APValue::ComplexFloat: 3830 // FIXME: Implement complex compound assignment. 3831 Info.FFDiag(E); 3832 return false; 3833 case APValue::LValue: 3834 return foundPointer(Subobj, SubobjType); 3835 default: 3836 // FIXME: can this happen? 3837 Info.FFDiag(E); 3838 return false; 3839 } 3840 } 3841 bool found(APSInt &Value, QualType SubobjType) { 3842 if (!checkConst(SubobjType)) 3843 return false; 3844 3845 if (!SubobjType->isIntegerType()) { 3846 // We don't support compound assignment on integer-cast-to-pointer 3847 // values. 3848 Info.FFDiag(E); 3849 return false; 3850 } 3851 3852 if (RHS.isInt()) { 3853 APSInt LHS = 3854 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 3855 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3856 return false; 3857 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3858 return true; 3859 } else if (RHS.isFloat()) { 3860 APFloat FValue(0.0); 3861 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 3862 FValue) && 3863 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 3864 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 3865 Value); 3866 } 3867 3868 Info.FFDiag(E); 3869 return false; 3870 } 3871 bool found(APFloat &Value, QualType SubobjType) { 3872 return checkConst(SubobjType) && 3873 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3874 Value) && 3875 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3876 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3877 } 3878 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3879 if (!checkConst(SubobjType)) 3880 return false; 3881 3882 QualType PointeeType; 3883 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3884 PointeeType = PT->getPointeeType(); 3885 3886 if (PointeeType.isNull() || !RHS.isInt() || 3887 (Opcode != BO_Add && Opcode != BO_Sub)) { 3888 Info.FFDiag(E); 3889 return false; 3890 } 3891 3892 APSInt Offset = RHS.getInt(); 3893 if (Opcode == BO_Sub) 3894 negateAsSigned(Offset); 3895 3896 LValue LVal; 3897 LVal.setFrom(Info.Ctx, Subobj); 3898 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3899 return false; 3900 LVal.moveInto(Subobj); 3901 return true; 3902 } 3903 }; 3904 } // end anonymous namespace 3905 3906 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3907 3908 /// Perform a compound assignment of LVal <op>= RVal. 3909 static bool handleCompoundAssignment( 3910 EvalInfo &Info, const Expr *E, 3911 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3912 BinaryOperatorKind Opcode, const APValue &RVal) { 3913 if (LVal.Designator.Invalid) 3914 return false; 3915 3916 if (!Info.getLangOpts().CPlusPlus14) { 3917 Info.FFDiag(E); 3918 return false; 3919 } 3920 3921 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3922 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3923 RVal }; 3924 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3925 } 3926 3927 namespace { 3928 struct IncDecSubobjectHandler { 3929 EvalInfo &Info; 3930 const UnaryOperator *E; 3931 AccessKinds AccessKind; 3932 APValue *Old; 3933 3934 typedef bool result_type; 3935 3936 bool checkConst(QualType QT) { 3937 // Assigning to a const object has undefined behavior. 3938 if (QT.isConstQualified()) { 3939 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3940 return false; 3941 } 3942 return true; 3943 } 3944 3945 bool failed() { return false; } 3946 bool found(APValue &Subobj, QualType SubobjType) { 3947 // Stash the old value. Also clear Old, so we don't clobber it later 3948 // if we're post-incrementing a complex. 3949 if (Old) { 3950 *Old = Subobj; 3951 Old = nullptr; 3952 } 3953 3954 switch (Subobj.getKind()) { 3955 case APValue::Int: 3956 return found(Subobj.getInt(), SubobjType); 3957 case APValue::Float: 3958 return found(Subobj.getFloat(), SubobjType); 3959 case APValue::ComplexInt: 3960 return found(Subobj.getComplexIntReal(), 3961 SubobjType->castAs<ComplexType>()->getElementType() 3962 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3963 case APValue::ComplexFloat: 3964 return found(Subobj.getComplexFloatReal(), 3965 SubobjType->castAs<ComplexType>()->getElementType() 3966 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3967 case APValue::LValue: 3968 return foundPointer(Subobj, SubobjType); 3969 default: 3970 // FIXME: can this happen? 3971 Info.FFDiag(E); 3972 return false; 3973 } 3974 } 3975 bool found(APSInt &Value, QualType SubobjType) { 3976 if (!checkConst(SubobjType)) 3977 return false; 3978 3979 if (!SubobjType->isIntegerType()) { 3980 // We don't support increment / decrement on integer-cast-to-pointer 3981 // values. 3982 Info.FFDiag(E); 3983 return false; 3984 } 3985 3986 if (Old) *Old = APValue(Value); 3987 3988 // bool arithmetic promotes to int, and the conversion back to bool 3989 // doesn't reduce mod 2^n, so special-case it. 3990 if (SubobjType->isBooleanType()) { 3991 if (AccessKind == AK_Increment) 3992 Value = 1; 3993 else 3994 Value = !Value; 3995 return true; 3996 } 3997 3998 bool WasNegative = Value.isNegative(); 3999 if (AccessKind == AK_Increment) { 4000 ++Value; 4001 4002 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4003 APSInt ActualValue(Value, /*IsUnsigned*/true); 4004 return HandleOverflow(Info, E, ActualValue, SubobjType); 4005 } 4006 } else { 4007 --Value; 4008 4009 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4010 unsigned BitWidth = Value.getBitWidth(); 4011 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4012 ActualValue.setBit(BitWidth); 4013 return HandleOverflow(Info, E, ActualValue, SubobjType); 4014 } 4015 } 4016 return true; 4017 } 4018 bool found(APFloat &Value, QualType SubobjType) { 4019 if (!checkConst(SubobjType)) 4020 return false; 4021 4022 if (Old) *Old = APValue(Value); 4023 4024 APFloat One(Value.getSemantics(), 1); 4025 if (AccessKind == AK_Increment) 4026 Value.add(One, APFloat::rmNearestTiesToEven); 4027 else 4028 Value.subtract(One, APFloat::rmNearestTiesToEven); 4029 return true; 4030 } 4031 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4032 if (!checkConst(SubobjType)) 4033 return false; 4034 4035 QualType PointeeType; 4036 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4037 PointeeType = PT->getPointeeType(); 4038 else { 4039 Info.FFDiag(E); 4040 return false; 4041 } 4042 4043 LValue LVal; 4044 LVal.setFrom(Info.Ctx, Subobj); 4045 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4046 AccessKind == AK_Increment ? 1 : -1)) 4047 return false; 4048 LVal.moveInto(Subobj); 4049 return true; 4050 } 4051 }; 4052 } // end anonymous namespace 4053 4054 /// Perform an increment or decrement on LVal. 4055 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4056 QualType LValType, bool IsIncrement, APValue *Old) { 4057 if (LVal.Designator.Invalid) 4058 return false; 4059 4060 if (!Info.getLangOpts().CPlusPlus14) { 4061 Info.FFDiag(E); 4062 return false; 4063 } 4064 4065 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4066 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4067 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4068 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4069 } 4070 4071 /// Build an lvalue for the object argument of a member function call. 4072 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4073 LValue &This) { 4074 if (Object->getType()->isPointerType() && Object->isRValue()) 4075 return EvaluatePointer(Object, This, Info); 4076 4077 if (Object->isGLValue()) 4078 return EvaluateLValue(Object, This, Info); 4079 4080 if (Object->getType()->isLiteralType(Info.Ctx)) 4081 return EvaluateTemporary(Object, This, Info); 4082 4083 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4084 return false; 4085 } 4086 4087 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4088 /// lvalue referring to the result. 4089 /// 4090 /// \param Info - Information about the ongoing evaluation. 4091 /// \param LV - An lvalue referring to the base of the member pointer. 4092 /// \param RHS - The member pointer expression. 4093 /// \param IncludeMember - Specifies whether the member itself is included in 4094 /// the resulting LValue subobject designator. This is not possible when 4095 /// creating a bound member function. 4096 /// \return The field or method declaration to which the member pointer refers, 4097 /// or 0 if evaluation fails. 4098 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4099 QualType LVType, 4100 LValue &LV, 4101 const Expr *RHS, 4102 bool IncludeMember = true) { 4103 MemberPtr MemPtr; 4104 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4105 return nullptr; 4106 4107 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4108 // member value, the behavior is undefined. 4109 if (!MemPtr.getDecl()) { 4110 // FIXME: Specific diagnostic. 4111 Info.FFDiag(RHS); 4112 return nullptr; 4113 } 4114 4115 if (MemPtr.isDerivedMember()) { 4116 // This is a member of some derived class. Truncate LV appropriately. 4117 // The end of the derived-to-base path for the base object must match the 4118 // derived-to-base path for the member pointer. 4119 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4120 LV.Designator.Entries.size()) { 4121 Info.FFDiag(RHS); 4122 return nullptr; 4123 } 4124 unsigned PathLengthToMember = 4125 LV.Designator.Entries.size() - MemPtr.Path.size(); 4126 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4127 const CXXRecordDecl *LVDecl = getAsBaseClass( 4128 LV.Designator.Entries[PathLengthToMember + I]); 4129 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4130 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4131 Info.FFDiag(RHS); 4132 return nullptr; 4133 } 4134 } 4135 4136 // Truncate the lvalue to the appropriate derived class. 4137 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4138 PathLengthToMember)) 4139 return nullptr; 4140 } else if (!MemPtr.Path.empty()) { 4141 // Extend the LValue path with the member pointer's path. 4142 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4143 MemPtr.Path.size() + IncludeMember); 4144 4145 // Walk down to the appropriate base class. 4146 if (const PointerType *PT = LVType->getAs<PointerType>()) 4147 LVType = PT->getPointeeType(); 4148 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4149 assert(RD && "member pointer access on non-class-type expression"); 4150 // The first class in the path is that of the lvalue. 4151 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4152 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4153 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4154 return nullptr; 4155 RD = Base; 4156 } 4157 // Finally cast to the class containing the member. 4158 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4159 MemPtr.getContainingRecord())) 4160 return nullptr; 4161 } 4162 4163 // Add the member. Note that we cannot build bound member functions here. 4164 if (IncludeMember) { 4165 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4166 if (!HandleLValueMember(Info, RHS, LV, FD)) 4167 return nullptr; 4168 } else if (const IndirectFieldDecl *IFD = 4169 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4170 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4171 return nullptr; 4172 } else { 4173 llvm_unreachable("can't construct reference to bound member function"); 4174 } 4175 } 4176 4177 return MemPtr.getDecl(); 4178 } 4179 4180 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4181 const BinaryOperator *BO, 4182 LValue &LV, 4183 bool IncludeMember = true) { 4184 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4185 4186 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4187 if (Info.noteFailure()) { 4188 MemberPtr MemPtr; 4189 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4190 } 4191 return nullptr; 4192 } 4193 4194 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4195 BO->getRHS(), IncludeMember); 4196 } 4197 4198 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4199 /// the provided lvalue, which currently refers to the base object. 4200 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4201 LValue &Result) { 4202 SubobjectDesignator &D = Result.Designator; 4203 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4204 return false; 4205 4206 QualType TargetQT = E->getType(); 4207 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4208 TargetQT = PT->getPointeeType(); 4209 4210 // Check this cast lands within the final derived-to-base subobject path. 4211 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4212 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4213 << D.MostDerivedType << TargetQT; 4214 return false; 4215 } 4216 4217 // Check the type of the final cast. We don't need to check the path, 4218 // since a cast can only be formed if the path is unique. 4219 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4220 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4221 const CXXRecordDecl *FinalType; 4222 if (NewEntriesSize == D.MostDerivedPathLength) 4223 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4224 else 4225 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4226 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4227 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4228 << D.MostDerivedType << TargetQT; 4229 return false; 4230 } 4231 4232 // Truncate the lvalue to the appropriate derived class. 4233 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4234 } 4235 4236 /// Get the value to use for a default-initialized object of type T. 4237 static APValue getDefaultInitValue(QualType T) { 4238 if (auto *RD = T->getAsCXXRecordDecl()) { 4239 if (RD->isUnion()) 4240 return APValue((const FieldDecl*)nullptr); 4241 4242 APValue Struct(APValue::UninitStruct(), RD->getNumBases(), 4243 std::distance(RD->field_begin(), RD->field_end())); 4244 4245 unsigned Index = 0; 4246 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4247 End = RD->bases_end(); I != End; ++I, ++Index) 4248 Struct.getStructBase(Index) = getDefaultInitValue(I->getType()); 4249 4250 for (const auto *I : RD->fields()) { 4251 if (I->isUnnamedBitfield()) 4252 continue; 4253 Struct.getStructField(I->getFieldIndex()) = 4254 getDefaultInitValue(I->getType()); 4255 } 4256 return Struct; 4257 } 4258 4259 if (auto *AT = 4260 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4261 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4262 if (Array.hasArrayFiller()) 4263 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType()); 4264 return Array; 4265 } 4266 4267 return APValue::IndeterminateValue(); 4268 } 4269 4270 namespace { 4271 enum EvalStmtResult { 4272 /// Evaluation failed. 4273 ESR_Failed, 4274 /// Hit a 'return' statement. 4275 ESR_Returned, 4276 /// Evaluation succeeded. 4277 ESR_Succeeded, 4278 /// Hit a 'continue' statement. 4279 ESR_Continue, 4280 /// Hit a 'break' statement. 4281 ESR_Break, 4282 /// Still scanning for 'case' or 'default' statement. 4283 ESR_CaseNotFound 4284 }; 4285 } 4286 4287 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4288 // We don't need to evaluate the initializer for a static local. 4289 if (!VD->hasLocalStorage()) 4290 return true; 4291 4292 LValue Result; 4293 APValue &Val = 4294 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); 4295 4296 const Expr *InitE = VD->getInit(); 4297 if (!InitE) { 4298 Val = getDefaultInitValue(VD->getType()); 4299 return true; 4300 } 4301 4302 if (InitE->isValueDependent()) 4303 return false; 4304 4305 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4306 // Wipe out any partially-computed value, to allow tracking that this 4307 // evaluation failed. 4308 Val = APValue(); 4309 return false; 4310 } 4311 4312 return true; 4313 } 4314 4315 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4316 bool OK = true; 4317 4318 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4319 OK &= EvaluateVarDecl(Info, VD); 4320 4321 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4322 for (auto *BD : DD->bindings()) 4323 if (auto *VD = BD->getHoldingVar()) 4324 OK &= EvaluateDecl(Info, VD); 4325 4326 return OK; 4327 } 4328 4329 4330 /// Evaluate a condition (either a variable declaration or an expression). 4331 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4332 const Expr *Cond, bool &Result) { 4333 FullExpressionRAII Scope(Info); 4334 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4335 return false; 4336 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4337 return false; 4338 return Scope.destroy(); 4339 } 4340 4341 namespace { 4342 /// A location where the result (returned value) of evaluating a 4343 /// statement should be stored. 4344 struct StmtResult { 4345 /// The APValue that should be filled in with the returned value. 4346 APValue &Value; 4347 /// The location containing the result, if any (used to support RVO). 4348 const LValue *Slot; 4349 }; 4350 4351 struct TempVersionRAII { 4352 CallStackFrame &Frame; 4353 4354 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4355 Frame.pushTempVersion(); 4356 } 4357 4358 ~TempVersionRAII() { 4359 Frame.popTempVersion(); 4360 } 4361 }; 4362 4363 } 4364 4365 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4366 const Stmt *S, 4367 const SwitchCase *SC = nullptr); 4368 4369 /// Evaluate the body of a loop, and translate the result as appropriate. 4370 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4371 const Stmt *Body, 4372 const SwitchCase *Case = nullptr) { 4373 BlockScopeRAII Scope(Info); 4374 4375 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4376 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4377 ESR = ESR_Failed; 4378 4379 switch (ESR) { 4380 case ESR_Break: 4381 return ESR_Succeeded; 4382 case ESR_Succeeded: 4383 case ESR_Continue: 4384 return ESR_Continue; 4385 case ESR_Failed: 4386 case ESR_Returned: 4387 case ESR_CaseNotFound: 4388 return ESR; 4389 } 4390 llvm_unreachable("Invalid EvalStmtResult!"); 4391 } 4392 4393 /// Evaluate a switch statement. 4394 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4395 const SwitchStmt *SS) { 4396 BlockScopeRAII Scope(Info); 4397 4398 // Evaluate the switch condition. 4399 APSInt Value; 4400 { 4401 if (const Stmt *Init = SS->getInit()) { 4402 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4403 if (ESR != ESR_Succeeded) { 4404 if (ESR != ESR_Failed && !Scope.destroy()) 4405 ESR = ESR_Failed; 4406 return ESR; 4407 } 4408 } 4409 4410 FullExpressionRAII CondScope(Info); 4411 if (SS->getConditionVariable() && 4412 !EvaluateDecl(Info, SS->getConditionVariable())) 4413 return ESR_Failed; 4414 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4415 return ESR_Failed; 4416 if (!CondScope.destroy()) 4417 return ESR_Failed; 4418 } 4419 4420 // Find the switch case corresponding to the value of the condition. 4421 // FIXME: Cache this lookup. 4422 const SwitchCase *Found = nullptr; 4423 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4424 SC = SC->getNextSwitchCase()) { 4425 if (isa<DefaultStmt>(SC)) { 4426 Found = SC; 4427 continue; 4428 } 4429 4430 const CaseStmt *CS = cast<CaseStmt>(SC); 4431 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4432 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4433 : LHS; 4434 if (LHS <= Value && Value <= RHS) { 4435 Found = SC; 4436 break; 4437 } 4438 } 4439 4440 if (!Found) 4441 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4442 4443 // Search the switch body for the switch case and evaluate it from there. 4444 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4445 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4446 return ESR_Failed; 4447 4448 switch (ESR) { 4449 case ESR_Break: 4450 return ESR_Succeeded; 4451 case ESR_Succeeded: 4452 case ESR_Continue: 4453 case ESR_Failed: 4454 case ESR_Returned: 4455 return ESR; 4456 case ESR_CaseNotFound: 4457 // This can only happen if the switch case is nested within a statement 4458 // expression. We have no intention of supporting that. 4459 Info.FFDiag(Found->getBeginLoc(), 4460 diag::note_constexpr_stmt_expr_unsupported); 4461 return ESR_Failed; 4462 } 4463 llvm_unreachable("Invalid EvalStmtResult!"); 4464 } 4465 4466 // Evaluate a statement. 4467 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4468 const Stmt *S, const SwitchCase *Case) { 4469 if (!Info.nextStep(S)) 4470 return ESR_Failed; 4471 4472 // If we're hunting down a 'case' or 'default' label, recurse through 4473 // substatements until we hit the label. 4474 if (Case) { 4475 switch (S->getStmtClass()) { 4476 case Stmt::CompoundStmtClass: 4477 // FIXME: Precompute which substatement of a compound statement we 4478 // would jump to, and go straight there rather than performing a 4479 // linear scan each time. 4480 case Stmt::LabelStmtClass: 4481 case Stmt::AttributedStmtClass: 4482 case Stmt::DoStmtClass: 4483 break; 4484 4485 case Stmt::CaseStmtClass: 4486 case Stmt::DefaultStmtClass: 4487 if (Case == S) 4488 Case = nullptr; 4489 break; 4490 4491 case Stmt::IfStmtClass: { 4492 // FIXME: Precompute which side of an 'if' we would jump to, and go 4493 // straight there rather than scanning both sides. 4494 const IfStmt *IS = cast<IfStmt>(S); 4495 4496 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4497 // preceded by our switch label. 4498 BlockScopeRAII Scope(Info); 4499 4500 // Step into the init statement in case it brings an (uninitialized) 4501 // variable into scope. 4502 if (const Stmt *Init = IS->getInit()) { 4503 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4504 if (ESR != ESR_CaseNotFound) { 4505 assert(ESR != ESR_Succeeded); 4506 return ESR; 4507 } 4508 } 4509 4510 // Condition variable must be initialized if it exists. 4511 // FIXME: We can skip evaluating the body if there's a condition 4512 // variable, as there can't be any case labels within it. 4513 // (The same is true for 'for' statements.) 4514 4515 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4516 if (ESR == ESR_Failed) 4517 return ESR; 4518 if (ESR != ESR_CaseNotFound) 4519 return Scope.destroy() ? ESR : ESR_Failed; 4520 if (!IS->getElse()) 4521 return ESR_CaseNotFound; 4522 4523 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4524 if (ESR == ESR_Failed) 4525 return ESR; 4526 if (ESR != ESR_CaseNotFound) 4527 return Scope.destroy() ? ESR : ESR_Failed; 4528 return ESR_CaseNotFound; 4529 } 4530 4531 case Stmt::WhileStmtClass: { 4532 EvalStmtResult ESR = 4533 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4534 if (ESR != ESR_Continue) 4535 return ESR; 4536 break; 4537 } 4538 4539 case Stmt::ForStmtClass: { 4540 const ForStmt *FS = cast<ForStmt>(S); 4541 BlockScopeRAII Scope(Info); 4542 4543 // Step into the init statement in case it brings an (uninitialized) 4544 // variable into scope. 4545 if (const Stmt *Init = FS->getInit()) { 4546 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4547 if (ESR != ESR_CaseNotFound) { 4548 assert(ESR != ESR_Succeeded); 4549 return ESR; 4550 } 4551 } 4552 4553 EvalStmtResult ESR = 4554 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4555 if (ESR != ESR_Continue) 4556 return ESR; 4557 if (FS->getInc()) { 4558 FullExpressionRAII IncScope(Info); 4559 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4560 return ESR_Failed; 4561 } 4562 break; 4563 } 4564 4565 case Stmt::DeclStmtClass: { 4566 // Start the lifetime of any uninitialized variables we encounter. They 4567 // might be used by the selected branch of the switch. 4568 const DeclStmt *DS = cast<DeclStmt>(S); 4569 for (const auto *D : DS->decls()) { 4570 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4571 if (VD->hasLocalStorage() && !VD->getInit()) 4572 if (!EvaluateVarDecl(Info, VD)) 4573 return ESR_Failed; 4574 // FIXME: If the variable has initialization that can't be jumped 4575 // over, bail out of any immediately-surrounding compound-statement 4576 // too. There can't be any case labels here. 4577 } 4578 } 4579 return ESR_CaseNotFound; 4580 } 4581 4582 default: 4583 return ESR_CaseNotFound; 4584 } 4585 } 4586 4587 switch (S->getStmtClass()) { 4588 default: 4589 if (const Expr *E = dyn_cast<Expr>(S)) { 4590 // Don't bother evaluating beyond an expression-statement which couldn't 4591 // be evaluated. 4592 // FIXME: Do we need the FullExpressionRAII object here? 4593 // VisitExprWithCleanups should create one when necessary. 4594 FullExpressionRAII Scope(Info); 4595 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 4596 return ESR_Failed; 4597 return ESR_Succeeded; 4598 } 4599 4600 Info.FFDiag(S->getBeginLoc()); 4601 return ESR_Failed; 4602 4603 case Stmt::NullStmtClass: 4604 return ESR_Succeeded; 4605 4606 case Stmt::DeclStmtClass: { 4607 const DeclStmt *DS = cast<DeclStmt>(S); 4608 for (const auto *D : DS->decls()) { 4609 // Each declaration initialization is its own full-expression. 4610 FullExpressionRAII Scope(Info); 4611 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 4612 return ESR_Failed; 4613 if (!Scope.destroy()) 4614 return ESR_Failed; 4615 } 4616 return ESR_Succeeded; 4617 } 4618 4619 case Stmt::ReturnStmtClass: { 4620 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4621 FullExpressionRAII Scope(Info); 4622 if (RetExpr && 4623 !(Result.Slot 4624 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4625 : Evaluate(Result.Value, Info, RetExpr))) 4626 return ESR_Failed; 4627 return Scope.destroy() ? ESR_Returned : ESR_Failed; 4628 } 4629 4630 case Stmt::CompoundStmtClass: { 4631 BlockScopeRAII Scope(Info); 4632 4633 const CompoundStmt *CS = cast<CompoundStmt>(S); 4634 for (const auto *BI : CS->body()) { 4635 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4636 if (ESR == ESR_Succeeded) 4637 Case = nullptr; 4638 else if (ESR != ESR_CaseNotFound) { 4639 if (ESR != ESR_Failed && !Scope.destroy()) 4640 return ESR_Failed; 4641 return ESR; 4642 } 4643 } 4644 if (Case) 4645 return ESR_CaseNotFound; 4646 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4647 } 4648 4649 case Stmt::IfStmtClass: { 4650 const IfStmt *IS = cast<IfStmt>(S); 4651 4652 // Evaluate the condition, as either a var decl or as an expression. 4653 BlockScopeRAII Scope(Info); 4654 if (const Stmt *Init = IS->getInit()) { 4655 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4656 if (ESR != ESR_Succeeded) { 4657 if (ESR != ESR_Failed && !Scope.destroy()) 4658 return ESR_Failed; 4659 return ESR; 4660 } 4661 } 4662 bool Cond; 4663 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4664 return ESR_Failed; 4665 4666 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4667 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4668 if (ESR != ESR_Succeeded) { 4669 if (ESR != ESR_Failed && !Scope.destroy()) 4670 return ESR_Failed; 4671 return ESR; 4672 } 4673 } 4674 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4675 } 4676 4677 case Stmt::WhileStmtClass: { 4678 const WhileStmt *WS = cast<WhileStmt>(S); 4679 while (true) { 4680 BlockScopeRAII Scope(Info); 4681 bool Continue; 4682 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4683 Continue)) 4684 return ESR_Failed; 4685 if (!Continue) 4686 break; 4687 4688 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4689 if (ESR != ESR_Continue) { 4690 if (ESR != ESR_Failed && !Scope.destroy()) 4691 return ESR_Failed; 4692 return ESR; 4693 } 4694 if (!Scope.destroy()) 4695 return ESR_Failed; 4696 } 4697 return ESR_Succeeded; 4698 } 4699 4700 case Stmt::DoStmtClass: { 4701 const DoStmt *DS = cast<DoStmt>(S); 4702 bool Continue; 4703 do { 4704 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4705 if (ESR != ESR_Continue) 4706 return ESR; 4707 Case = nullptr; 4708 4709 FullExpressionRAII CondScope(Info); 4710 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 4711 !CondScope.destroy()) 4712 return ESR_Failed; 4713 } while (Continue); 4714 return ESR_Succeeded; 4715 } 4716 4717 case Stmt::ForStmtClass: { 4718 const ForStmt *FS = cast<ForStmt>(S); 4719 BlockScopeRAII ForScope(Info); 4720 if (FS->getInit()) { 4721 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4722 if (ESR != ESR_Succeeded) { 4723 if (ESR != ESR_Failed && !ForScope.destroy()) 4724 return ESR_Failed; 4725 return ESR; 4726 } 4727 } 4728 while (true) { 4729 BlockScopeRAII IterScope(Info); 4730 bool Continue = true; 4731 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4732 FS->getCond(), Continue)) 4733 return ESR_Failed; 4734 if (!Continue) 4735 break; 4736 4737 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4738 if (ESR != ESR_Continue) { 4739 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 4740 return ESR_Failed; 4741 return ESR; 4742 } 4743 4744 if (FS->getInc()) { 4745 FullExpressionRAII IncScope(Info); 4746 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4747 return ESR_Failed; 4748 } 4749 4750 if (!IterScope.destroy()) 4751 return ESR_Failed; 4752 } 4753 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 4754 } 4755 4756 case Stmt::CXXForRangeStmtClass: { 4757 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4758 BlockScopeRAII Scope(Info); 4759 4760 // Evaluate the init-statement if present. 4761 if (FS->getInit()) { 4762 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4763 if (ESR != ESR_Succeeded) { 4764 if (ESR != ESR_Failed && !Scope.destroy()) 4765 return ESR_Failed; 4766 return ESR; 4767 } 4768 } 4769 4770 // Initialize the __range variable. 4771 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4772 if (ESR != ESR_Succeeded) { 4773 if (ESR != ESR_Failed && !Scope.destroy()) 4774 return ESR_Failed; 4775 return ESR; 4776 } 4777 4778 // Create the __begin and __end iterators. 4779 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4780 if (ESR != ESR_Succeeded) { 4781 if (ESR != ESR_Failed && !Scope.destroy()) 4782 return ESR_Failed; 4783 return ESR; 4784 } 4785 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4786 if (ESR != ESR_Succeeded) { 4787 if (ESR != ESR_Failed && !Scope.destroy()) 4788 return ESR_Failed; 4789 return ESR; 4790 } 4791 4792 while (true) { 4793 // Condition: __begin != __end. 4794 { 4795 bool Continue = true; 4796 FullExpressionRAII CondExpr(Info); 4797 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4798 return ESR_Failed; 4799 if (!Continue) 4800 break; 4801 } 4802 4803 // User's variable declaration, initialized by *__begin. 4804 BlockScopeRAII InnerScope(Info); 4805 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4806 if (ESR != ESR_Succeeded) { 4807 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 4808 return ESR_Failed; 4809 return ESR; 4810 } 4811 4812 // Loop body. 4813 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4814 if (ESR != ESR_Continue) { 4815 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 4816 return ESR_Failed; 4817 return ESR; 4818 } 4819 4820 // Increment: ++__begin 4821 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4822 return ESR_Failed; 4823 4824 if (!InnerScope.destroy()) 4825 return ESR_Failed; 4826 } 4827 4828 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4829 } 4830 4831 case Stmt::SwitchStmtClass: 4832 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4833 4834 case Stmt::ContinueStmtClass: 4835 return ESR_Continue; 4836 4837 case Stmt::BreakStmtClass: 4838 return ESR_Break; 4839 4840 case Stmt::LabelStmtClass: 4841 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4842 4843 case Stmt::AttributedStmtClass: 4844 // As a general principle, C++11 attributes can be ignored without 4845 // any semantic impact. 4846 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4847 Case); 4848 4849 case Stmt::CaseStmtClass: 4850 case Stmt::DefaultStmtClass: 4851 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4852 case Stmt::CXXTryStmtClass: 4853 // Evaluate try blocks by evaluating all sub statements. 4854 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 4855 } 4856 } 4857 4858 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4859 /// default constructor. If so, we'll fold it whether or not it's marked as 4860 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4861 /// so we need special handling. 4862 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4863 const CXXConstructorDecl *CD, 4864 bool IsValueInitialization) { 4865 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4866 return false; 4867 4868 // Value-initialization does not call a trivial default constructor, so such a 4869 // call is a core constant expression whether or not the constructor is 4870 // constexpr. 4871 if (!CD->isConstexpr() && !IsValueInitialization) { 4872 if (Info.getLangOpts().CPlusPlus11) { 4873 // FIXME: If DiagDecl is an implicitly-declared special member function, 4874 // we should be much more explicit about why it's not constexpr. 4875 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4876 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4877 Info.Note(CD->getLocation(), diag::note_declared_at); 4878 } else { 4879 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4880 } 4881 } 4882 return true; 4883 } 4884 4885 /// CheckConstexprFunction - Check that a function can be called in a constant 4886 /// expression. 4887 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4888 const FunctionDecl *Declaration, 4889 const FunctionDecl *Definition, 4890 const Stmt *Body) { 4891 // Potential constant expressions can contain calls to declared, but not yet 4892 // defined, constexpr functions. 4893 if (Info.checkingPotentialConstantExpression() && !Definition && 4894 Declaration->isConstexpr()) 4895 return false; 4896 4897 // Bail out if the function declaration itself is invalid. We will 4898 // have produced a relevant diagnostic while parsing it, so just 4899 // note the problematic sub-expression. 4900 if (Declaration->isInvalidDecl()) { 4901 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4902 return false; 4903 } 4904 4905 // DR1872: An instantiated virtual constexpr function can't be called in a 4906 // constant expression (prior to C++20). We can still constant-fold such a 4907 // call. 4908 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) && 4909 cast<CXXMethodDecl>(Declaration)->isVirtual()) 4910 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 4911 4912 if (Definition && Definition->isInvalidDecl()) { 4913 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4914 return false; 4915 } 4916 4917 // Can we evaluate this function call? 4918 if (Definition && Definition->isConstexpr() && Body) 4919 return true; 4920 4921 if (Info.getLangOpts().CPlusPlus11) { 4922 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4923 4924 // If this function is not constexpr because it is an inherited 4925 // non-constexpr constructor, diagnose that directly. 4926 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4927 if (CD && CD->isInheritingConstructor()) { 4928 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4929 if (!Inherited->isConstexpr()) 4930 DiagDecl = CD = Inherited; 4931 } 4932 4933 // FIXME: If DiagDecl is an implicitly-declared special member function 4934 // or an inheriting constructor, we should be much more explicit about why 4935 // it's not constexpr. 4936 if (CD && CD->isInheritingConstructor()) 4937 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4938 << CD->getInheritedConstructor().getConstructor()->getParent(); 4939 else 4940 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4941 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4942 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4943 } else { 4944 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4945 } 4946 return false; 4947 } 4948 4949 namespace { 4950 struct CheckDynamicTypeHandler { 4951 AccessKinds AccessKind; 4952 typedef bool result_type; 4953 bool failed() { return false; } 4954 bool found(APValue &Subobj, QualType SubobjType) { return true; } 4955 bool found(APSInt &Value, QualType SubobjType) { return true; } 4956 bool found(APFloat &Value, QualType SubobjType) { return true; } 4957 }; 4958 } // end anonymous namespace 4959 4960 /// Check that we can access the notional vptr of an object / determine its 4961 /// dynamic type. 4962 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 4963 AccessKinds AK, bool Polymorphic) { 4964 if (This.Designator.Invalid) 4965 return false; 4966 4967 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 4968 4969 if (!Obj) 4970 return false; 4971 4972 if (!Obj.Value) { 4973 // The object is not usable in constant expressions, so we can't inspect 4974 // its value to see if it's in-lifetime or what the active union members 4975 // are. We can still check for a one-past-the-end lvalue. 4976 if (This.Designator.isOnePastTheEnd() || 4977 This.Designator.isMostDerivedAnUnsizedArray()) { 4978 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 4979 ? diag::note_constexpr_access_past_end 4980 : diag::note_constexpr_access_unsized_array) 4981 << AK; 4982 return false; 4983 } else if (Polymorphic) { 4984 // Conservatively refuse to perform a polymorphic operation if we would 4985 // not be able to read a notional 'vptr' value. 4986 APValue Val; 4987 This.moveInto(Val); 4988 QualType StarThisType = 4989 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 4990 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 4991 << AK << Val.getAsString(Info.Ctx, StarThisType); 4992 return false; 4993 } 4994 return true; 4995 } 4996 4997 CheckDynamicTypeHandler Handler{AK}; 4998 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 4999 } 5000 5001 /// Check that the pointee of the 'this' pointer in a member function call is 5002 /// either within its lifetime or in its period of construction or destruction. 5003 static bool 5004 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5005 const LValue &This, 5006 const CXXMethodDecl *NamedMember) { 5007 return checkDynamicType( 5008 Info, E, This, 5009 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5010 } 5011 5012 struct DynamicType { 5013 /// The dynamic class type of the object. 5014 const CXXRecordDecl *Type; 5015 /// The corresponding path length in the lvalue. 5016 unsigned PathLength; 5017 }; 5018 5019 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5020 unsigned PathLength) { 5021 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5022 Designator.Entries.size() && "invalid path length"); 5023 return (PathLength == Designator.MostDerivedPathLength) 5024 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5025 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5026 } 5027 5028 /// Determine the dynamic type of an object. 5029 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5030 LValue &This, AccessKinds AK) { 5031 // If we don't have an lvalue denoting an object of class type, there is no 5032 // meaningful dynamic type. (We consider objects of non-class type to have no 5033 // dynamic type.) 5034 if (!checkDynamicType(Info, E, This, AK, true)) 5035 return None; 5036 5037 // Refuse to compute a dynamic type in the presence of virtual bases. This 5038 // shouldn't happen other than in constant-folding situations, since literal 5039 // types can't have virtual bases. 5040 // 5041 // Note that consumers of DynamicType assume that the type has no virtual 5042 // bases, and will need modifications if this restriction is relaxed. 5043 const CXXRecordDecl *Class = 5044 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5045 if (!Class || Class->getNumVBases()) { 5046 Info.FFDiag(E); 5047 return None; 5048 } 5049 5050 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5051 // binary search here instead. But the overwhelmingly common case is that 5052 // we're not in the middle of a constructor, so it probably doesn't matter 5053 // in practice. 5054 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5055 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5056 PathLength <= Path.size(); ++PathLength) { 5057 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5058 Path.slice(0, PathLength))) { 5059 case ConstructionPhase::Bases: 5060 case ConstructionPhase::DestroyingBases: 5061 // We're constructing or destroying a base class. This is not the dynamic 5062 // type. 5063 break; 5064 5065 case ConstructionPhase::None: 5066 case ConstructionPhase::AfterBases: 5067 case ConstructionPhase::Destroying: 5068 // We've finished constructing the base classes and not yet started 5069 // destroying them again, so this is the dynamic type. 5070 return DynamicType{getBaseClassType(This.Designator, PathLength), 5071 PathLength}; 5072 } 5073 } 5074 5075 // CWG issue 1517: we're constructing a base class of the object described by 5076 // 'This', so that object has not yet begun its period of construction and 5077 // any polymorphic operation on it results in undefined behavior. 5078 Info.FFDiag(E); 5079 return None; 5080 } 5081 5082 /// Perform virtual dispatch. 5083 static const CXXMethodDecl *HandleVirtualDispatch( 5084 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5085 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5086 Optional<DynamicType> DynType = ComputeDynamicType( 5087 Info, E, This, 5088 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5089 if (!DynType) 5090 return nullptr; 5091 5092 // Find the final overrider. It must be declared in one of the classes on the 5093 // path from the dynamic type to the static type. 5094 // FIXME: If we ever allow literal types to have virtual base classes, that 5095 // won't be true. 5096 const CXXMethodDecl *Callee = Found; 5097 unsigned PathLength = DynType->PathLength; 5098 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5099 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5100 const CXXMethodDecl *Overrider = 5101 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5102 if (Overrider) { 5103 Callee = Overrider; 5104 break; 5105 } 5106 } 5107 5108 // C++2a [class.abstract]p6: 5109 // the effect of making a virtual call to a pure virtual function [...] is 5110 // undefined 5111 if (Callee->isPure()) { 5112 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5113 Info.Note(Callee->getLocation(), diag::note_declared_at); 5114 return nullptr; 5115 } 5116 5117 // If necessary, walk the rest of the path to determine the sequence of 5118 // covariant adjustment steps to apply. 5119 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5120 Found->getReturnType())) { 5121 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5122 for (unsigned CovariantPathLength = PathLength + 1; 5123 CovariantPathLength != This.Designator.Entries.size(); 5124 ++CovariantPathLength) { 5125 const CXXRecordDecl *NextClass = 5126 getBaseClassType(This.Designator, CovariantPathLength); 5127 const CXXMethodDecl *Next = 5128 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5129 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5130 Next->getReturnType(), CovariantAdjustmentPath.back())) 5131 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5132 } 5133 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5134 CovariantAdjustmentPath.back())) 5135 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5136 } 5137 5138 // Perform 'this' adjustment. 5139 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5140 return nullptr; 5141 5142 return Callee; 5143 } 5144 5145 /// Perform the adjustment from a value returned by a virtual function to 5146 /// a value of the statically expected type, which may be a pointer or 5147 /// reference to a base class of the returned type. 5148 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5149 APValue &Result, 5150 ArrayRef<QualType> Path) { 5151 assert(Result.isLValue() && 5152 "unexpected kind of APValue for covariant return"); 5153 if (Result.isNullPointer()) 5154 return true; 5155 5156 LValue LVal; 5157 LVal.setFrom(Info.Ctx, Result); 5158 5159 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5160 for (unsigned I = 1; I != Path.size(); ++I) { 5161 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5162 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5163 if (OldClass != NewClass && 5164 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5165 return false; 5166 OldClass = NewClass; 5167 } 5168 5169 LVal.moveInto(Result); 5170 return true; 5171 } 5172 5173 /// Determine whether \p Base, which is known to be a direct base class of 5174 /// \p Derived, is a public base class. 5175 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5176 const CXXRecordDecl *Base) { 5177 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5178 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5179 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5180 return BaseSpec.getAccessSpecifier() == AS_public; 5181 } 5182 llvm_unreachable("Base is not a direct base of Derived"); 5183 } 5184 5185 /// Apply the given dynamic cast operation on the provided lvalue. 5186 /// 5187 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5188 /// to find a suitable target subobject. 5189 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5190 LValue &Ptr) { 5191 // We can't do anything with a non-symbolic pointer value. 5192 SubobjectDesignator &D = Ptr.Designator; 5193 if (D.Invalid) 5194 return false; 5195 5196 // C++ [expr.dynamic.cast]p6: 5197 // If v is a null pointer value, the result is a null pointer value. 5198 if (Ptr.isNullPointer() && !E->isGLValue()) 5199 return true; 5200 5201 // For all the other cases, we need the pointer to point to an object within 5202 // its lifetime / period of construction / destruction, and we need to know 5203 // its dynamic type. 5204 Optional<DynamicType> DynType = 5205 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5206 if (!DynType) 5207 return false; 5208 5209 // C++ [expr.dynamic.cast]p7: 5210 // If T is "pointer to cv void", then the result is a pointer to the most 5211 // derived object 5212 if (E->getType()->isVoidPointerType()) 5213 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5214 5215 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5216 assert(C && "dynamic_cast target is not void pointer nor class"); 5217 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5218 5219 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5220 // C++ [expr.dynamic.cast]p9: 5221 if (!E->isGLValue()) { 5222 // The value of a failed cast to pointer type is the null pointer value 5223 // of the required result type. 5224 Ptr.setNull(Info.Ctx, E->getType()); 5225 return true; 5226 } 5227 5228 // A failed cast to reference type throws [...] std::bad_cast. 5229 unsigned DiagKind; 5230 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5231 DynType->Type->isDerivedFrom(C))) 5232 DiagKind = 0; 5233 else if (!Paths || Paths->begin() == Paths->end()) 5234 DiagKind = 1; 5235 else if (Paths->isAmbiguous(CQT)) 5236 DiagKind = 2; 5237 else { 5238 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5239 DiagKind = 3; 5240 } 5241 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5242 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5243 << Info.Ctx.getRecordType(DynType->Type) 5244 << E->getType().getUnqualifiedType(); 5245 return false; 5246 }; 5247 5248 // Runtime check, phase 1: 5249 // Walk from the base subobject towards the derived object looking for the 5250 // target type. 5251 for (int PathLength = Ptr.Designator.Entries.size(); 5252 PathLength >= (int)DynType->PathLength; --PathLength) { 5253 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5254 if (declaresSameEntity(Class, C)) 5255 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5256 // We can only walk across public inheritance edges. 5257 if (PathLength > (int)DynType->PathLength && 5258 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5259 Class)) 5260 return RuntimeCheckFailed(nullptr); 5261 } 5262 5263 // Runtime check, phase 2: 5264 // Search the dynamic type for an unambiguous public base of type C. 5265 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5266 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5267 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5268 Paths.front().Access == AS_public) { 5269 // Downcast to the dynamic type... 5270 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5271 return false; 5272 // ... then upcast to the chosen base class subobject. 5273 for (CXXBasePathElement &Elem : Paths.front()) 5274 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5275 return false; 5276 return true; 5277 } 5278 5279 // Otherwise, the runtime check fails. 5280 return RuntimeCheckFailed(&Paths); 5281 } 5282 5283 namespace { 5284 struct StartLifetimeOfUnionMemberHandler { 5285 const FieldDecl *Field; 5286 5287 static const AccessKinds AccessKind = AK_Assign; 5288 5289 typedef bool result_type; 5290 bool failed() { return false; } 5291 bool found(APValue &Subobj, QualType SubobjType) { 5292 // We are supposed to perform no initialization but begin the lifetime of 5293 // the object. We interpret that as meaning to do what default 5294 // initialization of the object would do if all constructors involved were 5295 // trivial: 5296 // * All base, non-variant member, and array element subobjects' lifetimes 5297 // begin 5298 // * No variant members' lifetimes begin 5299 // * All scalar subobjects whose lifetimes begin have indeterminate values 5300 assert(SubobjType->isUnionType()); 5301 if (!declaresSameEntity(Subobj.getUnionField(), Field) || 5302 !Subobj.getUnionValue().hasValue()) 5303 Subobj.setUnion(Field, getDefaultInitValue(Field->getType())); 5304 return true; 5305 } 5306 bool found(APSInt &Value, QualType SubobjType) { 5307 llvm_unreachable("wrong value kind for union object"); 5308 } 5309 bool found(APFloat &Value, QualType SubobjType) { 5310 llvm_unreachable("wrong value kind for union object"); 5311 } 5312 }; 5313 } // end anonymous namespace 5314 5315 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5316 5317 /// Handle a builtin simple-assignment or a call to a trivial assignment 5318 /// operator whose left-hand side might involve a union member access. If it 5319 /// does, implicitly start the lifetime of any accessed union elements per 5320 /// C++20 [class.union]5. 5321 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5322 const LValue &LHS) { 5323 if (LHS.InvalidBase || LHS.Designator.Invalid) 5324 return false; 5325 5326 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5327 // C++ [class.union]p5: 5328 // define the set S(E) of subexpressions of E as follows: 5329 unsigned PathLength = LHS.Designator.Entries.size(); 5330 for (const Expr *E = LHSExpr; E != nullptr;) { 5331 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5332 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5333 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5334 // Note that we can't implicitly start the lifetime of a reference, 5335 // so we don't need to proceed any further if we reach one. 5336 if (!FD || FD->getType()->isReferenceType()) 5337 break; 5338 5339 // ... and also contains A.B if B names a union member ... 5340 if (FD->getParent()->isUnion()) { 5341 // ... of a non-class, non-array type, or of a class type with a 5342 // trivial default constructor that is not deleted, or an array of 5343 // such types. 5344 auto *RD = 5345 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5346 if (!RD || RD->hasTrivialDefaultConstructor()) 5347 UnionPathLengths.push_back({PathLength - 1, FD}); 5348 } 5349 5350 E = ME->getBase(); 5351 --PathLength; 5352 assert(declaresSameEntity(FD, 5353 LHS.Designator.Entries[PathLength] 5354 .getAsBaseOrMember().getPointer())); 5355 5356 // -- If E is of the form A[B] and is interpreted as a built-in array 5357 // subscripting operator, S(E) is [S(the array operand, if any)]. 5358 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5359 // Step over an ArrayToPointerDecay implicit cast. 5360 auto *Base = ASE->getBase()->IgnoreImplicit(); 5361 if (!Base->getType()->isArrayType()) 5362 break; 5363 5364 E = Base; 5365 --PathLength; 5366 5367 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5368 // Step over a derived-to-base conversion. 5369 E = ICE->getSubExpr(); 5370 if (ICE->getCastKind() == CK_NoOp) 5371 continue; 5372 if (ICE->getCastKind() != CK_DerivedToBase && 5373 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5374 break; 5375 // Walk path backwards as we walk up from the base to the derived class. 5376 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5377 --PathLength; 5378 (void)Elt; 5379 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5380 LHS.Designator.Entries[PathLength] 5381 .getAsBaseOrMember().getPointer())); 5382 } 5383 5384 // -- Otherwise, S(E) is empty. 5385 } else { 5386 break; 5387 } 5388 } 5389 5390 // Common case: no unions' lifetimes are started. 5391 if (UnionPathLengths.empty()) 5392 return true; 5393 5394 // if modification of X [would access an inactive union member], an object 5395 // of the type of X is implicitly created 5396 CompleteObject Obj = 5397 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5398 if (!Obj) 5399 return false; 5400 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5401 llvm::reverse(UnionPathLengths)) { 5402 // Form a designator for the union object. 5403 SubobjectDesignator D = LHS.Designator; 5404 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5405 5406 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second}; 5407 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5408 return false; 5409 } 5410 5411 return true; 5412 } 5413 5414 /// Determine if a class has any fields that might need to be copied by a 5415 /// trivial copy or move operation. 5416 static bool hasFields(const CXXRecordDecl *RD) { 5417 if (!RD || RD->isEmpty()) 5418 return false; 5419 for (auto *FD : RD->fields()) { 5420 if (FD->isUnnamedBitfield()) 5421 continue; 5422 return true; 5423 } 5424 for (auto &Base : RD->bases()) 5425 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 5426 return true; 5427 return false; 5428 } 5429 5430 namespace { 5431 typedef SmallVector<APValue, 8> ArgVector; 5432 } 5433 5434 /// EvaluateArgs - Evaluate the arguments to a function call. 5435 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5436 EvalInfo &Info, const FunctionDecl *Callee) { 5437 bool Success = true; 5438 llvm::SmallBitVector ForbiddenNullArgs; 5439 if (Callee->hasAttr<NonNullAttr>()) { 5440 ForbiddenNullArgs.resize(Args.size()); 5441 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5442 if (!Attr->args_size()) { 5443 ForbiddenNullArgs.set(); 5444 break; 5445 } else 5446 for (auto Idx : Attr->args()) { 5447 unsigned ASTIdx = Idx.getASTIndex(); 5448 if (ASTIdx >= Args.size()) 5449 continue; 5450 ForbiddenNullArgs[ASTIdx] = 1; 5451 } 5452 } 5453 } 5454 for (unsigned Idx = 0; Idx < Args.size(); Idx++) { 5455 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) { 5456 // If we're checking for a potential constant expression, evaluate all 5457 // initializers even if some of them fail. 5458 if (!Info.noteFailure()) 5459 return false; 5460 Success = false; 5461 } else if (!ForbiddenNullArgs.empty() && 5462 ForbiddenNullArgs[Idx] && 5463 ArgValues[Idx].isLValue() && 5464 ArgValues[Idx].isNullPointer()) { 5465 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed); 5466 if (!Info.noteFailure()) 5467 return false; 5468 Success = false; 5469 } 5470 } 5471 return Success; 5472 } 5473 5474 /// Evaluate a function call. 5475 static bool HandleFunctionCall(SourceLocation CallLoc, 5476 const FunctionDecl *Callee, const LValue *This, 5477 ArrayRef<const Expr*> Args, const Stmt *Body, 5478 EvalInfo &Info, APValue &Result, 5479 const LValue *ResultSlot) { 5480 ArgVector ArgValues(Args.size()); 5481 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 5482 return false; 5483 5484 if (!Info.CheckCallLimit(CallLoc)) 5485 return false; 5486 5487 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5488 5489 // For a trivial copy or move assignment, perform an APValue copy. This is 5490 // essential for unions, where the operations performed by the assignment 5491 // operator cannot be represented as statements. 5492 // 5493 // Skip this for non-union classes with no fields; in that case, the defaulted 5494 // copy/move does not actually read the object. 5495 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5496 if (MD && MD->isDefaulted() && 5497 (MD->getParent()->isUnion() || 5498 (MD->isTrivial() && hasFields(MD->getParent())))) { 5499 assert(This && 5500 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5501 LValue RHS; 5502 RHS.setFrom(Info.Ctx, ArgValues[0]); 5503 APValue RHSValue; 5504 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, 5505 RHSValue, MD->getParent()->isUnion())) 5506 return false; 5507 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() && 5508 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5509 return false; 5510 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5511 RHSValue)) 5512 return false; 5513 This->moveInto(Result); 5514 return true; 5515 } else if (MD && isLambdaCallOperator(MD)) { 5516 // We're in a lambda; determine the lambda capture field maps unless we're 5517 // just constexpr checking a lambda's call operator. constexpr checking is 5518 // done before the captures have been added to the closure object (unless 5519 // we're inferring constexpr-ness), so we don't have access to them in this 5520 // case. But since we don't need the captures to constexpr check, we can 5521 // just ignore them. 5522 if (!Info.checkingPotentialConstantExpression()) 5523 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5524 Frame.LambdaThisCaptureField); 5525 } 5526 5527 StmtResult Ret = {Result, ResultSlot}; 5528 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5529 if (ESR == ESR_Succeeded) { 5530 if (Callee->getReturnType()->isVoidType()) 5531 return true; 5532 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5533 } 5534 return ESR == ESR_Returned; 5535 } 5536 5537 /// Evaluate a constructor call. 5538 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5539 APValue *ArgValues, 5540 const CXXConstructorDecl *Definition, 5541 EvalInfo &Info, APValue &Result) { 5542 SourceLocation CallLoc = E->getExprLoc(); 5543 if (!Info.CheckCallLimit(CallLoc)) 5544 return false; 5545 5546 const CXXRecordDecl *RD = Definition->getParent(); 5547 if (RD->getNumVBases()) { 5548 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5549 return false; 5550 } 5551 5552 EvalInfo::EvaluatingConstructorRAII EvalObj( 5553 Info, 5554 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5555 RD->getNumBases()); 5556 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5557 5558 // FIXME: Creating an APValue just to hold a nonexistent return value is 5559 // wasteful. 5560 APValue RetVal; 5561 StmtResult Ret = {RetVal, nullptr}; 5562 5563 // If it's a delegating constructor, delegate. 5564 if (Definition->isDelegatingConstructor()) { 5565 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5566 { 5567 FullExpressionRAII InitScope(Info); 5568 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 5569 !InitScope.destroy()) 5570 return false; 5571 } 5572 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5573 } 5574 5575 // For a trivial copy or move constructor, perform an APValue copy. This is 5576 // essential for unions (or classes with anonymous union members), where the 5577 // operations performed by the constructor cannot be represented by 5578 // ctor-initializers. 5579 // 5580 // Skip this for empty non-union classes; we should not perform an 5581 // lvalue-to-rvalue conversion on them because their copy constructor does not 5582 // actually read them. 5583 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5584 (Definition->getParent()->isUnion() || 5585 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 5586 LValue RHS; 5587 RHS.setFrom(Info.Ctx, ArgValues[0]); 5588 return handleLValueToRValueConversion( 5589 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5590 RHS, Result, Definition->getParent()->isUnion()); 5591 } 5592 5593 // Reserve space for the struct members. 5594 if (!RD->isUnion() && !Result.hasValue()) 5595 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5596 std::distance(RD->field_begin(), RD->field_end())); 5597 5598 if (RD->isInvalidDecl()) return false; 5599 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5600 5601 // A scope for temporaries lifetime-extended by reference members. 5602 BlockScopeRAII LifetimeExtendedScope(Info); 5603 5604 bool Success = true; 5605 unsigned BasesSeen = 0; 5606 #ifndef NDEBUG 5607 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5608 #endif 5609 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 5610 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 5611 // We might be initializing the same field again if this is an indirect 5612 // field initialization. 5613 if (FieldIt == RD->field_end() || 5614 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 5615 assert(Indirect && "fields out of order?"); 5616 return; 5617 } 5618 5619 // Default-initialize any fields with no explicit initializer. 5620 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 5621 assert(FieldIt != RD->field_end() && "missing field?"); 5622 if (!FieldIt->isUnnamedBitfield()) 5623 Result.getStructField(FieldIt->getFieldIndex()) = 5624 getDefaultInitValue(FieldIt->getType()); 5625 } 5626 ++FieldIt; 5627 }; 5628 for (const auto *I : Definition->inits()) { 5629 LValue Subobject = This; 5630 LValue SubobjectParent = This; 5631 APValue *Value = &Result; 5632 5633 // Determine the subobject to initialize. 5634 FieldDecl *FD = nullptr; 5635 if (I->isBaseInitializer()) { 5636 QualType BaseType(I->getBaseClass(), 0); 5637 #ifndef NDEBUG 5638 // Non-virtual base classes are initialized in the order in the class 5639 // definition. We have already checked for virtual base classes. 5640 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5641 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5642 "base class initializers not in expected order"); 5643 ++BaseIt; 5644 #endif 5645 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5646 BaseType->getAsCXXRecordDecl(), &Layout)) 5647 return false; 5648 Value = &Result.getStructBase(BasesSeen++); 5649 } else if ((FD = I->getMember())) { 5650 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5651 return false; 5652 if (RD->isUnion()) { 5653 Result = APValue(FD); 5654 Value = &Result.getUnionValue(); 5655 } else { 5656 SkipToField(FD, false); 5657 Value = &Result.getStructField(FD->getFieldIndex()); 5658 } 5659 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5660 // Walk the indirect field decl's chain to find the object to initialize, 5661 // and make sure we've initialized every step along it. 5662 auto IndirectFieldChain = IFD->chain(); 5663 for (auto *C : IndirectFieldChain) { 5664 FD = cast<FieldDecl>(C); 5665 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5666 // Switch the union field if it differs. This happens if we had 5667 // preceding zero-initialization, and we're now initializing a union 5668 // subobject other than the first. 5669 // FIXME: In this case, the values of the other subobjects are 5670 // specified, since zero-initialization sets all padding bits to zero. 5671 if (!Value->hasValue() || 5672 (Value->isUnion() && Value->getUnionField() != FD)) { 5673 if (CD->isUnion()) 5674 *Value = APValue(FD); 5675 else 5676 // FIXME: This immediately starts the lifetime of all members of an 5677 // anonymous struct. It would be preferable to strictly start member 5678 // lifetime in initialization order. 5679 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD)); 5680 } 5681 // Store Subobject as its parent before updating it for the last element 5682 // in the chain. 5683 if (C == IndirectFieldChain.back()) 5684 SubobjectParent = Subobject; 5685 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 5686 return false; 5687 if (CD->isUnion()) 5688 Value = &Value->getUnionValue(); 5689 else { 5690 if (C == IndirectFieldChain.front() && !RD->isUnion()) 5691 SkipToField(FD, true); 5692 Value = &Value->getStructField(FD->getFieldIndex()); 5693 } 5694 } 5695 } else { 5696 llvm_unreachable("unknown base initializer kind"); 5697 } 5698 5699 // Need to override This for implicit field initializers as in this case 5700 // This refers to innermost anonymous struct/union containing initializer, 5701 // not to currently constructed class. 5702 const Expr *Init = I->getInit(); 5703 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 5704 isa<CXXDefaultInitExpr>(Init)); 5705 FullExpressionRAII InitScope(Info); 5706 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 5707 (FD && FD->isBitField() && 5708 !truncateBitfieldValue(Info, Init, *Value, FD))) { 5709 // If we're checking for a potential constant expression, evaluate all 5710 // initializers even if some of them fail. 5711 if (!Info.noteFailure()) 5712 return false; 5713 Success = false; 5714 } 5715 5716 // This is the point at which the dynamic type of the object becomes this 5717 // class type. 5718 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 5719 EvalObj.finishedConstructingBases(); 5720 } 5721 5722 // Default-initialize any remaining fields. 5723 if (!RD->isUnion()) { 5724 for (; FieldIt != RD->field_end(); ++FieldIt) { 5725 if (!FieldIt->isUnnamedBitfield()) 5726 Result.getStructField(FieldIt->getFieldIndex()) = 5727 getDefaultInitValue(FieldIt->getType()); 5728 } 5729 } 5730 5731 return Success && 5732 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 5733 LifetimeExtendedScope.destroy(); 5734 } 5735 5736 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5737 ArrayRef<const Expr*> Args, 5738 const CXXConstructorDecl *Definition, 5739 EvalInfo &Info, APValue &Result) { 5740 ArgVector ArgValues(Args.size()); 5741 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 5742 return false; 5743 5744 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 5745 Info, Result); 5746 } 5747 5748 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 5749 const LValue &This, APValue &Value, 5750 QualType T) { 5751 // Objects can only be destroyed while they're within their lifetimes. 5752 // FIXME: We have no representation for whether an object of type nullptr_t 5753 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 5754 // as indeterminate instead? 5755 if (Value.isAbsent() && !T->isNullPtrType()) { 5756 APValue Printable; 5757 This.moveInto(Printable); 5758 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 5759 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 5760 return false; 5761 } 5762 5763 // Invent an expression for location purposes. 5764 // FIXME: We shouldn't need to do this. 5765 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 5766 5767 // For arrays, destroy elements right-to-left. 5768 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 5769 uint64_t Size = CAT->getSize().getZExtValue(); 5770 QualType ElemT = CAT->getElementType(); 5771 5772 LValue ElemLV = This; 5773 ElemLV.addArray(Info, &LocE, CAT); 5774 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 5775 return false; 5776 5777 // Ensure that we have actual array elements available to destroy; the 5778 // destructors might mutate the value, so we can't run them on the array 5779 // filler. 5780 if (Size && Size > Value.getArrayInitializedElts()) 5781 expandArray(Value, Value.getArraySize() - 1); 5782 5783 for (; Size != 0; --Size) { 5784 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 5785 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 5786 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 5787 return false; 5788 } 5789 5790 // End the lifetime of this array now. 5791 Value = APValue(); 5792 return true; 5793 } 5794 5795 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5796 if (!RD) { 5797 if (T.isDestructedType()) { 5798 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 5799 return false; 5800 } 5801 5802 Value = APValue(); 5803 return true; 5804 } 5805 5806 if (RD->getNumVBases()) { 5807 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5808 return false; 5809 } 5810 5811 const CXXDestructorDecl *DD = RD->getDestructor(); 5812 if (!DD && !RD->hasTrivialDestructor()) { 5813 Info.FFDiag(CallLoc); 5814 return false; 5815 } 5816 5817 if (!DD || DD->isTrivial() || 5818 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 5819 // A trivial destructor just ends the lifetime of the object. Check for 5820 // this case before checking for a body, because we might not bother 5821 // building a body for a trivial destructor. Note that it doesn't matter 5822 // whether the destructor is constexpr in this case; all trivial 5823 // destructors are constexpr. 5824 // 5825 // If an anonymous union would be destroyed, some enclosing destructor must 5826 // have been explicitly defined, and the anonymous union destruction should 5827 // have no effect. 5828 Value = APValue(); 5829 return true; 5830 } 5831 5832 if (!Info.CheckCallLimit(CallLoc)) 5833 return false; 5834 5835 const FunctionDecl *Definition = nullptr; 5836 const Stmt *Body = DD->getBody(Definition); 5837 5838 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 5839 return false; 5840 5841 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); 5842 5843 // We're now in the period of destruction of this object. 5844 unsigned BasesLeft = RD->getNumBases(); 5845 EvalInfo::EvaluatingDestructorRAII EvalObj( 5846 Info, 5847 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 5848 if (!EvalObj.DidInsert) { 5849 // C++2a [class.dtor]p19: 5850 // the behavior is undefined if the destructor is invoked for an object 5851 // whose lifetime has ended 5852 // (Note that formally the lifetime ends when the period of destruction 5853 // begins, even though certain uses of the object remain valid until the 5854 // period of destruction ends.) 5855 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 5856 return false; 5857 } 5858 5859 // FIXME: Creating an APValue just to hold a nonexistent return value is 5860 // wasteful. 5861 APValue RetVal; 5862 StmtResult Ret = {RetVal, nullptr}; 5863 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 5864 return false; 5865 5866 // A union destructor does not implicitly destroy its members. 5867 if (RD->isUnion()) 5868 return true; 5869 5870 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5871 5872 // We don't have a good way to iterate fields in reverse, so collect all the 5873 // fields first and then walk them backwards. 5874 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 5875 for (const FieldDecl *FD : llvm::reverse(Fields)) { 5876 if (FD->isUnnamedBitfield()) 5877 continue; 5878 5879 LValue Subobject = This; 5880 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 5881 return false; 5882 5883 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 5884 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 5885 FD->getType())) 5886 return false; 5887 } 5888 5889 if (BasesLeft != 0) 5890 EvalObj.startedDestroyingBases(); 5891 5892 // Destroy base classes in reverse order. 5893 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 5894 --BasesLeft; 5895 5896 QualType BaseType = Base.getType(); 5897 LValue Subobject = This; 5898 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 5899 BaseType->getAsCXXRecordDecl(), &Layout)) 5900 return false; 5901 5902 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 5903 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 5904 BaseType)) 5905 return false; 5906 } 5907 assert(BasesLeft == 0 && "NumBases was wrong?"); 5908 5909 // The period of destruction ends now. The object is gone. 5910 Value = APValue(); 5911 return true; 5912 } 5913 5914 namespace { 5915 struct DestroyObjectHandler { 5916 EvalInfo &Info; 5917 const Expr *E; 5918 const LValue &This; 5919 const AccessKinds AccessKind; 5920 5921 typedef bool result_type; 5922 bool failed() { return false; } 5923 bool found(APValue &Subobj, QualType SubobjType) { 5924 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 5925 SubobjType); 5926 } 5927 bool found(APSInt &Value, QualType SubobjType) { 5928 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 5929 return false; 5930 } 5931 bool found(APFloat &Value, QualType SubobjType) { 5932 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 5933 return false; 5934 } 5935 }; 5936 } 5937 5938 /// Perform a destructor or pseudo-destructor call on the given object, which 5939 /// might in general not be a complete object. 5940 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 5941 const LValue &This, QualType ThisType) { 5942 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 5943 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 5944 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5945 } 5946 5947 /// Destroy and end the lifetime of the given complete object. 5948 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 5949 APValue::LValueBase LVBase, APValue &Value, 5950 QualType T) { 5951 // If we've had an unmodeled side-effect, we can't rely on mutable state 5952 // (such as the object we're about to destroy) being correct. 5953 if (Info.EvalStatus.HasSideEffects) 5954 return false; 5955 5956 LValue LV; 5957 LV.set({LVBase}); 5958 return HandleDestructionImpl(Info, Loc, LV, Value, T); 5959 } 5960 5961 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 5962 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 5963 LValue &Result) { 5964 if (Info.checkingPotentialConstantExpression() || 5965 Info.SpeculativeEvaluationDepth) 5966 return false; 5967 5968 // This is permitted only within a call to std::allocator<T>::allocate. 5969 auto Caller = Info.getStdAllocatorCaller("allocate"); 5970 if (!Caller) { 5971 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a 5972 ? diag::note_constexpr_new_untyped 5973 : diag::note_constexpr_new); 5974 return false; 5975 } 5976 5977 QualType ElemType = Caller.ElemType; 5978 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 5979 Info.FFDiag(E->getExprLoc(), 5980 diag::note_constexpr_new_not_complete_object_type) 5981 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 5982 return false; 5983 } 5984 5985 APSInt ByteSize; 5986 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 5987 return false; 5988 bool IsNothrow = false; 5989 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 5990 EvaluateIgnoredValue(Info, E->getArg(I)); 5991 IsNothrow |= E->getType()->isNothrowT(); 5992 } 5993 5994 CharUnits ElemSize; 5995 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 5996 return false; 5997 APInt Size, Remainder; 5998 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 5999 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6000 if (Remainder != 0) { 6001 // This likely indicates a bug in the implementation of 'std::allocator'. 6002 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6003 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6004 return false; 6005 } 6006 6007 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6008 if (IsNothrow) { 6009 Result.setNull(Info.Ctx, E->getType()); 6010 return true; 6011 } 6012 6013 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6014 return false; 6015 } 6016 6017 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6018 ArrayType::Normal, 0); 6019 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6020 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6021 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6022 return true; 6023 } 6024 6025 static bool hasVirtualDestructor(QualType T) { 6026 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6027 if (CXXDestructorDecl *DD = RD->getDestructor()) 6028 return DD->isVirtual(); 6029 return false; 6030 } 6031 6032 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6033 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6034 if (CXXDestructorDecl *DD = RD->getDestructor()) 6035 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6036 return nullptr; 6037 } 6038 6039 /// Check that the given object is a suitable pointer to a heap allocation that 6040 /// still exists and is of the right kind for the purpose of a deletion. 6041 /// 6042 /// On success, returns the heap allocation to deallocate. On failure, produces 6043 /// a diagnostic and returns None. 6044 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6045 const LValue &Pointer, 6046 DynAlloc::Kind DeallocKind) { 6047 auto PointerAsString = [&] { 6048 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6049 }; 6050 6051 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6052 if (!DA) { 6053 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6054 << PointerAsString(); 6055 if (Pointer.Base) 6056 NoteLValueLocation(Info, Pointer.Base); 6057 return None; 6058 } 6059 6060 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6061 if (!Alloc) { 6062 Info.FFDiag(E, diag::note_constexpr_double_delete); 6063 return None; 6064 } 6065 6066 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6067 if (DeallocKind != (*Alloc)->getKind()) { 6068 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6069 << DeallocKind << (*Alloc)->getKind() << AllocType; 6070 NoteLValueLocation(Info, Pointer.Base); 6071 return None; 6072 } 6073 6074 bool Subobject = false; 6075 if (DeallocKind == DynAlloc::New) { 6076 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6077 Pointer.Designator.isOnePastTheEnd(); 6078 } else { 6079 Subobject = Pointer.Designator.Entries.size() != 1 || 6080 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6081 } 6082 if (Subobject) { 6083 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6084 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6085 return None; 6086 } 6087 6088 return Alloc; 6089 } 6090 6091 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6092 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6093 if (Info.checkingPotentialConstantExpression() || 6094 Info.SpeculativeEvaluationDepth) 6095 return false; 6096 6097 // This is permitted only within a call to std::allocator<T>::deallocate. 6098 if (!Info.getStdAllocatorCaller("deallocate")) { 6099 Info.FFDiag(E->getExprLoc()); 6100 return true; 6101 } 6102 6103 LValue Pointer; 6104 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6105 return false; 6106 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6107 EvaluateIgnoredValue(Info, E->getArg(I)); 6108 6109 if (Pointer.Designator.Invalid) 6110 return false; 6111 6112 // Deleting a null pointer has no effect. 6113 if (Pointer.isNullPointer()) 6114 return true; 6115 6116 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6117 return false; 6118 6119 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6120 return true; 6121 } 6122 6123 //===----------------------------------------------------------------------===// 6124 // Generic Evaluation 6125 //===----------------------------------------------------------------------===// 6126 namespace { 6127 6128 class BitCastBuffer { 6129 // FIXME: We're going to need bit-level granularity when we support 6130 // bit-fields. 6131 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6132 // we don't support a host or target where that is the case. Still, we should 6133 // use a more generic type in case we ever do. 6134 SmallVector<Optional<unsigned char>, 32> Bytes; 6135 6136 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6137 "Need at least 8 bit unsigned char"); 6138 6139 bool TargetIsLittleEndian; 6140 6141 public: 6142 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6143 : Bytes(Width.getQuantity()), 6144 TargetIsLittleEndian(TargetIsLittleEndian) {} 6145 6146 LLVM_NODISCARD 6147 bool readObject(CharUnits Offset, CharUnits Width, 6148 SmallVectorImpl<unsigned char> &Output) const { 6149 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6150 // If a byte of an integer is uninitialized, then the whole integer is 6151 // uninitalized. 6152 if (!Bytes[I.getQuantity()]) 6153 return false; 6154 Output.push_back(*Bytes[I.getQuantity()]); 6155 } 6156 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6157 std::reverse(Output.begin(), Output.end()); 6158 return true; 6159 } 6160 6161 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6162 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6163 std::reverse(Input.begin(), Input.end()); 6164 6165 size_t Index = 0; 6166 for (unsigned char Byte : Input) { 6167 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6168 Bytes[Offset.getQuantity() + Index] = Byte; 6169 ++Index; 6170 } 6171 } 6172 6173 size_t size() { return Bytes.size(); } 6174 }; 6175 6176 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6177 /// target would represent the value at runtime. 6178 class APValueToBufferConverter { 6179 EvalInfo &Info; 6180 BitCastBuffer Buffer; 6181 const CastExpr *BCE; 6182 6183 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6184 const CastExpr *BCE) 6185 : Info(Info), 6186 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6187 BCE(BCE) {} 6188 6189 bool visit(const APValue &Val, QualType Ty) { 6190 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6191 } 6192 6193 // Write out Val with type Ty into Buffer starting at Offset. 6194 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6195 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6196 6197 // As a special case, nullptr_t has an indeterminate value. 6198 if (Ty->isNullPtrType()) 6199 return true; 6200 6201 // Dig through Src to find the byte at SrcOffset. 6202 switch (Val.getKind()) { 6203 case APValue::Indeterminate: 6204 case APValue::None: 6205 return true; 6206 6207 case APValue::Int: 6208 return visitInt(Val.getInt(), Ty, Offset); 6209 case APValue::Float: 6210 return visitFloat(Val.getFloat(), Ty, Offset); 6211 case APValue::Array: 6212 return visitArray(Val, Ty, Offset); 6213 case APValue::Struct: 6214 return visitRecord(Val, Ty, Offset); 6215 6216 case APValue::ComplexInt: 6217 case APValue::ComplexFloat: 6218 case APValue::Vector: 6219 case APValue::FixedPoint: 6220 // FIXME: We should support these. 6221 6222 case APValue::Union: 6223 case APValue::MemberPointer: 6224 case APValue::AddrLabelDiff: { 6225 Info.FFDiag(BCE->getBeginLoc(), 6226 diag::note_constexpr_bit_cast_unsupported_type) 6227 << Ty; 6228 return false; 6229 } 6230 6231 case APValue::LValue: 6232 llvm_unreachable("LValue subobject in bit_cast?"); 6233 } 6234 llvm_unreachable("Unhandled APValue::ValueKind"); 6235 } 6236 6237 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6238 const RecordDecl *RD = Ty->getAsRecordDecl(); 6239 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6240 6241 // Visit the base classes. 6242 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6243 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6244 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6245 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6246 6247 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6248 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6249 return false; 6250 } 6251 } 6252 6253 // Visit the fields. 6254 unsigned FieldIdx = 0; 6255 for (FieldDecl *FD : RD->fields()) { 6256 if (FD->isBitField()) { 6257 Info.FFDiag(BCE->getBeginLoc(), 6258 diag::note_constexpr_bit_cast_unsupported_bitfield); 6259 return false; 6260 } 6261 6262 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6263 6264 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6265 "only bit-fields can have sub-char alignment"); 6266 CharUnits FieldOffset = 6267 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6268 QualType FieldTy = FD->getType(); 6269 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6270 return false; 6271 ++FieldIdx; 6272 } 6273 6274 return true; 6275 } 6276 6277 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6278 const auto *CAT = 6279 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6280 if (!CAT) 6281 return false; 6282 6283 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6284 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6285 unsigned ArraySize = Val.getArraySize(); 6286 // First, initialize the initialized elements. 6287 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6288 const APValue &SubObj = Val.getArrayInitializedElt(I); 6289 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6290 return false; 6291 } 6292 6293 // Next, initialize the rest of the array using the filler. 6294 if (Val.hasArrayFiller()) { 6295 const APValue &Filler = Val.getArrayFiller(); 6296 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6297 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6298 return false; 6299 } 6300 } 6301 6302 return true; 6303 } 6304 6305 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6306 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); 6307 SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); 6308 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); 6309 Buffer.writeObject(Offset, Bytes); 6310 return true; 6311 } 6312 6313 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6314 APSInt AsInt(Val.bitcastToAPInt()); 6315 return visitInt(AsInt, Ty, Offset); 6316 } 6317 6318 public: 6319 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6320 const CastExpr *BCE) { 6321 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6322 APValueToBufferConverter Converter(Info, DstSize, BCE); 6323 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6324 return None; 6325 return Converter.Buffer; 6326 } 6327 }; 6328 6329 /// Write an BitCastBuffer into an APValue. 6330 class BufferToAPValueConverter { 6331 EvalInfo &Info; 6332 const BitCastBuffer &Buffer; 6333 const CastExpr *BCE; 6334 6335 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6336 const CastExpr *BCE) 6337 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6338 6339 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6340 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6341 // Ideally this will be unreachable. 6342 llvm::NoneType unsupportedType(QualType Ty) { 6343 Info.FFDiag(BCE->getBeginLoc(), 6344 diag::note_constexpr_bit_cast_unsupported_type) 6345 << Ty; 6346 return None; 6347 } 6348 6349 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6350 const EnumType *EnumSugar = nullptr) { 6351 if (T->isNullPtrType()) { 6352 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6353 return APValue((Expr *)nullptr, 6354 /*Offset=*/CharUnits::fromQuantity(NullValue), 6355 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6356 } 6357 6358 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6359 SmallVector<uint8_t, 8> Bytes; 6360 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6361 // If this is std::byte or unsigned char, then its okay to store an 6362 // indeterminate value. 6363 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6364 bool IsUChar = 6365 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6366 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6367 if (!IsStdByte && !IsUChar) { 6368 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6369 Info.FFDiag(BCE->getExprLoc(), 6370 diag::note_constexpr_bit_cast_indet_dest) 6371 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6372 return None; 6373 } 6374 6375 return APValue::IndeterminateValue(); 6376 } 6377 6378 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6379 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6380 6381 if (T->isIntegralOrEnumerationType()) { 6382 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6383 return APValue(Val); 6384 } 6385 6386 if (T->isRealFloatingType()) { 6387 const llvm::fltSemantics &Semantics = 6388 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6389 return APValue(APFloat(Semantics, Val)); 6390 } 6391 6392 return unsupportedType(QualType(T, 0)); 6393 } 6394 6395 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6396 const RecordDecl *RD = RTy->getAsRecordDecl(); 6397 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6398 6399 unsigned NumBases = 0; 6400 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6401 NumBases = CXXRD->getNumBases(); 6402 6403 APValue ResultVal(APValue::UninitStruct(), NumBases, 6404 std::distance(RD->field_begin(), RD->field_end())); 6405 6406 // Visit the base classes. 6407 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6408 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6409 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6410 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6411 if (BaseDecl->isEmpty() || 6412 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6413 continue; 6414 6415 Optional<APValue> SubObj = visitType( 6416 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6417 if (!SubObj) 6418 return None; 6419 ResultVal.getStructBase(I) = *SubObj; 6420 } 6421 } 6422 6423 // Visit the fields. 6424 unsigned FieldIdx = 0; 6425 for (FieldDecl *FD : RD->fields()) { 6426 // FIXME: We don't currently support bit-fields. A lot of the logic for 6427 // this is in CodeGen, so we need to factor it around. 6428 if (FD->isBitField()) { 6429 Info.FFDiag(BCE->getBeginLoc(), 6430 diag::note_constexpr_bit_cast_unsupported_bitfield); 6431 return None; 6432 } 6433 6434 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6435 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6436 6437 CharUnits FieldOffset = 6438 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6439 Offset; 6440 QualType FieldTy = FD->getType(); 6441 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6442 if (!SubObj) 6443 return None; 6444 ResultVal.getStructField(FieldIdx) = *SubObj; 6445 ++FieldIdx; 6446 } 6447 6448 return ResultVal; 6449 } 6450 6451 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6452 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6453 assert(!RepresentationType.isNull() && 6454 "enum forward decl should be caught by Sema"); 6455 const auto *AsBuiltin = 6456 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 6457 // Recurse into the underlying type. Treat std::byte transparently as 6458 // unsigned char. 6459 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6460 } 6461 6462 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6463 size_t Size = Ty->getSize().getLimitedValue(); 6464 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6465 6466 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6467 for (size_t I = 0; I != Size; ++I) { 6468 Optional<APValue> ElementValue = 6469 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6470 if (!ElementValue) 6471 return None; 6472 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6473 } 6474 6475 return ArrayValue; 6476 } 6477 6478 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6479 return unsupportedType(QualType(Ty, 0)); 6480 } 6481 6482 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6483 QualType Can = Ty.getCanonicalType(); 6484 6485 switch (Can->getTypeClass()) { 6486 #define TYPE(Class, Base) \ 6487 case Type::Class: \ 6488 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6489 #define ABSTRACT_TYPE(Class, Base) 6490 #define NON_CANONICAL_TYPE(Class, Base) \ 6491 case Type::Class: \ 6492 llvm_unreachable("non-canonical type should be impossible!"); 6493 #define DEPENDENT_TYPE(Class, Base) \ 6494 case Type::Class: \ 6495 llvm_unreachable( \ 6496 "dependent types aren't supported in the constant evaluator!"); 6497 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6498 case Type::Class: \ 6499 llvm_unreachable("either dependent or not canonical!"); 6500 #include "clang/AST/TypeNodes.inc" 6501 } 6502 llvm_unreachable("Unhandled Type::TypeClass"); 6503 } 6504 6505 public: 6506 // Pull out a full value of type DstType. 6507 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6508 const CastExpr *BCE) { 6509 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6510 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6511 } 6512 }; 6513 6514 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6515 QualType Ty, EvalInfo *Info, 6516 const ASTContext &Ctx, 6517 bool CheckingDest) { 6518 Ty = Ty.getCanonicalType(); 6519 6520 auto diag = [&](int Reason) { 6521 if (Info) 6522 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6523 << CheckingDest << (Reason == 4) << Reason; 6524 return false; 6525 }; 6526 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6527 if (Info) 6528 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6529 << NoteTy << Construct << Ty; 6530 return false; 6531 }; 6532 6533 if (Ty->isUnionType()) 6534 return diag(0); 6535 if (Ty->isPointerType()) 6536 return diag(1); 6537 if (Ty->isMemberPointerType()) 6538 return diag(2); 6539 if (Ty.isVolatileQualified()) 6540 return diag(3); 6541 6542 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6543 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6544 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6545 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6546 CheckingDest)) 6547 return note(1, BS.getType(), BS.getBeginLoc()); 6548 } 6549 for (FieldDecl *FD : Record->fields()) { 6550 if (FD->getType()->isReferenceType()) 6551 return diag(4); 6552 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6553 CheckingDest)) 6554 return note(0, FD->getType(), FD->getBeginLoc()); 6555 } 6556 } 6557 6558 if (Ty->isArrayType() && 6559 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6560 Info, Ctx, CheckingDest)) 6561 return false; 6562 6563 return true; 6564 } 6565 6566 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6567 const ASTContext &Ctx, 6568 const CastExpr *BCE) { 6569 bool DestOK = checkBitCastConstexprEligibilityType( 6570 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6571 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6572 BCE->getBeginLoc(), 6573 BCE->getSubExpr()->getType(), Info, Ctx, false); 6574 return SourceOK; 6575 } 6576 6577 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6578 APValue &SourceValue, 6579 const CastExpr *BCE) { 6580 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6581 "no host or target supports non 8-bit chars"); 6582 assert(SourceValue.isLValue() && 6583 "LValueToRValueBitcast requires an lvalue operand!"); 6584 6585 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6586 return false; 6587 6588 LValue SourceLValue; 6589 APValue SourceRValue; 6590 SourceLValue.setFrom(Info.Ctx, SourceValue); 6591 if (!handleLValueToRValueConversion( 6592 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 6593 SourceRValue, /*WantObjectRepresentation=*/true)) 6594 return false; 6595 6596 // Read out SourceValue into a char buffer. 6597 Optional<BitCastBuffer> Buffer = 6598 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 6599 if (!Buffer) 6600 return false; 6601 6602 // Write out the buffer into a new APValue. 6603 Optional<APValue> MaybeDestValue = 6604 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 6605 if (!MaybeDestValue) 6606 return false; 6607 6608 DestValue = std::move(*MaybeDestValue); 6609 return true; 6610 } 6611 6612 template <class Derived> 6613 class ExprEvaluatorBase 6614 : public ConstStmtVisitor<Derived, bool> { 6615 private: 6616 Derived &getDerived() { return static_cast<Derived&>(*this); } 6617 bool DerivedSuccess(const APValue &V, const Expr *E) { 6618 return getDerived().Success(V, E); 6619 } 6620 bool DerivedZeroInitialization(const Expr *E) { 6621 return getDerived().ZeroInitialization(E); 6622 } 6623 6624 // Check whether a conditional operator with a non-constant condition is a 6625 // potential constant expression. If neither arm is a potential constant 6626 // expression, then the conditional operator is not either. 6627 template<typename ConditionalOperator> 6628 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 6629 assert(Info.checkingPotentialConstantExpression()); 6630 6631 // Speculatively evaluate both arms. 6632 SmallVector<PartialDiagnosticAt, 8> Diag; 6633 { 6634 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6635 StmtVisitorTy::Visit(E->getFalseExpr()); 6636 if (Diag.empty()) 6637 return; 6638 } 6639 6640 { 6641 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6642 Diag.clear(); 6643 StmtVisitorTy::Visit(E->getTrueExpr()); 6644 if (Diag.empty()) 6645 return; 6646 } 6647 6648 Error(E, diag::note_constexpr_conditional_never_const); 6649 } 6650 6651 6652 template<typename ConditionalOperator> 6653 bool HandleConditionalOperator(const ConditionalOperator *E) { 6654 bool BoolResult; 6655 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 6656 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 6657 CheckPotentialConstantConditional(E); 6658 return false; 6659 } 6660 if (Info.noteFailure()) { 6661 StmtVisitorTy::Visit(E->getTrueExpr()); 6662 StmtVisitorTy::Visit(E->getFalseExpr()); 6663 } 6664 return false; 6665 } 6666 6667 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 6668 return StmtVisitorTy::Visit(EvalExpr); 6669 } 6670 6671 protected: 6672 EvalInfo &Info; 6673 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 6674 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 6675 6676 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 6677 return Info.CCEDiag(E, D); 6678 } 6679 6680 bool ZeroInitialization(const Expr *E) { return Error(E); } 6681 6682 public: 6683 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 6684 6685 EvalInfo &getEvalInfo() { return Info; } 6686 6687 /// Report an evaluation error. This should only be called when an error is 6688 /// first discovered. When propagating an error, just return false. 6689 bool Error(const Expr *E, diag::kind D) { 6690 Info.FFDiag(E, D); 6691 return false; 6692 } 6693 bool Error(const Expr *E) { 6694 return Error(E, diag::note_invalid_subexpr_in_const_expr); 6695 } 6696 6697 bool VisitStmt(const Stmt *) { 6698 llvm_unreachable("Expression evaluator should not be called on stmts"); 6699 } 6700 bool VisitExpr(const Expr *E) { 6701 return Error(E); 6702 } 6703 6704 bool VisitConstantExpr(const ConstantExpr *E) 6705 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6706 bool VisitParenExpr(const ParenExpr *E) 6707 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6708 bool VisitUnaryExtension(const UnaryOperator *E) 6709 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6710 bool VisitUnaryPlus(const UnaryOperator *E) 6711 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6712 bool VisitChooseExpr(const ChooseExpr *E) 6713 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 6714 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 6715 { return StmtVisitorTy::Visit(E->getResultExpr()); } 6716 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 6717 { return StmtVisitorTy::Visit(E->getReplacement()); } 6718 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 6719 TempVersionRAII RAII(*Info.CurrentCall); 6720 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 6721 return StmtVisitorTy::Visit(E->getExpr()); 6722 } 6723 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 6724 TempVersionRAII RAII(*Info.CurrentCall); 6725 // The initializer may not have been parsed yet, or might be erroneous. 6726 if (!E->getExpr()) 6727 return Error(E); 6728 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 6729 return StmtVisitorTy::Visit(E->getExpr()); 6730 } 6731 6732 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 6733 FullExpressionRAII Scope(Info); 6734 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 6735 } 6736 6737 // Temporaries are registered when created, so we don't care about 6738 // CXXBindTemporaryExpr. 6739 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 6740 return StmtVisitorTy::Visit(E->getSubExpr()); 6741 } 6742 6743 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 6744 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 6745 return static_cast<Derived*>(this)->VisitCastExpr(E); 6746 } 6747 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 6748 if (!Info.Ctx.getLangOpts().CPlusPlus2a) 6749 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 6750 return static_cast<Derived*>(this)->VisitCastExpr(E); 6751 } 6752 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 6753 return static_cast<Derived*>(this)->VisitCastExpr(E); 6754 } 6755 6756 bool VisitBinaryOperator(const BinaryOperator *E) { 6757 switch (E->getOpcode()) { 6758 default: 6759 return Error(E); 6760 6761 case BO_Comma: 6762 VisitIgnoredValue(E->getLHS()); 6763 return StmtVisitorTy::Visit(E->getRHS()); 6764 6765 case BO_PtrMemD: 6766 case BO_PtrMemI: { 6767 LValue Obj; 6768 if (!HandleMemberPointerAccess(Info, E, Obj)) 6769 return false; 6770 APValue Result; 6771 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 6772 return false; 6773 return DerivedSuccess(Result, E); 6774 } 6775 } 6776 } 6777 6778 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 6779 return StmtVisitorTy::Visit(E->getSemanticForm()); 6780 } 6781 6782 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 6783 // Evaluate and cache the common expression. We treat it as a temporary, 6784 // even though it's not quite the same thing. 6785 LValue CommonLV; 6786 if (!Evaluate(Info.CurrentCall->createTemporary( 6787 E->getOpaqueValue(), 6788 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 6789 CommonLV), 6790 Info, E->getCommon())) 6791 return false; 6792 6793 return HandleConditionalOperator(E); 6794 } 6795 6796 bool VisitConditionalOperator(const ConditionalOperator *E) { 6797 bool IsBcpCall = false; 6798 // If the condition (ignoring parens) is a __builtin_constant_p call, 6799 // the result is a constant expression if it can be folded without 6800 // side-effects. This is an important GNU extension. See GCC PR38377 6801 // for discussion. 6802 if (const CallExpr *CallCE = 6803 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 6804 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 6805 IsBcpCall = true; 6806 6807 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 6808 // constant expression; we can't check whether it's potentially foldable. 6809 // FIXME: We should instead treat __builtin_constant_p as non-constant if 6810 // it would return 'false' in this mode. 6811 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 6812 return false; 6813 6814 FoldConstant Fold(Info, IsBcpCall); 6815 if (!HandleConditionalOperator(E)) { 6816 Fold.keepDiagnostics(); 6817 return false; 6818 } 6819 6820 return true; 6821 } 6822 6823 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 6824 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 6825 return DerivedSuccess(*Value, E); 6826 6827 const Expr *Source = E->getSourceExpr(); 6828 if (!Source) 6829 return Error(E); 6830 if (Source == E) { // sanity checking. 6831 assert(0 && "OpaqueValueExpr recursively refers to itself"); 6832 return Error(E); 6833 } 6834 return StmtVisitorTy::Visit(Source); 6835 } 6836 6837 bool VisitCallExpr(const CallExpr *E) { 6838 APValue Result; 6839 if (!handleCallExpr(E, Result, nullptr)) 6840 return false; 6841 return DerivedSuccess(Result, E); 6842 } 6843 6844 bool handleCallExpr(const CallExpr *E, APValue &Result, 6845 const LValue *ResultSlot) { 6846 const Expr *Callee = E->getCallee()->IgnoreParens(); 6847 QualType CalleeType = Callee->getType(); 6848 6849 const FunctionDecl *FD = nullptr; 6850 LValue *This = nullptr, ThisVal; 6851 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6852 bool HasQualifier = false; 6853 6854 // Extract function decl and 'this' pointer from the callee. 6855 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 6856 const CXXMethodDecl *Member = nullptr; 6857 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 6858 // Explicit bound member calls, such as x.f() or p->g(); 6859 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 6860 return false; 6861 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 6862 if (!Member) 6863 return Error(Callee); 6864 This = &ThisVal; 6865 HasQualifier = ME->hasQualifier(); 6866 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 6867 // Indirect bound member calls ('.*' or '->*'). 6868 const ValueDecl *D = 6869 HandleMemberPointerAccess(Info, BE, ThisVal, false); 6870 if (!D) 6871 return false; 6872 Member = dyn_cast<CXXMethodDecl>(D); 6873 if (!Member) 6874 return Error(Callee); 6875 This = &ThisVal; 6876 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 6877 if (!Info.getLangOpts().CPlusPlus2a) 6878 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 6879 // FIXME: If pseudo-destructor calls ever start ending the lifetime of 6880 // their callee, we should start calling HandleDestruction here. 6881 // For now, we just evaluate the object argument and discard it. 6882 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal); 6883 } else 6884 return Error(Callee); 6885 FD = Member; 6886 } else if (CalleeType->isFunctionPointerType()) { 6887 LValue Call; 6888 if (!EvaluatePointer(Callee, Call, Info)) 6889 return false; 6890 6891 if (!Call.getLValueOffset().isZero()) 6892 return Error(Callee); 6893 FD = dyn_cast_or_null<FunctionDecl>( 6894 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 6895 if (!FD) 6896 return Error(Callee); 6897 // Don't call function pointers which have been cast to some other type. 6898 // Per DR (no number yet), the caller and callee can differ in noexcept. 6899 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 6900 CalleeType->getPointeeType(), FD->getType())) { 6901 return Error(E); 6902 } 6903 6904 // Overloaded operator calls to member functions are represented as normal 6905 // calls with '*this' as the first argument. 6906 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6907 if (MD && !MD->isStatic()) { 6908 // FIXME: When selecting an implicit conversion for an overloaded 6909 // operator delete, we sometimes try to evaluate calls to conversion 6910 // operators without a 'this' parameter! 6911 if (Args.empty()) 6912 return Error(E); 6913 6914 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 6915 return false; 6916 This = &ThisVal; 6917 Args = Args.slice(1); 6918 } else if (MD && MD->isLambdaStaticInvoker()) { 6919 // Map the static invoker for the lambda back to the call operator. 6920 // Conveniently, we don't have to slice out the 'this' argument (as is 6921 // being done for the non-static case), since a static member function 6922 // doesn't have an implicit argument passed in. 6923 const CXXRecordDecl *ClosureClass = MD->getParent(); 6924 assert( 6925 ClosureClass->captures_begin() == ClosureClass->captures_end() && 6926 "Number of captures must be zero for conversion to function-ptr"); 6927 6928 const CXXMethodDecl *LambdaCallOp = 6929 ClosureClass->getLambdaCallOperator(); 6930 6931 // Set 'FD', the function that will be called below, to the call 6932 // operator. If the closure object represents a generic lambda, find 6933 // the corresponding specialization of the call operator. 6934 6935 if (ClosureClass->isGenericLambda()) { 6936 assert(MD->isFunctionTemplateSpecialization() && 6937 "A generic lambda's static-invoker function must be a " 6938 "template specialization"); 6939 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 6940 FunctionTemplateDecl *CallOpTemplate = 6941 LambdaCallOp->getDescribedFunctionTemplate(); 6942 void *InsertPos = nullptr; 6943 FunctionDecl *CorrespondingCallOpSpecialization = 6944 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 6945 assert(CorrespondingCallOpSpecialization && 6946 "We must always have a function call operator specialization " 6947 "that corresponds to our static invoker specialization"); 6948 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 6949 } else 6950 FD = LambdaCallOp; 6951 } else if (FD->isReplaceableGlobalAllocationFunction()) { 6952 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 6953 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 6954 LValue Ptr; 6955 if (!HandleOperatorNewCall(Info, E, Ptr)) 6956 return false; 6957 Ptr.moveInto(Result); 6958 return true; 6959 } else { 6960 return HandleOperatorDeleteCall(Info, E); 6961 } 6962 } 6963 } else 6964 return Error(E); 6965 6966 SmallVector<QualType, 4> CovariantAdjustmentPath; 6967 if (This) { 6968 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 6969 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 6970 // Perform virtual dispatch, if necessary. 6971 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 6972 CovariantAdjustmentPath); 6973 if (!FD) 6974 return false; 6975 } else { 6976 // Check that the 'this' pointer points to an object of the right type. 6977 // FIXME: If this is an assignment operator call, we may need to change 6978 // the active union member before we check this. 6979 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 6980 return false; 6981 } 6982 } 6983 6984 // Destructor calls are different enough that they have their own codepath. 6985 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 6986 assert(This && "no 'this' pointer for destructor call"); 6987 return HandleDestruction(Info, E, *This, 6988 Info.Ctx.getRecordType(DD->getParent())); 6989 } 6990 6991 const FunctionDecl *Definition = nullptr; 6992 Stmt *Body = FD->getBody(Definition); 6993 6994 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 6995 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 6996 Result, ResultSlot)) 6997 return false; 6998 6999 if (!CovariantAdjustmentPath.empty() && 7000 !HandleCovariantReturnAdjustment(Info, E, Result, 7001 CovariantAdjustmentPath)) 7002 return false; 7003 7004 return true; 7005 } 7006 7007 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7008 return StmtVisitorTy::Visit(E->getInitializer()); 7009 } 7010 bool VisitInitListExpr(const InitListExpr *E) { 7011 if (E->getNumInits() == 0) 7012 return DerivedZeroInitialization(E); 7013 if (E->getNumInits() == 1) 7014 return StmtVisitorTy::Visit(E->getInit(0)); 7015 return Error(E); 7016 } 7017 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7018 return DerivedZeroInitialization(E); 7019 } 7020 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7021 return DerivedZeroInitialization(E); 7022 } 7023 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7024 return DerivedZeroInitialization(E); 7025 } 7026 7027 /// A member expression where the object is a prvalue is itself a prvalue. 7028 bool VisitMemberExpr(const MemberExpr *E) { 7029 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7030 "missing temporary materialization conversion"); 7031 assert(!E->isArrow() && "missing call to bound member function?"); 7032 7033 APValue Val; 7034 if (!Evaluate(Val, Info, E->getBase())) 7035 return false; 7036 7037 QualType BaseTy = E->getBase()->getType(); 7038 7039 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7040 if (!FD) return Error(E); 7041 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7042 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7043 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7044 7045 // Note: there is no lvalue base here. But this case should only ever 7046 // happen in C or in C++98, where we cannot be evaluating a constexpr 7047 // constructor, which is the only case the base matters. 7048 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7049 SubobjectDesignator Designator(BaseTy); 7050 Designator.addDeclUnchecked(FD); 7051 7052 APValue Result; 7053 return extractSubobject(Info, E, Obj, Designator, Result) && 7054 DerivedSuccess(Result, E); 7055 } 7056 7057 bool VisitCastExpr(const CastExpr *E) { 7058 switch (E->getCastKind()) { 7059 default: 7060 break; 7061 7062 case CK_AtomicToNonAtomic: { 7063 APValue AtomicVal; 7064 // This does not need to be done in place even for class/array types: 7065 // atomic-to-non-atomic conversion implies copying the object 7066 // representation. 7067 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7068 return false; 7069 return DerivedSuccess(AtomicVal, E); 7070 } 7071 7072 case CK_NoOp: 7073 case CK_UserDefinedConversion: 7074 return StmtVisitorTy::Visit(E->getSubExpr()); 7075 7076 case CK_LValueToRValue: { 7077 LValue LVal; 7078 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7079 return false; 7080 APValue RVal; 7081 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7082 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7083 LVal, RVal)) 7084 return false; 7085 return DerivedSuccess(RVal, E); 7086 } 7087 case CK_LValueToRValueBitCast: { 7088 APValue DestValue, SourceValue; 7089 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7090 return false; 7091 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7092 return false; 7093 return DerivedSuccess(DestValue, E); 7094 } 7095 } 7096 7097 return Error(E); 7098 } 7099 7100 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7101 return VisitUnaryPostIncDec(UO); 7102 } 7103 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7104 return VisitUnaryPostIncDec(UO); 7105 } 7106 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7107 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7108 return Error(UO); 7109 7110 LValue LVal; 7111 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7112 return false; 7113 APValue RVal; 7114 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7115 UO->isIncrementOp(), &RVal)) 7116 return false; 7117 return DerivedSuccess(RVal, UO); 7118 } 7119 7120 bool VisitStmtExpr(const StmtExpr *E) { 7121 // We will have checked the full-expressions inside the statement expression 7122 // when they were completed, and don't need to check them again now. 7123 if (Info.checkingForUndefinedBehavior()) 7124 return Error(E); 7125 7126 const CompoundStmt *CS = E->getSubStmt(); 7127 if (CS->body_empty()) 7128 return true; 7129 7130 BlockScopeRAII Scope(Info); 7131 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7132 BE = CS->body_end(); 7133 /**/; ++BI) { 7134 if (BI + 1 == BE) { 7135 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7136 if (!FinalExpr) { 7137 Info.FFDiag((*BI)->getBeginLoc(), 7138 diag::note_constexpr_stmt_expr_unsupported); 7139 return false; 7140 } 7141 return this->Visit(FinalExpr) && Scope.destroy(); 7142 } 7143 7144 APValue ReturnValue; 7145 StmtResult Result = { ReturnValue, nullptr }; 7146 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7147 if (ESR != ESR_Succeeded) { 7148 // FIXME: If the statement-expression terminated due to 'return', 7149 // 'break', or 'continue', it would be nice to propagate that to 7150 // the outer statement evaluation rather than bailing out. 7151 if (ESR != ESR_Failed) 7152 Info.FFDiag((*BI)->getBeginLoc(), 7153 diag::note_constexpr_stmt_expr_unsupported); 7154 return false; 7155 } 7156 } 7157 7158 llvm_unreachable("Return from function from the loop above."); 7159 } 7160 7161 /// Visit a value which is evaluated, but whose value is ignored. 7162 void VisitIgnoredValue(const Expr *E) { 7163 EvaluateIgnoredValue(Info, E); 7164 } 7165 7166 /// Potentially visit a MemberExpr's base expression. 7167 void VisitIgnoredBaseExpression(const Expr *E) { 7168 // While MSVC doesn't evaluate the base expression, it does diagnose the 7169 // presence of side-effecting behavior. 7170 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7171 return; 7172 VisitIgnoredValue(E); 7173 } 7174 }; 7175 7176 } // namespace 7177 7178 //===----------------------------------------------------------------------===// 7179 // Common base class for lvalue and temporary evaluation. 7180 //===----------------------------------------------------------------------===// 7181 namespace { 7182 template<class Derived> 7183 class LValueExprEvaluatorBase 7184 : public ExprEvaluatorBase<Derived> { 7185 protected: 7186 LValue &Result; 7187 bool InvalidBaseOK; 7188 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7189 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7190 7191 bool Success(APValue::LValueBase B) { 7192 Result.set(B); 7193 return true; 7194 } 7195 7196 bool evaluatePointer(const Expr *E, LValue &Result) { 7197 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7198 } 7199 7200 public: 7201 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7202 : ExprEvaluatorBaseTy(Info), Result(Result), 7203 InvalidBaseOK(InvalidBaseOK) {} 7204 7205 bool Success(const APValue &V, const Expr *E) { 7206 Result.setFrom(this->Info.Ctx, V); 7207 return true; 7208 } 7209 7210 bool VisitMemberExpr(const MemberExpr *E) { 7211 // Handle non-static data members. 7212 QualType BaseTy; 7213 bool EvalOK; 7214 if (E->isArrow()) { 7215 EvalOK = evaluatePointer(E->getBase(), Result); 7216 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7217 } else if (E->getBase()->isRValue()) { 7218 assert(E->getBase()->getType()->isRecordType()); 7219 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7220 BaseTy = E->getBase()->getType(); 7221 } else { 7222 EvalOK = this->Visit(E->getBase()); 7223 BaseTy = E->getBase()->getType(); 7224 } 7225 if (!EvalOK) { 7226 if (!InvalidBaseOK) 7227 return false; 7228 Result.setInvalid(E); 7229 return true; 7230 } 7231 7232 const ValueDecl *MD = E->getMemberDecl(); 7233 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7234 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7235 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7236 (void)BaseTy; 7237 if (!HandleLValueMember(this->Info, E, Result, FD)) 7238 return false; 7239 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7240 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7241 return false; 7242 } else 7243 return this->Error(E); 7244 7245 if (MD->getType()->isReferenceType()) { 7246 APValue RefValue; 7247 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7248 RefValue)) 7249 return false; 7250 return Success(RefValue, E); 7251 } 7252 return true; 7253 } 7254 7255 bool VisitBinaryOperator(const BinaryOperator *E) { 7256 switch (E->getOpcode()) { 7257 default: 7258 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7259 7260 case BO_PtrMemD: 7261 case BO_PtrMemI: 7262 return HandleMemberPointerAccess(this->Info, E, Result); 7263 } 7264 } 7265 7266 bool VisitCastExpr(const CastExpr *E) { 7267 switch (E->getCastKind()) { 7268 default: 7269 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7270 7271 case CK_DerivedToBase: 7272 case CK_UncheckedDerivedToBase: 7273 if (!this->Visit(E->getSubExpr())) 7274 return false; 7275 7276 // Now figure out the necessary offset to add to the base LV to get from 7277 // the derived class to the base class. 7278 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7279 Result); 7280 } 7281 } 7282 }; 7283 } 7284 7285 //===----------------------------------------------------------------------===// 7286 // LValue Evaluation 7287 // 7288 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7289 // function designators (in C), decl references to void objects (in C), and 7290 // temporaries (if building with -Wno-address-of-temporary). 7291 // 7292 // LValue evaluation produces values comprising a base expression of one of the 7293 // following types: 7294 // - Declarations 7295 // * VarDecl 7296 // * FunctionDecl 7297 // - Literals 7298 // * CompoundLiteralExpr in C (and in global scope in C++) 7299 // * StringLiteral 7300 // * PredefinedExpr 7301 // * ObjCStringLiteralExpr 7302 // * ObjCEncodeExpr 7303 // * AddrLabelExpr 7304 // * BlockExpr 7305 // * CallExpr for a MakeStringConstant builtin 7306 // - typeid(T) expressions, as TypeInfoLValues 7307 // - Locals and temporaries 7308 // * MaterializeTemporaryExpr 7309 // * Any Expr, with a CallIndex indicating the function in which the temporary 7310 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7311 // from the AST (FIXME). 7312 // * A MaterializeTemporaryExpr that has static storage duration, with no 7313 // CallIndex, for a lifetime-extended temporary. 7314 // plus an offset in bytes. 7315 //===----------------------------------------------------------------------===// 7316 namespace { 7317 class LValueExprEvaluator 7318 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7319 public: 7320 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7321 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7322 7323 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7324 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7325 7326 bool VisitDeclRefExpr(const DeclRefExpr *E); 7327 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7328 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7329 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7330 bool VisitMemberExpr(const MemberExpr *E); 7331 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7332 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7333 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7334 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7335 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7336 bool VisitUnaryDeref(const UnaryOperator *E); 7337 bool VisitUnaryReal(const UnaryOperator *E); 7338 bool VisitUnaryImag(const UnaryOperator *E); 7339 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7340 return VisitUnaryPreIncDec(UO); 7341 } 7342 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7343 return VisitUnaryPreIncDec(UO); 7344 } 7345 bool VisitBinAssign(const BinaryOperator *BO); 7346 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7347 7348 bool VisitCastExpr(const CastExpr *E) { 7349 switch (E->getCastKind()) { 7350 default: 7351 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7352 7353 case CK_LValueBitCast: 7354 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7355 if (!Visit(E->getSubExpr())) 7356 return false; 7357 Result.Designator.setInvalid(); 7358 return true; 7359 7360 case CK_BaseToDerived: 7361 if (!Visit(E->getSubExpr())) 7362 return false; 7363 return HandleBaseToDerivedCast(Info, E, Result); 7364 7365 case CK_Dynamic: 7366 if (!Visit(E->getSubExpr())) 7367 return false; 7368 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7369 } 7370 } 7371 }; 7372 } // end anonymous namespace 7373 7374 /// Evaluate an expression as an lvalue. This can be legitimately called on 7375 /// expressions which are not glvalues, in three cases: 7376 /// * function designators in C, and 7377 /// * "extern void" objects 7378 /// * @selector() expressions in Objective-C 7379 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7380 bool InvalidBaseOK) { 7381 assert(E->isGLValue() || E->getType()->isFunctionType() || 7382 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7383 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7384 } 7385 7386 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7387 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7388 return Success(FD); 7389 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7390 return VisitVarDecl(E, VD); 7391 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7392 return Visit(BD->getBinding()); 7393 return Error(E); 7394 } 7395 7396 7397 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7398 7399 // If we are within a lambda's call operator, check whether the 'VD' referred 7400 // to within 'E' actually represents a lambda-capture that maps to a 7401 // data-member/field within the closure object, and if so, evaluate to the 7402 // field or what the field refers to. 7403 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7404 isa<DeclRefExpr>(E) && 7405 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7406 // We don't always have a complete capture-map when checking or inferring if 7407 // the function call operator meets the requirements of a constexpr function 7408 // - but we don't need to evaluate the captures to determine constexprness 7409 // (dcl.constexpr C++17). 7410 if (Info.checkingPotentialConstantExpression()) 7411 return false; 7412 7413 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7414 // Start with 'Result' referring to the complete closure object... 7415 Result = *Info.CurrentCall->This; 7416 // ... then update it to refer to the field of the closure object 7417 // that represents the capture. 7418 if (!HandleLValueMember(Info, E, Result, FD)) 7419 return false; 7420 // And if the field is of reference type, update 'Result' to refer to what 7421 // the field refers to. 7422 if (FD->getType()->isReferenceType()) { 7423 APValue RVal; 7424 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7425 RVal)) 7426 return false; 7427 Result.setFrom(Info.Ctx, RVal); 7428 } 7429 return true; 7430 } 7431 } 7432 CallStackFrame *Frame = nullptr; 7433 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7434 // Only if a local variable was declared in the function currently being 7435 // evaluated, do we expect to be able to find its value in the current 7436 // frame. (Otherwise it was likely declared in an enclosing context and 7437 // could either have a valid evaluatable value (for e.g. a constexpr 7438 // variable) or be ill-formed (and trigger an appropriate evaluation 7439 // diagnostic)). 7440 if (Info.CurrentCall->Callee && 7441 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7442 Frame = Info.CurrentCall; 7443 } 7444 } 7445 7446 if (!VD->getType()->isReferenceType()) { 7447 if (Frame) { 7448 Result.set({VD, Frame->Index, 7449 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7450 return true; 7451 } 7452 return Success(VD); 7453 } 7454 7455 APValue *V; 7456 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7457 return false; 7458 if (!V->hasValue()) { 7459 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7460 // adjust the diagnostic to say that. 7461 if (!Info.checkingPotentialConstantExpression()) 7462 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7463 return false; 7464 } 7465 return Success(*V, E); 7466 } 7467 7468 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7469 const MaterializeTemporaryExpr *E) { 7470 // Walk through the expression to find the materialized temporary itself. 7471 SmallVector<const Expr *, 2> CommaLHSs; 7472 SmallVector<SubobjectAdjustment, 2> Adjustments; 7473 const Expr *Inner = 7474 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7475 7476 // If we passed any comma operators, evaluate their LHSs. 7477 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7478 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7479 return false; 7480 7481 // A materialized temporary with static storage duration can appear within the 7482 // result of a constant expression evaluation, so we need to preserve its 7483 // value for use outside this evaluation. 7484 APValue *Value; 7485 if (E->getStorageDuration() == SD_Static) { 7486 Value = E->getOrCreateValue(true); 7487 *Value = APValue(); 7488 Result.set(E); 7489 } else { 7490 Value = &Info.CurrentCall->createTemporary( 7491 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7492 } 7493 7494 QualType Type = Inner->getType(); 7495 7496 // Materialize the temporary itself. 7497 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7498 *Value = APValue(); 7499 return false; 7500 } 7501 7502 // Adjust our lvalue to refer to the desired subobject. 7503 for (unsigned I = Adjustments.size(); I != 0; /**/) { 7504 --I; 7505 switch (Adjustments[I].Kind) { 7506 case SubobjectAdjustment::DerivedToBaseAdjustment: 7507 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 7508 Type, Result)) 7509 return false; 7510 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 7511 break; 7512 7513 case SubobjectAdjustment::FieldAdjustment: 7514 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 7515 return false; 7516 Type = Adjustments[I].Field->getType(); 7517 break; 7518 7519 case SubobjectAdjustment::MemberPointerAdjustment: 7520 if (!HandleMemberPointerAccess(this->Info, Type, Result, 7521 Adjustments[I].Ptr.RHS)) 7522 return false; 7523 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 7524 break; 7525 } 7526 } 7527 7528 return true; 7529 } 7530 7531 bool 7532 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7533 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 7534 "lvalue compound literal in c++?"); 7535 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 7536 // only see this when folding in C, so there's no standard to follow here. 7537 return Success(E); 7538 } 7539 7540 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 7541 TypeInfoLValue TypeInfo; 7542 7543 if (!E->isPotentiallyEvaluated()) { 7544 if (E->isTypeOperand()) 7545 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 7546 else 7547 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 7548 } else { 7549 if (!Info.Ctx.getLangOpts().CPlusPlus2a) { 7550 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 7551 << E->getExprOperand()->getType() 7552 << E->getExprOperand()->getSourceRange(); 7553 } 7554 7555 if (!Visit(E->getExprOperand())) 7556 return false; 7557 7558 Optional<DynamicType> DynType = 7559 ComputeDynamicType(Info, E, Result, AK_TypeId); 7560 if (!DynType) 7561 return false; 7562 7563 TypeInfo = 7564 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 7565 } 7566 7567 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 7568 } 7569 7570 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 7571 return Success(E); 7572 } 7573 7574 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 7575 // Handle static data members. 7576 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 7577 VisitIgnoredBaseExpression(E->getBase()); 7578 return VisitVarDecl(E, VD); 7579 } 7580 7581 // Handle static member functions. 7582 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 7583 if (MD->isStatic()) { 7584 VisitIgnoredBaseExpression(E->getBase()); 7585 return Success(MD); 7586 } 7587 } 7588 7589 // Handle non-static data members. 7590 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 7591 } 7592 7593 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 7594 // FIXME: Deal with vectors as array subscript bases. 7595 if (E->getBase()->getType()->isVectorType()) 7596 return Error(E); 7597 7598 bool Success = true; 7599 if (!evaluatePointer(E->getBase(), Result)) { 7600 if (!Info.noteFailure()) 7601 return false; 7602 Success = false; 7603 } 7604 7605 APSInt Index; 7606 if (!EvaluateInteger(E->getIdx(), Index, Info)) 7607 return false; 7608 7609 return Success && 7610 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 7611 } 7612 7613 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 7614 return evaluatePointer(E->getSubExpr(), Result); 7615 } 7616 7617 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 7618 if (!Visit(E->getSubExpr())) 7619 return false; 7620 // __real is a no-op on scalar lvalues. 7621 if (E->getSubExpr()->getType()->isAnyComplexType()) 7622 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 7623 return true; 7624 } 7625 7626 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 7627 assert(E->getSubExpr()->getType()->isAnyComplexType() && 7628 "lvalue __imag__ on scalar?"); 7629 if (!Visit(E->getSubExpr())) 7630 return false; 7631 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 7632 return true; 7633 } 7634 7635 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 7636 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7637 return Error(UO); 7638 7639 if (!this->Visit(UO->getSubExpr())) 7640 return false; 7641 7642 return handleIncDec( 7643 this->Info, UO, Result, UO->getSubExpr()->getType(), 7644 UO->isIncrementOp(), nullptr); 7645 } 7646 7647 bool LValueExprEvaluator::VisitCompoundAssignOperator( 7648 const CompoundAssignOperator *CAO) { 7649 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7650 return Error(CAO); 7651 7652 APValue RHS; 7653 7654 // The overall lvalue result is the result of evaluating the LHS. 7655 if (!this->Visit(CAO->getLHS())) { 7656 if (Info.noteFailure()) 7657 Evaluate(RHS, this->Info, CAO->getRHS()); 7658 return false; 7659 } 7660 7661 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 7662 return false; 7663 7664 return handleCompoundAssignment( 7665 this->Info, CAO, 7666 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 7667 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 7668 } 7669 7670 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 7671 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7672 return Error(E); 7673 7674 APValue NewVal; 7675 7676 if (!this->Visit(E->getLHS())) { 7677 if (Info.noteFailure()) 7678 Evaluate(NewVal, this->Info, E->getRHS()); 7679 return false; 7680 } 7681 7682 if (!Evaluate(NewVal, this->Info, E->getRHS())) 7683 return false; 7684 7685 if (Info.getLangOpts().CPlusPlus2a && 7686 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 7687 return false; 7688 7689 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 7690 NewVal); 7691 } 7692 7693 //===----------------------------------------------------------------------===// 7694 // Pointer Evaluation 7695 //===----------------------------------------------------------------------===// 7696 7697 /// Attempts to compute the number of bytes available at the pointer 7698 /// returned by a function with the alloc_size attribute. Returns true if we 7699 /// were successful. Places an unsigned number into `Result`. 7700 /// 7701 /// This expects the given CallExpr to be a call to a function with an 7702 /// alloc_size attribute. 7703 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 7704 const CallExpr *Call, 7705 llvm::APInt &Result) { 7706 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 7707 7708 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 7709 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 7710 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 7711 if (Call->getNumArgs() <= SizeArgNo) 7712 return false; 7713 7714 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 7715 Expr::EvalResult ExprResult; 7716 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 7717 return false; 7718 Into = ExprResult.Val.getInt(); 7719 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 7720 return false; 7721 Into = Into.zextOrSelf(BitsInSizeT); 7722 return true; 7723 }; 7724 7725 APSInt SizeOfElem; 7726 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 7727 return false; 7728 7729 if (!AllocSize->getNumElemsParam().isValid()) { 7730 Result = std::move(SizeOfElem); 7731 return true; 7732 } 7733 7734 APSInt NumberOfElems; 7735 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 7736 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 7737 return false; 7738 7739 bool Overflow; 7740 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 7741 if (Overflow) 7742 return false; 7743 7744 Result = std::move(BytesAvailable); 7745 return true; 7746 } 7747 7748 /// Convenience function. LVal's base must be a call to an alloc_size 7749 /// function. 7750 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 7751 const LValue &LVal, 7752 llvm::APInt &Result) { 7753 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7754 "Can't get the size of a non alloc_size function"); 7755 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 7756 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 7757 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 7758 } 7759 7760 /// Attempts to evaluate the given LValueBase as the result of a call to 7761 /// a function with the alloc_size attribute. If it was possible to do so, this 7762 /// function will return true, make Result's Base point to said function call, 7763 /// and mark Result's Base as invalid. 7764 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 7765 LValue &Result) { 7766 if (Base.isNull()) 7767 return false; 7768 7769 // Because we do no form of static analysis, we only support const variables. 7770 // 7771 // Additionally, we can't support parameters, nor can we support static 7772 // variables (in the latter case, use-before-assign isn't UB; in the former, 7773 // we have no clue what they'll be assigned to). 7774 const auto *VD = 7775 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 7776 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 7777 return false; 7778 7779 const Expr *Init = VD->getAnyInitializer(); 7780 if (!Init) 7781 return false; 7782 7783 const Expr *E = Init->IgnoreParens(); 7784 if (!tryUnwrapAllocSizeCall(E)) 7785 return false; 7786 7787 // Store E instead of E unwrapped so that the type of the LValue's base is 7788 // what the user wanted. 7789 Result.setInvalid(E); 7790 7791 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 7792 Result.addUnsizedArray(Info, E, Pointee); 7793 return true; 7794 } 7795 7796 namespace { 7797 class PointerExprEvaluator 7798 : public ExprEvaluatorBase<PointerExprEvaluator> { 7799 LValue &Result; 7800 bool InvalidBaseOK; 7801 7802 bool Success(const Expr *E) { 7803 Result.set(E); 7804 return true; 7805 } 7806 7807 bool evaluateLValue(const Expr *E, LValue &Result) { 7808 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 7809 } 7810 7811 bool evaluatePointer(const Expr *E, LValue &Result) { 7812 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 7813 } 7814 7815 bool visitNonBuiltinCallExpr(const CallExpr *E); 7816 public: 7817 7818 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 7819 : ExprEvaluatorBaseTy(info), Result(Result), 7820 InvalidBaseOK(InvalidBaseOK) {} 7821 7822 bool Success(const APValue &V, const Expr *E) { 7823 Result.setFrom(Info.Ctx, V); 7824 return true; 7825 } 7826 bool ZeroInitialization(const Expr *E) { 7827 Result.setNull(Info.Ctx, E->getType()); 7828 return true; 7829 } 7830 7831 bool VisitBinaryOperator(const BinaryOperator *E); 7832 bool VisitCastExpr(const CastExpr* E); 7833 bool VisitUnaryAddrOf(const UnaryOperator *E); 7834 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 7835 { return Success(E); } 7836 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 7837 if (E->isExpressibleAsConstantInitializer()) 7838 return Success(E); 7839 if (Info.noteFailure()) 7840 EvaluateIgnoredValue(Info, E->getSubExpr()); 7841 return Error(E); 7842 } 7843 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 7844 { return Success(E); } 7845 bool VisitCallExpr(const CallExpr *E); 7846 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7847 bool VisitBlockExpr(const BlockExpr *E) { 7848 if (!E->getBlockDecl()->hasCaptures()) 7849 return Success(E); 7850 return Error(E); 7851 } 7852 bool VisitCXXThisExpr(const CXXThisExpr *E) { 7853 // Can't look at 'this' when checking a potential constant expression. 7854 if (Info.checkingPotentialConstantExpression()) 7855 return false; 7856 if (!Info.CurrentCall->This) { 7857 if (Info.getLangOpts().CPlusPlus11) 7858 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 7859 else 7860 Info.FFDiag(E); 7861 return false; 7862 } 7863 Result = *Info.CurrentCall->This; 7864 // If we are inside a lambda's call operator, the 'this' expression refers 7865 // to the enclosing '*this' object (either by value or reference) which is 7866 // either copied into the closure object's field that represents the '*this' 7867 // or refers to '*this'. 7868 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 7869 // Update 'Result' to refer to the data member/field of the closure object 7870 // that represents the '*this' capture. 7871 if (!HandleLValueMember(Info, E, Result, 7872 Info.CurrentCall->LambdaThisCaptureField)) 7873 return false; 7874 // If we captured '*this' by reference, replace the field with its referent. 7875 if (Info.CurrentCall->LambdaThisCaptureField->getType() 7876 ->isPointerType()) { 7877 APValue RVal; 7878 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 7879 RVal)) 7880 return false; 7881 7882 Result.setFrom(Info.Ctx, RVal); 7883 } 7884 } 7885 return true; 7886 } 7887 7888 bool VisitCXXNewExpr(const CXXNewExpr *E); 7889 7890 bool VisitSourceLocExpr(const SourceLocExpr *E) { 7891 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 7892 APValue LValResult = E->EvaluateInContext( 7893 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 7894 Result.setFrom(Info.Ctx, LValResult); 7895 return true; 7896 } 7897 7898 // FIXME: Missing: @protocol, @selector 7899 }; 7900 } // end anonymous namespace 7901 7902 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 7903 bool InvalidBaseOK) { 7904 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7905 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7906 } 7907 7908 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 7909 if (E->getOpcode() != BO_Add && 7910 E->getOpcode() != BO_Sub) 7911 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7912 7913 const Expr *PExp = E->getLHS(); 7914 const Expr *IExp = E->getRHS(); 7915 if (IExp->getType()->isPointerType()) 7916 std::swap(PExp, IExp); 7917 7918 bool EvalPtrOK = evaluatePointer(PExp, Result); 7919 if (!EvalPtrOK && !Info.noteFailure()) 7920 return false; 7921 7922 llvm::APSInt Offset; 7923 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 7924 return false; 7925 7926 if (E->getOpcode() == BO_Sub) 7927 negateAsSigned(Offset); 7928 7929 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 7930 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 7931 } 7932 7933 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 7934 return evaluateLValue(E->getSubExpr(), Result); 7935 } 7936 7937 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 7938 const Expr *SubExpr = E->getSubExpr(); 7939 7940 switch (E->getCastKind()) { 7941 default: 7942 break; 7943 case CK_BitCast: 7944 case CK_CPointerToObjCPointerCast: 7945 case CK_BlockPointerToObjCPointerCast: 7946 case CK_AnyPointerToBlockPointerCast: 7947 case CK_AddressSpaceConversion: 7948 if (!Visit(SubExpr)) 7949 return false; 7950 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 7951 // permitted in constant expressions in C++11. Bitcasts from cv void* are 7952 // also static_casts, but we disallow them as a resolution to DR1312. 7953 if (!E->getType()->isVoidPointerType()) { 7954 if (!Result.InvalidBase && !Result.Designator.Invalid && 7955 !Result.IsNullPtr && 7956 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 7957 E->getType()->getPointeeType()) && 7958 Info.getStdAllocatorCaller("allocate")) { 7959 // Inside a call to std::allocator::allocate and friends, we permit 7960 // casting from void* back to cv1 T* for a pointer that points to a 7961 // cv2 T. 7962 } else { 7963 Result.Designator.setInvalid(); 7964 if (SubExpr->getType()->isVoidPointerType()) 7965 CCEDiag(E, diag::note_constexpr_invalid_cast) 7966 << 3 << SubExpr->getType(); 7967 else 7968 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7969 } 7970 } 7971 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 7972 ZeroInitialization(E); 7973 return true; 7974 7975 case CK_DerivedToBase: 7976 case CK_UncheckedDerivedToBase: 7977 if (!evaluatePointer(E->getSubExpr(), Result)) 7978 return false; 7979 if (!Result.Base && Result.Offset.isZero()) 7980 return true; 7981 7982 // Now figure out the necessary offset to add to the base LV to get from 7983 // the derived class to the base class. 7984 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 7985 castAs<PointerType>()->getPointeeType(), 7986 Result); 7987 7988 case CK_BaseToDerived: 7989 if (!Visit(E->getSubExpr())) 7990 return false; 7991 if (!Result.Base && Result.Offset.isZero()) 7992 return true; 7993 return HandleBaseToDerivedCast(Info, E, Result); 7994 7995 case CK_Dynamic: 7996 if (!Visit(E->getSubExpr())) 7997 return false; 7998 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7999 8000 case CK_NullToPointer: 8001 VisitIgnoredValue(E->getSubExpr()); 8002 return ZeroInitialization(E); 8003 8004 case CK_IntegralToPointer: { 8005 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8006 8007 APValue Value; 8008 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8009 break; 8010 8011 if (Value.isInt()) { 8012 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8013 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8014 Result.Base = (Expr*)nullptr; 8015 Result.InvalidBase = false; 8016 Result.Offset = CharUnits::fromQuantity(N); 8017 Result.Designator.setInvalid(); 8018 Result.IsNullPtr = false; 8019 return true; 8020 } else { 8021 // Cast is of an lvalue, no need to change value. 8022 Result.setFrom(Info.Ctx, Value); 8023 return true; 8024 } 8025 } 8026 8027 case CK_ArrayToPointerDecay: { 8028 if (SubExpr->isGLValue()) { 8029 if (!evaluateLValue(SubExpr, Result)) 8030 return false; 8031 } else { 8032 APValue &Value = Info.CurrentCall->createTemporary( 8033 SubExpr, SubExpr->getType(), false, Result); 8034 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8035 return false; 8036 } 8037 // The result is a pointer to the first element of the array. 8038 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8039 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8040 Result.addArray(Info, E, CAT); 8041 else 8042 Result.addUnsizedArray(Info, E, AT->getElementType()); 8043 return true; 8044 } 8045 8046 case CK_FunctionToPointerDecay: 8047 return evaluateLValue(SubExpr, Result); 8048 8049 case CK_LValueToRValue: { 8050 LValue LVal; 8051 if (!evaluateLValue(E->getSubExpr(), LVal)) 8052 return false; 8053 8054 APValue RVal; 8055 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8056 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8057 LVal, RVal)) 8058 return InvalidBaseOK && 8059 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8060 return Success(RVal, E); 8061 } 8062 } 8063 8064 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8065 } 8066 8067 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8068 UnaryExprOrTypeTrait ExprKind) { 8069 // C++ [expr.alignof]p3: 8070 // When alignof is applied to a reference type, the result is the 8071 // alignment of the referenced type. 8072 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8073 T = Ref->getPointeeType(); 8074 8075 if (T.getQualifiers().hasUnaligned()) 8076 return CharUnits::One(); 8077 8078 const bool AlignOfReturnsPreferred = 8079 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8080 8081 // __alignof is defined to return the preferred alignment. 8082 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8083 // as well. 8084 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8085 return Info.Ctx.toCharUnitsFromBits( 8086 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8087 // alignof and _Alignof are defined to return the ABI alignment. 8088 else if (ExprKind == UETT_AlignOf) 8089 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8090 else 8091 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8092 } 8093 8094 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8095 UnaryExprOrTypeTrait ExprKind) { 8096 E = E->IgnoreParens(); 8097 8098 // The kinds of expressions that we have special-case logic here for 8099 // should be kept up to date with the special checks for those 8100 // expressions in Sema. 8101 8102 // alignof decl is always accepted, even if it doesn't make sense: we default 8103 // to 1 in those cases. 8104 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8105 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8106 /*RefAsPointee*/true); 8107 8108 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8109 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8110 /*RefAsPointee*/true); 8111 8112 return GetAlignOfType(Info, E->getType(), ExprKind); 8113 } 8114 8115 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8116 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8117 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8118 return true; 8119 8120 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8121 return false; 8122 8123 Result.setInvalid(E); 8124 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8125 Result.addUnsizedArray(Info, E, PointeeTy); 8126 return true; 8127 } 8128 8129 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8130 if (IsStringLiteralCall(E)) 8131 return Success(E); 8132 8133 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8134 return VisitBuiltinCallExpr(E, BuiltinOp); 8135 8136 return visitNonBuiltinCallExpr(E); 8137 } 8138 8139 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8140 unsigned BuiltinOp) { 8141 switch (BuiltinOp) { 8142 case Builtin::BI__builtin_addressof: 8143 return evaluateLValue(E->getArg(0), Result); 8144 case Builtin::BI__builtin_assume_aligned: { 8145 // We need to be very careful here because: if the pointer does not have the 8146 // asserted alignment, then the behavior is undefined, and undefined 8147 // behavior is non-constant. 8148 if (!evaluatePointer(E->getArg(0), Result)) 8149 return false; 8150 8151 LValue OffsetResult(Result); 8152 APSInt Alignment; 8153 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 8154 return false; 8155 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8156 8157 if (E->getNumArgs() > 2) { 8158 APSInt Offset; 8159 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8160 return false; 8161 8162 int64_t AdditionalOffset = -Offset.getZExtValue(); 8163 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8164 } 8165 8166 // If there is a base object, then it must have the correct alignment. 8167 if (OffsetResult.Base) { 8168 CharUnits BaseAlignment; 8169 if (const ValueDecl *VD = 8170 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 8171 BaseAlignment = Info.Ctx.getDeclAlign(VD); 8172 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) { 8173 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf); 8174 } else { 8175 BaseAlignment = GetAlignOfType( 8176 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf); 8177 } 8178 8179 if (BaseAlignment < Align) { 8180 Result.Designator.setInvalid(); 8181 // FIXME: Add support to Diagnostic for long / long long. 8182 CCEDiag(E->getArg(0), 8183 diag::note_constexpr_baa_insufficient_alignment) << 0 8184 << (unsigned)BaseAlignment.getQuantity() 8185 << (unsigned)Align.getQuantity(); 8186 return false; 8187 } 8188 } 8189 8190 // The offset must also have the correct alignment. 8191 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8192 Result.Designator.setInvalid(); 8193 8194 (OffsetResult.Base 8195 ? CCEDiag(E->getArg(0), 8196 diag::note_constexpr_baa_insufficient_alignment) << 1 8197 : CCEDiag(E->getArg(0), 8198 diag::note_constexpr_baa_value_insufficient_alignment)) 8199 << (int)OffsetResult.Offset.getQuantity() 8200 << (unsigned)Align.getQuantity(); 8201 return false; 8202 } 8203 8204 return true; 8205 } 8206 case Builtin::BI__builtin_operator_new: 8207 return HandleOperatorNewCall(Info, E, Result); 8208 case Builtin::BI__builtin_launder: 8209 return evaluatePointer(E->getArg(0), Result); 8210 case Builtin::BIstrchr: 8211 case Builtin::BIwcschr: 8212 case Builtin::BImemchr: 8213 case Builtin::BIwmemchr: 8214 if (Info.getLangOpts().CPlusPlus11) 8215 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8216 << /*isConstexpr*/0 << /*isConstructor*/0 8217 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8218 else 8219 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8220 LLVM_FALLTHROUGH; 8221 case Builtin::BI__builtin_strchr: 8222 case Builtin::BI__builtin_wcschr: 8223 case Builtin::BI__builtin_memchr: 8224 case Builtin::BI__builtin_char_memchr: 8225 case Builtin::BI__builtin_wmemchr: { 8226 if (!Visit(E->getArg(0))) 8227 return false; 8228 APSInt Desired; 8229 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8230 return false; 8231 uint64_t MaxLength = uint64_t(-1); 8232 if (BuiltinOp != Builtin::BIstrchr && 8233 BuiltinOp != Builtin::BIwcschr && 8234 BuiltinOp != Builtin::BI__builtin_strchr && 8235 BuiltinOp != Builtin::BI__builtin_wcschr) { 8236 APSInt N; 8237 if (!EvaluateInteger(E->getArg(2), N, Info)) 8238 return false; 8239 MaxLength = N.getExtValue(); 8240 } 8241 // We cannot find the value if there are no candidates to match against. 8242 if (MaxLength == 0u) 8243 return ZeroInitialization(E); 8244 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8245 Result.Designator.Invalid) 8246 return false; 8247 QualType CharTy = Result.Designator.getType(Info.Ctx); 8248 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 8249 BuiltinOp == Builtin::BI__builtin_memchr; 8250 assert(IsRawByte || 8251 Info.Ctx.hasSameUnqualifiedType( 8252 CharTy, E->getArg(0)->getType()->getPointeeType())); 8253 // Pointers to const void may point to objects of incomplete type. 8254 if (IsRawByte && CharTy->isIncompleteType()) { 8255 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 8256 return false; 8257 } 8258 // Give up on byte-oriented matching against multibyte elements. 8259 // FIXME: We can compare the bytes in the correct order. 8260 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One()) 8261 return false; 8262 // Figure out what value we're actually looking for (after converting to 8263 // the corresponding unsigned type if necessary). 8264 uint64_t DesiredVal; 8265 bool StopAtNull = false; 8266 switch (BuiltinOp) { 8267 case Builtin::BIstrchr: 8268 case Builtin::BI__builtin_strchr: 8269 // strchr compares directly to the passed integer, and therefore 8270 // always fails if given an int that is not a char. 8271 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8272 E->getArg(1)->getType(), 8273 Desired), 8274 Desired)) 8275 return ZeroInitialization(E); 8276 StopAtNull = true; 8277 LLVM_FALLTHROUGH; 8278 case Builtin::BImemchr: 8279 case Builtin::BI__builtin_memchr: 8280 case Builtin::BI__builtin_char_memchr: 8281 // memchr compares by converting both sides to unsigned char. That's also 8282 // correct for strchr if we get this far (to cope with plain char being 8283 // unsigned in the strchr case). 8284 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8285 break; 8286 8287 case Builtin::BIwcschr: 8288 case Builtin::BI__builtin_wcschr: 8289 StopAtNull = true; 8290 LLVM_FALLTHROUGH; 8291 case Builtin::BIwmemchr: 8292 case Builtin::BI__builtin_wmemchr: 8293 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8294 DesiredVal = Desired.getZExtValue(); 8295 break; 8296 } 8297 8298 for (; MaxLength; --MaxLength) { 8299 APValue Char; 8300 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8301 !Char.isInt()) 8302 return false; 8303 if (Char.getInt().getZExtValue() == DesiredVal) 8304 return true; 8305 if (StopAtNull && !Char.getInt()) 8306 break; 8307 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8308 return false; 8309 } 8310 // Not found: return nullptr. 8311 return ZeroInitialization(E); 8312 } 8313 8314 case Builtin::BImemcpy: 8315 case Builtin::BImemmove: 8316 case Builtin::BIwmemcpy: 8317 case Builtin::BIwmemmove: 8318 if (Info.getLangOpts().CPlusPlus11) 8319 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8320 << /*isConstexpr*/0 << /*isConstructor*/0 8321 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8322 else 8323 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8324 LLVM_FALLTHROUGH; 8325 case Builtin::BI__builtin_memcpy: 8326 case Builtin::BI__builtin_memmove: 8327 case Builtin::BI__builtin_wmemcpy: 8328 case Builtin::BI__builtin_wmemmove: { 8329 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8330 BuiltinOp == Builtin::BIwmemmove || 8331 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8332 BuiltinOp == Builtin::BI__builtin_wmemmove; 8333 bool Move = BuiltinOp == Builtin::BImemmove || 8334 BuiltinOp == Builtin::BIwmemmove || 8335 BuiltinOp == Builtin::BI__builtin_memmove || 8336 BuiltinOp == Builtin::BI__builtin_wmemmove; 8337 8338 // The result of mem* is the first argument. 8339 if (!Visit(E->getArg(0))) 8340 return false; 8341 LValue Dest = Result; 8342 8343 LValue Src; 8344 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8345 return false; 8346 8347 APSInt N; 8348 if (!EvaluateInteger(E->getArg(2), N, Info)) 8349 return false; 8350 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8351 8352 // If the size is zero, we treat this as always being a valid no-op. 8353 // (Even if one of the src and dest pointers is null.) 8354 if (!N) 8355 return true; 8356 8357 // Otherwise, if either of the operands is null, we can't proceed. Don't 8358 // try to determine the type of the copied objects, because there aren't 8359 // any. 8360 if (!Src.Base || !Dest.Base) { 8361 APValue Val; 8362 (!Src.Base ? Src : Dest).moveInto(Val); 8363 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8364 << Move << WChar << !!Src.Base 8365 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8366 return false; 8367 } 8368 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8369 return false; 8370 8371 // We require that Src and Dest are both pointers to arrays of 8372 // trivially-copyable type. (For the wide version, the designator will be 8373 // invalid if the designated object is not a wchar_t.) 8374 QualType T = Dest.Designator.getType(Info.Ctx); 8375 QualType SrcT = Src.Designator.getType(Info.Ctx); 8376 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8377 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8378 return false; 8379 } 8380 if (T->isIncompleteType()) { 8381 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8382 return false; 8383 } 8384 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8385 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8386 return false; 8387 } 8388 8389 // Figure out how many T's we're copying. 8390 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8391 if (!WChar) { 8392 uint64_t Remainder; 8393 llvm::APInt OrigN = N; 8394 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8395 if (Remainder) { 8396 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8397 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8398 << (unsigned)TSize; 8399 return false; 8400 } 8401 } 8402 8403 // Check that the copying will remain within the arrays, just so that we 8404 // can give a more meaningful diagnostic. This implicitly also checks that 8405 // N fits into 64 bits. 8406 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8407 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8408 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8409 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8410 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8411 << N.toString(10, /*Signed*/false); 8412 return false; 8413 } 8414 uint64_t NElems = N.getZExtValue(); 8415 uint64_t NBytes = NElems * TSize; 8416 8417 // Check for overlap. 8418 int Direction = 1; 8419 if (HasSameBase(Src, Dest)) { 8420 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 8421 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 8422 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 8423 // Dest is inside the source region. 8424 if (!Move) { 8425 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8426 return false; 8427 } 8428 // For memmove and friends, copy backwards. 8429 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 8430 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 8431 return false; 8432 Direction = -1; 8433 } else if (!Move && SrcOffset >= DestOffset && 8434 SrcOffset - DestOffset < NBytes) { 8435 // Src is inside the destination region for memcpy: invalid. 8436 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8437 return false; 8438 } 8439 } 8440 8441 while (true) { 8442 APValue Val; 8443 // FIXME: Set WantObjectRepresentation to true if we're copying a 8444 // char-like type? 8445 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 8446 !handleAssignment(Info, E, Dest, T, Val)) 8447 return false; 8448 // Do not iterate past the last element; if we're copying backwards, that 8449 // might take us off the start of the array. 8450 if (--NElems == 0) 8451 return true; 8452 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 8453 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 8454 return false; 8455 } 8456 } 8457 8458 default: 8459 break; 8460 } 8461 8462 return visitNonBuiltinCallExpr(E); 8463 } 8464 8465 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 8466 APValue &Result, const InitListExpr *ILE, 8467 QualType AllocType); 8468 8469 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 8470 if (!Info.getLangOpts().CPlusPlus2a) 8471 Info.CCEDiag(E, diag::note_constexpr_new); 8472 8473 // We cannot speculatively evaluate a delete expression. 8474 if (Info.SpeculativeEvaluationDepth) 8475 return false; 8476 8477 FunctionDecl *OperatorNew = E->getOperatorNew(); 8478 8479 bool IsNothrow = false; 8480 bool IsPlacement = false; 8481 if (OperatorNew->isReservedGlobalPlacementOperator() && 8482 Info.CurrentCall->isStdFunction() && !E->isArray()) { 8483 // FIXME Support array placement new. 8484 assert(E->getNumPlacementArgs() == 1); 8485 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 8486 return false; 8487 if (Result.Designator.Invalid) 8488 return false; 8489 IsPlacement = true; 8490 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 8491 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 8492 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 8493 return false; 8494 } else if (E->getNumPlacementArgs()) { 8495 // The only new-placement list we support is of the form (std::nothrow). 8496 // 8497 // FIXME: There is no restriction on this, but it's not clear that any 8498 // other form makes any sense. We get here for cases such as: 8499 // 8500 // new (std::align_val_t{N}) X(int) 8501 // 8502 // (which should presumably be valid only if N is a multiple of 8503 // alignof(int), and in any case can't be deallocated unless N is 8504 // alignof(X) and X has new-extended alignment). 8505 if (E->getNumPlacementArgs() != 1 || 8506 !E->getPlacementArg(0)->getType()->isNothrowT()) 8507 return Error(E, diag::note_constexpr_new_placement); 8508 8509 LValue Nothrow; 8510 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 8511 return false; 8512 IsNothrow = true; 8513 } 8514 8515 const Expr *Init = E->getInitializer(); 8516 const InitListExpr *ResizedArrayILE = nullptr; 8517 8518 QualType AllocType = E->getAllocatedType(); 8519 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 8520 const Expr *Stripped = *ArraySize; 8521 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 8522 Stripped = ICE->getSubExpr()) 8523 if (ICE->getCastKind() != CK_NoOp && 8524 ICE->getCastKind() != CK_IntegralCast) 8525 break; 8526 8527 llvm::APSInt ArrayBound; 8528 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 8529 return false; 8530 8531 // C++ [expr.new]p9: 8532 // The expression is erroneous if: 8533 // -- [...] its value before converting to size_t [or] applying the 8534 // second standard conversion sequence is less than zero 8535 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 8536 if (IsNothrow) 8537 return ZeroInitialization(E); 8538 8539 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 8540 << ArrayBound << (*ArraySize)->getSourceRange(); 8541 return false; 8542 } 8543 8544 // -- its value is such that the size of the allocated object would 8545 // exceed the implementation-defined limit 8546 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 8547 ArrayBound) > 8548 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 8549 if (IsNothrow) 8550 return ZeroInitialization(E); 8551 8552 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 8553 << ArrayBound << (*ArraySize)->getSourceRange(); 8554 return false; 8555 } 8556 8557 // -- the new-initializer is a braced-init-list and the number of 8558 // array elements for which initializers are provided [...] 8559 // exceeds the number of elements to initialize 8560 if (Init) { 8561 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 8562 assert(CAT && "unexpected type for array initializer"); 8563 8564 unsigned Bits = 8565 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 8566 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 8567 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 8568 if (InitBound.ugt(AllocBound)) { 8569 if (IsNothrow) 8570 return ZeroInitialization(E); 8571 8572 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 8573 << AllocBound.toString(10, /*Signed=*/false) 8574 << InitBound.toString(10, /*Signed=*/false) 8575 << (*ArraySize)->getSourceRange(); 8576 return false; 8577 } 8578 8579 // If the sizes differ, we must have an initializer list, and we need 8580 // special handling for this case when we initialize. 8581 if (InitBound != AllocBound) 8582 ResizedArrayILE = cast<InitListExpr>(Init); 8583 } 8584 8585 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 8586 ArrayType::Normal, 0); 8587 } else { 8588 assert(!AllocType->isArrayType() && 8589 "array allocation with non-array new"); 8590 } 8591 8592 APValue *Val; 8593 if (IsPlacement) { 8594 AccessKinds AK = AK_Construct; 8595 struct FindObjectHandler { 8596 EvalInfo &Info; 8597 const Expr *E; 8598 QualType AllocType; 8599 const AccessKinds AccessKind; 8600 APValue *Value; 8601 8602 typedef bool result_type; 8603 bool failed() { return false; } 8604 bool found(APValue &Subobj, QualType SubobjType) { 8605 // FIXME: Reject the cases where [basic.life]p8 would not permit the 8606 // old name of the object to be used to name the new object. 8607 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 8608 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 8609 SubobjType << AllocType; 8610 return false; 8611 } 8612 Value = &Subobj; 8613 return true; 8614 } 8615 bool found(APSInt &Value, QualType SubobjType) { 8616 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 8617 return false; 8618 } 8619 bool found(APFloat &Value, QualType SubobjType) { 8620 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 8621 return false; 8622 } 8623 } Handler = {Info, E, AllocType, AK, nullptr}; 8624 8625 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 8626 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 8627 return false; 8628 8629 Val = Handler.Value; 8630 8631 // [basic.life]p1: 8632 // The lifetime of an object o of type T ends when [...] the storage 8633 // which the object occupies is [...] reused by an object that is not 8634 // nested within o (6.6.2). 8635 *Val = APValue(); 8636 } else { 8637 // Perform the allocation and obtain a pointer to the resulting object. 8638 Val = Info.createHeapAlloc(E, AllocType, Result); 8639 if (!Val) 8640 return false; 8641 } 8642 8643 if (ResizedArrayILE) { 8644 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 8645 AllocType)) 8646 return false; 8647 } else if (Init) { 8648 if (!EvaluateInPlace(*Val, Info, Result, Init)) 8649 return false; 8650 } else { 8651 *Val = getDefaultInitValue(AllocType); 8652 } 8653 8654 // Array new returns a pointer to the first element, not a pointer to the 8655 // array. 8656 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 8657 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 8658 8659 return true; 8660 } 8661 //===----------------------------------------------------------------------===// 8662 // Member Pointer Evaluation 8663 //===----------------------------------------------------------------------===// 8664 8665 namespace { 8666 class MemberPointerExprEvaluator 8667 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 8668 MemberPtr &Result; 8669 8670 bool Success(const ValueDecl *D) { 8671 Result = MemberPtr(D); 8672 return true; 8673 } 8674 public: 8675 8676 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 8677 : ExprEvaluatorBaseTy(Info), Result(Result) {} 8678 8679 bool Success(const APValue &V, const Expr *E) { 8680 Result.setFrom(V); 8681 return true; 8682 } 8683 bool ZeroInitialization(const Expr *E) { 8684 return Success((const ValueDecl*)nullptr); 8685 } 8686 8687 bool VisitCastExpr(const CastExpr *E); 8688 bool VisitUnaryAddrOf(const UnaryOperator *E); 8689 }; 8690 } // end anonymous namespace 8691 8692 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 8693 EvalInfo &Info) { 8694 assert(E->isRValue() && E->getType()->isMemberPointerType()); 8695 return MemberPointerExprEvaluator(Info, Result).Visit(E); 8696 } 8697 8698 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8699 switch (E->getCastKind()) { 8700 default: 8701 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8702 8703 case CK_NullToMemberPointer: 8704 VisitIgnoredValue(E->getSubExpr()); 8705 return ZeroInitialization(E); 8706 8707 case CK_BaseToDerivedMemberPointer: { 8708 if (!Visit(E->getSubExpr())) 8709 return false; 8710 if (E->path_empty()) 8711 return true; 8712 // Base-to-derived member pointer casts store the path in derived-to-base 8713 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 8714 // the wrong end of the derived->base arc, so stagger the path by one class. 8715 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 8716 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 8717 PathI != PathE; ++PathI) { 8718 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 8719 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 8720 if (!Result.castToDerived(Derived)) 8721 return Error(E); 8722 } 8723 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 8724 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 8725 return Error(E); 8726 return true; 8727 } 8728 8729 case CK_DerivedToBaseMemberPointer: 8730 if (!Visit(E->getSubExpr())) 8731 return false; 8732 for (CastExpr::path_const_iterator PathI = E->path_begin(), 8733 PathE = E->path_end(); PathI != PathE; ++PathI) { 8734 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 8735 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 8736 if (!Result.castToBase(Base)) 8737 return Error(E); 8738 } 8739 return true; 8740 } 8741 } 8742 8743 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8744 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 8745 // member can be formed. 8746 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 8747 } 8748 8749 //===----------------------------------------------------------------------===// 8750 // Record Evaluation 8751 //===----------------------------------------------------------------------===// 8752 8753 namespace { 8754 class RecordExprEvaluator 8755 : public ExprEvaluatorBase<RecordExprEvaluator> { 8756 const LValue &This; 8757 APValue &Result; 8758 public: 8759 8760 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 8761 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 8762 8763 bool Success(const APValue &V, const Expr *E) { 8764 Result = V; 8765 return true; 8766 } 8767 bool ZeroInitialization(const Expr *E) { 8768 return ZeroInitialization(E, E->getType()); 8769 } 8770 bool ZeroInitialization(const Expr *E, QualType T); 8771 8772 bool VisitCallExpr(const CallExpr *E) { 8773 return handleCallExpr(E, Result, &This); 8774 } 8775 bool VisitCastExpr(const CastExpr *E); 8776 bool VisitInitListExpr(const InitListExpr *E); 8777 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 8778 return VisitCXXConstructExpr(E, E->getType()); 8779 } 8780 bool VisitLambdaExpr(const LambdaExpr *E); 8781 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 8782 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 8783 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 8784 bool VisitBinCmp(const BinaryOperator *E); 8785 }; 8786 } 8787 8788 /// Perform zero-initialization on an object of non-union class type. 8789 /// C++11 [dcl.init]p5: 8790 /// To zero-initialize an object or reference of type T means: 8791 /// [...] 8792 /// -- if T is a (possibly cv-qualified) non-union class type, 8793 /// each non-static data member and each base-class subobject is 8794 /// zero-initialized 8795 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 8796 const RecordDecl *RD, 8797 const LValue &This, APValue &Result) { 8798 assert(!RD->isUnion() && "Expected non-union class type"); 8799 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 8800 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 8801 std::distance(RD->field_begin(), RD->field_end())); 8802 8803 if (RD->isInvalidDecl()) return false; 8804 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 8805 8806 if (CD) { 8807 unsigned Index = 0; 8808 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 8809 End = CD->bases_end(); I != End; ++I, ++Index) { 8810 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 8811 LValue Subobject = This; 8812 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 8813 return false; 8814 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 8815 Result.getStructBase(Index))) 8816 return false; 8817 } 8818 } 8819 8820 for (const auto *I : RD->fields()) { 8821 // -- if T is a reference type, no initialization is performed. 8822 if (I->getType()->isReferenceType()) 8823 continue; 8824 8825 LValue Subobject = This; 8826 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 8827 return false; 8828 8829 ImplicitValueInitExpr VIE(I->getType()); 8830 if (!EvaluateInPlace( 8831 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 8832 return false; 8833 } 8834 8835 return true; 8836 } 8837 8838 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 8839 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 8840 if (RD->isInvalidDecl()) return false; 8841 if (RD->isUnion()) { 8842 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 8843 // object's first non-static named data member is zero-initialized 8844 RecordDecl::field_iterator I = RD->field_begin(); 8845 if (I == RD->field_end()) { 8846 Result = APValue((const FieldDecl*)nullptr); 8847 return true; 8848 } 8849 8850 LValue Subobject = This; 8851 if (!HandleLValueMember(Info, E, Subobject, *I)) 8852 return false; 8853 Result = APValue(*I); 8854 ImplicitValueInitExpr VIE(I->getType()); 8855 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 8856 } 8857 8858 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 8859 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 8860 return false; 8861 } 8862 8863 return HandleClassZeroInitialization(Info, E, RD, This, Result); 8864 } 8865 8866 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 8867 switch (E->getCastKind()) { 8868 default: 8869 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8870 8871 case CK_ConstructorConversion: 8872 return Visit(E->getSubExpr()); 8873 8874 case CK_DerivedToBase: 8875 case CK_UncheckedDerivedToBase: { 8876 APValue DerivedObject; 8877 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 8878 return false; 8879 if (!DerivedObject.isStruct()) 8880 return Error(E->getSubExpr()); 8881 8882 // Derived-to-base rvalue conversion: just slice off the derived part. 8883 APValue *Value = &DerivedObject; 8884 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 8885 for (CastExpr::path_const_iterator PathI = E->path_begin(), 8886 PathE = E->path_end(); PathI != PathE; ++PathI) { 8887 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 8888 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 8889 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 8890 RD = Base; 8891 } 8892 Result = *Value; 8893 return true; 8894 } 8895 } 8896 } 8897 8898 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 8899 if (E->isTransparent()) 8900 return Visit(E->getInit(0)); 8901 8902 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 8903 if (RD->isInvalidDecl()) return false; 8904 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 8905 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 8906 8907 EvalInfo::EvaluatingConstructorRAII EvalObj( 8908 Info, 8909 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 8910 CXXRD && CXXRD->getNumBases()); 8911 8912 if (RD->isUnion()) { 8913 const FieldDecl *Field = E->getInitializedFieldInUnion(); 8914 Result = APValue(Field); 8915 if (!Field) 8916 return true; 8917 8918 // If the initializer list for a union does not contain any elements, the 8919 // first element of the union is value-initialized. 8920 // FIXME: The element should be initialized from an initializer list. 8921 // Is this difference ever observable for initializer lists which 8922 // we don't build? 8923 ImplicitValueInitExpr VIE(Field->getType()); 8924 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 8925 8926 LValue Subobject = This; 8927 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 8928 return false; 8929 8930 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 8931 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 8932 isa<CXXDefaultInitExpr>(InitExpr)); 8933 8934 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 8935 } 8936 8937 if (!Result.hasValue()) 8938 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 8939 std::distance(RD->field_begin(), RD->field_end())); 8940 unsigned ElementNo = 0; 8941 bool Success = true; 8942 8943 // Initialize base classes. 8944 if (CXXRD && CXXRD->getNumBases()) { 8945 for (const auto &Base : CXXRD->bases()) { 8946 assert(ElementNo < E->getNumInits() && "missing init for base class"); 8947 const Expr *Init = E->getInit(ElementNo); 8948 8949 LValue Subobject = This; 8950 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 8951 return false; 8952 8953 APValue &FieldVal = Result.getStructBase(ElementNo); 8954 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 8955 if (!Info.noteFailure()) 8956 return false; 8957 Success = false; 8958 } 8959 ++ElementNo; 8960 } 8961 8962 EvalObj.finishedConstructingBases(); 8963 } 8964 8965 // Initialize members. 8966 for (const auto *Field : RD->fields()) { 8967 // Anonymous bit-fields are not considered members of the class for 8968 // purposes of aggregate initialization. 8969 if (Field->isUnnamedBitfield()) 8970 continue; 8971 8972 LValue Subobject = This; 8973 8974 bool HaveInit = ElementNo < E->getNumInits(); 8975 8976 // FIXME: Diagnostics here should point to the end of the initializer 8977 // list, not the start. 8978 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 8979 Subobject, Field, &Layout)) 8980 return false; 8981 8982 // Perform an implicit value-initialization for members beyond the end of 8983 // the initializer list. 8984 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 8985 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 8986 8987 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 8988 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 8989 isa<CXXDefaultInitExpr>(Init)); 8990 8991 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 8992 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 8993 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 8994 FieldVal, Field))) { 8995 if (!Info.noteFailure()) 8996 return false; 8997 Success = false; 8998 } 8999 } 9000 9001 return Success; 9002 } 9003 9004 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9005 QualType T) { 9006 // Note that E's type is not necessarily the type of our class here; we might 9007 // be initializing an array element instead. 9008 const CXXConstructorDecl *FD = E->getConstructor(); 9009 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9010 9011 bool ZeroInit = E->requiresZeroInitialization(); 9012 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9013 // If we've already performed zero-initialization, we're already done. 9014 if (Result.hasValue()) 9015 return true; 9016 9017 if (ZeroInit) 9018 return ZeroInitialization(E, T); 9019 9020 Result = getDefaultInitValue(T); 9021 return true; 9022 } 9023 9024 const FunctionDecl *Definition = nullptr; 9025 auto Body = FD->getBody(Definition); 9026 9027 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9028 return false; 9029 9030 // Avoid materializing a temporary for an elidable copy/move constructor. 9031 if (E->isElidable() && !ZeroInit) 9032 if (const MaterializeTemporaryExpr *ME 9033 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9034 return Visit(ME->getSubExpr()); 9035 9036 if (ZeroInit && !ZeroInitialization(E, T)) 9037 return false; 9038 9039 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9040 return HandleConstructorCall(E, This, Args, 9041 cast<CXXConstructorDecl>(Definition), Info, 9042 Result); 9043 } 9044 9045 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9046 const CXXInheritedCtorInitExpr *E) { 9047 if (!Info.CurrentCall) { 9048 assert(Info.checkingPotentialConstantExpression()); 9049 return false; 9050 } 9051 9052 const CXXConstructorDecl *FD = E->getConstructor(); 9053 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9054 return false; 9055 9056 const FunctionDecl *Definition = nullptr; 9057 auto Body = FD->getBody(Definition); 9058 9059 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9060 return false; 9061 9062 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9063 cast<CXXConstructorDecl>(Definition), Info, 9064 Result); 9065 } 9066 9067 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9068 const CXXStdInitializerListExpr *E) { 9069 const ConstantArrayType *ArrayType = 9070 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9071 9072 LValue Array; 9073 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9074 return false; 9075 9076 // Get a pointer to the first element of the array. 9077 Array.addArray(Info, E, ArrayType); 9078 9079 // FIXME: Perform the checks on the field types in SemaInit. 9080 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9081 RecordDecl::field_iterator Field = Record->field_begin(); 9082 if (Field == Record->field_end()) 9083 return Error(E); 9084 9085 // Start pointer. 9086 if (!Field->getType()->isPointerType() || 9087 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9088 ArrayType->getElementType())) 9089 return Error(E); 9090 9091 // FIXME: What if the initializer_list type has base classes, etc? 9092 Result = APValue(APValue::UninitStruct(), 0, 2); 9093 Array.moveInto(Result.getStructField(0)); 9094 9095 if (++Field == Record->field_end()) 9096 return Error(E); 9097 9098 if (Field->getType()->isPointerType() && 9099 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9100 ArrayType->getElementType())) { 9101 // End pointer. 9102 if (!HandleLValueArrayAdjustment(Info, E, Array, 9103 ArrayType->getElementType(), 9104 ArrayType->getSize().getZExtValue())) 9105 return false; 9106 Array.moveInto(Result.getStructField(1)); 9107 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9108 // Length. 9109 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9110 else 9111 return Error(E); 9112 9113 if (++Field != Record->field_end()) 9114 return Error(E); 9115 9116 return true; 9117 } 9118 9119 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9120 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9121 if (ClosureClass->isInvalidDecl()) 9122 return false; 9123 9124 const size_t NumFields = 9125 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9126 9127 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9128 E->capture_init_end()) && 9129 "The number of lambda capture initializers should equal the number of " 9130 "fields within the closure type"); 9131 9132 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9133 // Iterate through all the lambda's closure object's fields and initialize 9134 // them. 9135 auto *CaptureInitIt = E->capture_init_begin(); 9136 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9137 bool Success = true; 9138 for (const auto *Field : ClosureClass->fields()) { 9139 assert(CaptureInitIt != E->capture_init_end()); 9140 // Get the initializer for this field 9141 Expr *const CurFieldInit = *CaptureInitIt++; 9142 9143 // If there is no initializer, either this is a VLA or an error has 9144 // occurred. 9145 if (!CurFieldInit) 9146 return Error(E); 9147 9148 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9149 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9150 if (!Info.keepEvaluatingAfterFailure()) 9151 return false; 9152 Success = false; 9153 } 9154 ++CaptureIt; 9155 } 9156 return Success; 9157 } 9158 9159 static bool EvaluateRecord(const Expr *E, const LValue &This, 9160 APValue &Result, EvalInfo &Info) { 9161 assert(E->isRValue() && E->getType()->isRecordType() && 9162 "can't evaluate expression as a record rvalue"); 9163 return RecordExprEvaluator(Info, This, Result).Visit(E); 9164 } 9165 9166 //===----------------------------------------------------------------------===// 9167 // Temporary Evaluation 9168 // 9169 // Temporaries are represented in the AST as rvalues, but generally behave like 9170 // lvalues. The full-object of which the temporary is a subobject is implicitly 9171 // materialized so that a reference can bind to it. 9172 //===----------------------------------------------------------------------===// 9173 namespace { 9174 class TemporaryExprEvaluator 9175 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9176 public: 9177 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9178 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9179 9180 /// Visit an expression which constructs the value of this temporary. 9181 bool VisitConstructExpr(const Expr *E) { 9182 APValue &Value = 9183 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 9184 return EvaluateInPlace(Value, Info, Result, E); 9185 } 9186 9187 bool VisitCastExpr(const CastExpr *E) { 9188 switch (E->getCastKind()) { 9189 default: 9190 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9191 9192 case CK_ConstructorConversion: 9193 return VisitConstructExpr(E->getSubExpr()); 9194 } 9195 } 9196 bool VisitInitListExpr(const InitListExpr *E) { 9197 return VisitConstructExpr(E); 9198 } 9199 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9200 return VisitConstructExpr(E); 9201 } 9202 bool VisitCallExpr(const CallExpr *E) { 9203 return VisitConstructExpr(E); 9204 } 9205 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9206 return VisitConstructExpr(E); 9207 } 9208 bool VisitLambdaExpr(const LambdaExpr *E) { 9209 return VisitConstructExpr(E); 9210 } 9211 }; 9212 } // end anonymous namespace 9213 9214 /// Evaluate an expression of record type as a temporary. 9215 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 9216 assert(E->isRValue() && E->getType()->isRecordType()); 9217 return TemporaryExprEvaluator(Info, Result).Visit(E); 9218 } 9219 9220 //===----------------------------------------------------------------------===// 9221 // Vector Evaluation 9222 //===----------------------------------------------------------------------===// 9223 9224 namespace { 9225 class VectorExprEvaluator 9226 : public ExprEvaluatorBase<VectorExprEvaluator> { 9227 APValue &Result; 9228 public: 9229 9230 VectorExprEvaluator(EvalInfo &info, APValue &Result) 9231 : ExprEvaluatorBaseTy(info), Result(Result) {} 9232 9233 bool Success(ArrayRef<APValue> V, const Expr *E) { 9234 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 9235 // FIXME: remove this APValue copy. 9236 Result = APValue(V.data(), V.size()); 9237 return true; 9238 } 9239 bool Success(const APValue &V, const Expr *E) { 9240 assert(V.isVector()); 9241 Result = V; 9242 return true; 9243 } 9244 bool ZeroInitialization(const Expr *E); 9245 9246 bool VisitUnaryReal(const UnaryOperator *E) 9247 { return Visit(E->getSubExpr()); } 9248 bool VisitCastExpr(const CastExpr* E); 9249 bool VisitInitListExpr(const InitListExpr *E); 9250 bool VisitUnaryImag(const UnaryOperator *E); 9251 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 9252 // binary comparisons, binary and/or/xor, 9253 // shufflevector, ExtVectorElementExpr 9254 }; 9255 } // end anonymous namespace 9256 9257 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 9258 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 9259 return VectorExprEvaluator(Info, Result).Visit(E); 9260 } 9261 9262 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 9263 const VectorType *VTy = E->getType()->castAs<VectorType>(); 9264 unsigned NElts = VTy->getNumElements(); 9265 9266 const Expr *SE = E->getSubExpr(); 9267 QualType SETy = SE->getType(); 9268 9269 switch (E->getCastKind()) { 9270 case CK_VectorSplat: { 9271 APValue Val = APValue(); 9272 if (SETy->isIntegerType()) { 9273 APSInt IntResult; 9274 if (!EvaluateInteger(SE, IntResult, Info)) 9275 return false; 9276 Val = APValue(std::move(IntResult)); 9277 } else if (SETy->isRealFloatingType()) { 9278 APFloat FloatResult(0.0); 9279 if (!EvaluateFloat(SE, FloatResult, Info)) 9280 return false; 9281 Val = APValue(std::move(FloatResult)); 9282 } else { 9283 return Error(E); 9284 } 9285 9286 // Splat and create vector APValue. 9287 SmallVector<APValue, 4> Elts(NElts, Val); 9288 return Success(Elts, E); 9289 } 9290 case CK_BitCast: { 9291 // Evaluate the operand into an APInt we can extract from. 9292 llvm::APInt SValInt; 9293 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 9294 return false; 9295 // Extract the elements 9296 QualType EltTy = VTy->getElementType(); 9297 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 9298 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 9299 SmallVector<APValue, 4> Elts; 9300 if (EltTy->isRealFloatingType()) { 9301 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 9302 unsigned FloatEltSize = EltSize; 9303 if (&Sem == &APFloat::x87DoubleExtended()) 9304 FloatEltSize = 80; 9305 for (unsigned i = 0; i < NElts; i++) { 9306 llvm::APInt Elt; 9307 if (BigEndian) 9308 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 9309 else 9310 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 9311 Elts.push_back(APValue(APFloat(Sem, Elt))); 9312 } 9313 } else if (EltTy->isIntegerType()) { 9314 for (unsigned i = 0; i < NElts; i++) { 9315 llvm::APInt Elt; 9316 if (BigEndian) 9317 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 9318 else 9319 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 9320 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 9321 } 9322 } else { 9323 return Error(E); 9324 } 9325 return Success(Elts, E); 9326 } 9327 default: 9328 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9329 } 9330 } 9331 9332 bool 9333 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9334 const VectorType *VT = E->getType()->castAs<VectorType>(); 9335 unsigned NumInits = E->getNumInits(); 9336 unsigned NumElements = VT->getNumElements(); 9337 9338 QualType EltTy = VT->getElementType(); 9339 SmallVector<APValue, 4> Elements; 9340 9341 // The number of initializers can be less than the number of 9342 // vector elements. For OpenCL, this can be due to nested vector 9343 // initialization. For GCC compatibility, missing trailing elements 9344 // should be initialized with zeroes. 9345 unsigned CountInits = 0, CountElts = 0; 9346 while (CountElts < NumElements) { 9347 // Handle nested vector initialization. 9348 if (CountInits < NumInits 9349 && E->getInit(CountInits)->getType()->isVectorType()) { 9350 APValue v; 9351 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9352 return Error(E); 9353 unsigned vlen = v.getVectorLength(); 9354 for (unsigned j = 0; j < vlen; j++) 9355 Elements.push_back(v.getVectorElt(j)); 9356 CountElts += vlen; 9357 } else if (EltTy->isIntegerType()) { 9358 llvm::APSInt sInt(32); 9359 if (CountInits < NumInits) { 9360 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9361 return false; 9362 } else // trailing integer zero. 9363 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9364 Elements.push_back(APValue(sInt)); 9365 CountElts++; 9366 } else { 9367 llvm::APFloat f(0.0); 9368 if (CountInits < NumInits) { 9369 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9370 return false; 9371 } else // trailing float zero. 9372 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9373 Elements.push_back(APValue(f)); 9374 CountElts++; 9375 } 9376 CountInits++; 9377 } 9378 return Success(Elements, E); 9379 } 9380 9381 bool 9382 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9383 const auto *VT = E->getType()->castAs<VectorType>(); 9384 QualType EltTy = VT->getElementType(); 9385 APValue ZeroElement; 9386 if (EltTy->isIntegerType()) 9387 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 9388 else 9389 ZeroElement = 9390 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 9391 9392 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 9393 return Success(Elements, E); 9394 } 9395 9396 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9397 VisitIgnoredValue(E->getSubExpr()); 9398 return ZeroInitialization(E); 9399 } 9400 9401 //===----------------------------------------------------------------------===// 9402 // Array Evaluation 9403 //===----------------------------------------------------------------------===// 9404 9405 namespace { 9406 class ArrayExprEvaluator 9407 : public ExprEvaluatorBase<ArrayExprEvaluator> { 9408 const LValue &This; 9409 APValue &Result; 9410 public: 9411 9412 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 9413 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 9414 9415 bool Success(const APValue &V, const Expr *E) { 9416 assert(V.isArray() && "expected array"); 9417 Result = V; 9418 return true; 9419 } 9420 9421 bool ZeroInitialization(const Expr *E) { 9422 const ConstantArrayType *CAT = 9423 Info.Ctx.getAsConstantArrayType(E->getType()); 9424 if (!CAT) 9425 return Error(E); 9426 9427 Result = APValue(APValue::UninitArray(), 0, 9428 CAT->getSize().getZExtValue()); 9429 if (!Result.hasArrayFiller()) return true; 9430 9431 // Zero-initialize all elements. 9432 LValue Subobject = This; 9433 Subobject.addArray(Info, E, CAT); 9434 ImplicitValueInitExpr VIE(CAT->getElementType()); 9435 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 9436 } 9437 9438 bool VisitCallExpr(const CallExpr *E) { 9439 return handleCallExpr(E, Result, &This); 9440 } 9441 bool VisitInitListExpr(const InitListExpr *E, 9442 QualType AllocType = QualType()); 9443 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 9444 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 9445 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 9446 const LValue &Subobject, 9447 APValue *Value, QualType Type); 9448 bool VisitStringLiteral(const StringLiteral *E, 9449 QualType AllocType = QualType()) { 9450 expandStringLiteral(Info, E, Result, AllocType); 9451 return true; 9452 } 9453 }; 9454 } // end anonymous namespace 9455 9456 static bool EvaluateArray(const Expr *E, const LValue &This, 9457 APValue &Result, EvalInfo &Info) { 9458 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 9459 return ArrayExprEvaluator(Info, This, Result).Visit(E); 9460 } 9461 9462 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9463 APValue &Result, const InitListExpr *ILE, 9464 QualType AllocType) { 9465 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 9466 "not an array rvalue"); 9467 return ArrayExprEvaluator(Info, This, Result) 9468 .VisitInitListExpr(ILE, AllocType); 9469 } 9470 9471 // Return true iff the given array filler may depend on the element index. 9472 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 9473 // For now, just whitelist non-class value-initialization and initialization 9474 // lists comprised of them. 9475 if (isa<ImplicitValueInitExpr>(FillerExpr)) 9476 return false; 9477 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 9478 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 9479 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 9480 return true; 9481 } 9482 return false; 9483 } 9484 return true; 9485 } 9486 9487 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 9488 QualType AllocType) { 9489 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 9490 AllocType.isNull() ? E->getType() : AllocType); 9491 if (!CAT) 9492 return Error(E); 9493 9494 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 9495 // an appropriately-typed string literal enclosed in braces. 9496 if (E->isStringLiteralInit()) { 9497 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 9498 // FIXME: Support ObjCEncodeExpr here once we support it in 9499 // ArrayExprEvaluator generally. 9500 if (!SL) 9501 return Error(E); 9502 return VisitStringLiteral(SL, AllocType); 9503 } 9504 9505 bool Success = true; 9506 9507 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 9508 "zero-initialized array shouldn't have any initialized elts"); 9509 APValue Filler; 9510 if (Result.isArray() && Result.hasArrayFiller()) 9511 Filler = Result.getArrayFiller(); 9512 9513 unsigned NumEltsToInit = E->getNumInits(); 9514 unsigned NumElts = CAT->getSize().getZExtValue(); 9515 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 9516 9517 // If the initializer might depend on the array index, run it for each 9518 // array element. 9519 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 9520 NumEltsToInit = NumElts; 9521 9522 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 9523 << NumEltsToInit << ".\n"); 9524 9525 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 9526 9527 // If the array was previously zero-initialized, preserve the 9528 // zero-initialized values. 9529 if (Filler.hasValue()) { 9530 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 9531 Result.getArrayInitializedElt(I) = Filler; 9532 if (Result.hasArrayFiller()) 9533 Result.getArrayFiller() = Filler; 9534 } 9535 9536 LValue Subobject = This; 9537 Subobject.addArray(Info, E, CAT); 9538 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 9539 const Expr *Init = 9540 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 9541 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 9542 Info, Subobject, Init) || 9543 !HandleLValueArrayAdjustment(Info, Init, Subobject, 9544 CAT->getElementType(), 1)) { 9545 if (!Info.noteFailure()) 9546 return false; 9547 Success = false; 9548 } 9549 } 9550 9551 if (!Result.hasArrayFiller()) 9552 return Success; 9553 9554 // If we get here, we have a trivial filler, which we can just evaluate 9555 // once and splat over the rest of the array elements. 9556 assert(FillerExpr && "no array filler for incomplete init list"); 9557 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 9558 FillerExpr) && Success; 9559 } 9560 9561 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 9562 LValue CommonLV; 9563 if (E->getCommonExpr() && 9564 !Evaluate(Info.CurrentCall->createTemporary( 9565 E->getCommonExpr(), 9566 getStorageType(Info.Ctx, E->getCommonExpr()), false, 9567 CommonLV), 9568 Info, E->getCommonExpr()->getSourceExpr())) 9569 return false; 9570 9571 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 9572 9573 uint64_t Elements = CAT->getSize().getZExtValue(); 9574 Result = APValue(APValue::UninitArray(), Elements, Elements); 9575 9576 LValue Subobject = This; 9577 Subobject.addArray(Info, E, CAT); 9578 9579 bool Success = true; 9580 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 9581 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 9582 Info, Subobject, E->getSubExpr()) || 9583 !HandleLValueArrayAdjustment(Info, E, Subobject, 9584 CAT->getElementType(), 1)) { 9585 if (!Info.noteFailure()) 9586 return false; 9587 Success = false; 9588 } 9589 } 9590 9591 return Success; 9592 } 9593 9594 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 9595 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 9596 } 9597 9598 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9599 const LValue &Subobject, 9600 APValue *Value, 9601 QualType Type) { 9602 bool HadZeroInit = Value->hasValue(); 9603 9604 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 9605 unsigned N = CAT->getSize().getZExtValue(); 9606 9607 // Preserve the array filler if we had prior zero-initialization. 9608 APValue Filler = 9609 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 9610 : APValue(); 9611 9612 *Value = APValue(APValue::UninitArray(), N, N); 9613 9614 if (HadZeroInit) 9615 for (unsigned I = 0; I != N; ++I) 9616 Value->getArrayInitializedElt(I) = Filler; 9617 9618 // Initialize the elements. 9619 LValue ArrayElt = Subobject; 9620 ArrayElt.addArray(Info, E, CAT); 9621 for (unsigned I = 0; I != N; ++I) 9622 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 9623 CAT->getElementType()) || 9624 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 9625 CAT->getElementType(), 1)) 9626 return false; 9627 9628 return true; 9629 } 9630 9631 if (!Type->isRecordType()) 9632 return Error(E); 9633 9634 return RecordExprEvaluator(Info, Subobject, *Value) 9635 .VisitCXXConstructExpr(E, Type); 9636 } 9637 9638 //===----------------------------------------------------------------------===// 9639 // Integer Evaluation 9640 // 9641 // As a GNU extension, we support casting pointers to sufficiently-wide integer 9642 // types and back in constant folding. Integer values are thus represented 9643 // either as an integer-valued APValue, or as an lvalue-valued APValue. 9644 //===----------------------------------------------------------------------===// 9645 9646 namespace { 9647 class IntExprEvaluator 9648 : public ExprEvaluatorBase<IntExprEvaluator> { 9649 APValue &Result; 9650 public: 9651 IntExprEvaluator(EvalInfo &info, APValue &result) 9652 : ExprEvaluatorBaseTy(info), Result(result) {} 9653 9654 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 9655 assert(E->getType()->isIntegralOrEnumerationType() && 9656 "Invalid evaluation result."); 9657 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 9658 "Invalid evaluation result."); 9659 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 9660 "Invalid evaluation result."); 9661 Result = APValue(SI); 9662 return true; 9663 } 9664 bool Success(const llvm::APSInt &SI, const Expr *E) { 9665 return Success(SI, E, Result); 9666 } 9667 9668 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 9669 assert(E->getType()->isIntegralOrEnumerationType() && 9670 "Invalid evaluation result."); 9671 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 9672 "Invalid evaluation result."); 9673 Result = APValue(APSInt(I)); 9674 Result.getInt().setIsUnsigned( 9675 E->getType()->isUnsignedIntegerOrEnumerationType()); 9676 return true; 9677 } 9678 bool Success(const llvm::APInt &I, const Expr *E) { 9679 return Success(I, E, Result); 9680 } 9681 9682 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 9683 assert(E->getType()->isIntegralOrEnumerationType() && 9684 "Invalid evaluation result."); 9685 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 9686 return true; 9687 } 9688 bool Success(uint64_t Value, const Expr *E) { 9689 return Success(Value, E, Result); 9690 } 9691 9692 bool Success(CharUnits Size, const Expr *E) { 9693 return Success(Size.getQuantity(), E); 9694 } 9695 9696 bool Success(const APValue &V, const Expr *E) { 9697 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 9698 Result = V; 9699 return true; 9700 } 9701 return Success(V.getInt(), E); 9702 } 9703 9704 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 9705 9706 //===--------------------------------------------------------------------===// 9707 // Visitor Methods 9708 //===--------------------------------------------------------------------===// 9709 9710 bool VisitConstantExpr(const ConstantExpr *E); 9711 9712 bool VisitIntegerLiteral(const IntegerLiteral *E) { 9713 return Success(E->getValue(), E); 9714 } 9715 bool VisitCharacterLiteral(const CharacterLiteral *E) { 9716 return Success(E->getValue(), E); 9717 } 9718 9719 bool CheckReferencedDecl(const Expr *E, const Decl *D); 9720 bool VisitDeclRefExpr(const DeclRefExpr *E) { 9721 if (CheckReferencedDecl(E, E->getDecl())) 9722 return true; 9723 9724 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 9725 } 9726 bool VisitMemberExpr(const MemberExpr *E) { 9727 if (CheckReferencedDecl(E, E->getMemberDecl())) { 9728 VisitIgnoredBaseExpression(E->getBase()); 9729 return true; 9730 } 9731 9732 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 9733 } 9734 9735 bool VisitCallExpr(const CallExpr *E); 9736 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 9737 bool VisitBinaryOperator(const BinaryOperator *E); 9738 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 9739 bool VisitUnaryOperator(const UnaryOperator *E); 9740 9741 bool VisitCastExpr(const CastExpr* E); 9742 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 9743 9744 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 9745 return Success(E->getValue(), E); 9746 } 9747 9748 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 9749 return Success(E->getValue(), E); 9750 } 9751 9752 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 9753 if (Info.ArrayInitIndex == uint64_t(-1)) { 9754 // We were asked to evaluate this subexpression independent of the 9755 // enclosing ArrayInitLoopExpr. We can't do that. 9756 Info.FFDiag(E); 9757 return false; 9758 } 9759 return Success(Info.ArrayInitIndex, E); 9760 } 9761 9762 // Note, GNU defines __null as an integer, not a pointer. 9763 bool VisitGNUNullExpr(const GNUNullExpr *E) { 9764 return ZeroInitialization(E); 9765 } 9766 9767 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 9768 return Success(E->getValue(), E); 9769 } 9770 9771 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 9772 return Success(E->getValue(), E); 9773 } 9774 9775 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 9776 return Success(E->getValue(), E); 9777 } 9778 9779 bool VisitUnaryReal(const UnaryOperator *E); 9780 bool VisitUnaryImag(const UnaryOperator *E); 9781 9782 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 9783 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 9784 bool VisitSourceLocExpr(const SourceLocExpr *E); 9785 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 9786 // FIXME: Missing: array subscript of vector, member of vector 9787 }; 9788 9789 class FixedPointExprEvaluator 9790 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 9791 APValue &Result; 9792 9793 public: 9794 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 9795 : ExprEvaluatorBaseTy(info), Result(result) {} 9796 9797 bool Success(const llvm::APInt &I, const Expr *E) { 9798 return Success( 9799 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 9800 } 9801 9802 bool Success(uint64_t Value, const Expr *E) { 9803 return Success( 9804 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 9805 } 9806 9807 bool Success(const APValue &V, const Expr *E) { 9808 return Success(V.getFixedPoint(), E); 9809 } 9810 9811 bool Success(const APFixedPoint &V, const Expr *E) { 9812 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 9813 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 9814 "Invalid evaluation result."); 9815 Result = APValue(V); 9816 return true; 9817 } 9818 9819 //===--------------------------------------------------------------------===// 9820 // Visitor Methods 9821 //===--------------------------------------------------------------------===// 9822 9823 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 9824 return Success(E->getValue(), E); 9825 } 9826 9827 bool VisitCastExpr(const CastExpr *E); 9828 bool VisitUnaryOperator(const UnaryOperator *E); 9829 bool VisitBinaryOperator(const BinaryOperator *E); 9830 }; 9831 } // end anonymous namespace 9832 9833 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 9834 /// produce either the integer value or a pointer. 9835 /// 9836 /// GCC has a heinous extension which folds casts between pointer types and 9837 /// pointer-sized integral types. We support this by allowing the evaluation of 9838 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 9839 /// Some simple arithmetic on such values is supported (they are treated much 9840 /// like char*). 9841 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 9842 EvalInfo &Info) { 9843 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 9844 return IntExprEvaluator(Info, Result).Visit(E); 9845 } 9846 9847 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 9848 APValue Val; 9849 if (!EvaluateIntegerOrLValue(E, Val, Info)) 9850 return false; 9851 if (!Val.isInt()) { 9852 // FIXME: It would be better to produce the diagnostic for casting 9853 // a pointer to an integer. 9854 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9855 return false; 9856 } 9857 Result = Val.getInt(); 9858 return true; 9859 } 9860 9861 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 9862 APValue Evaluated = E->EvaluateInContext( 9863 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 9864 return Success(Evaluated, E); 9865 } 9866 9867 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 9868 EvalInfo &Info) { 9869 if (E->getType()->isFixedPointType()) { 9870 APValue Val; 9871 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 9872 return false; 9873 if (!Val.isFixedPoint()) 9874 return false; 9875 9876 Result = Val.getFixedPoint(); 9877 return true; 9878 } 9879 return false; 9880 } 9881 9882 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 9883 EvalInfo &Info) { 9884 if (E->getType()->isIntegerType()) { 9885 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 9886 APSInt Val; 9887 if (!EvaluateInteger(E, Val, Info)) 9888 return false; 9889 Result = APFixedPoint(Val, FXSema); 9890 return true; 9891 } else if (E->getType()->isFixedPointType()) { 9892 return EvaluateFixedPoint(E, Result, Info); 9893 } 9894 return false; 9895 } 9896 9897 /// Check whether the given declaration can be directly converted to an integral 9898 /// rvalue. If not, no diagnostic is produced; there are other things we can 9899 /// try. 9900 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 9901 // Enums are integer constant exprs. 9902 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 9903 // Check for signedness/width mismatches between E type and ECD value. 9904 bool SameSign = (ECD->getInitVal().isSigned() 9905 == E->getType()->isSignedIntegerOrEnumerationType()); 9906 bool SameWidth = (ECD->getInitVal().getBitWidth() 9907 == Info.Ctx.getIntWidth(E->getType())); 9908 if (SameSign && SameWidth) 9909 return Success(ECD->getInitVal(), E); 9910 else { 9911 // Get rid of mismatch (otherwise Success assertions will fail) 9912 // by computing a new value matching the type of E. 9913 llvm::APSInt Val = ECD->getInitVal(); 9914 if (!SameSign) 9915 Val.setIsSigned(!ECD->getInitVal().isSigned()); 9916 if (!SameWidth) 9917 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 9918 return Success(Val, E); 9919 } 9920 } 9921 return false; 9922 } 9923 9924 /// Values returned by __builtin_classify_type, chosen to match the values 9925 /// produced by GCC's builtin. 9926 enum class GCCTypeClass { 9927 None = -1, 9928 Void = 0, 9929 Integer = 1, 9930 // GCC reserves 2 for character types, but instead classifies them as 9931 // integers. 9932 Enum = 3, 9933 Bool = 4, 9934 Pointer = 5, 9935 // GCC reserves 6 for references, but appears to never use it (because 9936 // expressions never have reference type, presumably). 9937 PointerToDataMember = 7, 9938 RealFloat = 8, 9939 Complex = 9, 9940 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 9941 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 9942 // GCC claims to reserve 11 for pointers to member functions, but *actually* 9943 // uses 12 for that purpose, same as for a class or struct. Maybe it 9944 // internally implements a pointer to member as a struct? Who knows. 9945 PointerToMemberFunction = 12, // Not a bug, see above. 9946 ClassOrStruct = 12, 9947 Union = 13, 9948 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 9949 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 9950 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 9951 // literals. 9952 }; 9953 9954 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 9955 /// as GCC. 9956 static GCCTypeClass 9957 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 9958 assert(!T->isDependentType() && "unexpected dependent type"); 9959 9960 QualType CanTy = T.getCanonicalType(); 9961 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 9962 9963 switch (CanTy->getTypeClass()) { 9964 #define TYPE(ID, BASE) 9965 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 9966 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 9967 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 9968 #include "clang/AST/TypeNodes.inc" 9969 case Type::Auto: 9970 case Type::DeducedTemplateSpecialization: 9971 llvm_unreachable("unexpected non-canonical or dependent type"); 9972 9973 case Type::Builtin: 9974 switch (BT->getKind()) { 9975 #define BUILTIN_TYPE(ID, SINGLETON_ID) 9976 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 9977 case BuiltinType::ID: return GCCTypeClass::Integer; 9978 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 9979 case BuiltinType::ID: return GCCTypeClass::RealFloat; 9980 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 9981 case BuiltinType::ID: break; 9982 #include "clang/AST/BuiltinTypes.def" 9983 case BuiltinType::Void: 9984 return GCCTypeClass::Void; 9985 9986 case BuiltinType::Bool: 9987 return GCCTypeClass::Bool; 9988 9989 case BuiltinType::Char_U: 9990 case BuiltinType::UChar: 9991 case BuiltinType::WChar_U: 9992 case BuiltinType::Char8: 9993 case BuiltinType::Char16: 9994 case BuiltinType::Char32: 9995 case BuiltinType::UShort: 9996 case BuiltinType::UInt: 9997 case BuiltinType::ULong: 9998 case BuiltinType::ULongLong: 9999 case BuiltinType::UInt128: 10000 return GCCTypeClass::Integer; 10001 10002 case BuiltinType::UShortAccum: 10003 case BuiltinType::UAccum: 10004 case BuiltinType::ULongAccum: 10005 case BuiltinType::UShortFract: 10006 case BuiltinType::UFract: 10007 case BuiltinType::ULongFract: 10008 case BuiltinType::SatUShortAccum: 10009 case BuiltinType::SatUAccum: 10010 case BuiltinType::SatULongAccum: 10011 case BuiltinType::SatUShortFract: 10012 case BuiltinType::SatUFract: 10013 case BuiltinType::SatULongFract: 10014 return GCCTypeClass::None; 10015 10016 case BuiltinType::NullPtr: 10017 10018 case BuiltinType::ObjCId: 10019 case BuiltinType::ObjCClass: 10020 case BuiltinType::ObjCSel: 10021 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10022 case BuiltinType::Id: 10023 #include "clang/Basic/OpenCLImageTypes.def" 10024 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10025 case BuiltinType::Id: 10026 #include "clang/Basic/OpenCLExtensionTypes.def" 10027 case BuiltinType::OCLSampler: 10028 case BuiltinType::OCLEvent: 10029 case BuiltinType::OCLClkEvent: 10030 case BuiltinType::OCLQueue: 10031 case BuiltinType::OCLReserveID: 10032 #define SVE_TYPE(Name, Id, SingletonId) \ 10033 case BuiltinType::Id: 10034 #include "clang/Basic/AArch64SVEACLETypes.def" 10035 return GCCTypeClass::None; 10036 10037 case BuiltinType::Dependent: 10038 llvm_unreachable("unexpected dependent type"); 10039 }; 10040 llvm_unreachable("unexpected placeholder type"); 10041 10042 case Type::Enum: 10043 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10044 10045 case Type::Pointer: 10046 case Type::ConstantArray: 10047 case Type::VariableArray: 10048 case Type::IncompleteArray: 10049 case Type::FunctionNoProto: 10050 case Type::FunctionProto: 10051 return GCCTypeClass::Pointer; 10052 10053 case Type::MemberPointer: 10054 return CanTy->isMemberDataPointerType() 10055 ? GCCTypeClass::PointerToDataMember 10056 : GCCTypeClass::PointerToMemberFunction; 10057 10058 case Type::Complex: 10059 return GCCTypeClass::Complex; 10060 10061 case Type::Record: 10062 return CanTy->isUnionType() ? GCCTypeClass::Union 10063 : GCCTypeClass::ClassOrStruct; 10064 10065 case Type::Atomic: 10066 // GCC classifies _Atomic T the same as T. 10067 return EvaluateBuiltinClassifyType( 10068 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10069 10070 case Type::BlockPointer: 10071 case Type::Vector: 10072 case Type::ExtVector: 10073 case Type::ObjCObject: 10074 case Type::ObjCInterface: 10075 case Type::ObjCObjectPointer: 10076 case Type::Pipe: 10077 // GCC classifies vectors as None. We follow its lead and classify all 10078 // other types that don't fit into the regular classification the same way. 10079 return GCCTypeClass::None; 10080 10081 case Type::LValueReference: 10082 case Type::RValueReference: 10083 llvm_unreachable("invalid type for expression"); 10084 } 10085 10086 llvm_unreachable("unexpected type class"); 10087 } 10088 10089 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10090 /// as GCC. 10091 static GCCTypeClass 10092 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10093 // If no argument was supplied, default to None. This isn't 10094 // ideal, however it is what gcc does. 10095 if (E->getNumArgs() == 0) 10096 return GCCTypeClass::None; 10097 10098 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10099 // being an ICE, but still folds it to a constant using the type of the first 10100 // argument. 10101 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10102 } 10103 10104 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10105 /// __builtin_constant_p when applied to the given pointer. 10106 /// 10107 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10108 /// or it points to the first character of a string literal. 10109 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10110 APValue::LValueBase Base = LV.getLValueBase(); 10111 if (Base.isNull()) { 10112 // A null base is acceptable. 10113 return true; 10114 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10115 if (!isa<StringLiteral>(E)) 10116 return false; 10117 return LV.getLValueOffset().isZero(); 10118 } else if (Base.is<TypeInfoLValue>()) { 10119 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10120 // evaluate to true. 10121 return true; 10122 } else { 10123 // Any other base is not constant enough for GCC. 10124 return false; 10125 } 10126 } 10127 10128 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10129 /// GCC as we can manage. 10130 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10131 // This evaluation is not permitted to have side-effects, so evaluate it in 10132 // a speculative evaluation context. 10133 SpeculativeEvaluationRAII SpeculativeEval(Info); 10134 10135 // Constant-folding is always enabled for the operand of __builtin_constant_p 10136 // (even when the enclosing evaluation context otherwise requires a strict 10137 // language-specific constant expression). 10138 FoldConstant Fold(Info, true); 10139 10140 QualType ArgType = Arg->getType(); 10141 10142 // __builtin_constant_p always has one operand. The rules which gcc follows 10143 // are not precisely documented, but are as follows: 10144 // 10145 // - If the operand is of integral, floating, complex or enumeration type, 10146 // and can be folded to a known value of that type, it returns 1. 10147 // - If the operand can be folded to a pointer to the first character 10148 // of a string literal (or such a pointer cast to an integral type) 10149 // or to a null pointer or an integer cast to a pointer, it returns 1. 10150 // 10151 // Otherwise, it returns 0. 10152 // 10153 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10154 // its support for this did not work prior to GCC 9 and is not yet well 10155 // understood. 10156 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10157 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10158 ArgType->isNullPtrType()) { 10159 APValue V; 10160 if (!::EvaluateAsRValue(Info, Arg, V)) { 10161 Fold.keepDiagnostics(); 10162 return false; 10163 } 10164 10165 // For a pointer (possibly cast to integer), there are special rules. 10166 if (V.getKind() == APValue::LValue) 10167 return EvaluateBuiltinConstantPForLValue(V); 10168 10169 // Otherwise, any constant value is good enough. 10170 return V.hasValue(); 10171 } 10172 10173 // Anything else isn't considered to be sufficiently constant. 10174 return false; 10175 } 10176 10177 /// Retrieves the "underlying object type" of the given expression, 10178 /// as used by __builtin_object_size. 10179 static QualType getObjectType(APValue::LValueBase B) { 10180 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 10181 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 10182 return VD->getType(); 10183 } else if (const Expr *E = B.get<const Expr*>()) { 10184 if (isa<CompoundLiteralExpr>(E)) 10185 return E->getType(); 10186 } else if (B.is<TypeInfoLValue>()) { 10187 return B.getTypeInfoType(); 10188 } else if (B.is<DynamicAllocLValue>()) { 10189 return B.getDynamicAllocType(); 10190 } 10191 10192 return QualType(); 10193 } 10194 10195 /// A more selective version of E->IgnoreParenCasts for 10196 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 10197 /// to change the type of E. 10198 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 10199 /// 10200 /// Always returns an RValue with a pointer representation. 10201 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 10202 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 10203 10204 auto *NoParens = E->IgnoreParens(); 10205 auto *Cast = dyn_cast<CastExpr>(NoParens); 10206 if (Cast == nullptr) 10207 return NoParens; 10208 10209 // We only conservatively allow a few kinds of casts, because this code is 10210 // inherently a simple solution that seeks to support the common case. 10211 auto CastKind = Cast->getCastKind(); 10212 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 10213 CastKind != CK_AddressSpaceConversion) 10214 return NoParens; 10215 10216 auto *SubExpr = Cast->getSubExpr(); 10217 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 10218 return NoParens; 10219 return ignorePointerCastsAndParens(SubExpr); 10220 } 10221 10222 /// Checks to see if the given LValue's Designator is at the end of the LValue's 10223 /// record layout. e.g. 10224 /// struct { struct { int a, b; } fst, snd; } obj; 10225 /// obj.fst // no 10226 /// obj.snd // yes 10227 /// obj.fst.a // no 10228 /// obj.fst.b // no 10229 /// obj.snd.a // no 10230 /// obj.snd.b // yes 10231 /// 10232 /// Please note: this function is specialized for how __builtin_object_size 10233 /// views "objects". 10234 /// 10235 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 10236 /// correct result, it will always return true. 10237 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 10238 assert(!LVal.Designator.Invalid); 10239 10240 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 10241 const RecordDecl *Parent = FD->getParent(); 10242 Invalid = Parent->isInvalidDecl(); 10243 if (Invalid || Parent->isUnion()) 10244 return true; 10245 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 10246 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 10247 }; 10248 10249 auto &Base = LVal.getLValueBase(); 10250 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 10251 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 10252 bool Invalid; 10253 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10254 return Invalid; 10255 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 10256 for (auto *FD : IFD->chain()) { 10257 bool Invalid; 10258 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 10259 return Invalid; 10260 } 10261 } 10262 } 10263 10264 unsigned I = 0; 10265 QualType BaseType = getType(Base); 10266 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 10267 // If we don't know the array bound, conservatively assume we're looking at 10268 // the final array element. 10269 ++I; 10270 if (BaseType->isIncompleteArrayType()) 10271 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 10272 else 10273 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 10274 } 10275 10276 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 10277 const auto &Entry = LVal.Designator.Entries[I]; 10278 if (BaseType->isArrayType()) { 10279 // Because __builtin_object_size treats arrays as objects, we can ignore 10280 // the index iff this is the last array in the Designator. 10281 if (I + 1 == E) 10282 return true; 10283 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 10284 uint64_t Index = Entry.getAsArrayIndex(); 10285 if (Index + 1 != CAT->getSize()) 10286 return false; 10287 BaseType = CAT->getElementType(); 10288 } else if (BaseType->isAnyComplexType()) { 10289 const auto *CT = BaseType->castAs<ComplexType>(); 10290 uint64_t Index = Entry.getAsArrayIndex(); 10291 if (Index != 1) 10292 return false; 10293 BaseType = CT->getElementType(); 10294 } else if (auto *FD = getAsField(Entry)) { 10295 bool Invalid; 10296 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10297 return Invalid; 10298 BaseType = FD->getType(); 10299 } else { 10300 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 10301 return false; 10302 } 10303 } 10304 return true; 10305 } 10306 10307 /// Tests to see if the LValue has a user-specified designator (that isn't 10308 /// necessarily valid). Note that this always returns 'true' if the LValue has 10309 /// an unsized array as its first designator entry, because there's currently no 10310 /// way to tell if the user typed *foo or foo[0]. 10311 static bool refersToCompleteObject(const LValue &LVal) { 10312 if (LVal.Designator.Invalid) 10313 return false; 10314 10315 if (!LVal.Designator.Entries.empty()) 10316 return LVal.Designator.isMostDerivedAnUnsizedArray(); 10317 10318 if (!LVal.InvalidBase) 10319 return true; 10320 10321 // If `E` is a MemberExpr, then the first part of the designator is hiding in 10322 // the LValueBase. 10323 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 10324 return !E || !isa<MemberExpr>(E); 10325 } 10326 10327 /// Attempts to detect a user writing into a piece of memory that's impossible 10328 /// to figure out the size of by just using types. 10329 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 10330 const SubobjectDesignator &Designator = LVal.Designator; 10331 // Notes: 10332 // - Users can only write off of the end when we have an invalid base. Invalid 10333 // bases imply we don't know where the memory came from. 10334 // - We used to be a bit more aggressive here; we'd only be conservative if 10335 // the array at the end was flexible, or if it had 0 or 1 elements. This 10336 // broke some common standard library extensions (PR30346), but was 10337 // otherwise seemingly fine. It may be useful to reintroduce this behavior 10338 // with some sort of whitelist. OTOH, it seems that GCC is always 10339 // conservative with the last element in structs (if it's an array), so our 10340 // current behavior is more compatible than a whitelisting approach would 10341 // be. 10342 return LVal.InvalidBase && 10343 Designator.Entries.size() == Designator.MostDerivedPathLength && 10344 Designator.MostDerivedIsArrayElement && 10345 isDesignatorAtObjectEnd(Ctx, LVal); 10346 } 10347 10348 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 10349 /// Fails if the conversion would cause loss of precision. 10350 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 10351 CharUnits &Result) { 10352 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 10353 if (Int.ugt(CharUnitsMax)) 10354 return false; 10355 Result = CharUnits::fromQuantity(Int.getZExtValue()); 10356 return true; 10357 } 10358 10359 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 10360 /// determine how many bytes exist from the beginning of the object to either 10361 /// the end of the current subobject, or the end of the object itself, depending 10362 /// on what the LValue looks like + the value of Type. 10363 /// 10364 /// If this returns false, the value of Result is undefined. 10365 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 10366 unsigned Type, const LValue &LVal, 10367 CharUnits &EndOffset) { 10368 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 10369 10370 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 10371 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 10372 return false; 10373 return HandleSizeof(Info, ExprLoc, Ty, Result); 10374 }; 10375 10376 // We want to evaluate the size of the entire object. This is a valid fallback 10377 // for when Type=1 and the designator is invalid, because we're asked for an 10378 // upper-bound. 10379 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 10380 // Type=3 wants a lower bound, so we can't fall back to this. 10381 if (Type == 3 && !DetermineForCompleteObject) 10382 return false; 10383 10384 llvm::APInt APEndOffset; 10385 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10386 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10387 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10388 10389 if (LVal.InvalidBase) 10390 return false; 10391 10392 QualType BaseTy = getObjectType(LVal.getLValueBase()); 10393 return CheckedHandleSizeof(BaseTy, EndOffset); 10394 } 10395 10396 // We want to evaluate the size of a subobject. 10397 const SubobjectDesignator &Designator = LVal.Designator; 10398 10399 // The following is a moderately common idiom in C: 10400 // 10401 // struct Foo { int a; char c[1]; }; 10402 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 10403 // strcpy(&F->c[0], Bar); 10404 // 10405 // In order to not break too much legacy code, we need to support it. 10406 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 10407 // If we can resolve this to an alloc_size call, we can hand that back, 10408 // because we know for certain how many bytes there are to write to. 10409 llvm::APInt APEndOffset; 10410 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10411 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10412 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10413 10414 // If we cannot determine the size of the initial allocation, then we can't 10415 // given an accurate upper-bound. However, we are still able to give 10416 // conservative lower-bounds for Type=3. 10417 if (Type == 1) 10418 return false; 10419 } 10420 10421 CharUnits BytesPerElem; 10422 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 10423 return false; 10424 10425 // According to the GCC documentation, we want the size of the subobject 10426 // denoted by the pointer. But that's not quite right -- what we actually 10427 // want is the size of the immediately-enclosing array, if there is one. 10428 int64_t ElemsRemaining; 10429 if (Designator.MostDerivedIsArrayElement && 10430 Designator.Entries.size() == Designator.MostDerivedPathLength) { 10431 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 10432 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 10433 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 10434 } else { 10435 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 10436 } 10437 10438 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 10439 return true; 10440 } 10441 10442 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 10443 /// returns true and stores the result in @p Size. 10444 /// 10445 /// If @p WasError is non-null, this will report whether the failure to evaluate 10446 /// is to be treated as an Error in IntExprEvaluator. 10447 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 10448 EvalInfo &Info, uint64_t &Size) { 10449 // Determine the denoted object. 10450 LValue LVal; 10451 { 10452 // The operand of __builtin_object_size is never evaluated for side-effects. 10453 // If there are any, but we can determine the pointed-to object anyway, then 10454 // ignore the side-effects. 10455 SpeculativeEvaluationRAII SpeculativeEval(Info); 10456 IgnoreSideEffectsRAII Fold(Info); 10457 10458 if (E->isGLValue()) { 10459 // It's possible for us to be given GLValues if we're called via 10460 // Expr::tryEvaluateObjectSize. 10461 APValue RVal; 10462 if (!EvaluateAsRValue(Info, E, RVal)) 10463 return false; 10464 LVal.setFrom(Info.Ctx, RVal); 10465 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 10466 /*InvalidBaseOK=*/true)) 10467 return false; 10468 } 10469 10470 // If we point to before the start of the object, there are no accessible 10471 // bytes. 10472 if (LVal.getLValueOffset().isNegative()) { 10473 Size = 0; 10474 return true; 10475 } 10476 10477 CharUnits EndOffset; 10478 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 10479 return false; 10480 10481 // If we've fallen outside of the end offset, just pretend there's nothing to 10482 // write to/read from. 10483 if (EndOffset <= LVal.getLValueOffset()) 10484 Size = 0; 10485 else 10486 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 10487 return true; 10488 } 10489 10490 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { 10491 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); 10492 if (E->getResultAPValueKind() != APValue::None) 10493 return Success(E->getAPValueResult(), E); 10494 return ExprEvaluatorBaseTy::VisitConstantExpr(E); 10495 } 10496 10497 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 10498 if (unsigned BuiltinOp = E->getBuiltinCallee()) 10499 return VisitBuiltinCallExpr(E, BuiltinOp); 10500 10501 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10502 } 10503 10504 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 10505 unsigned BuiltinOp) { 10506 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 10507 default: 10508 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10509 10510 case Builtin::BI__builtin_dynamic_object_size: 10511 case Builtin::BI__builtin_object_size: { 10512 // The type was checked when we built the expression. 10513 unsigned Type = 10514 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 10515 assert(Type <= 3 && "unexpected type"); 10516 10517 uint64_t Size; 10518 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 10519 return Success(Size, E); 10520 10521 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 10522 return Success((Type & 2) ? 0 : -1, E); 10523 10524 // Expression had no side effects, but we couldn't statically determine the 10525 // size of the referenced object. 10526 switch (Info.EvalMode) { 10527 case EvalInfo::EM_ConstantExpression: 10528 case EvalInfo::EM_ConstantFold: 10529 case EvalInfo::EM_IgnoreSideEffects: 10530 // Leave it to IR generation. 10531 return Error(E); 10532 case EvalInfo::EM_ConstantExpressionUnevaluated: 10533 // Reduce it to a constant now. 10534 return Success((Type & 2) ? 0 : -1, E); 10535 } 10536 10537 llvm_unreachable("unexpected EvalMode"); 10538 } 10539 10540 case Builtin::BI__builtin_os_log_format_buffer_size: { 10541 analyze_os_log::OSLogBufferLayout Layout; 10542 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 10543 return Success(Layout.size().getQuantity(), E); 10544 } 10545 10546 case Builtin::BI__builtin_bswap16: 10547 case Builtin::BI__builtin_bswap32: 10548 case Builtin::BI__builtin_bswap64: { 10549 APSInt Val; 10550 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10551 return false; 10552 10553 return Success(Val.byteSwap(), E); 10554 } 10555 10556 case Builtin::BI__builtin_classify_type: 10557 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 10558 10559 case Builtin::BI__builtin_clrsb: 10560 case Builtin::BI__builtin_clrsbl: 10561 case Builtin::BI__builtin_clrsbll: { 10562 APSInt Val; 10563 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10564 return false; 10565 10566 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 10567 } 10568 10569 case Builtin::BI__builtin_clz: 10570 case Builtin::BI__builtin_clzl: 10571 case Builtin::BI__builtin_clzll: 10572 case Builtin::BI__builtin_clzs: { 10573 APSInt Val; 10574 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10575 return false; 10576 if (!Val) 10577 return Error(E); 10578 10579 return Success(Val.countLeadingZeros(), E); 10580 } 10581 10582 case Builtin::BI__builtin_constant_p: { 10583 const Expr *Arg = E->getArg(0); 10584 if (EvaluateBuiltinConstantP(Info, Arg)) 10585 return Success(true, E); 10586 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 10587 // Outside a constant context, eagerly evaluate to false in the presence 10588 // of side-effects in order to avoid -Wunsequenced false-positives in 10589 // a branch on __builtin_constant_p(expr). 10590 return Success(false, E); 10591 } 10592 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10593 return false; 10594 } 10595 10596 case Builtin::BI__builtin_is_constant_evaluated: { 10597 const auto *Callee = Info.CurrentCall->getCallee(); 10598 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 10599 (Info.CallStackDepth == 1 || 10600 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 10601 Callee->getIdentifier() && 10602 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 10603 // FIXME: Find a better way to avoid duplicated diagnostics. 10604 if (Info.EvalStatus.Diag) 10605 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 10606 : Info.CurrentCall->CallLoc, 10607 diag::warn_is_constant_evaluated_always_true_constexpr) 10608 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 10609 : "std::is_constant_evaluated"); 10610 } 10611 10612 return Success(Info.InConstantContext, E); 10613 } 10614 10615 case Builtin::BI__builtin_ctz: 10616 case Builtin::BI__builtin_ctzl: 10617 case Builtin::BI__builtin_ctzll: 10618 case Builtin::BI__builtin_ctzs: { 10619 APSInt Val; 10620 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10621 return false; 10622 if (!Val) 10623 return Error(E); 10624 10625 return Success(Val.countTrailingZeros(), E); 10626 } 10627 10628 case Builtin::BI__builtin_eh_return_data_regno: { 10629 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 10630 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 10631 return Success(Operand, E); 10632 } 10633 10634 case Builtin::BI__builtin_expect: 10635 return Visit(E->getArg(0)); 10636 10637 case Builtin::BI__builtin_ffs: 10638 case Builtin::BI__builtin_ffsl: 10639 case Builtin::BI__builtin_ffsll: { 10640 APSInt Val; 10641 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10642 return false; 10643 10644 unsigned N = Val.countTrailingZeros(); 10645 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 10646 } 10647 10648 case Builtin::BI__builtin_fpclassify: { 10649 APFloat Val(0.0); 10650 if (!EvaluateFloat(E->getArg(5), Val, Info)) 10651 return false; 10652 unsigned Arg; 10653 switch (Val.getCategory()) { 10654 case APFloat::fcNaN: Arg = 0; break; 10655 case APFloat::fcInfinity: Arg = 1; break; 10656 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 10657 case APFloat::fcZero: Arg = 4; break; 10658 } 10659 return Visit(E->getArg(Arg)); 10660 } 10661 10662 case Builtin::BI__builtin_isinf_sign: { 10663 APFloat Val(0.0); 10664 return EvaluateFloat(E->getArg(0), Val, Info) && 10665 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 10666 } 10667 10668 case Builtin::BI__builtin_isinf: { 10669 APFloat Val(0.0); 10670 return EvaluateFloat(E->getArg(0), Val, Info) && 10671 Success(Val.isInfinity() ? 1 : 0, E); 10672 } 10673 10674 case Builtin::BI__builtin_isfinite: { 10675 APFloat Val(0.0); 10676 return EvaluateFloat(E->getArg(0), Val, Info) && 10677 Success(Val.isFinite() ? 1 : 0, E); 10678 } 10679 10680 case Builtin::BI__builtin_isnan: { 10681 APFloat Val(0.0); 10682 return EvaluateFloat(E->getArg(0), Val, Info) && 10683 Success(Val.isNaN() ? 1 : 0, E); 10684 } 10685 10686 case Builtin::BI__builtin_isnormal: { 10687 APFloat Val(0.0); 10688 return EvaluateFloat(E->getArg(0), Val, Info) && 10689 Success(Val.isNormal() ? 1 : 0, E); 10690 } 10691 10692 case Builtin::BI__builtin_parity: 10693 case Builtin::BI__builtin_parityl: 10694 case Builtin::BI__builtin_parityll: { 10695 APSInt Val; 10696 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10697 return false; 10698 10699 return Success(Val.countPopulation() % 2, E); 10700 } 10701 10702 case Builtin::BI__builtin_popcount: 10703 case Builtin::BI__builtin_popcountl: 10704 case Builtin::BI__builtin_popcountll: { 10705 APSInt Val; 10706 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10707 return false; 10708 10709 return Success(Val.countPopulation(), E); 10710 } 10711 10712 case Builtin::BIstrlen: 10713 case Builtin::BIwcslen: 10714 // A call to strlen is not a constant expression. 10715 if (Info.getLangOpts().CPlusPlus11) 10716 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 10717 << /*isConstexpr*/0 << /*isConstructor*/0 10718 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 10719 else 10720 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 10721 LLVM_FALLTHROUGH; 10722 case Builtin::BI__builtin_strlen: 10723 case Builtin::BI__builtin_wcslen: { 10724 // As an extension, we support __builtin_strlen() as a constant expression, 10725 // and support folding strlen() to a constant. 10726 LValue String; 10727 if (!EvaluatePointer(E->getArg(0), String, Info)) 10728 return false; 10729 10730 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 10731 10732 // Fast path: if it's a string literal, search the string value. 10733 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 10734 String.getLValueBase().dyn_cast<const Expr *>())) { 10735 // The string literal may have embedded null characters. Find the first 10736 // one and truncate there. 10737 StringRef Str = S->getBytes(); 10738 int64_t Off = String.Offset.getQuantity(); 10739 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 10740 S->getCharByteWidth() == 1 && 10741 // FIXME: Add fast-path for wchar_t too. 10742 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 10743 Str = Str.substr(Off); 10744 10745 StringRef::size_type Pos = Str.find(0); 10746 if (Pos != StringRef::npos) 10747 Str = Str.substr(0, Pos); 10748 10749 return Success(Str.size(), E); 10750 } 10751 10752 // Fall through to slow path to issue appropriate diagnostic. 10753 } 10754 10755 // Slow path: scan the bytes of the string looking for the terminating 0. 10756 for (uint64_t Strlen = 0; /**/; ++Strlen) { 10757 APValue Char; 10758 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 10759 !Char.isInt()) 10760 return false; 10761 if (!Char.getInt()) 10762 return Success(Strlen, E); 10763 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 10764 return false; 10765 } 10766 } 10767 10768 case Builtin::BIstrcmp: 10769 case Builtin::BIwcscmp: 10770 case Builtin::BIstrncmp: 10771 case Builtin::BIwcsncmp: 10772 case Builtin::BImemcmp: 10773 case Builtin::BIbcmp: 10774 case Builtin::BIwmemcmp: 10775 // A call to strlen is not a constant expression. 10776 if (Info.getLangOpts().CPlusPlus11) 10777 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 10778 << /*isConstexpr*/0 << /*isConstructor*/0 10779 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 10780 else 10781 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 10782 LLVM_FALLTHROUGH; 10783 case Builtin::BI__builtin_strcmp: 10784 case Builtin::BI__builtin_wcscmp: 10785 case Builtin::BI__builtin_strncmp: 10786 case Builtin::BI__builtin_wcsncmp: 10787 case Builtin::BI__builtin_memcmp: 10788 case Builtin::BI__builtin_bcmp: 10789 case Builtin::BI__builtin_wmemcmp: { 10790 LValue String1, String2; 10791 if (!EvaluatePointer(E->getArg(0), String1, Info) || 10792 !EvaluatePointer(E->getArg(1), String2, Info)) 10793 return false; 10794 10795 uint64_t MaxLength = uint64_t(-1); 10796 if (BuiltinOp != Builtin::BIstrcmp && 10797 BuiltinOp != Builtin::BIwcscmp && 10798 BuiltinOp != Builtin::BI__builtin_strcmp && 10799 BuiltinOp != Builtin::BI__builtin_wcscmp) { 10800 APSInt N; 10801 if (!EvaluateInteger(E->getArg(2), N, Info)) 10802 return false; 10803 MaxLength = N.getExtValue(); 10804 } 10805 10806 // Empty substrings compare equal by definition. 10807 if (MaxLength == 0u) 10808 return Success(0, E); 10809 10810 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 10811 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 10812 String1.Designator.Invalid || String2.Designator.Invalid) 10813 return false; 10814 10815 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 10816 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 10817 10818 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 10819 BuiltinOp == Builtin::BIbcmp || 10820 BuiltinOp == Builtin::BI__builtin_memcmp || 10821 BuiltinOp == Builtin::BI__builtin_bcmp; 10822 10823 assert(IsRawByte || 10824 (Info.Ctx.hasSameUnqualifiedType( 10825 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 10826 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 10827 10828 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 10829 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 10830 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 10831 Char1.isInt() && Char2.isInt(); 10832 }; 10833 const auto &AdvanceElems = [&] { 10834 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 10835 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 10836 }; 10837 10838 if (IsRawByte) { 10839 uint64_t BytesRemaining = MaxLength; 10840 // Pointers to const void may point to objects of incomplete type. 10841 if (CharTy1->isIncompleteType()) { 10842 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1; 10843 return false; 10844 } 10845 if (CharTy2->isIncompleteType()) { 10846 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2; 10847 return false; 10848 } 10849 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)}; 10850 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width); 10851 // Give up on comparing between elements with disparate widths. 10852 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2)) 10853 return false; 10854 uint64_t BytesPerElement = CharTy1Size.getQuantity(); 10855 assert(BytesRemaining && "BytesRemaining should not be zero: the " 10856 "following loop considers at least one element"); 10857 while (true) { 10858 APValue Char1, Char2; 10859 if (!ReadCurElems(Char1, Char2)) 10860 return false; 10861 // We have compatible in-memory widths, but a possible type and 10862 // (for `bool`) internal representation mismatch. 10863 // Assuming two's complement representation, including 0 for `false` and 10864 // 1 for `true`, we can check an appropriate number of elements for 10865 // equality even if they are not byte-sized. 10866 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width); 10867 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width); 10868 if (Char1InMem.ne(Char2InMem)) { 10869 // If the elements are byte-sized, then we can produce a three-way 10870 // comparison result in a straightforward manner. 10871 if (BytesPerElement == 1u) { 10872 // memcmp always compares unsigned chars. 10873 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E); 10874 } 10875 // The result is byte-order sensitive, and we have multibyte elements. 10876 // FIXME: We can compare the remaining bytes in the correct order. 10877 return false; 10878 } 10879 if (!AdvanceElems()) 10880 return false; 10881 if (BytesRemaining <= BytesPerElement) 10882 break; 10883 BytesRemaining -= BytesPerElement; 10884 } 10885 // Enough elements are equal to account for the memcmp limit. 10886 return Success(0, E); 10887 } 10888 10889 bool StopAtNull = 10890 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 10891 BuiltinOp != Builtin::BIwmemcmp && 10892 BuiltinOp != Builtin::BI__builtin_memcmp && 10893 BuiltinOp != Builtin::BI__builtin_bcmp && 10894 BuiltinOp != Builtin::BI__builtin_wmemcmp); 10895 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 10896 BuiltinOp == Builtin::BIwcsncmp || 10897 BuiltinOp == Builtin::BIwmemcmp || 10898 BuiltinOp == Builtin::BI__builtin_wcscmp || 10899 BuiltinOp == Builtin::BI__builtin_wcsncmp || 10900 BuiltinOp == Builtin::BI__builtin_wmemcmp; 10901 10902 for (; MaxLength; --MaxLength) { 10903 APValue Char1, Char2; 10904 if (!ReadCurElems(Char1, Char2)) 10905 return false; 10906 if (Char1.getInt() != Char2.getInt()) { 10907 if (IsWide) // wmemcmp compares with wchar_t signedness. 10908 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 10909 // memcmp always compares unsigned chars. 10910 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 10911 } 10912 if (StopAtNull && !Char1.getInt()) 10913 return Success(0, E); 10914 assert(!(StopAtNull && !Char2.getInt())); 10915 if (!AdvanceElems()) 10916 return false; 10917 } 10918 // We hit the strncmp / memcmp limit. 10919 return Success(0, E); 10920 } 10921 10922 case Builtin::BI__atomic_always_lock_free: 10923 case Builtin::BI__atomic_is_lock_free: 10924 case Builtin::BI__c11_atomic_is_lock_free: { 10925 APSInt SizeVal; 10926 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 10927 return false; 10928 10929 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 10930 // of two less than the maximum inline atomic width, we know it is 10931 // lock-free. If the size isn't a power of two, or greater than the 10932 // maximum alignment where we promote atomics, we know it is not lock-free 10933 // (at least not in the sense of atomic_is_lock_free). Otherwise, 10934 // the answer can only be determined at runtime; for example, 16-byte 10935 // atomics have lock-free implementations on some, but not all, 10936 // x86-64 processors. 10937 10938 // Check power-of-two. 10939 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 10940 if (Size.isPowerOfTwo()) { 10941 // Check against inlining width. 10942 unsigned InlineWidthBits = 10943 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 10944 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 10945 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 10946 Size == CharUnits::One() || 10947 E->getArg(1)->isNullPointerConstant(Info.Ctx, 10948 Expr::NPC_NeverValueDependent)) 10949 // OK, we will inline appropriately-aligned operations of this size, 10950 // and _Atomic(T) is appropriately-aligned. 10951 return Success(1, E); 10952 10953 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 10954 castAs<PointerType>()->getPointeeType(); 10955 if (!PointeeType->isIncompleteType() && 10956 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 10957 // OK, we will inline operations on this object. 10958 return Success(1, E); 10959 } 10960 } 10961 } 10962 10963 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 10964 Success(0, E) : Error(E); 10965 } 10966 case Builtin::BIomp_is_initial_device: 10967 // We can decide statically which value the runtime would return if called. 10968 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 10969 case Builtin::BI__builtin_add_overflow: 10970 case Builtin::BI__builtin_sub_overflow: 10971 case Builtin::BI__builtin_mul_overflow: 10972 case Builtin::BI__builtin_sadd_overflow: 10973 case Builtin::BI__builtin_uadd_overflow: 10974 case Builtin::BI__builtin_uaddl_overflow: 10975 case Builtin::BI__builtin_uaddll_overflow: 10976 case Builtin::BI__builtin_usub_overflow: 10977 case Builtin::BI__builtin_usubl_overflow: 10978 case Builtin::BI__builtin_usubll_overflow: 10979 case Builtin::BI__builtin_umul_overflow: 10980 case Builtin::BI__builtin_umull_overflow: 10981 case Builtin::BI__builtin_umulll_overflow: 10982 case Builtin::BI__builtin_saddl_overflow: 10983 case Builtin::BI__builtin_saddll_overflow: 10984 case Builtin::BI__builtin_ssub_overflow: 10985 case Builtin::BI__builtin_ssubl_overflow: 10986 case Builtin::BI__builtin_ssubll_overflow: 10987 case Builtin::BI__builtin_smul_overflow: 10988 case Builtin::BI__builtin_smull_overflow: 10989 case Builtin::BI__builtin_smulll_overflow: { 10990 LValue ResultLValue; 10991 APSInt LHS, RHS; 10992 10993 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 10994 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 10995 !EvaluateInteger(E->getArg(1), RHS, Info) || 10996 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 10997 return false; 10998 10999 APSInt Result; 11000 bool DidOverflow = false; 11001 11002 // If the types don't have to match, enlarge all 3 to the largest of them. 11003 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11004 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11005 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11006 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11007 ResultType->isSignedIntegerOrEnumerationType(); 11008 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11009 ResultType->isSignedIntegerOrEnumerationType(); 11010 uint64_t LHSSize = LHS.getBitWidth(); 11011 uint64_t RHSSize = RHS.getBitWidth(); 11012 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11013 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11014 11015 // Add an additional bit if the signedness isn't uniformly agreed to. We 11016 // could do this ONLY if there is a signed and an unsigned that both have 11017 // MaxBits, but the code to check that is pretty nasty. The issue will be 11018 // caught in the shrink-to-result later anyway. 11019 if (IsSigned && !AllSigned) 11020 ++MaxBits; 11021 11022 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11023 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11024 Result = APSInt(MaxBits, !IsSigned); 11025 } 11026 11027 // Find largest int. 11028 switch (BuiltinOp) { 11029 default: 11030 llvm_unreachable("Invalid value for BuiltinOp"); 11031 case Builtin::BI__builtin_add_overflow: 11032 case Builtin::BI__builtin_sadd_overflow: 11033 case Builtin::BI__builtin_saddl_overflow: 11034 case Builtin::BI__builtin_saddll_overflow: 11035 case Builtin::BI__builtin_uadd_overflow: 11036 case Builtin::BI__builtin_uaddl_overflow: 11037 case Builtin::BI__builtin_uaddll_overflow: 11038 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11039 : LHS.uadd_ov(RHS, DidOverflow); 11040 break; 11041 case Builtin::BI__builtin_sub_overflow: 11042 case Builtin::BI__builtin_ssub_overflow: 11043 case Builtin::BI__builtin_ssubl_overflow: 11044 case Builtin::BI__builtin_ssubll_overflow: 11045 case Builtin::BI__builtin_usub_overflow: 11046 case Builtin::BI__builtin_usubl_overflow: 11047 case Builtin::BI__builtin_usubll_overflow: 11048 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11049 : LHS.usub_ov(RHS, DidOverflow); 11050 break; 11051 case Builtin::BI__builtin_mul_overflow: 11052 case Builtin::BI__builtin_smul_overflow: 11053 case Builtin::BI__builtin_smull_overflow: 11054 case Builtin::BI__builtin_smulll_overflow: 11055 case Builtin::BI__builtin_umul_overflow: 11056 case Builtin::BI__builtin_umull_overflow: 11057 case Builtin::BI__builtin_umulll_overflow: 11058 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11059 : LHS.umul_ov(RHS, DidOverflow); 11060 break; 11061 } 11062 11063 // In the case where multiple sizes are allowed, truncate and see if 11064 // the values are the same. 11065 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11066 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11067 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11068 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11069 // since it will give us the behavior of a TruncOrSelf in the case where 11070 // its parameter <= its size. We previously set Result to be at least the 11071 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11072 // will work exactly like TruncOrSelf. 11073 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11074 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 11075 11076 if (!APSInt::isSameValue(Temp, Result)) 11077 DidOverflow = true; 11078 Result = Temp; 11079 } 11080 11081 APValue APV{Result}; 11082 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 11083 return false; 11084 return Success(DidOverflow, E); 11085 } 11086 } 11087 } 11088 11089 /// Determine whether this is a pointer past the end of the complete 11090 /// object referred to by the lvalue. 11091 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 11092 const LValue &LV) { 11093 // A null pointer can be viewed as being "past the end" but we don't 11094 // choose to look at it that way here. 11095 if (!LV.getLValueBase()) 11096 return false; 11097 11098 // If the designator is valid and refers to a subobject, we're not pointing 11099 // past the end. 11100 if (!LV.getLValueDesignator().Invalid && 11101 !LV.getLValueDesignator().isOnePastTheEnd()) 11102 return false; 11103 11104 // A pointer to an incomplete type might be past-the-end if the type's size is 11105 // zero. We cannot tell because the type is incomplete. 11106 QualType Ty = getType(LV.getLValueBase()); 11107 if (Ty->isIncompleteType()) 11108 return true; 11109 11110 // We're a past-the-end pointer if we point to the byte after the object, 11111 // no matter what our type or path is. 11112 auto Size = Ctx.getTypeSizeInChars(Ty); 11113 return LV.getLValueOffset() == Size; 11114 } 11115 11116 namespace { 11117 11118 /// Data recursive integer evaluator of certain binary operators. 11119 /// 11120 /// We use a data recursive algorithm for binary operators so that we are able 11121 /// to handle extreme cases of chained binary operators without causing stack 11122 /// overflow. 11123 class DataRecursiveIntBinOpEvaluator { 11124 struct EvalResult { 11125 APValue Val; 11126 bool Failed; 11127 11128 EvalResult() : Failed(false) { } 11129 11130 void swap(EvalResult &RHS) { 11131 Val.swap(RHS.Val); 11132 Failed = RHS.Failed; 11133 RHS.Failed = false; 11134 } 11135 }; 11136 11137 struct Job { 11138 const Expr *E; 11139 EvalResult LHSResult; // meaningful only for binary operator expression. 11140 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 11141 11142 Job() = default; 11143 Job(Job &&) = default; 11144 11145 void startSpeculativeEval(EvalInfo &Info) { 11146 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 11147 } 11148 11149 private: 11150 SpeculativeEvaluationRAII SpecEvalRAII; 11151 }; 11152 11153 SmallVector<Job, 16> Queue; 11154 11155 IntExprEvaluator &IntEval; 11156 EvalInfo &Info; 11157 APValue &FinalResult; 11158 11159 public: 11160 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 11161 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 11162 11163 /// True if \param E is a binary operator that we are going to handle 11164 /// data recursively. 11165 /// We handle binary operators that are comma, logical, or that have operands 11166 /// with integral or enumeration type. 11167 static bool shouldEnqueue(const BinaryOperator *E) { 11168 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 11169 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 11170 E->getLHS()->getType()->isIntegralOrEnumerationType() && 11171 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11172 } 11173 11174 bool Traverse(const BinaryOperator *E) { 11175 enqueue(E); 11176 EvalResult PrevResult; 11177 while (!Queue.empty()) 11178 process(PrevResult); 11179 11180 if (PrevResult.Failed) return false; 11181 11182 FinalResult.swap(PrevResult.Val); 11183 return true; 11184 } 11185 11186 private: 11187 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11188 return IntEval.Success(Value, E, Result); 11189 } 11190 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 11191 return IntEval.Success(Value, E, Result); 11192 } 11193 bool Error(const Expr *E) { 11194 return IntEval.Error(E); 11195 } 11196 bool Error(const Expr *E, diag::kind D) { 11197 return IntEval.Error(E, D); 11198 } 11199 11200 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 11201 return Info.CCEDiag(E, D); 11202 } 11203 11204 // Returns true if visiting the RHS is necessary, false otherwise. 11205 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11206 bool &SuppressRHSDiags); 11207 11208 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11209 const BinaryOperator *E, APValue &Result); 11210 11211 void EvaluateExpr(const Expr *E, EvalResult &Result) { 11212 Result.Failed = !Evaluate(Result.Val, Info, E); 11213 if (Result.Failed) 11214 Result.Val = APValue(); 11215 } 11216 11217 void process(EvalResult &Result); 11218 11219 void enqueue(const Expr *E) { 11220 E = E->IgnoreParens(); 11221 Queue.resize(Queue.size()+1); 11222 Queue.back().E = E; 11223 Queue.back().Kind = Job::AnyExprKind; 11224 } 11225 }; 11226 11227 } 11228 11229 bool DataRecursiveIntBinOpEvaluator:: 11230 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11231 bool &SuppressRHSDiags) { 11232 if (E->getOpcode() == BO_Comma) { 11233 // Ignore LHS but note if we could not evaluate it. 11234 if (LHSResult.Failed) 11235 return Info.noteSideEffect(); 11236 return true; 11237 } 11238 11239 if (E->isLogicalOp()) { 11240 bool LHSAsBool; 11241 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 11242 // We were able to evaluate the LHS, see if we can get away with not 11243 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 11244 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 11245 Success(LHSAsBool, E, LHSResult.Val); 11246 return false; // Ignore RHS 11247 } 11248 } else { 11249 LHSResult.Failed = true; 11250 11251 // Since we weren't able to evaluate the left hand side, it 11252 // might have had side effects. 11253 if (!Info.noteSideEffect()) 11254 return false; 11255 11256 // We can't evaluate the LHS; however, sometimes the result 11257 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11258 // Don't ignore RHS and suppress diagnostics from this arm. 11259 SuppressRHSDiags = true; 11260 } 11261 11262 return true; 11263 } 11264 11265 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11266 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11267 11268 if (LHSResult.Failed && !Info.noteFailure()) 11269 return false; // Ignore RHS; 11270 11271 return true; 11272 } 11273 11274 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 11275 bool IsSub) { 11276 // Compute the new offset in the appropriate width, wrapping at 64 bits. 11277 // FIXME: When compiling for a 32-bit target, we should use 32-bit 11278 // offsets. 11279 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 11280 CharUnits &Offset = LVal.getLValueOffset(); 11281 uint64_t Offset64 = Offset.getQuantity(); 11282 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 11283 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 11284 : Offset64 + Index64); 11285 } 11286 11287 bool DataRecursiveIntBinOpEvaluator:: 11288 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11289 const BinaryOperator *E, APValue &Result) { 11290 if (E->getOpcode() == BO_Comma) { 11291 if (RHSResult.Failed) 11292 return false; 11293 Result = RHSResult.Val; 11294 return true; 11295 } 11296 11297 if (E->isLogicalOp()) { 11298 bool lhsResult, rhsResult; 11299 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 11300 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 11301 11302 if (LHSIsOK) { 11303 if (RHSIsOK) { 11304 if (E->getOpcode() == BO_LOr) 11305 return Success(lhsResult || rhsResult, E, Result); 11306 else 11307 return Success(lhsResult && rhsResult, E, Result); 11308 } 11309 } else { 11310 if (RHSIsOK) { 11311 // We can't evaluate the LHS; however, sometimes the result 11312 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11313 if (rhsResult == (E->getOpcode() == BO_LOr)) 11314 return Success(rhsResult, E, Result); 11315 } 11316 } 11317 11318 return false; 11319 } 11320 11321 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11322 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11323 11324 if (LHSResult.Failed || RHSResult.Failed) 11325 return false; 11326 11327 const APValue &LHSVal = LHSResult.Val; 11328 const APValue &RHSVal = RHSResult.Val; 11329 11330 // Handle cases like (unsigned long)&a + 4. 11331 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 11332 Result = LHSVal; 11333 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 11334 return true; 11335 } 11336 11337 // Handle cases like 4 + (unsigned long)&a 11338 if (E->getOpcode() == BO_Add && 11339 RHSVal.isLValue() && LHSVal.isInt()) { 11340 Result = RHSVal; 11341 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 11342 return true; 11343 } 11344 11345 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 11346 // Handle (intptr_t)&&A - (intptr_t)&&B. 11347 if (!LHSVal.getLValueOffset().isZero() || 11348 !RHSVal.getLValueOffset().isZero()) 11349 return false; 11350 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 11351 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 11352 if (!LHSExpr || !RHSExpr) 11353 return false; 11354 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 11355 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 11356 if (!LHSAddrExpr || !RHSAddrExpr) 11357 return false; 11358 // Make sure both labels come from the same function. 11359 if (LHSAddrExpr->getLabel()->getDeclContext() != 11360 RHSAddrExpr->getLabel()->getDeclContext()) 11361 return false; 11362 Result = APValue(LHSAddrExpr, RHSAddrExpr); 11363 return true; 11364 } 11365 11366 // All the remaining cases expect both operands to be an integer 11367 if (!LHSVal.isInt() || !RHSVal.isInt()) 11368 return Error(E); 11369 11370 // Set up the width and signedness manually, in case it can't be deduced 11371 // from the operation we're performing. 11372 // FIXME: Don't do this in the cases where we can deduce it. 11373 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 11374 E->getType()->isUnsignedIntegerOrEnumerationType()); 11375 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 11376 RHSVal.getInt(), Value)) 11377 return false; 11378 return Success(Value, E, Result); 11379 } 11380 11381 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 11382 Job &job = Queue.back(); 11383 11384 switch (job.Kind) { 11385 case Job::AnyExprKind: { 11386 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 11387 if (shouldEnqueue(Bop)) { 11388 job.Kind = Job::BinOpKind; 11389 enqueue(Bop->getLHS()); 11390 return; 11391 } 11392 } 11393 11394 EvaluateExpr(job.E, Result); 11395 Queue.pop_back(); 11396 return; 11397 } 11398 11399 case Job::BinOpKind: { 11400 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11401 bool SuppressRHSDiags = false; 11402 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 11403 Queue.pop_back(); 11404 return; 11405 } 11406 if (SuppressRHSDiags) 11407 job.startSpeculativeEval(Info); 11408 job.LHSResult.swap(Result); 11409 job.Kind = Job::BinOpVisitedLHSKind; 11410 enqueue(Bop->getRHS()); 11411 return; 11412 } 11413 11414 case Job::BinOpVisitedLHSKind: { 11415 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11416 EvalResult RHS; 11417 RHS.swap(Result); 11418 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 11419 Queue.pop_back(); 11420 return; 11421 } 11422 } 11423 11424 llvm_unreachable("Invalid Job::Kind!"); 11425 } 11426 11427 namespace { 11428 /// Used when we determine that we should fail, but can keep evaluating prior to 11429 /// noting that we had a failure. 11430 class DelayedNoteFailureRAII { 11431 EvalInfo &Info; 11432 bool NoteFailure; 11433 11434 public: 11435 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 11436 : Info(Info), NoteFailure(NoteFailure) {} 11437 ~DelayedNoteFailureRAII() { 11438 if (NoteFailure) { 11439 bool ContinueAfterFailure = Info.noteFailure(); 11440 (void)ContinueAfterFailure; 11441 assert(ContinueAfterFailure && 11442 "Shouldn't have kept evaluating on failure."); 11443 } 11444 } 11445 }; 11446 } 11447 11448 template <class SuccessCB, class AfterCB> 11449 static bool 11450 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 11451 SuccessCB &&Success, AfterCB &&DoAfter) { 11452 assert(E->isComparisonOp() && "expected comparison operator"); 11453 assert((E->getOpcode() == BO_Cmp || 11454 E->getType()->isIntegralOrEnumerationType()) && 11455 "unsupported binary expression evaluation"); 11456 auto Error = [&](const Expr *E) { 11457 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11458 return false; 11459 }; 11460 11461 using CCR = ComparisonCategoryResult; 11462 bool IsRelational = E->isRelationalOp(); 11463 bool IsEquality = E->isEqualityOp(); 11464 if (E->getOpcode() == BO_Cmp) { 11465 const ComparisonCategoryInfo &CmpInfo = 11466 Info.Ctx.CompCategories.getInfoForType(E->getType()); 11467 IsRelational = CmpInfo.isOrdered(); 11468 IsEquality = CmpInfo.isEquality(); 11469 } 11470 11471 QualType LHSTy = E->getLHS()->getType(); 11472 QualType RHSTy = E->getRHS()->getType(); 11473 11474 if (LHSTy->isIntegralOrEnumerationType() && 11475 RHSTy->isIntegralOrEnumerationType()) { 11476 APSInt LHS, RHS; 11477 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 11478 if (!LHSOK && !Info.noteFailure()) 11479 return false; 11480 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 11481 return false; 11482 if (LHS < RHS) 11483 return Success(CCR::Less, E); 11484 if (LHS > RHS) 11485 return Success(CCR::Greater, E); 11486 return Success(CCR::Equal, E); 11487 } 11488 11489 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 11490 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 11491 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 11492 11493 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 11494 if (!LHSOK && !Info.noteFailure()) 11495 return false; 11496 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 11497 return false; 11498 if (LHSFX < RHSFX) 11499 return Success(CCR::Less, E); 11500 if (LHSFX > RHSFX) 11501 return Success(CCR::Greater, E); 11502 return Success(CCR::Equal, E); 11503 } 11504 11505 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 11506 ComplexValue LHS, RHS; 11507 bool LHSOK; 11508 if (E->isAssignmentOp()) { 11509 LValue LV; 11510 EvaluateLValue(E->getLHS(), LV, Info); 11511 LHSOK = false; 11512 } else if (LHSTy->isRealFloatingType()) { 11513 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 11514 if (LHSOK) { 11515 LHS.makeComplexFloat(); 11516 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 11517 } 11518 } else { 11519 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 11520 } 11521 if (!LHSOK && !Info.noteFailure()) 11522 return false; 11523 11524 if (E->getRHS()->getType()->isRealFloatingType()) { 11525 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 11526 return false; 11527 RHS.makeComplexFloat(); 11528 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 11529 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 11530 return false; 11531 11532 if (LHS.isComplexFloat()) { 11533 APFloat::cmpResult CR_r = 11534 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 11535 APFloat::cmpResult CR_i = 11536 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 11537 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 11538 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 11539 } else { 11540 assert(IsEquality && "invalid complex comparison"); 11541 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 11542 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 11543 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 11544 } 11545 } 11546 11547 if (LHSTy->isRealFloatingType() && 11548 RHSTy->isRealFloatingType()) { 11549 APFloat RHS(0.0), LHS(0.0); 11550 11551 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 11552 if (!LHSOK && !Info.noteFailure()) 11553 return false; 11554 11555 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 11556 return false; 11557 11558 assert(E->isComparisonOp() && "Invalid binary operator!"); 11559 auto GetCmpRes = [&]() { 11560 switch (LHS.compare(RHS)) { 11561 case APFloat::cmpEqual: 11562 return CCR::Equal; 11563 case APFloat::cmpLessThan: 11564 return CCR::Less; 11565 case APFloat::cmpGreaterThan: 11566 return CCR::Greater; 11567 case APFloat::cmpUnordered: 11568 return CCR::Unordered; 11569 } 11570 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 11571 }; 11572 return Success(GetCmpRes(), E); 11573 } 11574 11575 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 11576 LValue LHSValue, RHSValue; 11577 11578 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 11579 if (!LHSOK && !Info.noteFailure()) 11580 return false; 11581 11582 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 11583 return false; 11584 11585 // Reject differing bases from the normal codepath; we special-case 11586 // comparisons to null. 11587 if (!HasSameBase(LHSValue, RHSValue)) { 11588 // Inequalities and subtractions between unrelated pointers have 11589 // unspecified or undefined behavior. 11590 if (!IsEquality) 11591 return Error(E); 11592 // A constant address may compare equal to the address of a symbol. 11593 // The one exception is that address of an object cannot compare equal 11594 // to a null pointer constant. 11595 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 11596 (!RHSValue.Base && !RHSValue.Offset.isZero())) 11597 return Error(E); 11598 // It's implementation-defined whether distinct literals will have 11599 // distinct addresses. In clang, the result of such a comparison is 11600 // unspecified, so it is not a constant expression. However, we do know 11601 // that the address of a literal will be non-null. 11602 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 11603 LHSValue.Base && RHSValue.Base) 11604 return Error(E); 11605 // We can't tell whether weak symbols will end up pointing to the same 11606 // object. 11607 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 11608 return Error(E); 11609 // We can't compare the address of the start of one object with the 11610 // past-the-end address of another object, per C++ DR1652. 11611 if ((LHSValue.Base && LHSValue.Offset.isZero() && 11612 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 11613 (RHSValue.Base && RHSValue.Offset.isZero() && 11614 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 11615 return Error(E); 11616 // We can't tell whether an object is at the same address as another 11617 // zero sized object. 11618 if ((RHSValue.Base && isZeroSized(LHSValue)) || 11619 (LHSValue.Base && isZeroSized(RHSValue))) 11620 return Error(E); 11621 return Success(CCR::Nonequal, E); 11622 } 11623 11624 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 11625 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 11626 11627 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 11628 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 11629 11630 // C++11 [expr.rel]p3: 11631 // Pointers to void (after pointer conversions) can be compared, with a 11632 // result defined as follows: If both pointers represent the same 11633 // address or are both the null pointer value, the result is true if the 11634 // operator is <= or >= and false otherwise; otherwise the result is 11635 // unspecified. 11636 // We interpret this as applying to pointers to *cv* void. 11637 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 11638 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 11639 11640 // C++11 [expr.rel]p2: 11641 // - If two pointers point to non-static data members of the same object, 11642 // or to subobjects or array elements fo such members, recursively, the 11643 // pointer to the later declared member compares greater provided the 11644 // two members have the same access control and provided their class is 11645 // not a union. 11646 // [...] 11647 // - Otherwise pointer comparisons are unspecified. 11648 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 11649 bool WasArrayIndex; 11650 unsigned Mismatch = FindDesignatorMismatch( 11651 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 11652 // At the point where the designators diverge, the comparison has a 11653 // specified value if: 11654 // - we are comparing array indices 11655 // - we are comparing fields of a union, or fields with the same access 11656 // Otherwise, the result is unspecified and thus the comparison is not a 11657 // constant expression. 11658 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 11659 Mismatch < RHSDesignator.Entries.size()) { 11660 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 11661 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 11662 if (!LF && !RF) 11663 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 11664 else if (!LF) 11665 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 11666 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 11667 << RF->getParent() << RF; 11668 else if (!RF) 11669 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 11670 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 11671 << LF->getParent() << LF; 11672 else if (!LF->getParent()->isUnion() && 11673 LF->getAccess() != RF->getAccess()) 11674 Info.CCEDiag(E, 11675 diag::note_constexpr_pointer_comparison_differing_access) 11676 << LF << LF->getAccess() << RF << RF->getAccess() 11677 << LF->getParent(); 11678 } 11679 } 11680 11681 // The comparison here must be unsigned, and performed with the same 11682 // width as the pointer. 11683 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 11684 uint64_t CompareLHS = LHSOffset.getQuantity(); 11685 uint64_t CompareRHS = RHSOffset.getQuantity(); 11686 assert(PtrSize <= 64 && "Unexpected pointer width"); 11687 uint64_t Mask = ~0ULL >> (64 - PtrSize); 11688 CompareLHS &= Mask; 11689 CompareRHS &= Mask; 11690 11691 // If there is a base and this is a relational operator, we can only 11692 // compare pointers within the object in question; otherwise, the result 11693 // depends on where the object is located in memory. 11694 if (!LHSValue.Base.isNull() && IsRelational) { 11695 QualType BaseTy = getType(LHSValue.Base); 11696 if (BaseTy->isIncompleteType()) 11697 return Error(E); 11698 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 11699 uint64_t OffsetLimit = Size.getQuantity(); 11700 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 11701 return Error(E); 11702 } 11703 11704 if (CompareLHS < CompareRHS) 11705 return Success(CCR::Less, E); 11706 if (CompareLHS > CompareRHS) 11707 return Success(CCR::Greater, E); 11708 return Success(CCR::Equal, E); 11709 } 11710 11711 if (LHSTy->isMemberPointerType()) { 11712 assert(IsEquality && "unexpected member pointer operation"); 11713 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 11714 11715 MemberPtr LHSValue, RHSValue; 11716 11717 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 11718 if (!LHSOK && !Info.noteFailure()) 11719 return false; 11720 11721 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 11722 return false; 11723 11724 // C++11 [expr.eq]p2: 11725 // If both operands are null, they compare equal. Otherwise if only one is 11726 // null, they compare unequal. 11727 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 11728 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 11729 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 11730 } 11731 11732 // Otherwise if either is a pointer to a virtual member function, the 11733 // result is unspecified. 11734 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 11735 if (MD->isVirtual()) 11736 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 11737 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 11738 if (MD->isVirtual()) 11739 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 11740 11741 // Otherwise they compare equal if and only if they would refer to the 11742 // same member of the same most derived object or the same subobject if 11743 // they were dereferenced with a hypothetical object of the associated 11744 // class type. 11745 bool Equal = LHSValue == RHSValue; 11746 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 11747 } 11748 11749 if (LHSTy->isNullPtrType()) { 11750 assert(E->isComparisonOp() && "unexpected nullptr operation"); 11751 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 11752 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 11753 // are compared, the result is true of the operator is <=, >= or ==, and 11754 // false otherwise. 11755 return Success(CCR::Equal, E); 11756 } 11757 11758 return DoAfter(); 11759 } 11760 11761 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 11762 if (!CheckLiteralType(Info, E)) 11763 return false; 11764 11765 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 11766 const BinaryOperator *E) { 11767 // Evaluation succeeded. Lookup the information for the comparison category 11768 // type and fetch the VarDecl for the result. 11769 const ComparisonCategoryInfo &CmpInfo = 11770 Info.Ctx.CompCategories.getInfoForType(E->getType()); 11771 const VarDecl *VD = 11772 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 11773 // Check and evaluate the result as a constant expression. 11774 LValue LV; 11775 LV.set(VD); 11776 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 11777 return false; 11778 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 11779 }; 11780 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 11781 return ExprEvaluatorBaseTy::VisitBinCmp(E); 11782 }); 11783 } 11784 11785 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11786 // We don't call noteFailure immediately because the assignment happens after 11787 // we evaluate LHS and RHS. 11788 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 11789 return Error(E); 11790 11791 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 11792 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 11793 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 11794 11795 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 11796 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 11797 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 11798 11799 if (E->isComparisonOp()) { 11800 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 11801 // comparisons and then translating the result. 11802 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 11803 const BinaryOperator *E) { 11804 using CCR = ComparisonCategoryResult; 11805 bool IsEqual = ResKind == CCR::Equal, 11806 IsLess = ResKind == CCR::Less, 11807 IsGreater = ResKind == CCR::Greater; 11808 auto Op = E->getOpcode(); 11809 switch (Op) { 11810 default: 11811 llvm_unreachable("unsupported binary operator"); 11812 case BO_EQ: 11813 case BO_NE: 11814 return Success(IsEqual == (Op == BO_EQ), E); 11815 case BO_LT: return Success(IsLess, E); 11816 case BO_GT: return Success(IsGreater, E); 11817 case BO_LE: return Success(IsEqual || IsLess, E); 11818 case BO_GE: return Success(IsEqual || IsGreater, E); 11819 } 11820 }; 11821 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 11822 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11823 }); 11824 } 11825 11826 QualType LHSTy = E->getLHS()->getType(); 11827 QualType RHSTy = E->getRHS()->getType(); 11828 11829 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 11830 E->getOpcode() == BO_Sub) { 11831 LValue LHSValue, RHSValue; 11832 11833 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 11834 if (!LHSOK && !Info.noteFailure()) 11835 return false; 11836 11837 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 11838 return false; 11839 11840 // Reject differing bases from the normal codepath; we special-case 11841 // comparisons to null. 11842 if (!HasSameBase(LHSValue, RHSValue)) { 11843 // Handle &&A - &&B. 11844 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 11845 return Error(E); 11846 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 11847 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 11848 if (!LHSExpr || !RHSExpr) 11849 return Error(E); 11850 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 11851 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 11852 if (!LHSAddrExpr || !RHSAddrExpr) 11853 return Error(E); 11854 // Make sure both labels come from the same function. 11855 if (LHSAddrExpr->getLabel()->getDeclContext() != 11856 RHSAddrExpr->getLabel()->getDeclContext()) 11857 return Error(E); 11858 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 11859 } 11860 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 11861 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 11862 11863 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 11864 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 11865 11866 // C++11 [expr.add]p6: 11867 // Unless both pointers point to elements of the same array object, or 11868 // one past the last element of the array object, the behavior is 11869 // undefined. 11870 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 11871 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 11872 RHSDesignator)) 11873 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 11874 11875 QualType Type = E->getLHS()->getType(); 11876 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 11877 11878 CharUnits ElementSize; 11879 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 11880 return false; 11881 11882 // As an extension, a type may have zero size (empty struct or union in 11883 // C, array of zero length). Pointer subtraction in such cases has 11884 // undefined behavior, so is not constant. 11885 if (ElementSize.isZero()) { 11886 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 11887 << ElementType; 11888 return false; 11889 } 11890 11891 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 11892 // and produce incorrect results when it overflows. Such behavior 11893 // appears to be non-conforming, but is common, so perhaps we should 11894 // assume the standard intended for such cases to be undefined behavior 11895 // and check for them. 11896 11897 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 11898 // overflow in the final conversion to ptrdiff_t. 11899 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 11900 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 11901 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 11902 false); 11903 APSInt TrueResult = (LHS - RHS) / ElemSize; 11904 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 11905 11906 if (Result.extend(65) != TrueResult && 11907 !HandleOverflow(Info, E, TrueResult, E->getType())) 11908 return false; 11909 return Success(Result, E); 11910 } 11911 11912 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11913 } 11914 11915 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 11916 /// a result as the expression's type. 11917 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 11918 const UnaryExprOrTypeTraitExpr *E) { 11919 switch(E->getKind()) { 11920 case UETT_PreferredAlignOf: 11921 case UETT_AlignOf: { 11922 if (E->isArgumentType()) 11923 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 11924 E); 11925 else 11926 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 11927 E); 11928 } 11929 11930 case UETT_VecStep: { 11931 QualType Ty = E->getTypeOfArgument(); 11932 11933 if (Ty->isVectorType()) { 11934 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 11935 11936 // The vec_step built-in functions that take a 3-component 11937 // vector return 4. (OpenCL 1.1 spec 6.11.12) 11938 if (n == 3) 11939 n = 4; 11940 11941 return Success(n, E); 11942 } else 11943 return Success(1, E); 11944 } 11945 11946 case UETT_SizeOf: { 11947 QualType SrcTy = E->getTypeOfArgument(); 11948 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 11949 // the result is the size of the referenced type." 11950 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 11951 SrcTy = Ref->getPointeeType(); 11952 11953 CharUnits Sizeof; 11954 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 11955 return false; 11956 return Success(Sizeof, E); 11957 } 11958 case UETT_OpenMPRequiredSimdAlign: 11959 assert(E->isArgumentType()); 11960 return Success( 11961 Info.Ctx.toCharUnitsFromBits( 11962 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 11963 .getQuantity(), 11964 E); 11965 } 11966 11967 llvm_unreachable("unknown expr/type trait"); 11968 } 11969 11970 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 11971 CharUnits Result; 11972 unsigned n = OOE->getNumComponents(); 11973 if (n == 0) 11974 return Error(OOE); 11975 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 11976 for (unsigned i = 0; i != n; ++i) { 11977 OffsetOfNode ON = OOE->getComponent(i); 11978 switch (ON.getKind()) { 11979 case OffsetOfNode::Array: { 11980 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 11981 APSInt IdxResult; 11982 if (!EvaluateInteger(Idx, IdxResult, Info)) 11983 return false; 11984 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 11985 if (!AT) 11986 return Error(OOE); 11987 CurrentType = AT->getElementType(); 11988 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 11989 Result += IdxResult.getSExtValue() * ElementSize; 11990 break; 11991 } 11992 11993 case OffsetOfNode::Field: { 11994 FieldDecl *MemberDecl = ON.getField(); 11995 const RecordType *RT = CurrentType->getAs<RecordType>(); 11996 if (!RT) 11997 return Error(OOE); 11998 RecordDecl *RD = RT->getDecl(); 11999 if (RD->isInvalidDecl()) return false; 12000 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12001 unsigned i = MemberDecl->getFieldIndex(); 12002 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12003 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12004 CurrentType = MemberDecl->getType().getNonReferenceType(); 12005 break; 12006 } 12007 12008 case OffsetOfNode::Identifier: 12009 llvm_unreachable("dependent __builtin_offsetof"); 12010 12011 case OffsetOfNode::Base: { 12012 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12013 if (BaseSpec->isVirtual()) 12014 return Error(OOE); 12015 12016 // Find the layout of the class whose base we are looking into. 12017 const RecordType *RT = CurrentType->getAs<RecordType>(); 12018 if (!RT) 12019 return Error(OOE); 12020 RecordDecl *RD = RT->getDecl(); 12021 if (RD->isInvalidDecl()) return false; 12022 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12023 12024 // Find the base class itself. 12025 CurrentType = BaseSpec->getType(); 12026 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12027 if (!BaseRT) 12028 return Error(OOE); 12029 12030 // Add the offset to the base. 12031 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12032 break; 12033 } 12034 } 12035 } 12036 return Success(Result, OOE); 12037 } 12038 12039 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12040 switch (E->getOpcode()) { 12041 default: 12042 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12043 // See C99 6.6p3. 12044 return Error(E); 12045 case UO_Extension: 12046 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12047 // If so, we could clear the diagnostic ID. 12048 return Visit(E->getSubExpr()); 12049 case UO_Plus: 12050 // The result is just the value. 12051 return Visit(E->getSubExpr()); 12052 case UO_Minus: { 12053 if (!Visit(E->getSubExpr())) 12054 return false; 12055 if (!Result.isInt()) return Error(E); 12056 const APSInt &Value = Result.getInt(); 12057 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 12058 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 12059 E->getType())) 12060 return false; 12061 return Success(-Value, E); 12062 } 12063 case UO_Not: { 12064 if (!Visit(E->getSubExpr())) 12065 return false; 12066 if (!Result.isInt()) return Error(E); 12067 return Success(~Result.getInt(), E); 12068 } 12069 case UO_LNot: { 12070 bool bres; 12071 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12072 return false; 12073 return Success(!bres, E); 12074 } 12075 } 12076 } 12077 12078 /// HandleCast - This is used to evaluate implicit or explicit casts where the 12079 /// result type is integer. 12080 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 12081 const Expr *SubExpr = E->getSubExpr(); 12082 QualType DestType = E->getType(); 12083 QualType SrcType = SubExpr->getType(); 12084 12085 switch (E->getCastKind()) { 12086 case CK_BaseToDerived: 12087 case CK_DerivedToBase: 12088 case CK_UncheckedDerivedToBase: 12089 case CK_Dynamic: 12090 case CK_ToUnion: 12091 case CK_ArrayToPointerDecay: 12092 case CK_FunctionToPointerDecay: 12093 case CK_NullToPointer: 12094 case CK_NullToMemberPointer: 12095 case CK_BaseToDerivedMemberPointer: 12096 case CK_DerivedToBaseMemberPointer: 12097 case CK_ReinterpretMemberPointer: 12098 case CK_ConstructorConversion: 12099 case CK_IntegralToPointer: 12100 case CK_ToVoid: 12101 case CK_VectorSplat: 12102 case CK_IntegralToFloating: 12103 case CK_FloatingCast: 12104 case CK_CPointerToObjCPointerCast: 12105 case CK_BlockPointerToObjCPointerCast: 12106 case CK_AnyPointerToBlockPointerCast: 12107 case CK_ObjCObjectLValueCast: 12108 case CK_FloatingRealToComplex: 12109 case CK_FloatingComplexToReal: 12110 case CK_FloatingComplexCast: 12111 case CK_FloatingComplexToIntegralComplex: 12112 case CK_IntegralRealToComplex: 12113 case CK_IntegralComplexCast: 12114 case CK_IntegralComplexToFloatingComplex: 12115 case CK_BuiltinFnToFnPtr: 12116 case CK_ZeroToOCLOpaqueType: 12117 case CK_NonAtomicToAtomic: 12118 case CK_AddressSpaceConversion: 12119 case CK_IntToOCLSampler: 12120 case CK_FixedPointCast: 12121 case CK_IntegralToFixedPoint: 12122 llvm_unreachable("invalid cast kind for integral value"); 12123 12124 case CK_BitCast: 12125 case CK_Dependent: 12126 case CK_LValueBitCast: 12127 case CK_ARCProduceObject: 12128 case CK_ARCConsumeObject: 12129 case CK_ARCReclaimReturnedObject: 12130 case CK_ARCExtendBlockObject: 12131 case CK_CopyAndAutoreleaseBlockObject: 12132 return Error(E); 12133 12134 case CK_UserDefinedConversion: 12135 case CK_LValueToRValue: 12136 case CK_AtomicToNonAtomic: 12137 case CK_NoOp: 12138 case CK_LValueToRValueBitCast: 12139 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12140 12141 case CK_MemberPointerToBoolean: 12142 case CK_PointerToBoolean: 12143 case CK_IntegralToBoolean: 12144 case CK_FloatingToBoolean: 12145 case CK_BooleanToSignedIntegral: 12146 case CK_FloatingComplexToBoolean: 12147 case CK_IntegralComplexToBoolean: { 12148 bool BoolResult; 12149 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 12150 return false; 12151 uint64_t IntResult = BoolResult; 12152 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 12153 IntResult = (uint64_t)-1; 12154 return Success(IntResult, E); 12155 } 12156 12157 case CK_FixedPointToIntegral: { 12158 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 12159 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12160 return false; 12161 bool Overflowed; 12162 llvm::APSInt Result = Src.convertToInt( 12163 Info.Ctx.getIntWidth(DestType), 12164 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 12165 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12166 return false; 12167 return Success(Result, E); 12168 } 12169 12170 case CK_FixedPointToBoolean: { 12171 // Unsigned padding does not affect this. 12172 APValue Val; 12173 if (!Evaluate(Val, Info, SubExpr)) 12174 return false; 12175 return Success(Val.getFixedPoint().getBoolValue(), E); 12176 } 12177 12178 case CK_IntegralCast: { 12179 if (!Visit(SubExpr)) 12180 return false; 12181 12182 if (!Result.isInt()) { 12183 // Allow casts of address-of-label differences if they are no-ops 12184 // or narrowing. (The narrowing case isn't actually guaranteed to 12185 // be constant-evaluatable except in some narrow cases which are hard 12186 // to detect here. We let it through on the assumption the user knows 12187 // what they are doing.) 12188 if (Result.isAddrLabelDiff()) 12189 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 12190 // Only allow casts of lvalues if they are lossless. 12191 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 12192 } 12193 12194 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 12195 Result.getInt()), E); 12196 } 12197 12198 case CK_PointerToIntegral: { 12199 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 12200 12201 LValue LV; 12202 if (!EvaluatePointer(SubExpr, LV, Info)) 12203 return false; 12204 12205 if (LV.getLValueBase()) { 12206 // Only allow based lvalue casts if they are lossless. 12207 // FIXME: Allow a larger integer size than the pointer size, and allow 12208 // narrowing back down to pointer width in subsequent integral casts. 12209 // FIXME: Check integer type's active bits, not its type size. 12210 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 12211 return Error(E); 12212 12213 LV.Designator.setInvalid(); 12214 LV.moveInto(Result); 12215 return true; 12216 } 12217 12218 APSInt AsInt; 12219 APValue V; 12220 LV.moveInto(V); 12221 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 12222 llvm_unreachable("Can't cast this!"); 12223 12224 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 12225 } 12226 12227 case CK_IntegralComplexToReal: { 12228 ComplexValue C; 12229 if (!EvaluateComplex(SubExpr, C, Info)) 12230 return false; 12231 return Success(C.getComplexIntReal(), E); 12232 } 12233 12234 case CK_FloatingToIntegral: { 12235 APFloat F(0.0); 12236 if (!EvaluateFloat(SubExpr, F, Info)) 12237 return false; 12238 12239 APSInt Value; 12240 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 12241 return false; 12242 return Success(Value, E); 12243 } 12244 } 12245 12246 llvm_unreachable("unknown cast resulting in integral value"); 12247 } 12248 12249 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 12250 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12251 ComplexValue LV; 12252 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12253 return false; 12254 if (!LV.isComplexInt()) 12255 return Error(E); 12256 return Success(LV.getComplexIntReal(), E); 12257 } 12258 12259 return Visit(E->getSubExpr()); 12260 } 12261 12262 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 12263 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 12264 ComplexValue LV; 12265 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12266 return false; 12267 if (!LV.isComplexInt()) 12268 return Error(E); 12269 return Success(LV.getComplexIntImag(), E); 12270 } 12271 12272 VisitIgnoredValue(E->getSubExpr()); 12273 return Success(0, E); 12274 } 12275 12276 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 12277 return Success(E->getPackLength(), E); 12278 } 12279 12280 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 12281 return Success(E->getValue(), E); 12282 } 12283 12284 bool IntExprEvaluator::VisitConceptSpecializationExpr( 12285 const ConceptSpecializationExpr *E) { 12286 return Success(E->isSatisfied(), E); 12287 } 12288 12289 12290 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12291 switch (E->getOpcode()) { 12292 default: 12293 // Invalid unary operators 12294 return Error(E); 12295 case UO_Plus: 12296 // The result is just the value. 12297 return Visit(E->getSubExpr()); 12298 case UO_Minus: { 12299 if (!Visit(E->getSubExpr())) return false; 12300 if (!Result.isFixedPoint()) 12301 return Error(E); 12302 bool Overflowed; 12303 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 12304 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 12305 return false; 12306 return Success(Negated, E); 12307 } 12308 case UO_LNot: { 12309 bool bres; 12310 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12311 return false; 12312 return Success(!bres, E); 12313 } 12314 } 12315 } 12316 12317 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 12318 const Expr *SubExpr = E->getSubExpr(); 12319 QualType DestType = E->getType(); 12320 assert(DestType->isFixedPointType() && 12321 "Expected destination type to be a fixed point type"); 12322 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 12323 12324 switch (E->getCastKind()) { 12325 case CK_FixedPointCast: { 12326 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 12327 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12328 return false; 12329 bool Overflowed; 12330 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 12331 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12332 return false; 12333 return Success(Result, E); 12334 } 12335 case CK_IntegralToFixedPoint: { 12336 APSInt Src; 12337 if (!EvaluateInteger(SubExpr, Src, Info)) 12338 return false; 12339 12340 bool Overflowed; 12341 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 12342 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 12343 12344 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType)) 12345 return false; 12346 12347 return Success(IntResult, E); 12348 } 12349 case CK_NoOp: 12350 case CK_LValueToRValue: 12351 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12352 default: 12353 return Error(E); 12354 } 12355 } 12356 12357 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12358 const Expr *LHS = E->getLHS(); 12359 const Expr *RHS = E->getRHS(); 12360 FixedPointSemantics ResultFXSema = 12361 Info.Ctx.getFixedPointSemantics(E->getType()); 12362 12363 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 12364 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 12365 return false; 12366 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 12367 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 12368 return false; 12369 12370 switch (E->getOpcode()) { 12371 case BO_Add: { 12372 bool AddOverflow, ConversionOverflow; 12373 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow) 12374 .convert(ResultFXSema, &ConversionOverflow); 12375 if ((AddOverflow || ConversionOverflow) && 12376 !HandleOverflow(Info, E, Result, E->getType())) 12377 return false; 12378 return Success(Result, E); 12379 } 12380 default: 12381 return false; 12382 } 12383 llvm_unreachable("Should've exited before this"); 12384 } 12385 12386 //===----------------------------------------------------------------------===// 12387 // Float Evaluation 12388 //===----------------------------------------------------------------------===// 12389 12390 namespace { 12391 class FloatExprEvaluator 12392 : public ExprEvaluatorBase<FloatExprEvaluator> { 12393 APFloat &Result; 12394 public: 12395 FloatExprEvaluator(EvalInfo &info, APFloat &result) 12396 : ExprEvaluatorBaseTy(info), Result(result) {} 12397 12398 bool Success(const APValue &V, const Expr *e) { 12399 Result = V.getFloat(); 12400 return true; 12401 } 12402 12403 bool ZeroInitialization(const Expr *E) { 12404 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 12405 return true; 12406 } 12407 12408 bool VisitCallExpr(const CallExpr *E); 12409 12410 bool VisitUnaryOperator(const UnaryOperator *E); 12411 bool VisitBinaryOperator(const BinaryOperator *E); 12412 bool VisitFloatingLiteral(const FloatingLiteral *E); 12413 bool VisitCastExpr(const CastExpr *E); 12414 12415 bool VisitUnaryReal(const UnaryOperator *E); 12416 bool VisitUnaryImag(const UnaryOperator *E); 12417 12418 // FIXME: Missing: array subscript of vector, member of vector 12419 }; 12420 } // end anonymous namespace 12421 12422 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 12423 assert(E->isRValue() && E->getType()->isRealFloatingType()); 12424 return FloatExprEvaluator(Info, Result).Visit(E); 12425 } 12426 12427 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 12428 QualType ResultTy, 12429 const Expr *Arg, 12430 bool SNaN, 12431 llvm::APFloat &Result) { 12432 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 12433 if (!S) return false; 12434 12435 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 12436 12437 llvm::APInt fill; 12438 12439 // Treat empty strings as if they were zero. 12440 if (S->getString().empty()) 12441 fill = llvm::APInt(32, 0); 12442 else if (S->getString().getAsInteger(0, fill)) 12443 return false; 12444 12445 if (Context.getTargetInfo().isNan2008()) { 12446 if (SNaN) 12447 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 12448 else 12449 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 12450 } else { 12451 // Prior to IEEE 754-2008, architectures were allowed to choose whether 12452 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 12453 // a different encoding to what became a standard in 2008, and for pre- 12454 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 12455 // sNaN. This is now known as "legacy NaN" encoding. 12456 if (SNaN) 12457 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 12458 else 12459 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 12460 } 12461 12462 return true; 12463 } 12464 12465 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 12466 switch (E->getBuiltinCallee()) { 12467 default: 12468 return ExprEvaluatorBaseTy::VisitCallExpr(E); 12469 12470 case Builtin::BI__builtin_huge_val: 12471 case Builtin::BI__builtin_huge_valf: 12472 case Builtin::BI__builtin_huge_vall: 12473 case Builtin::BI__builtin_huge_valf128: 12474 case Builtin::BI__builtin_inf: 12475 case Builtin::BI__builtin_inff: 12476 case Builtin::BI__builtin_infl: 12477 case Builtin::BI__builtin_inff128: { 12478 const llvm::fltSemantics &Sem = 12479 Info.Ctx.getFloatTypeSemantics(E->getType()); 12480 Result = llvm::APFloat::getInf(Sem); 12481 return true; 12482 } 12483 12484 case Builtin::BI__builtin_nans: 12485 case Builtin::BI__builtin_nansf: 12486 case Builtin::BI__builtin_nansl: 12487 case Builtin::BI__builtin_nansf128: 12488 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 12489 true, Result)) 12490 return Error(E); 12491 return true; 12492 12493 case Builtin::BI__builtin_nan: 12494 case Builtin::BI__builtin_nanf: 12495 case Builtin::BI__builtin_nanl: 12496 case Builtin::BI__builtin_nanf128: 12497 // If this is __builtin_nan() turn this into a nan, otherwise we 12498 // can't constant fold it. 12499 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 12500 false, Result)) 12501 return Error(E); 12502 return true; 12503 12504 case Builtin::BI__builtin_fabs: 12505 case Builtin::BI__builtin_fabsf: 12506 case Builtin::BI__builtin_fabsl: 12507 case Builtin::BI__builtin_fabsf128: 12508 if (!EvaluateFloat(E->getArg(0), Result, Info)) 12509 return false; 12510 12511 if (Result.isNegative()) 12512 Result.changeSign(); 12513 return true; 12514 12515 // FIXME: Builtin::BI__builtin_powi 12516 // FIXME: Builtin::BI__builtin_powif 12517 // FIXME: Builtin::BI__builtin_powil 12518 12519 case Builtin::BI__builtin_copysign: 12520 case Builtin::BI__builtin_copysignf: 12521 case Builtin::BI__builtin_copysignl: 12522 case Builtin::BI__builtin_copysignf128: { 12523 APFloat RHS(0.); 12524 if (!EvaluateFloat(E->getArg(0), Result, Info) || 12525 !EvaluateFloat(E->getArg(1), RHS, Info)) 12526 return false; 12527 Result.copySign(RHS); 12528 return true; 12529 } 12530 } 12531 } 12532 12533 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 12534 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12535 ComplexValue CV; 12536 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 12537 return false; 12538 Result = CV.FloatReal; 12539 return true; 12540 } 12541 12542 return Visit(E->getSubExpr()); 12543 } 12544 12545 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 12546 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12547 ComplexValue CV; 12548 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 12549 return false; 12550 Result = CV.FloatImag; 12551 return true; 12552 } 12553 12554 VisitIgnoredValue(E->getSubExpr()); 12555 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 12556 Result = llvm::APFloat::getZero(Sem); 12557 return true; 12558 } 12559 12560 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12561 switch (E->getOpcode()) { 12562 default: return Error(E); 12563 case UO_Plus: 12564 return EvaluateFloat(E->getSubExpr(), Result, Info); 12565 case UO_Minus: 12566 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 12567 return false; 12568 Result.changeSign(); 12569 return true; 12570 } 12571 } 12572 12573 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12574 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 12575 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12576 12577 APFloat RHS(0.0); 12578 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 12579 if (!LHSOK && !Info.noteFailure()) 12580 return false; 12581 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 12582 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 12583 } 12584 12585 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 12586 Result = E->getValue(); 12587 return true; 12588 } 12589 12590 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 12591 const Expr* SubExpr = E->getSubExpr(); 12592 12593 switch (E->getCastKind()) { 12594 default: 12595 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12596 12597 case CK_IntegralToFloating: { 12598 APSInt IntResult; 12599 return EvaluateInteger(SubExpr, IntResult, Info) && 12600 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 12601 E->getType(), Result); 12602 } 12603 12604 case CK_FloatingCast: { 12605 if (!Visit(SubExpr)) 12606 return false; 12607 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 12608 Result); 12609 } 12610 12611 case CK_FloatingComplexToReal: { 12612 ComplexValue V; 12613 if (!EvaluateComplex(SubExpr, V, Info)) 12614 return false; 12615 Result = V.getComplexFloatReal(); 12616 return true; 12617 } 12618 } 12619 } 12620 12621 //===----------------------------------------------------------------------===// 12622 // Complex Evaluation (for float and integer) 12623 //===----------------------------------------------------------------------===// 12624 12625 namespace { 12626 class ComplexExprEvaluator 12627 : public ExprEvaluatorBase<ComplexExprEvaluator> { 12628 ComplexValue &Result; 12629 12630 public: 12631 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 12632 : ExprEvaluatorBaseTy(info), Result(Result) {} 12633 12634 bool Success(const APValue &V, const Expr *e) { 12635 Result.setFrom(V); 12636 return true; 12637 } 12638 12639 bool ZeroInitialization(const Expr *E); 12640 12641 //===--------------------------------------------------------------------===// 12642 // Visitor Methods 12643 //===--------------------------------------------------------------------===// 12644 12645 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 12646 bool VisitCastExpr(const CastExpr *E); 12647 bool VisitBinaryOperator(const BinaryOperator *E); 12648 bool VisitUnaryOperator(const UnaryOperator *E); 12649 bool VisitInitListExpr(const InitListExpr *E); 12650 }; 12651 } // end anonymous namespace 12652 12653 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 12654 EvalInfo &Info) { 12655 assert(E->isRValue() && E->getType()->isAnyComplexType()); 12656 return ComplexExprEvaluator(Info, Result).Visit(E); 12657 } 12658 12659 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 12660 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 12661 if (ElemTy->isRealFloatingType()) { 12662 Result.makeComplexFloat(); 12663 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 12664 Result.FloatReal = Zero; 12665 Result.FloatImag = Zero; 12666 } else { 12667 Result.makeComplexInt(); 12668 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 12669 Result.IntReal = Zero; 12670 Result.IntImag = Zero; 12671 } 12672 return true; 12673 } 12674 12675 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 12676 const Expr* SubExpr = E->getSubExpr(); 12677 12678 if (SubExpr->getType()->isRealFloatingType()) { 12679 Result.makeComplexFloat(); 12680 APFloat &Imag = Result.FloatImag; 12681 if (!EvaluateFloat(SubExpr, Imag, Info)) 12682 return false; 12683 12684 Result.FloatReal = APFloat(Imag.getSemantics()); 12685 return true; 12686 } else { 12687 assert(SubExpr->getType()->isIntegerType() && 12688 "Unexpected imaginary literal."); 12689 12690 Result.makeComplexInt(); 12691 APSInt &Imag = Result.IntImag; 12692 if (!EvaluateInteger(SubExpr, Imag, Info)) 12693 return false; 12694 12695 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 12696 return true; 12697 } 12698 } 12699 12700 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 12701 12702 switch (E->getCastKind()) { 12703 case CK_BitCast: 12704 case CK_BaseToDerived: 12705 case CK_DerivedToBase: 12706 case CK_UncheckedDerivedToBase: 12707 case CK_Dynamic: 12708 case CK_ToUnion: 12709 case CK_ArrayToPointerDecay: 12710 case CK_FunctionToPointerDecay: 12711 case CK_NullToPointer: 12712 case CK_NullToMemberPointer: 12713 case CK_BaseToDerivedMemberPointer: 12714 case CK_DerivedToBaseMemberPointer: 12715 case CK_MemberPointerToBoolean: 12716 case CK_ReinterpretMemberPointer: 12717 case CK_ConstructorConversion: 12718 case CK_IntegralToPointer: 12719 case CK_PointerToIntegral: 12720 case CK_PointerToBoolean: 12721 case CK_ToVoid: 12722 case CK_VectorSplat: 12723 case CK_IntegralCast: 12724 case CK_BooleanToSignedIntegral: 12725 case CK_IntegralToBoolean: 12726 case CK_IntegralToFloating: 12727 case CK_FloatingToIntegral: 12728 case CK_FloatingToBoolean: 12729 case CK_FloatingCast: 12730 case CK_CPointerToObjCPointerCast: 12731 case CK_BlockPointerToObjCPointerCast: 12732 case CK_AnyPointerToBlockPointerCast: 12733 case CK_ObjCObjectLValueCast: 12734 case CK_FloatingComplexToReal: 12735 case CK_FloatingComplexToBoolean: 12736 case CK_IntegralComplexToReal: 12737 case CK_IntegralComplexToBoolean: 12738 case CK_ARCProduceObject: 12739 case CK_ARCConsumeObject: 12740 case CK_ARCReclaimReturnedObject: 12741 case CK_ARCExtendBlockObject: 12742 case CK_CopyAndAutoreleaseBlockObject: 12743 case CK_BuiltinFnToFnPtr: 12744 case CK_ZeroToOCLOpaqueType: 12745 case CK_NonAtomicToAtomic: 12746 case CK_AddressSpaceConversion: 12747 case CK_IntToOCLSampler: 12748 case CK_FixedPointCast: 12749 case CK_FixedPointToBoolean: 12750 case CK_FixedPointToIntegral: 12751 case CK_IntegralToFixedPoint: 12752 llvm_unreachable("invalid cast kind for complex value"); 12753 12754 case CK_LValueToRValue: 12755 case CK_AtomicToNonAtomic: 12756 case CK_NoOp: 12757 case CK_LValueToRValueBitCast: 12758 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12759 12760 case CK_Dependent: 12761 case CK_LValueBitCast: 12762 case CK_UserDefinedConversion: 12763 return Error(E); 12764 12765 case CK_FloatingRealToComplex: { 12766 APFloat &Real = Result.FloatReal; 12767 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 12768 return false; 12769 12770 Result.makeComplexFloat(); 12771 Result.FloatImag = APFloat(Real.getSemantics()); 12772 return true; 12773 } 12774 12775 case CK_FloatingComplexCast: { 12776 if (!Visit(E->getSubExpr())) 12777 return false; 12778 12779 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 12780 QualType From 12781 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 12782 12783 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 12784 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 12785 } 12786 12787 case CK_FloatingComplexToIntegralComplex: { 12788 if (!Visit(E->getSubExpr())) 12789 return false; 12790 12791 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 12792 QualType From 12793 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 12794 Result.makeComplexInt(); 12795 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 12796 To, Result.IntReal) && 12797 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 12798 To, Result.IntImag); 12799 } 12800 12801 case CK_IntegralRealToComplex: { 12802 APSInt &Real = Result.IntReal; 12803 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 12804 return false; 12805 12806 Result.makeComplexInt(); 12807 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 12808 return true; 12809 } 12810 12811 case CK_IntegralComplexCast: { 12812 if (!Visit(E->getSubExpr())) 12813 return false; 12814 12815 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 12816 QualType From 12817 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 12818 12819 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 12820 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 12821 return true; 12822 } 12823 12824 case CK_IntegralComplexToFloatingComplex: { 12825 if (!Visit(E->getSubExpr())) 12826 return false; 12827 12828 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 12829 QualType From 12830 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 12831 Result.makeComplexFloat(); 12832 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 12833 To, Result.FloatReal) && 12834 HandleIntToFloatCast(Info, E, From, Result.IntImag, 12835 To, Result.FloatImag); 12836 } 12837 } 12838 12839 llvm_unreachable("unknown cast resulting in complex value"); 12840 } 12841 12842 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12843 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 12844 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12845 12846 // Track whether the LHS or RHS is real at the type system level. When this is 12847 // the case we can simplify our evaluation strategy. 12848 bool LHSReal = false, RHSReal = false; 12849 12850 bool LHSOK; 12851 if (E->getLHS()->getType()->isRealFloatingType()) { 12852 LHSReal = true; 12853 APFloat &Real = Result.FloatReal; 12854 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 12855 if (LHSOK) { 12856 Result.makeComplexFloat(); 12857 Result.FloatImag = APFloat(Real.getSemantics()); 12858 } 12859 } else { 12860 LHSOK = Visit(E->getLHS()); 12861 } 12862 if (!LHSOK && !Info.noteFailure()) 12863 return false; 12864 12865 ComplexValue RHS; 12866 if (E->getRHS()->getType()->isRealFloatingType()) { 12867 RHSReal = true; 12868 APFloat &Real = RHS.FloatReal; 12869 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 12870 return false; 12871 RHS.makeComplexFloat(); 12872 RHS.FloatImag = APFloat(Real.getSemantics()); 12873 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12874 return false; 12875 12876 assert(!(LHSReal && RHSReal) && 12877 "Cannot have both operands of a complex operation be real."); 12878 switch (E->getOpcode()) { 12879 default: return Error(E); 12880 case BO_Add: 12881 if (Result.isComplexFloat()) { 12882 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 12883 APFloat::rmNearestTiesToEven); 12884 if (LHSReal) 12885 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 12886 else if (!RHSReal) 12887 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 12888 APFloat::rmNearestTiesToEven); 12889 } else { 12890 Result.getComplexIntReal() += RHS.getComplexIntReal(); 12891 Result.getComplexIntImag() += RHS.getComplexIntImag(); 12892 } 12893 break; 12894 case BO_Sub: 12895 if (Result.isComplexFloat()) { 12896 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 12897 APFloat::rmNearestTiesToEven); 12898 if (LHSReal) { 12899 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 12900 Result.getComplexFloatImag().changeSign(); 12901 } else if (!RHSReal) { 12902 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 12903 APFloat::rmNearestTiesToEven); 12904 } 12905 } else { 12906 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 12907 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 12908 } 12909 break; 12910 case BO_Mul: 12911 if (Result.isComplexFloat()) { 12912 // This is an implementation of complex multiplication according to the 12913 // constraints laid out in C11 Annex G. The implementation uses the 12914 // following naming scheme: 12915 // (a + ib) * (c + id) 12916 ComplexValue LHS = Result; 12917 APFloat &A = LHS.getComplexFloatReal(); 12918 APFloat &B = LHS.getComplexFloatImag(); 12919 APFloat &C = RHS.getComplexFloatReal(); 12920 APFloat &D = RHS.getComplexFloatImag(); 12921 APFloat &ResR = Result.getComplexFloatReal(); 12922 APFloat &ResI = Result.getComplexFloatImag(); 12923 if (LHSReal) { 12924 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 12925 ResR = A * C; 12926 ResI = A * D; 12927 } else if (RHSReal) { 12928 ResR = C * A; 12929 ResI = C * B; 12930 } else { 12931 // In the fully general case, we need to handle NaNs and infinities 12932 // robustly. 12933 APFloat AC = A * C; 12934 APFloat BD = B * D; 12935 APFloat AD = A * D; 12936 APFloat BC = B * C; 12937 ResR = AC - BD; 12938 ResI = AD + BC; 12939 if (ResR.isNaN() && ResI.isNaN()) { 12940 bool Recalc = false; 12941 if (A.isInfinity() || B.isInfinity()) { 12942 A = APFloat::copySign( 12943 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 12944 B = APFloat::copySign( 12945 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 12946 if (C.isNaN()) 12947 C = APFloat::copySign(APFloat(C.getSemantics()), C); 12948 if (D.isNaN()) 12949 D = APFloat::copySign(APFloat(D.getSemantics()), D); 12950 Recalc = true; 12951 } 12952 if (C.isInfinity() || D.isInfinity()) { 12953 C = APFloat::copySign( 12954 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 12955 D = APFloat::copySign( 12956 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 12957 if (A.isNaN()) 12958 A = APFloat::copySign(APFloat(A.getSemantics()), A); 12959 if (B.isNaN()) 12960 B = APFloat::copySign(APFloat(B.getSemantics()), B); 12961 Recalc = true; 12962 } 12963 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 12964 AD.isInfinity() || BC.isInfinity())) { 12965 if (A.isNaN()) 12966 A = APFloat::copySign(APFloat(A.getSemantics()), A); 12967 if (B.isNaN()) 12968 B = APFloat::copySign(APFloat(B.getSemantics()), B); 12969 if (C.isNaN()) 12970 C = APFloat::copySign(APFloat(C.getSemantics()), C); 12971 if (D.isNaN()) 12972 D = APFloat::copySign(APFloat(D.getSemantics()), D); 12973 Recalc = true; 12974 } 12975 if (Recalc) { 12976 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 12977 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 12978 } 12979 } 12980 } 12981 } else { 12982 ComplexValue LHS = Result; 12983 Result.getComplexIntReal() = 12984 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 12985 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 12986 Result.getComplexIntImag() = 12987 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 12988 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 12989 } 12990 break; 12991 case BO_Div: 12992 if (Result.isComplexFloat()) { 12993 // This is an implementation of complex division according to the 12994 // constraints laid out in C11 Annex G. The implementation uses the 12995 // following naming scheme: 12996 // (a + ib) / (c + id) 12997 ComplexValue LHS = Result; 12998 APFloat &A = LHS.getComplexFloatReal(); 12999 APFloat &B = LHS.getComplexFloatImag(); 13000 APFloat &C = RHS.getComplexFloatReal(); 13001 APFloat &D = RHS.getComplexFloatImag(); 13002 APFloat &ResR = Result.getComplexFloatReal(); 13003 APFloat &ResI = Result.getComplexFloatImag(); 13004 if (RHSReal) { 13005 ResR = A / C; 13006 ResI = B / C; 13007 } else { 13008 if (LHSReal) { 13009 // No real optimizations we can do here, stub out with zero. 13010 B = APFloat::getZero(A.getSemantics()); 13011 } 13012 int DenomLogB = 0; 13013 APFloat MaxCD = maxnum(abs(C), abs(D)); 13014 if (MaxCD.isFinite()) { 13015 DenomLogB = ilogb(MaxCD); 13016 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 13017 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 13018 } 13019 APFloat Denom = C * C + D * D; 13020 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 13021 APFloat::rmNearestTiesToEven); 13022 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 13023 APFloat::rmNearestTiesToEven); 13024 if (ResR.isNaN() && ResI.isNaN()) { 13025 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 13026 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 13027 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 13028 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 13029 D.isFinite()) { 13030 A = APFloat::copySign( 13031 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13032 B = APFloat::copySign( 13033 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13034 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 13035 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 13036 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 13037 C = APFloat::copySign( 13038 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13039 D = APFloat::copySign( 13040 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13041 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 13042 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 13043 } 13044 } 13045 } 13046 } else { 13047 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 13048 return Error(E, diag::note_expr_divide_by_zero); 13049 13050 ComplexValue LHS = Result; 13051 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 13052 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 13053 Result.getComplexIntReal() = 13054 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 13055 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 13056 Result.getComplexIntImag() = 13057 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 13058 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 13059 } 13060 break; 13061 } 13062 13063 return true; 13064 } 13065 13066 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13067 // Get the operand value into 'Result'. 13068 if (!Visit(E->getSubExpr())) 13069 return false; 13070 13071 switch (E->getOpcode()) { 13072 default: 13073 return Error(E); 13074 case UO_Extension: 13075 return true; 13076 case UO_Plus: 13077 // The result is always just the subexpr. 13078 return true; 13079 case UO_Minus: 13080 if (Result.isComplexFloat()) { 13081 Result.getComplexFloatReal().changeSign(); 13082 Result.getComplexFloatImag().changeSign(); 13083 } 13084 else { 13085 Result.getComplexIntReal() = -Result.getComplexIntReal(); 13086 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13087 } 13088 return true; 13089 case UO_Not: 13090 if (Result.isComplexFloat()) 13091 Result.getComplexFloatImag().changeSign(); 13092 else 13093 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13094 return true; 13095 } 13096 } 13097 13098 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 13099 if (E->getNumInits() == 2) { 13100 if (E->getType()->isComplexType()) { 13101 Result.makeComplexFloat(); 13102 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 13103 return false; 13104 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 13105 return false; 13106 } else { 13107 Result.makeComplexInt(); 13108 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 13109 return false; 13110 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 13111 return false; 13112 } 13113 return true; 13114 } 13115 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 13116 } 13117 13118 //===----------------------------------------------------------------------===// 13119 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 13120 // implicit conversion. 13121 //===----------------------------------------------------------------------===// 13122 13123 namespace { 13124 class AtomicExprEvaluator : 13125 public ExprEvaluatorBase<AtomicExprEvaluator> { 13126 const LValue *This; 13127 APValue &Result; 13128 public: 13129 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 13130 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 13131 13132 bool Success(const APValue &V, const Expr *E) { 13133 Result = V; 13134 return true; 13135 } 13136 13137 bool ZeroInitialization(const Expr *E) { 13138 ImplicitValueInitExpr VIE( 13139 E->getType()->castAs<AtomicType>()->getValueType()); 13140 // For atomic-qualified class (and array) types in C++, initialize the 13141 // _Atomic-wrapped subobject directly, in-place. 13142 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 13143 : Evaluate(Result, Info, &VIE); 13144 } 13145 13146 bool VisitCastExpr(const CastExpr *E) { 13147 switch (E->getCastKind()) { 13148 default: 13149 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13150 case CK_NonAtomicToAtomic: 13151 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 13152 : Evaluate(Result, Info, E->getSubExpr()); 13153 } 13154 } 13155 }; 13156 } // end anonymous namespace 13157 13158 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 13159 EvalInfo &Info) { 13160 assert(E->isRValue() && E->getType()->isAtomicType()); 13161 return AtomicExprEvaluator(Info, This, Result).Visit(E); 13162 } 13163 13164 //===----------------------------------------------------------------------===// 13165 // Void expression evaluation, primarily for a cast to void on the LHS of a 13166 // comma operator 13167 //===----------------------------------------------------------------------===// 13168 13169 namespace { 13170 class VoidExprEvaluator 13171 : public ExprEvaluatorBase<VoidExprEvaluator> { 13172 public: 13173 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 13174 13175 bool Success(const APValue &V, const Expr *e) { return true; } 13176 13177 bool ZeroInitialization(const Expr *E) { return true; } 13178 13179 bool VisitCastExpr(const CastExpr *E) { 13180 switch (E->getCastKind()) { 13181 default: 13182 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13183 case CK_ToVoid: 13184 VisitIgnoredValue(E->getSubExpr()); 13185 return true; 13186 } 13187 } 13188 13189 bool VisitCallExpr(const CallExpr *E) { 13190 switch (E->getBuiltinCallee()) { 13191 case Builtin::BI__assume: 13192 case Builtin::BI__builtin_assume: 13193 // The argument is not evaluated! 13194 return true; 13195 13196 case Builtin::BI__builtin_operator_delete: 13197 return HandleOperatorDeleteCall(Info, E); 13198 13199 default: 13200 break; 13201 } 13202 13203 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13204 } 13205 13206 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 13207 }; 13208 } // end anonymous namespace 13209 13210 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 13211 // We cannot speculatively evaluate a delete expression. 13212 if (Info.SpeculativeEvaluationDepth) 13213 return false; 13214 13215 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 13216 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 13217 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13218 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 13219 return false; 13220 } 13221 13222 const Expr *Arg = E->getArgument(); 13223 13224 LValue Pointer; 13225 if (!EvaluatePointer(Arg, Pointer, Info)) 13226 return false; 13227 if (Pointer.Designator.Invalid) 13228 return false; 13229 13230 // Deleting a null pointer has no effect. 13231 if (Pointer.isNullPointer()) { 13232 // This is the only case where we need to produce an extension warning: 13233 // the only other way we can succeed is if we find a dynamic allocation, 13234 // and we will have warned when we allocated it in that case. 13235 if (!Info.getLangOpts().CPlusPlus2a) 13236 Info.CCEDiag(E, diag::note_constexpr_new); 13237 return true; 13238 } 13239 13240 Optional<DynAlloc *> Alloc = CheckDeleteKind( 13241 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 13242 if (!Alloc) 13243 return false; 13244 QualType AllocType = Pointer.Base.getDynamicAllocType(); 13245 13246 // For the non-array case, the designator must be empty if the static type 13247 // does not have a virtual destructor. 13248 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 13249 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 13250 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 13251 << Arg->getType()->getPointeeType() << AllocType; 13252 return false; 13253 } 13254 13255 // For a class type with a virtual destructor, the selected operator delete 13256 // is the one looked up when building the destructor. 13257 if (!E->isArrayForm() && !E->isGlobalDelete()) { 13258 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 13259 if (VirtualDelete && 13260 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 13261 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13262 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 13263 return false; 13264 } 13265 } 13266 13267 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 13268 (*Alloc)->Value, AllocType)) 13269 return false; 13270 13271 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 13272 // The element was already erased. This means the destructor call also 13273 // deleted the object. 13274 // FIXME: This probably results in undefined behavior before we get this 13275 // far, and should be diagnosed elsewhere first. 13276 Info.FFDiag(E, diag::note_constexpr_double_delete); 13277 return false; 13278 } 13279 13280 return true; 13281 } 13282 13283 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 13284 assert(E->isRValue() && E->getType()->isVoidType()); 13285 return VoidExprEvaluator(Info).Visit(E); 13286 } 13287 13288 //===----------------------------------------------------------------------===// 13289 // Top level Expr::EvaluateAsRValue method. 13290 //===----------------------------------------------------------------------===// 13291 13292 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 13293 // In C, function designators are not lvalues, but we evaluate them as if they 13294 // are. 13295 QualType T = E->getType(); 13296 if (E->isGLValue() || T->isFunctionType()) { 13297 LValue LV; 13298 if (!EvaluateLValue(E, LV, Info)) 13299 return false; 13300 LV.moveInto(Result); 13301 } else if (T->isVectorType()) { 13302 if (!EvaluateVector(E, Result, Info)) 13303 return false; 13304 } else if (T->isIntegralOrEnumerationType()) { 13305 if (!IntExprEvaluator(Info, Result).Visit(E)) 13306 return false; 13307 } else if (T->hasPointerRepresentation()) { 13308 LValue LV; 13309 if (!EvaluatePointer(E, LV, Info)) 13310 return false; 13311 LV.moveInto(Result); 13312 } else if (T->isRealFloatingType()) { 13313 llvm::APFloat F(0.0); 13314 if (!EvaluateFloat(E, F, Info)) 13315 return false; 13316 Result = APValue(F); 13317 } else if (T->isAnyComplexType()) { 13318 ComplexValue C; 13319 if (!EvaluateComplex(E, C, Info)) 13320 return false; 13321 C.moveInto(Result); 13322 } else if (T->isFixedPointType()) { 13323 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 13324 } else if (T->isMemberPointerType()) { 13325 MemberPtr P; 13326 if (!EvaluateMemberPointer(E, P, Info)) 13327 return false; 13328 P.moveInto(Result); 13329 return true; 13330 } else if (T->isArrayType()) { 13331 LValue LV; 13332 APValue &Value = 13333 Info.CurrentCall->createTemporary(E, T, false, LV); 13334 if (!EvaluateArray(E, LV, Value, Info)) 13335 return false; 13336 Result = Value; 13337 } else if (T->isRecordType()) { 13338 LValue LV; 13339 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 13340 if (!EvaluateRecord(E, LV, Value, Info)) 13341 return false; 13342 Result = Value; 13343 } else if (T->isVoidType()) { 13344 if (!Info.getLangOpts().CPlusPlus11) 13345 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 13346 << E->getType(); 13347 if (!EvaluateVoid(E, Info)) 13348 return false; 13349 } else if (T->isAtomicType()) { 13350 QualType Unqual = T.getAtomicUnqualifiedType(); 13351 if (Unqual->isArrayType() || Unqual->isRecordType()) { 13352 LValue LV; 13353 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 13354 if (!EvaluateAtomic(E, &LV, Value, Info)) 13355 return false; 13356 } else { 13357 if (!EvaluateAtomic(E, nullptr, Result, Info)) 13358 return false; 13359 } 13360 } else if (Info.getLangOpts().CPlusPlus11) { 13361 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 13362 return false; 13363 } else { 13364 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 13365 return false; 13366 } 13367 13368 return true; 13369 } 13370 13371 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 13372 /// cases, the in-place evaluation is essential, since later initializers for 13373 /// an object can indirectly refer to subobjects which were initialized earlier. 13374 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 13375 const Expr *E, bool AllowNonLiteralTypes) { 13376 assert(!E->isValueDependent()); 13377 13378 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 13379 return false; 13380 13381 if (E->isRValue()) { 13382 // Evaluate arrays and record types in-place, so that later initializers can 13383 // refer to earlier-initialized members of the object. 13384 QualType T = E->getType(); 13385 if (T->isArrayType()) 13386 return EvaluateArray(E, This, Result, Info); 13387 else if (T->isRecordType()) 13388 return EvaluateRecord(E, This, Result, Info); 13389 else if (T->isAtomicType()) { 13390 QualType Unqual = T.getAtomicUnqualifiedType(); 13391 if (Unqual->isArrayType() || Unqual->isRecordType()) 13392 return EvaluateAtomic(E, &This, Result, Info); 13393 } 13394 } 13395 13396 // For any other type, in-place evaluation is unimportant. 13397 return Evaluate(Result, Info, E); 13398 } 13399 13400 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 13401 /// lvalue-to-rvalue cast if it is an lvalue. 13402 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 13403 if (Info.EnableNewConstInterp) { 13404 auto &InterpCtx = Info.Ctx.getInterpContext(); 13405 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) { 13406 case interp::InterpResult::Success: 13407 return true; 13408 case interp::InterpResult::Fail: 13409 return false; 13410 case interp::InterpResult::Bail: 13411 break; 13412 } 13413 } 13414 13415 if (E->getType().isNull()) 13416 return false; 13417 13418 if (!CheckLiteralType(Info, E)) 13419 return false; 13420 13421 if (!::Evaluate(Result, Info, E)) 13422 return false; 13423 13424 if (E->isGLValue()) { 13425 LValue LV; 13426 LV.setFrom(Info.Ctx, Result); 13427 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 13428 return false; 13429 } 13430 13431 // Check this core constant expression is a constant expression. 13432 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 13433 CheckMemoryLeaks(Info); 13434 } 13435 13436 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 13437 const ASTContext &Ctx, bool &IsConst) { 13438 // Fast-path evaluations of integer literals, since we sometimes see files 13439 // containing vast quantities of these. 13440 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 13441 Result.Val = APValue(APSInt(L->getValue(), 13442 L->getType()->isUnsignedIntegerType())); 13443 IsConst = true; 13444 return true; 13445 } 13446 13447 // This case should be rare, but we need to check it before we check on 13448 // the type below. 13449 if (Exp->getType().isNull()) { 13450 IsConst = false; 13451 return true; 13452 } 13453 13454 // FIXME: Evaluating values of large array and record types can cause 13455 // performance problems. Only do so in C++11 for now. 13456 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 13457 Exp->getType()->isRecordType()) && 13458 !Ctx.getLangOpts().CPlusPlus11) { 13459 IsConst = false; 13460 return true; 13461 } 13462 return false; 13463 } 13464 13465 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 13466 Expr::SideEffectsKind SEK) { 13467 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 13468 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 13469 } 13470 13471 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 13472 const ASTContext &Ctx, EvalInfo &Info) { 13473 bool IsConst; 13474 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 13475 return IsConst; 13476 13477 return EvaluateAsRValue(Info, E, Result.Val); 13478 } 13479 13480 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 13481 const ASTContext &Ctx, 13482 Expr::SideEffectsKind AllowSideEffects, 13483 EvalInfo &Info) { 13484 if (!E->getType()->isIntegralOrEnumerationType()) 13485 return false; 13486 13487 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 13488 !ExprResult.Val.isInt() || 13489 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 13490 return false; 13491 13492 return true; 13493 } 13494 13495 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 13496 const ASTContext &Ctx, 13497 Expr::SideEffectsKind AllowSideEffects, 13498 EvalInfo &Info) { 13499 if (!E->getType()->isFixedPointType()) 13500 return false; 13501 13502 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 13503 return false; 13504 13505 if (!ExprResult.Val.isFixedPoint() || 13506 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 13507 return false; 13508 13509 return true; 13510 } 13511 13512 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 13513 /// any crazy technique (that has nothing to do with language standards) that 13514 /// we want to. If this function returns true, it returns the folded constant 13515 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 13516 /// will be applied to the result. 13517 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 13518 bool InConstantContext) const { 13519 assert(!isValueDependent() && 13520 "Expression evaluator can't be called on a dependent expression."); 13521 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 13522 Info.InConstantContext = InConstantContext; 13523 return ::EvaluateAsRValue(this, Result, Ctx, Info); 13524 } 13525 13526 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 13527 bool InConstantContext) const { 13528 assert(!isValueDependent() && 13529 "Expression evaluator can't be called on a dependent expression."); 13530 EvalResult Scratch; 13531 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 13532 HandleConversionToBool(Scratch.Val, Result); 13533 } 13534 13535 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 13536 SideEffectsKind AllowSideEffects, 13537 bool InConstantContext) const { 13538 assert(!isValueDependent() && 13539 "Expression evaluator can't be called on a dependent expression."); 13540 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 13541 Info.InConstantContext = InConstantContext; 13542 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 13543 } 13544 13545 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 13546 SideEffectsKind AllowSideEffects, 13547 bool InConstantContext) const { 13548 assert(!isValueDependent() && 13549 "Expression evaluator can't be called on a dependent expression."); 13550 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 13551 Info.InConstantContext = InConstantContext; 13552 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 13553 } 13554 13555 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 13556 SideEffectsKind AllowSideEffects, 13557 bool InConstantContext) const { 13558 assert(!isValueDependent() && 13559 "Expression evaluator can't be called on a dependent expression."); 13560 13561 if (!getType()->isRealFloatingType()) 13562 return false; 13563 13564 EvalResult ExprResult; 13565 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 13566 !ExprResult.Val.isFloat() || 13567 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 13568 return false; 13569 13570 Result = ExprResult.Val.getFloat(); 13571 return true; 13572 } 13573 13574 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 13575 bool InConstantContext) const { 13576 assert(!isValueDependent() && 13577 "Expression evaluator can't be called on a dependent expression."); 13578 13579 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 13580 Info.InConstantContext = InConstantContext; 13581 LValue LV; 13582 CheckedTemporaries CheckedTemps; 13583 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 13584 Result.HasSideEffects || 13585 !CheckLValueConstantExpression(Info, getExprLoc(), 13586 Ctx.getLValueReferenceType(getType()), LV, 13587 Expr::EvaluateForCodeGen, CheckedTemps)) 13588 return false; 13589 13590 LV.moveInto(Result.Val); 13591 return true; 13592 } 13593 13594 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 13595 const ASTContext &Ctx) const { 13596 assert(!isValueDependent() && 13597 "Expression evaluator can't be called on a dependent expression."); 13598 13599 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 13600 EvalInfo Info(Ctx, Result, EM); 13601 Info.InConstantContext = true; 13602 13603 if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 13604 return false; 13605 13606 if (!Info.discardCleanups()) 13607 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 13608 13609 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 13610 Result.Val, Usage) && 13611 CheckMemoryLeaks(Info); 13612 } 13613 13614 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 13615 const VarDecl *VD, 13616 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 13617 assert(!isValueDependent() && 13618 "Expression evaluator can't be called on a dependent expression."); 13619 13620 // FIXME: Evaluating initializers for large array and record types can cause 13621 // performance problems. Only do so in C++11 for now. 13622 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 13623 !Ctx.getLangOpts().CPlusPlus11) 13624 return false; 13625 13626 Expr::EvalStatus EStatus; 13627 EStatus.Diag = &Notes; 13628 13629 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 13630 ? EvalInfo::EM_ConstantExpression 13631 : EvalInfo::EM_ConstantFold); 13632 Info.setEvaluatingDecl(VD, Value); 13633 Info.InConstantContext = true; 13634 13635 SourceLocation DeclLoc = VD->getLocation(); 13636 QualType DeclTy = VD->getType(); 13637 13638 if (Info.EnableNewConstInterp) { 13639 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 13640 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) { 13641 case interp::InterpResult::Fail: 13642 // Bail out if an error was encountered. 13643 return false; 13644 case interp::InterpResult::Success: 13645 // Evaluation succeeded and value was set. 13646 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value); 13647 case interp::InterpResult::Bail: 13648 // Evaluate the value again for the tree evaluator to use. 13649 break; 13650 } 13651 } 13652 13653 LValue LVal; 13654 LVal.set(VD); 13655 13656 // C++11 [basic.start.init]p2: 13657 // Variables with static storage duration or thread storage duration shall be 13658 // zero-initialized before any other initialization takes place. 13659 // This behavior is not present in C. 13660 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 13661 !DeclTy->isReferenceType()) { 13662 ImplicitValueInitExpr VIE(DeclTy); 13663 if (!EvaluateInPlace(Value, Info, LVal, &VIE, 13664 /*AllowNonLiteralTypes=*/true)) 13665 return false; 13666 } 13667 13668 if (!EvaluateInPlace(Value, Info, LVal, this, 13669 /*AllowNonLiteralTypes=*/true) || 13670 EStatus.HasSideEffects) 13671 return false; 13672 13673 // At this point, any lifetime-extended temporaries are completely 13674 // initialized. 13675 Info.performLifetimeExtension(); 13676 13677 if (!Info.discardCleanups()) 13678 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 13679 13680 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 13681 CheckMemoryLeaks(Info); 13682 } 13683 13684 bool VarDecl::evaluateDestruction( 13685 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 13686 assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() && 13687 "cannot evaluate destruction of non-constant-initialized variable"); 13688 13689 Expr::EvalStatus EStatus; 13690 EStatus.Diag = &Notes; 13691 13692 // Make a copy of the value for the destructor to mutate. 13693 APValue DestroyedValue = *getEvaluatedValue(); 13694 13695 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 13696 Info.setEvaluatingDecl(this, DestroyedValue, 13697 EvalInfo::EvaluatingDeclKind::Dtor); 13698 Info.InConstantContext = true; 13699 13700 SourceLocation DeclLoc = getLocation(); 13701 QualType DeclTy = getType(); 13702 13703 LValue LVal; 13704 LVal.set(this); 13705 13706 // FIXME: Consider storing whether this variable has constant destruction in 13707 // the EvaluatedStmt so that CodeGen can query it. 13708 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 13709 EStatus.HasSideEffects) 13710 return false; 13711 13712 if (!Info.discardCleanups()) 13713 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 13714 13715 ensureEvaluatedStmt()->HasConstantDestruction = true; 13716 return true; 13717 } 13718 13719 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 13720 /// constant folded, but discard the result. 13721 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 13722 assert(!isValueDependent() && 13723 "Expression evaluator can't be called on a dependent expression."); 13724 13725 EvalResult Result; 13726 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 13727 !hasUnacceptableSideEffect(Result, SEK); 13728 } 13729 13730 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 13731 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 13732 assert(!isValueDependent() && 13733 "Expression evaluator can't be called on a dependent expression."); 13734 13735 EvalResult EVResult; 13736 EVResult.Diag = Diag; 13737 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 13738 Info.InConstantContext = true; 13739 13740 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 13741 (void)Result; 13742 assert(Result && "Could not evaluate expression"); 13743 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 13744 13745 return EVResult.Val.getInt(); 13746 } 13747 13748 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 13749 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 13750 assert(!isValueDependent() && 13751 "Expression evaluator can't be called on a dependent expression."); 13752 13753 EvalResult EVResult; 13754 EVResult.Diag = Diag; 13755 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 13756 Info.InConstantContext = true; 13757 Info.CheckingForUndefinedBehavior = true; 13758 13759 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 13760 (void)Result; 13761 assert(Result && "Could not evaluate expression"); 13762 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 13763 13764 return EVResult.Val.getInt(); 13765 } 13766 13767 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 13768 assert(!isValueDependent() && 13769 "Expression evaluator can't be called on a dependent expression."); 13770 13771 bool IsConst; 13772 EvalResult EVResult; 13773 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 13774 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 13775 Info.CheckingForUndefinedBehavior = true; 13776 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 13777 } 13778 } 13779 13780 bool Expr::EvalResult::isGlobalLValue() const { 13781 assert(Val.isLValue()); 13782 return IsGlobalLValue(Val.getLValueBase()); 13783 } 13784 13785 13786 /// isIntegerConstantExpr - this recursive routine will test if an expression is 13787 /// an integer constant expression. 13788 13789 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 13790 /// comma, etc 13791 13792 // CheckICE - This function does the fundamental ICE checking: the returned 13793 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 13794 // and a (possibly null) SourceLocation indicating the location of the problem. 13795 // 13796 // Note that to reduce code duplication, this helper does no evaluation 13797 // itself; the caller checks whether the expression is evaluatable, and 13798 // in the rare cases where CheckICE actually cares about the evaluated 13799 // value, it calls into Evaluate. 13800 13801 namespace { 13802 13803 enum ICEKind { 13804 /// This expression is an ICE. 13805 IK_ICE, 13806 /// This expression is not an ICE, but if it isn't evaluated, it's 13807 /// a legal subexpression for an ICE. This return value is used to handle 13808 /// the comma operator in C99 mode, and non-constant subexpressions. 13809 IK_ICEIfUnevaluated, 13810 /// This expression is not an ICE, and is not a legal subexpression for one. 13811 IK_NotICE 13812 }; 13813 13814 struct ICEDiag { 13815 ICEKind Kind; 13816 SourceLocation Loc; 13817 13818 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 13819 }; 13820 13821 } 13822 13823 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 13824 13825 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 13826 13827 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 13828 Expr::EvalResult EVResult; 13829 Expr::EvalStatus Status; 13830 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 13831 13832 Info.InConstantContext = true; 13833 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 13834 !EVResult.Val.isInt()) 13835 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13836 13837 return NoDiag(); 13838 } 13839 13840 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 13841 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 13842 if (!E->getType()->isIntegralOrEnumerationType()) 13843 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13844 13845 switch (E->getStmtClass()) { 13846 #define ABSTRACT_STMT(Node) 13847 #define STMT(Node, Base) case Expr::Node##Class: 13848 #define EXPR(Node, Base) 13849 #include "clang/AST/StmtNodes.inc" 13850 case Expr::PredefinedExprClass: 13851 case Expr::FloatingLiteralClass: 13852 case Expr::ImaginaryLiteralClass: 13853 case Expr::StringLiteralClass: 13854 case Expr::ArraySubscriptExprClass: 13855 case Expr::OMPArraySectionExprClass: 13856 case Expr::MemberExprClass: 13857 case Expr::CompoundAssignOperatorClass: 13858 case Expr::CompoundLiteralExprClass: 13859 case Expr::ExtVectorElementExprClass: 13860 case Expr::DesignatedInitExprClass: 13861 case Expr::ArrayInitLoopExprClass: 13862 case Expr::ArrayInitIndexExprClass: 13863 case Expr::NoInitExprClass: 13864 case Expr::DesignatedInitUpdateExprClass: 13865 case Expr::ImplicitValueInitExprClass: 13866 case Expr::ParenListExprClass: 13867 case Expr::VAArgExprClass: 13868 case Expr::AddrLabelExprClass: 13869 case Expr::StmtExprClass: 13870 case Expr::CXXMemberCallExprClass: 13871 case Expr::CUDAKernelCallExprClass: 13872 case Expr::CXXDynamicCastExprClass: 13873 case Expr::CXXTypeidExprClass: 13874 case Expr::CXXUuidofExprClass: 13875 case Expr::MSPropertyRefExprClass: 13876 case Expr::MSPropertySubscriptExprClass: 13877 case Expr::CXXNullPtrLiteralExprClass: 13878 case Expr::UserDefinedLiteralClass: 13879 case Expr::CXXThisExprClass: 13880 case Expr::CXXThrowExprClass: 13881 case Expr::CXXNewExprClass: 13882 case Expr::CXXDeleteExprClass: 13883 case Expr::CXXPseudoDestructorExprClass: 13884 case Expr::UnresolvedLookupExprClass: 13885 case Expr::TypoExprClass: 13886 case Expr::DependentScopeDeclRefExprClass: 13887 case Expr::CXXConstructExprClass: 13888 case Expr::CXXInheritedCtorInitExprClass: 13889 case Expr::CXXStdInitializerListExprClass: 13890 case Expr::CXXBindTemporaryExprClass: 13891 case Expr::ExprWithCleanupsClass: 13892 case Expr::CXXTemporaryObjectExprClass: 13893 case Expr::CXXUnresolvedConstructExprClass: 13894 case Expr::CXXDependentScopeMemberExprClass: 13895 case Expr::UnresolvedMemberExprClass: 13896 case Expr::ObjCStringLiteralClass: 13897 case Expr::ObjCBoxedExprClass: 13898 case Expr::ObjCArrayLiteralClass: 13899 case Expr::ObjCDictionaryLiteralClass: 13900 case Expr::ObjCEncodeExprClass: 13901 case Expr::ObjCMessageExprClass: 13902 case Expr::ObjCSelectorExprClass: 13903 case Expr::ObjCProtocolExprClass: 13904 case Expr::ObjCIvarRefExprClass: 13905 case Expr::ObjCPropertyRefExprClass: 13906 case Expr::ObjCSubscriptRefExprClass: 13907 case Expr::ObjCIsaExprClass: 13908 case Expr::ObjCAvailabilityCheckExprClass: 13909 case Expr::ShuffleVectorExprClass: 13910 case Expr::ConvertVectorExprClass: 13911 case Expr::BlockExprClass: 13912 case Expr::NoStmtClass: 13913 case Expr::OpaqueValueExprClass: 13914 case Expr::PackExpansionExprClass: 13915 case Expr::SubstNonTypeTemplateParmPackExprClass: 13916 case Expr::FunctionParmPackExprClass: 13917 case Expr::AsTypeExprClass: 13918 case Expr::ObjCIndirectCopyRestoreExprClass: 13919 case Expr::MaterializeTemporaryExprClass: 13920 case Expr::PseudoObjectExprClass: 13921 case Expr::AtomicExprClass: 13922 case Expr::LambdaExprClass: 13923 case Expr::CXXFoldExprClass: 13924 case Expr::CoawaitExprClass: 13925 case Expr::DependentCoawaitExprClass: 13926 case Expr::CoyieldExprClass: 13927 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13928 13929 case Expr::InitListExprClass: { 13930 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 13931 // form "T x = { a };" is equivalent to "T x = a;". 13932 // Unless we're initializing a reference, T is a scalar as it is known to be 13933 // of integral or enumeration type. 13934 if (E->isRValue()) 13935 if (cast<InitListExpr>(E)->getNumInits() == 1) 13936 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 13937 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13938 } 13939 13940 case Expr::SizeOfPackExprClass: 13941 case Expr::GNUNullExprClass: 13942 case Expr::SourceLocExprClass: 13943 return NoDiag(); 13944 13945 case Expr::SubstNonTypeTemplateParmExprClass: 13946 return 13947 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 13948 13949 case Expr::ConstantExprClass: 13950 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 13951 13952 case Expr::ParenExprClass: 13953 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 13954 case Expr::GenericSelectionExprClass: 13955 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 13956 case Expr::IntegerLiteralClass: 13957 case Expr::FixedPointLiteralClass: 13958 case Expr::CharacterLiteralClass: 13959 case Expr::ObjCBoolLiteralExprClass: 13960 case Expr::CXXBoolLiteralExprClass: 13961 case Expr::CXXScalarValueInitExprClass: 13962 case Expr::TypeTraitExprClass: 13963 case Expr::ConceptSpecializationExprClass: 13964 case Expr::ArrayTypeTraitExprClass: 13965 case Expr::ExpressionTraitExprClass: 13966 case Expr::CXXNoexceptExprClass: 13967 return NoDiag(); 13968 case Expr::CallExprClass: 13969 case Expr::CXXOperatorCallExprClass: { 13970 // C99 6.6/3 allows function calls within unevaluated subexpressions of 13971 // constant expressions, but they can never be ICEs because an ICE cannot 13972 // contain an operand of (pointer to) function type. 13973 const CallExpr *CE = cast<CallExpr>(E); 13974 if (CE->getBuiltinCallee()) 13975 return CheckEvalInICE(E, Ctx); 13976 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13977 } 13978 case Expr::CXXRewrittenBinaryOperatorClass: 13979 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 13980 Ctx); 13981 case Expr::DeclRefExprClass: { 13982 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 13983 return NoDiag(); 13984 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 13985 if (Ctx.getLangOpts().CPlusPlus && 13986 D && IsConstNonVolatile(D->getType())) { 13987 // Parameter variables are never constants. Without this check, 13988 // getAnyInitializer() can find a default argument, which leads 13989 // to chaos. 13990 if (isa<ParmVarDecl>(D)) 13991 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 13992 13993 // C++ 7.1.5.1p2 13994 // A variable of non-volatile const-qualified integral or enumeration 13995 // type initialized by an ICE can be used in ICEs. 13996 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 13997 if (!Dcl->getType()->isIntegralOrEnumerationType()) 13998 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 13999 14000 const VarDecl *VD; 14001 // Look for a declaration of this variable that has an initializer, and 14002 // check whether it is an ICE. 14003 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 14004 return NoDiag(); 14005 else 14006 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14007 } 14008 } 14009 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14010 } 14011 case Expr::UnaryOperatorClass: { 14012 const UnaryOperator *Exp = cast<UnaryOperator>(E); 14013 switch (Exp->getOpcode()) { 14014 case UO_PostInc: 14015 case UO_PostDec: 14016 case UO_PreInc: 14017 case UO_PreDec: 14018 case UO_AddrOf: 14019 case UO_Deref: 14020 case UO_Coawait: 14021 // C99 6.6/3 allows increment and decrement within unevaluated 14022 // subexpressions of constant expressions, but they can never be ICEs 14023 // because an ICE cannot contain an lvalue operand. 14024 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14025 case UO_Extension: 14026 case UO_LNot: 14027 case UO_Plus: 14028 case UO_Minus: 14029 case UO_Not: 14030 case UO_Real: 14031 case UO_Imag: 14032 return CheckICE(Exp->getSubExpr(), Ctx); 14033 } 14034 llvm_unreachable("invalid unary operator class"); 14035 } 14036 case Expr::OffsetOfExprClass: { 14037 // Note that per C99, offsetof must be an ICE. And AFAIK, using 14038 // EvaluateAsRValue matches the proposed gcc behavior for cases like 14039 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 14040 // compliance: we should warn earlier for offsetof expressions with 14041 // array subscripts that aren't ICEs, and if the array subscripts 14042 // are ICEs, the value of the offsetof must be an integer constant. 14043 return CheckEvalInICE(E, Ctx); 14044 } 14045 case Expr::UnaryExprOrTypeTraitExprClass: { 14046 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 14047 if ((Exp->getKind() == UETT_SizeOf) && 14048 Exp->getTypeOfArgument()->isVariableArrayType()) 14049 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14050 return NoDiag(); 14051 } 14052 case Expr::BinaryOperatorClass: { 14053 const BinaryOperator *Exp = cast<BinaryOperator>(E); 14054 switch (Exp->getOpcode()) { 14055 case BO_PtrMemD: 14056 case BO_PtrMemI: 14057 case BO_Assign: 14058 case BO_MulAssign: 14059 case BO_DivAssign: 14060 case BO_RemAssign: 14061 case BO_AddAssign: 14062 case BO_SubAssign: 14063 case BO_ShlAssign: 14064 case BO_ShrAssign: 14065 case BO_AndAssign: 14066 case BO_XorAssign: 14067 case BO_OrAssign: 14068 // C99 6.6/3 allows assignments within unevaluated subexpressions of 14069 // constant expressions, but they can never be ICEs because an ICE cannot 14070 // contain an lvalue operand. 14071 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14072 14073 case BO_Mul: 14074 case BO_Div: 14075 case BO_Rem: 14076 case BO_Add: 14077 case BO_Sub: 14078 case BO_Shl: 14079 case BO_Shr: 14080 case BO_LT: 14081 case BO_GT: 14082 case BO_LE: 14083 case BO_GE: 14084 case BO_EQ: 14085 case BO_NE: 14086 case BO_And: 14087 case BO_Xor: 14088 case BO_Or: 14089 case BO_Comma: 14090 case BO_Cmp: { 14091 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14092 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14093 if (Exp->getOpcode() == BO_Div || 14094 Exp->getOpcode() == BO_Rem) { 14095 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 14096 // we don't evaluate one. 14097 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 14098 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 14099 if (REval == 0) 14100 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14101 if (REval.isSigned() && REval.isAllOnesValue()) { 14102 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 14103 if (LEval.isMinSignedValue()) 14104 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14105 } 14106 } 14107 } 14108 if (Exp->getOpcode() == BO_Comma) { 14109 if (Ctx.getLangOpts().C99) { 14110 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 14111 // if it isn't evaluated. 14112 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 14113 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14114 } else { 14115 // In both C89 and C++, commas in ICEs are illegal. 14116 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14117 } 14118 } 14119 return Worst(LHSResult, RHSResult); 14120 } 14121 case BO_LAnd: 14122 case BO_LOr: { 14123 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14124 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14125 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 14126 // Rare case where the RHS has a comma "side-effect"; we need 14127 // to actually check the condition to see whether the side 14128 // with the comma is evaluated. 14129 if ((Exp->getOpcode() == BO_LAnd) != 14130 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 14131 return RHSResult; 14132 return NoDiag(); 14133 } 14134 14135 return Worst(LHSResult, RHSResult); 14136 } 14137 } 14138 llvm_unreachable("invalid binary operator kind"); 14139 } 14140 case Expr::ImplicitCastExprClass: 14141 case Expr::CStyleCastExprClass: 14142 case Expr::CXXFunctionalCastExprClass: 14143 case Expr::CXXStaticCastExprClass: 14144 case Expr::CXXReinterpretCastExprClass: 14145 case Expr::CXXConstCastExprClass: 14146 case Expr::ObjCBridgedCastExprClass: { 14147 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 14148 if (isa<ExplicitCastExpr>(E)) { 14149 if (const FloatingLiteral *FL 14150 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 14151 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 14152 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 14153 APSInt IgnoredVal(DestWidth, !DestSigned); 14154 bool Ignored; 14155 // If the value does not fit in the destination type, the behavior is 14156 // undefined, so we are not required to treat it as a constant 14157 // expression. 14158 if (FL->getValue().convertToInteger(IgnoredVal, 14159 llvm::APFloat::rmTowardZero, 14160 &Ignored) & APFloat::opInvalidOp) 14161 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14162 return NoDiag(); 14163 } 14164 } 14165 switch (cast<CastExpr>(E)->getCastKind()) { 14166 case CK_LValueToRValue: 14167 case CK_AtomicToNonAtomic: 14168 case CK_NonAtomicToAtomic: 14169 case CK_NoOp: 14170 case CK_IntegralToBoolean: 14171 case CK_IntegralCast: 14172 return CheckICE(SubExpr, Ctx); 14173 default: 14174 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14175 } 14176 } 14177 case Expr::BinaryConditionalOperatorClass: { 14178 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 14179 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 14180 if (CommonResult.Kind == IK_NotICE) return CommonResult; 14181 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14182 if (FalseResult.Kind == IK_NotICE) return FalseResult; 14183 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 14184 if (FalseResult.Kind == IK_ICEIfUnevaluated && 14185 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 14186 return FalseResult; 14187 } 14188 case Expr::ConditionalOperatorClass: { 14189 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 14190 // If the condition (ignoring parens) is a __builtin_constant_p call, 14191 // then only the true side is actually considered in an integer constant 14192 // expression, and it is fully evaluated. This is an important GNU 14193 // extension. See GCC PR38377 for discussion. 14194 if (const CallExpr *CallCE 14195 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 14196 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 14197 return CheckEvalInICE(E, Ctx); 14198 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 14199 if (CondResult.Kind == IK_NotICE) 14200 return CondResult; 14201 14202 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 14203 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14204 14205 if (TrueResult.Kind == IK_NotICE) 14206 return TrueResult; 14207 if (FalseResult.Kind == IK_NotICE) 14208 return FalseResult; 14209 if (CondResult.Kind == IK_ICEIfUnevaluated) 14210 return CondResult; 14211 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 14212 return NoDiag(); 14213 // Rare case where the diagnostics depend on which side is evaluated 14214 // Note that if we get here, CondResult is 0, and at least one of 14215 // TrueResult and FalseResult is non-zero. 14216 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 14217 return FalseResult; 14218 return TrueResult; 14219 } 14220 case Expr::CXXDefaultArgExprClass: 14221 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 14222 case Expr::CXXDefaultInitExprClass: 14223 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 14224 case Expr::ChooseExprClass: { 14225 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 14226 } 14227 case Expr::BuiltinBitCastExprClass: { 14228 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 14229 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14230 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 14231 } 14232 } 14233 14234 llvm_unreachable("Invalid StmtClass!"); 14235 } 14236 14237 /// Evaluate an expression as a C++11 integral constant expression. 14238 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 14239 const Expr *E, 14240 llvm::APSInt *Value, 14241 SourceLocation *Loc) { 14242 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14243 if (Loc) *Loc = E->getExprLoc(); 14244 return false; 14245 } 14246 14247 APValue Result; 14248 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 14249 return false; 14250 14251 if (!Result.isInt()) { 14252 if (Loc) *Loc = E->getExprLoc(); 14253 return false; 14254 } 14255 14256 if (Value) *Value = Result.getInt(); 14257 return true; 14258 } 14259 14260 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 14261 SourceLocation *Loc) const { 14262 assert(!isValueDependent() && 14263 "Expression evaluator can't be called on a dependent expression."); 14264 14265 if (Ctx.getLangOpts().CPlusPlus11) 14266 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 14267 14268 ICEDiag D = CheckICE(this, Ctx); 14269 if (D.Kind != IK_ICE) { 14270 if (Loc) *Loc = D.Loc; 14271 return false; 14272 } 14273 return true; 14274 } 14275 14276 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 14277 SourceLocation *Loc, bool isEvaluated) const { 14278 assert(!isValueDependent() && 14279 "Expression evaluator can't be called on a dependent expression."); 14280 14281 if (Ctx.getLangOpts().CPlusPlus11) 14282 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 14283 14284 if (!isIntegerConstantExpr(Ctx, Loc)) 14285 return false; 14286 14287 // The only possible side-effects here are due to UB discovered in the 14288 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 14289 // required to treat the expression as an ICE, so we produce the folded 14290 // value. 14291 EvalResult ExprResult; 14292 Expr::EvalStatus Status; 14293 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 14294 Info.InConstantContext = true; 14295 14296 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 14297 llvm_unreachable("ICE cannot be evaluated!"); 14298 14299 Value = ExprResult.Val.getInt(); 14300 return true; 14301 } 14302 14303 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 14304 assert(!isValueDependent() && 14305 "Expression evaluator can't be called on a dependent expression."); 14306 14307 return CheckICE(this, Ctx).Kind == IK_ICE; 14308 } 14309 14310 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 14311 SourceLocation *Loc) const { 14312 assert(!isValueDependent() && 14313 "Expression evaluator can't be called on a dependent expression."); 14314 14315 // We support this checking in C++98 mode in order to diagnose compatibility 14316 // issues. 14317 assert(Ctx.getLangOpts().CPlusPlus); 14318 14319 // Build evaluation settings. 14320 Expr::EvalStatus Status; 14321 SmallVector<PartialDiagnosticAt, 8> Diags; 14322 Status.Diag = &Diags; 14323 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14324 14325 APValue Scratch; 14326 bool IsConstExpr = 14327 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 14328 // FIXME: We don't produce a diagnostic for this, but the callers that 14329 // call us on arbitrary full-expressions should generally not care. 14330 Info.discardCleanups() && !Status.HasSideEffects; 14331 14332 if (!Diags.empty()) { 14333 IsConstExpr = false; 14334 if (Loc) *Loc = Diags[0].first; 14335 } else if (!IsConstExpr) { 14336 // FIXME: This shouldn't happen. 14337 if (Loc) *Loc = getExprLoc(); 14338 } 14339 14340 return IsConstExpr; 14341 } 14342 14343 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 14344 const FunctionDecl *Callee, 14345 ArrayRef<const Expr*> Args, 14346 const Expr *This) const { 14347 assert(!isValueDependent() && 14348 "Expression evaluator can't be called on a dependent expression."); 14349 14350 Expr::EvalStatus Status; 14351 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 14352 Info.InConstantContext = true; 14353 14354 LValue ThisVal; 14355 const LValue *ThisPtr = nullptr; 14356 if (This) { 14357 #ifndef NDEBUG 14358 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 14359 assert(MD && "Don't provide `this` for non-methods."); 14360 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 14361 #endif 14362 if (!This->isValueDependent() && 14363 EvaluateObjectArgument(Info, This, ThisVal) && 14364 !Info.EvalStatus.HasSideEffects) 14365 ThisPtr = &ThisVal; 14366 14367 // Ignore any side-effects from a failed evaluation. This is safe because 14368 // they can't interfere with any other argument evaluation. 14369 Info.EvalStatus.HasSideEffects = false; 14370 } 14371 14372 ArgVector ArgValues(Args.size()); 14373 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 14374 I != E; ++I) { 14375 if ((*I)->isValueDependent() || 14376 !Evaluate(ArgValues[I - Args.begin()], Info, *I) || 14377 Info.EvalStatus.HasSideEffects) 14378 // If evaluation fails, throw away the argument entirely. 14379 ArgValues[I - Args.begin()] = APValue(); 14380 14381 // Ignore any side-effects from a failed evaluation. This is safe because 14382 // they can't interfere with any other argument evaluation. 14383 Info.EvalStatus.HasSideEffects = false; 14384 } 14385 14386 // Parameter cleanups happen in the caller and are not part of this 14387 // evaluation. 14388 Info.discardCleanups(); 14389 Info.EvalStatus.HasSideEffects = false; 14390 14391 // Build fake call to Callee. 14392 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 14393 ArgValues.data()); 14394 // FIXME: Missing ExprWithCleanups in enable_if conditions? 14395 FullExpressionRAII Scope(Info); 14396 return Evaluate(Value, Info, this) && Scope.destroy() && 14397 !Info.EvalStatus.HasSideEffects; 14398 } 14399 14400 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 14401 SmallVectorImpl< 14402 PartialDiagnosticAt> &Diags) { 14403 // FIXME: It would be useful to check constexpr function templates, but at the 14404 // moment the constant expression evaluator cannot cope with the non-rigorous 14405 // ASTs which we build for dependent expressions. 14406 if (FD->isDependentContext()) 14407 return true; 14408 14409 Expr::EvalStatus Status; 14410 Status.Diag = &Diags; 14411 14412 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 14413 Info.InConstantContext = true; 14414 Info.CheckingPotentialConstantExpression = true; 14415 14416 // The constexpr VM attempts to compile all methods to bytecode here. 14417 if (Info.EnableNewConstInterp) { 14418 auto &InterpCtx = Info.Ctx.getInterpContext(); 14419 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) { 14420 case interp::InterpResult::Success: 14421 case interp::InterpResult::Fail: 14422 return Diags.empty(); 14423 case interp::InterpResult::Bail: 14424 break; 14425 } 14426 } 14427 14428 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 14429 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 14430 14431 // Fabricate an arbitrary expression on the stack and pretend that it 14432 // is a temporary being used as the 'this' pointer. 14433 LValue This; 14434 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 14435 This.set({&VIE, Info.CurrentCall->Index}); 14436 14437 ArrayRef<const Expr*> Args; 14438 14439 APValue Scratch; 14440 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 14441 // Evaluate the call as a constant initializer, to allow the construction 14442 // of objects of non-literal types. 14443 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 14444 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 14445 } else { 14446 SourceLocation Loc = FD->getLocation(); 14447 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 14448 Args, FD->getBody(), Info, Scratch, nullptr); 14449 } 14450 14451 return Diags.empty(); 14452 } 14453 14454 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 14455 const FunctionDecl *FD, 14456 SmallVectorImpl< 14457 PartialDiagnosticAt> &Diags) { 14458 assert(!E->isValueDependent() && 14459 "Expression evaluator can't be called on a dependent expression."); 14460 14461 Expr::EvalStatus Status; 14462 Status.Diag = &Diags; 14463 14464 EvalInfo Info(FD->getASTContext(), Status, 14465 EvalInfo::EM_ConstantExpressionUnevaluated); 14466 Info.InConstantContext = true; 14467 Info.CheckingPotentialConstantExpression = true; 14468 14469 // Fabricate a call stack frame to give the arguments a plausible cover story. 14470 ArrayRef<const Expr*> Args; 14471 ArgVector ArgValues(0); 14472 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 14473 (void)Success; 14474 assert(Success && 14475 "Failed to set up arguments for potential constant evaluation"); 14476 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 14477 14478 APValue ResultScratch; 14479 Evaluate(ResultScratch, Info, E); 14480 return Diags.empty(); 14481 } 14482 14483 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 14484 unsigned Type) const { 14485 if (!getType()->isPointerType()) 14486 return false; 14487 14488 Expr::EvalStatus Status; 14489 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 14490 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 14491 } 14492