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 "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/FixedPoint.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APInt; 67 using llvm::APSInt; 68 using llvm::APFloat; 69 using llvm::Optional; 70 71 namespace { 72 struct LValue; 73 class CallStackFrame; 74 class EvalInfo; 75 76 using SourceLocExprScopeGuard = 77 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 78 79 static QualType getType(APValue::LValueBase B) { 80 if (!B) return QualType(); 81 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 82 // FIXME: It's unclear where we're supposed to take the type from, and 83 // this actually matters for arrays of unknown bound. Eg: 84 // 85 // extern int arr[]; void f() { extern int arr[3]; }; 86 // constexpr int *p = &arr[1]; // valid? 87 // 88 // For now, we take the array bound from the most recent declaration. 89 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 90 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 91 QualType T = Redecl->getType(); 92 if (!T->isIncompleteArrayType()) 93 return T; 94 } 95 return D->getType(); 96 } 97 98 if (B.is<TypeInfoLValue>()) 99 return B.getTypeInfoType(); 100 101 if (B.is<DynamicAllocLValue>()) 102 return B.getDynamicAllocType(); 103 104 const Expr *Base = B.get<const Expr*>(); 105 106 // For a materialized temporary, the type of the temporary we materialized 107 // may not be the type of the expression. 108 if (const MaterializeTemporaryExpr *MTE = 109 dyn_cast<MaterializeTemporaryExpr>(Base)) { 110 SmallVector<const Expr *, 2> CommaLHSs; 111 SmallVector<SubobjectAdjustment, 2> Adjustments; 112 const Expr *Temp = MTE->getSubExpr(); 113 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 114 Adjustments); 115 // Keep any cv-qualifiers from the reference if we generated a temporary 116 // for it directly. Otherwise use the type after adjustment. 117 if (!Adjustments.empty()) 118 return Inner->getType(); 119 } 120 121 return Base->getType(); 122 } 123 124 /// Get an LValue path entry, which is known to not be an array index, as a 125 /// field declaration. 126 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 127 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 128 } 129 /// Get an LValue path entry, which is known to not be an array index, as a 130 /// base class declaration. 131 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 132 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 133 } 134 /// Determine whether this LValue path entry for a base class names a virtual 135 /// base class. 136 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 137 return E.getAsBaseOrMember().getInt(); 138 } 139 140 /// Given an expression, determine the type used to store the result of 141 /// evaluating that expression. 142 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 143 if (E->isRValue()) 144 return E->getType(); 145 return Ctx.getLValueReferenceType(E->getType()); 146 } 147 148 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 149 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 150 const FunctionDecl *Callee = CE->getDirectCallee(); 151 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 152 } 153 154 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 155 /// This will look through a single cast. 156 /// 157 /// Returns null if we couldn't unwrap a function with alloc_size. 158 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 159 if (!E->getType()->isPointerType()) 160 return nullptr; 161 162 E = E->IgnoreParens(); 163 // If we're doing a variable assignment from e.g. malloc(N), there will 164 // probably be a cast of some kind. In exotic cases, we might also see a 165 // top-level ExprWithCleanups. Ignore them either way. 166 if (const auto *FE = dyn_cast<FullExpr>(E)) 167 E = FE->getSubExpr()->IgnoreParens(); 168 169 if (const auto *Cast = dyn_cast<CastExpr>(E)) 170 E = Cast->getSubExpr()->IgnoreParens(); 171 172 if (const auto *CE = dyn_cast<CallExpr>(E)) 173 return getAllocSizeAttr(CE) ? CE : nullptr; 174 return nullptr; 175 } 176 177 /// Determines whether or not the given Base contains a call to a function 178 /// with the alloc_size attribute. 179 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 180 const auto *E = Base.dyn_cast<const Expr *>(); 181 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 182 } 183 184 /// The bound to claim that an array of unknown bound has. 185 /// The value in MostDerivedArraySize is undefined in this case. So, set it 186 /// to an arbitrary value that's likely to loudly break things if it's used. 187 static const uint64_t AssumedSizeForUnsizedArray = 188 std::numeric_limits<uint64_t>::max() / 2; 189 190 /// Determines if an LValue with the given LValueBase will have an unsized 191 /// array in its designator. 192 /// Find the path length and type of the most-derived subobject in the given 193 /// path, and find the size of the containing array, if any. 194 static unsigned 195 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 196 ArrayRef<APValue::LValuePathEntry> Path, 197 uint64_t &ArraySize, QualType &Type, bool &IsArray, 198 bool &FirstEntryIsUnsizedArray) { 199 // This only accepts LValueBases from APValues, and APValues don't support 200 // arrays that lack size info. 201 assert(!isBaseAnAllocSizeCall(Base) && 202 "Unsized arrays shouldn't appear here"); 203 unsigned MostDerivedLength = 0; 204 Type = getType(Base); 205 206 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 207 if (Type->isArrayType()) { 208 const ArrayType *AT = Ctx.getAsArrayType(Type); 209 Type = AT->getElementType(); 210 MostDerivedLength = I + 1; 211 IsArray = true; 212 213 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 214 ArraySize = CAT->getSize().getZExtValue(); 215 } else { 216 assert(I == 0 && "unexpected unsized array designator"); 217 FirstEntryIsUnsizedArray = true; 218 ArraySize = AssumedSizeForUnsizedArray; 219 } 220 } else if (Type->isAnyComplexType()) { 221 const ComplexType *CT = Type->castAs<ComplexType>(); 222 Type = CT->getElementType(); 223 ArraySize = 2; 224 MostDerivedLength = I + 1; 225 IsArray = true; 226 } else if (const FieldDecl *FD = getAsField(Path[I])) { 227 Type = FD->getType(); 228 ArraySize = 0; 229 MostDerivedLength = I + 1; 230 IsArray = false; 231 } else { 232 // Path[I] describes a base class. 233 ArraySize = 0; 234 IsArray = false; 235 } 236 } 237 return MostDerivedLength; 238 } 239 240 /// A path from a glvalue to a subobject of that glvalue. 241 struct SubobjectDesignator { 242 /// True if the subobject was named in a manner not supported by C++11. Such 243 /// lvalues can still be folded, but they are not core constant expressions 244 /// and we cannot perform lvalue-to-rvalue conversions on them. 245 unsigned Invalid : 1; 246 247 /// Is this a pointer one past the end of an object? 248 unsigned IsOnePastTheEnd : 1; 249 250 /// Indicator of whether the first entry is an unsized array. 251 unsigned FirstEntryIsAnUnsizedArray : 1; 252 253 /// Indicator of whether the most-derived object is an array element. 254 unsigned MostDerivedIsArrayElement : 1; 255 256 /// The length of the path to the most-derived object of which this is a 257 /// subobject. 258 unsigned MostDerivedPathLength : 28; 259 260 /// The size of the array of which the most-derived object is an element. 261 /// This will always be 0 if the most-derived object is not an array 262 /// element. 0 is not an indicator of whether or not the most-derived object 263 /// is an array, however, because 0-length arrays are allowed. 264 /// 265 /// If the current array is an unsized array, the value of this is 266 /// undefined. 267 uint64_t MostDerivedArraySize; 268 269 /// The type of the most derived object referred to by this address. 270 QualType MostDerivedType; 271 272 typedef APValue::LValuePathEntry PathEntry; 273 274 /// The entries on the path from the glvalue to the designated subobject. 275 SmallVector<PathEntry, 8> Entries; 276 277 SubobjectDesignator() : Invalid(true) {} 278 279 explicit SubobjectDesignator(QualType T) 280 : Invalid(false), IsOnePastTheEnd(false), 281 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 282 MostDerivedPathLength(0), MostDerivedArraySize(0), 283 MostDerivedType(T) {} 284 285 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 286 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 287 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 288 MostDerivedPathLength(0), MostDerivedArraySize(0) { 289 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 290 if (!Invalid) { 291 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 292 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 293 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 294 if (V.getLValueBase()) { 295 bool IsArray = false; 296 bool FirstIsUnsizedArray = false; 297 MostDerivedPathLength = findMostDerivedSubobject( 298 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 299 MostDerivedType, IsArray, FirstIsUnsizedArray); 300 MostDerivedIsArrayElement = IsArray; 301 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 302 } 303 } 304 } 305 306 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 307 unsigned NewLength) { 308 if (Invalid) 309 return; 310 311 assert(Base && "cannot truncate path for null pointer"); 312 assert(NewLength <= Entries.size() && "not a truncation"); 313 314 if (NewLength == Entries.size()) 315 return; 316 Entries.resize(NewLength); 317 318 bool IsArray = false; 319 bool FirstIsUnsizedArray = false; 320 MostDerivedPathLength = findMostDerivedSubobject( 321 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 322 FirstIsUnsizedArray); 323 MostDerivedIsArrayElement = IsArray; 324 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 325 } 326 327 void setInvalid() { 328 Invalid = true; 329 Entries.clear(); 330 } 331 332 /// Determine whether the most derived subobject is an array without a 333 /// known bound. 334 bool isMostDerivedAnUnsizedArray() const { 335 assert(!Invalid && "Calling this makes no sense on invalid designators"); 336 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 337 } 338 339 /// Determine what the most derived array's size is. Results in an assertion 340 /// failure if the most derived array lacks a size. 341 uint64_t getMostDerivedArraySize() const { 342 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 343 return MostDerivedArraySize; 344 } 345 346 /// Determine whether this is a one-past-the-end pointer. 347 bool isOnePastTheEnd() const { 348 assert(!Invalid); 349 if (IsOnePastTheEnd) 350 return true; 351 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 352 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 353 MostDerivedArraySize) 354 return true; 355 return false; 356 } 357 358 /// Get the range of valid index adjustments in the form 359 /// {maximum value that can be subtracted from this pointer, 360 /// maximum value that can be added to this pointer} 361 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 362 if (Invalid || isMostDerivedAnUnsizedArray()) 363 return {0, 0}; 364 365 // [expr.add]p4: For the purposes of these operators, a pointer to a 366 // nonarray object behaves the same as a pointer to the first element of 367 // an array of length one with the type of the object as its element type. 368 bool IsArray = MostDerivedPathLength == Entries.size() && 369 MostDerivedIsArrayElement; 370 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 371 : (uint64_t)IsOnePastTheEnd; 372 uint64_t ArraySize = 373 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 374 return {ArrayIndex, ArraySize - ArrayIndex}; 375 } 376 377 /// Check that this refers to a valid subobject. 378 bool isValidSubobject() const { 379 if (Invalid) 380 return false; 381 return !isOnePastTheEnd(); 382 } 383 /// Check that this refers to a valid subobject, and if not, produce a 384 /// relevant diagnostic and set the designator as invalid. 385 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 386 387 /// Get the type of the designated object. 388 QualType getType(ASTContext &Ctx) const { 389 assert(!Invalid && "invalid designator has no subobject type"); 390 return MostDerivedPathLength == Entries.size() 391 ? MostDerivedType 392 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 393 } 394 395 /// Update this designator to refer to the first element within this array. 396 void addArrayUnchecked(const ConstantArrayType *CAT) { 397 Entries.push_back(PathEntry::ArrayIndex(0)); 398 399 // This is a most-derived object. 400 MostDerivedType = CAT->getElementType(); 401 MostDerivedIsArrayElement = true; 402 MostDerivedArraySize = CAT->getSize().getZExtValue(); 403 MostDerivedPathLength = Entries.size(); 404 } 405 /// Update this designator to refer to the first element within the array of 406 /// elements of type T. This is an array of unknown size. 407 void addUnsizedArrayUnchecked(QualType ElemTy) { 408 Entries.push_back(PathEntry::ArrayIndex(0)); 409 410 MostDerivedType = ElemTy; 411 MostDerivedIsArrayElement = true; 412 // The value in MostDerivedArraySize is undefined in this case. So, set it 413 // to an arbitrary value that's likely to loudly break things if it's 414 // used. 415 MostDerivedArraySize = AssumedSizeForUnsizedArray; 416 MostDerivedPathLength = Entries.size(); 417 } 418 /// Update this designator to refer to the given base or member of this 419 /// object. 420 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 421 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 422 423 // If this isn't a base class, it's a new most-derived object. 424 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 425 MostDerivedType = FD->getType(); 426 MostDerivedIsArrayElement = false; 427 MostDerivedArraySize = 0; 428 MostDerivedPathLength = Entries.size(); 429 } 430 } 431 /// Update this designator to refer to the given complex component. 432 void addComplexUnchecked(QualType EltTy, bool Imag) { 433 Entries.push_back(PathEntry::ArrayIndex(Imag)); 434 435 // This is technically a most-derived object, though in practice this 436 // is unlikely to matter. 437 MostDerivedType = EltTy; 438 MostDerivedIsArrayElement = true; 439 MostDerivedArraySize = 2; 440 MostDerivedPathLength = Entries.size(); 441 } 442 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 443 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 444 const APSInt &N); 445 /// Add N to the address of this subobject. 446 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 447 if (Invalid || !N) return; 448 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 449 if (isMostDerivedAnUnsizedArray()) { 450 diagnoseUnsizedArrayPointerArithmetic(Info, E); 451 // Can't verify -- trust that the user is doing the right thing (or if 452 // not, trust that the caller will catch the bad behavior). 453 // FIXME: Should we reject if this overflows, at least? 454 Entries.back() = PathEntry::ArrayIndex( 455 Entries.back().getAsArrayIndex() + TruncatedN); 456 return; 457 } 458 459 // [expr.add]p4: For the purposes of these operators, a pointer to a 460 // nonarray object behaves the same as a pointer to the first element of 461 // an array of length one with the type of the object as its element type. 462 bool IsArray = MostDerivedPathLength == Entries.size() && 463 MostDerivedIsArrayElement; 464 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 465 : (uint64_t)IsOnePastTheEnd; 466 uint64_t ArraySize = 467 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 468 469 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 470 // Calculate the actual index in a wide enough type, so we can include 471 // it in the note. 472 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 473 (llvm::APInt&)N += ArrayIndex; 474 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 475 diagnosePointerArithmetic(Info, E, N); 476 setInvalid(); 477 return; 478 } 479 480 ArrayIndex += TruncatedN; 481 assert(ArrayIndex <= ArraySize && 482 "bounds check succeeded for out-of-bounds index"); 483 484 if (IsArray) 485 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 486 else 487 IsOnePastTheEnd = (ArrayIndex != 0); 488 } 489 }; 490 491 /// A stack frame in the constexpr call stack. 492 class CallStackFrame : public interp::Frame { 493 public: 494 EvalInfo &Info; 495 496 /// Parent - The caller of this stack frame. 497 CallStackFrame *Caller; 498 499 /// Callee - The function which was called. 500 const FunctionDecl *Callee; 501 502 /// This - The binding for the this pointer in this call, if any. 503 const LValue *This; 504 505 /// Arguments - Parameter bindings for this function call, indexed by 506 /// parameters' function scope indices. 507 APValue *Arguments; 508 509 /// Source location information about the default argument or default 510 /// initializer expression we're evaluating, if any. 511 CurrentSourceLocExprScope CurSourceLocExprScope; 512 513 // Note that we intentionally use std::map here so that references to 514 // values are stable. 515 typedef std::pair<const void *, unsigned> MapKeyTy; 516 typedef std::map<MapKeyTy, APValue> MapTy; 517 /// Temporaries - Temporary lvalues materialized within this stack frame. 518 MapTy Temporaries; 519 520 /// CallLoc - The location of the call expression for this call. 521 SourceLocation CallLoc; 522 523 /// Index - The call index of this call. 524 unsigned Index; 525 526 /// The stack of integers for tracking version numbers for temporaries. 527 SmallVector<unsigned, 2> TempVersionStack = {1}; 528 unsigned CurTempVersion = TempVersionStack.back(); 529 530 unsigned getTempVersion() const { return TempVersionStack.back(); } 531 532 void pushTempVersion() { 533 TempVersionStack.push_back(++CurTempVersion); 534 } 535 536 void popTempVersion() { 537 TempVersionStack.pop_back(); 538 } 539 540 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 541 // on the overall stack usage of deeply-recursing constexpr evaluations. 542 // (We should cache this map rather than recomputing it repeatedly.) 543 // But let's try this and see how it goes; we can look into caching the map 544 // as a later change. 545 546 /// LambdaCaptureFields - Mapping from captured variables/this to 547 /// corresponding data members in the closure class. 548 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 549 FieldDecl *LambdaThisCaptureField; 550 551 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 552 const FunctionDecl *Callee, const LValue *This, 553 APValue *Arguments); 554 ~CallStackFrame(); 555 556 // Return the temporary for Key whose version number is Version. 557 APValue *getTemporary(const void *Key, unsigned Version) { 558 MapKeyTy KV(Key, Version); 559 auto LB = Temporaries.lower_bound(KV); 560 if (LB != Temporaries.end() && LB->first == KV) 561 return &LB->second; 562 // Pair (Key,Version) wasn't found in the map. Check that no elements 563 // in the map have 'Key' as their key. 564 assert((LB == Temporaries.end() || LB->first.first != Key) && 565 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 566 "Element with key 'Key' found in map"); 567 return nullptr; 568 } 569 570 // Return the current temporary for Key in the map. 571 APValue *getCurrentTemporary(const void *Key) { 572 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 573 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 574 return &std::prev(UB)->second; 575 return nullptr; 576 } 577 578 // Return the version number of the current temporary for Key. 579 unsigned getCurrentTemporaryVersion(const void *Key) const { 580 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 581 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 582 return std::prev(UB)->first.second; 583 return 0; 584 } 585 586 /// Allocate storage for an object of type T in this stack frame. 587 /// Populates LV with a handle to the created object. Key identifies 588 /// the temporary within the stack frame, and must not be reused without 589 /// bumping the temporary version number. 590 template<typename KeyT> 591 APValue &createTemporary(const KeyT *Key, QualType T, 592 bool IsLifetimeExtended, LValue &LV); 593 594 void describe(llvm::raw_ostream &OS) override; 595 596 Frame *getCaller() const override { return Caller; } 597 SourceLocation getCallLocation() const override { return CallLoc; } 598 const FunctionDecl *getCallee() const override { return Callee; } 599 600 bool isStdFunction() const { 601 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 602 if (DC->isStdNamespace()) 603 return true; 604 return false; 605 } 606 }; 607 608 /// Temporarily override 'this'. 609 class ThisOverrideRAII { 610 public: 611 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 612 : Frame(Frame), OldThis(Frame.This) { 613 if (Enable) 614 Frame.This = NewThis; 615 } 616 ~ThisOverrideRAII() { 617 Frame.This = OldThis; 618 } 619 private: 620 CallStackFrame &Frame; 621 const LValue *OldThis; 622 }; 623 } 624 625 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 626 const LValue &This, QualType ThisType); 627 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 628 APValue::LValueBase LVBase, APValue &Value, 629 QualType T); 630 631 namespace { 632 /// A cleanup, and a flag indicating whether it is lifetime-extended. 633 class Cleanup { 634 llvm::PointerIntPair<APValue*, 1, bool> Value; 635 APValue::LValueBase Base; 636 QualType T; 637 638 public: 639 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 640 bool IsLifetimeExtended) 641 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {} 642 643 bool isLifetimeExtended() const { return Value.getInt(); } 644 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 645 if (RunDestructors) { 646 SourceLocation Loc; 647 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 648 Loc = VD->getLocation(); 649 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 650 Loc = E->getExprLoc(); 651 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 652 } 653 *Value.getPointer() = APValue(); 654 return true; 655 } 656 657 bool hasSideEffect() { 658 return T.isDestructedType(); 659 } 660 }; 661 662 /// A reference to an object whose construction we are currently evaluating. 663 struct ObjectUnderConstruction { 664 APValue::LValueBase Base; 665 ArrayRef<APValue::LValuePathEntry> Path; 666 friend bool operator==(const ObjectUnderConstruction &LHS, 667 const ObjectUnderConstruction &RHS) { 668 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 669 } 670 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 671 return llvm::hash_combine(Obj.Base, Obj.Path); 672 } 673 }; 674 enum class ConstructionPhase { 675 None, 676 Bases, 677 AfterBases, 678 AfterFields, 679 Destroying, 680 DestroyingBases 681 }; 682 } 683 684 namespace llvm { 685 template<> struct DenseMapInfo<ObjectUnderConstruction> { 686 using Base = DenseMapInfo<APValue::LValueBase>; 687 static ObjectUnderConstruction getEmptyKey() { 688 return {Base::getEmptyKey(), {}}; } 689 static ObjectUnderConstruction getTombstoneKey() { 690 return {Base::getTombstoneKey(), {}}; 691 } 692 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 693 return hash_value(Object); 694 } 695 static bool isEqual(const ObjectUnderConstruction &LHS, 696 const ObjectUnderConstruction &RHS) { 697 return LHS == RHS; 698 } 699 }; 700 } 701 702 namespace { 703 /// A dynamically-allocated heap object. 704 struct DynAlloc { 705 /// The value of this heap-allocated object. 706 APValue Value; 707 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 708 /// or a CallExpr (the latter is for direct calls to operator new inside 709 /// std::allocator<T>::allocate). 710 const Expr *AllocExpr = nullptr; 711 712 enum Kind { 713 New, 714 ArrayNew, 715 StdAllocator 716 }; 717 718 /// Get the kind of the allocation. This must match between allocation 719 /// and deallocation. 720 Kind getKind() const { 721 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 722 return NE->isArray() ? ArrayNew : New; 723 assert(isa<CallExpr>(AllocExpr)); 724 return StdAllocator; 725 } 726 }; 727 728 struct DynAllocOrder { 729 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 730 return L.getIndex() < R.getIndex(); 731 } 732 }; 733 734 /// EvalInfo - This is a private struct used by the evaluator to capture 735 /// information about a subexpression as it is folded. It retains information 736 /// about the AST context, but also maintains information about the folded 737 /// expression. 738 /// 739 /// If an expression could be evaluated, it is still possible it is not a C 740 /// "integer constant expression" or constant expression. If not, this struct 741 /// captures information about how and why not. 742 /// 743 /// One bit of information passed *into* the request for constant folding 744 /// indicates whether the subexpression is "evaluated" or not according to C 745 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 746 /// evaluate the expression regardless of what the RHS is, but C only allows 747 /// certain things in certain situations. 748 class EvalInfo : public interp::State { 749 public: 750 ASTContext &Ctx; 751 752 /// EvalStatus - Contains information about the evaluation. 753 Expr::EvalStatus &EvalStatus; 754 755 /// CurrentCall - The top of the constexpr call stack. 756 CallStackFrame *CurrentCall; 757 758 /// CallStackDepth - The number of calls in the call stack right now. 759 unsigned CallStackDepth; 760 761 /// NextCallIndex - The next call index to assign. 762 unsigned NextCallIndex; 763 764 /// StepsLeft - The remaining number of evaluation steps we're permitted 765 /// to perform. This is essentially a limit for the number of statements 766 /// we will evaluate. 767 unsigned StepsLeft; 768 769 /// Enable the experimental new constant interpreter. If an expression is 770 /// not supported by the interpreter, an error is triggered. 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 void finishedConstructingFields() { 827 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 828 } 829 ~EvaluatingConstructorRAII() { 830 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 831 } 832 }; 833 834 struct EvaluatingDestructorRAII { 835 EvalInfo &EI; 836 ObjectUnderConstruction Object; 837 bool DidInsert; 838 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 839 : EI(EI), Object(Object) { 840 DidInsert = EI.ObjectsUnderConstruction 841 .insert({Object, ConstructionPhase::Destroying}) 842 .second; 843 } 844 void startedDestroyingBases() { 845 EI.ObjectsUnderConstruction[Object] = 846 ConstructionPhase::DestroyingBases; 847 } 848 ~EvaluatingDestructorRAII() { 849 if (DidInsert) 850 EI.ObjectsUnderConstruction.erase(Object); 851 } 852 }; 853 854 ConstructionPhase 855 isEvaluatingCtorDtor(APValue::LValueBase Base, 856 ArrayRef<APValue::LValuePathEntry> Path) { 857 return ObjectsUnderConstruction.lookup({Base, Path}); 858 } 859 860 /// If we're currently speculatively evaluating, the outermost call stack 861 /// depth at which we can mutate state, otherwise 0. 862 unsigned SpeculativeEvaluationDepth = 0; 863 864 /// The current array initialization index, if we're performing array 865 /// initialization. 866 uint64_t ArrayInitIndex = -1; 867 868 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 869 /// notes attached to it will also be stored, otherwise they will not be. 870 bool HasActiveDiagnostic; 871 872 /// Have we emitted a diagnostic explaining why we couldn't constant 873 /// fold (not just why it's not strictly a constant expression)? 874 bool HasFoldFailureDiagnostic; 875 876 /// Whether or not we're in a context where the front end requires a 877 /// constant value. 878 bool InConstantContext; 879 880 /// Whether we're checking that an expression is a potential constant 881 /// expression. If so, do not fail on constructs that could become constant 882 /// later on (such as a use of an undefined global). 883 bool CheckingPotentialConstantExpression = false; 884 885 /// Whether we're checking for an expression that has undefined behavior. 886 /// If so, we will produce warnings if we encounter an operation that is 887 /// always undefined. 888 bool CheckingForUndefinedBehavior = false; 889 890 enum EvaluationMode { 891 /// Evaluate as a constant expression. Stop if we find that the expression 892 /// is not a constant expression. 893 EM_ConstantExpression, 894 895 /// Evaluate as a constant expression. Stop if we find that the expression 896 /// is not a constant expression. Some expressions can be retried in the 897 /// optimizer if we don't constant fold them here, but in an unevaluated 898 /// context we try to fold them immediately since the optimizer never 899 /// gets a chance to look at it. 900 EM_ConstantExpressionUnevaluated, 901 902 /// Fold the expression to a constant. Stop if we hit a side-effect that 903 /// we can't model. 904 EM_ConstantFold, 905 906 /// Evaluate in any way we know how. Don't worry about side-effects that 907 /// can't be modeled. 908 EM_IgnoreSideEffects, 909 } EvalMode; 910 911 /// Are we checking whether the expression is a potential constant 912 /// expression? 913 bool checkingPotentialConstantExpression() const override { 914 return CheckingPotentialConstantExpression; 915 } 916 917 /// Are we checking an expression for overflow? 918 // FIXME: We should check for any kind of undefined or suspicious behavior 919 // in such constructs, not just overflow. 920 bool checkingForUndefinedBehavior() const override { 921 return CheckingForUndefinedBehavior; 922 } 923 924 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 925 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 926 CallStackDepth(0), NextCallIndex(1), 927 StepsLeft(C.getLangOpts().ConstexprStepLimit), 928 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 929 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 930 EvaluatingDecl((const ValueDecl *)nullptr), 931 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 932 HasFoldFailureDiagnostic(false), InConstantContext(false), 933 EvalMode(Mode) {} 934 935 ~EvalInfo() { 936 discardCleanups(); 937 } 938 939 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 940 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 941 EvaluatingDecl = Base; 942 IsEvaluatingDecl = EDK; 943 EvaluatingDeclValue = &Value; 944 } 945 946 bool CheckCallLimit(SourceLocation Loc) { 947 // Don't perform any constexpr calls (other than the call we're checking) 948 // when checking a potential constant expression. 949 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 950 return false; 951 if (NextCallIndex == 0) { 952 // NextCallIndex has wrapped around. 953 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 954 return false; 955 } 956 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 957 return true; 958 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 959 << getLangOpts().ConstexprCallDepth; 960 return false; 961 } 962 963 std::pair<CallStackFrame *, unsigned> 964 getCallFrameAndDepth(unsigned CallIndex) { 965 assert(CallIndex && "no call index in getCallFrameAndDepth"); 966 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 967 // be null in this loop. 968 unsigned Depth = CallStackDepth; 969 CallStackFrame *Frame = CurrentCall; 970 while (Frame->Index > CallIndex) { 971 Frame = Frame->Caller; 972 --Depth; 973 } 974 if (Frame->Index == CallIndex) 975 return {Frame, Depth}; 976 return {nullptr, 0}; 977 } 978 979 bool nextStep(const Stmt *S) { 980 if (!StepsLeft) { 981 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 982 return false; 983 } 984 --StepsLeft; 985 return true; 986 } 987 988 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 989 990 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 991 Optional<DynAlloc*> Result; 992 auto It = HeapAllocs.find(DA); 993 if (It != HeapAllocs.end()) 994 Result = &It->second; 995 return Result; 996 } 997 998 /// Information about a stack frame for std::allocator<T>::[de]allocate. 999 struct StdAllocatorCaller { 1000 unsigned FrameIndex; 1001 QualType ElemType; 1002 explicit operator bool() const { return FrameIndex != 0; }; 1003 }; 1004 1005 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1006 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1007 Call = Call->Caller) { 1008 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1009 if (!MD) 1010 continue; 1011 const IdentifierInfo *FnII = MD->getIdentifier(); 1012 if (!FnII || !FnII->isStr(FnName)) 1013 continue; 1014 1015 const auto *CTSD = 1016 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1017 if (!CTSD) 1018 continue; 1019 1020 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1021 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1022 if (CTSD->isInStdNamespace() && ClassII && 1023 ClassII->isStr("allocator") && TAL.size() >= 1 && 1024 TAL[0].getKind() == TemplateArgument::Type) 1025 return {Call->Index, TAL[0].getAsType()}; 1026 } 1027 1028 return {}; 1029 } 1030 1031 void performLifetimeExtension() { 1032 // Disable the cleanups for lifetime-extended temporaries. 1033 CleanupStack.erase( 1034 std::remove_if(CleanupStack.begin(), CleanupStack.end(), 1035 [](Cleanup &C) { return C.isLifetimeExtended(); }), 1036 CleanupStack.end()); 1037 } 1038 1039 /// Throw away any remaining cleanups at the end of evaluation. If any 1040 /// cleanups would have had a side-effect, note that as an unmodeled 1041 /// side-effect and return false. Otherwise, return true. 1042 bool discardCleanups() { 1043 for (Cleanup &C : CleanupStack) { 1044 if (C.hasSideEffect() && !noteSideEffect()) { 1045 CleanupStack.clear(); 1046 return false; 1047 } 1048 } 1049 CleanupStack.clear(); 1050 return true; 1051 } 1052 1053 private: 1054 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1055 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1056 1057 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1058 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1059 1060 void setFoldFailureDiagnostic(bool Flag) override { 1061 HasFoldFailureDiagnostic = Flag; 1062 } 1063 1064 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1065 1066 ASTContext &getCtx() const override { return Ctx; } 1067 1068 // If we have a prior diagnostic, it will be noting that the expression 1069 // isn't a constant expression. This diagnostic is more important, 1070 // unless we require this evaluation to produce a constant expression. 1071 // 1072 // FIXME: We might want to show both diagnostics to the user in 1073 // EM_ConstantFold mode. 1074 bool hasPriorDiagnostic() override { 1075 if (!EvalStatus.Diag->empty()) { 1076 switch (EvalMode) { 1077 case EM_ConstantFold: 1078 case EM_IgnoreSideEffects: 1079 if (!HasFoldFailureDiagnostic) 1080 break; 1081 // We've already failed to fold something. Keep that diagnostic. 1082 LLVM_FALLTHROUGH; 1083 case EM_ConstantExpression: 1084 case EM_ConstantExpressionUnevaluated: 1085 setActiveDiagnostic(false); 1086 return true; 1087 } 1088 } 1089 return false; 1090 } 1091 1092 unsigned getCallStackDepth() override { return CallStackDepth; } 1093 1094 public: 1095 /// Should we continue evaluation after encountering a side-effect that we 1096 /// couldn't model? 1097 bool keepEvaluatingAfterSideEffect() { 1098 switch (EvalMode) { 1099 case EM_IgnoreSideEffects: 1100 return true; 1101 1102 case EM_ConstantExpression: 1103 case EM_ConstantExpressionUnevaluated: 1104 case EM_ConstantFold: 1105 // By default, assume any side effect might be valid in some other 1106 // evaluation of this expression from a different context. 1107 return checkingPotentialConstantExpression() || 1108 checkingForUndefinedBehavior(); 1109 } 1110 llvm_unreachable("Missed EvalMode case"); 1111 } 1112 1113 /// Note that we have had a side-effect, and determine whether we should 1114 /// keep evaluating. 1115 bool noteSideEffect() { 1116 EvalStatus.HasSideEffects = true; 1117 return keepEvaluatingAfterSideEffect(); 1118 } 1119 1120 /// Should we continue evaluation after encountering undefined behavior? 1121 bool keepEvaluatingAfterUndefinedBehavior() { 1122 switch (EvalMode) { 1123 case EM_IgnoreSideEffects: 1124 case EM_ConstantFold: 1125 return true; 1126 1127 case EM_ConstantExpression: 1128 case EM_ConstantExpressionUnevaluated: 1129 return checkingForUndefinedBehavior(); 1130 } 1131 llvm_unreachable("Missed EvalMode case"); 1132 } 1133 1134 /// Note that we hit something that was technically undefined behavior, but 1135 /// that we can evaluate past it (such as signed overflow or floating-point 1136 /// division by zero.) 1137 bool noteUndefinedBehavior() override { 1138 EvalStatus.HasUndefinedBehavior = true; 1139 return keepEvaluatingAfterUndefinedBehavior(); 1140 } 1141 1142 /// Should we continue evaluation as much as possible after encountering a 1143 /// construct which can't be reduced to a value? 1144 bool keepEvaluatingAfterFailure() const override { 1145 if (!StepsLeft) 1146 return false; 1147 1148 switch (EvalMode) { 1149 case EM_ConstantExpression: 1150 case EM_ConstantExpressionUnevaluated: 1151 case EM_ConstantFold: 1152 case EM_IgnoreSideEffects: 1153 return checkingPotentialConstantExpression() || 1154 checkingForUndefinedBehavior(); 1155 } 1156 llvm_unreachable("Missed EvalMode case"); 1157 } 1158 1159 /// Notes that we failed to evaluate an expression that other expressions 1160 /// directly depend on, and determine if we should keep evaluating. This 1161 /// should only be called if we actually intend to keep evaluating. 1162 /// 1163 /// Call noteSideEffect() instead if we may be able to ignore the value that 1164 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1165 /// 1166 /// (Foo(), 1) // use noteSideEffect 1167 /// (Foo() || true) // use noteSideEffect 1168 /// Foo() + 1 // use noteFailure 1169 LLVM_NODISCARD bool noteFailure() { 1170 // Failure when evaluating some expression often means there is some 1171 // subexpression whose evaluation was skipped. Therefore, (because we 1172 // don't track whether we skipped an expression when unwinding after an 1173 // evaluation failure) every evaluation failure that bubbles up from a 1174 // subexpression implies that a side-effect has potentially happened. We 1175 // skip setting the HasSideEffects flag to true until we decide to 1176 // continue evaluating after that point, which happens here. 1177 bool KeepGoing = keepEvaluatingAfterFailure(); 1178 EvalStatus.HasSideEffects |= KeepGoing; 1179 return KeepGoing; 1180 } 1181 1182 class ArrayInitLoopIndex { 1183 EvalInfo &Info; 1184 uint64_t OuterIndex; 1185 1186 public: 1187 ArrayInitLoopIndex(EvalInfo &Info) 1188 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1189 Info.ArrayInitIndex = 0; 1190 } 1191 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1192 1193 operator uint64_t&() { return Info.ArrayInitIndex; } 1194 }; 1195 }; 1196 1197 /// Object used to treat all foldable expressions as constant expressions. 1198 struct FoldConstant { 1199 EvalInfo &Info; 1200 bool Enabled; 1201 bool HadNoPriorDiags; 1202 EvalInfo::EvaluationMode OldMode; 1203 1204 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1205 : Info(Info), 1206 Enabled(Enabled), 1207 HadNoPriorDiags(Info.EvalStatus.Diag && 1208 Info.EvalStatus.Diag->empty() && 1209 !Info.EvalStatus.HasSideEffects), 1210 OldMode(Info.EvalMode) { 1211 if (Enabled) 1212 Info.EvalMode = EvalInfo::EM_ConstantFold; 1213 } 1214 void keepDiagnostics() { Enabled = false; } 1215 ~FoldConstant() { 1216 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1217 !Info.EvalStatus.HasSideEffects) 1218 Info.EvalStatus.Diag->clear(); 1219 Info.EvalMode = OldMode; 1220 } 1221 }; 1222 1223 /// RAII object used to set the current evaluation mode to ignore 1224 /// side-effects. 1225 struct IgnoreSideEffectsRAII { 1226 EvalInfo &Info; 1227 EvalInfo::EvaluationMode OldMode; 1228 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1229 : Info(Info), OldMode(Info.EvalMode) { 1230 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1231 } 1232 1233 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1234 }; 1235 1236 /// RAII object used to optionally suppress diagnostics and side-effects from 1237 /// a speculative evaluation. 1238 class SpeculativeEvaluationRAII { 1239 EvalInfo *Info = nullptr; 1240 Expr::EvalStatus OldStatus; 1241 unsigned OldSpeculativeEvaluationDepth; 1242 1243 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1244 Info = Other.Info; 1245 OldStatus = Other.OldStatus; 1246 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1247 Other.Info = nullptr; 1248 } 1249 1250 void maybeRestoreState() { 1251 if (!Info) 1252 return; 1253 1254 Info->EvalStatus = OldStatus; 1255 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1256 } 1257 1258 public: 1259 SpeculativeEvaluationRAII() = default; 1260 1261 SpeculativeEvaluationRAII( 1262 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1263 : Info(&Info), OldStatus(Info.EvalStatus), 1264 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1265 Info.EvalStatus.Diag = NewDiag; 1266 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1267 } 1268 1269 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1270 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1271 moveFromAndCancel(std::move(Other)); 1272 } 1273 1274 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1275 maybeRestoreState(); 1276 moveFromAndCancel(std::move(Other)); 1277 return *this; 1278 } 1279 1280 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1281 }; 1282 1283 /// RAII object wrapping a full-expression or block scope, and handling 1284 /// the ending of the lifetime of temporaries created within it. 1285 template<bool IsFullExpression> 1286 class ScopeRAII { 1287 EvalInfo &Info; 1288 unsigned OldStackSize; 1289 public: 1290 ScopeRAII(EvalInfo &Info) 1291 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1292 // Push a new temporary version. This is needed to distinguish between 1293 // temporaries created in different iterations of a loop. 1294 Info.CurrentCall->pushTempVersion(); 1295 } 1296 bool destroy(bool RunDestructors = true) { 1297 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1298 OldStackSize = -1U; 1299 return OK; 1300 } 1301 ~ScopeRAII() { 1302 if (OldStackSize != -1U) 1303 destroy(false); 1304 // Body moved to a static method to encourage the compiler to inline away 1305 // instances of this class. 1306 Info.CurrentCall->popTempVersion(); 1307 } 1308 private: 1309 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1310 unsigned OldStackSize) { 1311 assert(OldStackSize <= Info.CleanupStack.size() && 1312 "running cleanups out of order?"); 1313 1314 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1315 // for a full-expression scope. 1316 bool Success = true; 1317 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1318 if (!(IsFullExpression && 1319 Info.CleanupStack[I - 1].isLifetimeExtended())) { 1320 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1321 Success = false; 1322 break; 1323 } 1324 } 1325 } 1326 1327 // Compact lifetime-extended cleanups. 1328 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1329 if (IsFullExpression) 1330 NewEnd = 1331 std::remove_if(NewEnd, Info.CleanupStack.end(), 1332 [](Cleanup &C) { return !C.isLifetimeExtended(); }); 1333 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1334 return Success; 1335 } 1336 }; 1337 typedef ScopeRAII<false> BlockScopeRAII; 1338 typedef ScopeRAII<true> FullExpressionRAII; 1339 } 1340 1341 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1342 CheckSubobjectKind CSK) { 1343 if (Invalid) 1344 return false; 1345 if (isOnePastTheEnd()) { 1346 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1347 << CSK; 1348 setInvalid(); 1349 return false; 1350 } 1351 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1352 // must actually be at least one array element; even a VLA cannot have a 1353 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1354 return true; 1355 } 1356 1357 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1358 const Expr *E) { 1359 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1360 // Do not set the designator as invalid: we can represent this situation, 1361 // and correct handling of __builtin_object_size requires us to do so. 1362 } 1363 1364 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1365 const Expr *E, 1366 const APSInt &N) { 1367 // If we're complaining, we must be able to statically determine the size of 1368 // the most derived array. 1369 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1370 Info.CCEDiag(E, diag::note_constexpr_array_index) 1371 << N << /*array*/ 0 1372 << static_cast<unsigned>(getMostDerivedArraySize()); 1373 else 1374 Info.CCEDiag(E, diag::note_constexpr_array_index) 1375 << N << /*non-array*/ 1; 1376 setInvalid(); 1377 } 1378 1379 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1380 const FunctionDecl *Callee, const LValue *This, 1381 APValue *Arguments) 1382 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1383 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1384 Info.CurrentCall = this; 1385 ++Info.CallStackDepth; 1386 } 1387 1388 CallStackFrame::~CallStackFrame() { 1389 assert(Info.CurrentCall == this && "calls retired out of order"); 1390 --Info.CallStackDepth; 1391 Info.CurrentCall = Caller; 1392 } 1393 1394 static bool isRead(AccessKinds AK) { 1395 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1396 } 1397 1398 static bool isModification(AccessKinds AK) { 1399 switch (AK) { 1400 case AK_Read: 1401 case AK_ReadObjectRepresentation: 1402 case AK_MemberCall: 1403 case AK_DynamicCast: 1404 case AK_TypeId: 1405 return false; 1406 case AK_Assign: 1407 case AK_Increment: 1408 case AK_Decrement: 1409 case AK_Construct: 1410 case AK_Destroy: 1411 return true; 1412 } 1413 llvm_unreachable("unknown access kind"); 1414 } 1415 1416 static bool isAnyAccess(AccessKinds AK) { 1417 return isRead(AK) || isModification(AK); 1418 } 1419 1420 /// Is this an access per the C++ definition? 1421 static bool isFormalAccess(AccessKinds AK) { 1422 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1423 } 1424 1425 /// Is this kind of axcess valid on an indeterminate object value? 1426 static bool isValidIndeterminateAccess(AccessKinds AK) { 1427 switch (AK) { 1428 case AK_Read: 1429 case AK_Increment: 1430 case AK_Decrement: 1431 // These need the object's value. 1432 return false; 1433 1434 case AK_ReadObjectRepresentation: 1435 case AK_Assign: 1436 case AK_Construct: 1437 case AK_Destroy: 1438 // Construction and destruction don't need the value. 1439 return true; 1440 1441 case AK_MemberCall: 1442 case AK_DynamicCast: 1443 case AK_TypeId: 1444 // These aren't really meaningful on scalars. 1445 return true; 1446 } 1447 llvm_unreachable("unknown access kind"); 1448 } 1449 1450 namespace { 1451 struct ComplexValue { 1452 private: 1453 bool IsInt; 1454 1455 public: 1456 APSInt IntReal, IntImag; 1457 APFloat FloatReal, FloatImag; 1458 1459 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1460 1461 void makeComplexFloat() { IsInt = false; } 1462 bool isComplexFloat() const { return !IsInt; } 1463 APFloat &getComplexFloatReal() { return FloatReal; } 1464 APFloat &getComplexFloatImag() { return FloatImag; } 1465 1466 void makeComplexInt() { IsInt = true; } 1467 bool isComplexInt() const { return IsInt; } 1468 APSInt &getComplexIntReal() { return IntReal; } 1469 APSInt &getComplexIntImag() { return IntImag; } 1470 1471 void moveInto(APValue &v) const { 1472 if (isComplexFloat()) 1473 v = APValue(FloatReal, FloatImag); 1474 else 1475 v = APValue(IntReal, IntImag); 1476 } 1477 void setFrom(const APValue &v) { 1478 assert(v.isComplexFloat() || v.isComplexInt()); 1479 if (v.isComplexFloat()) { 1480 makeComplexFloat(); 1481 FloatReal = v.getComplexFloatReal(); 1482 FloatImag = v.getComplexFloatImag(); 1483 } else { 1484 makeComplexInt(); 1485 IntReal = v.getComplexIntReal(); 1486 IntImag = v.getComplexIntImag(); 1487 } 1488 } 1489 }; 1490 1491 struct LValue { 1492 APValue::LValueBase Base; 1493 CharUnits Offset; 1494 SubobjectDesignator Designator; 1495 bool IsNullPtr : 1; 1496 bool InvalidBase : 1; 1497 1498 const APValue::LValueBase getLValueBase() const { return Base; } 1499 CharUnits &getLValueOffset() { return Offset; } 1500 const CharUnits &getLValueOffset() const { return Offset; } 1501 SubobjectDesignator &getLValueDesignator() { return Designator; } 1502 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1503 bool isNullPointer() const { return IsNullPtr;} 1504 1505 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1506 unsigned getLValueVersion() const { return Base.getVersion(); } 1507 1508 void moveInto(APValue &V) const { 1509 if (Designator.Invalid) 1510 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1511 else { 1512 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1513 V = APValue(Base, Offset, Designator.Entries, 1514 Designator.IsOnePastTheEnd, IsNullPtr); 1515 } 1516 } 1517 void setFrom(ASTContext &Ctx, const APValue &V) { 1518 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1519 Base = V.getLValueBase(); 1520 Offset = V.getLValueOffset(); 1521 InvalidBase = false; 1522 Designator = SubobjectDesignator(Ctx, V); 1523 IsNullPtr = V.isNullPointer(); 1524 } 1525 1526 void set(APValue::LValueBase B, bool BInvalid = false) { 1527 #ifndef NDEBUG 1528 // We only allow a few types of invalid bases. Enforce that here. 1529 if (BInvalid) { 1530 const auto *E = B.get<const Expr *>(); 1531 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1532 "Unexpected type of invalid base"); 1533 } 1534 #endif 1535 1536 Base = B; 1537 Offset = CharUnits::fromQuantity(0); 1538 InvalidBase = BInvalid; 1539 Designator = SubobjectDesignator(getType(B)); 1540 IsNullPtr = false; 1541 } 1542 1543 void setNull(ASTContext &Ctx, QualType PointerTy) { 1544 Base = (Expr *)nullptr; 1545 Offset = 1546 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1547 InvalidBase = false; 1548 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1549 IsNullPtr = true; 1550 } 1551 1552 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1553 set(B, true); 1554 } 1555 1556 std::string toString(ASTContext &Ctx, QualType T) const { 1557 APValue Printable; 1558 moveInto(Printable); 1559 return Printable.getAsString(Ctx, T); 1560 } 1561 1562 private: 1563 // Check that this LValue is not based on a null pointer. If it is, produce 1564 // a diagnostic and mark the designator as invalid. 1565 template <typename GenDiagType> 1566 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1567 if (Designator.Invalid) 1568 return false; 1569 if (IsNullPtr) { 1570 GenDiag(); 1571 Designator.setInvalid(); 1572 return false; 1573 } 1574 return true; 1575 } 1576 1577 public: 1578 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1579 CheckSubobjectKind CSK) { 1580 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1581 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1582 }); 1583 } 1584 1585 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1586 AccessKinds AK) { 1587 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1588 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1589 }); 1590 } 1591 1592 // Check this LValue refers to an object. If not, set the designator to be 1593 // invalid and emit a diagnostic. 1594 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1595 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1596 Designator.checkSubobject(Info, E, CSK); 1597 } 1598 1599 void addDecl(EvalInfo &Info, const Expr *E, 1600 const Decl *D, bool Virtual = false) { 1601 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1602 Designator.addDeclUnchecked(D, Virtual); 1603 } 1604 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1605 if (!Designator.Entries.empty()) { 1606 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1607 Designator.setInvalid(); 1608 return; 1609 } 1610 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1611 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1612 Designator.FirstEntryIsAnUnsizedArray = true; 1613 Designator.addUnsizedArrayUnchecked(ElemTy); 1614 } 1615 } 1616 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1617 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1618 Designator.addArrayUnchecked(CAT); 1619 } 1620 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1621 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1622 Designator.addComplexUnchecked(EltTy, Imag); 1623 } 1624 void clearIsNullPointer() { 1625 IsNullPtr = false; 1626 } 1627 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1628 const APSInt &Index, CharUnits ElementSize) { 1629 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1630 // but we're not required to diagnose it and it's valid in C++.) 1631 if (!Index) 1632 return; 1633 1634 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1635 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1636 // offsets. 1637 uint64_t Offset64 = Offset.getQuantity(); 1638 uint64_t ElemSize64 = ElementSize.getQuantity(); 1639 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1640 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1641 1642 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1643 Designator.adjustIndex(Info, E, Index); 1644 clearIsNullPointer(); 1645 } 1646 void adjustOffset(CharUnits N) { 1647 Offset += N; 1648 if (N.getQuantity()) 1649 clearIsNullPointer(); 1650 } 1651 }; 1652 1653 struct MemberPtr { 1654 MemberPtr() {} 1655 explicit MemberPtr(const ValueDecl *Decl) : 1656 DeclAndIsDerivedMember(Decl, false), Path() {} 1657 1658 /// The member or (direct or indirect) field referred to by this member 1659 /// pointer, or 0 if this is a null member pointer. 1660 const ValueDecl *getDecl() const { 1661 return DeclAndIsDerivedMember.getPointer(); 1662 } 1663 /// Is this actually a member of some type derived from the relevant class? 1664 bool isDerivedMember() const { 1665 return DeclAndIsDerivedMember.getInt(); 1666 } 1667 /// Get the class which the declaration actually lives in. 1668 const CXXRecordDecl *getContainingRecord() const { 1669 return cast<CXXRecordDecl>( 1670 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1671 } 1672 1673 void moveInto(APValue &V) const { 1674 V = APValue(getDecl(), isDerivedMember(), Path); 1675 } 1676 void setFrom(const APValue &V) { 1677 assert(V.isMemberPointer()); 1678 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1679 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1680 Path.clear(); 1681 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1682 Path.insert(Path.end(), P.begin(), P.end()); 1683 } 1684 1685 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1686 /// whether the member is a member of some class derived from the class type 1687 /// of the member pointer. 1688 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1689 /// Path - The path of base/derived classes from the member declaration's 1690 /// class (exclusive) to the class type of the member pointer (inclusive). 1691 SmallVector<const CXXRecordDecl*, 4> Path; 1692 1693 /// Perform a cast towards the class of the Decl (either up or down the 1694 /// hierarchy). 1695 bool castBack(const CXXRecordDecl *Class) { 1696 assert(!Path.empty()); 1697 const CXXRecordDecl *Expected; 1698 if (Path.size() >= 2) 1699 Expected = Path[Path.size() - 2]; 1700 else 1701 Expected = getContainingRecord(); 1702 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1703 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1704 // if B does not contain the original member and is not a base or 1705 // derived class of the class containing the original member, the result 1706 // of the cast is undefined. 1707 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1708 // (D::*). We consider that to be a language defect. 1709 return false; 1710 } 1711 Path.pop_back(); 1712 return true; 1713 } 1714 /// Perform a base-to-derived member pointer cast. 1715 bool castToDerived(const CXXRecordDecl *Derived) { 1716 if (!getDecl()) 1717 return true; 1718 if (!isDerivedMember()) { 1719 Path.push_back(Derived); 1720 return true; 1721 } 1722 if (!castBack(Derived)) 1723 return false; 1724 if (Path.empty()) 1725 DeclAndIsDerivedMember.setInt(false); 1726 return true; 1727 } 1728 /// Perform a derived-to-base member pointer cast. 1729 bool castToBase(const CXXRecordDecl *Base) { 1730 if (!getDecl()) 1731 return true; 1732 if (Path.empty()) 1733 DeclAndIsDerivedMember.setInt(true); 1734 if (isDerivedMember()) { 1735 Path.push_back(Base); 1736 return true; 1737 } 1738 return castBack(Base); 1739 } 1740 }; 1741 1742 /// Compare two member pointers, which are assumed to be of the same type. 1743 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1744 if (!LHS.getDecl() || !RHS.getDecl()) 1745 return !LHS.getDecl() && !RHS.getDecl(); 1746 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1747 return false; 1748 return LHS.Path == RHS.Path; 1749 } 1750 } 1751 1752 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1753 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1754 const LValue &This, const Expr *E, 1755 bool AllowNonLiteralTypes = false); 1756 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1757 bool InvalidBaseOK = false); 1758 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1759 bool InvalidBaseOK = false); 1760 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1761 EvalInfo &Info); 1762 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1763 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1764 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1765 EvalInfo &Info); 1766 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1767 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1768 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1769 EvalInfo &Info); 1770 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1771 1772 /// Evaluate an integer or fixed point expression into an APResult. 1773 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1774 EvalInfo &Info); 1775 1776 /// Evaluate only a fixed point expression into an APResult. 1777 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1778 EvalInfo &Info); 1779 1780 //===----------------------------------------------------------------------===// 1781 // Misc utilities 1782 //===----------------------------------------------------------------------===// 1783 1784 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1785 /// preserving its value (by extending by up to one bit as needed). 1786 static void negateAsSigned(APSInt &Int) { 1787 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1788 Int = Int.extend(Int.getBitWidth() + 1); 1789 Int.setIsSigned(true); 1790 } 1791 Int = -Int; 1792 } 1793 1794 template<typename KeyT> 1795 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1796 bool IsLifetimeExtended, LValue &LV) { 1797 unsigned Version = getTempVersion(); 1798 APValue::LValueBase Base(Key, Index, Version); 1799 LV.set(Base); 1800 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1801 assert(Result.isAbsent() && "temporary created multiple times"); 1802 1803 // If we're creating a temporary immediately in the operand of a speculative 1804 // evaluation, don't register a cleanup to be run outside the speculative 1805 // evaluation context, since we won't actually be able to initialize this 1806 // object. 1807 if (Index <= Info.SpeculativeEvaluationDepth) { 1808 if (T.isDestructedType()) 1809 Info.noteSideEffect(); 1810 } else { 1811 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended)); 1812 } 1813 return Result; 1814 } 1815 1816 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1817 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1818 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1819 return nullptr; 1820 } 1821 1822 DynamicAllocLValue DA(NumHeapAllocs++); 1823 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1824 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1825 std::forward_as_tuple(DA), std::tuple<>()); 1826 assert(Result.second && "reused a heap alloc index?"); 1827 Result.first->second.AllocExpr = E; 1828 return &Result.first->second.Value; 1829 } 1830 1831 /// Produce a string describing the given constexpr call. 1832 void CallStackFrame::describe(raw_ostream &Out) { 1833 unsigned ArgIndex = 0; 1834 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1835 !isa<CXXConstructorDecl>(Callee) && 1836 cast<CXXMethodDecl>(Callee)->isInstance(); 1837 1838 if (!IsMemberCall) 1839 Out << *Callee << '('; 1840 1841 if (This && IsMemberCall) { 1842 APValue Val; 1843 This->moveInto(Val); 1844 Val.printPretty(Out, Info.Ctx, 1845 This->Designator.MostDerivedType); 1846 // FIXME: Add parens around Val if needed. 1847 Out << "->" << *Callee << '('; 1848 IsMemberCall = false; 1849 } 1850 1851 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1852 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1853 if (ArgIndex > (unsigned)IsMemberCall) 1854 Out << ", "; 1855 1856 const ParmVarDecl *Param = *I; 1857 const APValue &Arg = Arguments[ArgIndex]; 1858 Arg.printPretty(Out, Info.Ctx, Param->getType()); 1859 1860 if (ArgIndex == 0 && IsMemberCall) 1861 Out << "->" << *Callee << '('; 1862 } 1863 1864 Out << ')'; 1865 } 1866 1867 /// Evaluate an expression to see if it had side-effects, and discard its 1868 /// result. 1869 /// \return \c true if the caller should keep evaluating. 1870 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1871 APValue Scratch; 1872 if (!Evaluate(Scratch, Info, E)) 1873 // We don't need the value, but we might have skipped a side effect here. 1874 return Info.noteSideEffect(); 1875 return true; 1876 } 1877 1878 /// Should this call expression be treated as a string literal? 1879 static bool IsStringLiteralCall(const CallExpr *E) { 1880 unsigned Builtin = E->getBuiltinCallee(); 1881 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1882 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1883 } 1884 1885 static bool IsGlobalLValue(APValue::LValueBase B) { 1886 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1887 // constant expression of pointer type that evaluates to... 1888 1889 // ... a null pointer value, or a prvalue core constant expression of type 1890 // std::nullptr_t. 1891 if (!B) return true; 1892 1893 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1894 // ... the address of an object with static storage duration, 1895 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1896 return VD->hasGlobalStorage(); 1897 // ... the address of a function, 1898 // ... the address of a GUID [MS extension], 1899 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1900 } 1901 1902 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1903 return true; 1904 1905 const Expr *E = B.get<const Expr*>(); 1906 switch (E->getStmtClass()) { 1907 default: 1908 return false; 1909 case Expr::CompoundLiteralExprClass: { 1910 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1911 return CLE->isFileScope() && CLE->isLValue(); 1912 } 1913 case Expr::MaterializeTemporaryExprClass: 1914 // A materialized temporary might have been lifetime-extended to static 1915 // storage duration. 1916 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1917 // A string literal has static storage duration. 1918 case Expr::StringLiteralClass: 1919 case Expr::PredefinedExprClass: 1920 case Expr::ObjCStringLiteralClass: 1921 case Expr::ObjCEncodeExprClass: 1922 return true; 1923 case Expr::ObjCBoxedExprClass: 1924 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1925 case Expr::CallExprClass: 1926 return IsStringLiteralCall(cast<CallExpr>(E)); 1927 // For GCC compatibility, &&label has static storage duration. 1928 case Expr::AddrLabelExprClass: 1929 return true; 1930 // A Block literal expression may be used as the initialization value for 1931 // Block variables at global or local static scope. 1932 case Expr::BlockExprClass: 1933 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1934 case Expr::ImplicitValueInitExprClass: 1935 // FIXME: 1936 // We can never form an lvalue with an implicit value initialization as its 1937 // base through expression evaluation, so these only appear in one case: the 1938 // implicit variable declaration we invent when checking whether a constexpr 1939 // constructor can produce a constant expression. We must assume that such 1940 // an expression might be a global lvalue. 1941 return true; 1942 } 1943 } 1944 1945 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1946 return LVal.Base.dyn_cast<const ValueDecl*>(); 1947 } 1948 1949 static bool IsLiteralLValue(const LValue &Value) { 1950 if (Value.getLValueCallIndex()) 1951 return false; 1952 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1953 return E && !isa<MaterializeTemporaryExpr>(E); 1954 } 1955 1956 static bool IsWeakLValue(const LValue &Value) { 1957 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1958 return Decl && Decl->isWeak(); 1959 } 1960 1961 static bool isZeroSized(const LValue &Value) { 1962 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1963 if (Decl && isa<VarDecl>(Decl)) { 1964 QualType Ty = Decl->getType(); 1965 if (Ty->isArrayType()) 1966 return Ty->isIncompleteType() || 1967 Decl->getASTContext().getTypeSize(Ty) == 0; 1968 } 1969 return false; 1970 } 1971 1972 static bool HasSameBase(const LValue &A, const LValue &B) { 1973 if (!A.getLValueBase()) 1974 return !B.getLValueBase(); 1975 if (!B.getLValueBase()) 1976 return false; 1977 1978 if (A.getLValueBase().getOpaqueValue() != 1979 B.getLValueBase().getOpaqueValue()) { 1980 const Decl *ADecl = GetLValueBaseDecl(A); 1981 if (!ADecl) 1982 return false; 1983 const Decl *BDecl = GetLValueBaseDecl(B); 1984 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1985 return false; 1986 } 1987 1988 return IsGlobalLValue(A.getLValueBase()) || 1989 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1990 A.getLValueVersion() == B.getLValueVersion()); 1991 } 1992 1993 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1994 assert(Base && "no location for a null lvalue"); 1995 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1996 if (VD) 1997 Info.Note(VD->getLocation(), diag::note_declared_at); 1998 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1999 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2000 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2001 // FIXME: Produce a note for dangling pointers too. 2002 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2003 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2004 diag::note_constexpr_dynamic_alloc_here); 2005 } 2006 // We have no information to show for a typeid(T) object. 2007 } 2008 2009 enum class CheckEvaluationResultKind { 2010 ConstantExpression, 2011 FullyInitialized, 2012 }; 2013 2014 /// Materialized temporaries that we've already checked to determine if they're 2015 /// initializsed by a constant expression. 2016 using CheckedTemporaries = 2017 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2018 2019 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2020 EvalInfo &Info, SourceLocation DiagLoc, 2021 QualType Type, const APValue &Value, 2022 Expr::ConstExprUsage Usage, 2023 SourceLocation SubobjectLoc, 2024 CheckedTemporaries &CheckedTemps); 2025 2026 /// Check that this reference or pointer core constant expression is a valid 2027 /// value for an address or reference constant expression. Return true if we 2028 /// can fold this expression, whether or not it's a constant expression. 2029 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2030 QualType Type, const LValue &LVal, 2031 Expr::ConstExprUsage Usage, 2032 CheckedTemporaries &CheckedTemps) { 2033 bool IsReferenceType = Type->isReferenceType(); 2034 2035 APValue::LValueBase Base = LVal.getLValueBase(); 2036 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2037 2038 if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) { 2039 if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 2040 if (FD->isConsteval()) { 2041 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2042 << !Type->isAnyPointerType(); 2043 Info.Note(FD->getLocation(), diag::note_declared_at); 2044 return false; 2045 } 2046 } 2047 } 2048 2049 // Check that the object is a global. Note that the fake 'this' object we 2050 // manufacture when checking potential constant expressions is conservatively 2051 // assumed to be global here. 2052 if (!IsGlobalLValue(Base)) { 2053 if (Info.getLangOpts().CPlusPlus11) { 2054 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2055 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2056 << IsReferenceType << !Designator.Entries.empty() 2057 << !!VD << VD; 2058 2059 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2060 if (VarD && VarD->isConstexpr()) { 2061 // Non-static local constexpr variables have unintuitive semantics: 2062 // constexpr int a = 1; 2063 // constexpr const int *p = &a; 2064 // ... is invalid because the address of 'a' is not constant. Suggest 2065 // adding a 'static' in this case. 2066 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2067 << VarD 2068 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2069 } else { 2070 NoteLValueLocation(Info, Base); 2071 } 2072 } else { 2073 Info.FFDiag(Loc); 2074 } 2075 // Don't allow references to temporaries to escape. 2076 return false; 2077 } 2078 assert((Info.checkingPotentialConstantExpression() || 2079 LVal.getLValueCallIndex() == 0) && 2080 "have call index for global lvalue"); 2081 2082 if (Base.is<DynamicAllocLValue>()) { 2083 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2084 << IsReferenceType << !Designator.Entries.empty(); 2085 NoteLValueLocation(Info, Base); 2086 return false; 2087 } 2088 2089 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 2090 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 2091 // Check if this is a thread-local variable. 2092 if (Var->getTLSKind()) 2093 // FIXME: Diagnostic! 2094 return false; 2095 2096 // A dllimport variable never acts like a constant. 2097 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 2098 // FIXME: Diagnostic! 2099 return false; 2100 } 2101 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 2102 // __declspec(dllimport) must be handled very carefully: 2103 // We must never initialize an expression with the thunk in C++. 2104 // Doing otherwise would allow the same id-expression to yield 2105 // different addresses for the same function in different translation 2106 // units. However, this means that we must dynamically initialize the 2107 // expression with the contents of the import address table at runtime. 2108 // 2109 // The C language has no notion of ODR; furthermore, it has no notion of 2110 // dynamic initialization. This means that we are permitted to 2111 // perform initialization with the address of the thunk. 2112 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 2113 FD->hasAttr<DLLImportAttr>()) 2114 // FIXME: Diagnostic! 2115 return false; 2116 } 2117 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2118 Base.dyn_cast<const Expr *>())) { 2119 if (CheckedTemps.insert(MTE).second) { 2120 QualType TempType = getType(Base); 2121 if (TempType.isDestructedType()) { 2122 Info.FFDiag(MTE->getExprLoc(), 2123 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) 2124 << TempType; 2125 return false; 2126 } 2127 2128 APValue *V = MTE->getOrCreateValue(false); 2129 assert(V && "evasluation result refers to uninitialised temporary"); 2130 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2131 Info, MTE->getExprLoc(), TempType, *V, 2132 Usage, SourceLocation(), CheckedTemps)) 2133 return false; 2134 } 2135 } 2136 2137 // Allow address constant expressions to be past-the-end pointers. This is 2138 // an extension: the standard requires them to point to an object. 2139 if (!IsReferenceType) 2140 return true; 2141 2142 // A reference constant expression must refer to an object. 2143 if (!Base) { 2144 // FIXME: diagnostic 2145 Info.CCEDiag(Loc); 2146 return true; 2147 } 2148 2149 // Does this refer one past the end of some object? 2150 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2151 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2152 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2153 << !Designator.Entries.empty() << !!VD << VD; 2154 NoteLValueLocation(Info, Base); 2155 } 2156 2157 return true; 2158 } 2159 2160 /// Member pointers are constant expressions unless they point to a 2161 /// non-virtual dllimport member function. 2162 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2163 SourceLocation Loc, 2164 QualType Type, 2165 const APValue &Value, 2166 Expr::ConstExprUsage Usage) { 2167 const ValueDecl *Member = Value.getMemberPointerDecl(); 2168 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2169 if (!FD) 2170 return true; 2171 if (FD->isConsteval()) { 2172 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2173 Info.Note(FD->getLocation(), diag::note_declared_at); 2174 return false; 2175 } 2176 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2177 !FD->hasAttr<DLLImportAttr>(); 2178 } 2179 2180 /// Check that this core constant expression is of literal type, and if not, 2181 /// produce an appropriate diagnostic. 2182 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2183 const LValue *This = nullptr) { 2184 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2185 return true; 2186 2187 // C++1y: A constant initializer for an object o [...] may also invoke 2188 // constexpr constructors for o and its subobjects even if those objects 2189 // are of non-literal class types. 2190 // 2191 // C++11 missed this detail for aggregates, so classes like this: 2192 // struct foo_t { union { int i; volatile int j; } u; }; 2193 // are not (obviously) initializable like so: 2194 // __attribute__((__require_constant_initialization__)) 2195 // static const foo_t x = {{0}}; 2196 // because "i" is a subobject with non-literal initialization (due to the 2197 // volatile member of the union). See: 2198 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2199 // Therefore, we use the C++1y behavior. 2200 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2201 return true; 2202 2203 // Prvalue constant expressions must be of literal types. 2204 if (Info.getLangOpts().CPlusPlus11) 2205 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2206 << E->getType(); 2207 else 2208 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2209 return false; 2210 } 2211 2212 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2213 EvalInfo &Info, SourceLocation DiagLoc, 2214 QualType Type, const APValue &Value, 2215 Expr::ConstExprUsage Usage, 2216 SourceLocation SubobjectLoc, 2217 CheckedTemporaries &CheckedTemps) { 2218 if (!Value.hasValue()) { 2219 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2220 << true << Type; 2221 if (SubobjectLoc.isValid()) 2222 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2223 return false; 2224 } 2225 2226 // We allow _Atomic(T) to be initialized from anything that T can be 2227 // initialized from. 2228 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2229 Type = AT->getValueType(); 2230 2231 // Core issue 1454: For a literal constant expression of array or class type, 2232 // each subobject of its value shall have been initialized by a constant 2233 // expression. 2234 if (Value.isArray()) { 2235 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2236 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2237 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2238 Value.getArrayInitializedElt(I), Usage, 2239 SubobjectLoc, CheckedTemps)) 2240 return false; 2241 } 2242 if (!Value.hasArrayFiller()) 2243 return true; 2244 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2245 Value.getArrayFiller(), Usage, SubobjectLoc, 2246 CheckedTemps); 2247 } 2248 if (Value.isUnion() && Value.getUnionField()) { 2249 return CheckEvaluationResult( 2250 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2251 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2252 CheckedTemps); 2253 } 2254 if (Value.isStruct()) { 2255 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2256 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2257 unsigned BaseIndex = 0; 2258 for (const CXXBaseSpecifier &BS : CD->bases()) { 2259 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2260 Value.getStructBase(BaseIndex), Usage, 2261 BS.getBeginLoc(), CheckedTemps)) 2262 return false; 2263 ++BaseIndex; 2264 } 2265 } 2266 for (const auto *I : RD->fields()) { 2267 if (I->isUnnamedBitfield()) 2268 continue; 2269 2270 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2271 Value.getStructField(I->getFieldIndex()), 2272 Usage, I->getLocation(), CheckedTemps)) 2273 return false; 2274 } 2275 } 2276 2277 if (Value.isLValue() && 2278 CERK == CheckEvaluationResultKind::ConstantExpression) { 2279 LValue LVal; 2280 LVal.setFrom(Info.Ctx, Value); 2281 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2282 CheckedTemps); 2283 } 2284 2285 if (Value.isMemberPointer() && 2286 CERK == CheckEvaluationResultKind::ConstantExpression) 2287 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2288 2289 // Everything else is fine. 2290 return true; 2291 } 2292 2293 /// Check that this core constant expression value is a valid value for a 2294 /// constant expression. If not, report an appropriate diagnostic. Does not 2295 /// check that the expression is of literal type. 2296 static bool 2297 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2298 const APValue &Value, 2299 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2300 CheckedTemporaries CheckedTemps; 2301 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2302 Info, DiagLoc, Type, Value, Usage, 2303 SourceLocation(), CheckedTemps); 2304 } 2305 2306 /// Check that this evaluated value is fully-initialized and can be loaded by 2307 /// an lvalue-to-rvalue conversion. 2308 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2309 QualType Type, const APValue &Value) { 2310 CheckedTemporaries CheckedTemps; 2311 return CheckEvaluationResult( 2312 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2313 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2314 } 2315 2316 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2317 /// "the allocated storage is deallocated within the evaluation". 2318 static bool CheckMemoryLeaks(EvalInfo &Info) { 2319 if (!Info.HeapAllocs.empty()) { 2320 // We can still fold to a constant despite a compile-time memory leak, 2321 // so long as the heap allocation isn't referenced in the result (we check 2322 // that in CheckConstantExpression). 2323 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2324 diag::note_constexpr_memory_leak) 2325 << unsigned(Info.HeapAllocs.size() - 1); 2326 } 2327 return true; 2328 } 2329 2330 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2331 // A null base expression indicates a null pointer. These are always 2332 // evaluatable, and they are false unless the offset is zero. 2333 if (!Value.getLValueBase()) { 2334 Result = !Value.getLValueOffset().isZero(); 2335 return true; 2336 } 2337 2338 // We have a non-null base. These are generally known to be true, but if it's 2339 // a weak declaration it can be null at runtime. 2340 Result = true; 2341 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2342 return !Decl || !Decl->isWeak(); 2343 } 2344 2345 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2346 switch (Val.getKind()) { 2347 case APValue::None: 2348 case APValue::Indeterminate: 2349 return false; 2350 case APValue::Int: 2351 Result = Val.getInt().getBoolValue(); 2352 return true; 2353 case APValue::FixedPoint: 2354 Result = Val.getFixedPoint().getBoolValue(); 2355 return true; 2356 case APValue::Float: 2357 Result = !Val.getFloat().isZero(); 2358 return true; 2359 case APValue::ComplexInt: 2360 Result = Val.getComplexIntReal().getBoolValue() || 2361 Val.getComplexIntImag().getBoolValue(); 2362 return true; 2363 case APValue::ComplexFloat: 2364 Result = !Val.getComplexFloatReal().isZero() || 2365 !Val.getComplexFloatImag().isZero(); 2366 return true; 2367 case APValue::LValue: 2368 return EvalPointerValueAsBool(Val, Result); 2369 case APValue::MemberPointer: 2370 Result = Val.getMemberPointerDecl(); 2371 return true; 2372 case APValue::Vector: 2373 case APValue::Array: 2374 case APValue::Struct: 2375 case APValue::Union: 2376 case APValue::AddrLabelDiff: 2377 return false; 2378 } 2379 2380 llvm_unreachable("unknown APValue kind"); 2381 } 2382 2383 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2384 EvalInfo &Info) { 2385 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2386 APValue Val; 2387 if (!Evaluate(Val, Info, E)) 2388 return false; 2389 return HandleConversionToBool(Val, Result); 2390 } 2391 2392 template<typename T> 2393 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2394 const T &SrcValue, QualType DestType) { 2395 Info.CCEDiag(E, diag::note_constexpr_overflow) 2396 << SrcValue << DestType; 2397 return Info.noteUndefinedBehavior(); 2398 } 2399 2400 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2401 QualType SrcType, const APFloat &Value, 2402 QualType DestType, APSInt &Result) { 2403 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2404 // Determine whether we are converting to unsigned or signed. 2405 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2406 2407 Result = APSInt(DestWidth, !DestSigned); 2408 bool ignored; 2409 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2410 & APFloat::opInvalidOp) 2411 return HandleOverflow(Info, E, Value, DestType); 2412 return true; 2413 } 2414 2415 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2416 QualType SrcType, QualType DestType, 2417 APFloat &Result) { 2418 APFloat Value = Result; 2419 bool ignored; 2420 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2421 APFloat::rmNearestTiesToEven, &ignored); 2422 return true; 2423 } 2424 2425 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2426 QualType DestType, QualType SrcType, 2427 const APSInt &Value) { 2428 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2429 // Figure out if this is a truncate, extend or noop cast. 2430 // If the input is signed, do a sign extend, noop, or truncate. 2431 APSInt Result = Value.extOrTrunc(DestWidth); 2432 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2433 if (DestType->isBooleanType()) 2434 Result = Value.getBoolValue(); 2435 return Result; 2436 } 2437 2438 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2439 QualType SrcType, const APSInt &Value, 2440 QualType DestType, APFloat &Result) { 2441 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2442 Result.convertFromAPInt(Value, Value.isSigned(), 2443 APFloat::rmNearestTiesToEven); 2444 return true; 2445 } 2446 2447 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2448 APValue &Value, const FieldDecl *FD) { 2449 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2450 2451 if (!Value.isInt()) { 2452 // Trying to store a pointer-cast-to-integer into a bitfield. 2453 // FIXME: In this case, we should provide the diagnostic for casting 2454 // a pointer to an integer. 2455 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2456 Info.FFDiag(E); 2457 return false; 2458 } 2459 2460 APSInt &Int = Value.getInt(); 2461 unsigned OldBitWidth = Int.getBitWidth(); 2462 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2463 if (NewBitWidth < OldBitWidth) 2464 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2465 return true; 2466 } 2467 2468 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2469 llvm::APInt &Res) { 2470 APValue SVal; 2471 if (!Evaluate(SVal, Info, E)) 2472 return false; 2473 if (SVal.isInt()) { 2474 Res = SVal.getInt(); 2475 return true; 2476 } 2477 if (SVal.isFloat()) { 2478 Res = SVal.getFloat().bitcastToAPInt(); 2479 return true; 2480 } 2481 if (SVal.isVector()) { 2482 QualType VecTy = E->getType(); 2483 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2484 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2485 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2486 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2487 Res = llvm::APInt::getNullValue(VecSize); 2488 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2489 APValue &Elt = SVal.getVectorElt(i); 2490 llvm::APInt EltAsInt; 2491 if (Elt.isInt()) { 2492 EltAsInt = Elt.getInt(); 2493 } else if (Elt.isFloat()) { 2494 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2495 } else { 2496 // Don't try to handle vectors of anything other than int or float 2497 // (not sure if it's possible to hit this case). 2498 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2499 return false; 2500 } 2501 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2502 if (BigEndian) 2503 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2504 else 2505 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2506 } 2507 return true; 2508 } 2509 // Give up if the input isn't an int, float, or vector. For example, we 2510 // reject "(v4i16)(intptr_t)&a". 2511 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2512 return false; 2513 } 2514 2515 /// Perform the given integer operation, which is known to need at most BitWidth 2516 /// bits, and check for overflow in the original type (if that type was not an 2517 /// unsigned type). 2518 template<typename Operation> 2519 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2520 const APSInt &LHS, const APSInt &RHS, 2521 unsigned BitWidth, Operation Op, 2522 APSInt &Result) { 2523 if (LHS.isUnsigned()) { 2524 Result = Op(LHS, RHS); 2525 return true; 2526 } 2527 2528 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2529 Result = Value.trunc(LHS.getBitWidth()); 2530 if (Result.extend(BitWidth) != Value) { 2531 if (Info.checkingForUndefinedBehavior()) 2532 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2533 diag::warn_integer_constant_overflow) 2534 << Result.toString(10) << E->getType(); 2535 else 2536 return HandleOverflow(Info, E, Value, E->getType()); 2537 } 2538 return true; 2539 } 2540 2541 /// Perform the given binary integer operation. 2542 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2543 BinaryOperatorKind Opcode, APSInt RHS, 2544 APSInt &Result) { 2545 switch (Opcode) { 2546 default: 2547 Info.FFDiag(E); 2548 return false; 2549 case BO_Mul: 2550 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2551 std::multiplies<APSInt>(), Result); 2552 case BO_Add: 2553 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2554 std::plus<APSInt>(), Result); 2555 case BO_Sub: 2556 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2557 std::minus<APSInt>(), Result); 2558 case BO_And: Result = LHS & RHS; return true; 2559 case BO_Xor: Result = LHS ^ RHS; return true; 2560 case BO_Or: Result = LHS | RHS; return true; 2561 case BO_Div: 2562 case BO_Rem: 2563 if (RHS == 0) { 2564 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2565 return false; 2566 } 2567 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2568 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2569 // this operation and gives the two's complement result. 2570 if (RHS.isNegative() && RHS.isAllOnesValue() && 2571 LHS.isSigned() && LHS.isMinSignedValue()) 2572 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2573 E->getType()); 2574 return true; 2575 case BO_Shl: { 2576 if (Info.getLangOpts().OpenCL) 2577 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2578 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2579 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2580 RHS.isUnsigned()); 2581 else if (RHS.isSigned() && RHS.isNegative()) { 2582 // During constant-folding, a negative shift is an opposite shift. Such 2583 // a shift is not a constant expression. 2584 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2585 RHS = -RHS; 2586 goto shift_right; 2587 } 2588 shift_left: 2589 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2590 // the shifted type. 2591 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2592 if (SA != RHS) { 2593 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2594 << RHS << E->getType() << LHS.getBitWidth(); 2595 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2596 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2597 // operand, and must not overflow the corresponding unsigned type. 2598 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2599 // E1 x 2^E2 module 2^N. 2600 if (LHS.isNegative()) 2601 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2602 else if (LHS.countLeadingZeros() < SA) 2603 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2604 } 2605 Result = LHS << SA; 2606 return true; 2607 } 2608 case BO_Shr: { 2609 if (Info.getLangOpts().OpenCL) 2610 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2611 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2612 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2613 RHS.isUnsigned()); 2614 else if (RHS.isSigned() && RHS.isNegative()) { 2615 // During constant-folding, a negative shift is an opposite shift. Such a 2616 // shift is not a constant expression. 2617 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2618 RHS = -RHS; 2619 goto shift_left; 2620 } 2621 shift_right: 2622 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2623 // shifted type. 2624 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2625 if (SA != RHS) 2626 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2627 << RHS << E->getType() << LHS.getBitWidth(); 2628 Result = LHS >> SA; 2629 return true; 2630 } 2631 2632 case BO_LT: Result = LHS < RHS; return true; 2633 case BO_GT: Result = LHS > RHS; return true; 2634 case BO_LE: Result = LHS <= RHS; return true; 2635 case BO_GE: Result = LHS >= RHS; return true; 2636 case BO_EQ: Result = LHS == RHS; return true; 2637 case BO_NE: Result = LHS != RHS; return true; 2638 case BO_Cmp: 2639 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2640 } 2641 } 2642 2643 /// Perform the given binary floating-point operation, in-place, on LHS. 2644 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2645 APFloat &LHS, BinaryOperatorKind Opcode, 2646 const APFloat &RHS) { 2647 switch (Opcode) { 2648 default: 2649 Info.FFDiag(E); 2650 return false; 2651 case BO_Mul: 2652 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2653 break; 2654 case BO_Add: 2655 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2656 break; 2657 case BO_Sub: 2658 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2659 break; 2660 case BO_Div: 2661 // [expr.mul]p4: 2662 // If the second operand of / or % is zero the behavior is undefined. 2663 if (RHS.isZero()) 2664 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2665 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2666 break; 2667 } 2668 2669 // [expr.pre]p4: 2670 // If during the evaluation of an expression, the result is not 2671 // mathematically defined [...], the behavior is undefined. 2672 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2673 if (LHS.isNaN()) { 2674 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2675 return Info.noteUndefinedBehavior(); 2676 } 2677 return true; 2678 } 2679 2680 static bool handleLogicalOpForVector(const APInt &LHSValue, 2681 BinaryOperatorKind Opcode, 2682 const APInt &RHSValue, APInt &Result) { 2683 bool LHS = (LHSValue != 0); 2684 bool RHS = (RHSValue != 0); 2685 2686 if (Opcode == BO_LAnd) 2687 Result = LHS && RHS; 2688 else 2689 Result = LHS || RHS; 2690 return true; 2691 } 2692 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2693 BinaryOperatorKind Opcode, 2694 const APFloat &RHSValue, APInt &Result) { 2695 bool LHS = !LHSValue.isZero(); 2696 bool RHS = !RHSValue.isZero(); 2697 2698 if (Opcode == BO_LAnd) 2699 Result = LHS && RHS; 2700 else 2701 Result = LHS || RHS; 2702 return true; 2703 } 2704 2705 static bool handleLogicalOpForVector(const APValue &LHSValue, 2706 BinaryOperatorKind Opcode, 2707 const APValue &RHSValue, APInt &Result) { 2708 // The result is always an int type, however operands match the first. 2709 if (LHSValue.getKind() == APValue::Int) 2710 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2711 RHSValue.getInt(), Result); 2712 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2713 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2714 RHSValue.getFloat(), Result); 2715 } 2716 2717 template <typename APTy> 2718 static bool 2719 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2720 const APTy &RHSValue, APInt &Result) { 2721 switch (Opcode) { 2722 default: 2723 llvm_unreachable("unsupported binary operator"); 2724 case BO_EQ: 2725 Result = (LHSValue == RHSValue); 2726 break; 2727 case BO_NE: 2728 Result = (LHSValue != RHSValue); 2729 break; 2730 case BO_LT: 2731 Result = (LHSValue < RHSValue); 2732 break; 2733 case BO_GT: 2734 Result = (LHSValue > RHSValue); 2735 break; 2736 case BO_LE: 2737 Result = (LHSValue <= RHSValue); 2738 break; 2739 case BO_GE: 2740 Result = (LHSValue >= RHSValue); 2741 break; 2742 } 2743 2744 return true; 2745 } 2746 2747 static bool handleCompareOpForVector(const APValue &LHSValue, 2748 BinaryOperatorKind Opcode, 2749 const APValue &RHSValue, APInt &Result) { 2750 // The result is always an int type, however operands match the first. 2751 if (LHSValue.getKind() == APValue::Int) 2752 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2753 RHSValue.getInt(), Result); 2754 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2755 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2756 RHSValue.getFloat(), Result); 2757 } 2758 2759 // Perform binary operations for vector types, in place on the LHS. 2760 static bool handleVectorVectorBinOp(EvalInfo &Info, const Expr *E, 2761 BinaryOperatorKind Opcode, 2762 APValue &LHSValue, 2763 const APValue &RHSValue) { 2764 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2765 "Operation not supported on vector types"); 2766 2767 const auto *VT = E->getType()->castAs<VectorType>(); 2768 unsigned NumElements = VT->getNumElements(); 2769 QualType EltTy = VT->getElementType(); 2770 2771 // In the cases (typically C as I've observed) where we aren't evaluating 2772 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2773 // just give up. 2774 if (!LHSValue.isVector()) { 2775 assert(LHSValue.isLValue() && 2776 "A vector result that isn't a vector OR uncalculated LValue"); 2777 Info.FFDiag(E); 2778 return false; 2779 } 2780 2781 assert(LHSValue.getVectorLength() == NumElements && 2782 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2783 2784 SmallVector<APValue, 4> ResultElements; 2785 2786 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2787 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2788 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2789 2790 if (EltTy->isIntegerType()) { 2791 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2792 EltTy->isUnsignedIntegerType()}; 2793 bool Success = true; 2794 2795 if (BinaryOperator::isLogicalOp(Opcode)) 2796 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2797 else if (BinaryOperator::isComparisonOp(Opcode)) 2798 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2799 else 2800 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2801 RHSElt.getInt(), EltResult); 2802 2803 if (!Success) { 2804 Info.FFDiag(E); 2805 return false; 2806 } 2807 ResultElements.emplace_back(EltResult); 2808 2809 } else if (EltTy->isFloatingType()) { 2810 assert(LHSElt.getKind() == APValue::Float && 2811 RHSElt.getKind() == APValue::Float && 2812 "Mismatched LHS/RHS/Result Type"); 2813 APFloat LHSFloat = LHSElt.getFloat(); 2814 2815 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 2816 RHSElt.getFloat())) { 2817 Info.FFDiag(E); 2818 return false; 2819 } 2820 2821 ResultElements.emplace_back(LHSFloat); 2822 } 2823 } 2824 2825 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 2826 return true; 2827 } 2828 2829 /// Cast an lvalue referring to a base subobject to a derived class, by 2830 /// truncating the lvalue's path to the given length. 2831 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2832 const RecordDecl *TruncatedType, 2833 unsigned TruncatedElements) { 2834 SubobjectDesignator &D = Result.Designator; 2835 2836 // Check we actually point to a derived class object. 2837 if (TruncatedElements == D.Entries.size()) 2838 return true; 2839 assert(TruncatedElements >= D.MostDerivedPathLength && 2840 "not casting to a derived class"); 2841 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2842 return false; 2843 2844 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2845 const RecordDecl *RD = TruncatedType; 2846 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2847 if (RD->isInvalidDecl()) return false; 2848 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2849 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2850 if (isVirtualBaseClass(D.Entries[I])) 2851 Result.Offset -= Layout.getVBaseClassOffset(Base); 2852 else 2853 Result.Offset -= Layout.getBaseClassOffset(Base); 2854 RD = Base; 2855 } 2856 D.Entries.resize(TruncatedElements); 2857 return true; 2858 } 2859 2860 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2861 const CXXRecordDecl *Derived, 2862 const CXXRecordDecl *Base, 2863 const ASTRecordLayout *RL = nullptr) { 2864 if (!RL) { 2865 if (Derived->isInvalidDecl()) return false; 2866 RL = &Info.Ctx.getASTRecordLayout(Derived); 2867 } 2868 2869 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2870 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2871 return true; 2872 } 2873 2874 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2875 const CXXRecordDecl *DerivedDecl, 2876 const CXXBaseSpecifier *Base) { 2877 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2878 2879 if (!Base->isVirtual()) 2880 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2881 2882 SubobjectDesignator &D = Obj.Designator; 2883 if (D.Invalid) 2884 return false; 2885 2886 // Extract most-derived object and corresponding type. 2887 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2888 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2889 return false; 2890 2891 // Find the virtual base class. 2892 if (DerivedDecl->isInvalidDecl()) return false; 2893 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2894 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2895 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2896 return true; 2897 } 2898 2899 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2900 QualType Type, LValue &Result) { 2901 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2902 PathE = E->path_end(); 2903 PathI != PathE; ++PathI) { 2904 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2905 *PathI)) 2906 return false; 2907 Type = (*PathI)->getType(); 2908 } 2909 return true; 2910 } 2911 2912 /// Cast an lvalue referring to a derived class to a known base subobject. 2913 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2914 const CXXRecordDecl *DerivedRD, 2915 const CXXRecordDecl *BaseRD) { 2916 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2917 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2918 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2919 llvm_unreachable("Class must be derived from the passed in base class!"); 2920 2921 for (CXXBasePathElement &Elem : Paths.front()) 2922 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2923 return false; 2924 return true; 2925 } 2926 2927 /// Update LVal to refer to the given field, which must be a member of the type 2928 /// currently described by LVal. 2929 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2930 const FieldDecl *FD, 2931 const ASTRecordLayout *RL = nullptr) { 2932 if (!RL) { 2933 if (FD->getParent()->isInvalidDecl()) return false; 2934 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2935 } 2936 2937 unsigned I = FD->getFieldIndex(); 2938 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2939 LVal.addDecl(Info, E, FD); 2940 return true; 2941 } 2942 2943 /// Update LVal to refer to the given indirect field. 2944 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2945 LValue &LVal, 2946 const IndirectFieldDecl *IFD) { 2947 for (const auto *C : IFD->chain()) 2948 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2949 return false; 2950 return true; 2951 } 2952 2953 /// Get the size of the given type in char units. 2954 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2955 QualType Type, CharUnits &Size) { 2956 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2957 // extension. 2958 if (Type->isVoidType() || Type->isFunctionType()) { 2959 Size = CharUnits::One(); 2960 return true; 2961 } 2962 2963 if (Type->isDependentType()) { 2964 Info.FFDiag(Loc); 2965 return false; 2966 } 2967 2968 if (!Type->isConstantSizeType()) { 2969 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2970 // FIXME: Better diagnostic. 2971 Info.FFDiag(Loc); 2972 return false; 2973 } 2974 2975 Size = Info.Ctx.getTypeSizeInChars(Type); 2976 return true; 2977 } 2978 2979 /// Update a pointer value to model pointer arithmetic. 2980 /// \param Info - Information about the ongoing evaluation. 2981 /// \param E - The expression being evaluated, for diagnostic purposes. 2982 /// \param LVal - The pointer value to be updated. 2983 /// \param EltTy - The pointee type represented by LVal. 2984 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2985 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2986 LValue &LVal, QualType EltTy, 2987 APSInt Adjustment) { 2988 CharUnits SizeOfPointee; 2989 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2990 return false; 2991 2992 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2993 return true; 2994 } 2995 2996 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2997 LValue &LVal, QualType EltTy, 2998 int64_t Adjustment) { 2999 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3000 APSInt::get(Adjustment)); 3001 } 3002 3003 /// Update an lvalue to refer to a component of a complex number. 3004 /// \param Info - Information about the ongoing evaluation. 3005 /// \param LVal - The lvalue to be updated. 3006 /// \param EltTy - The complex number's component type. 3007 /// \param Imag - False for the real component, true for the imaginary. 3008 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3009 LValue &LVal, QualType EltTy, 3010 bool Imag) { 3011 if (Imag) { 3012 CharUnits SizeOfComponent; 3013 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3014 return false; 3015 LVal.Offset += SizeOfComponent; 3016 } 3017 LVal.addComplex(Info, E, EltTy, Imag); 3018 return true; 3019 } 3020 3021 /// Try to evaluate the initializer for a variable declaration. 3022 /// 3023 /// \param Info Information about the ongoing evaluation. 3024 /// \param E An expression to be used when printing diagnostics. 3025 /// \param VD The variable whose initializer should be obtained. 3026 /// \param Frame The frame in which the variable was created. Must be null 3027 /// if this variable is not local to the evaluation. 3028 /// \param Result Filled in with a pointer to the value of the variable. 3029 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3030 const VarDecl *VD, CallStackFrame *Frame, 3031 APValue *&Result, const LValue *LVal) { 3032 3033 // If this is a parameter to an active constexpr function call, perform 3034 // argument substitution. 3035 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 3036 // Assume arguments of a potential constant expression are unknown 3037 // constant expressions. 3038 if (Info.checkingPotentialConstantExpression()) 3039 return false; 3040 if (!Frame || !Frame->Arguments) { 3041 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD; 3042 return false; 3043 } 3044 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 3045 return true; 3046 } 3047 3048 // If this is a local variable, dig out its value. 3049 if (Frame) { 3050 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 3051 : Frame->getCurrentTemporary(VD); 3052 if (!Result) { 3053 // Assume variables referenced within a lambda's call operator that were 3054 // not declared within the call operator are captures and during checking 3055 // of a potential constant expression, assume they are unknown constant 3056 // expressions. 3057 assert(isLambdaCallOperator(Frame->Callee) && 3058 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3059 "missing value for local variable"); 3060 if (Info.checkingPotentialConstantExpression()) 3061 return false; 3062 // FIXME: implement capture evaluation during constant expr evaluation. 3063 Info.FFDiag(E->getBeginLoc(), 3064 diag::note_unimplemented_constexpr_lambda_feature_ast) 3065 << "captures not currently allowed"; 3066 return false; 3067 } 3068 return true; 3069 } 3070 3071 // Dig out the initializer, and use the declaration which it's attached to. 3072 // FIXME: We should eventually check whether the variable has a reachable 3073 // initializing declaration. 3074 const Expr *Init = VD->getAnyInitializer(VD); 3075 if (!Init) { 3076 // Don't diagnose during potential constant expression checking; an 3077 // initializer might be added later. 3078 if (!Info.checkingPotentialConstantExpression()) { 3079 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3080 << VD; 3081 Info.Note(VD->getLocation(), diag::note_declared_at); 3082 } 3083 return false; 3084 } 3085 3086 if (Init->isValueDependent()) { 3087 // The DeclRefExpr is not value-dependent, but the variable it refers to 3088 // has a value-dependent initializer. This should only happen in 3089 // constant-folding cases, where the variable is not actually of a suitable 3090 // type for use in a constant expression (otherwise the DeclRefExpr would 3091 // have been value-dependent too), so diagnose that. 3092 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3093 if (!Info.checkingPotentialConstantExpression()) { 3094 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3095 ? diag::note_constexpr_ltor_non_constexpr 3096 : diag::note_constexpr_ltor_non_integral, 1) 3097 << VD << VD->getType(); 3098 Info.Note(VD->getLocation(), diag::note_declared_at); 3099 } 3100 return false; 3101 } 3102 3103 // If we're currently evaluating the initializer of this declaration, use that 3104 // in-flight value. 3105 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 3106 Result = Info.EvaluatingDeclValue; 3107 return true; 3108 } 3109 3110 // Check that we can fold the initializer. In C++, we will have already done 3111 // this in the cases where it matters for conformance. 3112 SmallVector<PartialDiagnosticAt, 8> Notes; 3113 if (!VD->evaluateValue(Notes)) { 3114 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 3115 Notes.size() + 1) << VD; 3116 Info.Note(VD->getLocation(), diag::note_declared_at); 3117 Info.addNotes(Notes); 3118 return false; 3119 } 3120 3121 // Check that the variable is actually usable in constant expressions. 3122 if (!VD->checkInitIsICE()) { 3123 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 3124 Notes.size() + 1) << VD; 3125 Info.Note(VD->getLocation(), diag::note_declared_at); 3126 Info.addNotes(Notes); 3127 } 3128 3129 // Never use the initializer of a weak variable, not even for constant 3130 // folding. We can't be sure that this is the definition that will be used. 3131 if (VD->isWeak()) { 3132 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3133 Info.Note(VD->getLocation(), diag::note_declared_at); 3134 return false; 3135 } 3136 3137 Result = VD->getEvaluatedValue(); 3138 return true; 3139 } 3140 3141 static bool IsConstNonVolatile(QualType T) { 3142 Qualifiers Quals = T.getQualifiers(); 3143 return Quals.hasConst() && !Quals.hasVolatile(); 3144 } 3145 3146 /// Get the base index of the given base class within an APValue representing 3147 /// the given derived class. 3148 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3149 const CXXRecordDecl *Base) { 3150 Base = Base->getCanonicalDecl(); 3151 unsigned Index = 0; 3152 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3153 E = Derived->bases_end(); I != E; ++I, ++Index) { 3154 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3155 return Index; 3156 } 3157 3158 llvm_unreachable("base class missing from derived class's bases list"); 3159 } 3160 3161 /// Extract the value of a character from a string literal. 3162 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3163 uint64_t Index) { 3164 assert(!isa<SourceLocExpr>(Lit) && 3165 "SourceLocExpr should have already been converted to a StringLiteral"); 3166 3167 // FIXME: Support MakeStringConstant 3168 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3169 std::string Str; 3170 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3171 assert(Index <= Str.size() && "Index too large"); 3172 return APSInt::getUnsigned(Str.c_str()[Index]); 3173 } 3174 3175 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3176 Lit = PE->getFunctionName(); 3177 const StringLiteral *S = cast<StringLiteral>(Lit); 3178 const ConstantArrayType *CAT = 3179 Info.Ctx.getAsConstantArrayType(S->getType()); 3180 assert(CAT && "string literal isn't an array"); 3181 QualType CharType = CAT->getElementType(); 3182 assert(CharType->isIntegerType() && "unexpected character type"); 3183 3184 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3185 CharType->isUnsignedIntegerType()); 3186 if (Index < S->getLength()) 3187 Value = S->getCodeUnit(Index); 3188 return Value; 3189 } 3190 3191 // Expand a string literal into an array of characters. 3192 // 3193 // FIXME: This is inefficient; we should probably introduce something similar 3194 // to the LLVM ConstantDataArray to make this cheaper. 3195 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3196 APValue &Result, 3197 QualType AllocType = QualType()) { 3198 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3199 AllocType.isNull() ? S->getType() : AllocType); 3200 assert(CAT && "string literal isn't an array"); 3201 QualType CharType = CAT->getElementType(); 3202 assert(CharType->isIntegerType() && "unexpected character type"); 3203 3204 unsigned Elts = CAT->getSize().getZExtValue(); 3205 Result = APValue(APValue::UninitArray(), 3206 std::min(S->getLength(), Elts), Elts); 3207 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3208 CharType->isUnsignedIntegerType()); 3209 if (Result.hasArrayFiller()) 3210 Result.getArrayFiller() = APValue(Value); 3211 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3212 Value = S->getCodeUnit(I); 3213 Result.getArrayInitializedElt(I) = APValue(Value); 3214 } 3215 } 3216 3217 // Expand an array so that it has more than Index filled elements. 3218 static void expandArray(APValue &Array, unsigned Index) { 3219 unsigned Size = Array.getArraySize(); 3220 assert(Index < Size); 3221 3222 // Always at least double the number of elements for which we store a value. 3223 unsigned OldElts = Array.getArrayInitializedElts(); 3224 unsigned NewElts = std::max(Index+1, OldElts * 2); 3225 NewElts = std::min(Size, std::max(NewElts, 8u)); 3226 3227 // Copy the data across. 3228 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3229 for (unsigned I = 0; I != OldElts; ++I) 3230 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3231 for (unsigned I = OldElts; I != NewElts; ++I) 3232 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3233 if (NewValue.hasArrayFiller()) 3234 NewValue.getArrayFiller() = Array.getArrayFiller(); 3235 Array.swap(NewValue); 3236 } 3237 3238 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3239 /// conversion. If it's of class type, we may assume that the copy operation 3240 /// is trivial. Note that this is never true for a union type with fields 3241 /// (because the copy always "reads" the active member) and always true for 3242 /// a non-class type. 3243 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3244 static bool isReadByLvalueToRvalueConversion(QualType T) { 3245 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3246 return !RD || isReadByLvalueToRvalueConversion(RD); 3247 } 3248 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3249 // FIXME: A trivial copy of a union copies the object representation, even if 3250 // the union is empty. 3251 if (RD->isUnion()) 3252 return !RD->field_empty(); 3253 if (RD->isEmpty()) 3254 return false; 3255 3256 for (auto *Field : RD->fields()) 3257 if (!Field->isUnnamedBitfield() && 3258 isReadByLvalueToRvalueConversion(Field->getType())) 3259 return true; 3260 3261 for (auto &BaseSpec : RD->bases()) 3262 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3263 return true; 3264 3265 return false; 3266 } 3267 3268 /// Diagnose an attempt to read from any unreadable field within the specified 3269 /// type, which might be a class type. 3270 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3271 QualType T) { 3272 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3273 if (!RD) 3274 return false; 3275 3276 if (!RD->hasMutableFields()) 3277 return false; 3278 3279 for (auto *Field : RD->fields()) { 3280 // If we're actually going to read this field in some way, then it can't 3281 // be mutable. If we're in a union, then assigning to a mutable field 3282 // (even an empty one) can change the active member, so that's not OK. 3283 // FIXME: Add core issue number for the union case. 3284 if (Field->isMutable() && 3285 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3286 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3287 Info.Note(Field->getLocation(), diag::note_declared_at); 3288 return true; 3289 } 3290 3291 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3292 return true; 3293 } 3294 3295 for (auto &BaseSpec : RD->bases()) 3296 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3297 return true; 3298 3299 // All mutable fields were empty, and thus not actually read. 3300 return false; 3301 } 3302 3303 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3304 APValue::LValueBase Base, 3305 bool MutableSubobject = false) { 3306 // A temporary we created. 3307 if (Base.getCallIndex()) 3308 return true; 3309 3310 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3311 if (!Evaluating) 3312 return false; 3313 3314 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3315 3316 switch (Info.IsEvaluatingDecl) { 3317 case EvalInfo::EvaluatingDeclKind::None: 3318 return false; 3319 3320 case EvalInfo::EvaluatingDeclKind::Ctor: 3321 // The variable whose initializer we're evaluating. 3322 if (BaseD) 3323 return declaresSameEntity(Evaluating, BaseD); 3324 3325 // A temporary lifetime-extended by the variable whose initializer we're 3326 // evaluating. 3327 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3328 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3329 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3330 return false; 3331 3332 case EvalInfo::EvaluatingDeclKind::Dtor: 3333 // C++2a [expr.const]p6: 3334 // [during constant destruction] the lifetime of a and its non-mutable 3335 // subobjects (but not its mutable subobjects) [are] considered to start 3336 // within e. 3337 // 3338 // FIXME: We can meaningfully extend this to cover non-const objects, but 3339 // we will need special handling: we should be able to access only 3340 // subobjects of such objects that are themselves declared const. 3341 if (!BaseD || 3342 !(BaseD->getType().isConstQualified() || 3343 BaseD->getType()->isReferenceType()) || 3344 MutableSubobject) 3345 return false; 3346 return declaresSameEntity(Evaluating, BaseD); 3347 } 3348 3349 llvm_unreachable("unknown evaluating decl kind"); 3350 } 3351 3352 namespace { 3353 /// A handle to a complete object (an object that is not a subobject of 3354 /// another object). 3355 struct CompleteObject { 3356 /// The identity of the object. 3357 APValue::LValueBase Base; 3358 /// The value of the complete object. 3359 APValue *Value; 3360 /// The type of the complete object. 3361 QualType Type; 3362 3363 CompleteObject() : Value(nullptr) {} 3364 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3365 : Base(Base), Value(Value), Type(Type) {} 3366 3367 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3368 // If this isn't a "real" access (eg, if it's just accessing the type 3369 // info), allow it. We assume the type doesn't change dynamically for 3370 // subobjects of constexpr objects (even though we'd hit UB here if it 3371 // did). FIXME: Is this right? 3372 if (!isAnyAccess(AK)) 3373 return true; 3374 3375 // In C++14 onwards, it is permitted to read a mutable member whose 3376 // lifetime began within the evaluation. 3377 // FIXME: Should we also allow this in C++11? 3378 if (!Info.getLangOpts().CPlusPlus14) 3379 return false; 3380 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3381 } 3382 3383 explicit operator bool() const { return !Type.isNull(); } 3384 }; 3385 } // end anonymous namespace 3386 3387 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3388 bool IsMutable = false) { 3389 // C++ [basic.type.qualifier]p1: 3390 // - A const object is an object of type const T or a non-mutable subobject 3391 // of a const object. 3392 if (ObjType.isConstQualified() && !IsMutable) 3393 SubobjType.addConst(); 3394 // - A volatile object is an object of type const T or a subobject of a 3395 // volatile object. 3396 if (ObjType.isVolatileQualified()) 3397 SubobjType.addVolatile(); 3398 return SubobjType; 3399 } 3400 3401 /// Find the designated sub-object of an rvalue. 3402 template<typename SubobjectHandler> 3403 typename SubobjectHandler::result_type 3404 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3405 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3406 if (Sub.Invalid) 3407 // A diagnostic will have already been produced. 3408 return handler.failed(); 3409 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3410 if (Info.getLangOpts().CPlusPlus11) 3411 Info.FFDiag(E, Sub.isOnePastTheEnd() 3412 ? diag::note_constexpr_access_past_end 3413 : diag::note_constexpr_access_unsized_array) 3414 << handler.AccessKind; 3415 else 3416 Info.FFDiag(E); 3417 return handler.failed(); 3418 } 3419 3420 APValue *O = Obj.Value; 3421 QualType ObjType = Obj.Type; 3422 const FieldDecl *LastField = nullptr; 3423 const FieldDecl *VolatileField = nullptr; 3424 3425 // Walk the designator's path to find the subobject. 3426 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3427 // Reading an indeterminate value is undefined, but assigning over one is OK. 3428 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3429 (O->isIndeterminate() && 3430 !isValidIndeterminateAccess(handler.AccessKind))) { 3431 if (!Info.checkingPotentialConstantExpression()) 3432 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3433 << handler.AccessKind << O->isIndeterminate(); 3434 return handler.failed(); 3435 } 3436 3437 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3438 // const and volatile semantics are not applied on an object under 3439 // {con,de}struction. 3440 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3441 ObjType->isRecordType() && 3442 Info.isEvaluatingCtorDtor( 3443 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3444 Sub.Entries.begin() + I)) != 3445 ConstructionPhase::None) { 3446 ObjType = Info.Ctx.getCanonicalType(ObjType); 3447 ObjType.removeLocalConst(); 3448 ObjType.removeLocalVolatile(); 3449 } 3450 3451 // If this is our last pass, check that the final object type is OK. 3452 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3453 // Accesses to volatile objects are prohibited. 3454 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3455 if (Info.getLangOpts().CPlusPlus) { 3456 int DiagKind; 3457 SourceLocation Loc; 3458 const NamedDecl *Decl = nullptr; 3459 if (VolatileField) { 3460 DiagKind = 2; 3461 Loc = VolatileField->getLocation(); 3462 Decl = VolatileField; 3463 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3464 DiagKind = 1; 3465 Loc = VD->getLocation(); 3466 Decl = VD; 3467 } else { 3468 DiagKind = 0; 3469 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3470 Loc = E->getExprLoc(); 3471 } 3472 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3473 << handler.AccessKind << DiagKind << Decl; 3474 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3475 } else { 3476 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3477 } 3478 return handler.failed(); 3479 } 3480 3481 // If we are reading an object of class type, there may still be more 3482 // things we need to check: if there are any mutable subobjects, we 3483 // cannot perform this read. (This only happens when performing a trivial 3484 // copy or assignment.) 3485 if (ObjType->isRecordType() && 3486 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3487 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3488 return handler.failed(); 3489 } 3490 3491 if (I == N) { 3492 if (!handler.found(*O, ObjType)) 3493 return false; 3494 3495 // If we modified a bit-field, truncate it to the right width. 3496 if (isModification(handler.AccessKind) && 3497 LastField && LastField->isBitField() && 3498 !truncateBitfieldValue(Info, E, *O, LastField)) 3499 return false; 3500 3501 return true; 3502 } 3503 3504 LastField = nullptr; 3505 if (ObjType->isArrayType()) { 3506 // Next subobject is an array element. 3507 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3508 assert(CAT && "vla in literal type?"); 3509 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3510 if (CAT->getSize().ule(Index)) { 3511 // Note, it should not be possible to form a pointer with a valid 3512 // designator which points more than one past the end of the array. 3513 if (Info.getLangOpts().CPlusPlus11) 3514 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3515 << handler.AccessKind; 3516 else 3517 Info.FFDiag(E); 3518 return handler.failed(); 3519 } 3520 3521 ObjType = CAT->getElementType(); 3522 3523 if (O->getArrayInitializedElts() > Index) 3524 O = &O->getArrayInitializedElt(Index); 3525 else if (!isRead(handler.AccessKind)) { 3526 expandArray(*O, Index); 3527 O = &O->getArrayInitializedElt(Index); 3528 } else 3529 O = &O->getArrayFiller(); 3530 } else if (ObjType->isAnyComplexType()) { 3531 // Next subobject is a complex number. 3532 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3533 if (Index > 1) { 3534 if (Info.getLangOpts().CPlusPlus11) 3535 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3536 << handler.AccessKind; 3537 else 3538 Info.FFDiag(E); 3539 return handler.failed(); 3540 } 3541 3542 ObjType = getSubobjectType( 3543 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3544 3545 assert(I == N - 1 && "extracting subobject of scalar?"); 3546 if (O->isComplexInt()) { 3547 return handler.found(Index ? O->getComplexIntImag() 3548 : O->getComplexIntReal(), ObjType); 3549 } else { 3550 assert(O->isComplexFloat()); 3551 return handler.found(Index ? O->getComplexFloatImag() 3552 : O->getComplexFloatReal(), ObjType); 3553 } 3554 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3555 if (Field->isMutable() && 3556 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3557 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3558 << handler.AccessKind << Field; 3559 Info.Note(Field->getLocation(), diag::note_declared_at); 3560 return handler.failed(); 3561 } 3562 3563 // Next subobject is a class, struct or union field. 3564 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3565 if (RD->isUnion()) { 3566 const FieldDecl *UnionField = O->getUnionField(); 3567 if (!UnionField || 3568 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3569 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3570 // Placement new onto an inactive union member makes it active. 3571 O->setUnion(Field, APValue()); 3572 } else { 3573 // FIXME: If O->getUnionValue() is absent, report that there's no 3574 // active union member rather than reporting the prior active union 3575 // member. We'll need to fix nullptr_t to not use APValue() as its 3576 // representation first. 3577 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3578 << handler.AccessKind << Field << !UnionField << UnionField; 3579 return handler.failed(); 3580 } 3581 } 3582 O = &O->getUnionValue(); 3583 } else 3584 O = &O->getStructField(Field->getFieldIndex()); 3585 3586 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3587 LastField = Field; 3588 if (Field->getType().isVolatileQualified()) 3589 VolatileField = Field; 3590 } else { 3591 // Next subobject is a base class. 3592 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3593 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3594 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3595 3596 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3597 } 3598 } 3599 } 3600 3601 namespace { 3602 struct ExtractSubobjectHandler { 3603 EvalInfo &Info; 3604 const Expr *E; 3605 APValue &Result; 3606 const AccessKinds AccessKind; 3607 3608 typedef bool result_type; 3609 bool failed() { return false; } 3610 bool found(APValue &Subobj, QualType SubobjType) { 3611 Result = Subobj; 3612 if (AccessKind == AK_ReadObjectRepresentation) 3613 return true; 3614 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3615 } 3616 bool found(APSInt &Value, QualType SubobjType) { 3617 Result = APValue(Value); 3618 return true; 3619 } 3620 bool found(APFloat &Value, QualType SubobjType) { 3621 Result = APValue(Value); 3622 return true; 3623 } 3624 }; 3625 } // end anonymous namespace 3626 3627 /// Extract the designated sub-object of an rvalue. 3628 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3629 const CompleteObject &Obj, 3630 const SubobjectDesignator &Sub, APValue &Result, 3631 AccessKinds AK = AK_Read) { 3632 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3633 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3634 return findSubobject(Info, E, Obj, Sub, Handler); 3635 } 3636 3637 namespace { 3638 struct ModifySubobjectHandler { 3639 EvalInfo &Info; 3640 APValue &NewVal; 3641 const Expr *E; 3642 3643 typedef bool result_type; 3644 static const AccessKinds AccessKind = AK_Assign; 3645 3646 bool checkConst(QualType QT) { 3647 // Assigning to a const object has undefined behavior. 3648 if (QT.isConstQualified()) { 3649 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3650 return false; 3651 } 3652 return true; 3653 } 3654 3655 bool failed() { return false; } 3656 bool found(APValue &Subobj, QualType SubobjType) { 3657 if (!checkConst(SubobjType)) 3658 return false; 3659 // We've been given ownership of NewVal, so just swap it in. 3660 Subobj.swap(NewVal); 3661 return true; 3662 } 3663 bool found(APSInt &Value, QualType SubobjType) { 3664 if (!checkConst(SubobjType)) 3665 return false; 3666 if (!NewVal.isInt()) { 3667 // Maybe trying to write a cast pointer value into a complex? 3668 Info.FFDiag(E); 3669 return false; 3670 } 3671 Value = NewVal.getInt(); 3672 return true; 3673 } 3674 bool found(APFloat &Value, QualType SubobjType) { 3675 if (!checkConst(SubobjType)) 3676 return false; 3677 Value = NewVal.getFloat(); 3678 return true; 3679 } 3680 }; 3681 } // end anonymous namespace 3682 3683 const AccessKinds ModifySubobjectHandler::AccessKind; 3684 3685 /// Update the designated sub-object of an rvalue to the given value. 3686 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3687 const CompleteObject &Obj, 3688 const SubobjectDesignator &Sub, 3689 APValue &NewVal) { 3690 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3691 return findSubobject(Info, E, Obj, Sub, Handler); 3692 } 3693 3694 /// Find the position where two subobject designators diverge, or equivalently 3695 /// the length of the common initial subsequence. 3696 static unsigned FindDesignatorMismatch(QualType ObjType, 3697 const SubobjectDesignator &A, 3698 const SubobjectDesignator &B, 3699 bool &WasArrayIndex) { 3700 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3701 for (/**/; I != N; ++I) { 3702 if (!ObjType.isNull() && 3703 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3704 // Next subobject is an array element. 3705 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3706 WasArrayIndex = true; 3707 return I; 3708 } 3709 if (ObjType->isAnyComplexType()) 3710 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3711 else 3712 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3713 } else { 3714 if (A.Entries[I].getAsBaseOrMember() != 3715 B.Entries[I].getAsBaseOrMember()) { 3716 WasArrayIndex = false; 3717 return I; 3718 } 3719 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3720 // Next subobject is a field. 3721 ObjType = FD->getType(); 3722 else 3723 // Next subobject is a base class. 3724 ObjType = QualType(); 3725 } 3726 } 3727 WasArrayIndex = false; 3728 return I; 3729 } 3730 3731 /// Determine whether the given subobject designators refer to elements of the 3732 /// same array object. 3733 static bool AreElementsOfSameArray(QualType ObjType, 3734 const SubobjectDesignator &A, 3735 const SubobjectDesignator &B) { 3736 if (A.Entries.size() != B.Entries.size()) 3737 return false; 3738 3739 bool IsArray = A.MostDerivedIsArrayElement; 3740 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3741 // A is a subobject of the array element. 3742 return false; 3743 3744 // If A (and B) designates an array element, the last entry will be the array 3745 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3746 // of length 1' case, and the entire path must match. 3747 bool WasArrayIndex; 3748 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3749 return CommonLength >= A.Entries.size() - IsArray; 3750 } 3751 3752 /// Find the complete object to which an LValue refers. 3753 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3754 AccessKinds AK, const LValue &LVal, 3755 QualType LValType) { 3756 if (LVal.InvalidBase) { 3757 Info.FFDiag(E); 3758 return CompleteObject(); 3759 } 3760 3761 if (!LVal.Base) { 3762 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3763 return CompleteObject(); 3764 } 3765 3766 CallStackFrame *Frame = nullptr; 3767 unsigned Depth = 0; 3768 if (LVal.getLValueCallIndex()) { 3769 std::tie(Frame, Depth) = 3770 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3771 if (!Frame) { 3772 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3773 << AK << LVal.Base.is<const ValueDecl*>(); 3774 NoteLValueLocation(Info, LVal.Base); 3775 return CompleteObject(); 3776 } 3777 } 3778 3779 bool IsAccess = isAnyAccess(AK); 3780 3781 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3782 // is not a constant expression (even if the object is non-volatile). We also 3783 // apply this rule to C++98, in order to conform to the expected 'volatile' 3784 // semantics. 3785 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3786 if (Info.getLangOpts().CPlusPlus) 3787 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3788 << AK << LValType; 3789 else 3790 Info.FFDiag(E); 3791 return CompleteObject(); 3792 } 3793 3794 // Compute value storage location and type of base object. 3795 APValue *BaseVal = nullptr; 3796 QualType BaseType = getType(LVal.Base); 3797 3798 if (const ConstantExpr *CE = 3799 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) { 3800 /// Nested immediate invocation have been previously removed so if we found 3801 /// a ConstantExpr it can only be the EvaluatingDecl. 3802 assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl); 3803 (void)CE; 3804 BaseVal = Info.EvaluatingDeclValue; 3805 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3806 // Allow reading from a GUID declaration. 3807 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3808 if (isModification(AK)) { 3809 // All the remaining cases do not permit modification of the object. 3810 Info.FFDiag(E, diag::note_constexpr_modify_global); 3811 return CompleteObject(); 3812 } 3813 APValue &V = GD->getAsAPValue(); 3814 if (V.isAbsent()) { 3815 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3816 << GD->getType(); 3817 return CompleteObject(); 3818 } 3819 return CompleteObject(LVal.Base, &V, GD->getType()); 3820 } 3821 3822 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3823 // In C++11, constexpr, non-volatile variables initialized with constant 3824 // expressions are constant expressions too. Inside constexpr functions, 3825 // parameters are constant expressions even if they're non-const. 3826 // In C++1y, objects local to a constant expression (those with a Frame) are 3827 // both readable and writable inside constant expressions. 3828 // In C, such things can also be folded, although they are not ICEs. 3829 const VarDecl *VD = dyn_cast<VarDecl>(D); 3830 if (VD) { 3831 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3832 VD = VDef; 3833 } 3834 if (!VD || VD->isInvalidDecl()) { 3835 Info.FFDiag(E); 3836 return CompleteObject(); 3837 } 3838 3839 // In OpenCL if a variable is in constant address space it is a const value. 3840 bool IsConstant = BaseType.isConstQualified() || 3841 (Info.getLangOpts().OpenCL && 3842 BaseType.getAddressSpace() == LangAS::opencl_constant); 3843 3844 // Unless we're looking at a local variable or argument in a constexpr call, 3845 // the variable we're reading must be const. 3846 if (!Frame) { 3847 if (Info.getLangOpts().CPlusPlus14 && 3848 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3849 // OK, we can read and modify an object if we're in the process of 3850 // evaluating its initializer, because its lifetime began in this 3851 // evaluation. 3852 } else if (isModification(AK)) { 3853 // All the remaining cases do not permit modification of the object. 3854 Info.FFDiag(E, diag::note_constexpr_modify_global); 3855 return CompleteObject(); 3856 } else if (VD->isConstexpr()) { 3857 // OK, we can read this variable. 3858 } else if (BaseType->isIntegralOrEnumerationType()) { 3859 // In OpenCL if a variable is in constant address space it is a const 3860 // value. 3861 if (!IsConstant) { 3862 if (!IsAccess) 3863 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3864 if (Info.getLangOpts().CPlusPlus) { 3865 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3866 Info.Note(VD->getLocation(), diag::note_declared_at); 3867 } else { 3868 Info.FFDiag(E); 3869 } 3870 return CompleteObject(); 3871 } 3872 } else if (!IsAccess) { 3873 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3874 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 3875 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 3876 // This variable might end up being constexpr. Don't diagnose it yet. 3877 } else if (IsConstant) { 3878 // Keep evaluating to see what we can do. In particular, we support 3879 // folding of const floating-point types, in order to make static const 3880 // data members of such types (supported as an extension) more useful. 3881 if (Info.getLangOpts().CPlusPlus) { 3882 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 3883 ? diag::note_constexpr_ltor_non_constexpr 3884 : diag::note_constexpr_ltor_non_integral, 1) 3885 << VD << BaseType; 3886 Info.Note(VD->getLocation(), diag::note_declared_at); 3887 } else { 3888 Info.CCEDiag(E); 3889 } 3890 } else { 3891 // Never allow reading a non-const value. 3892 if (Info.getLangOpts().CPlusPlus) { 3893 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3894 ? diag::note_constexpr_ltor_non_constexpr 3895 : diag::note_constexpr_ltor_non_integral, 1) 3896 << VD << BaseType; 3897 Info.Note(VD->getLocation(), diag::note_declared_at); 3898 } else { 3899 Info.FFDiag(E); 3900 } 3901 return CompleteObject(); 3902 } 3903 } 3904 3905 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3906 return CompleteObject(); 3907 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 3908 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 3909 if (!Alloc) { 3910 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 3911 return CompleteObject(); 3912 } 3913 return CompleteObject(LVal.Base, &(*Alloc)->Value, 3914 LVal.Base.getDynamicAllocType()); 3915 } else { 3916 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3917 3918 if (!Frame) { 3919 if (const MaterializeTemporaryExpr *MTE = 3920 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3921 assert(MTE->getStorageDuration() == SD_Static && 3922 "should have a frame for a non-global materialized temporary"); 3923 3924 // Per C++1y [expr.const]p2: 3925 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3926 // - a [...] glvalue of integral or enumeration type that refers to 3927 // a non-volatile const object [...] 3928 // [...] 3929 // - a [...] glvalue of literal type that refers to a non-volatile 3930 // object whose lifetime began within the evaluation of e. 3931 // 3932 // C++11 misses the 'began within the evaluation of e' check and 3933 // instead allows all temporaries, including things like: 3934 // int &&r = 1; 3935 // int x = ++r; 3936 // constexpr int k = r; 3937 // Therefore we use the C++14 rules in C++11 too. 3938 // 3939 // Note that temporaries whose lifetimes began while evaluating a 3940 // variable's constructor are not usable while evaluating the 3941 // corresponding destructor, not even if they're of const-qualified 3942 // types. 3943 if (!(BaseType.isConstQualified() && 3944 BaseType->isIntegralOrEnumerationType()) && 3945 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 3946 if (!IsAccess) 3947 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3948 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3949 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3950 return CompleteObject(); 3951 } 3952 3953 BaseVal = MTE->getOrCreateValue(false); 3954 assert(BaseVal && "got reference to unevaluated temporary"); 3955 } else { 3956 if (!IsAccess) 3957 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3958 APValue Val; 3959 LVal.moveInto(Val); 3960 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3961 << AK 3962 << Val.getAsString(Info.Ctx, 3963 Info.Ctx.getLValueReferenceType(LValType)); 3964 NoteLValueLocation(Info, LVal.Base); 3965 return CompleteObject(); 3966 } 3967 } else { 3968 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3969 assert(BaseVal && "missing value for temporary"); 3970 } 3971 } 3972 3973 // In C++14, we can't safely access any mutable state when we might be 3974 // evaluating after an unmodeled side effect. 3975 // 3976 // FIXME: Not all local state is mutable. Allow local constant subobjects 3977 // to be read here (but take care with 'mutable' fields). 3978 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3979 Info.EvalStatus.HasSideEffects) || 3980 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3981 return CompleteObject(); 3982 3983 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3984 } 3985 3986 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3987 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3988 /// glvalue referred to by an entity of reference type. 3989 /// 3990 /// \param Info - Information about the ongoing evaluation. 3991 /// \param Conv - The expression for which we are performing the conversion. 3992 /// Used for diagnostics. 3993 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3994 /// case of a non-class type). 3995 /// \param LVal - The glvalue on which we are attempting to perform this action. 3996 /// \param RVal - The produced value will be placed here. 3997 /// \param WantObjectRepresentation - If true, we're looking for the object 3998 /// representation rather than the value, and in particular, 3999 /// there is no requirement that the result be fully initialized. 4000 static bool 4001 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4002 const LValue &LVal, APValue &RVal, 4003 bool WantObjectRepresentation = false) { 4004 if (LVal.Designator.Invalid) 4005 return false; 4006 4007 // Check for special cases where there is no existing APValue to look at. 4008 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4009 4010 AccessKinds AK = 4011 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4012 4013 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4014 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4015 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4016 // initializer until now for such expressions. Such an expression can't be 4017 // an ICE in C, so this only matters for fold. 4018 if (Type.isVolatileQualified()) { 4019 Info.FFDiag(Conv); 4020 return false; 4021 } 4022 APValue Lit; 4023 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4024 return false; 4025 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4026 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4027 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4028 // Special-case character extraction so we don't have to construct an 4029 // APValue for the whole string. 4030 assert(LVal.Designator.Entries.size() <= 1 && 4031 "Can only read characters from string literals"); 4032 if (LVal.Designator.Entries.empty()) { 4033 // Fail for now for LValue to RValue conversion of an array. 4034 // (This shouldn't show up in C/C++, but it could be triggered by a 4035 // weird EvaluateAsRValue call from a tool.) 4036 Info.FFDiag(Conv); 4037 return false; 4038 } 4039 if (LVal.Designator.isOnePastTheEnd()) { 4040 if (Info.getLangOpts().CPlusPlus11) 4041 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4042 else 4043 Info.FFDiag(Conv); 4044 return false; 4045 } 4046 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4047 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4048 return true; 4049 } 4050 } 4051 4052 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4053 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4054 } 4055 4056 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4057 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4058 QualType LValType, APValue &Val) { 4059 if (LVal.Designator.Invalid) 4060 return false; 4061 4062 if (!Info.getLangOpts().CPlusPlus14) { 4063 Info.FFDiag(E); 4064 return false; 4065 } 4066 4067 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4068 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4069 } 4070 4071 namespace { 4072 struct CompoundAssignSubobjectHandler { 4073 EvalInfo &Info; 4074 const Expr *E; 4075 QualType PromotedLHSType; 4076 BinaryOperatorKind Opcode; 4077 const APValue &RHS; 4078 4079 static const AccessKinds AccessKind = AK_Assign; 4080 4081 typedef bool result_type; 4082 4083 bool checkConst(QualType QT) { 4084 // Assigning to a const object has undefined behavior. 4085 if (QT.isConstQualified()) { 4086 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4087 return false; 4088 } 4089 return true; 4090 } 4091 4092 bool failed() { return false; } 4093 bool found(APValue &Subobj, QualType SubobjType) { 4094 switch (Subobj.getKind()) { 4095 case APValue::Int: 4096 return found(Subobj.getInt(), SubobjType); 4097 case APValue::Float: 4098 return found(Subobj.getFloat(), SubobjType); 4099 case APValue::ComplexInt: 4100 case APValue::ComplexFloat: 4101 // FIXME: Implement complex compound assignment. 4102 Info.FFDiag(E); 4103 return false; 4104 case APValue::LValue: 4105 return foundPointer(Subobj, SubobjType); 4106 case APValue::Vector: 4107 return foundVector(Subobj, SubobjType); 4108 default: 4109 // FIXME: can this happen? 4110 Info.FFDiag(E); 4111 return false; 4112 } 4113 } 4114 4115 bool foundVector(APValue &Value, QualType SubobjType) { 4116 if (!checkConst(SubobjType)) 4117 return false; 4118 4119 if (!SubobjType->isVectorType()) { 4120 Info.FFDiag(E); 4121 return false; 4122 } 4123 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4124 } 4125 4126 bool found(APSInt &Value, QualType SubobjType) { 4127 if (!checkConst(SubobjType)) 4128 return false; 4129 4130 if (!SubobjType->isIntegerType()) { 4131 // We don't support compound assignment on integer-cast-to-pointer 4132 // values. 4133 Info.FFDiag(E); 4134 return false; 4135 } 4136 4137 if (RHS.isInt()) { 4138 APSInt LHS = 4139 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4140 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4141 return false; 4142 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4143 return true; 4144 } else if (RHS.isFloat()) { 4145 APFloat FValue(0.0); 4146 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 4147 FValue) && 4148 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4149 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4150 Value); 4151 } 4152 4153 Info.FFDiag(E); 4154 return false; 4155 } 4156 bool found(APFloat &Value, QualType SubobjType) { 4157 return checkConst(SubobjType) && 4158 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4159 Value) && 4160 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4161 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4162 } 4163 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4164 if (!checkConst(SubobjType)) 4165 return false; 4166 4167 QualType PointeeType; 4168 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4169 PointeeType = PT->getPointeeType(); 4170 4171 if (PointeeType.isNull() || !RHS.isInt() || 4172 (Opcode != BO_Add && Opcode != BO_Sub)) { 4173 Info.FFDiag(E); 4174 return false; 4175 } 4176 4177 APSInt Offset = RHS.getInt(); 4178 if (Opcode == BO_Sub) 4179 negateAsSigned(Offset); 4180 4181 LValue LVal; 4182 LVal.setFrom(Info.Ctx, Subobj); 4183 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4184 return false; 4185 LVal.moveInto(Subobj); 4186 return true; 4187 } 4188 }; 4189 } // end anonymous namespace 4190 4191 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4192 4193 /// Perform a compound assignment of LVal <op>= RVal. 4194 static bool handleCompoundAssignment( 4195 EvalInfo &Info, const Expr *E, 4196 const LValue &LVal, QualType LValType, QualType PromotedLValType, 4197 BinaryOperatorKind Opcode, const APValue &RVal) { 4198 if (LVal.Designator.Invalid) 4199 return false; 4200 4201 if (!Info.getLangOpts().CPlusPlus14) { 4202 Info.FFDiag(E); 4203 return false; 4204 } 4205 4206 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4207 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4208 RVal }; 4209 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4210 } 4211 4212 namespace { 4213 struct IncDecSubobjectHandler { 4214 EvalInfo &Info; 4215 const UnaryOperator *E; 4216 AccessKinds AccessKind; 4217 APValue *Old; 4218 4219 typedef bool result_type; 4220 4221 bool checkConst(QualType QT) { 4222 // Assigning to a const object has undefined behavior. 4223 if (QT.isConstQualified()) { 4224 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4225 return false; 4226 } 4227 return true; 4228 } 4229 4230 bool failed() { return false; } 4231 bool found(APValue &Subobj, QualType SubobjType) { 4232 // Stash the old value. Also clear Old, so we don't clobber it later 4233 // if we're post-incrementing a complex. 4234 if (Old) { 4235 *Old = Subobj; 4236 Old = nullptr; 4237 } 4238 4239 switch (Subobj.getKind()) { 4240 case APValue::Int: 4241 return found(Subobj.getInt(), SubobjType); 4242 case APValue::Float: 4243 return found(Subobj.getFloat(), SubobjType); 4244 case APValue::ComplexInt: 4245 return found(Subobj.getComplexIntReal(), 4246 SubobjType->castAs<ComplexType>()->getElementType() 4247 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4248 case APValue::ComplexFloat: 4249 return found(Subobj.getComplexFloatReal(), 4250 SubobjType->castAs<ComplexType>()->getElementType() 4251 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4252 case APValue::LValue: 4253 return foundPointer(Subobj, SubobjType); 4254 default: 4255 // FIXME: can this happen? 4256 Info.FFDiag(E); 4257 return false; 4258 } 4259 } 4260 bool found(APSInt &Value, QualType SubobjType) { 4261 if (!checkConst(SubobjType)) 4262 return false; 4263 4264 if (!SubobjType->isIntegerType()) { 4265 // We don't support increment / decrement on integer-cast-to-pointer 4266 // values. 4267 Info.FFDiag(E); 4268 return false; 4269 } 4270 4271 if (Old) *Old = APValue(Value); 4272 4273 // bool arithmetic promotes to int, and the conversion back to bool 4274 // doesn't reduce mod 2^n, so special-case it. 4275 if (SubobjType->isBooleanType()) { 4276 if (AccessKind == AK_Increment) 4277 Value = 1; 4278 else 4279 Value = !Value; 4280 return true; 4281 } 4282 4283 bool WasNegative = Value.isNegative(); 4284 if (AccessKind == AK_Increment) { 4285 ++Value; 4286 4287 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4288 APSInt ActualValue(Value, /*IsUnsigned*/true); 4289 return HandleOverflow(Info, E, ActualValue, SubobjType); 4290 } 4291 } else { 4292 --Value; 4293 4294 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4295 unsigned BitWidth = Value.getBitWidth(); 4296 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4297 ActualValue.setBit(BitWidth); 4298 return HandleOverflow(Info, E, ActualValue, SubobjType); 4299 } 4300 } 4301 return true; 4302 } 4303 bool found(APFloat &Value, QualType SubobjType) { 4304 if (!checkConst(SubobjType)) 4305 return false; 4306 4307 if (Old) *Old = APValue(Value); 4308 4309 APFloat One(Value.getSemantics(), 1); 4310 if (AccessKind == AK_Increment) 4311 Value.add(One, APFloat::rmNearestTiesToEven); 4312 else 4313 Value.subtract(One, APFloat::rmNearestTiesToEven); 4314 return true; 4315 } 4316 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4317 if (!checkConst(SubobjType)) 4318 return false; 4319 4320 QualType PointeeType; 4321 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4322 PointeeType = PT->getPointeeType(); 4323 else { 4324 Info.FFDiag(E); 4325 return false; 4326 } 4327 4328 LValue LVal; 4329 LVal.setFrom(Info.Ctx, Subobj); 4330 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4331 AccessKind == AK_Increment ? 1 : -1)) 4332 return false; 4333 LVal.moveInto(Subobj); 4334 return true; 4335 } 4336 }; 4337 } // end anonymous namespace 4338 4339 /// Perform an increment or decrement on LVal. 4340 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4341 QualType LValType, bool IsIncrement, APValue *Old) { 4342 if (LVal.Designator.Invalid) 4343 return false; 4344 4345 if (!Info.getLangOpts().CPlusPlus14) { 4346 Info.FFDiag(E); 4347 return false; 4348 } 4349 4350 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4351 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4352 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4353 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4354 } 4355 4356 /// Build an lvalue for the object argument of a member function call. 4357 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4358 LValue &This) { 4359 if (Object->getType()->isPointerType() && Object->isRValue()) 4360 return EvaluatePointer(Object, This, Info); 4361 4362 if (Object->isGLValue()) 4363 return EvaluateLValue(Object, This, Info); 4364 4365 if (Object->getType()->isLiteralType(Info.Ctx)) 4366 return EvaluateTemporary(Object, This, Info); 4367 4368 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4369 return false; 4370 } 4371 4372 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4373 /// lvalue referring to the result. 4374 /// 4375 /// \param Info - Information about the ongoing evaluation. 4376 /// \param LV - An lvalue referring to the base of the member pointer. 4377 /// \param RHS - The member pointer expression. 4378 /// \param IncludeMember - Specifies whether the member itself is included in 4379 /// the resulting LValue subobject designator. This is not possible when 4380 /// creating a bound member function. 4381 /// \return The field or method declaration to which the member pointer refers, 4382 /// or 0 if evaluation fails. 4383 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4384 QualType LVType, 4385 LValue &LV, 4386 const Expr *RHS, 4387 bool IncludeMember = true) { 4388 MemberPtr MemPtr; 4389 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4390 return nullptr; 4391 4392 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4393 // member value, the behavior is undefined. 4394 if (!MemPtr.getDecl()) { 4395 // FIXME: Specific diagnostic. 4396 Info.FFDiag(RHS); 4397 return nullptr; 4398 } 4399 4400 if (MemPtr.isDerivedMember()) { 4401 // This is a member of some derived class. Truncate LV appropriately. 4402 // The end of the derived-to-base path for the base object must match the 4403 // derived-to-base path for the member pointer. 4404 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4405 LV.Designator.Entries.size()) { 4406 Info.FFDiag(RHS); 4407 return nullptr; 4408 } 4409 unsigned PathLengthToMember = 4410 LV.Designator.Entries.size() - MemPtr.Path.size(); 4411 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4412 const CXXRecordDecl *LVDecl = getAsBaseClass( 4413 LV.Designator.Entries[PathLengthToMember + I]); 4414 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4415 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4416 Info.FFDiag(RHS); 4417 return nullptr; 4418 } 4419 } 4420 4421 // Truncate the lvalue to the appropriate derived class. 4422 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4423 PathLengthToMember)) 4424 return nullptr; 4425 } else if (!MemPtr.Path.empty()) { 4426 // Extend the LValue path with the member pointer's path. 4427 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4428 MemPtr.Path.size() + IncludeMember); 4429 4430 // Walk down to the appropriate base class. 4431 if (const PointerType *PT = LVType->getAs<PointerType>()) 4432 LVType = PT->getPointeeType(); 4433 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4434 assert(RD && "member pointer access on non-class-type expression"); 4435 // The first class in the path is that of the lvalue. 4436 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4437 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4438 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4439 return nullptr; 4440 RD = Base; 4441 } 4442 // Finally cast to the class containing the member. 4443 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4444 MemPtr.getContainingRecord())) 4445 return nullptr; 4446 } 4447 4448 // Add the member. Note that we cannot build bound member functions here. 4449 if (IncludeMember) { 4450 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4451 if (!HandleLValueMember(Info, RHS, LV, FD)) 4452 return nullptr; 4453 } else if (const IndirectFieldDecl *IFD = 4454 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4455 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4456 return nullptr; 4457 } else { 4458 llvm_unreachable("can't construct reference to bound member function"); 4459 } 4460 } 4461 4462 return MemPtr.getDecl(); 4463 } 4464 4465 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4466 const BinaryOperator *BO, 4467 LValue &LV, 4468 bool IncludeMember = true) { 4469 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4470 4471 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4472 if (Info.noteFailure()) { 4473 MemberPtr MemPtr; 4474 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4475 } 4476 return nullptr; 4477 } 4478 4479 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4480 BO->getRHS(), IncludeMember); 4481 } 4482 4483 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4484 /// the provided lvalue, which currently refers to the base object. 4485 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4486 LValue &Result) { 4487 SubobjectDesignator &D = Result.Designator; 4488 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4489 return false; 4490 4491 QualType TargetQT = E->getType(); 4492 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4493 TargetQT = PT->getPointeeType(); 4494 4495 // Check this cast lands within the final derived-to-base subobject path. 4496 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4497 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4498 << D.MostDerivedType << TargetQT; 4499 return false; 4500 } 4501 4502 // Check the type of the final cast. We don't need to check the path, 4503 // since a cast can only be formed if the path is unique. 4504 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4505 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4506 const CXXRecordDecl *FinalType; 4507 if (NewEntriesSize == D.MostDerivedPathLength) 4508 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4509 else 4510 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4511 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4512 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4513 << D.MostDerivedType << TargetQT; 4514 return false; 4515 } 4516 4517 // Truncate the lvalue to the appropriate derived class. 4518 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4519 } 4520 4521 /// Get the value to use for a default-initialized object of type T. 4522 /// Return false if it encounters something invalid. 4523 static bool getDefaultInitValue(QualType T, APValue &Result) { 4524 bool Success = true; 4525 if (auto *RD = T->getAsCXXRecordDecl()) { 4526 if (RD->isInvalidDecl()) { 4527 Result = APValue(); 4528 return false; 4529 } 4530 if (RD->isUnion()) { 4531 Result = APValue((const FieldDecl *)nullptr); 4532 return true; 4533 } 4534 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4535 std::distance(RD->field_begin(), RD->field_end())); 4536 4537 unsigned Index = 0; 4538 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4539 End = RD->bases_end(); 4540 I != End; ++I, ++Index) 4541 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4542 4543 for (const auto *I : RD->fields()) { 4544 if (I->isUnnamedBitfield()) 4545 continue; 4546 Success &= getDefaultInitValue(I->getType(), 4547 Result.getStructField(I->getFieldIndex())); 4548 } 4549 return Success; 4550 } 4551 4552 if (auto *AT = 4553 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4554 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4555 if (Result.hasArrayFiller()) 4556 Success &= 4557 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4558 4559 return Success; 4560 } 4561 4562 Result = APValue::IndeterminateValue(); 4563 return true; 4564 } 4565 4566 namespace { 4567 enum EvalStmtResult { 4568 /// Evaluation failed. 4569 ESR_Failed, 4570 /// Hit a 'return' statement. 4571 ESR_Returned, 4572 /// Evaluation succeeded. 4573 ESR_Succeeded, 4574 /// Hit a 'continue' statement. 4575 ESR_Continue, 4576 /// Hit a 'break' statement. 4577 ESR_Break, 4578 /// Still scanning for 'case' or 'default' statement. 4579 ESR_CaseNotFound 4580 }; 4581 } 4582 4583 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4584 // We don't need to evaluate the initializer for a static local. 4585 if (!VD->hasLocalStorage()) 4586 return true; 4587 4588 LValue Result; 4589 APValue &Val = 4590 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); 4591 4592 const Expr *InitE = VD->getInit(); 4593 if (!InitE) 4594 return getDefaultInitValue(VD->getType(), Val); 4595 4596 if (InitE->isValueDependent()) 4597 return false; 4598 4599 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4600 // Wipe out any partially-computed value, to allow tracking that this 4601 // evaluation failed. 4602 Val = APValue(); 4603 return false; 4604 } 4605 4606 return true; 4607 } 4608 4609 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4610 bool OK = true; 4611 4612 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4613 OK &= EvaluateVarDecl(Info, VD); 4614 4615 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4616 for (auto *BD : DD->bindings()) 4617 if (auto *VD = BD->getHoldingVar()) 4618 OK &= EvaluateDecl(Info, VD); 4619 4620 return OK; 4621 } 4622 4623 4624 /// Evaluate a condition (either a variable declaration or an expression). 4625 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4626 const Expr *Cond, bool &Result) { 4627 FullExpressionRAII Scope(Info); 4628 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4629 return false; 4630 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4631 return false; 4632 return Scope.destroy(); 4633 } 4634 4635 namespace { 4636 /// A location where the result (returned value) of evaluating a 4637 /// statement should be stored. 4638 struct StmtResult { 4639 /// The APValue that should be filled in with the returned value. 4640 APValue &Value; 4641 /// The location containing the result, if any (used to support RVO). 4642 const LValue *Slot; 4643 }; 4644 4645 struct TempVersionRAII { 4646 CallStackFrame &Frame; 4647 4648 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4649 Frame.pushTempVersion(); 4650 } 4651 4652 ~TempVersionRAII() { 4653 Frame.popTempVersion(); 4654 } 4655 }; 4656 4657 } 4658 4659 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4660 const Stmt *S, 4661 const SwitchCase *SC = nullptr); 4662 4663 /// Evaluate the body of a loop, and translate the result as appropriate. 4664 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4665 const Stmt *Body, 4666 const SwitchCase *Case = nullptr) { 4667 BlockScopeRAII Scope(Info); 4668 4669 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4670 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4671 ESR = ESR_Failed; 4672 4673 switch (ESR) { 4674 case ESR_Break: 4675 return ESR_Succeeded; 4676 case ESR_Succeeded: 4677 case ESR_Continue: 4678 return ESR_Continue; 4679 case ESR_Failed: 4680 case ESR_Returned: 4681 case ESR_CaseNotFound: 4682 return ESR; 4683 } 4684 llvm_unreachable("Invalid EvalStmtResult!"); 4685 } 4686 4687 /// Evaluate a switch statement. 4688 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4689 const SwitchStmt *SS) { 4690 BlockScopeRAII Scope(Info); 4691 4692 // Evaluate the switch condition. 4693 APSInt Value; 4694 { 4695 if (const Stmt *Init = SS->getInit()) { 4696 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4697 if (ESR != ESR_Succeeded) { 4698 if (ESR != ESR_Failed && !Scope.destroy()) 4699 ESR = ESR_Failed; 4700 return ESR; 4701 } 4702 } 4703 4704 FullExpressionRAII CondScope(Info); 4705 if (SS->getConditionVariable() && 4706 !EvaluateDecl(Info, SS->getConditionVariable())) 4707 return ESR_Failed; 4708 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4709 return ESR_Failed; 4710 if (!CondScope.destroy()) 4711 return ESR_Failed; 4712 } 4713 4714 // Find the switch case corresponding to the value of the condition. 4715 // FIXME: Cache this lookup. 4716 const SwitchCase *Found = nullptr; 4717 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4718 SC = SC->getNextSwitchCase()) { 4719 if (isa<DefaultStmt>(SC)) { 4720 Found = SC; 4721 continue; 4722 } 4723 4724 const CaseStmt *CS = cast<CaseStmt>(SC); 4725 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4726 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4727 : LHS; 4728 if (LHS <= Value && Value <= RHS) { 4729 Found = SC; 4730 break; 4731 } 4732 } 4733 4734 if (!Found) 4735 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4736 4737 // Search the switch body for the switch case and evaluate it from there. 4738 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4739 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4740 return ESR_Failed; 4741 4742 switch (ESR) { 4743 case ESR_Break: 4744 return ESR_Succeeded; 4745 case ESR_Succeeded: 4746 case ESR_Continue: 4747 case ESR_Failed: 4748 case ESR_Returned: 4749 return ESR; 4750 case ESR_CaseNotFound: 4751 // This can only happen if the switch case is nested within a statement 4752 // expression. We have no intention of supporting that. 4753 Info.FFDiag(Found->getBeginLoc(), 4754 diag::note_constexpr_stmt_expr_unsupported); 4755 return ESR_Failed; 4756 } 4757 llvm_unreachable("Invalid EvalStmtResult!"); 4758 } 4759 4760 // Evaluate a statement. 4761 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4762 const Stmt *S, const SwitchCase *Case) { 4763 if (!Info.nextStep(S)) 4764 return ESR_Failed; 4765 4766 // If we're hunting down a 'case' or 'default' label, recurse through 4767 // substatements until we hit the label. 4768 if (Case) { 4769 switch (S->getStmtClass()) { 4770 case Stmt::CompoundStmtClass: 4771 // FIXME: Precompute which substatement of a compound statement we 4772 // would jump to, and go straight there rather than performing a 4773 // linear scan each time. 4774 case Stmt::LabelStmtClass: 4775 case Stmt::AttributedStmtClass: 4776 case Stmt::DoStmtClass: 4777 break; 4778 4779 case Stmt::CaseStmtClass: 4780 case Stmt::DefaultStmtClass: 4781 if (Case == S) 4782 Case = nullptr; 4783 break; 4784 4785 case Stmt::IfStmtClass: { 4786 // FIXME: Precompute which side of an 'if' we would jump to, and go 4787 // straight there rather than scanning both sides. 4788 const IfStmt *IS = cast<IfStmt>(S); 4789 4790 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4791 // preceded by our switch label. 4792 BlockScopeRAII Scope(Info); 4793 4794 // Step into the init statement in case it brings an (uninitialized) 4795 // variable into scope. 4796 if (const Stmt *Init = IS->getInit()) { 4797 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4798 if (ESR != ESR_CaseNotFound) { 4799 assert(ESR != ESR_Succeeded); 4800 return ESR; 4801 } 4802 } 4803 4804 // Condition variable must be initialized if it exists. 4805 // FIXME: We can skip evaluating the body if there's a condition 4806 // variable, as there can't be any case labels within it. 4807 // (The same is true for 'for' statements.) 4808 4809 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4810 if (ESR == ESR_Failed) 4811 return ESR; 4812 if (ESR != ESR_CaseNotFound) 4813 return Scope.destroy() ? ESR : ESR_Failed; 4814 if (!IS->getElse()) 4815 return ESR_CaseNotFound; 4816 4817 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4818 if (ESR == ESR_Failed) 4819 return ESR; 4820 if (ESR != ESR_CaseNotFound) 4821 return Scope.destroy() ? ESR : ESR_Failed; 4822 return ESR_CaseNotFound; 4823 } 4824 4825 case Stmt::WhileStmtClass: { 4826 EvalStmtResult ESR = 4827 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4828 if (ESR != ESR_Continue) 4829 return ESR; 4830 break; 4831 } 4832 4833 case Stmt::ForStmtClass: { 4834 const ForStmt *FS = cast<ForStmt>(S); 4835 BlockScopeRAII Scope(Info); 4836 4837 // Step into the init statement in case it brings an (uninitialized) 4838 // variable into scope. 4839 if (const Stmt *Init = FS->getInit()) { 4840 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4841 if (ESR != ESR_CaseNotFound) { 4842 assert(ESR != ESR_Succeeded); 4843 return ESR; 4844 } 4845 } 4846 4847 EvalStmtResult ESR = 4848 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4849 if (ESR != ESR_Continue) 4850 return ESR; 4851 if (FS->getInc()) { 4852 FullExpressionRAII IncScope(Info); 4853 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4854 return ESR_Failed; 4855 } 4856 break; 4857 } 4858 4859 case Stmt::DeclStmtClass: { 4860 // Start the lifetime of any uninitialized variables we encounter. They 4861 // might be used by the selected branch of the switch. 4862 const DeclStmt *DS = cast<DeclStmt>(S); 4863 for (const auto *D : DS->decls()) { 4864 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4865 if (VD->hasLocalStorage() && !VD->getInit()) 4866 if (!EvaluateVarDecl(Info, VD)) 4867 return ESR_Failed; 4868 // FIXME: If the variable has initialization that can't be jumped 4869 // over, bail out of any immediately-surrounding compound-statement 4870 // too. There can't be any case labels here. 4871 } 4872 } 4873 return ESR_CaseNotFound; 4874 } 4875 4876 default: 4877 return ESR_CaseNotFound; 4878 } 4879 } 4880 4881 switch (S->getStmtClass()) { 4882 default: 4883 if (const Expr *E = dyn_cast<Expr>(S)) { 4884 // Don't bother evaluating beyond an expression-statement which couldn't 4885 // be evaluated. 4886 // FIXME: Do we need the FullExpressionRAII object here? 4887 // VisitExprWithCleanups should create one when necessary. 4888 FullExpressionRAII Scope(Info); 4889 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 4890 return ESR_Failed; 4891 return ESR_Succeeded; 4892 } 4893 4894 Info.FFDiag(S->getBeginLoc()); 4895 return ESR_Failed; 4896 4897 case Stmt::NullStmtClass: 4898 return ESR_Succeeded; 4899 4900 case Stmt::DeclStmtClass: { 4901 const DeclStmt *DS = cast<DeclStmt>(S); 4902 for (const auto *D : DS->decls()) { 4903 // Each declaration initialization is its own full-expression. 4904 FullExpressionRAII Scope(Info); 4905 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 4906 return ESR_Failed; 4907 if (!Scope.destroy()) 4908 return ESR_Failed; 4909 } 4910 return ESR_Succeeded; 4911 } 4912 4913 case Stmt::ReturnStmtClass: { 4914 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4915 FullExpressionRAII Scope(Info); 4916 if (RetExpr && 4917 !(Result.Slot 4918 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4919 : Evaluate(Result.Value, Info, RetExpr))) 4920 return ESR_Failed; 4921 return Scope.destroy() ? ESR_Returned : ESR_Failed; 4922 } 4923 4924 case Stmt::CompoundStmtClass: { 4925 BlockScopeRAII Scope(Info); 4926 4927 const CompoundStmt *CS = cast<CompoundStmt>(S); 4928 for (const auto *BI : CS->body()) { 4929 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4930 if (ESR == ESR_Succeeded) 4931 Case = nullptr; 4932 else if (ESR != ESR_CaseNotFound) { 4933 if (ESR != ESR_Failed && !Scope.destroy()) 4934 return ESR_Failed; 4935 return ESR; 4936 } 4937 } 4938 if (Case) 4939 return ESR_CaseNotFound; 4940 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4941 } 4942 4943 case Stmt::IfStmtClass: { 4944 const IfStmt *IS = cast<IfStmt>(S); 4945 4946 // Evaluate the condition, as either a var decl or as an expression. 4947 BlockScopeRAII Scope(Info); 4948 if (const Stmt *Init = IS->getInit()) { 4949 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4950 if (ESR != ESR_Succeeded) { 4951 if (ESR != ESR_Failed && !Scope.destroy()) 4952 return ESR_Failed; 4953 return ESR; 4954 } 4955 } 4956 bool Cond; 4957 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4958 return ESR_Failed; 4959 4960 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4961 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4962 if (ESR != ESR_Succeeded) { 4963 if (ESR != ESR_Failed && !Scope.destroy()) 4964 return ESR_Failed; 4965 return ESR; 4966 } 4967 } 4968 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4969 } 4970 4971 case Stmt::WhileStmtClass: { 4972 const WhileStmt *WS = cast<WhileStmt>(S); 4973 while (true) { 4974 BlockScopeRAII Scope(Info); 4975 bool Continue; 4976 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4977 Continue)) 4978 return ESR_Failed; 4979 if (!Continue) 4980 break; 4981 4982 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4983 if (ESR != ESR_Continue) { 4984 if (ESR != ESR_Failed && !Scope.destroy()) 4985 return ESR_Failed; 4986 return ESR; 4987 } 4988 if (!Scope.destroy()) 4989 return ESR_Failed; 4990 } 4991 return ESR_Succeeded; 4992 } 4993 4994 case Stmt::DoStmtClass: { 4995 const DoStmt *DS = cast<DoStmt>(S); 4996 bool Continue; 4997 do { 4998 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4999 if (ESR != ESR_Continue) 5000 return ESR; 5001 Case = nullptr; 5002 5003 FullExpressionRAII CondScope(Info); 5004 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5005 !CondScope.destroy()) 5006 return ESR_Failed; 5007 } while (Continue); 5008 return ESR_Succeeded; 5009 } 5010 5011 case Stmt::ForStmtClass: { 5012 const ForStmt *FS = cast<ForStmt>(S); 5013 BlockScopeRAII ForScope(Info); 5014 if (FS->getInit()) { 5015 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5016 if (ESR != ESR_Succeeded) { 5017 if (ESR != ESR_Failed && !ForScope.destroy()) 5018 return ESR_Failed; 5019 return ESR; 5020 } 5021 } 5022 while (true) { 5023 BlockScopeRAII IterScope(Info); 5024 bool Continue = true; 5025 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5026 FS->getCond(), Continue)) 5027 return ESR_Failed; 5028 if (!Continue) 5029 break; 5030 5031 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5032 if (ESR != ESR_Continue) { 5033 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5034 return ESR_Failed; 5035 return ESR; 5036 } 5037 5038 if (FS->getInc()) { 5039 FullExpressionRAII IncScope(Info); 5040 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5041 return ESR_Failed; 5042 } 5043 5044 if (!IterScope.destroy()) 5045 return ESR_Failed; 5046 } 5047 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5048 } 5049 5050 case Stmt::CXXForRangeStmtClass: { 5051 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5052 BlockScopeRAII Scope(Info); 5053 5054 // Evaluate the init-statement if present. 5055 if (FS->getInit()) { 5056 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5057 if (ESR != ESR_Succeeded) { 5058 if (ESR != ESR_Failed && !Scope.destroy()) 5059 return ESR_Failed; 5060 return ESR; 5061 } 5062 } 5063 5064 // Initialize the __range variable. 5065 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5066 if (ESR != ESR_Succeeded) { 5067 if (ESR != ESR_Failed && !Scope.destroy()) 5068 return ESR_Failed; 5069 return ESR; 5070 } 5071 5072 // Create the __begin and __end iterators. 5073 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5074 if (ESR != ESR_Succeeded) { 5075 if (ESR != ESR_Failed && !Scope.destroy()) 5076 return ESR_Failed; 5077 return ESR; 5078 } 5079 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5080 if (ESR != ESR_Succeeded) { 5081 if (ESR != ESR_Failed && !Scope.destroy()) 5082 return ESR_Failed; 5083 return ESR; 5084 } 5085 5086 while (true) { 5087 // Condition: __begin != __end. 5088 { 5089 bool Continue = true; 5090 FullExpressionRAII CondExpr(Info); 5091 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5092 return ESR_Failed; 5093 if (!Continue) 5094 break; 5095 } 5096 5097 // User's variable declaration, initialized by *__begin. 5098 BlockScopeRAII InnerScope(Info); 5099 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5100 if (ESR != ESR_Succeeded) { 5101 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5102 return ESR_Failed; 5103 return ESR; 5104 } 5105 5106 // Loop body. 5107 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5108 if (ESR != ESR_Continue) { 5109 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5110 return ESR_Failed; 5111 return ESR; 5112 } 5113 5114 // Increment: ++__begin 5115 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5116 return ESR_Failed; 5117 5118 if (!InnerScope.destroy()) 5119 return ESR_Failed; 5120 } 5121 5122 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5123 } 5124 5125 case Stmt::SwitchStmtClass: 5126 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5127 5128 case Stmt::ContinueStmtClass: 5129 return ESR_Continue; 5130 5131 case Stmt::BreakStmtClass: 5132 return ESR_Break; 5133 5134 case Stmt::LabelStmtClass: 5135 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5136 5137 case Stmt::AttributedStmtClass: 5138 // As a general principle, C++11 attributes can be ignored without 5139 // any semantic impact. 5140 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5141 Case); 5142 5143 case Stmt::CaseStmtClass: 5144 case Stmt::DefaultStmtClass: 5145 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5146 case Stmt::CXXTryStmtClass: 5147 // Evaluate try blocks by evaluating all sub statements. 5148 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5149 } 5150 } 5151 5152 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5153 /// default constructor. If so, we'll fold it whether or not it's marked as 5154 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5155 /// so we need special handling. 5156 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5157 const CXXConstructorDecl *CD, 5158 bool IsValueInitialization) { 5159 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5160 return false; 5161 5162 // Value-initialization does not call a trivial default constructor, so such a 5163 // call is a core constant expression whether or not the constructor is 5164 // constexpr. 5165 if (!CD->isConstexpr() && !IsValueInitialization) { 5166 if (Info.getLangOpts().CPlusPlus11) { 5167 // FIXME: If DiagDecl is an implicitly-declared special member function, 5168 // we should be much more explicit about why it's not constexpr. 5169 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5170 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5171 Info.Note(CD->getLocation(), diag::note_declared_at); 5172 } else { 5173 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5174 } 5175 } 5176 return true; 5177 } 5178 5179 /// CheckConstexprFunction - Check that a function can be called in a constant 5180 /// expression. 5181 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5182 const FunctionDecl *Declaration, 5183 const FunctionDecl *Definition, 5184 const Stmt *Body) { 5185 // Potential constant expressions can contain calls to declared, but not yet 5186 // defined, constexpr functions. 5187 if (Info.checkingPotentialConstantExpression() && !Definition && 5188 Declaration->isConstexpr()) 5189 return false; 5190 5191 // Bail out if the function declaration itself is invalid. We will 5192 // have produced a relevant diagnostic while parsing it, so just 5193 // note the problematic sub-expression. 5194 if (Declaration->isInvalidDecl()) { 5195 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5196 return false; 5197 } 5198 5199 // DR1872: An instantiated virtual constexpr function can't be called in a 5200 // constant expression (prior to C++20). We can still constant-fold such a 5201 // call. 5202 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5203 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5204 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5205 5206 if (Definition && Definition->isInvalidDecl()) { 5207 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5208 return false; 5209 } 5210 5211 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) { 5212 for (const auto *InitExpr : CtorDecl->inits()) { 5213 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 5214 return false; 5215 } 5216 } 5217 5218 // Can we evaluate this function call? 5219 if (Definition && Definition->isConstexpr() && Body) 5220 return true; 5221 5222 if (Info.getLangOpts().CPlusPlus11) { 5223 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5224 5225 // If this function is not constexpr because it is an inherited 5226 // non-constexpr constructor, diagnose that directly. 5227 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5228 if (CD && CD->isInheritingConstructor()) { 5229 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5230 if (!Inherited->isConstexpr()) 5231 DiagDecl = CD = Inherited; 5232 } 5233 5234 // FIXME: If DiagDecl is an implicitly-declared special member function 5235 // or an inheriting constructor, we should be much more explicit about why 5236 // it's not constexpr. 5237 if (CD && CD->isInheritingConstructor()) 5238 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5239 << CD->getInheritedConstructor().getConstructor()->getParent(); 5240 else 5241 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5242 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5243 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5244 } else { 5245 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5246 } 5247 return false; 5248 } 5249 5250 namespace { 5251 struct CheckDynamicTypeHandler { 5252 AccessKinds AccessKind; 5253 typedef bool result_type; 5254 bool failed() { return false; } 5255 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5256 bool found(APSInt &Value, QualType SubobjType) { return true; } 5257 bool found(APFloat &Value, QualType SubobjType) { return true; } 5258 }; 5259 } // end anonymous namespace 5260 5261 /// Check that we can access the notional vptr of an object / determine its 5262 /// dynamic type. 5263 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5264 AccessKinds AK, bool Polymorphic) { 5265 if (This.Designator.Invalid) 5266 return false; 5267 5268 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5269 5270 if (!Obj) 5271 return false; 5272 5273 if (!Obj.Value) { 5274 // The object is not usable in constant expressions, so we can't inspect 5275 // its value to see if it's in-lifetime or what the active union members 5276 // are. We can still check for a one-past-the-end lvalue. 5277 if (This.Designator.isOnePastTheEnd() || 5278 This.Designator.isMostDerivedAnUnsizedArray()) { 5279 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5280 ? diag::note_constexpr_access_past_end 5281 : diag::note_constexpr_access_unsized_array) 5282 << AK; 5283 return false; 5284 } else if (Polymorphic) { 5285 // Conservatively refuse to perform a polymorphic operation if we would 5286 // not be able to read a notional 'vptr' value. 5287 APValue Val; 5288 This.moveInto(Val); 5289 QualType StarThisType = 5290 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5291 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5292 << AK << Val.getAsString(Info.Ctx, StarThisType); 5293 return false; 5294 } 5295 return true; 5296 } 5297 5298 CheckDynamicTypeHandler Handler{AK}; 5299 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5300 } 5301 5302 /// Check that the pointee of the 'this' pointer in a member function call is 5303 /// either within its lifetime or in its period of construction or destruction. 5304 static bool 5305 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5306 const LValue &This, 5307 const CXXMethodDecl *NamedMember) { 5308 return checkDynamicType( 5309 Info, E, This, 5310 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5311 } 5312 5313 struct DynamicType { 5314 /// The dynamic class type of the object. 5315 const CXXRecordDecl *Type; 5316 /// The corresponding path length in the lvalue. 5317 unsigned PathLength; 5318 }; 5319 5320 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5321 unsigned PathLength) { 5322 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5323 Designator.Entries.size() && "invalid path length"); 5324 return (PathLength == Designator.MostDerivedPathLength) 5325 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5326 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5327 } 5328 5329 /// Determine the dynamic type of an object. 5330 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5331 LValue &This, AccessKinds AK) { 5332 // If we don't have an lvalue denoting an object of class type, there is no 5333 // meaningful dynamic type. (We consider objects of non-class type to have no 5334 // dynamic type.) 5335 if (!checkDynamicType(Info, E, This, AK, true)) 5336 return None; 5337 5338 // Refuse to compute a dynamic type in the presence of virtual bases. This 5339 // shouldn't happen other than in constant-folding situations, since literal 5340 // types can't have virtual bases. 5341 // 5342 // Note that consumers of DynamicType assume that the type has no virtual 5343 // bases, and will need modifications if this restriction is relaxed. 5344 const CXXRecordDecl *Class = 5345 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5346 if (!Class || Class->getNumVBases()) { 5347 Info.FFDiag(E); 5348 return None; 5349 } 5350 5351 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5352 // binary search here instead. But the overwhelmingly common case is that 5353 // we're not in the middle of a constructor, so it probably doesn't matter 5354 // in practice. 5355 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5356 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5357 PathLength <= Path.size(); ++PathLength) { 5358 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5359 Path.slice(0, PathLength))) { 5360 case ConstructionPhase::Bases: 5361 case ConstructionPhase::DestroyingBases: 5362 // We're constructing or destroying a base class. This is not the dynamic 5363 // type. 5364 break; 5365 5366 case ConstructionPhase::None: 5367 case ConstructionPhase::AfterBases: 5368 case ConstructionPhase::AfterFields: 5369 case ConstructionPhase::Destroying: 5370 // We've finished constructing the base classes and not yet started 5371 // destroying them again, so this is the dynamic type. 5372 return DynamicType{getBaseClassType(This.Designator, PathLength), 5373 PathLength}; 5374 } 5375 } 5376 5377 // CWG issue 1517: we're constructing a base class of the object described by 5378 // 'This', so that object has not yet begun its period of construction and 5379 // any polymorphic operation on it results in undefined behavior. 5380 Info.FFDiag(E); 5381 return None; 5382 } 5383 5384 /// Perform virtual dispatch. 5385 static const CXXMethodDecl *HandleVirtualDispatch( 5386 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5387 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5388 Optional<DynamicType> DynType = ComputeDynamicType( 5389 Info, E, This, 5390 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5391 if (!DynType) 5392 return nullptr; 5393 5394 // Find the final overrider. It must be declared in one of the classes on the 5395 // path from the dynamic type to the static type. 5396 // FIXME: If we ever allow literal types to have virtual base classes, that 5397 // won't be true. 5398 const CXXMethodDecl *Callee = Found; 5399 unsigned PathLength = DynType->PathLength; 5400 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5401 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5402 const CXXMethodDecl *Overrider = 5403 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5404 if (Overrider) { 5405 Callee = Overrider; 5406 break; 5407 } 5408 } 5409 5410 // C++2a [class.abstract]p6: 5411 // the effect of making a virtual call to a pure virtual function [...] is 5412 // undefined 5413 if (Callee->isPure()) { 5414 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5415 Info.Note(Callee->getLocation(), diag::note_declared_at); 5416 return nullptr; 5417 } 5418 5419 // If necessary, walk the rest of the path to determine the sequence of 5420 // covariant adjustment steps to apply. 5421 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5422 Found->getReturnType())) { 5423 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5424 for (unsigned CovariantPathLength = PathLength + 1; 5425 CovariantPathLength != This.Designator.Entries.size(); 5426 ++CovariantPathLength) { 5427 const CXXRecordDecl *NextClass = 5428 getBaseClassType(This.Designator, CovariantPathLength); 5429 const CXXMethodDecl *Next = 5430 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5431 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5432 Next->getReturnType(), CovariantAdjustmentPath.back())) 5433 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5434 } 5435 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5436 CovariantAdjustmentPath.back())) 5437 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5438 } 5439 5440 // Perform 'this' adjustment. 5441 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5442 return nullptr; 5443 5444 return Callee; 5445 } 5446 5447 /// Perform the adjustment from a value returned by a virtual function to 5448 /// a value of the statically expected type, which may be a pointer or 5449 /// reference to a base class of the returned type. 5450 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5451 APValue &Result, 5452 ArrayRef<QualType> Path) { 5453 assert(Result.isLValue() && 5454 "unexpected kind of APValue for covariant return"); 5455 if (Result.isNullPointer()) 5456 return true; 5457 5458 LValue LVal; 5459 LVal.setFrom(Info.Ctx, Result); 5460 5461 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5462 for (unsigned I = 1; I != Path.size(); ++I) { 5463 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5464 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5465 if (OldClass != NewClass && 5466 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5467 return false; 5468 OldClass = NewClass; 5469 } 5470 5471 LVal.moveInto(Result); 5472 return true; 5473 } 5474 5475 /// Determine whether \p Base, which is known to be a direct base class of 5476 /// \p Derived, is a public base class. 5477 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5478 const CXXRecordDecl *Base) { 5479 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5480 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5481 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5482 return BaseSpec.getAccessSpecifier() == AS_public; 5483 } 5484 llvm_unreachable("Base is not a direct base of Derived"); 5485 } 5486 5487 /// Apply the given dynamic cast operation on the provided lvalue. 5488 /// 5489 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5490 /// to find a suitable target subobject. 5491 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5492 LValue &Ptr) { 5493 // We can't do anything with a non-symbolic pointer value. 5494 SubobjectDesignator &D = Ptr.Designator; 5495 if (D.Invalid) 5496 return false; 5497 5498 // C++ [expr.dynamic.cast]p6: 5499 // If v is a null pointer value, the result is a null pointer value. 5500 if (Ptr.isNullPointer() && !E->isGLValue()) 5501 return true; 5502 5503 // For all the other cases, we need the pointer to point to an object within 5504 // its lifetime / period of construction / destruction, and we need to know 5505 // its dynamic type. 5506 Optional<DynamicType> DynType = 5507 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5508 if (!DynType) 5509 return false; 5510 5511 // C++ [expr.dynamic.cast]p7: 5512 // If T is "pointer to cv void", then the result is a pointer to the most 5513 // derived object 5514 if (E->getType()->isVoidPointerType()) 5515 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5516 5517 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5518 assert(C && "dynamic_cast target is not void pointer nor class"); 5519 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5520 5521 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5522 // C++ [expr.dynamic.cast]p9: 5523 if (!E->isGLValue()) { 5524 // The value of a failed cast to pointer type is the null pointer value 5525 // of the required result type. 5526 Ptr.setNull(Info.Ctx, E->getType()); 5527 return true; 5528 } 5529 5530 // A failed cast to reference type throws [...] std::bad_cast. 5531 unsigned DiagKind; 5532 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5533 DynType->Type->isDerivedFrom(C))) 5534 DiagKind = 0; 5535 else if (!Paths || Paths->begin() == Paths->end()) 5536 DiagKind = 1; 5537 else if (Paths->isAmbiguous(CQT)) 5538 DiagKind = 2; 5539 else { 5540 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5541 DiagKind = 3; 5542 } 5543 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5544 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5545 << Info.Ctx.getRecordType(DynType->Type) 5546 << E->getType().getUnqualifiedType(); 5547 return false; 5548 }; 5549 5550 // Runtime check, phase 1: 5551 // Walk from the base subobject towards the derived object looking for the 5552 // target type. 5553 for (int PathLength = Ptr.Designator.Entries.size(); 5554 PathLength >= (int)DynType->PathLength; --PathLength) { 5555 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5556 if (declaresSameEntity(Class, C)) 5557 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5558 // We can only walk across public inheritance edges. 5559 if (PathLength > (int)DynType->PathLength && 5560 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5561 Class)) 5562 return RuntimeCheckFailed(nullptr); 5563 } 5564 5565 // Runtime check, phase 2: 5566 // Search the dynamic type for an unambiguous public base of type C. 5567 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5568 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5569 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5570 Paths.front().Access == AS_public) { 5571 // Downcast to the dynamic type... 5572 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5573 return false; 5574 // ... then upcast to the chosen base class subobject. 5575 for (CXXBasePathElement &Elem : Paths.front()) 5576 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5577 return false; 5578 return true; 5579 } 5580 5581 // Otherwise, the runtime check fails. 5582 return RuntimeCheckFailed(&Paths); 5583 } 5584 5585 namespace { 5586 struct StartLifetimeOfUnionMemberHandler { 5587 EvalInfo &Info; 5588 const Expr *LHSExpr; 5589 const FieldDecl *Field; 5590 bool DuringInit; 5591 bool Failed = false; 5592 static const AccessKinds AccessKind = AK_Assign; 5593 5594 typedef bool result_type; 5595 bool failed() { return Failed; } 5596 bool found(APValue &Subobj, QualType SubobjType) { 5597 // We are supposed to perform no initialization but begin the lifetime of 5598 // the object. We interpret that as meaning to do what default 5599 // initialization of the object would do if all constructors involved were 5600 // trivial: 5601 // * All base, non-variant member, and array element subobjects' lifetimes 5602 // begin 5603 // * No variant members' lifetimes begin 5604 // * All scalar subobjects whose lifetimes begin have indeterminate values 5605 assert(SubobjType->isUnionType()); 5606 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5607 // This union member is already active. If it's also in-lifetime, there's 5608 // nothing to do. 5609 if (Subobj.getUnionValue().hasValue()) 5610 return true; 5611 } else if (DuringInit) { 5612 // We're currently in the process of initializing a different union 5613 // member. If we carried on, that initialization would attempt to 5614 // store to an inactive union member, resulting in undefined behavior. 5615 Info.FFDiag(LHSExpr, 5616 diag::note_constexpr_union_member_change_during_init); 5617 return false; 5618 } 5619 APValue Result; 5620 Failed = !getDefaultInitValue(Field->getType(), Result); 5621 Subobj.setUnion(Field, Result); 5622 return true; 5623 } 5624 bool found(APSInt &Value, QualType SubobjType) { 5625 llvm_unreachable("wrong value kind for union object"); 5626 } 5627 bool found(APFloat &Value, QualType SubobjType) { 5628 llvm_unreachable("wrong value kind for union object"); 5629 } 5630 }; 5631 } // end anonymous namespace 5632 5633 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5634 5635 /// Handle a builtin simple-assignment or a call to a trivial assignment 5636 /// operator whose left-hand side might involve a union member access. If it 5637 /// does, implicitly start the lifetime of any accessed union elements per 5638 /// C++20 [class.union]5. 5639 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5640 const LValue &LHS) { 5641 if (LHS.InvalidBase || LHS.Designator.Invalid) 5642 return false; 5643 5644 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5645 // C++ [class.union]p5: 5646 // define the set S(E) of subexpressions of E as follows: 5647 unsigned PathLength = LHS.Designator.Entries.size(); 5648 for (const Expr *E = LHSExpr; E != nullptr;) { 5649 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5650 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5651 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5652 // Note that we can't implicitly start the lifetime of a reference, 5653 // so we don't need to proceed any further if we reach one. 5654 if (!FD || FD->getType()->isReferenceType()) 5655 break; 5656 5657 // ... and also contains A.B if B names a union member ... 5658 if (FD->getParent()->isUnion()) { 5659 // ... of a non-class, non-array type, or of a class type with a 5660 // trivial default constructor that is not deleted, or an array of 5661 // such types. 5662 auto *RD = 5663 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5664 if (!RD || RD->hasTrivialDefaultConstructor()) 5665 UnionPathLengths.push_back({PathLength - 1, FD}); 5666 } 5667 5668 E = ME->getBase(); 5669 --PathLength; 5670 assert(declaresSameEntity(FD, 5671 LHS.Designator.Entries[PathLength] 5672 .getAsBaseOrMember().getPointer())); 5673 5674 // -- If E is of the form A[B] and is interpreted as a built-in array 5675 // subscripting operator, S(E) is [S(the array operand, if any)]. 5676 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5677 // Step over an ArrayToPointerDecay implicit cast. 5678 auto *Base = ASE->getBase()->IgnoreImplicit(); 5679 if (!Base->getType()->isArrayType()) 5680 break; 5681 5682 E = Base; 5683 --PathLength; 5684 5685 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5686 // Step over a derived-to-base conversion. 5687 E = ICE->getSubExpr(); 5688 if (ICE->getCastKind() == CK_NoOp) 5689 continue; 5690 if (ICE->getCastKind() != CK_DerivedToBase && 5691 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5692 break; 5693 // Walk path backwards as we walk up from the base to the derived class. 5694 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5695 --PathLength; 5696 (void)Elt; 5697 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5698 LHS.Designator.Entries[PathLength] 5699 .getAsBaseOrMember().getPointer())); 5700 } 5701 5702 // -- Otherwise, S(E) is empty. 5703 } else { 5704 break; 5705 } 5706 } 5707 5708 // Common case: no unions' lifetimes are started. 5709 if (UnionPathLengths.empty()) 5710 return true; 5711 5712 // if modification of X [would access an inactive union member], an object 5713 // of the type of X is implicitly created 5714 CompleteObject Obj = 5715 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5716 if (!Obj) 5717 return false; 5718 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5719 llvm::reverse(UnionPathLengths)) { 5720 // Form a designator for the union object. 5721 SubobjectDesignator D = LHS.Designator; 5722 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5723 5724 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5725 ConstructionPhase::AfterBases; 5726 StartLifetimeOfUnionMemberHandler StartLifetime{ 5727 Info, LHSExpr, LengthAndField.second, DuringInit}; 5728 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5729 return false; 5730 } 5731 5732 return true; 5733 } 5734 5735 namespace { 5736 typedef SmallVector<APValue, 8> ArgVector; 5737 } 5738 5739 /// EvaluateArgs - Evaluate the arguments to a function call. 5740 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5741 EvalInfo &Info, const FunctionDecl *Callee) { 5742 bool Success = true; 5743 llvm::SmallBitVector ForbiddenNullArgs; 5744 if (Callee->hasAttr<NonNullAttr>()) { 5745 ForbiddenNullArgs.resize(Args.size()); 5746 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5747 if (!Attr->args_size()) { 5748 ForbiddenNullArgs.set(); 5749 break; 5750 } else 5751 for (auto Idx : Attr->args()) { 5752 unsigned ASTIdx = Idx.getASTIndex(); 5753 if (ASTIdx >= Args.size()) 5754 continue; 5755 ForbiddenNullArgs[ASTIdx] = 1; 5756 } 5757 } 5758 } 5759 // FIXME: This is the wrong evaluation order for an assignment operator 5760 // called via operator syntax. 5761 for (unsigned Idx = 0; Idx < Args.size(); Idx++) { 5762 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) { 5763 // If we're checking for a potential constant expression, evaluate all 5764 // initializers even if some of them fail. 5765 if (!Info.noteFailure()) 5766 return false; 5767 Success = false; 5768 } else if (!ForbiddenNullArgs.empty() && 5769 ForbiddenNullArgs[Idx] && 5770 ArgValues[Idx].isLValue() && 5771 ArgValues[Idx].isNullPointer()) { 5772 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed); 5773 if (!Info.noteFailure()) 5774 return false; 5775 Success = false; 5776 } 5777 } 5778 return Success; 5779 } 5780 5781 /// Evaluate a function call. 5782 static bool HandleFunctionCall(SourceLocation CallLoc, 5783 const FunctionDecl *Callee, const LValue *This, 5784 ArrayRef<const Expr*> Args, const Stmt *Body, 5785 EvalInfo &Info, APValue &Result, 5786 const LValue *ResultSlot) { 5787 ArgVector ArgValues(Args.size()); 5788 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 5789 return false; 5790 5791 if (!Info.CheckCallLimit(CallLoc)) 5792 return false; 5793 5794 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5795 5796 // For a trivial copy or move assignment, perform an APValue copy. This is 5797 // essential for unions, where the operations performed by the assignment 5798 // operator cannot be represented as statements. 5799 // 5800 // Skip this for non-union classes with no fields; in that case, the defaulted 5801 // copy/move does not actually read the object. 5802 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5803 if (MD && MD->isDefaulted() && 5804 (MD->getParent()->isUnion() || 5805 (MD->isTrivial() && 5806 isReadByLvalueToRvalueConversion(MD->getParent())))) { 5807 assert(This && 5808 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5809 LValue RHS; 5810 RHS.setFrom(Info.Ctx, ArgValues[0]); 5811 APValue RHSValue; 5812 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, 5813 RHSValue, MD->getParent()->isUnion())) 5814 return false; 5815 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 5816 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5817 return false; 5818 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5819 RHSValue)) 5820 return false; 5821 This->moveInto(Result); 5822 return true; 5823 } else if (MD && isLambdaCallOperator(MD)) { 5824 // We're in a lambda; determine the lambda capture field maps unless we're 5825 // just constexpr checking a lambda's call operator. constexpr checking is 5826 // done before the captures have been added to the closure object (unless 5827 // we're inferring constexpr-ness), so we don't have access to them in this 5828 // case. But since we don't need the captures to constexpr check, we can 5829 // just ignore them. 5830 if (!Info.checkingPotentialConstantExpression()) 5831 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5832 Frame.LambdaThisCaptureField); 5833 } 5834 5835 StmtResult Ret = {Result, ResultSlot}; 5836 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5837 if (ESR == ESR_Succeeded) { 5838 if (Callee->getReturnType()->isVoidType()) 5839 return true; 5840 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5841 } 5842 return ESR == ESR_Returned; 5843 } 5844 5845 /// Evaluate a constructor call. 5846 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5847 APValue *ArgValues, 5848 const CXXConstructorDecl *Definition, 5849 EvalInfo &Info, APValue &Result) { 5850 SourceLocation CallLoc = E->getExprLoc(); 5851 if (!Info.CheckCallLimit(CallLoc)) 5852 return false; 5853 5854 const CXXRecordDecl *RD = Definition->getParent(); 5855 if (RD->getNumVBases()) { 5856 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5857 return false; 5858 } 5859 5860 EvalInfo::EvaluatingConstructorRAII EvalObj( 5861 Info, 5862 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5863 RD->getNumBases()); 5864 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5865 5866 // FIXME: Creating an APValue just to hold a nonexistent return value is 5867 // wasteful. 5868 APValue RetVal; 5869 StmtResult Ret = {RetVal, nullptr}; 5870 5871 // If it's a delegating constructor, delegate. 5872 if (Definition->isDelegatingConstructor()) { 5873 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5874 { 5875 FullExpressionRAII InitScope(Info); 5876 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 5877 !InitScope.destroy()) 5878 return false; 5879 } 5880 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5881 } 5882 5883 // For a trivial copy or move constructor, perform an APValue copy. This is 5884 // essential for unions (or classes with anonymous union members), where the 5885 // operations performed by the constructor cannot be represented by 5886 // ctor-initializers. 5887 // 5888 // Skip this for empty non-union classes; we should not perform an 5889 // lvalue-to-rvalue conversion on them because their copy constructor does not 5890 // actually read them. 5891 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5892 (Definition->getParent()->isUnion() || 5893 (Definition->isTrivial() && 5894 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 5895 LValue RHS; 5896 RHS.setFrom(Info.Ctx, ArgValues[0]); 5897 return handleLValueToRValueConversion( 5898 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5899 RHS, Result, Definition->getParent()->isUnion()); 5900 } 5901 5902 // Reserve space for the struct members. 5903 if (!Result.hasValue()) { 5904 if (!RD->isUnion()) 5905 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5906 std::distance(RD->field_begin(), RD->field_end())); 5907 else 5908 // A union starts with no active member. 5909 Result = APValue((const FieldDecl*)nullptr); 5910 } 5911 5912 if (RD->isInvalidDecl()) return false; 5913 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5914 5915 // A scope for temporaries lifetime-extended by reference members. 5916 BlockScopeRAII LifetimeExtendedScope(Info); 5917 5918 bool Success = true; 5919 unsigned BasesSeen = 0; 5920 #ifndef NDEBUG 5921 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5922 #endif 5923 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 5924 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 5925 // We might be initializing the same field again if this is an indirect 5926 // field initialization. 5927 if (FieldIt == RD->field_end() || 5928 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 5929 assert(Indirect && "fields out of order?"); 5930 return; 5931 } 5932 5933 // Default-initialize any fields with no explicit initializer. 5934 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 5935 assert(FieldIt != RD->field_end() && "missing field?"); 5936 if (!FieldIt->isUnnamedBitfield()) 5937 Success &= getDefaultInitValue( 5938 FieldIt->getType(), 5939 Result.getStructField(FieldIt->getFieldIndex())); 5940 } 5941 ++FieldIt; 5942 }; 5943 for (const auto *I : Definition->inits()) { 5944 LValue Subobject = This; 5945 LValue SubobjectParent = This; 5946 APValue *Value = &Result; 5947 5948 // Determine the subobject to initialize. 5949 FieldDecl *FD = nullptr; 5950 if (I->isBaseInitializer()) { 5951 QualType BaseType(I->getBaseClass(), 0); 5952 #ifndef NDEBUG 5953 // Non-virtual base classes are initialized in the order in the class 5954 // definition. We have already checked for virtual base classes. 5955 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5956 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5957 "base class initializers not in expected order"); 5958 ++BaseIt; 5959 #endif 5960 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5961 BaseType->getAsCXXRecordDecl(), &Layout)) 5962 return false; 5963 Value = &Result.getStructBase(BasesSeen++); 5964 } else if ((FD = I->getMember())) { 5965 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5966 return false; 5967 if (RD->isUnion()) { 5968 Result = APValue(FD); 5969 Value = &Result.getUnionValue(); 5970 } else { 5971 SkipToField(FD, false); 5972 Value = &Result.getStructField(FD->getFieldIndex()); 5973 } 5974 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5975 // Walk the indirect field decl's chain to find the object to initialize, 5976 // and make sure we've initialized every step along it. 5977 auto IndirectFieldChain = IFD->chain(); 5978 for (auto *C : IndirectFieldChain) { 5979 FD = cast<FieldDecl>(C); 5980 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5981 // Switch the union field if it differs. This happens if we had 5982 // preceding zero-initialization, and we're now initializing a union 5983 // subobject other than the first. 5984 // FIXME: In this case, the values of the other subobjects are 5985 // specified, since zero-initialization sets all padding bits to zero. 5986 if (!Value->hasValue() || 5987 (Value->isUnion() && Value->getUnionField() != FD)) { 5988 if (CD->isUnion()) 5989 *Value = APValue(FD); 5990 else 5991 // FIXME: This immediately starts the lifetime of all members of 5992 // an anonymous struct. It would be preferable to strictly start 5993 // member lifetime in initialization order. 5994 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 5995 } 5996 // Store Subobject as its parent before updating it for the last element 5997 // in the chain. 5998 if (C == IndirectFieldChain.back()) 5999 SubobjectParent = Subobject; 6000 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6001 return false; 6002 if (CD->isUnion()) 6003 Value = &Value->getUnionValue(); 6004 else { 6005 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6006 SkipToField(FD, true); 6007 Value = &Value->getStructField(FD->getFieldIndex()); 6008 } 6009 } 6010 } else { 6011 llvm_unreachable("unknown base initializer kind"); 6012 } 6013 6014 // Need to override This for implicit field initializers as in this case 6015 // This refers to innermost anonymous struct/union containing initializer, 6016 // not to currently constructed class. 6017 const Expr *Init = I->getInit(); 6018 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6019 isa<CXXDefaultInitExpr>(Init)); 6020 FullExpressionRAII InitScope(Info); 6021 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6022 (FD && FD->isBitField() && 6023 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6024 // If we're checking for a potential constant expression, evaluate all 6025 // initializers even if some of them fail. 6026 if (!Info.noteFailure()) 6027 return false; 6028 Success = false; 6029 } 6030 6031 // This is the point at which the dynamic type of the object becomes this 6032 // class type. 6033 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6034 EvalObj.finishedConstructingBases(); 6035 } 6036 6037 // Default-initialize any remaining fields. 6038 if (!RD->isUnion()) { 6039 for (; FieldIt != RD->field_end(); ++FieldIt) { 6040 if (!FieldIt->isUnnamedBitfield()) 6041 Success &= getDefaultInitValue( 6042 FieldIt->getType(), 6043 Result.getStructField(FieldIt->getFieldIndex())); 6044 } 6045 } 6046 6047 EvalObj.finishedConstructingFields(); 6048 6049 return Success && 6050 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6051 LifetimeExtendedScope.destroy(); 6052 } 6053 6054 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6055 ArrayRef<const Expr*> Args, 6056 const CXXConstructorDecl *Definition, 6057 EvalInfo &Info, APValue &Result) { 6058 ArgVector ArgValues(Args.size()); 6059 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 6060 return false; 6061 6062 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 6063 Info, Result); 6064 } 6065 6066 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6067 const LValue &This, APValue &Value, 6068 QualType T) { 6069 // Objects can only be destroyed while they're within their lifetimes. 6070 // FIXME: We have no representation for whether an object of type nullptr_t 6071 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6072 // as indeterminate instead? 6073 if (Value.isAbsent() && !T->isNullPtrType()) { 6074 APValue Printable; 6075 This.moveInto(Printable); 6076 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6077 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6078 return false; 6079 } 6080 6081 // Invent an expression for location purposes. 6082 // FIXME: We shouldn't need to do this. 6083 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6084 6085 // For arrays, destroy elements right-to-left. 6086 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6087 uint64_t Size = CAT->getSize().getZExtValue(); 6088 QualType ElemT = CAT->getElementType(); 6089 6090 LValue ElemLV = This; 6091 ElemLV.addArray(Info, &LocE, CAT); 6092 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6093 return false; 6094 6095 // Ensure that we have actual array elements available to destroy; the 6096 // destructors might mutate the value, so we can't run them on the array 6097 // filler. 6098 if (Size && Size > Value.getArrayInitializedElts()) 6099 expandArray(Value, Value.getArraySize() - 1); 6100 6101 for (; Size != 0; --Size) { 6102 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6103 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6104 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6105 return false; 6106 } 6107 6108 // End the lifetime of this array now. 6109 Value = APValue(); 6110 return true; 6111 } 6112 6113 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6114 if (!RD) { 6115 if (T.isDestructedType()) { 6116 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6117 return false; 6118 } 6119 6120 Value = APValue(); 6121 return true; 6122 } 6123 6124 if (RD->getNumVBases()) { 6125 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6126 return false; 6127 } 6128 6129 const CXXDestructorDecl *DD = RD->getDestructor(); 6130 if (!DD && !RD->hasTrivialDestructor()) { 6131 Info.FFDiag(CallLoc); 6132 return false; 6133 } 6134 6135 if (!DD || DD->isTrivial() || 6136 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6137 // A trivial destructor just ends the lifetime of the object. Check for 6138 // this case before checking for a body, because we might not bother 6139 // building a body for a trivial destructor. Note that it doesn't matter 6140 // whether the destructor is constexpr in this case; all trivial 6141 // destructors are constexpr. 6142 // 6143 // If an anonymous union would be destroyed, some enclosing destructor must 6144 // have been explicitly defined, and the anonymous union destruction should 6145 // have no effect. 6146 Value = APValue(); 6147 return true; 6148 } 6149 6150 if (!Info.CheckCallLimit(CallLoc)) 6151 return false; 6152 6153 const FunctionDecl *Definition = nullptr; 6154 const Stmt *Body = DD->getBody(Definition); 6155 6156 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6157 return false; 6158 6159 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); 6160 6161 // We're now in the period of destruction of this object. 6162 unsigned BasesLeft = RD->getNumBases(); 6163 EvalInfo::EvaluatingDestructorRAII EvalObj( 6164 Info, 6165 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6166 if (!EvalObj.DidInsert) { 6167 // C++2a [class.dtor]p19: 6168 // the behavior is undefined if the destructor is invoked for an object 6169 // whose lifetime has ended 6170 // (Note that formally the lifetime ends when the period of destruction 6171 // begins, even though certain uses of the object remain valid until the 6172 // period of destruction ends.) 6173 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6174 return false; 6175 } 6176 6177 // FIXME: Creating an APValue just to hold a nonexistent return value is 6178 // wasteful. 6179 APValue RetVal; 6180 StmtResult Ret = {RetVal, nullptr}; 6181 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6182 return false; 6183 6184 // A union destructor does not implicitly destroy its members. 6185 if (RD->isUnion()) 6186 return true; 6187 6188 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6189 6190 // We don't have a good way to iterate fields in reverse, so collect all the 6191 // fields first and then walk them backwards. 6192 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6193 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6194 if (FD->isUnnamedBitfield()) 6195 continue; 6196 6197 LValue Subobject = This; 6198 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6199 return false; 6200 6201 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6202 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6203 FD->getType())) 6204 return false; 6205 } 6206 6207 if (BasesLeft != 0) 6208 EvalObj.startedDestroyingBases(); 6209 6210 // Destroy base classes in reverse order. 6211 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6212 --BasesLeft; 6213 6214 QualType BaseType = Base.getType(); 6215 LValue Subobject = This; 6216 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6217 BaseType->getAsCXXRecordDecl(), &Layout)) 6218 return false; 6219 6220 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6221 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6222 BaseType)) 6223 return false; 6224 } 6225 assert(BasesLeft == 0 && "NumBases was wrong?"); 6226 6227 // The period of destruction ends now. The object is gone. 6228 Value = APValue(); 6229 return true; 6230 } 6231 6232 namespace { 6233 struct DestroyObjectHandler { 6234 EvalInfo &Info; 6235 const Expr *E; 6236 const LValue &This; 6237 const AccessKinds AccessKind; 6238 6239 typedef bool result_type; 6240 bool failed() { return false; } 6241 bool found(APValue &Subobj, QualType SubobjType) { 6242 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6243 SubobjType); 6244 } 6245 bool found(APSInt &Value, QualType SubobjType) { 6246 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6247 return false; 6248 } 6249 bool found(APFloat &Value, QualType SubobjType) { 6250 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6251 return false; 6252 } 6253 }; 6254 } 6255 6256 /// Perform a destructor or pseudo-destructor call on the given object, which 6257 /// might in general not be a complete object. 6258 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6259 const LValue &This, QualType ThisType) { 6260 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6261 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6262 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6263 } 6264 6265 /// Destroy and end the lifetime of the given complete object. 6266 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6267 APValue::LValueBase LVBase, APValue &Value, 6268 QualType T) { 6269 // If we've had an unmodeled side-effect, we can't rely on mutable state 6270 // (such as the object we're about to destroy) being correct. 6271 if (Info.EvalStatus.HasSideEffects) 6272 return false; 6273 6274 LValue LV; 6275 LV.set({LVBase}); 6276 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6277 } 6278 6279 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6280 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6281 LValue &Result) { 6282 if (Info.checkingPotentialConstantExpression() || 6283 Info.SpeculativeEvaluationDepth) 6284 return false; 6285 6286 // This is permitted only within a call to std::allocator<T>::allocate. 6287 auto Caller = Info.getStdAllocatorCaller("allocate"); 6288 if (!Caller) { 6289 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6290 ? diag::note_constexpr_new_untyped 6291 : diag::note_constexpr_new); 6292 return false; 6293 } 6294 6295 QualType ElemType = Caller.ElemType; 6296 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6297 Info.FFDiag(E->getExprLoc(), 6298 diag::note_constexpr_new_not_complete_object_type) 6299 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6300 return false; 6301 } 6302 6303 APSInt ByteSize; 6304 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6305 return false; 6306 bool IsNothrow = false; 6307 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6308 EvaluateIgnoredValue(Info, E->getArg(I)); 6309 IsNothrow |= E->getType()->isNothrowT(); 6310 } 6311 6312 CharUnits ElemSize; 6313 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6314 return false; 6315 APInt Size, Remainder; 6316 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6317 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6318 if (Remainder != 0) { 6319 // This likely indicates a bug in the implementation of 'std::allocator'. 6320 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6321 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6322 return false; 6323 } 6324 6325 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6326 if (IsNothrow) { 6327 Result.setNull(Info.Ctx, E->getType()); 6328 return true; 6329 } 6330 6331 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6332 return false; 6333 } 6334 6335 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6336 ArrayType::Normal, 0); 6337 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6338 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6339 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6340 return true; 6341 } 6342 6343 static bool hasVirtualDestructor(QualType T) { 6344 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6345 if (CXXDestructorDecl *DD = RD->getDestructor()) 6346 return DD->isVirtual(); 6347 return false; 6348 } 6349 6350 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6351 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6352 if (CXXDestructorDecl *DD = RD->getDestructor()) 6353 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6354 return nullptr; 6355 } 6356 6357 /// Check that the given object is a suitable pointer to a heap allocation that 6358 /// still exists and is of the right kind for the purpose of a deletion. 6359 /// 6360 /// On success, returns the heap allocation to deallocate. On failure, produces 6361 /// a diagnostic and returns None. 6362 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6363 const LValue &Pointer, 6364 DynAlloc::Kind DeallocKind) { 6365 auto PointerAsString = [&] { 6366 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6367 }; 6368 6369 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6370 if (!DA) { 6371 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6372 << PointerAsString(); 6373 if (Pointer.Base) 6374 NoteLValueLocation(Info, Pointer.Base); 6375 return None; 6376 } 6377 6378 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6379 if (!Alloc) { 6380 Info.FFDiag(E, diag::note_constexpr_double_delete); 6381 return None; 6382 } 6383 6384 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6385 if (DeallocKind != (*Alloc)->getKind()) { 6386 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6387 << DeallocKind << (*Alloc)->getKind() << AllocType; 6388 NoteLValueLocation(Info, Pointer.Base); 6389 return None; 6390 } 6391 6392 bool Subobject = false; 6393 if (DeallocKind == DynAlloc::New) { 6394 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6395 Pointer.Designator.isOnePastTheEnd(); 6396 } else { 6397 Subobject = Pointer.Designator.Entries.size() != 1 || 6398 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6399 } 6400 if (Subobject) { 6401 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6402 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6403 return None; 6404 } 6405 6406 return Alloc; 6407 } 6408 6409 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6410 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6411 if (Info.checkingPotentialConstantExpression() || 6412 Info.SpeculativeEvaluationDepth) 6413 return false; 6414 6415 // This is permitted only within a call to std::allocator<T>::deallocate. 6416 if (!Info.getStdAllocatorCaller("deallocate")) { 6417 Info.FFDiag(E->getExprLoc()); 6418 return true; 6419 } 6420 6421 LValue Pointer; 6422 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6423 return false; 6424 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6425 EvaluateIgnoredValue(Info, E->getArg(I)); 6426 6427 if (Pointer.Designator.Invalid) 6428 return false; 6429 6430 // Deleting a null pointer has no effect. 6431 if (Pointer.isNullPointer()) 6432 return true; 6433 6434 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6435 return false; 6436 6437 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6438 return true; 6439 } 6440 6441 //===----------------------------------------------------------------------===// 6442 // Generic Evaluation 6443 //===----------------------------------------------------------------------===// 6444 namespace { 6445 6446 class BitCastBuffer { 6447 // FIXME: We're going to need bit-level granularity when we support 6448 // bit-fields. 6449 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6450 // we don't support a host or target where that is the case. Still, we should 6451 // use a more generic type in case we ever do. 6452 SmallVector<Optional<unsigned char>, 32> Bytes; 6453 6454 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6455 "Need at least 8 bit unsigned char"); 6456 6457 bool TargetIsLittleEndian; 6458 6459 public: 6460 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6461 : Bytes(Width.getQuantity()), 6462 TargetIsLittleEndian(TargetIsLittleEndian) {} 6463 6464 LLVM_NODISCARD 6465 bool readObject(CharUnits Offset, CharUnits Width, 6466 SmallVectorImpl<unsigned char> &Output) const { 6467 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6468 // If a byte of an integer is uninitialized, then the whole integer is 6469 // uninitalized. 6470 if (!Bytes[I.getQuantity()]) 6471 return false; 6472 Output.push_back(*Bytes[I.getQuantity()]); 6473 } 6474 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6475 std::reverse(Output.begin(), Output.end()); 6476 return true; 6477 } 6478 6479 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6480 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6481 std::reverse(Input.begin(), Input.end()); 6482 6483 size_t Index = 0; 6484 for (unsigned char Byte : Input) { 6485 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6486 Bytes[Offset.getQuantity() + Index] = Byte; 6487 ++Index; 6488 } 6489 } 6490 6491 size_t size() { return Bytes.size(); } 6492 }; 6493 6494 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6495 /// target would represent the value at runtime. 6496 class APValueToBufferConverter { 6497 EvalInfo &Info; 6498 BitCastBuffer Buffer; 6499 const CastExpr *BCE; 6500 6501 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6502 const CastExpr *BCE) 6503 : Info(Info), 6504 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6505 BCE(BCE) {} 6506 6507 bool visit(const APValue &Val, QualType Ty) { 6508 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6509 } 6510 6511 // Write out Val with type Ty into Buffer starting at Offset. 6512 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6513 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6514 6515 // As a special case, nullptr_t has an indeterminate value. 6516 if (Ty->isNullPtrType()) 6517 return true; 6518 6519 // Dig through Src to find the byte at SrcOffset. 6520 switch (Val.getKind()) { 6521 case APValue::Indeterminate: 6522 case APValue::None: 6523 return true; 6524 6525 case APValue::Int: 6526 return visitInt(Val.getInt(), Ty, Offset); 6527 case APValue::Float: 6528 return visitFloat(Val.getFloat(), Ty, Offset); 6529 case APValue::Array: 6530 return visitArray(Val, Ty, Offset); 6531 case APValue::Struct: 6532 return visitRecord(Val, Ty, Offset); 6533 6534 case APValue::ComplexInt: 6535 case APValue::ComplexFloat: 6536 case APValue::Vector: 6537 case APValue::FixedPoint: 6538 // FIXME: We should support these. 6539 6540 case APValue::Union: 6541 case APValue::MemberPointer: 6542 case APValue::AddrLabelDiff: { 6543 Info.FFDiag(BCE->getBeginLoc(), 6544 diag::note_constexpr_bit_cast_unsupported_type) 6545 << Ty; 6546 return false; 6547 } 6548 6549 case APValue::LValue: 6550 llvm_unreachable("LValue subobject in bit_cast?"); 6551 } 6552 llvm_unreachable("Unhandled APValue::ValueKind"); 6553 } 6554 6555 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6556 const RecordDecl *RD = Ty->getAsRecordDecl(); 6557 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6558 6559 // Visit the base classes. 6560 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6561 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6562 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6563 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6564 6565 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6566 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6567 return false; 6568 } 6569 } 6570 6571 // Visit the fields. 6572 unsigned FieldIdx = 0; 6573 for (FieldDecl *FD : RD->fields()) { 6574 if (FD->isBitField()) { 6575 Info.FFDiag(BCE->getBeginLoc(), 6576 diag::note_constexpr_bit_cast_unsupported_bitfield); 6577 return false; 6578 } 6579 6580 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6581 6582 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6583 "only bit-fields can have sub-char alignment"); 6584 CharUnits FieldOffset = 6585 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6586 QualType FieldTy = FD->getType(); 6587 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6588 return false; 6589 ++FieldIdx; 6590 } 6591 6592 return true; 6593 } 6594 6595 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6596 const auto *CAT = 6597 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6598 if (!CAT) 6599 return false; 6600 6601 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6602 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6603 unsigned ArraySize = Val.getArraySize(); 6604 // First, initialize the initialized elements. 6605 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6606 const APValue &SubObj = Val.getArrayInitializedElt(I); 6607 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6608 return false; 6609 } 6610 6611 // Next, initialize the rest of the array using the filler. 6612 if (Val.hasArrayFiller()) { 6613 const APValue &Filler = Val.getArrayFiller(); 6614 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6615 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6616 return false; 6617 } 6618 } 6619 6620 return true; 6621 } 6622 6623 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6624 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); 6625 SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); 6626 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); 6627 Buffer.writeObject(Offset, Bytes); 6628 return true; 6629 } 6630 6631 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6632 APSInt AsInt(Val.bitcastToAPInt()); 6633 return visitInt(AsInt, Ty, Offset); 6634 } 6635 6636 public: 6637 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6638 const CastExpr *BCE) { 6639 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6640 APValueToBufferConverter Converter(Info, DstSize, BCE); 6641 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6642 return None; 6643 return Converter.Buffer; 6644 } 6645 }; 6646 6647 /// Write an BitCastBuffer into an APValue. 6648 class BufferToAPValueConverter { 6649 EvalInfo &Info; 6650 const BitCastBuffer &Buffer; 6651 const CastExpr *BCE; 6652 6653 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6654 const CastExpr *BCE) 6655 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6656 6657 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6658 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6659 // Ideally this will be unreachable. 6660 llvm::NoneType unsupportedType(QualType Ty) { 6661 Info.FFDiag(BCE->getBeginLoc(), 6662 diag::note_constexpr_bit_cast_unsupported_type) 6663 << Ty; 6664 return None; 6665 } 6666 6667 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6668 const EnumType *EnumSugar = nullptr) { 6669 if (T->isNullPtrType()) { 6670 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6671 return APValue((Expr *)nullptr, 6672 /*Offset=*/CharUnits::fromQuantity(NullValue), 6673 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6674 } 6675 6676 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6677 SmallVector<uint8_t, 8> Bytes; 6678 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6679 // If this is std::byte or unsigned char, then its okay to store an 6680 // indeterminate value. 6681 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6682 bool IsUChar = 6683 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6684 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6685 if (!IsStdByte && !IsUChar) { 6686 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6687 Info.FFDiag(BCE->getExprLoc(), 6688 diag::note_constexpr_bit_cast_indet_dest) 6689 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6690 return None; 6691 } 6692 6693 return APValue::IndeterminateValue(); 6694 } 6695 6696 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6697 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6698 6699 if (T->isIntegralOrEnumerationType()) { 6700 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6701 return APValue(Val); 6702 } 6703 6704 if (T->isRealFloatingType()) { 6705 const llvm::fltSemantics &Semantics = 6706 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6707 return APValue(APFloat(Semantics, Val)); 6708 } 6709 6710 return unsupportedType(QualType(T, 0)); 6711 } 6712 6713 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6714 const RecordDecl *RD = RTy->getAsRecordDecl(); 6715 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6716 6717 unsigned NumBases = 0; 6718 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6719 NumBases = CXXRD->getNumBases(); 6720 6721 APValue ResultVal(APValue::UninitStruct(), NumBases, 6722 std::distance(RD->field_begin(), RD->field_end())); 6723 6724 // Visit the base classes. 6725 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6726 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6727 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6728 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6729 if (BaseDecl->isEmpty() || 6730 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6731 continue; 6732 6733 Optional<APValue> SubObj = visitType( 6734 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6735 if (!SubObj) 6736 return None; 6737 ResultVal.getStructBase(I) = *SubObj; 6738 } 6739 } 6740 6741 // Visit the fields. 6742 unsigned FieldIdx = 0; 6743 for (FieldDecl *FD : RD->fields()) { 6744 // FIXME: We don't currently support bit-fields. A lot of the logic for 6745 // this is in CodeGen, so we need to factor it around. 6746 if (FD->isBitField()) { 6747 Info.FFDiag(BCE->getBeginLoc(), 6748 diag::note_constexpr_bit_cast_unsupported_bitfield); 6749 return None; 6750 } 6751 6752 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6753 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6754 6755 CharUnits FieldOffset = 6756 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6757 Offset; 6758 QualType FieldTy = FD->getType(); 6759 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6760 if (!SubObj) 6761 return None; 6762 ResultVal.getStructField(FieldIdx) = *SubObj; 6763 ++FieldIdx; 6764 } 6765 6766 return ResultVal; 6767 } 6768 6769 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6770 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6771 assert(!RepresentationType.isNull() && 6772 "enum forward decl should be caught by Sema"); 6773 const auto *AsBuiltin = 6774 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 6775 // Recurse into the underlying type. Treat std::byte transparently as 6776 // unsigned char. 6777 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6778 } 6779 6780 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6781 size_t Size = Ty->getSize().getLimitedValue(); 6782 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6783 6784 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6785 for (size_t I = 0; I != Size; ++I) { 6786 Optional<APValue> ElementValue = 6787 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6788 if (!ElementValue) 6789 return None; 6790 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6791 } 6792 6793 return ArrayValue; 6794 } 6795 6796 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6797 return unsupportedType(QualType(Ty, 0)); 6798 } 6799 6800 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6801 QualType Can = Ty.getCanonicalType(); 6802 6803 switch (Can->getTypeClass()) { 6804 #define TYPE(Class, Base) \ 6805 case Type::Class: \ 6806 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6807 #define ABSTRACT_TYPE(Class, Base) 6808 #define NON_CANONICAL_TYPE(Class, Base) \ 6809 case Type::Class: \ 6810 llvm_unreachable("non-canonical type should be impossible!"); 6811 #define DEPENDENT_TYPE(Class, Base) \ 6812 case Type::Class: \ 6813 llvm_unreachable( \ 6814 "dependent types aren't supported in the constant evaluator!"); 6815 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6816 case Type::Class: \ 6817 llvm_unreachable("either dependent or not canonical!"); 6818 #include "clang/AST/TypeNodes.inc" 6819 } 6820 llvm_unreachable("Unhandled Type::TypeClass"); 6821 } 6822 6823 public: 6824 // Pull out a full value of type DstType. 6825 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6826 const CastExpr *BCE) { 6827 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6828 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6829 } 6830 }; 6831 6832 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6833 QualType Ty, EvalInfo *Info, 6834 const ASTContext &Ctx, 6835 bool CheckingDest) { 6836 Ty = Ty.getCanonicalType(); 6837 6838 auto diag = [&](int Reason) { 6839 if (Info) 6840 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6841 << CheckingDest << (Reason == 4) << Reason; 6842 return false; 6843 }; 6844 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6845 if (Info) 6846 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6847 << NoteTy << Construct << Ty; 6848 return false; 6849 }; 6850 6851 if (Ty->isUnionType()) 6852 return diag(0); 6853 if (Ty->isPointerType()) 6854 return diag(1); 6855 if (Ty->isMemberPointerType()) 6856 return diag(2); 6857 if (Ty.isVolatileQualified()) 6858 return diag(3); 6859 6860 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6861 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6862 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6863 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6864 CheckingDest)) 6865 return note(1, BS.getType(), BS.getBeginLoc()); 6866 } 6867 for (FieldDecl *FD : Record->fields()) { 6868 if (FD->getType()->isReferenceType()) 6869 return diag(4); 6870 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6871 CheckingDest)) 6872 return note(0, FD->getType(), FD->getBeginLoc()); 6873 } 6874 } 6875 6876 if (Ty->isArrayType() && 6877 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6878 Info, Ctx, CheckingDest)) 6879 return false; 6880 6881 return true; 6882 } 6883 6884 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6885 const ASTContext &Ctx, 6886 const CastExpr *BCE) { 6887 bool DestOK = checkBitCastConstexprEligibilityType( 6888 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6889 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6890 BCE->getBeginLoc(), 6891 BCE->getSubExpr()->getType(), Info, Ctx, false); 6892 return SourceOK; 6893 } 6894 6895 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6896 APValue &SourceValue, 6897 const CastExpr *BCE) { 6898 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6899 "no host or target supports non 8-bit chars"); 6900 assert(SourceValue.isLValue() && 6901 "LValueToRValueBitcast requires an lvalue operand!"); 6902 6903 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6904 return false; 6905 6906 LValue SourceLValue; 6907 APValue SourceRValue; 6908 SourceLValue.setFrom(Info.Ctx, SourceValue); 6909 if (!handleLValueToRValueConversion( 6910 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 6911 SourceRValue, /*WantObjectRepresentation=*/true)) 6912 return false; 6913 6914 // Read out SourceValue into a char buffer. 6915 Optional<BitCastBuffer> Buffer = 6916 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 6917 if (!Buffer) 6918 return false; 6919 6920 // Write out the buffer into a new APValue. 6921 Optional<APValue> MaybeDestValue = 6922 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 6923 if (!MaybeDestValue) 6924 return false; 6925 6926 DestValue = std::move(*MaybeDestValue); 6927 return true; 6928 } 6929 6930 template <class Derived> 6931 class ExprEvaluatorBase 6932 : public ConstStmtVisitor<Derived, bool> { 6933 private: 6934 Derived &getDerived() { return static_cast<Derived&>(*this); } 6935 bool DerivedSuccess(const APValue &V, const Expr *E) { 6936 return getDerived().Success(V, E); 6937 } 6938 bool DerivedZeroInitialization(const Expr *E) { 6939 return getDerived().ZeroInitialization(E); 6940 } 6941 6942 // Check whether a conditional operator with a non-constant condition is a 6943 // potential constant expression. If neither arm is a potential constant 6944 // expression, then the conditional operator is not either. 6945 template<typename ConditionalOperator> 6946 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 6947 assert(Info.checkingPotentialConstantExpression()); 6948 6949 // Speculatively evaluate both arms. 6950 SmallVector<PartialDiagnosticAt, 8> Diag; 6951 { 6952 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6953 StmtVisitorTy::Visit(E->getFalseExpr()); 6954 if (Diag.empty()) 6955 return; 6956 } 6957 6958 { 6959 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6960 Diag.clear(); 6961 StmtVisitorTy::Visit(E->getTrueExpr()); 6962 if (Diag.empty()) 6963 return; 6964 } 6965 6966 Error(E, diag::note_constexpr_conditional_never_const); 6967 } 6968 6969 6970 template<typename ConditionalOperator> 6971 bool HandleConditionalOperator(const ConditionalOperator *E) { 6972 bool BoolResult; 6973 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 6974 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 6975 CheckPotentialConstantConditional(E); 6976 return false; 6977 } 6978 if (Info.noteFailure()) { 6979 StmtVisitorTy::Visit(E->getTrueExpr()); 6980 StmtVisitorTy::Visit(E->getFalseExpr()); 6981 } 6982 return false; 6983 } 6984 6985 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 6986 return StmtVisitorTy::Visit(EvalExpr); 6987 } 6988 6989 protected: 6990 EvalInfo &Info; 6991 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 6992 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 6993 6994 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 6995 return Info.CCEDiag(E, D); 6996 } 6997 6998 bool ZeroInitialization(const Expr *E) { return Error(E); } 6999 7000 public: 7001 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7002 7003 EvalInfo &getEvalInfo() { return Info; } 7004 7005 /// Report an evaluation error. This should only be called when an error is 7006 /// first discovered. When propagating an error, just return false. 7007 bool Error(const Expr *E, diag::kind D) { 7008 Info.FFDiag(E, D); 7009 return false; 7010 } 7011 bool Error(const Expr *E) { 7012 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7013 } 7014 7015 bool VisitStmt(const Stmt *) { 7016 llvm_unreachable("Expression evaluator should not be called on stmts"); 7017 } 7018 bool VisitExpr(const Expr *E) { 7019 return Error(E); 7020 } 7021 7022 bool VisitConstantExpr(const ConstantExpr *E) { 7023 if (E->hasAPValueResult()) 7024 return DerivedSuccess(E->getAPValueResult(), E); 7025 7026 return StmtVisitorTy::Visit(E->getSubExpr()); 7027 } 7028 7029 bool VisitParenExpr(const ParenExpr *E) 7030 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7031 bool VisitUnaryExtension(const UnaryOperator *E) 7032 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7033 bool VisitUnaryPlus(const UnaryOperator *E) 7034 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7035 bool VisitChooseExpr(const ChooseExpr *E) 7036 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7037 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7038 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7039 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7040 { return StmtVisitorTy::Visit(E->getReplacement()); } 7041 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7042 TempVersionRAII RAII(*Info.CurrentCall); 7043 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7044 return StmtVisitorTy::Visit(E->getExpr()); 7045 } 7046 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7047 TempVersionRAII RAII(*Info.CurrentCall); 7048 // The initializer may not have been parsed yet, or might be erroneous. 7049 if (!E->getExpr()) 7050 return Error(E); 7051 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7052 return StmtVisitorTy::Visit(E->getExpr()); 7053 } 7054 7055 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7056 FullExpressionRAII Scope(Info); 7057 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7058 } 7059 7060 // Temporaries are registered when created, so we don't care about 7061 // CXXBindTemporaryExpr. 7062 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7063 return StmtVisitorTy::Visit(E->getSubExpr()); 7064 } 7065 7066 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7067 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7068 return static_cast<Derived*>(this)->VisitCastExpr(E); 7069 } 7070 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7071 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7072 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7073 return static_cast<Derived*>(this)->VisitCastExpr(E); 7074 } 7075 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7076 return static_cast<Derived*>(this)->VisitCastExpr(E); 7077 } 7078 7079 bool VisitBinaryOperator(const BinaryOperator *E) { 7080 switch (E->getOpcode()) { 7081 default: 7082 return Error(E); 7083 7084 case BO_Comma: 7085 VisitIgnoredValue(E->getLHS()); 7086 return StmtVisitorTy::Visit(E->getRHS()); 7087 7088 case BO_PtrMemD: 7089 case BO_PtrMemI: { 7090 LValue Obj; 7091 if (!HandleMemberPointerAccess(Info, E, Obj)) 7092 return false; 7093 APValue Result; 7094 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7095 return false; 7096 return DerivedSuccess(Result, E); 7097 } 7098 } 7099 } 7100 7101 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7102 return StmtVisitorTy::Visit(E->getSemanticForm()); 7103 } 7104 7105 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7106 // Evaluate and cache the common expression. We treat it as a temporary, 7107 // even though it's not quite the same thing. 7108 LValue CommonLV; 7109 if (!Evaluate(Info.CurrentCall->createTemporary( 7110 E->getOpaqueValue(), 7111 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 7112 CommonLV), 7113 Info, E->getCommon())) 7114 return false; 7115 7116 return HandleConditionalOperator(E); 7117 } 7118 7119 bool VisitConditionalOperator(const ConditionalOperator *E) { 7120 bool IsBcpCall = false; 7121 // If the condition (ignoring parens) is a __builtin_constant_p call, 7122 // the result is a constant expression if it can be folded without 7123 // side-effects. This is an important GNU extension. See GCC PR38377 7124 // for discussion. 7125 if (const CallExpr *CallCE = 7126 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7127 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7128 IsBcpCall = true; 7129 7130 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7131 // constant expression; we can't check whether it's potentially foldable. 7132 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7133 // it would return 'false' in this mode. 7134 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7135 return false; 7136 7137 FoldConstant Fold(Info, IsBcpCall); 7138 if (!HandleConditionalOperator(E)) { 7139 Fold.keepDiagnostics(); 7140 return false; 7141 } 7142 7143 return true; 7144 } 7145 7146 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7147 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7148 return DerivedSuccess(*Value, E); 7149 7150 const Expr *Source = E->getSourceExpr(); 7151 if (!Source) 7152 return Error(E); 7153 if (Source == E) { // sanity checking. 7154 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7155 return Error(E); 7156 } 7157 return StmtVisitorTy::Visit(Source); 7158 } 7159 7160 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7161 for (const Expr *SemE : E->semantics()) { 7162 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7163 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7164 // result expression: there could be two different LValues that would 7165 // refer to the same object in that case, and we can't model that. 7166 if (SemE == E->getResultExpr()) 7167 return Error(E); 7168 7169 // Unique OVEs get evaluated if and when we encounter them when 7170 // emitting the rest of the semantic form, rather than eagerly. 7171 if (OVE->isUnique()) 7172 continue; 7173 7174 LValue LV; 7175 if (!Evaluate(Info.CurrentCall->createTemporary( 7176 OVE, getStorageType(Info.Ctx, OVE), false, LV), 7177 Info, OVE->getSourceExpr())) 7178 return false; 7179 } else if (SemE == E->getResultExpr()) { 7180 if (!StmtVisitorTy::Visit(SemE)) 7181 return false; 7182 } else { 7183 if (!EvaluateIgnoredValue(Info, SemE)) 7184 return false; 7185 } 7186 } 7187 return true; 7188 } 7189 7190 bool VisitCallExpr(const CallExpr *E) { 7191 APValue Result; 7192 if (!handleCallExpr(E, Result, nullptr)) 7193 return false; 7194 return DerivedSuccess(Result, E); 7195 } 7196 7197 bool handleCallExpr(const CallExpr *E, APValue &Result, 7198 const LValue *ResultSlot) { 7199 const Expr *Callee = E->getCallee()->IgnoreParens(); 7200 QualType CalleeType = Callee->getType(); 7201 7202 const FunctionDecl *FD = nullptr; 7203 LValue *This = nullptr, ThisVal; 7204 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7205 bool HasQualifier = false; 7206 7207 // Extract function decl and 'this' pointer from the callee. 7208 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7209 const CXXMethodDecl *Member = nullptr; 7210 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7211 // Explicit bound member calls, such as x.f() or p->g(); 7212 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7213 return false; 7214 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7215 if (!Member) 7216 return Error(Callee); 7217 This = &ThisVal; 7218 HasQualifier = ME->hasQualifier(); 7219 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7220 // Indirect bound member calls ('.*' or '->*'). 7221 const ValueDecl *D = 7222 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7223 if (!D) 7224 return false; 7225 Member = dyn_cast<CXXMethodDecl>(D); 7226 if (!Member) 7227 return Error(Callee); 7228 This = &ThisVal; 7229 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7230 if (!Info.getLangOpts().CPlusPlus20) 7231 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7232 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7233 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7234 } else 7235 return Error(Callee); 7236 FD = Member; 7237 } else if (CalleeType->isFunctionPointerType()) { 7238 LValue Call; 7239 if (!EvaluatePointer(Callee, Call, Info)) 7240 return false; 7241 7242 if (!Call.getLValueOffset().isZero()) 7243 return Error(Callee); 7244 FD = dyn_cast_or_null<FunctionDecl>( 7245 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 7246 if (!FD) 7247 return Error(Callee); 7248 // Don't call function pointers which have been cast to some other type. 7249 // Per DR (no number yet), the caller and callee can differ in noexcept. 7250 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7251 CalleeType->getPointeeType(), FD->getType())) { 7252 return Error(E); 7253 } 7254 7255 // Overloaded operator calls to member functions are represented as normal 7256 // calls with '*this' as the first argument. 7257 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7258 if (MD && !MD->isStatic()) { 7259 // FIXME: When selecting an implicit conversion for an overloaded 7260 // operator delete, we sometimes try to evaluate calls to conversion 7261 // operators without a 'this' parameter! 7262 if (Args.empty()) 7263 return Error(E); 7264 7265 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7266 return false; 7267 This = &ThisVal; 7268 Args = Args.slice(1); 7269 } else if (MD && MD->isLambdaStaticInvoker()) { 7270 // Map the static invoker for the lambda back to the call operator. 7271 // Conveniently, we don't have to slice out the 'this' argument (as is 7272 // being done for the non-static case), since a static member function 7273 // doesn't have an implicit argument passed in. 7274 const CXXRecordDecl *ClosureClass = MD->getParent(); 7275 assert( 7276 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7277 "Number of captures must be zero for conversion to function-ptr"); 7278 7279 const CXXMethodDecl *LambdaCallOp = 7280 ClosureClass->getLambdaCallOperator(); 7281 7282 // Set 'FD', the function that will be called below, to the call 7283 // operator. If the closure object represents a generic lambda, find 7284 // the corresponding specialization of the call operator. 7285 7286 if (ClosureClass->isGenericLambda()) { 7287 assert(MD->isFunctionTemplateSpecialization() && 7288 "A generic lambda's static-invoker function must be a " 7289 "template specialization"); 7290 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7291 FunctionTemplateDecl *CallOpTemplate = 7292 LambdaCallOp->getDescribedFunctionTemplate(); 7293 void *InsertPos = nullptr; 7294 FunctionDecl *CorrespondingCallOpSpecialization = 7295 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7296 assert(CorrespondingCallOpSpecialization && 7297 "We must always have a function call operator specialization " 7298 "that corresponds to our static invoker specialization"); 7299 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7300 } else 7301 FD = LambdaCallOp; 7302 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7303 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7304 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7305 LValue Ptr; 7306 if (!HandleOperatorNewCall(Info, E, Ptr)) 7307 return false; 7308 Ptr.moveInto(Result); 7309 return true; 7310 } else { 7311 return HandleOperatorDeleteCall(Info, E); 7312 } 7313 } 7314 } else 7315 return Error(E); 7316 7317 SmallVector<QualType, 4> CovariantAdjustmentPath; 7318 if (This) { 7319 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7320 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7321 // Perform virtual dispatch, if necessary. 7322 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7323 CovariantAdjustmentPath); 7324 if (!FD) 7325 return false; 7326 } else { 7327 // Check that the 'this' pointer points to an object of the right type. 7328 // FIXME: If this is an assignment operator call, we may need to change 7329 // the active union member before we check this. 7330 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7331 return false; 7332 } 7333 } 7334 7335 // Destructor calls are different enough that they have their own codepath. 7336 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7337 assert(This && "no 'this' pointer for destructor call"); 7338 return HandleDestruction(Info, E, *This, 7339 Info.Ctx.getRecordType(DD->getParent())); 7340 } 7341 7342 const FunctionDecl *Definition = nullptr; 7343 Stmt *Body = FD->getBody(Definition); 7344 7345 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7346 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 7347 Result, ResultSlot)) 7348 return false; 7349 7350 if (!CovariantAdjustmentPath.empty() && 7351 !HandleCovariantReturnAdjustment(Info, E, Result, 7352 CovariantAdjustmentPath)) 7353 return false; 7354 7355 return true; 7356 } 7357 7358 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7359 return StmtVisitorTy::Visit(E->getInitializer()); 7360 } 7361 bool VisitInitListExpr(const InitListExpr *E) { 7362 if (E->getNumInits() == 0) 7363 return DerivedZeroInitialization(E); 7364 if (E->getNumInits() == 1) 7365 return StmtVisitorTy::Visit(E->getInit(0)); 7366 return Error(E); 7367 } 7368 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7369 return DerivedZeroInitialization(E); 7370 } 7371 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7372 return DerivedZeroInitialization(E); 7373 } 7374 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7375 return DerivedZeroInitialization(E); 7376 } 7377 7378 /// A member expression where the object is a prvalue is itself a prvalue. 7379 bool VisitMemberExpr(const MemberExpr *E) { 7380 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7381 "missing temporary materialization conversion"); 7382 assert(!E->isArrow() && "missing call to bound member function?"); 7383 7384 APValue Val; 7385 if (!Evaluate(Val, Info, E->getBase())) 7386 return false; 7387 7388 QualType BaseTy = E->getBase()->getType(); 7389 7390 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7391 if (!FD) return Error(E); 7392 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7393 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7394 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7395 7396 // Note: there is no lvalue base here. But this case should only ever 7397 // happen in C or in C++98, where we cannot be evaluating a constexpr 7398 // constructor, which is the only case the base matters. 7399 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7400 SubobjectDesignator Designator(BaseTy); 7401 Designator.addDeclUnchecked(FD); 7402 7403 APValue Result; 7404 return extractSubobject(Info, E, Obj, Designator, Result) && 7405 DerivedSuccess(Result, E); 7406 } 7407 7408 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7409 APValue Val; 7410 if (!Evaluate(Val, Info, E->getBase())) 7411 return false; 7412 7413 if (Val.isVector()) { 7414 SmallVector<uint32_t, 4> Indices; 7415 E->getEncodedElementAccess(Indices); 7416 if (Indices.size() == 1) { 7417 // Return scalar. 7418 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7419 } else { 7420 // Construct new APValue vector. 7421 SmallVector<APValue, 4> Elts; 7422 for (unsigned I = 0; I < Indices.size(); ++I) { 7423 Elts.push_back(Val.getVectorElt(Indices[I])); 7424 } 7425 APValue VecResult(Elts.data(), Indices.size()); 7426 return DerivedSuccess(VecResult, E); 7427 } 7428 } 7429 7430 return false; 7431 } 7432 7433 bool VisitCastExpr(const CastExpr *E) { 7434 switch (E->getCastKind()) { 7435 default: 7436 break; 7437 7438 case CK_AtomicToNonAtomic: { 7439 APValue AtomicVal; 7440 // This does not need to be done in place even for class/array types: 7441 // atomic-to-non-atomic conversion implies copying the object 7442 // representation. 7443 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7444 return false; 7445 return DerivedSuccess(AtomicVal, E); 7446 } 7447 7448 case CK_NoOp: 7449 case CK_UserDefinedConversion: 7450 return StmtVisitorTy::Visit(E->getSubExpr()); 7451 7452 case CK_LValueToRValue: { 7453 LValue LVal; 7454 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7455 return false; 7456 APValue RVal; 7457 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7458 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7459 LVal, RVal)) 7460 return false; 7461 return DerivedSuccess(RVal, E); 7462 } 7463 case CK_LValueToRValueBitCast: { 7464 APValue DestValue, SourceValue; 7465 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7466 return false; 7467 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7468 return false; 7469 return DerivedSuccess(DestValue, E); 7470 } 7471 7472 case CK_AddressSpaceConversion: { 7473 APValue Value; 7474 if (!Evaluate(Value, Info, E->getSubExpr())) 7475 return false; 7476 return DerivedSuccess(Value, E); 7477 } 7478 } 7479 7480 return Error(E); 7481 } 7482 7483 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7484 return VisitUnaryPostIncDec(UO); 7485 } 7486 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7487 return VisitUnaryPostIncDec(UO); 7488 } 7489 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7490 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7491 return Error(UO); 7492 7493 LValue LVal; 7494 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7495 return false; 7496 APValue RVal; 7497 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7498 UO->isIncrementOp(), &RVal)) 7499 return false; 7500 return DerivedSuccess(RVal, UO); 7501 } 7502 7503 bool VisitStmtExpr(const StmtExpr *E) { 7504 // We will have checked the full-expressions inside the statement expression 7505 // when they were completed, and don't need to check them again now. 7506 if (Info.checkingForUndefinedBehavior()) 7507 return Error(E); 7508 7509 const CompoundStmt *CS = E->getSubStmt(); 7510 if (CS->body_empty()) 7511 return true; 7512 7513 BlockScopeRAII Scope(Info); 7514 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7515 BE = CS->body_end(); 7516 /**/; ++BI) { 7517 if (BI + 1 == BE) { 7518 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7519 if (!FinalExpr) { 7520 Info.FFDiag((*BI)->getBeginLoc(), 7521 diag::note_constexpr_stmt_expr_unsupported); 7522 return false; 7523 } 7524 return this->Visit(FinalExpr) && Scope.destroy(); 7525 } 7526 7527 APValue ReturnValue; 7528 StmtResult Result = { ReturnValue, nullptr }; 7529 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7530 if (ESR != ESR_Succeeded) { 7531 // FIXME: If the statement-expression terminated due to 'return', 7532 // 'break', or 'continue', it would be nice to propagate that to 7533 // the outer statement evaluation rather than bailing out. 7534 if (ESR != ESR_Failed) 7535 Info.FFDiag((*BI)->getBeginLoc(), 7536 diag::note_constexpr_stmt_expr_unsupported); 7537 return false; 7538 } 7539 } 7540 7541 llvm_unreachable("Return from function from the loop above."); 7542 } 7543 7544 /// Visit a value which is evaluated, but whose value is ignored. 7545 void VisitIgnoredValue(const Expr *E) { 7546 EvaluateIgnoredValue(Info, E); 7547 } 7548 7549 /// Potentially visit a MemberExpr's base expression. 7550 void VisitIgnoredBaseExpression(const Expr *E) { 7551 // While MSVC doesn't evaluate the base expression, it does diagnose the 7552 // presence of side-effecting behavior. 7553 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7554 return; 7555 VisitIgnoredValue(E); 7556 } 7557 }; 7558 7559 } // namespace 7560 7561 //===----------------------------------------------------------------------===// 7562 // Common base class for lvalue and temporary evaluation. 7563 //===----------------------------------------------------------------------===// 7564 namespace { 7565 template<class Derived> 7566 class LValueExprEvaluatorBase 7567 : public ExprEvaluatorBase<Derived> { 7568 protected: 7569 LValue &Result; 7570 bool InvalidBaseOK; 7571 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7572 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7573 7574 bool Success(APValue::LValueBase B) { 7575 Result.set(B); 7576 return true; 7577 } 7578 7579 bool evaluatePointer(const Expr *E, LValue &Result) { 7580 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7581 } 7582 7583 public: 7584 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7585 : ExprEvaluatorBaseTy(Info), Result(Result), 7586 InvalidBaseOK(InvalidBaseOK) {} 7587 7588 bool Success(const APValue &V, const Expr *E) { 7589 Result.setFrom(this->Info.Ctx, V); 7590 return true; 7591 } 7592 7593 bool VisitMemberExpr(const MemberExpr *E) { 7594 // Handle non-static data members. 7595 QualType BaseTy; 7596 bool EvalOK; 7597 if (E->isArrow()) { 7598 EvalOK = evaluatePointer(E->getBase(), Result); 7599 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7600 } else if (E->getBase()->isRValue()) { 7601 assert(E->getBase()->getType()->isRecordType()); 7602 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7603 BaseTy = E->getBase()->getType(); 7604 } else { 7605 EvalOK = this->Visit(E->getBase()); 7606 BaseTy = E->getBase()->getType(); 7607 } 7608 if (!EvalOK) { 7609 if (!InvalidBaseOK) 7610 return false; 7611 Result.setInvalid(E); 7612 return true; 7613 } 7614 7615 const ValueDecl *MD = E->getMemberDecl(); 7616 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7617 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7618 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7619 (void)BaseTy; 7620 if (!HandleLValueMember(this->Info, E, Result, FD)) 7621 return false; 7622 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7623 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7624 return false; 7625 } else 7626 return this->Error(E); 7627 7628 if (MD->getType()->isReferenceType()) { 7629 APValue RefValue; 7630 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7631 RefValue)) 7632 return false; 7633 return Success(RefValue, E); 7634 } 7635 return true; 7636 } 7637 7638 bool VisitBinaryOperator(const BinaryOperator *E) { 7639 switch (E->getOpcode()) { 7640 default: 7641 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7642 7643 case BO_PtrMemD: 7644 case BO_PtrMemI: 7645 return HandleMemberPointerAccess(this->Info, E, Result); 7646 } 7647 } 7648 7649 bool VisitCastExpr(const CastExpr *E) { 7650 switch (E->getCastKind()) { 7651 default: 7652 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7653 7654 case CK_DerivedToBase: 7655 case CK_UncheckedDerivedToBase: 7656 if (!this->Visit(E->getSubExpr())) 7657 return false; 7658 7659 // Now figure out the necessary offset to add to the base LV to get from 7660 // the derived class to the base class. 7661 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7662 Result); 7663 } 7664 } 7665 }; 7666 } 7667 7668 //===----------------------------------------------------------------------===// 7669 // LValue Evaluation 7670 // 7671 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7672 // function designators (in C), decl references to void objects (in C), and 7673 // temporaries (if building with -Wno-address-of-temporary). 7674 // 7675 // LValue evaluation produces values comprising a base expression of one of the 7676 // following types: 7677 // - Declarations 7678 // * VarDecl 7679 // * FunctionDecl 7680 // - Literals 7681 // * CompoundLiteralExpr in C (and in global scope in C++) 7682 // * StringLiteral 7683 // * PredefinedExpr 7684 // * ObjCStringLiteralExpr 7685 // * ObjCEncodeExpr 7686 // * AddrLabelExpr 7687 // * BlockExpr 7688 // * CallExpr for a MakeStringConstant builtin 7689 // - typeid(T) expressions, as TypeInfoLValues 7690 // - Locals and temporaries 7691 // * MaterializeTemporaryExpr 7692 // * Any Expr, with a CallIndex indicating the function in which the temporary 7693 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7694 // from the AST (FIXME). 7695 // * A MaterializeTemporaryExpr that has static storage duration, with no 7696 // CallIndex, for a lifetime-extended temporary. 7697 // * The ConstantExpr that is currently being evaluated during evaluation of an 7698 // immediate invocation. 7699 // plus an offset in bytes. 7700 //===----------------------------------------------------------------------===// 7701 namespace { 7702 class LValueExprEvaluator 7703 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7704 public: 7705 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7706 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7707 7708 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7709 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7710 7711 bool VisitDeclRefExpr(const DeclRefExpr *E); 7712 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7713 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7714 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7715 bool VisitMemberExpr(const MemberExpr *E); 7716 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7717 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7718 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7719 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7720 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7721 bool VisitUnaryDeref(const UnaryOperator *E); 7722 bool VisitUnaryReal(const UnaryOperator *E); 7723 bool VisitUnaryImag(const UnaryOperator *E); 7724 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7725 return VisitUnaryPreIncDec(UO); 7726 } 7727 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7728 return VisitUnaryPreIncDec(UO); 7729 } 7730 bool VisitBinAssign(const BinaryOperator *BO); 7731 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7732 7733 bool VisitCastExpr(const CastExpr *E) { 7734 switch (E->getCastKind()) { 7735 default: 7736 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7737 7738 case CK_LValueBitCast: 7739 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7740 if (!Visit(E->getSubExpr())) 7741 return false; 7742 Result.Designator.setInvalid(); 7743 return true; 7744 7745 case CK_BaseToDerived: 7746 if (!Visit(E->getSubExpr())) 7747 return false; 7748 return HandleBaseToDerivedCast(Info, E, Result); 7749 7750 case CK_Dynamic: 7751 if (!Visit(E->getSubExpr())) 7752 return false; 7753 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7754 } 7755 } 7756 }; 7757 } // end anonymous namespace 7758 7759 /// Evaluate an expression as an lvalue. This can be legitimately called on 7760 /// expressions which are not glvalues, in three cases: 7761 /// * function designators in C, and 7762 /// * "extern void" objects 7763 /// * @selector() expressions in Objective-C 7764 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7765 bool InvalidBaseOK) { 7766 assert(E->isGLValue() || E->getType()->isFunctionType() || 7767 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7768 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7769 } 7770 7771 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7772 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7773 return Success(FD); 7774 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7775 return VisitVarDecl(E, VD); 7776 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7777 return Visit(BD->getBinding()); 7778 if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl())) 7779 return Success(GD); 7780 return Error(E); 7781 } 7782 7783 7784 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7785 7786 // If we are within a lambda's call operator, check whether the 'VD' referred 7787 // to within 'E' actually represents a lambda-capture that maps to a 7788 // data-member/field within the closure object, and if so, evaluate to the 7789 // field or what the field refers to. 7790 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7791 isa<DeclRefExpr>(E) && 7792 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7793 // We don't always have a complete capture-map when checking or inferring if 7794 // the function call operator meets the requirements of a constexpr function 7795 // - but we don't need to evaluate the captures to determine constexprness 7796 // (dcl.constexpr C++17). 7797 if (Info.checkingPotentialConstantExpression()) 7798 return false; 7799 7800 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7801 // Start with 'Result' referring to the complete closure object... 7802 Result = *Info.CurrentCall->This; 7803 // ... then update it to refer to the field of the closure object 7804 // that represents the capture. 7805 if (!HandleLValueMember(Info, E, Result, FD)) 7806 return false; 7807 // And if the field is of reference type, update 'Result' to refer to what 7808 // the field refers to. 7809 if (FD->getType()->isReferenceType()) { 7810 APValue RVal; 7811 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7812 RVal)) 7813 return false; 7814 Result.setFrom(Info.Ctx, RVal); 7815 } 7816 return true; 7817 } 7818 } 7819 CallStackFrame *Frame = nullptr; 7820 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7821 // Only if a local variable was declared in the function currently being 7822 // evaluated, do we expect to be able to find its value in the current 7823 // frame. (Otherwise it was likely declared in an enclosing context and 7824 // could either have a valid evaluatable value (for e.g. a constexpr 7825 // variable) or be ill-formed (and trigger an appropriate evaluation 7826 // diagnostic)). 7827 if (Info.CurrentCall->Callee && 7828 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7829 Frame = Info.CurrentCall; 7830 } 7831 } 7832 7833 if (!VD->getType()->isReferenceType()) { 7834 if (Frame) { 7835 Result.set({VD, Frame->Index, 7836 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7837 return true; 7838 } 7839 return Success(VD); 7840 } 7841 7842 APValue *V; 7843 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7844 return false; 7845 if (!V->hasValue()) { 7846 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7847 // adjust the diagnostic to say that. 7848 if (!Info.checkingPotentialConstantExpression()) 7849 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7850 return false; 7851 } 7852 return Success(*V, E); 7853 } 7854 7855 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7856 const MaterializeTemporaryExpr *E) { 7857 // Walk through the expression to find the materialized temporary itself. 7858 SmallVector<const Expr *, 2> CommaLHSs; 7859 SmallVector<SubobjectAdjustment, 2> Adjustments; 7860 const Expr *Inner = 7861 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7862 7863 // If we passed any comma operators, evaluate their LHSs. 7864 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7865 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7866 return false; 7867 7868 // A materialized temporary with static storage duration can appear within the 7869 // result of a constant expression evaluation, so we need to preserve its 7870 // value for use outside this evaluation. 7871 APValue *Value; 7872 if (E->getStorageDuration() == SD_Static) { 7873 Value = E->getOrCreateValue(true); 7874 *Value = APValue(); 7875 Result.set(E); 7876 } else { 7877 Value = &Info.CurrentCall->createTemporary( 7878 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7879 } 7880 7881 QualType Type = Inner->getType(); 7882 7883 // Materialize the temporary itself. 7884 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7885 *Value = APValue(); 7886 return false; 7887 } 7888 7889 // Adjust our lvalue to refer to the desired subobject. 7890 for (unsigned I = Adjustments.size(); I != 0; /**/) { 7891 --I; 7892 switch (Adjustments[I].Kind) { 7893 case SubobjectAdjustment::DerivedToBaseAdjustment: 7894 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 7895 Type, Result)) 7896 return false; 7897 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 7898 break; 7899 7900 case SubobjectAdjustment::FieldAdjustment: 7901 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 7902 return false; 7903 Type = Adjustments[I].Field->getType(); 7904 break; 7905 7906 case SubobjectAdjustment::MemberPointerAdjustment: 7907 if (!HandleMemberPointerAccess(this->Info, Type, Result, 7908 Adjustments[I].Ptr.RHS)) 7909 return false; 7910 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 7911 break; 7912 } 7913 } 7914 7915 return true; 7916 } 7917 7918 bool 7919 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7920 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 7921 "lvalue compound literal in c++?"); 7922 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 7923 // only see this when folding in C, so there's no standard to follow here. 7924 return Success(E); 7925 } 7926 7927 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 7928 TypeInfoLValue TypeInfo; 7929 7930 if (!E->isPotentiallyEvaluated()) { 7931 if (E->isTypeOperand()) 7932 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 7933 else 7934 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 7935 } else { 7936 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 7937 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 7938 << E->getExprOperand()->getType() 7939 << E->getExprOperand()->getSourceRange(); 7940 } 7941 7942 if (!Visit(E->getExprOperand())) 7943 return false; 7944 7945 Optional<DynamicType> DynType = 7946 ComputeDynamicType(Info, E, Result, AK_TypeId); 7947 if (!DynType) 7948 return false; 7949 7950 TypeInfo = 7951 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 7952 } 7953 7954 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 7955 } 7956 7957 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 7958 return Success(E->getGuidDecl()); 7959 } 7960 7961 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 7962 // Handle static data members. 7963 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 7964 VisitIgnoredBaseExpression(E->getBase()); 7965 return VisitVarDecl(E, VD); 7966 } 7967 7968 // Handle static member functions. 7969 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 7970 if (MD->isStatic()) { 7971 VisitIgnoredBaseExpression(E->getBase()); 7972 return Success(MD); 7973 } 7974 } 7975 7976 // Handle non-static data members. 7977 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 7978 } 7979 7980 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 7981 // FIXME: Deal with vectors as array subscript bases. 7982 if (E->getBase()->getType()->isVectorType()) 7983 return Error(E); 7984 7985 bool Success = true; 7986 if (!evaluatePointer(E->getBase(), Result)) { 7987 if (!Info.noteFailure()) 7988 return false; 7989 Success = false; 7990 } 7991 7992 APSInt Index; 7993 if (!EvaluateInteger(E->getIdx(), Index, Info)) 7994 return false; 7995 7996 return Success && 7997 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 7998 } 7999 8000 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8001 return evaluatePointer(E->getSubExpr(), Result); 8002 } 8003 8004 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8005 if (!Visit(E->getSubExpr())) 8006 return false; 8007 // __real is a no-op on scalar lvalues. 8008 if (E->getSubExpr()->getType()->isAnyComplexType()) 8009 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8010 return true; 8011 } 8012 8013 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8014 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8015 "lvalue __imag__ on scalar?"); 8016 if (!Visit(E->getSubExpr())) 8017 return false; 8018 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8019 return true; 8020 } 8021 8022 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8023 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8024 return Error(UO); 8025 8026 if (!this->Visit(UO->getSubExpr())) 8027 return false; 8028 8029 return handleIncDec( 8030 this->Info, UO, Result, UO->getSubExpr()->getType(), 8031 UO->isIncrementOp(), nullptr); 8032 } 8033 8034 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8035 const CompoundAssignOperator *CAO) { 8036 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8037 return Error(CAO); 8038 8039 APValue RHS; 8040 8041 // The overall lvalue result is the result of evaluating the LHS. 8042 if (!this->Visit(CAO->getLHS())) { 8043 if (Info.noteFailure()) 8044 Evaluate(RHS, this->Info, CAO->getRHS()); 8045 return false; 8046 } 8047 8048 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 8049 return false; 8050 8051 return handleCompoundAssignment( 8052 this->Info, CAO, 8053 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8054 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8055 } 8056 8057 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8058 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8059 return Error(E); 8060 8061 APValue NewVal; 8062 8063 if (!this->Visit(E->getLHS())) { 8064 if (Info.noteFailure()) 8065 Evaluate(NewVal, this->Info, E->getRHS()); 8066 return false; 8067 } 8068 8069 if (!Evaluate(NewVal, this->Info, E->getRHS())) 8070 return false; 8071 8072 if (Info.getLangOpts().CPlusPlus20 && 8073 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8074 return false; 8075 8076 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8077 NewVal); 8078 } 8079 8080 //===----------------------------------------------------------------------===// 8081 // Pointer Evaluation 8082 //===----------------------------------------------------------------------===// 8083 8084 /// Attempts to compute the number of bytes available at the pointer 8085 /// returned by a function with the alloc_size attribute. Returns true if we 8086 /// were successful. Places an unsigned number into `Result`. 8087 /// 8088 /// This expects the given CallExpr to be a call to a function with an 8089 /// alloc_size attribute. 8090 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8091 const CallExpr *Call, 8092 llvm::APInt &Result) { 8093 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8094 8095 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8096 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8097 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8098 if (Call->getNumArgs() <= SizeArgNo) 8099 return false; 8100 8101 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8102 Expr::EvalResult ExprResult; 8103 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8104 return false; 8105 Into = ExprResult.Val.getInt(); 8106 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8107 return false; 8108 Into = Into.zextOrSelf(BitsInSizeT); 8109 return true; 8110 }; 8111 8112 APSInt SizeOfElem; 8113 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8114 return false; 8115 8116 if (!AllocSize->getNumElemsParam().isValid()) { 8117 Result = std::move(SizeOfElem); 8118 return true; 8119 } 8120 8121 APSInt NumberOfElems; 8122 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8123 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8124 return false; 8125 8126 bool Overflow; 8127 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8128 if (Overflow) 8129 return false; 8130 8131 Result = std::move(BytesAvailable); 8132 return true; 8133 } 8134 8135 /// Convenience function. LVal's base must be a call to an alloc_size 8136 /// function. 8137 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8138 const LValue &LVal, 8139 llvm::APInt &Result) { 8140 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8141 "Can't get the size of a non alloc_size function"); 8142 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8143 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8144 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8145 } 8146 8147 /// Attempts to evaluate the given LValueBase as the result of a call to 8148 /// a function with the alloc_size attribute. If it was possible to do so, this 8149 /// function will return true, make Result's Base point to said function call, 8150 /// and mark Result's Base as invalid. 8151 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8152 LValue &Result) { 8153 if (Base.isNull()) 8154 return false; 8155 8156 // Because we do no form of static analysis, we only support const variables. 8157 // 8158 // Additionally, we can't support parameters, nor can we support static 8159 // variables (in the latter case, use-before-assign isn't UB; in the former, 8160 // we have no clue what they'll be assigned to). 8161 const auto *VD = 8162 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8163 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8164 return false; 8165 8166 const Expr *Init = VD->getAnyInitializer(); 8167 if (!Init) 8168 return false; 8169 8170 const Expr *E = Init->IgnoreParens(); 8171 if (!tryUnwrapAllocSizeCall(E)) 8172 return false; 8173 8174 // Store E instead of E unwrapped so that the type of the LValue's base is 8175 // what the user wanted. 8176 Result.setInvalid(E); 8177 8178 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8179 Result.addUnsizedArray(Info, E, Pointee); 8180 return true; 8181 } 8182 8183 namespace { 8184 class PointerExprEvaluator 8185 : public ExprEvaluatorBase<PointerExprEvaluator> { 8186 LValue &Result; 8187 bool InvalidBaseOK; 8188 8189 bool Success(const Expr *E) { 8190 Result.set(E); 8191 return true; 8192 } 8193 8194 bool evaluateLValue(const Expr *E, LValue &Result) { 8195 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8196 } 8197 8198 bool evaluatePointer(const Expr *E, LValue &Result) { 8199 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8200 } 8201 8202 bool visitNonBuiltinCallExpr(const CallExpr *E); 8203 public: 8204 8205 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8206 : ExprEvaluatorBaseTy(info), Result(Result), 8207 InvalidBaseOK(InvalidBaseOK) {} 8208 8209 bool Success(const APValue &V, const Expr *E) { 8210 Result.setFrom(Info.Ctx, V); 8211 return true; 8212 } 8213 bool ZeroInitialization(const Expr *E) { 8214 Result.setNull(Info.Ctx, E->getType()); 8215 return true; 8216 } 8217 8218 bool VisitBinaryOperator(const BinaryOperator *E); 8219 bool VisitCastExpr(const CastExpr* E); 8220 bool VisitUnaryAddrOf(const UnaryOperator *E); 8221 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8222 { return Success(E); } 8223 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8224 if (E->isExpressibleAsConstantInitializer()) 8225 return Success(E); 8226 if (Info.noteFailure()) 8227 EvaluateIgnoredValue(Info, E->getSubExpr()); 8228 return Error(E); 8229 } 8230 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8231 { return Success(E); } 8232 bool VisitCallExpr(const CallExpr *E); 8233 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8234 bool VisitBlockExpr(const BlockExpr *E) { 8235 if (!E->getBlockDecl()->hasCaptures()) 8236 return Success(E); 8237 return Error(E); 8238 } 8239 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8240 // Can't look at 'this' when checking a potential constant expression. 8241 if (Info.checkingPotentialConstantExpression()) 8242 return false; 8243 if (!Info.CurrentCall->This) { 8244 if (Info.getLangOpts().CPlusPlus11) 8245 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8246 else 8247 Info.FFDiag(E); 8248 return false; 8249 } 8250 Result = *Info.CurrentCall->This; 8251 // If we are inside a lambda's call operator, the 'this' expression refers 8252 // to the enclosing '*this' object (either by value or reference) which is 8253 // either copied into the closure object's field that represents the '*this' 8254 // or refers to '*this'. 8255 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8256 // Ensure we actually have captured 'this'. (an error will have 8257 // been previously reported if not). 8258 if (!Info.CurrentCall->LambdaThisCaptureField) 8259 return false; 8260 8261 // Update 'Result' to refer to the data member/field of the closure object 8262 // that represents the '*this' capture. 8263 if (!HandleLValueMember(Info, E, Result, 8264 Info.CurrentCall->LambdaThisCaptureField)) 8265 return false; 8266 // If we captured '*this' by reference, replace the field with its referent. 8267 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8268 ->isPointerType()) { 8269 APValue RVal; 8270 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8271 RVal)) 8272 return false; 8273 8274 Result.setFrom(Info.Ctx, RVal); 8275 } 8276 } 8277 return true; 8278 } 8279 8280 bool VisitCXXNewExpr(const CXXNewExpr *E); 8281 8282 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8283 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8284 APValue LValResult = E->EvaluateInContext( 8285 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8286 Result.setFrom(Info.Ctx, LValResult); 8287 return true; 8288 } 8289 8290 // FIXME: Missing: @protocol, @selector 8291 }; 8292 } // end anonymous namespace 8293 8294 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8295 bool InvalidBaseOK) { 8296 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8297 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8298 } 8299 8300 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8301 if (E->getOpcode() != BO_Add && 8302 E->getOpcode() != BO_Sub) 8303 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8304 8305 const Expr *PExp = E->getLHS(); 8306 const Expr *IExp = E->getRHS(); 8307 if (IExp->getType()->isPointerType()) 8308 std::swap(PExp, IExp); 8309 8310 bool EvalPtrOK = evaluatePointer(PExp, Result); 8311 if (!EvalPtrOK && !Info.noteFailure()) 8312 return false; 8313 8314 llvm::APSInt Offset; 8315 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8316 return false; 8317 8318 if (E->getOpcode() == BO_Sub) 8319 negateAsSigned(Offset); 8320 8321 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8322 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8323 } 8324 8325 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8326 return evaluateLValue(E->getSubExpr(), Result); 8327 } 8328 8329 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8330 const Expr *SubExpr = E->getSubExpr(); 8331 8332 switch (E->getCastKind()) { 8333 default: 8334 break; 8335 case CK_BitCast: 8336 case CK_CPointerToObjCPointerCast: 8337 case CK_BlockPointerToObjCPointerCast: 8338 case CK_AnyPointerToBlockPointerCast: 8339 case CK_AddressSpaceConversion: 8340 if (!Visit(SubExpr)) 8341 return false; 8342 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8343 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8344 // also static_casts, but we disallow them as a resolution to DR1312. 8345 if (!E->getType()->isVoidPointerType()) { 8346 if (!Result.InvalidBase && !Result.Designator.Invalid && 8347 !Result.IsNullPtr && 8348 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8349 E->getType()->getPointeeType()) && 8350 Info.getStdAllocatorCaller("allocate")) { 8351 // Inside a call to std::allocator::allocate and friends, we permit 8352 // casting from void* back to cv1 T* for a pointer that points to a 8353 // cv2 T. 8354 } else { 8355 Result.Designator.setInvalid(); 8356 if (SubExpr->getType()->isVoidPointerType()) 8357 CCEDiag(E, diag::note_constexpr_invalid_cast) 8358 << 3 << SubExpr->getType(); 8359 else 8360 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8361 } 8362 } 8363 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8364 ZeroInitialization(E); 8365 return true; 8366 8367 case CK_DerivedToBase: 8368 case CK_UncheckedDerivedToBase: 8369 if (!evaluatePointer(E->getSubExpr(), Result)) 8370 return false; 8371 if (!Result.Base && Result.Offset.isZero()) 8372 return true; 8373 8374 // Now figure out the necessary offset to add to the base LV to get from 8375 // the derived class to the base class. 8376 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8377 castAs<PointerType>()->getPointeeType(), 8378 Result); 8379 8380 case CK_BaseToDerived: 8381 if (!Visit(E->getSubExpr())) 8382 return false; 8383 if (!Result.Base && Result.Offset.isZero()) 8384 return true; 8385 return HandleBaseToDerivedCast(Info, E, Result); 8386 8387 case CK_Dynamic: 8388 if (!Visit(E->getSubExpr())) 8389 return false; 8390 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8391 8392 case CK_NullToPointer: 8393 VisitIgnoredValue(E->getSubExpr()); 8394 return ZeroInitialization(E); 8395 8396 case CK_IntegralToPointer: { 8397 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8398 8399 APValue Value; 8400 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8401 break; 8402 8403 if (Value.isInt()) { 8404 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8405 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8406 Result.Base = (Expr*)nullptr; 8407 Result.InvalidBase = false; 8408 Result.Offset = CharUnits::fromQuantity(N); 8409 Result.Designator.setInvalid(); 8410 Result.IsNullPtr = false; 8411 return true; 8412 } else { 8413 // Cast is of an lvalue, no need to change value. 8414 Result.setFrom(Info.Ctx, Value); 8415 return true; 8416 } 8417 } 8418 8419 case CK_ArrayToPointerDecay: { 8420 if (SubExpr->isGLValue()) { 8421 if (!evaluateLValue(SubExpr, Result)) 8422 return false; 8423 } else { 8424 APValue &Value = Info.CurrentCall->createTemporary( 8425 SubExpr, SubExpr->getType(), false, Result); 8426 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8427 return false; 8428 } 8429 // The result is a pointer to the first element of the array. 8430 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8431 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8432 Result.addArray(Info, E, CAT); 8433 else 8434 Result.addUnsizedArray(Info, E, AT->getElementType()); 8435 return true; 8436 } 8437 8438 case CK_FunctionToPointerDecay: 8439 return evaluateLValue(SubExpr, Result); 8440 8441 case CK_LValueToRValue: { 8442 LValue LVal; 8443 if (!evaluateLValue(E->getSubExpr(), LVal)) 8444 return false; 8445 8446 APValue RVal; 8447 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8448 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8449 LVal, RVal)) 8450 return InvalidBaseOK && 8451 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8452 return Success(RVal, E); 8453 } 8454 } 8455 8456 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8457 } 8458 8459 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8460 UnaryExprOrTypeTrait ExprKind) { 8461 // C++ [expr.alignof]p3: 8462 // When alignof is applied to a reference type, the result is the 8463 // alignment of the referenced type. 8464 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8465 T = Ref->getPointeeType(); 8466 8467 if (T.getQualifiers().hasUnaligned()) 8468 return CharUnits::One(); 8469 8470 const bool AlignOfReturnsPreferred = 8471 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8472 8473 // __alignof is defined to return the preferred alignment. 8474 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8475 // as well. 8476 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8477 return Info.Ctx.toCharUnitsFromBits( 8478 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8479 // alignof and _Alignof are defined to return the ABI alignment. 8480 else if (ExprKind == UETT_AlignOf) 8481 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8482 else 8483 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8484 } 8485 8486 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8487 UnaryExprOrTypeTrait ExprKind) { 8488 E = E->IgnoreParens(); 8489 8490 // The kinds of expressions that we have special-case logic here for 8491 // should be kept up to date with the special checks for those 8492 // expressions in Sema. 8493 8494 // alignof decl is always accepted, even if it doesn't make sense: we default 8495 // to 1 in those cases. 8496 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8497 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8498 /*RefAsPointee*/true); 8499 8500 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8501 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8502 /*RefAsPointee*/true); 8503 8504 return GetAlignOfType(Info, E->getType(), ExprKind); 8505 } 8506 8507 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8508 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8509 return Info.Ctx.getDeclAlign(VD); 8510 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8511 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8512 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8513 } 8514 8515 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8516 /// __builtin_is_aligned and __builtin_assume_aligned. 8517 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8518 EvalInfo &Info, APSInt &Alignment) { 8519 if (!EvaluateInteger(E, Alignment, Info)) 8520 return false; 8521 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8522 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8523 return false; 8524 } 8525 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8526 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8527 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8528 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8529 << MaxValue << ForType << Alignment; 8530 return false; 8531 } 8532 // Ensure both alignment and source value have the same bit width so that we 8533 // don't assert when computing the resulting value. 8534 APSInt ExtAlignment = 8535 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8536 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8537 "Alignment should not be changed by ext/trunc"); 8538 Alignment = ExtAlignment; 8539 assert(Alignment.getBitWidth() == SrcWidth); 8540 return true; 8541 } 8542 8543 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8544 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8545 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8546 return true; 8547 8548 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8549 return false; 8550 8551 Result.setInvalid(E); 8552 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8553 Result.addUnsizedArray(Info, E, PointeeTy); 8554 return true; 8555 } 8556 8557 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8558 if (IsStringLiteralCall(E)) 8559 return Success(E); 8560 8561 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8562 return VisitBuiltinCallExpr(E, BuiltinOp); 8563 8564 return visitNonBuiltinCallExpr(E); 8565 } 8566 8567 // Determine if T is a character type for which we guarantee that 8568 // sizeof(T) == 1. 8569 static bool isOneByteCharacterType(QualType T) { 8570 return T->isCharType() || T->isChar8Type(); 8571 } 8572 8573 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8574 unsigned BuiltinOp) { 8575 switch (BuiltinOp) { 8576 case Builtin::BI__builtin_addressof: 8577 return evaluateLValue(E->getArg(0), Result); 8578 case Builtin::BI__builtin_assume_aligned: { 8579 // We need to be very careful here because: if the pointer does not have the 8580 // asserted alignment, then the behavior is undefined, and undefined 8581 // behavior is non-constant. 8582 if (!evaluatePointer(E->getArg(0), Result)) 8583 return false; 8584 8585 LValue OffsetResult(Result); 8586 APSInt Alignment; 8587 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8588 Alignment)) 8589 return false; 8590 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8591 8592 if (E->getNumArgs() > 2) { 8593 APSInt Offset; 8594 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8595 return false; 8596 8597 int64_t AdditionalOffset = -Offset.getZExtValue(); 8598 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8599 } 8600 8601 // If there is a base object, then it must have the correct alignment. 8602 if (OffsetResult.Base) { 8603 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8604 8605 if (BaseAlignment < Align) { 8606 Result.Designator.setInvalid(); 8607 // FIXME: Add support to Diagnostic for long / long long. 8608 CCEDiag(E->getArg(0), 8609 diag::note_constexpr_baa_insufficient_alignment) << 0 8610 << (unsigned)BaseAlignment.getQuantity() 8611 << (unsigned)Align.getQuantity(); 8612 return false; 8613 } 8614 } 8615 8616 // The offset must also have the correct alignment. 8617 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8618 Result.Designator.setInvalid(); 8619 8620 (OffsetResult.Base 8621 ? CCEDiag(E->getArg(0), 8622 diag::note_constexpr_baa_insufficient_alignment) << 1 8623 : CCEDiag(E->getArg(0), 8624 diag::note_constexpr_baa_value_insufficient_alignment)) 8625 << (int)OffsetResult.Offset.getQuantity() 8626 << (unsigned)Align.getQuantity(); 8627 return false; 8628 } 8629 8630 return true; 8631 } 8632 case Builtin::BI__builtin_align_up: 8633 case Builtin::BI__builtin_align_down: { 8634 if (!evaluatePointer(E->getArg(0), Result)) 8635 return false; 8636 APSInt Alignment; 8637 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8638 Alignment)) 8639 return false; 8640 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8641 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8642 // For align_up/align_down, we can return the same value if the alignment 8643 // is known to be greater or equal to the requested value. 8644 if (PtrAlign.getQuantity() >= Alignment) 8645 return true; 8646 8647 // The alignment could be greater than the minimum at run-time, so we cannot 8648 // infer much about the resulting pointer value. One case is possible: 8649 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8650 // can infer the correct index if the requested alignment is smaller than 8651 // the base alignment so we can perform the computation on the offset. 8652 if (BaseAlignment.getQuantity() >= Alignment) { 8653 assert(Alignment.getBitWidth() <= 64 && 8654 "Cannot handle > 64-bit address-space"); 8655 uint64_t Alignment64 = Alignment.getZExtValue(); 8656 CharUnits NewOffset = CharUnits::fromQuantity( 8657 BuiltinOp == Builtin::BI__builtin_align_down 8658 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8659 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8660 Result.adjustOffset(NewOffset - Result.Offset); 8661 // TODO: diagnose out-of-bounds values/only allow for arrays? 8662 return true; 8663 } 8664 // Otherwise, we cannot constant-evaluate the result. 8665 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8666 << Alignment; 8667 return false; 8668 } 8669 case Builtin::BI__builtin_operator_new: 8670 return HandleOperatorNewCall(Info, E, Result); 8671 case Builtin::BI__builtin_launder: 8672 return evaluatePointer(E->getArg(0), Result); 8673 case Builtin::BIstrchr: 8674 case Builtin::BIwcschr: 8675 case Builtin::BImemchr: 8676 case Builtin::BIwmemchr: 8677 if (Info.getLangOpts().CPlusPlus11) 8678 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8679 << /*isConstexpr*/0 << /*isConstructor*/0 8680 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8681 else 8682 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8683 LLVM_FALLTHROUGH; 8684 case Builtin::BI__builtin_strchr: 8685 case Builtin::BI__builtin_wcschr: 8686 case Builtin::BI__builtin_memchr: 8687 case Builtin::BI__builtin_char_memchr: 8688 case Builtin::BI__builtin_wmemchr: { 8689 if (!Visit(E->getArg(0))) 8690 return false; 8691 APSInt Desired; 8692 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8693 return false; 8694 uint64_t MaxLength = uint64_t(-1); 8695 if (BuiltinOp != Builtin::BIstrchr && 8696 BuiltinOp != Builtin::BIwcschr && 8697 BuiltinOp != Builtin::BI__builtin_strchr && 8698 BuiltinOp != Builtin::BI__builtin_wcschr) { 8699 APSInt N; 8700 if (!EvaluateInteger(E->getArg(2), N, Info)) 8701 return false; 8702 MaxLength = N.getExtValue(); 8703 } 8704 // We cannot find the value if there are no candidates to match against. 8705 if (MaxLength == 0u) 8706 return ZeroInitialization(E); 8707 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8708 Result.Designator.Invalid) 8709 return false; 8710 QualType CharTy = Result.Designator.getType(Info.Ctx); 8711 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 8712 BuiltinOp == Builtin::BI__builtin_memchr; 8713 assert(IsRawByte || 8714 Info.Ctx.hasSameUnqualifiedType( 8715 CharTy, E->getArg(0)->getType()->getPointeeType())); 8716 // Pointers to const void may point to objects of incomplete type. 8717 if (IsRawByte && CharTy->isIncompleteType()) { 8718 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 8719 return false; 8720 } 8721 // Give up on byte-oriented matching against multibyte elements. 8722 // FIXME: We can compare the bytes in the correct order. 8723 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 8724 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 8725 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 8726 << CharTy; 8727 return false; 8728 } 8729 // Figure out what value we're actually looking for (after converting to 8730 // the corresponding unsigned type if necessary). 8731 uint64_t DesiredVal; 8732 bool StopAtNull = false; 8733 switch (BuiltinOp) { 8734 case Builtin::BIstrchr: 8735 case Builtin::BI__builtin_strchr: 8736 // strchr compares directly to the passed integer, and therefore 8737 // always fails if given an int that is not a char. 8738 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8739 E->getArg(1)->getType(), 8740 Desired), 8741 Desired)) 8742 return ZeroInitialization(E); 8743 StopAtNull = true; 8744 LLVM_FALLTHROUGH; 8745 case Builtin::BImemchr: 8746 case Builtin::BI__builtin_memchr: 8747 case Builtin::BI__builtin_char_memchr: 8748 // memchr compares by converting both sides to unsigned char. That's also 8749 // correct for strchr if we get this far (to cope with plain char being 8750 // unsigned in the strchr case). 8751 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8752 break; 8753 8754 case Builtin::BIwcschr: 8755 case Builtin::BI__builtin_wcschr: 8756 StopAtNull = true; 8757 LLVM_FALLTHROUGH; 8758 case Builtin::BIwmemchr: 8759 case Builtin::BI__builtin_wmemchr: 8760 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8761 DesiredVal = Desired.getZExtValue(); 8762 break; 8763 } 8764 8765 for (; MaxLength; --MaxLength) { 8766 APValue Char; 8767 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8768 !Char.isInt()) 8769 return false; 8770 if (Char.getInt().getZExtValue() == DesiredVal) 8771 return true; 8772 if (StopAtNull && !Char.getInt()) 8773 break; 8774 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8775 return false; 8776 } 8777 // Not found: return nullptr. 8778 return ZeroInitialization(E); 8779 } 8780 8781 case Builtin::BImemcpy: 8782 case Builtin::BImemmove: 8783 case Builtin::BIwmemcpy: 8784 case Builtin::BIwmemmove: 8785 if (Info.getLangOpts().CPlusPlus11) 8786 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8787 << /*isConstexpr*/0 << /*isConstructor*/0 8788 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8789 else 8790 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8791 LLVM_FALLTHROUGH; 8792 case Builtin::BI__builtin_memcpy: 8793 case Builtin::BI__builtin_memmove: 8794 case Builtin::BI__builtin_wmemcpy: 8795 case Builtin::BI__builtin_wmemmove: { 8796 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8797 BuiltinOp == Builtin::BIwmemmove || 8798 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8799 BuiltinOp == Builtin::BI__builtin_wmemmove; 8800 bool Move = BuiltinOp == Builtin::BImemmove || 8801 BuiltinOp == Builtin::BIwmemmove || 8802 BuiltinOp == Builtin::BI__builtin_memmove || 8803 BuiltinOp == Builtin::BI__builtin_wmemmove; 8804 8805 // The result of mem* is the first argument. 8806 if (!Visit(E->getArg(0))) 8807 return false; 8808 LValue Dest = Result; 8809 8810 LValue Src; 8811 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8812 return false; 8813 8814 APSInt N; 8815 if (!EvaluateInteger(E->getArg(2), N, Info)) 8816 return false; 8817 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8818 8819 // If the size is zero, we treat this as always being a valid no-op. 8820 // (Even if one of the src and dest pointers is null.) 8821 if (!N) 8822 return true; 8823 8824 // Otherwise, if either of the operands is null, we can't proceed. Don't 8825 // try to determine the type of the copied objects, because there aren't 8826 // any. 8827 if (!Src.Base || !Dest.Base) { 8828 APValue Val; 8829 (!Src.Base ? Src : Dest).moveInto(Val); 8830 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8831 << Move << WChar << !!Src.Base 8832 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8833 return false; 8834 } 8835 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8836 return false; 8837 8838 // We require that Src and Dest are both pointers to arrays of 8839 // trivially-copyable type. (For the wide version, the designator will be 8840 // invalid if the designated object is not a wchar_t.) 8841 QualType T = Dest.Designator.getType(Info.Ctx); 8842 QualType SrcT = Src.Designator.getType(Info.Ctx); 8843 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8844 // FIXME: Consider using our bit_cast implementation to support this. 8845 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8846 return false; 8847 } 8848 if (T->isIncompleteType()) { 8849 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8850 return false; 8851 } 8852 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8853 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8854 return false; 8855 } 8856 8857 // Figure out how many T's we're copying. 8858 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8859 if (!WChar) { 8860 uint64_t Remainder; 8861 llvm::APInt OrigN = N; 8862 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8863 if (Remainder) { 8864 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8865 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8866 << (unsigned)TSize; 8867 return false; 8868 } 8869 } 8870 8871 // Check that the copying will remain within the arrays, just so that we 8872 // can give a more meaningful diagnostic. This implicitly also checks that 8873 // N fits into 64 bits. 8874 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8875 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8876 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8877 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8878 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8879 << N.toString(10, /*Signed*/false); 8880 return false; 8881 } 8882 uint64_t NElems = N.getZExtValue(); 8883 uint64_t NBytes = NElems * TSize; 8884 8885 // Check for overlap. 8886 int Direction = 1; 8887 if (HasSameBase(Src, Dest)) { 8888 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 8889 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 8890 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 8891 // Dest is inside the source region. 8892 if (!Move) { 8893 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8894 return false; 8895 } 8896 // For memmove and friends, copy backwards. 8897 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 8898 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 8899 return false; 8900 Direction = -1; 8901 } else if (!Move && SrcOffset >= DestOffset && 8902 SrcOffset - DestOffset < NBytes) { 8903 // Src is inside the destination region for memcpy: invalid. 8904 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8905 return false; 8906 } 8907 } 8908 8909 while (true) { 8910 APValue Val; 8911 // FIXME: Set WantObjectRepresentation to true if we're copying a 8912 // char-like type? 8913 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 8914 !handleAssignment(Info, E, Dest, T, Val)) 8915 return false; 8916 // Do not iterate past the last element; if we're copying backwards, that 8917 // might take us off the start of the array. 8918 if (--NElems == 0) 8919 return true; 8920 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 8921 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 8922 return false; 8923 } 8924 } 8925 8926 default: 8927 break; 8928 } 8929 8930 return visitNonBuiltinCallExpr(E); 8931 } 8932 8933 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 8934 APValue &Result, const InitListExpr *ILE, 8935 QualType AllocType); 8936 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 8937 APValue &Result, 8938 const CXXConstructExpr *CCE, 8939 QualType AllocType); 8940 8941 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 8942 if (!Info.getLangOpts().CPlusPlus20) 8943 Info.CCEDiag(E, diag::note_constexpr_new); 8944 8945 // We cannot speculatively evaluate a delete expression. 8946 if (Info.SpeculativeEvaluationDepth) 8947 return false; 8948 8949 FunctionDecl *OperatorNew = E->getOperatorNew(); 8950 8951 bool IsNothrow = false; 8952 bool IsPlacement = false; 8953 if (OperatorNew->isReservedGlobalPlacementOperator() && 8954 Info.CurrentCall->isStdFunction() && !E->isArray()) { 8955 // FIXME Support array placement new. 8956 assert(E->getNumPlacementArgs() == 1); 8957 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 8958 return false; 8959 if (Result.Designator.Invalid) 8960 return false; 8961 IsPlacement = true; 8962 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 8963 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 8964 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 8965 return false; 8966 } else if (E->getNumPlacementArgs()) { 8967 // The only new-placement list we support is of the form (std::nothrow). 8968 // 8969 // FIXME: There is no restriction on this, but it's not clear that any 8970 // other form makes any sense. We get here for cases such as: 8971 // 8972 // new (std::align_val_t{N}) X(int) 8973 // 8974 // (which should presumably be valid only if N is a multiple of 8975 // alignof(int), and in any case can't be deallocated unless N is 8976 // alignof(X) and X has new-extended alignment). 8977 if (E->getNumPlacementArgs() != 1 || 8978 !E->getPlacementArg(0)->getType()->isNothrowT()) 8979 return Error(E, diag::note_constexpr_new_placement); 8980 8981 LValue Nothrow; 8982 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 8983 return false; 8984 IsNothrow = true; 8985 } 8986 8987 const Expr *Init = E->getInitializer(); 8988 const InitListExpr *ResizedArrayILE = nullptr; 8989 const CXXConstructExpr *ResizedArrayCCE = nullptr; 8990 8991 QualType AllocType = E->getAllocatedType(); 8992 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 8993 const Expr *Stripped = *ArraySize; 8994 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 8995 Stripped = ICE->getSubExpr()) 8996 if (ICE->getCastKind() != CK_NoOp && 8997 ICE->getCastKind() != CK_IntegralCast) 8998 break; 8999 9000 llvm::APSInt ArrayBound; 9001 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9002 return false; 9003 9004 // C++ [expr.new]p9: 9005 // The expression is erroneous if: 9006 // -- [...] its value before converting to size_t [or] applying the 9007 // second standard conversion sequence is less than zero 9008 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9009 if (IsNothrow) 9010 return ZeroInitialization(E); 9011 9012 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9013 << ArrayBound << (*ArraySize)->getSourceRange(); 9014 return false; 9015 } 9016 9017 // -- its value is such that the size of the allocated object would 9018 // exceed the implementation-defined limit 9019 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9020 ArrayBound) > 9021 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9022 if (IsNothrow) 9023 return ZeroInitialization(E); 9024 9025 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9026 << ArrayBound << (*ArraySize)->getSourceRange(); 9027 return false; 9028 } 9029 9030 // -- the new-initializer is a braced-init-list and the number of 9031 // array elements for which initializers are provided [...] 9032 // exceeds the number of elements to initialize 9033 if (Init && !isa<CXXConstructExpr>(Init)) { 9034 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9035 assert(CAT && "unexpected type for array initializer"); 9036 9037 unsigned Bits = 9038 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9039 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9040 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9041 if (InitBound.ugt(AllocBound)) { 9042 if (IsNothrow) 9043 return ZeroInitialization(E); 9044 9045 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9046 << AllocBound.toString(10, /*Signed=*/false) 9047 << InitBound.toString(10, /*Signed=*/false) 9048 << (*ArraySize)->getSourceRange(); 9049 return false; 9050 } 9051 9052 // If the sizes differ, we must have an initializer list, and we need 9053 // special handling for this case when we initialize. 9054 if (InitBound != AllocBound) 9055 ResizedArrayILE = cast<InitListExpr>(Init); 9056 } else if (Init) { 9057 ResizedArrayCCE = cast<CXXConstructExpr>(Init); 9058 } 9059 9060 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9061 ArrayType::Normal, 0); 9062 } else { 9063 assert(!AllocType->isArrayType() && 9064 "array allocation with non-array new"); 9065 } 9066 9067 APValue *Val; 9068 if (IsPlacement) { 9069 AccessKinds AK = AK_Construct; 9070 struct FindObjectHandler { 9071 EvalInfo &Info; 9072 const Expr *E; 9073 QualType AllocType; 9074 const AccessKinds AccessKind; 9075 APValue *Value; 9076 9077 typedef bool result_type; 9078 bool failed() { return false; } 9079 bool found(APValue &Subobj, QualType SubobjType) { 9080 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9081 // old name of the object to be used to name the new object. 9082 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9083 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9084 SubobjType << AllocType; 9085 return false; 9086 } 9087 Value = &Subobj; 9088 return true; 9089 } 9090 bool found(APSInt &Value, QualType SubobjType) { 9091 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9092 return false; 9093 } 9094 bool found(APFloat &Value, QualType SubobjType) { 9095 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9096 return false; 9097 } 9098 } Handler = {Info, E, AllocType, AK, nullptr}; 9099 9100 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9101 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9102 return false; 9103 9104 Val = Handler.Value; 9105 9106 // [basic.life]p1: 9107 // The lifetime of an object o of type T ends when [...] the storage 9108 // which the object occupies is [...] reused by an object that is not 9109 // nested within o (6.6.2). 9110 *Val = APValue(); 9111 } else { 9112 // Perform the allocation and obtain a pointer to the resulting object. 9113 Val = Info.createHeapAlloc(E, AllocType, Result); 9114 if (!Val) 9115 return false; 9116 } 9117 9118 if (ResizedArrayILE) { 9119 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9120 AllocType)) 9121 return false; 9122 } else if (ResizedArrayCCE) { 9123 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9124 AllocType)) 9125 return false; 9126 } else if (Init) { 9127 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9128 return false; 9129 } else if (!getDefaultInitValue(AllocType, *Val)) { 9130 return false; 9131 } 9132 9133 // Array new returns a pointer to the first element, not a pointer to the 9134 // array. 9135 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9136 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9137 9138 return true; 9139 } 9140 //===----------------------------------------------------------------------===// 9141 // Member Pointer Evaluation 9142 //===----------------------------------------------------------------------===// 9143 9144 namespace { 9145 class MemberPointerExprEvaluator 9146 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9147 MemberPtr &Result; 9148 9149 bool Success(const ValueDecl *D) { 9150 Result = MemberPtr(D); 9151 return true; 9152 } 9153 public: 9154 9155 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9156 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9157 9158 bool Success(const APValue &V, const Expr *E) { 9159 Result.setFrom(V); 9160 return true; 9161 } 9162 bool ZeroInitialization(const Expr *E) { 9163 return Success((const ValueDecl*)nullptr); 9164 } 9165 9166 bool VisitCastExpr(const CastExpr *E); 9167 bool VisitUnaryAddrOf(const UnaryOperator *E); 9168 }; 9169 } // end anonymous namespace 9170 9171 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9172 EvalInfo &Info) { 9173 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9174 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9175 } 9176 9177 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9178 switch (E->getCastKind()) { 9179 default: 9180 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9181 9182 case CK_NullToMemberPointer: 9183 VisitIgnoredValue(E->getSubExpr()); 9184 return ZeroInitialization(E); 9185 9186 case CK_BaseToDerivedMemberPointer: { 9187 if (!Visit(E->getSubExpr())) 9188 return false; 9189 if (E->path_empty()) 9190 return true; 9191 // Base-to-derived member pointer casts store the path in derived-to-base 9192 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9193 // the wrong end of the derived->base arc, so stagger the path by one class. 9194 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9195 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9196 PathI != PathE; ++PathI) { 9197 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9198 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9199 if (!Result.castToDerived(Derived)) 9200 return Error(E); 9201 } 9202 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9203 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9204 return Error(E); 9205 return true; 9206 } 9207 9208 case CK_DerivedToBaseMemberPointer: 9209 if (!Visit(E->getSubExpr())) 9210 return false; 9211 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9212 PathE = E->path_end(); PathI != PathE; ++PathI) { 9213 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9214 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9215 if (!Result.castToBase(Base)) 9216 return Error(E); 9217 } 9218 return true; 9219 } 9220 } 9221 9222 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9223 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9224 // member can be formed. 9225 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9226 } 9227 9228 //===----------------------------------------------------------------------===// 9229 // Record Evaluation 9230 //===----------------------------------------------------------------------===// 9231 9232 namespace { 9233 class RecordExprEvaluator 9234 : public ExprEvaluatorBase<RecordExprEvaluator> { 9235 const LValue &This; 9236 APValue &Result; 9237 public: 9238 9239 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9240 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9241 9242 bool Success(const APValue &V, const Expr *E) { 9243 Result = V; 9244 return true; 9245 } 9246 bool ZeroInitialization(const Expr *E) { 9247 return ZeroInitialization(E, E->getType()); 9248 } 9249 bool ZeroInitialization(const Expr *E, QualType T); 9250 9251 bool VisitCallExpr(const CallExpr *E) { 9252 return handleCallExpr(E, Result, &This); 9253 } 9254 bool VisitCastExpr(const CastExpr *E); 9255 bool VisitInitListExpr(const InitListExpr *E); 9256 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9257 return VisitCXXConstructExpr(E, E->getType()); 9258 } 9259 bool VisitLambdaExpr(const LambdaExpr *E); 9260 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9261 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9262 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9263 bool VisitBinCmp(const BinaryOperator *E); 9264 }; 9265 } 9266 9267 /// Perform zero-initialization on an object of non-union class type. 9268 /// C++11 [dcl.init]p5: 9269 /// To zero-initialize an object or reference of type T means: 9270 /// [...] 9271 /// -- if T is a (possibly cv-qualified) non-union class type, 9272 /// each non-static data member and each base-class subobject is 9273 /// zero-initialized 9274 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9275 const RecordDecl *RD, 9276 const LValue &This, APValue &Result) { 9277 assert(!RD->isUnion() && "Expected non-union class type"); 9278 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9279 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9280 std::distance(RD->field_begin(), RD->field_end())); 9281 9282 if (RD->isInvalidDecl()) return false; 9283 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9284 9285 if (CD) { 9286 unsigned Index = 0; 9287 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9288 End = CD->bases_end(); I != End; ++I, ++Index) { 9289 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9290 LValue Subobject = This; 9291 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9292 return false; 9293 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9294 Result.getStructBase(Index))) 9295 return false; 9296 } 9297 } 9298 9299 for (const auto *I : RD->fields()) { 9300 // -- if T is a reference type, no initialization is performed. 9301 if (I->getType()->isReferenceType()) 9302 continue; 9303 9304 LValue Subobject = This; 9305 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9306 return false; 9307 9308 ImplicitValueInitExpr VIE(I->getType()); 9309 if (!EvaluateInPlace( 9310 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9311 return false; 9312 } 9313 9314 return true; 9315 } 9316 9317 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9318 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9319 if (RD->isInvalidDecl()) return false; 9320 if (RD->isUnion()) { 9321 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9322 // object's first non-static named data member is zero-initialized 9323 RecordDecl::field_iterator I = RD->field_begin(); 9324 if (I == RD->field_end()) { 9325 Result = APValue((const FieldDecl*)nullptr); 9326 return true; 9327 } 9328 9329 LValue Subobject = This; 9330 if (!HandleLValueMember(Info, E, Subobject, *I)) 9331 return false; 9332 Result = APValue(*I); 9333 ImplicitValueInitExpr VIE(I->getType()); 9334 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9335 } 9336 9337 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9338 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9339 return false; 9340 } 9341 9342 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9343 } 9344 9345 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9346 switch (E->getCastKind()) { 9347 default: 9348 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9349 9350 case CK_ConstructorConversion: 9351 return Visit(E->getSubExpr()); 9352 9353 case CK_DerivedToBase: 9354 case CK_UncheckedDerivedToBase: { 9355 APValue DerivedObject; 9356 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9357 return false; 9358 if (!DerivedObject.isStruct()) 9359 return Error(E->getSubExpr()); 9360 9361 // Derived-to-base rvalue conversion: just slice off the derived part. 9362 APValue *Value = &DerivedObject; 9363 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9364 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9365 PathE = E->path_end(); PathI != PathE; ++PathI) { 9366 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9367 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9368 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9369 RD = Base; 9370 } 9371 Result = *Value; 9372 return true; 9373 } 9374 } 9375 } 9376 9377 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9378 if (E->isTransparent()) 9379 return Visit(E->getInit(0)); 9380 9381 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9382 if (RD->isInvalidDecl()) return false; 9383 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9384 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9385 9386 EvalInfo::EvaluatingConstructorRAII EvalObj( 9387 Info, 9388 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9389 CXXRD && CXXRD->getNumBases()); 9390 9391 if (RD->isUnion()) { 9392 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9393 Result = APValue(Field); 9394 if (!Field) 9395 return true; 9396 9397 // If the initializer list for a union does not contain any elements, the 9398 // first element of the union is value-initialized. 9399 // FIXME: The element should be initialized from an initializer list. 9400 // Is this difference ever observable for initializer lists which 9401 // we don't build? 9402 ImplicitValueInitExpr VIE(Field->getType()); 9403 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9404 9405 LValue Subobject = This; 9406 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9407 return false; 9408 9409 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9410 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9411 isa<CXXDefaultInitExpr>(InitExpr)); 9412 9413 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9414 } 9415 9416 if (!Result.hasValue()) 9417 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9418 std::distance(RD->field_begin(), RD->field_end())); 9419 unsigned ElementNo = 0; 9420 bool Success = true; 9421 9422 // Initialize base classes. 9423 if (CXXRD && CXXRD->getNumBases()) { 9424 for (const auto &Base : CXXRD->bases()) { 9425 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9426 const Expr *Init = E->getInit(ElementNo); 9427 9428 LValue Subobject = This; 9429 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9430 return false; 9431 9432 APValue &FieldVal = Result.getStructBase(ElementNo); 9433 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9434 if (!Info.noteFailure()) 9435 return false; 9436 Success = false; 9437 } 9438 ++ElementNo; 9439 } 9440 9441 EvalObj.finishedConstructingBases(); 9442 } 9443 9444 // Initialize members. 9445 for (const auto *Field : RD->fields()) { 9446 // Anonymous bit-fields are not considered members of the class for 9447 // purposes of aggregate initialization. 9448 if (Field->isUnnamedBitfield()) 9449 continue; 9450 9451 LValue Subobject = This; 9452 9453 bool HaveInit = ElementNo < E->getNumInits(); 9454 9455 // FIXME: Diagnostics here should point to the end of the initializer 9456 // list, not the start. 9457 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9458 Subobject, Field, &Layout)) 9459 return false; 9460 9461 // Perform an implicit value-initialization for members beyond the end of 9462 // the initializer list. 9463 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9464 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9465 9466 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9467 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9468 isa<CXXDefaultInitExpr>(Init)); 9469 9470 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9471 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9472 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9473 FieldVal, Field))) { 9474 if (!Info.noteFailure()) 9475 return false; 9476 Success = false; 9477 } 9478 } 9479 9480 EvalObj.finishedConstructingFields(); 9481 9482 return Success; 9483 } 9484 9485 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9486 QualType T) { 9487 // Note that E's type is not necessarily the type of our class here; we might 9488 // be initializing an array element instead. 9489 const CXXConstructorDecl *FD = E->getConstructor(); 9490 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9491 9492 bool ZeroInit = E->requiresZeroInitialization(); 9493 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9494 // If we've already performed zero-initialization, we're already done. 9495 if (Result.hasValue()) 9496 return true; 9497 9498 if (ZeroInit) 9499 return ZeroInitialization(E, T); 9500 9501 return getDefaultInitValue(T, Result); 9502 } 9503 9504 const FunctionDecl *Definition = nullptr; 9505 auto Body = FD->getBody(Definition); 9506 9507 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9508 return false; 9509 9510 // Avoid materializing a temporary for an elidable copy/move constructor. 9511 if (E->isElidable() && !ZeroInit) 9512 if (const MaterializeTemporaryExpr *ME 9513 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9514 return Visit(ME->getSubExpr()); 9515 9516 if (ZeroInit && !ZeroInitialization(E, T)) 9517 return false; 9518 9519 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9520 return HandleConstructorCall(E, This, Args, 9521 cast<CXXConstructorDecl>(Definition), Info, 9522 Result); 9523 } 9524 9525 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9526 const CXXInheritedCtorInitExpr *E) { 9527 if (!Info.CurrentCall) { 9528 assert(Info.checkingPotentialConstantExpression()); 9529 return false; 9530 } 9531 9532 const CXXConstructorDecl *FD = E->getConstructor(); 9533 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9534 return false; 9535 9536 const FunctionDecl *Definition = nullptr; 9537 auto Body = FD->getBody(Definition); 9538 9539 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9540 return false; 9541 9542 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9543 cast<CXXConstructorDecl>(Definition), Info, 9544 Result); 9545 } 9546 9547 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9548 const CXXStdInitializerListExpr *E) { 9549 const ConstantArrayType *ArrayType = 9550 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9551 9552 LValue Array; 9553 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9554 return false; 9555 9556 // Get a pointer to the first element of the array. 9557 Array.addArray(Info, E, ArrayType); 9558 9559 auto InvalidType = [&] { 9560 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9561 << E->getType(); 9562 return false; 9563 }; 9564 9565 // FIXME: Perform the checks on the field types in SemaInit. 9566 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9567 RecordDecl::field_iterator Field = Record->field_begin(); 9568 if (Field == Record->field_end()) 9569 return InvalidType(); 9570 9571 // Start pointer. 9572 if (!Field->getType()->isPointerType() || 9573 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9574 ArrayType->getElementType())) 9575 return InvalidType(); 9576 9577 // FIXME: What if the initializer_list type has base classes, etc? 9578 Result = APValue(APValue::UninitStruct(), 0, 2); 9579 Array.moveInto(Result.getStructField(0)); 9580 9581 if (++Field == Record->field_end()) 9582 return InvalidType(); 9583 9584 if (Field->getType()->isPointerType() && 9585 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9586 ArrayType->getElementType())) { 9587 // End pointer. 9588 if (!HandleLValueArrayAdjustment(Info, E, Array, 9589 ArrayType->getElementType(), 9590 ArrayType->getSize().getZExtValue())) 9591 return false; 9592 Array.moveInto(Result.getStructField(1)); 9593 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9594 // Length. 9595 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9596 else 9597 return InvalidType(); 9598 9599 if (++Field != Record->field_end()) 9600 return InvalidType(); 9601 9602 return true; 9603 } 9604 9605 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9606 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9607 if (ClosureClass->isInvalidDecl()) 9608 return false; 9609 9610 const size_t NumFields = 9611 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9612 9613 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9614 E->capture_init_end()) && 9615 "The number of lambda capture initializers should equal the number of " 9616 "fields within the closure type"); 9617 9618 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9619 // Iterate through all the lambda's closure object's fields and initialize 9620 // them. 9621 auto *CaptureInitIt = E->capture_init_begin(); 9622 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9623 bool Success = true; 9624 for (const auto *Field : ClosureClass->fields()) { 9625 assert(CaptureInitIt != E->capture_init_end()); 9626 // Get the initializer for this field 9627 Expr *const CurFieldInit = *CaptureInitIt++; 9628 9629 // If there is no initializer, either this is a VLA or an error has 9630 // occurred. 9631 if (!CurFieldInit) 9632 return Error(E); 9633 9634 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9635 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9636 if (!Info.keepEvaluatingAfterFailure()) 9637 return false; 9638 Success = false; 9639 } 9640 ++CaptureIt; 9641 } 9642 return Success; 9643 } 9644 9645 static bool EvaluateRecord(const Expr *E, const LValue &This, 9646 APValue &Result, EvalInfo &Info) { 9647 assert(E->isRValue() && E->getType()->isRecordType() && 9648 "can't evaluate expression as a record rvalue"); 9649 return RecordExprEvaluator(Info, This, Result).Visit(E); 9650 } 9651 9652 //===----------------------------------------------------------------------===// 9653 // Temporary Evaluation 9654 // 9655 // Temporaries are represented in the AST as rvalues, but generally behave like 9656 // lvalues. The full-object of which the temporary is a subobject is implicitly 9657 // materialized so that a reference can bind to it. 9658 //===----------------------------------------------------------------------===// 9659 namespace { 9660 class TemporaryExprEvaluator 9661 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9662 public: 9663 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9664 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9665 9666 /// Visit an expression which constructs the value of this temporary. 9667 bool VisitConstructExpr(const Expr *E) { 9668 APValue &Value = 9669 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 9670 return EvaluateInPlace(Value, Info, Result, E); 9671 } 9672 9673 bool VisitCastExpr(const CastExpr *E) { 9674 switch (E->getCastKind()) { 9675 default: 9676 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9677 9678 case CK_ConstructorConversion: 9679 return VisitConstructExpr(E->getSubExpr()); 9680 } 9681 } 9682 bool VisitInitListExpr(const InitListExpr *E) { 9683 return VisitConstructExpr(E); 9684 } 9685 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9686 return VisitConstructExpr(E); 9687 } 9688 bool VisitCallExpr(const CallExpr *E) { 9689 return VisitConstructExpr(E); 9690 } 9691 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9692 return VisitConstructExpr(E); 9693 } 9694 bool VisitLambdaExpr(const LambdaExpr *E) { 9695 return VisitConstructExpr(E); 9696 } 9697 }; 9698 } // end anonymous namespace 9699 9700 /// Evaluate an expression of record type as a temporary. 9701 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 9702 assert(E->isRValue() && E->getType()->isRecordType()); 9703 return TemporaryExprEvaluator(Info, Result).Visit(E); 9704 } 9705 9706 //===----------------------------------------------------------------------===// 9707 // Vector Evaluation 9708 //===----------------------------------------------------------------------===// 9709 9710 namespace { 9711 class VectorExprEvaluator 9712 : public ExprEvaluatorBase<VectorExprEvaluator> { 9713 APValue &Result; 9714 public: 9715 9716 VectorExprEvaluator(EvalInfo &info, APValue &Result) 9717 : ExprEvaluatorBaseTy(info), Result(Result) {} 9718 9719 bool Success(ArrayRef<APValue> V, const Expr *E) { 9720 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 9721 // FIXME: remove this APValue copy. 9722 Result = APValue(V.data(), V.size()); 9723 return true; 9724 } 9725 bool Success(const APValue &V, const Expr *E) { 9726 assert(V.isVector()); 9727 Result = V; 9728 return true; 9729 } 9730 bool ZeroInitialization(const Expr *E); 9731 9732 bool VisitUnaryReal(const UnaryOperator *E) 9733 { return Visit(E->getSubExpr()); } 9734 bool VisitCastExpr(const CastExpr* E); 9735 bool VisitInitListExpr(const InitListExpr *E); 9736 bool VisitUnaryImag(const UnaryOperator *E); 9737 bool VisitBinaryOperator(const BinaryOperator *E); 9738 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 9739 // conditional select), shufflevector, ExtVectorElementExpr 9740 }; 9741 } // end anonymous namespace 9742 9743 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 9744 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 9745 return VectorExprEvaluator(Info, Result).Visit(E); 9746 } 9747 9748 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 9749 const VectorType *VTy = E->getType()->castAs<VectorType>(); 9750 unsigned NElts = VTy->getNumElements(); 9751 9752 const Expr *SE = E->getSubExpr(); 9753 QualType SETy = SE->getType(); 9754 9755 switch (E->getCastKind()) { 9756 case CK_VectorSplat: { 9757 APValue Val = APValue(); 9758 if (SETy->isIntegerType()) { 9759 APSInt IntResult; 9760 if (!EvaluateInteger(SE, IntResult, Info)) 9761 return false; 9762 Val = APValue(std::move(IntResult)); 9763 } else if (SETy->isRealFloatingType()) { 9764 APFloat FloatResult(0.0); 9765 if (!EvaluateFloat(SE, FloatResult, Info)) 9766 return false; 9767 Val = APValue(std::move(FloatResult)); 9768 } else { 9769 return Error(E); 9770 } 9771 9772 // Splat and create vector APValue. 9773 SmallVector<APValue, 4> Elts(NElts, Val); 9774 return Success(Elts, E); 9775 } 9776 case CK_BitCast: { 9777 // Evaluate the operand into an APInt we can extract from. 9778 llvm::APInt SValInt; 9779 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 9780 return false; 9781 // Extract the elements 9782 QualType EltTy = VTy->getElementType(); 9783 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 9784 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 9785 SmallVector<APValue, 4> Elts; 9786 if (EltTy->isRealFloatingType()) { 9787 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 9788 unsigned FloatEltSize = EltSize; 9789 if (&Sem == &APFloat::x87DoubleExtended()) 9790 FloatEltSize = 80; 9791 for (unsigned i = 0; i < NElts; i++) { 9792 llvm::APInt Elt; 9793 if (BigEndian) 9794 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 9795 else 9796 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 9797 Elts.push_back(APValue(APFloat(Sem, Elt))); 9798 } 9799 } else if (EltTy->isIntegerType()) { 9800 for (unsigned i = 0; i < NElts; i++) { 9801 llvm::APInt Elt; 9802 if (BigEndian) 9803 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 9804 else 9805 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 9806 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 9807 } 9808 } else { 9809 return Error(E); 9810 } 9811 return Success(Elts, E); 9812 } 9813 default: 9814 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9815 } 9816 } 9817 9818 bool 9819 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9820 const VectorType *VT = E->getType()->castAs<VectorType>(); 9821 unsigned NumInits = E->getNumInits(); 9822 unsigned NumElements = VT->getNumElements(); 9823 9824 QualType EltTy = VT->getElementType(); 9825 SmallVector<APValue, 4> Elements; 9826 9827 // The number of initializers can be less than the number of 9828 // vector elements. For OpenCL, this can be due to nested vector 9829 // initialization. For GCC compatibility, missing trailing elements 9830 // should be initialized with zeroes. 9831 unsigned CountInits = 0, CountElts = 0; 9832 while (CountElts < NumElements) { 9833 // Handle nested vector initialization. 9834 if (CountInits < NumInits 9835 && E->getInit(CountInits)->getType()->isVectorType()) { 9836 APValue v; 9837 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9838 return Error(E); 9839 unsigned vlen = v.getVectorLength(); 9840 for (unsigned j = 0; j < vlen; j++) 9841 Elements.push_back(v.getVectorElt(j)); 9842 CountElts += vlen; 9843 } else if (EltTy->isIntegerType()) { 9844 llvm::APSInt sInt(32); 9845 if (CountInits < NumInits) { 9846 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9847 return false; 9848 } else // trailing integer zero. 9849 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9850 Elements.push_back(APValue(sInt)); 9851 CountElts++; 9852 } else { 9853 llvm::APFloat f(0.0); 9854 if (CountInits < NumInits) { 9855 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9856 return false; 9857 } else // trailing float zero. 9858 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9859 Elements.push_back(APValue(f)); 9860 CountElts++; 9861 } 9862 CountInits++; 9863 } 9864 return Success(Elements, E); 9865 } 9866 9867 bool 9868 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9869 const auto *VT = E->getType()->castAs<VectorType>(); 9870 QualType EltTy = VT->getElementType(); 9871 APValue ZeroElement; 9872 if (EltTy->isIntegerType()) 9873 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 9874 else 9875 ZeroElement = 9876 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 9877 9878 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 9879 return Success(Elements, E); 9880 } 9881 9882 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9883 VisitIgnoredValue(E->getSubExpr()); 9884 return ZeroInitialization(E); 9885 } 9886 9887 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9888 BinaryOperatorKind Op = E->getOpcode(); 9889 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 9890 "Operation not supported on vector types"); 9891 9892 if (Op == BO_Comma) 9893 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9894 9895 Expr *LHS = E->getLHS(); 9896 Expr *RHS = E->getRHS(); 9897 9898 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 9899 "Must both be vector types"); 9900 // Checking JUST the types are the same would be fine, except shifts don't 9901 // need to have their types be the same (since you always shift by an int). 9902 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 9903 E->getType()->getAs<VectorType>()->getNumElements() && 9904 RHS->getType()->getAs<VectorType>()->getNumElements() == 9905 E->getType()->getAs<VectorType>()->getNumElements() && 9906 "All operands must be the same size."); 9907 9908 APValue LHSValue; 9909 APValue RHSValue; 9910 bool LHSOK = Evaluate(LHSValue, Info, LHS); 9911 if (!LHSOK && !Info.noteFailure()) 9912 return false; 9913 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 9914 return false; 9915 9916 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 9917 return false; 9918 9919 return Success(LHSValue, E); 9920 } 9921 9922 //===----------------------------------------------------------------------===// 9923 // Array Evaluation 9924 //===----------------------------------------------------------------------===// 9925 9926 namespace { 9927 class ArrayExprEvaluator 9928 : public ExprEvaluatorBase<ArrayExprEvaluator> { 9929 const LValue &This; 9930 APValue &Result; 9931 public: 9932 9933 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 9934 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 9935 9936 bool Success(const APValue &V, const Expr *E) { 9937 assert(V.isArray() && "expected array"); 9938 Result = V; 9939 return true; 9940 } 9941 9942 bool ZeroInitialization(const Expr *E) { 9943 const ConstantArrayType *CAT = 9944 Info.Ctx.getAsConstantArrayType(E->getType()); 9945 if (!CAT) { 9946 if (E->getType()->isIncompleteArrayType()) { 9947 // We can be asked to zero-initialize a flexible array member; this 9948 // is represented as an ImplicitValueInitExpr of incomplete array 9949 // type. In this case, the array has zero elements. 9950 Result = APValue(APValue::UninitArray(), 0, 0); 9951 return true; 9952 } 9953 // FIXME: We could handle VLAs here. 9954 return Error(E); 9955 } 9956 9957 Result = APValue(APValue::UninitArray(), 0, 9958 CAT->getSize().getZExtValue()); 9959 if (!Result.hasArrayFiller()) return true; 9960 9961 // Zero-initialize all elements. 9962 LValue Subobject = This; 9963 Subobject.addArray(Info, E, CAT); 9964 ImplicitValueInitExpr VIE(CAT->getElementType()); 9965 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 9966 } 9967 9968 bool VisitCallExpr(const CallExpr *E) { 9969 return handleCallExpr(E, Result, &This); 9970 } 9971 bool VisitInitListExpr(const InitListExpr *E, 9972 QualType AllocType = QualType()); 9973 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 9974 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 9975 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 9976 const LValue &Subobject, 9977 APValue *Value, QualType Type); 9978 bool VisitStringLiteral(const StringLiteral *E, 9979 QualType AllocType = QualType()) { 9980 expandStringLiteral(Info, E, Result, AllocType); 9981 return true; 9982 } 9983 }; 9984 } // end anonymous namespace 9985 9986 static bool EvaluateArray(const Expr *E, const LValue &This, 9987 APValue &Result, EvalInfo &Info) { 9988 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 9989 return ArrayExprEvaluator(Info, This, Result).Visit(E); 9990 } 9991 9992 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9993 APValue &Result, const InitListExpr *ILE, 9994 QualType AllocType) { 9995 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 9996 "not an array rvalue"); 9997 return ArrayExprEvaluator(Info, This, Result) 9998 .VisitInitListExpr(ILE, AllocType); 9999 } 10000 10001 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10002 APValue &Result, 10003 const CXXConstructExpr *CCE, 10004 QualType AllocType) { 10005 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10006 "not an array rvalue"); 10007 return ArrayExprEvaluator(Info, This, Result) 10008 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10009 } 10010 10011 // Return true iff the given array filler may depend on the element index. 10012 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10013 // For now, just allow non-class value-initialization and initialization 10014 // lists comprised of them. 10015 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10016 return false; 10017 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10018 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10019 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10020 return true; 10021 } 10022 return false; 10023 } 10024 return true; 10025 } 10026 10027 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10028 QualType AllocType) { 10029 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10030 AllocType.isNull() ? E->getType() : AllocType); 10031 if (!CAT) 10032 return Error(E); 10033 10034 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10035 // an appropriately-typed string literal enclosed in braces. 10036 if (E->isStringLiteralInit()) { 10037 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10038 // FIXME: Support ObjCEncodeExpr here once we support it in 10039 // ArrayExprEvaluator generally. 10040 if (!SL) 10041 return Error(E); 10042 return VisitStringLiteral(SL, AllocType); 10043 } 10044 10045 bool Success = true; 10046 10047 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10048 "zero-initialized array shouldn't have any initialized elts"); 10049 APValue Filler; 10050 if (Result.isArray() && Result.hasArrayFiller()) 10051 Filler = Result.getArrayFiller(); 10052 10053 unsigned NumEltsToInit = E->getNumInits(); 10054 unsigned NumElts = CAT->getSize().getZExtValue(); 10055 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10056 10057 // If the initializer might depend on the array index, run it for each 10058 // array element. 10059 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10060 NumEltsToInit = NumElts; 10061 10062 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10063 << NumEltsToInit << ".\n"); 10064 10065 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10066 10067 // If the array was previously zero-initialized, preserve the 10068 // zero-initialized values. 10069 if (Filler.hasValue()) { 10070 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10071 Result.getArrayInitializedElt(I) = Filler; 10072 if (Result.hasArrayFiller()) 10073 Result.getArrayFiller() = Filler; 10074 } 10075 10076 LValue Subobject = This; 10077 Subobject.addArray(Info, E, CAT); 10078 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10079 const Expr *Init = 10080 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10081 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10082 Info, Subobject, Init) || 10083 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10084 CAT->getElementType(), 1)) { 10085 if (!Info.noteFailure()) 10086 return false; 10087 Success = false; 10088 } 10089 } 10090 10091 if (!Result.hasArrayFiller()) 10092 return Success; 10093 10094 // If we get here, we have a trivial filler, which we can just evaluate 10095 // once and splat over the rest of the array elements. 10096 assert(FillerExpr && "no array filler for incomplete init list"); 10097 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10098 FillerExpr) && Success; 10099 } 10100 10101 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10102 LValue CommonLV; 10103 if (E->getCommonExpr() && 10104 !Evaluate(Info.CurrentCall->createTemporary( 10105 E->getCommonExpr(), 10106 getStorageType(Info.Ctx, E->getCommonExpr()), false, 10107 CommonLV), 10108 Info, E->getCommonExpr()->getSourceExpr())) 10109 return false; 10110 10111 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10112 10113 uint64_t Elements = CAT->getSize().getZExtValue(); 10114 Result = APValue(APValue::UninitArray(), Elements, Elements); 10115 10116 LValue Subobject = This; 10117 Subobject.addArray(Info, E, CAT); 10118 10119 bool Success = true; 10120 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10121 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10122 Info, Subobject, E->getSubExpr()) || 10123 !HandleLValueArrayAdjustment(Info, E, Subobject, 10124 CAT->getElementType(), 1)) { 10125 if (!Info.noteFailure()) 10126 return false; 10127 Success = false; 10128 } 10129 } 10130 10131 return Success; 10132 } 10133 10134 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10135 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10136 } 10137 10138 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10139 const LValue &Subobject, 10140 APValue *Value, 10141 QualType Type) { 10142 bool HadZeroInit = Value->hasValue(); 10143 10144 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10145 unsigned N = CAT->getSize().getZExtValue(); 10146 10147 // Preserve the array filler if we had prior zero-initialization. 10148 APValue Filler = 10149 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10150 : APValue(); 10151 10152 *Value = APValue(APValue::UninitArray(), N, N); 10153 10154 if (HadZeroInit) 10155 for (unsigned I = 0; I != N; ++I) 10156 Value->getArrayInitializedElt(I) = Filler; 10157 10158 // Initialize the elements. 10159 LValue ArrayElt = Subobject; 10160 ArrayElt.addArray(Info, E, CAT); 10161 for (unsigned I = 0; I != N; ++I) 10162 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10163 CAT->getElementType()) || 10164 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10165 CAT->getElementType(), 1)) 10166 return false; 10167 10168 return true; 10169 } 10170 10171 if (!Type->isRecordType()) 10172 return Error(E); 10173 10174 return RecordExprEvaluator(Info, Subobject, *Value) 10175 .VisitCXXConstructExpr(E, Type); 10176 } 10177 10178 //===----------------------------------------------------------------------===// 10179 // Integer Evaluation 10180 // 10181 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10182 // types and back in constant folding. Integer values are thus represented 10183 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10184 //===----------------------------------------------------------------------===// 10185 10186 namespace { 10187 class IntExprEvaluator 10188 : public ExprEvaluatorBase<IntExprEvaluator> { 10189 APValue &Result; 10190 public: 10191 IntExprEvaluator(EvalInfo &info, APValue &result) 10192 : ExprEvaluatorBaseTy(info), Result(result) {} 10193 10194 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10195 assert(E->getType()->isIntegralOrEnumerationType() && 10196 "Invalid evaluation result."); 10197 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10198 "Invalid evaluation result."); 10199 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10200 "Invalid evaluation result."); 10201 Result = APValue(SI); 10202 return true; 10203 } 10204 bool Success(const llvm::APSInt &SI, const Expr *E) { 10205 return Success(SI, E, Result); 10206 } 10207 10208 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10209 assert(E->getType()->isIntegralOrEnumerationType() && 10210 "Invalid evaluation result."); 10211 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10212 "Invalid evaluation result."); 10213 Result = APValue(APSInt(I)); 10214 Result.getInt().setIsUnsigned( 10215 E->getType()->isUnsignedIntegerOrEnumerationType()); 10216 return true; 10217 } 10218 bool Success(const llvm::APInt &I, const Expr *E) { 10219 return Success(I, E, Result); 10220 } 10221 10222 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10223 assert(E->getType()->isIntegralOrEnumerationType() && 10224 "Invalid evaluation result."); 10225 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10226 return true; 10227 } 10228 bool Success(uint64_t Value, const Expr *E) { 10229 return Success(Value, E, Result); 10230 } 10231 10232 bool Success(CharUnits Size, const Expr *E) { 10233 return Success(Size.getQuantity(), E); 10234 } 10235 10236 bool Success(const APValue &V, const Expr *E) { 10237 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10238 Result = V; 10239 return true; 10240 } 10241 return Success(V.getInt(), E); 10242 } 10243 10244 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10245 10246 //===--------------------------------------------------------------------===// 10247 // Visitor Methods 10248 //===--------------------------------------------------------------------===// 10249 10250 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10251 return Success(E->getValue(), E); 10252 } 10253 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10254 return Success(E->getValue(), E); 10255 } 10256 10257 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10258 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10259 if (CheckReferencedDecl(E, E->getDecl())) 10260 return true; 10261 10262 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10263 } 10264 bool VisitMemberExpr(const MemberExpr *E) { 10265 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10266 VisitIgnoredBaseExpression(E->getBase()); 10267 return true; 10268 } 10269 10270 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10271 } 10272 10273 bool VisitCallExpr(const CallExpr *E); 10274 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10275 bool VisitBinaryOperator(const BinaryOperator *E); 10276 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10277 bool VisitUnaryOperator(const UnaryOperator *E); 10278 10279 bool VisitCastExpr(const CastExpr* E); 10280 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10281 10282 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10283 return Success(E->getValue(), E); 10284 } 10285 10286 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10287 return Success(E->getValue(), E); 10288 } 10289 10290 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10291 if (Info.ArrayInitIndex == uint64_t(-1)) { 10292 // We were asked to evaluate this subexpression independent of the 10293 // enclosing ArrayInitLoopExpr. We can't do that. 10294 Info.FFDiag(E); 10295 return false; 10296 } 10297 return Success(Info.ArrayInitIndex, E); 10298 } 10299 10300 // Note, GNU defines __null as an integer, not a pointer. 10301 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10302 return ZeroInitialization(E); 10303 } 10304 10305 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10306 return Success(E->getValue(), E); 10307 } 10308 10309 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10310 return Success(E->getValue(), E); 10311 } 10312 10313 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10314 return Success(E->getValue(), E); 10315 } 10316 10317 bool VisitUnaryReal(const UnaryOperator *E); 10318 bool VisitUnaryImag(const UnaryOperator *E); 10319 10320 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10321 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10322 bool VisitSourceLocExpr(const SourceLocExpr *E); 10323 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10324 bool VisitRequiresExpr(const RequiresExpr *E); 10325 // FIXME: Missing: array subscript of vector, member of vector 10326 }; 10327 10328 class FixedPointExprEvaluator 10329 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10330 APValue &Result; 10331 10332 public: 10333 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10334 : ExprEvaluatorBaseTy(info), Result(result) {} 10335 10336 bool Success(const llvm::APInt &I, const Expr *E) { 10337 return Success( 10338 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10339 } 10340 10341 bool Success(uint64_t Value, const Expr *E) { 10342 return Success( 10343 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10344 } 10345 10346 bool Success(const APValue &V, const Expr *E) { 10347 return Success(V.getFixedPoint(), E); 10348 } 10349 10350 bool Success(const APFixedPoint &V, const Expr *E) { 10351 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10352 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10353 "Invalid evaluation result."); 10354 Result = APValue(V); 10355 return true; 10356 } 10357 10358 //===--------------------------------------------------------------------===// 10359 // Visitor Methods 10360 //===--------------------------------------------------------------------===// 10361 10362 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10363 return Success(E->getValue(), E); 10364 } 10365 10366 bool VisitCastExpr(const CastExpr *E); 10367 bool VisitUnaryOperator(const UnaryOperator *E); 10368 bool VisitBinaryOperator(const BinaryOperator *E); 10369 }; 10370 } // end anonymous namespace 10371 10372 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10373 /// produce either the integer value or a pointer. 10374 /// 10375 /// GCC has a heinous extension which folds casts between pointer types and 10376 /// pointer-sized integral types. We support this by allowing the evaluation of 10377 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10378 /// Some simple arithmetic on such values is supported (they are treated much 10379 /// like char*). 10380 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10381 EvalInfo &Info) { 10382 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10383 return IntExprEvaluator(Info, Result).Visit(E); 10384 } 10385 10386 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10387 APValue Val; 10388 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10389 return false; 10390 if (!Val.isInt()) { 10391 // FIXME: It would be better to produce the diagnostic for casting 10392 // a pointer to an integer. 10393 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10394 return false; 10395 } 10396 Result = Val.getInt(); 10397 return true; 10398 } 10399 10400 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10401 APValue Evaluated = E->EvaluateInContext( 10402 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10403 return Success(Evaluated, E); 10404 } 10405 10406 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10407 EvalInfo &Info) { 10408 if (E->getType()->isFixedPointType()) { 10409 APValue Val; 10410 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10411 return false; 10412 if (!Val.isFixedPoint()) 10413 return false; 10414 10415 Result = Val.getFixedPoint(); 10416 return true; 10417 } 10418 return false; 10419 } 10420 10421 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10422 EvalInfo &Info) { 10423 if (E->getType()->isIntegerType()) { 10424 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10425 APSInt Val; 10426 if (!EvaluateInteger(E, Val, Info)) 10427 return false; 10428 Result = APFixedPoint(Val, FXSema); 10429 return true; 10430 } else if (E->getType()->isFixedPointType()) { 10431 return EvaluateFixedPoint(E, Result, Info); 10432 } 10433 return false; 10434 } 10435 10436 /// Check whether the given declaration can be directly converted to an integral 10437 /// rvalue. If not, no diagnostic is produced; there are other things we can 10438 /// try. 10439 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10440 // Enums are integer constant exprs. 10441 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10442 // Check for signedness/width mismatches between E type and ECD value. 10443 bool SameSign = (ECD->getInitVal().isSigned() 10444 == E->getType()->isSignedIntegerOrEnumerationType()); 10445 bool SameWidth = (ECD->getInitVal().getBitWidth() 10446 == Info.Ctx.getIntWidth(E->getType())); 10447 if (SameSign && SameWidth) 10448 return Success(ECD->getInitVal(), E); 10449 else { 10450 // Get rid of mismatch (otherwise Success assertions will fail) 10451 // by computing a new value matching the type of E. 10452 llvm::APSInt Val = ECD->getInitVal(); 10453 if (!SameSign) 10454 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10455 if (!SameWidth) 10456 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10457 return Success(Val, E); 10458 } 10459 } 10460 return false; 10461 } 10462 10463 /// Values returned by __builtin_classify_type, chosen to match the values 10464 /// produced by GCC's builtin. 10465 enum class GCCTypeClass { 10466 None = -1, 10467 Void = 0, 10468 Integer = 1, 10469 // GCC reserves 2 for character types, but instead classifies them as 10470 // integers. 10471 Enum = 3, 10472 Bool = 4, 10473 Pointer = 5, 10474 // GCC reserves 6 for references, but appears to never use it (because 10475 // expressions never have reference type, presumably). 10476 PointerToDataMember = 7, 10477 RealFloat = 8, 10478 Complex = 9, 10479 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10480 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10481 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10482 // uses 12 for that purpose, same as for a class or struct. Maybe it 10483 // internally implements a pointer to member as a struct? Who knows. 10484 PointerToMemberFunction = 12, // Not a bug, see above. 10485 ClassOrStruct = 12, 10486 Union = 13, 10487 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10488 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10489 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10490 // literals. 10491 }; 10492 10493 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10494 /// as GCC. 10495 static GCCTypeClass 10496 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10497 assert(!T->isDependentType() && "unexpected dependent type"); 10498 10499 QualType CanTy = T.getCanonicalType(); 10500 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10501 10502 switch (CanTy->getTypeClass()) { 10503 #define TYPE(ID, BASE) 10504 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10505 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10506 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10507 #include "clang/AST/TypeNodes.inc" 10508 case Type::Auto: 10509 case Type::DeducedTemplateSpecialization: 10510 llvm_unreachable("unexpected non-canonical or dependent type"); 10511 10512 case Type::Builtin: 10513 switch (BT->getKind()) { 10514 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10515 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10516 case BuiltinType::ID: return GCCTypeClass::Integer; 10517 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10518 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10519 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10520 case BuiltinType::ID: break; 10521 #include "clang/AST/BuiltinTypes.def" 10522 case BuiltinType::Void: 10523 return GCCTypeClass::Void; 10524 10525 case BuiltinType::Bool: 10526 return GCCTypeClass::Bool; 10527 10528 case BuiltinType::Char_U: 10529 case BuiltinType::UChar: 10530 case BuiltinType::WChar_U: 10531 case BuiltinType::Char8: 10532 case BuiltinType::Char16: 10533 case BuiltinType::Char32: 10534 case BuiltinType::UShort: 10535 case BuiltinType::UInt: 10536 case BuiltinType::ULong: 10537 case BuiltinType::ULongLong: 10538 case BuiltinType::UInt128: 10539 return GCCTypeClass::Integer; 10540 10541 case BuiltinType::UShortAccum: 10542 case BuiltinType::UAccum: 10543 case BuiltinType::ULongAccum: 10544 case BuiltinType::UShortFract: 10545 case BuiltinType::UFract: 10546 case BuiltinType::ULongFract: 10547 case BuiltinType::SatUShortAccum: 10548 case BuiltinType::SatUAccum: 10549 case BuiltinType::SatULongAccum: 10550 case BuiltinType::SatUShortFract: 10551 case BuiltinType::SatUFract: 10552 case BuiltinType::SatULongFract: 10553 return GCCTypeClass::None; 10554 10555 case BuiltinType::NullPtr: 10556 10557 case BuiltinType::ObjCId: 10558 case BuiltinType::ObjCClass: 10559 case BuiltinType::ObjCSel: 10560 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10561 case BuiltinType::Id: 10562 #include "clang/Basic/OpenCLImageTypes.def" 10563 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10564 case BuiltinType::Id: 10565 #include "clang/Basic/OpenCLExtensionTypes.def" 10566 case BuiltinType::OCLSampler: 10567 case BuiltinType::OCLEvent: 10568 case BuiltinType::OCLClkEvent: 10569 case BuiltinType::OCLQueue: 10570 case BuiltinType::OCLReserveID: 10571 #define SVE_TYPE(Name, Id, SingletonId) \ 10572 case BuiltinType::Id: 10573 #include "clang/Basic/AArch64SVEACLETypes.def" 10574 return GCCTypeClass::None; 10575 10576 case BuiltinType::Dependent: 10577 llvm_unreachable("unexpected dependent type"); 10578 }; 10579 llvm_unreachable("unexpected placeholder type"); 10580 10581 case Type::Enum: 10582 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10583 10584 case Type::Pointer: 10585 case Type::ConstantArray: 10586 case Type::VariableArray: 10587 case Type::IncompleteArray: 10588 case Type::FunctionNoProto: 10589 case Type::FunctionProto: 10590 return GCCTypeClass::Pointer; 10591 10592 case Type::MemberPointer: 10593 return CanTy->isMemberDataPointerType() 10594 ? GCCTypeClass::PointerToDataMember 10595 : GCCTypeClass::PointerToMemberFunction; 10596 10597 case Type::Complex: 10598 return GCCTypeClass::Complex; 10599 10600 case Type::Record: 10601 return CanTy->isUnionType() ? GCCTypeClass::Union 10602 : GCCTypeClass::ClassOrStruct; 10603 10604 case Type::Atomic: 10605 // GCC classifies _Atomic T the same as T. 10606 return EvaluateBuiltinClassifyType( 10607 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10608 10609 case Type::BlockPointer: 10610 case Type::Vector: 10611 case Type::ExtVector: 10612 case Type::ConstantMatrix: 10613 case Type::ObjCObject: 10614 case Type::ObjCInterface: 10615 case Type::ObjCObjectPointer: 10616 case Type::Pipe: 10617 case Type::ExtInt: 10618 // GCC classifies vectors as None. We follow its lead and classify all 10619 // other types that don't fit into the regular classification the same way. 10620 return GCCTypeClass::None; 10621 10622 case Type::LValueReference: 10623 case Type::RValueReference: 10624 llvm_unreachable("invalid type for expression"); 10625 } 10626 10627 llvm_unreachable("unexpected type class"); 10628 } 10629 10630 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10631 /// as GCC. 10632 static GCCTypeClass 10633 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10634 // If no argument was supplied, default to None. This isn't 10635 // ideal, however it is what gcc does. 10636 if (E->getNumArgs() == 0) 10637 return GCCTypeClass::None; 10638 10639 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10640 // being an ICE, but still folds it to a constant using the type of the first 10641 // argument. 10642 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10643 } 10644 10645 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10646 /// __builtin_constant_p when applied to the given pointer. 10647 /// 10648 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10649 /// or it points to the first character of a string literal. 10650 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10651 APValue::LValueBase Base = LV.getLValueBase(); 10652 if (Base.isNull()) { 10653 // A null base is acceptable. 10654 return true; 10655 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10656 if (!isa<StringLiteral>(E)) 10657 return false; 10658 return LV.getLValueOffset().isZero(); 10659 } else if (Base.is<TypeInfoLValue>()) { 10660 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10661 // evaluate to true. 10662 return true; 10663 } else { 10664 // Any other base is not constant enough for GCC. 10665 return false; 10666 } 10667 } 10668 10669 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10670 /// GCC as we can manage. 10671 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10672 // This evaluation is not permitted to have side-effects, so evaluate it in 10673 // a speculative evaluation context. 10674 SpeculativeEvaluationRAII SpeculativeEval(Info); 10675 10676 // Constant-folding is always enabled for the operand of __builtin_constant_p 10677 // (even when the enclosing evaluation context otherwise requires a strict 10678 // language-specific constant expression). 10679 FoldConstant Fold(Info, true); 10680 10681 QualType ArgType = Arg->getType(); 10682 10683 // __builtin_constant_p always has one operand. The rules which gcc follows 10684 // are not precisely documented, but are as follows: 10685 // 10686 // - If the operand is of integral, floating, complex or enumeration type, 10687 // and can be folded to a known value of that type, it returns 1. 10688 // - If the operand can be folded to a pointer to the first character 10689 // of a string literal (or such a pointer cast to an integral type) 10690 // or to a null pointer or an integer cast to a pointer, it returns 1. 10691 // 10692 // Otherwise, it returns 0. 10693 // 10694 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10695 // its support for this did not work prior to GCC 9 and is not yet well 10696 // understood. 10697 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10698 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10699 ArgType->isNullPtrType()) { 10700 APValue V; 10701 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 10702 Fold.keepDiagnostics(); 10703 return false; 10704 } 10705 10706 // For a pointer (possibly cast to integer), there are special rules. 10707 if (V.getKind() == APValue::LValue) 10708 return EvaluateBuiltinConstantPForLValue(V); 10709 10710 // Otherwise, any constant value is good enough. 10711 return V.hasValue(); 10712 } 10713 10714 // Anything else isn't considered to be sufficiently constant. 10715 return false; 10716 } 10717 10718 /// Retrieves the "underlying object type" of the given expression, 10719 /// as used by __builtin_object_size. 10720 static QualType getObjectType(APValue::LValueBase B) { 10721 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 10722 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 10723 return VD->getType(); 10724 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 10725 if (isa<CompoundLiteralExpr>(E)) 10726 return E->getType(); 10727 } else if (B.is<TypeInfoLValue>()) { 10728 return B.getTypeInfoType(); 10729 } else if (B.is<DynamicAllocLValue>()) { 10730 return B.getDynamicAllocType(); 10731 } 10732 10733 return QualType(); 10734 } 10735 10736 /// A more selective version of E->IgnoreParenCasts for 10737 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 10738 /// to change the type of E. 10739 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 10740 /// 10741 /// Always returns an RValue with a pointer representation. 10742 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 10743 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 10744 10745 auto *NoParens = E->IgnoreParens(); 10746 auto *Cast = dyn_cast<CastExpr>(NoParens); 10747 if (Cast == nullptr) 10748 return NoParens; 10749 10750 // We only conservatively allow a few kinds of casts, because this code is 10751 // inherently a simple solution that seeks to support the common case. 10752 auto CastKind = Cast->getCastKind(); 10753 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 10754 CastKind != CK_AddressSpaceConversion) 10755 return NoParens; 10756 10757 auto *SubExpr = Cast->getSubExpr(); 10758 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 10759 return NoParens; 10760 return ignorePointerCastsAndParens(SubExpr); 10761 } 10762 10763 /// Checks to see if the given LValue's Designator is at the end of the LValue's 10764 /// record layout. e.g. 10765 /// struct { struct { int a, b; } fst, snd; } obj; 10766 /// obj.fst // no 10767 /// obj.snd // yes 10768 /// obj.fst.a // no 10769 /// obj.fst.b // no 10770 /// obj.snd.a // no 10771 /// obj.snd.b // yes 10772 /// 10773 /// Please note: this function is specialized for how __builtin_object_size 10774 /// views "objects". 10775 /// 10776 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 10777 /// correct result, it will always return true. 10778 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 10779 assert(!LVal.Designator.Invalid); 10780 10781 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 10782 const RecordDecl *Parent = FD->getParent(); 10783 Invalid = Parent->isInvalidDecl(); 10784 if (Invalid || Parent->isUnion()) 10785 return true; 10786 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 10787 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 10788 }; 10789 10790 auto &Base = LVal.getLValueBase(); 10791 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 10792 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 10793 bool Invalid; 10794 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10795 return Invalid; 10796 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 10797 for (auto *FD : IFD->chain()) { 10798 bool Invalid; 10799 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 10800 return Invalid; 10801 } 10802 } 10803 } 10804 10805 unsigned I = 0; 10806 QualType BaseType = getType(Base); 10807 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 10808 // If we don't know the array bound, conservatively assume we're looking at 10809 // the final array element. 10810 ++I; 10811 if (BaseType->isIncompleteArrayType()) 10812 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 10813 else 10814 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 10815 } 10816 10817 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 10818 const auto &Entry = LVal.Designator.Entries[I]; 10819 if (BaseType->isArrayType()) { 10820 // Because __builtin_object_size treats arrays as objects, we can ignore 10821 // the index iff this is the last array in the Designator. 10822 if (I + 1 == E) 10823 return true; 10824 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 10825 uint64_t Index = Entry.getAsArrayIndex(); 10826 if (Index + 1 != CAT->getSize()) 10827 return false; 10828 BaseType = CAT->getElementType(); 10829 } else if (BaseType->isAnyComplexType()) { 10830 const auto *CT = BaseType->castAs<ComplexType>(); 10831 uint64_t Index = Entry.getAsArrayIndex(); 10832 if (Index != 1) 10833 return false; 10834 BaseType = CT->getElementType(); 10835 } else if (auto *FD = getAsField(Entry)) { 10836 bool Invalid; 10837 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10838 return Invalid; 10839 BaseType = FD->getType(); 10840 } else { 10841 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 10842 return false; 10843 } 10844 } 10845 return true; 10846 } 10847 10848 /// Tests to see if the LValue has a user-specified designator (that isn't 10849 /// necessarily valid). Note that this always returns 'true' if the LValue has 10850 /// an unsized array as its first designator entry, because there's currently no 10851 /// way to tell if the user typed *foo or foo[0]. 10852 static bool refersToCompleteObject(const LValue &LVal) { 10853 if (LVal.Designator.Invalid) 10854 return false; 10855 10856 if (!LVal.Designator.Entries.empty()) 10857 return LVal.Designator.isMostDerivedAnUnsizedArray(); 10858 10859 if (!LVal.InvalidBase) 10860 return true; 10861 10862 // If `E` is a MemberExpr, then the first part of the designator is hiding in 10863 // the LValueBase. 10864 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 10865 return !E || !isa<MemberExpr>(E); 10866 } 10867 10868 /// Attempts to detect a user writing into a piece of memory that's impossible 10869 /// to figure out the size of by just using types. 10870 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 10871 const SubobjectDesignator &Designator = LVal.Designator; 10872 // Notes: 10873 // - Users can only write off of the end when we have an invalid base. Invalid 10874 // bases imply we don't know where the memory came from. 10875 // - We used to be a bit more aggressive here; we'd only be conservative if 10876 // the array at the end was flexible, or if it had 0 or 1 elements. This 10877 // broke some common standard library extensions (PR30346), but was 10878 // otherwise seemingly fine. It may be useful to reintroduce this behavior 10879 // with some sort of list. OTOH, it seems that GCC is always 10880 // conservative with the last element in structs (if it's an array), so our 10881 // current behavior is more compatible than an explicit list approach would 10882 // be. 10883 return LVal.InvalidBase && 10884 Designator.Entries.size() == Designator.MostDerivedPathLength && 10885 Designator.MostDerivedIsArrayElement && 10886 isDesignatorAtObjectEnd(Ctx, LVal); 10887 } 10888 10889 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 10890 /// Fails if the conversion would cause loss of precision. 10891 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 10892 CharUnits &Result) { 10893 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 10894 if (Int.ugt(CharUnitsMax)) 10895 return false; 10896 Result = CharUnits::fromQuantity(Int.getZExtValue()); 10897 return true; 10898 } 10899 10900 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 10901 /// determine how many bytes exist from the beginning of the object to either 10902 /// the end of the current subobject, or the end of the object itself, depending 10903 /// on what the LValue looks like + the value of Type. 10904 /// 10905 /// If this returns false, the value of Result is undefined. 10906 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 10907 unsigned Type, const LValue &LVal, 10908 CharUnits &EndOffset) { 10909 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 10910 10911 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 10912 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 10913 return false; 10914 return HandleSizeof(Info, ExprLoc, Ty, Result); 10915 }; 10916 10917 // We want to evaluate the size of the entire object. This is a valid fallback 10918 // for when Type=1 and the designator is invalid, because we're asked for an 10919 // upper-bound. 10920 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 10921 // Type=3 wants a lower bound, so we can't fall back to this. 10922 if (Type == 3 && !DetermineForCompleteObject) 10923 return false; 10924 10925 llvm::APInt APEndOffset; 10926 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10927 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10928 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10929 10930 if (LVal.InvalidBase) 10931 return false; 10932 10933 QualType BaseTy = getObjectType(LVal.getLValueBase()); 10934 return CheckedHandleSizeof(BaseTy, EndOffset); 10935 } 10936 10937 // We want to evaluate the size of a subobject. 10938 const SubobjectDesignator &Designator = LVal.Designator; 10939 10940 // The following is a moderately common idiom in C: 10941 // 10942 // struct Foo { int a; char c[1]; }; 10943 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 10944 // strcpy(&F->c[0], Bar); 10945 // 10946 // In order to not break too much legacy code, we need to support it. 10947 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 10948 // If we can resolve this to an alloc_size call, we can hand that back, 10949 // because we know for certain how many bytes there are to write to. 10950 llvm::APInt APEndOffset; 10951 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10952 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10953 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10954 10955 // If we cannot determine the size of the initial allocation, then we can't 10956 // given an accurate upper-bound. However, we are still able to give 10957 // conservative lower-bounds for Type=3. 10958 if (Type == 1) 10959 return false; 10960 } 10961 10962 CharUnits BytesPerElem; 10963 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 10964 return false; 10965 10966 // According to the GCC documentation, we want the size of the subobject 10967 // denoted by the pointer. But that's not quite right -- what we actually 10968 // want is the size of the immediately-enclosing array, if there is one. 10969 int64_t ElemsRemaining; 10970 if (Designator.MostDerivedIsArrayElement && 10971 Designator.Entries.size() == Designator.MostDerivedPathLength) { 10972 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 10973 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 10974 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 10975 } else { 10976 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 10977 } 10978 10979 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 10980 return true; 10981 } 10982 10983 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 10984 /// returns true and stores the result in @p Size. 10985 /// 10986 /// If @p WasError is non-null, this will report whether the failure to evaluate 10987 /// is to be treated as an Error in IntExprEvaluator. 10988 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 10989 EvalInfo &Info, uint64_t &Size) { 10990 // Determine the denoted object. 10991 LValue LVal; 10992 { 10993 // The operand of __builtin_object_size is never evaluated for side-effects. 10994 // If there are any, but we can determine the pointed-to object anyway, then 10995 // ignore the side-effects. 10996 SpeculativeEvaluationRAII SpeculativeEval(Info); 10997 IgnoreSideEffectsRAII Fold(Info); 10998 10999 if (E->isGLValue()) { 11000 // It's possible for us to be given GLValues if we're called via 11001 // Expr::tryEvaluateObjectSize. 11002 APValue RVal; 11003 if (!EvaluateAsRValue(Info, E, RVal)) 11004 return false; 11005 LVal.setFrom(Info.Ctx, RVal); 11006 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11007 /*InvalidBaseOK=*/true)) 11008 return false; 11009 } 11010 11011 // If we point to before the start of the object, there are no accessible 11012 // bytes. 11013 if (LVal.getLValueOffset().isNegative()) { 11014 Size = 0; 11015 return true; 11016 } 11017 11018 CharUnits EndOffset; 11019 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11020 return false; 11021 11022 // If we've fallen outside of the end offset, just pretend there's nothing to 11023 // write to/read from. 11024 if (EndOffset <= LVal.getLValueOffset()) 11025 Size = 0; 11026 else 11027 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11028 return true; 11029 } 11030 11031 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11032 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11033 return VisitBuiltinCallExpr(E, BuiltinOp); 11034 11035 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11036 } 11037 11038 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11039 APValue &Val, APSInt &Alignment) { 11040 QualType SrcTy = E->getArg(0)->getType(); 11041 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11042 return false; 11043 // Even though we are evaluating integer expressions we could get a pointer 11044 // argument for the __builtin_is_aligned() case. 11045 if (SrcTy->isPointerType()) { 11046 LValue Ptr; 11047 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11048 return false; 11049 Ptr.moveInto(Val); 11050 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11051 Info.FFDiag(E->getArg(0)); 11052 return false; 11053 } else { 11054 APSInt SrcInt; 11055 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11056 return false; 11057 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11058 "Bit widths must be the same"); 11059 Val = APValue(SrcInt); 11060 } 11061 assert(Val.hasValue()); 11062 return true; 11063 } 11064 11065 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11066 unsigned BuiltinOp) { 11067 switch (BuiltinOp) { 11068 default: 11069 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11070 11071 case Builtin::BI__builtin_dynamic_object_size: 11072 case Builtin::BI__builtin_object_size: { 11073 // The type was checked when we built the expression. 11074 unsigned Type = 11075 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11076 assert(Type <= 3 && "unexpected type"); 11077 11078 uint64_t Size; 11079 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11080 return Success(Size, E); 11081 11082 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11083 return Success((Type & 2) ? 0 : -1, E); 11084 11085 // Expression had no side effects, but we couldn't statically determine the 11086 // size of the referenced object. 11087 switch (Info.EvalMode) { 11088 case EvalInfo::EM_ConstantExpression: 11089 case EvalInfo::EM_ConstantFold: 11090 case EvalInfo::EM_IgnoreSideEffects: 11091 // Leave it to IR generation. 11092 return Error(E); 11093 case EvalInfo::EM_ConstantExpressionUnevaluated: 11094 // Reduce it to a constant now. 11095 return Success((Type & 2) ? 0 : -1, E); 11096 } 11097 11098 llvm_unreachable("unexpected EvalMode"); 11099 } 11100 11101 case Builtin::BI__builtin_os_log_format_buffer_size: { 11102 analyze_os_log::OSLogBufferLayout Layout; 11103 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11104 return Success(Layout.size().getQuantity(), E); 11105 } 11106 11107 case Builtin::BI__builtin_is_aligned: { 11108 APValue Src; 11109 APSInt Alignment; 11110 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11111 return false; 11112 if (Src.isLValue()) { 11113 // If we evaluated a pointer, check the minimum known alignment. 11114 LValue Ptr; 11115 Ptr.setFrom(Info.Ctx, Src); 11116 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11117 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11118 // We can return true if the known alignment at the computed offset is 11119 // greater than the requested alignment. 11120 assert(PtrAlign.isPowerOfTwo()); 11121 assert(Alignment.isPowerOf2()); 11122 if (PtrAlign.getQuantity() >= Alignment) 11123 return Success(1, E); 11124 // If the alignment is not known to be sufficient, some cases could still 11125 // be aligned at run time. However, if the requested alignment is less or 11126 // equal to the base alignment and the offset is not aligned, we know that 11127 // the run-time value can never be aligned. 11128 if (BaseAlignment.getQuantity() >= Alignment && 11129 PtrAlign.getQuantity() < Alignment) 11130 return Success(0, E); 11131 // Otherwise we can't infer whether the value is sufficiently aligned. 11132 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11133 // in cases where we can't fully evaluate the pointer. 11134 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11135 << Alignment; 11136 return false; 11137 } 11138 assert(Src.isInt()); 11139 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11140 } 11141 case Builtin::BI__builtin_align_up: { 11142 APValue Src; 11143 APSInt Alignment; 11144 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11145 return false; 11146 if (!Src.isInt()) 11147 return Error(E); 11148 APSInt AlignedVal = 11149 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11150 Src.getInt().isUnsigned()); 11151 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11152 return Success(AlignedVal, E); 11153 } 11154 case Builtin::BI__builtin_align_down: { 11155 APValue Src; 11156 APSInt Alignment; 11157 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11158 return false; 11159 if (!Src.isInt()) 11160 return Error(E); 11161 APSInt AlignedVal = 11162 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11163 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11164 return Success(AlignedVal, E); 11165 } 11166 11167 case Builtin::BI__builtin_bswap16: 11168 case Builtin::BI__builtin_bswap32: 11169 case Builtin::BI__builtin_bswap64: { 11170 APSInt Val; 11171 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11172 return false; 11173 11174 return Success(Val.byteSwap(), E); 11175 } 11176 11177 case Builtin::BI__builtin_classify_type: 11178 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11179 11180 case Builtin::BI__builtin_clrsb: 11181 case Builtin::BI__builtin_clrsbl: 11182 case Builtin::BI__builtin_clrsbll: { 11183 APSInt Val; 11184 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11185 return false; 11186 11187 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11188 } 11189 11190 case Builtin::BI__builtin_clz: 11191 case Builtin::BI__builtin_clzl: 11192 case Builtin::BI__builtin_clzll: 11193 case Builtin::BI__builtin_clzs: { 11194 APSInt Val; 11195 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11196 return false; 11197 if (!Val) 11198 return Error(E); 11199 11200 return Success(Val.countLeadingZeros(), E); 11201 } 11202 11203 case Builtin::BI__builtin_constant_p: { 11204 const Expr *Arg = E->getArg(0); 11205 if (EvaluateBuiltinConstantP(Info, Arg)) 11206 return Success(true, E); 11207 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11208 // Outside a constant context, eagerly evaluate to false in the presence 11209 // of side-effects in order to avoid -Wunsequenced false-positives in 11210 // a branch on __builtin_constant_p(expr). 11211 return Success(false, E); 11212 } 11213 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11214 return false; 11215 } 11216 11217 case Builtin::BI__builtin_is_constant_evaluated: { 11218 const auto *Callee = Info.CurrentCall->getCallee(); 11219 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11220 (Info.CallStackDepth == 1 || 11221 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11222 Callee->getIdentifier() && 11223 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11224 // FIXME: Find a better way to avoid duplicated diagnostics. 11225 if (Info.EvalStatus.Diag) 11226 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11227 : Info.CurrentCall->CallLoc, 11228 diag::warn_is_constant_evaluated_always_true_constexpr) 11229 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11230 : "std::is_constant_evaluated"); 11231 } 11232 11233 return Success(Info.InConstantContext, E); 11234 } 11235 11236 case Builtin::BI__builtin_ctz: 11237 case Builtin::BI__builtin_ctzl: 11238 case Builtin::BI__builtin_ctzll: 11239 case Builtin::BI__builtin_ctzs: { 11240 APSInt Val; 11241 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11242 return false; 11243 if (!Val) 11244 return Error(E); 11245 11246 return Success(Val.countTrailingZeros(), E); 11247 } 11248 11249 case Builtin::BI__builtin_eh_return_data_regno: { 11250 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11251 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11252 return Success(Operand, E); 11253 } 11254 11255 case Builtin::BI__builtin_expect: 11256 case Builtin::BI__builtin_expect_with_probability: 11257 return Visit(E->getArg(0)); 11258 11259 case Builtin::BI__builtin_ffs: 11260 case Builtin::BI__builtin_ffsl: 11261 case Builtin::BI__builtin_ffsll: { 11262 APSInt Val; 11263 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11264 return false; 11265 11266 unsigned N = Val.countTrailingZeros(); 11267 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11268 } 11269 11270 case Builtin::BI__builtin_fpclassify: { 11271 APFloat Val(0.0); 11272 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11273 return false; 11274 unsigned Arg; 11275 switch (Val.getCategory()) { 11276 case APFloat::fcNaN: Arg = 0; break; 11277 case APFloat::fcInfinity: Arg = 1; break; 11278 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11279 case APFloat::fcZero: Arg = 4; break; 11280 } 11281 return Visit(E->getArg(Arg)); 11282 } 11283 11284 case Builtin::BI__builtin_isinf_sign: { 11285 APFloat Val(0.0); 11286 return EvaluateFloat(E->getArg(0), Val, Info) && 11287 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11288 } 11289 11290 case Builtin::BI__builtin_isinf: { 11291 APFloat Val(0.0); 11292 return EvaluateFloat(E->getArg(0), Val, Info) && 11293 Success(Val.isInfinity() ? 1 : 0, E); 11294 } 11295 11296 case Builtin::BI__builtin_isfinite: { 11297 APFloat Val(0.0); 11298 return EvaluateFloat(E->getArg(0), Val, Info) && 11299 Success(Val.isFinite() ? 1 : 0, E); 11300 } 11301 11302 case Builtin::BI__builtin_isnan: { 11303 APFloat Val(0.0); 11304 return EvaluateFloat(E->getArg(0), Val, Info) && 11305 Success(Val.isNaN() ? 1 : 0, E); 11306 } 11307 11308 case Builtin::BI__builtin_isnormal: { 11309 APFloat Val(0.0); 11310 return EvaluateFloat(E->getArg(0), Val, Info) && 11311 Success(Val.isNormal() ? 1 : 0, E); 11312 } 11313 11314 case Builtin::BI__builtin_parity: 11315 case Builtin::BI__builtin_parityl: 11316 case Builtin::BI__builtin_parityll: { 11317 APSInt Val; 11318 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11319 return false; 11320 11321 return Success(Val.countPopulation() % 2, E); 11322 } 11323 11324 case Builtin::BI__builtin_popcount: 11325 case Builtin::BI__builtin_popcountl: 11326 case Builtin::BI__builtin_popcountll: { 11327 APSInt Val; 11328 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11329 return false; 11330 11331 return Success(Val.countPopulation(), E); 11332 } 11333 11334 case Builtin::BIstrlen: 11335 case Builtin::BIwcslen: 11336 // A call to strlen is not a constant expression. 11337 if (Info.getLangOpts().CPlusPlus11) 11338 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11339 << /*isConstexpr*/0 << /*isConstructor*/0 11340 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11341 else 11342 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11343 LLVM_FALLTHROUGH; 11344 case Builtin::BI__builtin_strlen: 11345 case Builtin::BI__builtin_wcslen: { 11346 // As an extension, we support __builtin_strlen() as a constant expression, 11347 // and support folding strlen() to a constant. 11348 LValue String; 11349 if (!EvaluatePointer(E->getArg(0), String, Info)) 11350 return false; 11351 11352 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11353 11354 // Fast path: if it's a string literal, search the string value. 11355 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11356 String.getLValueBase().dyn_cast<const Expr *>())) { 11357 // The string literal may have embedded null characters. Find the first 11358 // one and truncate there. 11359 StringRef Str = S->getBytes(); 11360 int64_t Off = String.Offset.getQuantity(); 11361 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11362 S->getCharByteWidth() == 1 && 11363 // FIXME: Add fast-path for wchar_t too. 11364 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11365 Str = Str.substr(Off); 11366 11367 StringRef::size_type Pos = Str.find(0); 11368 if (Pos != StringRef::npos) 11369 Str = Str.substr(0, Pos); 11370 11371 return Success(Str.size(), E); 11372 } 11373 11374 // Fall through to slow path to issue appropriate diagnostic. 11375 } 11376 11377 // Slow path: scan the bytes of the string looking for the terminating 0. 11378 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11379 APValue Char; 11380 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11381 !Char.isInt()) 11382 return false; 11383 if (!Char.getInt()) 11384 return Success(Strlen, E); 11385 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11386 return false; 11387 } 11388 } 11389 11390 case Builtin::BIstrcmp: 11391 case Builtin::BIwcscmp: 11392 case Builtin::BIstrncmp: 11393 case Builtin::BIwcsncmp: 11394 case Builtin::BImemcmp: 11395 case Builtin::BIbcmp: 11396 case Builtin::BIwmemcmp: 11397 // A call to strlen is not a constant expression. 11398 if (Info.getLangOpts().CPlusPlus11) 11399 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11400 << /*isConstexpr*/0 << /*isConstructor*/0 11401 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11402 else 11403 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11404 LLVM_FALLTHROUGH; 11405 case Builtin::BI__builtin_strcmp: 11406 case Builtin::BI__builtin_wcscmp: 11407 case Builtin::BI__builtin_strncmp: 11408 case Builtin::BI__builtin_wcsncmp: 11409 case Builtin::BI__builtin_memcmp: 11410 case Builtin::BI__builtin_bcmp: 11411 case Builtin::BI__builtin_wmemcmp: { 11412 LValue String1, String2; 11413 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11414 !EvaluatePointer(E->getArg(1), String2, Info)) 11415 return false; 11416 11417 uint64_t MaxLength = uint64_t(-1); 11418 if (BuiltinOp != Builtin::BIstrcmp && 11419 BuiltinOp != Builtin::BIwcscmp && 11420 BuiltinOp != Builtin::BI__builtin_strcmp && 11421 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11422 APSInt N; 11423 if (!EvaluateInteger(E->getArg(2), N, Info)) 11424 return false; 11425 MaxLength = N.getExtValue(); 11426 } 11427 11428 // Empty substrings compare equal by definition. 11429 if (MaxLength == 0u) 11430 return Success(0, E); 11431 11432 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11433 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11434 String1.Designator.Invalid || String2.Designator.Invalid) 11435 return false; 11436 11437 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11438 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11439 11440 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11441 BuiltinOp == Builtin::BIbcmp || 11442 BuiltinOp == Builtin::BI__builtin_memcmp || 11443 BuiltinOp == Builtin::BI__builtin_bcmp; 11444 11445 assert(IsRawByte || 11446 (Info.Ctx.hasSameUnqualifiedType( 11447 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11448 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11449 11450 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11451 // 'char8_t', but no other types. 11452 if (IsRawByte && 11453 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11454 // FIXME: Consider using our bit_cast implementation to support this. 11455 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11456 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11457 << CharTy1 << CharTy2; 11458 return false; 11459 } 11460 11461 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11462 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11463 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11464 Char1.isInt() && Char2.isInt(); 11465 }; 11466 const auto &AdvanceElems = [&] { 11467 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11468 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11469 }; 11470 11471 bool StopAtNull = 11472 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11473 BuiltinOp != Builtin::BIwmemcmp && 11474 BuiltinOp != Builtin::BI__builtin_memcmp && 11475 BuiltinOp != Builtin::BI__builtin_bcmp && 11476 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11477 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11478 BuiltinOp == Builtin::BIwcsncmp || 11479 BuiltinOp == Builtin::BIwmemcmp || 11480 BuiltinOp == Builtin::BI__builtin_wcscmp || 11481 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11482 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11483 11484 for (; MaxLength; --MaxLength) { 11485 APValue Char1, Char2; 11486 if (!ReadCurElems(Char1, Char2)) 11487 return false; 11488 if (Char1.getInt().ne(Char2.getInt())) { 11489 if (IsWide) // wmemcmp compares with wchar_t signedness. 11490 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11491 // memcmp always compares unsigned chars. 11492 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11493 } 11494 if (StopAtNull && !Char1.getInt()) 11495 return Success(0, E); 11496 assert(!(StopAtNull && !Char2.getInt())); 11497 if (!AdvanceElems()) 11498 return false; 11499 } 11500 // We hit the strncmp / memcmp limit. 11501 return Success(0, E); 11502 } 11503 11504 case Builtin::BI__atomic_always_lock_free: 11505 case Builtin::BI__atomic_is_lock_free: 11506 case Builtin::BI__c11_atomic_is_lock_free: { 11507 APSInt SizeVal; 11508 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11509 return false; 11510 11511 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11512 // of two less than the maximum inline atomic width, we know it is 11513 // lock-free. If the size isn't a power of two, or greater than the 11514 // maximum alignment where we promote atomics, we know it is not lock-free 11515 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11516 // the answer can only be determined at runtime; for example, 16-byte 11517 // atomics have lock-free implementations on some, but not all, 11518 // x86-64 processors. 11519 11520 // Check power-of-two. 11521 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11522 if (Size.isPowerOfTwo()) { 11523 // Check against inlining width. 11524 unsigned InlineWidthBits = 11525 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11526 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11527 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11528 Size == CharUnits::One() || 11529 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11530 Expr::NPC_NeverValueDependent)) 11531 // OK, we will inline appropriately-aligned operations of this size, 11532 // and _Atomic(T) is appropriately-aligned. 11533 return Success(1, E); 11534 11535 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11536 castAs<PointerType>()->getPointeeType(); 11537 if (!PointeeType->isIncompleteType() && 11538 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11539 // OK, we will inline operations on this object. 11540 return Success(1, E); 11541 } 11542 } 11543 } 11544 11545 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11546 Success(0, E) : Error(E); 11547 } 11548 case Builtin::BIomp_is_initial_device: 11549 // We can decide statically which value the runtime would return if called. 11550 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11551 case Builtin::BI__builtin_add_overflow: 11552 case Builtin::BI__builtin_sub_overflow: 11553 case Builtin::BI__builtin_mul_overflow: 11554 case Builtin::BI__builtin_sadd_overflow: 11555 case Builtin::BI__builtin_uadd_overflow: 11556 case Builtin::BI__builtin_uaddl_overflow: 11557 case Builtin::BI__builtin_uaddll_overflow: 11558 case Builtin::BI__builtin_usub_overflow: 11559 case Builtin::BI__builtin_usubl_overflow: 11560 case Builtin::BI__builtin_usubll_overflow: 11561 case Builtin::BI__builtin_umul_overflow: 11562 case Builtin::BI__builtin_umull_overflow: 11563 case Builtin::BI__builtin_umulll_overflow: 11564 case Builtin::BI__builtin_saddl_overflow: 11565 case Builtin::BI__builtin_saddll_overflow: 11566 case Builtin::BI__builtin_ssub_overflow: 11567 case Builtin::BI__builtin_ssubl_overflow: 11568 case Builtin::BI__builtin_ssubll_overflow: 11569 case Builtin::BI__builtin_smul_overflow: 11570 case Builtin::BI__builtin_smull_overflow: 11571 case Builtin::BI__builtin_smulll_overflow: { 11572 LValue ResultLValue; 11573 APSInt LHS, RHS; 11574 11575 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11576 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11577 !EvaluateInteger(E->getArg(1), RHS, Info) || 11578 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11579 return false; 11580 11581 APSInt Result; 11582 bool DidOverflow = false; 11583 11584 // If the types don't have to match, enlarge all 3 to the largest of them. 11585 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11586 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11587 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11588 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11589 ResultType->isSignedIntegerOrEnumerationType(); 11590 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11591 ResultType->isSignedIntegerOrEnumerationType(); 11592 uint64_t LHSSize = LHS.getBitWidth(); 11593 uint64_t RHSSize = RHS.getBitWidth(); 11594 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11595 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11596 11597 // Add an additional bit if the signedness isn't uniformly agreed to. We 11598 // could do this ONLY if there is a signed and an unsigned that both have 11599 // MaxBits, but the code to check that is pretty nasty. The issue will be 11600 // caught in the shrink-to-result later anyway. 11601 if (IsSigned && !AllSigned) 11602 ++MaxBits; 11603 11604 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11605 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11606 Result = APSInt(MaxBits, !IsSigned); 11607 } 11608 11609 // Find largest int. 11610 switch (BuiltinOp) { 11611 default: 11612 llvm_unreachable("Invalid value for BuiltinOp"); 11613 case Builtin::BI__builtin_add_overflow: 11614 case Builtin::BI__builtin_sadd_overflow: 11615 case Builtin::BI__builtin_saddl_overflow: 11616 case Builtin::BI__builtin_saddll_overflow: 11617 case Builtin::BI__builtin_uadd_overflow: 11618 case Builtin::BI__builtin_uaddl_overflow: 11619 case Builtin::BI__builtin_uaddll_overflow: 11620 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11621 : LHS.uadd_ov(RHS, DidOverflow); 11622 break; 11623 case Builtin::BI__builtin_sub_overflow: 11624 case Builtin::BI__builtin_ssub_overflow: 11625 case Builtin::BI__builtin_ssubl_overflow: 11626 case Builtin::BI__builtin_ssubll_overflow: 11627 case Builtin::BI__builtin_usub_overflow: 11628 case Builtin::BI__builtin_usubl_overflow: 11629 case Builtin::BI__builtin_usubll_overflow: 11630 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11631 : LHS.usub_ov(RHS, DidOverflow); 11632 break; 11633 case Builtin::BI__builtin_mul_overflow: 11634 case Builtin::BI__builtin_smul_overflow: 11635 case Builtin::BI__builtin_smull_overflow: 11636 case Builtin::BI__builtin_smulll_overflow: 11637 case Builtin::BI__builtin_umul_overflow: 11638 case Builtin::BI__builtin_umull_overflow: 11639 case Builtin::BI__builtin_umulll_overflow: 11640 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11641 : LHS.umul_ov(RHS, DidOverflow); 11642 break; 11643 } 11644 11645 // In the case where multiple sizes are allowed, truncate and see if 11646 // the values are the same. 11647 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11648 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11649 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11650 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11651 // since it will give us the behavior of a TruncOrSelf in the case where 11652 // its parameter <= its size. We previously set Result to be at least the 11653 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11654 // will work exactly like TruncOrSelf. 11655 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11656 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 11657 11658 if (!APSInt::isSameValue(Temp, Result)) 11659 DidOverflow = true; 11660 Result = Temp; 11661 } 11662 11663 APValue APV{Result}; 11664 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 11665 return false; 11666 return Success(DidOverflow, E); 11667 } 11668 } 11669 } 11670 11671 /// Determine whether this is a pointer past the end of the complete 11672 /// object referred to by the lvalue. 11673 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 11674 const LValue &LV) { 11675 // A null pointer can be viewed as being "past the end" but we don't 11676 // choose to look at it that way here. 11677 if (!LV.getLValueBase()) 11678 return false; 11679 11680 // If the designator is valid and refers to a subobject, we're not pointing 11681 // past the end. 11682 if (!LV.getLValueDesignator().Invalid && 11683 !LV.getLValueDesignator().isOnePastTheEnd()) 11684 return false; 11685 11686 // A pointer to an incomplete type might be past-the-end if the type's size is 11687 // zero. We cannot tell because the type is incomplete. 11688 QualType Ty = getType(LV.getLValueBase()); 11689 if (Ty->isIncompleteType()) 11690 return true; 11691 11692 // We're a past-the-end pointer if we point to the byte after the object, 11693 // no matter what our type or path is. 11694 auto Size = Ctx.getTypeSizeInChars(Ty); 11695 return LV.getLValueOffset() == Size; 11696 } 11697 11698 namespace { 11699 11700 /// Data recursive integer evaluator of certain binary operators. 11701 /// 11702 /// We use a data recursive algorithm for binary operators so that we are able 11703 /// to handle extreme cases of chained binary operators without causing stack 11704 /// overflow. 11705 class DataRecursiveIntBinOpEvaluator { 11706 struct EvalResult { 11707 APValue Val; 11708 bool Failed; 11709 11710 EvalResult() : Failed(false) { } 11711 11712 void swap(EvalResult &RHS) { 11713 Val.swap(RHS.Val); 11714 Failed = RHS.Failed; 11715 RHS.Failed = false; 11716 } 11717 }; 11718 11719 struct Job { 11720 const Expr *E; 11721 EvalResult LHSResult; // meaningful only for binary operator expression. 11722 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 11723 11724 Job() = default; 11725 Job(Job &&) = default; 11726 11727 void startSpeculativeEval(EvalInfo &Info) { 11728 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 11729 } 11730 11731 private: 11732 SpeculativeEvaluationRAII SpecEvalRAII; 11733 }; 11734 11735 SmallVector<Job, 16> Queue; 11736 11737 IntExprEvaluator &IntEval; 11738 EvalInfo &Info; 11739 APValue &FinalResult; 11740 11741 public: 11742 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 11743 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 11744 11745 /// True if \param E is a binary operator that we are going to handle 11746 /// data recursively. 11747 /// We handle binary operators that are comma, logical, or that have operands 11748 /// with integral or enumeration type. 11749 static bool shouldEnqueue(const BinaryOperator *E) { 11750 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 11751 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 11752 E->getLHS()->getType()->isIntegralOrEnumerationType() && 11753 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11754 } 11755 11756 bool Traverse(const BinaryOperator *E) { 11757 enqueue(E); 11758 EvalResult PrevResult; 11759 while (!Queue.empty()) 11760 process(PrevResult); 11761 11762 if (PrevResult.Failed) return false; 11763 11764 FinalResult.swap(PrevResult.Val); 11765 return true; 11766 } 11767 11768 private: 11769 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11770 return IntEval.Success(Value, E, Result); 11771 } 11772 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 11773 return IntEval.Success(Value, E, Result); 11774 } 11775 bool Error(const Expr *E) { 11776 return IntEval.Error(E); 11777 } 11778 bool Error(const Expr *E, diag::kind D) { 11779 return IntEval.Error(E, D); 11780 } 11781 11782 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 11783 return Info.CCEDiag(E, D); 11784 } 11785 11786 // Returns true if visiting the RHS is necessary, false otherwise. 11787 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11788 bool &SuppressRHSDiags); 11789 11790 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11791 const BinaryOperator *E, APValue &Result); 11792 11793 void EvaluateExpr(const Expr *E, EvalResult &Result) { 11794 Result.Failed = !Evaluate(Result.Val, Info, E); 11795 if (Result.Failed) 11796 Result.Val = APValue(); 11797 } 11798 11799 void process(EvalResult &Result); 11800 11801 void enqueue(const Expr *E) { 11802 E = E->IgnoreParens(); 11803 Queue.resize(Queue.size()+1); 11804 Queue.back().E = E; 11805 Queue.back().Kind = Job::AnyExprKind; 11806 } 11807 }; 11808 11809 } 11810 11811 bool DataRecursiveIntBinOpEvaluator:: 11812 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11813 bool &SuppressRHSDiags) { 11814 if (E->getOpcode() == BO_Comma) { 11815 // Ignore LHS but note if we could not evaluate it. 11816 if (LHSResult.Failed) 11817 return Info.noteSideEffect(); 11818 return true; 11819 } 11820 11821 if (E->isLogicalOp()) { 11822 bool LHSAsBool; 11823 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 11824 // We were able to evaluate the LHS, see if we can get away with not 11825 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 11826 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 11827 Success(LHSAsBool, E, LHSResult.Val); 11828 return false; // Ignore RHS 11829 } 11830 } else { 11831 LHSResult.Failed = true; 11832 11833 // Since we weren't able to evaluate the left hand side, it 11834 // might have had side effects. 11835 if (!Info.noteSideEffect()) 11836 return false; 11837 11838 // We can't evaluate the LHS; however, sometimes the result 11839 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11840 // Don't ignore RHS and suppress diagnostics from this arm. 11841 SuppressRHSDiags = true; 11842 } 11843 11844 return true; 11845 } 11846 11847 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11848 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11849 11850 if (LHSResult.Failed && !Info.noteFailure()) 11851 return false; // Ignore RHS; 11852 11853 return true; 11854 } 11855 11856 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 11857 bool IsSub) { 11858 // Compute the new offset in the appropriate width, wrapping at 64 bits. 11859 // FIXME: When compiling for a 32-bit target, we should use 32-bit 11860 // offsets. 11861 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 11862 CharUnits &Offset = LVal.getLValueOffset(); 11863 uint64_t Offset64 = Offset.getQuantity(); 11864 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 11865 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 11866 : Offset64 + Index64); 11867 } 11868 11869 bool DataRecursiveIntBinOpEvaluator:: 11870 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11871 const BinaryOperator *E, APValue &Result) { 11872 if (E->getOpcode() == BO_Comma) { 11873 if (RHSResult.Failed) 11874 return false; 11875 Result = RHSResult.Val; 11876 return true; 11877 } 11878 11879 if (E->isLogicalOp()) { 11880 bool lhsResult, rhsResult; 11881 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 11882 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 11883 11884 if (LHSIsOK) { 11885 if (RHSIsOK) { 11886 if (E->getOpcode() == BO_LOr) 11887 return Success(lhsResult || rhsResult, E, Result); 11888 else 11889 return Success(lhsResult && rhsResult, E, Result); 11890 } 11891 } else { 11892 if (RHSIsOK) { 11893 // We can't evaluate the LHS; however, sometimes the result 11894 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11895 if (rhsResult == (E->getOpcode() == BO_LOr)) 11896 return Success(rhsResult, E, Result); 11897 } 11898 } 11899 11900 return false; 11901 } 11902 11903 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11904 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11905 11906 if (LHSResult.Failed || RHSResult.Failed) 11907 return false; 11908 11909 const APValue &LHSVal = LHSResult.Val; 11910 const APValue &RHSVal = RHSResult.Val; 11911 11912 // Handle cases like (unsigned long)&a + 4. 11913 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 11914 Result = LHSVal; 11915 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 11916 return true; 11917 } 11918 11919 // Handle cases like 4 + (unsigned long)&a 11920 if (E->getOpcode() == BO_Add && 11921 RHSVal.isLValue() && LHSVal.isInt()) { 11922 Result = RHSVal; 11923 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 11924 return true; 11925 } 11926 11927 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 11928 // Handle (intptr_t)&&A - (intptr_t)&&B. 11929 if (!LHSVal.getLValueOffset().isZero() || 11930 !RHSVal.getLValueOffset().isZero()) 11931 return false; 11932 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 11933 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 11934 if (!LHSExpr || !RHSExpr) 11935 return false; 11936 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 11937 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 11938 if (!LHSAddrExpr || !RHSAddrExpr) 11939 return false; 11940 // Make sure both labels come from the same function. 11941 if (LHSAddrExpr->getLabel()->getDeclContext() != 11942 RHSAddrExpr->getLabel()->getDeclContext()) 11943 return false; 11944 Result = APValue(LHSAddrExpr, RHSAddrExpr); 11945 return true; 11946 } 11947 11948 // All the remaining cases expect both operands to be an integer 11949 if (!LHSVal.isInt() || !RHSVal.isInt()) 11950 return Error(E); 11951 11952 // Set up the width and signedness manually, in case it can't be deduced 11953 // from the operation we're performing. 11954 // FIXME: Don't do this in the cases where we can deduce it. 11955 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 11956 E->getType()->isUnsignedIntegerOrEnumerationType()); 11957 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 11958 RHSVal.getInt(), Value)) 11959 return false; 11960 return Success(Value, E, Result); 11961 } 11962 11963 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 11964 Job &job = Queue.back(); 11965 11966 switch (job.Kind) { 11967 case Job::AnyExprKind: { 11968 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 11969 if (shouldEnqueue(Bop)) { 11970 job.Kind = Job::BinOpKind; 11971 enqueue(Bop->getLHS()); 11972 return; 11973 } 11974 } 11975 11976 EvaluateExpr(job.E, Result); 11977 Queue.pop_back(); 11978 return; 11979 } 11980 11981 case Job::BinOpKind: { 11982 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11983 bool SuppressRHSDiags = false; 11984 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 11985 Queue.pop_back(); 11986 return; 11987 } 11988 if (SuppressRHSDiags) 11989 job.startSpeculativeEval(Info); 11990 job.LHSResult.swap(Result); 11991 job.Kind = Job::BinOpVisitedLHSKind; 11992 enqueue(Bop->getRHS()); 11993 return; 11994 } 11995 11996 case Job::BinOpVisitedLHSKind: { 11997 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11998 EvalResult RHS; 11999 RHS.swap(Result); 12000 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12001 Queue.pop_back(); 12002 return; 12003 } 12004 } 12005 12006 llvm_unreachable("Invalid Job::Kind!"); 12007 } 12008 12009 namespace { 12010 /// Used when we determine that we should fail, but can keep evaluating prior to 12011 /// noting that we had a failure. 12012 class DelayedNoteFailureRAII { 12013 EvalInfo &Info; 12014 bool NoteFailure; 12015 12016 public: 12017 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12018 : Info(Info), NoteFailure(NoteFailure) {} 12019 ~DelayedNoteFailureRAII() { 12020 if (NoteFailure) { 12021 bool ContinueAfterFailure = Info.noteFailure(); 12022 (void)ContinueAfterFailure; 12023 assert(ContinueAfterFailure && 12024 "Shouldn't have kept evaluating on failure."); 12025 } 12026 } 12027 }; 12028 12029 enum class CmpResult { 12030 Unequal, 12031 Less, 12032 Equal, 12033 Greater, 12034 Unordered, 12035 }; 12036 } 12037 12038 template <class SuccessCB, class AfterCB> 12039 static bool 12040 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12041 SuccessCB &&Success, AfterCB &&DoAfter) { 12042 assert(E->isComparisonOp() && "expected comparison operator"); 12043 assert((E->getOpcode() == BO_Cmp || 12044 E->getType()->isIntegralOrEnumerationType()) && 12045 "unsupported binary expression evaluation"); 12046 auto Error = [&](const Expr *E) { 12047 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12048 return false; 12049 }; 12050 12051 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12052 bool IsEquality = E->isEqualityOp(); 12053 12054 QualType LHSTy = E->getLHS()->getType(); 12055 QualType RHSTy = E->getRHS()->getType(); 12056 12057 if (LHSTy->isIntegralOrEnumerationType() && 12058 RHSTy->isIntegralOrEnumerationType()) { 12059 APSInt LHS, RHS; 12060 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12061 if (!LHSOK && !Info.noteFailure()) 12062 return false; 12063 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12064 return false; 12065 if (LHS < RHS) 12066 return Success(CmpResult::Less, E); 12067 if (LHS > RHS) 12068 return Success(CmpResult::Greater, E); 12069 return Success(CmpResult::Equal, E); 12070 } 12071 12072 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12073 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12074 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12075 12076 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12077 if (!LHSOK && !Info.noteFailure()) 12078 return false; 12079 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12080 return false; 12081 if (LHSFX < RHSFX) 12082 return Success(CmpResult::Less, E); 12083 if (LHSFX > RHSFX) 12084 return Success(CmpResult::Greater, E); 12085 return Success(CmpResult::Equal, E); 12086 } 12087 12088 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12089 ComplexValue LHS, RHS; 12090 bool LHSOK; 12091 if (E->isAssignmentOp()) { 12092 LValue LV; 12093 EvaluateLValue(E->getLHS(), LV, Info); 12094 LHSOK = false; 12095 } else if (LHSTy->isRealFloatingType()) { 12096 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12097 if (LHSOK) { 12098 LHS.makeComplexFloat(); 12099 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12100 } 12101 } else { 12102 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12103 } 12104 if (!LHSOK && !Info.noteFailure()) 12105 return false; 12106 12107 if (E->getRHS()->getType()->isRealFloatingType()) { 12108 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12109 return false; 12110 RHS.makeComplexFloat(); 12111 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12112 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12113 return false; 12114 12115 if (LHS.isComplexFloat()) { 12116 APFloat::cmpResult CR_r = 12117 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12118 APFloat::cmpResult CR_i = 12119 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12120 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12121 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12122 } else { 12123 assert(IsEquality && "invalid complex comparison"); 12124 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12125 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12126 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12127 } 12128 } 12129 12130 if (LHSTy->isRealFloatingType() && 12131 RHSTy->isRealFloatingType()) { 12132 APFloat RHS(0.0), LHS(0.0); 12133 12134 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12135 if (!LHSOK && !Info.noteFailure()) 12136 return false; 12137 12138 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12139 return false; 12140 12141 assert(E->isComparisonOp() && "Invalid binary operator!"); 12142 auto GetCmpRes = [&]() { 12143 switch (LHS.compare(RHS)) { 12144 case APFloat::cmpEqual: 12145 return CmpResult::Equal; 12146 case APFloat::cmpLessThan: 12147 return CmpResult::Less; 12148 case APFloat::cmpGreaterThan: 12149 return CmpResult::Greater; 12150 case APFloat::cmpUnordered: 12151 return CmpResult::Unordered; 12152 } 12153 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12154 }; 12155 return Success(GetCmpRes(), E); 12156 } 12157 12158 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12159 LValue LHSValue, RHSValue; 12160 12161 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12162 if (!LHSOK && !Info.noteFailure()) 12163 return false; 12164 12165 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12166 return false; 12167 12168 // Reject differing bases from the normal codepath; we special-case 12169 // comparisons to null. 12170 if (!HasSameBase(LHSValue, RHSValue)) { 12171 // Inequalities and subtractions between unrelated pointers have 12172 // unspecified or undefined behavior. 12173 if (!IsEquality) { 12174 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12175 return false; 12176 } 12177 // A constant address may compare equal to the address of a symbol. 12178 // The one exception is that address of an object cannot compare equal 12179 // to a null pointer constant. 12180 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12181 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12182 return Error(E); 12183 // It's implementation-defined whether distinct literals will have 12184 // distinct addresses. In clang, the result of such a comparison is 12185 // unspecified, so it is not a constant expression. However, we do know 12186 // that the address of a literal will be non-null. 12187 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12188 LHSValue.Base && RHSValue.Base) 12189 return Error(E); 12190 // We can't tell whether weak symbols will end up pointing to the same 12191 // object. 12192 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12193 return Error(E); 12194 // We can't compare the address of the start of one object with the 12195 // past-the-end address of another object, per C++ DR1652. 12196 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12197 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12198 (RHSValue.Base && RHSValue.Offset.isZero() && 12199 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12200 return Error(E); 12201 // We can't tell whether an object is at the same address as another 12202 // zero sized object. 12203 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12204 (LHSValue.Base && isZeroSized(RHSValue))) 12205 return Error(E); 12206 return Success(CmpResult::Unequal, E); 12207 } 12208 12209 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12210 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12211 12212 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12213 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12214 12215 // C++11 [expr.rel]p3: 12216 // Pointers to void (after pointer conversions) can be compared, with a 12217 // result defined as follows: If both pointers represent the same 12218 // address or are both the null pointer value, the result is true if the 12219 // operator is <= or >= and false otherwise; otherwise the result is 12220 // unspecified. 12221 // We interpret this as applying to pointers to *cv* void. 12222 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12223 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12224 12225 // C++11 [expr.rel]p2: 12226 // - If two pointers point to non-static data members of the same object, 12227 // or to subobjects or array elements fo such members, recursively, the 12228 // pointer to the later declared member compares greater provided the 12229 // two members have the same access control and provided their class is 12230 // not a union. 12231 // [...] 12232 // - Otherwise pointer comparisons are unspecified. 12233 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12234 bool WasArrayIndex; 12235 unsigned Mismatch = FindDesignatorMismatch( 12236 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12237 // At the point where the designators diverge, the comparison has a 12238 // specified value if: 12239 // - we are comparing array indices 12240 // - we are comparing fields of a union, or fields with the same access 12241 // Otherwise, the result is unspecified and thus the comparison is not a 12242 // constant expression. 12243 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12244 Mismatch < RHSDesignator.Entries.size()) { 12245 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12246 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12247 if (!LF && !RF) 12248 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12249 else if (!LF) 12250 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12251 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12252 << RF->getParent() << RF; 12253 else if (!RF) 12254 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12255 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12256 << LF->getParent() << LF; 12257 else if (!LF->getParent()->isUnion() && 12258 LF->getAccess() != RF->getAccess()) 12259 Info.CCEDiag(E, 12260 diag::note_constexpr_pointer_comparison_differing_access) 12261 << LF << LF->getAccess() << RF << RF->getAccess() 12262 << LF->getParent(); 12263 } 12264 } 12265 12266 // The comparison here must be unsigned, and performed with the same 12267 // width as the pointer. 12268 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12269 uint64_t CompareLHS = LHSOffset.getQuantity(); 12270 uint64_t CompareRHS = RHSOffset.getQuantity(); 12271 assert(PtrSize <= 64 && "Unexpected pointer width"); 12272 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12273 CompareLHS &= Mask; 12274 CompareRHS &= Mask; 12275 12276 // If there is a base and this is a relational operator, we can only 12277 // compare pointers within the object in question; otherwise, the result 12278 // depends on where the object is located in memory. 12279 if (!LHSValue.Base.isNull() && IsRelational) { 12280 QualType BaseTy = getType(LHSValue.Base); 12281 if (BaseTy->isIncompleteType()) 12282 return Error(E); 12283 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12284 uint64_t OffsetLimit = Size.getQuantity(); 12285 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12286 return Error(E); 12287 } 12288 12289 if (CompareLHS < CompareRHS) 12290 return Success(CmpResult::Less, E); 12291 if (CompareLHS > CompareRHS) 12292 return Success(CmpResult::Greater, E); 12293 return Success(CmpResult::Equal, E); 12294 } 12295 12296 if (LHSTy->isMemberPointerType()) { 12297 assert(IsEquality && "unexpected member pointer operation"); 12298 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12299 12300 MemberPtr LHSValue, RHSValue; 12301 12302 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12303 if (!LHSOK && !Info.noteFailure()) 12304 return false; 12305 12306 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12307 return false; 12308 12309 // C++11 [expr.eq]p2: 12310 // If both operands are null, they compare equal. Otherwise if only one is 12311 // null, they compare unequal. 12312 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12313 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12314 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12315 } 12316 12317 // Otherwise if either is a pointer to a virtual member function, the 12318 // result is unspecified. 12319 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12320 if (MD->isVirtual()) 12321 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12322 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12323 if (MD->isVirtual()) 12324 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12325 12326 // Otherwise they compare equal if and only if they would refer to the 12327 // same member of the same most derived object or the same subobject if 12328 // they were dereferenced with a hypothetical object of the associated 12329 // class type. 12330 bool Equal = LHSValue == RHSValue; 12331 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12332 } 12333 12334 if (LHSTy->isNullPtrType()) { 12335 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12336 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12337 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12338 // are compared, the result is true of the operator is <=, >= or ==, and 12339 // false otherwise. 12340 return Success(CmpResult::Equal, E); 12341 } 12342 12343 return DoAfter(); 12344 } 12345 12346 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12347 if (!CheckLiteralType(Info, E)) 12348 return false; 12349 12350 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12351 ComparisonCategoryResult CCR; 12352 switch (CR) { 12353 case CmpResult::Unequal: 12354 llvm_unreachable("should never produce Unequal for three-way comparison"); 12355 case CmpResult::Less: 12356 CCR = ComparisonCategoryResult::Less; 12357 break; 12358 case CmpResult::Equal: 12359 CCR = ComparisonCategoryResult::Equal; 12360 break; 12361 case CmpResult::Greater: 12362 CCR = ComparisonCategoryResult::Greater; 12363 break; 12364 case CmpResult::Unordered: 12365 CCR = ComparisonCategoryResult::Unordered; 12366 break; 12367 } 12368 // Evaluation succeeded. Lookup the information for the comparison category 12369 // type and fetch the VarDecl for the result. 12370 const ComparisonCategoryInfo &CmpInfo = 12371 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12372 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12373 // Check and evaluate the result as a constant expression. 12374 LValue LV; 12375 LV.set(VD); 12376 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12377 return false; 12378 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12379 }; 12380 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12381 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12382 }); 12383 } 12384 12385 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12386 // We don't call noteFailure immediately because the assignment happens after 12387 // we evaluate LHS and RHS. 12388 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12389 return Error(E); 12390 12391 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12392 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12393 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12394 12395 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12396 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12397 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12398 12399 if (E->isComparisonOp()) { 12400 // Evaluate builtin binary comparisons by evaluating them as three-way 12401 // comparisons and then translating the result. 12402 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12403 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12404 "should only produce Unequal for equality comparisons"); 12405 bool IsEqual = CR == CmpResult::Equal, 12406 IsLess = CR == CmpResult::Less, 12407 IsGreater = CR == CmpResult::Greater; 12408 auto Op = E->getOpcode(); 12409 switch (Op) { 12410 default: 12411 llvm_unreachable("unsupported binary operator"); 12412 case BO_EQ: 12413 case BO_NE: 12414 return Success(IsEqual == (Op == BO_EQ), E); 12415 case BO_LT: 12416 return Success(IsLess, E); 12417 case BO_GT: 12418 return Success(IsGreater, E); 12419 case BO_LE: 12420 return Success(IsEqual || IsLess, E); 12421 case BO_GE: 12422 return Success(IsEqual || IsGreater, E); 12423 } 12424 }; 12425 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12426 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12427 }); 12428 } 12429 12430 QualType LHSTy = E->getLHS()->getType(); 12431 QualType RHSTy = E->getRHS()->getType(); 12432 12433 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12434 E->getOpcode() == BO_Sub) { 12435 LValue LHSValue, RHSValue; 12436 12437 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12438 if (!LHSOK && !Info.noteFailure()) 12439 return false; 12440 12441 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12442 return false; 12443 12444 // Reject differing bases from the normal codepath; we special-case 12445 // comparisons to null. 12446 if (!HasSameBase(LHSValue, RHSValue)) { 12447 // Handle &&A - &&B. 12448 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12449 return Error(E); 12450 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12451 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12452 if (!LHSExpr || !RHSExpr) 12453 return Error(E); 12454 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12455 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12456 if (!LHSAddrExpr || !RHSAddrExpr) 12457 return Error(E); 12458 // Make sure both labels come from the same function. 12459 if (LHSAddrExpr->getLabel()->getDeclContext() != 12460 RHSAddrExpr->getLabel()->getDeclContext()) 12461 return Error(E); 12462 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12463 } 12464 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12465 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12466 12467 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12468 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12469 12470 // C++11 [expr.add]p6: 12471 // Unless both pointers point to elements of the same array object, or 12472 // one past the last element of the array object, the behavior is 12473 // undefined. 12474 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12475 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12476 RHSDesignator)) 12477 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12478 12479 QualType Type = E->getLHS()->getType(); 12480 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12481 12482 CharUnits ElementSize; 12483 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12484 return false; 12485 12486 // As an extension, a type may have zero size (empty struct or union in 12487 // C, array of zero length). Pointer subtraction in such cases has 12488 // undefined behavior, so is not constant. 12489 if (ElementSize.isZero()) { 12490 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12491 << ElementType; 12492 return false; 12493 } 12494 12495 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12496 // and produce incorrect results when it overflows. Such behavior 12497 // appears to be non-conforming, but is common, so perhaps we should 12498 // assume the standard intended for such cases to be undefined behavior 12499 // and check for them. 12500 12501 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12502 // overflow in the final conversion to ptrdiff_t. 12503 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12504 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12505 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12506 false); 12507 APSInt TrueResult = (LHS - RHS) / ElemSize; 12508 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12509 12510 if (Result.extend(65) != TrueResult && 12511 !HandleOverflow(Info, E, TrueResult, E->getType())) 12512 return false; 12513 return Success(Result, E); 12514 } 12515 12516 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12517 } 12518 12519 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12520 /// a result as the expression's type. 12521 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12522 const UnaryExprOrTypeTraitExpr *E) { 12523 switch(E->getKind()) { 12524 case UETT_PreferredAlignOf: 12525 case UETT_AlignOf: { 12526 if (E->isArgumentType()) 12527 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12528 E); 12529 else 12530 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12531 E); 12532 } 12533 12534 case UETT_VecStep: { 12535 QualType Ty = E->getTypeOfArgument(); 12536 12537 if (Ty->isVectorType()) { 12538 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12539 12540 // The vec_step built-in functions that take a 3-component 12541 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12542 if (n == 3) 12543 n = 4; 12544 12545 return Success(n, E); 12546 } else 12547 return Success(1, E); 12548 } 12549 12550 case UETT_SizeOf: { 12551 QualType SrcTy = E->getTypeOfArgument(); 12552 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12553 // the result is the size of the referenced type." 12554 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12555 SrcTy = Ref->getPointeeType(); 12556 12557 CharUnits Sizeof; 12558 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12559 return false; 12560 return Success(Sizeof, E); 12561 } 12562 case UETT_OpenMPRequiredSimdAlign: 12563 assert(E->isArgumentType()); 12564 return Success( 12565 Info.Ctx.toCharUnitsFromBits( 12566 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12567 .getQuantity(), 12568 E); 12569 } 12570 12571 llvm_unreachable("unknown expr/type trait"); 12572 } 12573 12574 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12575 CharUnits Result; 12576 unsigned n = OOE->getNumComponents(); 12577 if (n == 0) 12578 return Error(OOE); 12579 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12580 for (unsigned i = 0; i != n; ++i) { 12581 OffsetOfNode ON = OOE->getComponent(i); 12582 switch (ON.getKind()) { 12583 case OffsetOfNode::Array: { 12584 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12585 APSInt IdxResult; 12586 if (!EvaluateInteger(Idx, IdxResult, Info)) 12587 return false; 12588 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12589 if (!AT) 12590 return Error(OOE); 12591 CurrentType = AT->getElementType(); 12592 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12593 Result += IdxResult.getSExtValue() * ElementSize; 12594 break; 12595 } 12596 12597 case OffsetOfNode::Field: { 12598 FieldDecl *MemberDecl = ON.getField(); 12599 const RecordType *RT = CurrentType->getAs<RecordType>(); 12600 if (!RT) 12601 return Error(OOE); 12602 RecordDecl *RD = RT->getDecl(); 12603 if (RD->isInvalidDecl()) return false; 12604 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12605 unsigned i = MemberDecl->getFieldIndex(); 12606 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12607 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12608 CurrentType = MemberDecl->getType().getNonReferenceType(); 12609 break; 12610 } 12611 12612 case OffsetOfNode::Identifier: 12613 llvm_unreachable("dependent __builtin_offsetof"); 12614 12615 case OffsetOfNode::Base: { 12616 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12617 if (BaseSpec->isVirtual()) 12618 return Error(OOE); 12619 12620 // Find the layout of the class whose base we are looking into. 12621 const RecordType *RT = CurrentType->getAs<RecordType>(); 12622 if (!RT) 12623 return Error(OOE); 12624 RecordDecl *RD = RT->getDecl(); 12625 if (RD->isInvalidDecl()) return false; 12626 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12627 12628 // Find the base class itself. 12629 CurrentType = BaseSpec->getType(); 12630 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12631 if (!BaseRT) 12632 return Error(OOE); 12633 12634 // Add the offset to the base. 12635 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12636 break; 12637 } 12638 } 12639 } 12640 return Success(Result, OOE); 12641 } 12642 12643 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12644 switch (E->getOpcode()) { 12645 default: 12646 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12647 // See C99 6.6p3. 12648 return Error(E); 12649 case UO_Extension: 12650 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12651 // If so, we could clear the diagnostic ID. 12652 return Visit(E->getSubExpr()); 12653 case UO_Plus: 12654 // The result is just the value. 12655 return Visit(E->getSubExpr()); 12656 case UO_Minus: { 12657 if (!Visit(E->getSubExpr())) 12658 return false; 12659 if (!Result.isInt()) return Error(E); 12660 const APSInt &Value = Result.getInt(); 12661 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 12662 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 12663 E->getType())) 12664 return false; 12665 return Success(-Value, E); 12666 } 12667 case UO_Not: { 12668 if (!Visit(E->getSubExpr())) 12669 return false; 12670 if (!Result.isInt()) return Error(E); 12671 return Success(~Result.getInt(), E); 12672 } 12673 case UO_LNot: { 12674 bool bres; 12675 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12676 return false; 12677 return Success(!bres, E); 12678 } 12679 } 12680 } 12681 12682 /// HandleCast - This is used to evaluate implicit or explicit casts where the 12683 /// result type is integer. 12684 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 12685 const Expr *SubExpr = E->getSubExpr(); 12686 QualType DestType = E->getType(); 12687 QualType SrcType = SubExpr->getType(); 12688 12689 switch (E->getCastKind()) { 12690 case CK_BaseToDerived: 12691 case CK_DerivedToBase: 12692 case CK_UncheckedDerivedToBase: 12693 case CK_Dynamic: 12694 case CK_ToUnion: 12695 case CK_ArrayToPointerDecay: 12696 case CK_FunctionToPointerDecay: 12697 case CK_NullToPointer: 12698 case CK_NullToMemberPointer: 12699 case CK_BaseToDerivedMemberPointer: 12700 case CK_DerivedToBaseMemberPointer: 12701 case CK_ReinterpretMemberPointer: 12702 case CK_ConstructorConversion: 12703 case CK_IntegralToPointer: 12704 case CK_ToVoid: 12705 case CK_VectorSplat: 12706 case CK_IntegralToFloating: 12707 case CK_FloatingCast: 12708 case CK_CPointerToObjCPointerCast: 12709 case CK_BlockPointerToObjCPointerCast: 12710 case CK_AnyPointerToBlockPointerCast: 12711 case CK_ObjCObjectLValueCast: 12712 case CK_FloatingRealToComplex: 12713 case CK_FloatingComplexToReal: 12714 case CK_FloatingComplexCast: 12715 case CK_FloatingComplexToIntegralComplex: 12716 case CK_IntegralRealToComplex: 12717 case CK_IntegralComplexCast: 12718 case CK_IntegralComplexToFloatingComplex: 12719 case CK_BuiltinFnToFnPtr: 12720 case CK_ZeroToOCLOpaqueType: 12721 case CK_NonAtomicToAtomic: 12722 case CK_AddressSpaceConversion: 12723 case CK_IntToOCLSampler: 12724 case CK_FixedPointCast: 12725 case CK_IntegralToFixedPoint: 12726 llvm_unreachable("invalid cast kind for integral value"); 12727 12728 case CK_BitCast: 12729 case CK_Dependent: 12730 case CK_LValueBitCast: 12731 case CK_ARCProduceObject: 12732 case CK_ARCConsumeObject: 12733 case CK_ARCReclaimReturnedObject: 12734 case CK_ARCExtendBlockObject: 12735 case CK_CopyAndAutoreleaseBlockObject: 12736 return Error(E); 12737 12738 case CK_UserDefinedConversion: 12739 case CK_LValueToRValue: 12740 case CK_AtomicToNonAtomic: 12741 case CK_NoOp: 12742 case CK_LValueToRValueBitCast: 12743 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12744 12745 case CK_MemberPointerToBoolean: 12746 case CK_PointerToBoolean: 12747 case CK_IntegralToBoolean: 12748 case CK_FloatingToBoolean: 12749 case CK_BooleanToSignedIntegral: 12750 case CK_FloatingComplexToBoolean: 12751 case CK_IntegralComplexToBoolean: { 12752 bool BoolResult; 12753 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 12754 return false; 12755 uint64_t IntResult = BoolResult; 12756 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 12757 IntResult = (uint64_t)-1; 12758 return Success(IntResult, E); 12759 } 12760 12761 case CK_FixedPointToIntegral: { 12762 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 12763 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12764 return false; 12765 bool Overflowed; 12766 llvm::APSInt Result = Src.convertToInt( 12767 Info.Ctx.getIntWidth(DestType), 12768 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 12769 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12770 return false; 12771 return Success(Result, E); 12772 } 12773 12774 case CK_FixedPointToBoolean: { 12775 // Unsigned padding does not affect this. 12776 APValue Val; 12777 if (!Evaluate(Val, Info, SubExpr)) 12778 return false; 12779 return Success(Val.getFixedPoint().getBoolValue(), E); 12780 } 12781 12782 case CK_IntegralCast: { 12783 if (!Visit(SubExpr)) 12784 return false; 12785 12786 if (!Result.isInt()) { 12787 // Allow casts of address-of-label differences if they are no-ops 12788 // or narrowing. (The narrowing case isn't actually guaranteed to 12789 // be constant-evaluatable except in some narrow cases which are hard 12790 // to detect here. We let it through on the assumption the user knows 12791 // what they are doing.) 12792 if (Result.isAddrLabelDiff()) 12793 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 12794 // Only allow casts of lvalues if they are lossless. 12795 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 12796 } 12797 12798 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 12799 Result.getInt()), E); 12800 } 12801 12802 case CK_PointerToIntegral: { 12803 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 12804 12805 LValue LV; 12806 if (!EvaluatePointer(SubExpr, LV, Info)) 12807 return false; 12808 12809 if (LV.getLValueBase()) { 12810 // Only allow based lvalue casts if they are lossless. 12811 // FIXME: Allow a larger integer size than the pointer size, and allow 12812 // narrowing back down to pointer width in subsequent integral casts. 12813 // FIXME: Check integer type's active bits, not its type size. 12814 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 12815 return Error(E); 12816 12817 LV.Designator.setInvalid(); 12818 LV.moveInto(Result); 12819 return true; 12820 } 12821 12822 APSInt AsInt; 12823 APValue V; 12824 LV.moveInto(V); 12825 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 12826 llvm_unreachable("Can't cast this!"); 12827 12828 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 12829 } 12830 12831 case CK_IntegralComplexToReal: { 12832 ComplexValue C; 12833 if (!EvaluateComplex(SubExpr, C, Info)) 12834 return false; 12835 return Success(C.getComplexIntReal(), E); 12836 } 12837 12838 case CK_FloatingToIntegral: { 12839 APFloat F(0.0); 12840 if (!EvaluateFloat(SubExpr, F, Info)) 12841 return false; 12842 12843 APSInt Value; 12844 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 12845 return false; 12846 return Success(Value, E); 12847 } 12848 } 12849 12850 llvm_unreachable("unknown cast resulting in integral value"); 12851 } 12852 12853 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 12854 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12855 ComplexValue LV; 12856 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12857 return false; 12858 if (!LV.isComplexInt()) 12859 return Error(E); 12860 return Success(LV.getComplexIntReal(), E); 12861 } 12862 12863 return Visit(E->getSubExpr()); 12864 } 12865 12866 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 12867 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 12868 ComplexValue LV; 12869 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12870 return false; 12871 if (!LV.isComplexInt()) 12872 return Error(E); 12873 return Success(LV.getComplexIntImag(), E); 12874 } 12875 12876 VisitIgnoredValue(E->getSubExpr()); 12877 return Success(0, E); 12878 } 12879 12880 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 12881 return Success(E->getPackLength(), E); 12882 } 12883 12884 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 12885 return Success(E->getValue(), E); 12886 } 12887 12888 bool IntExprEvaluator::VisitConceptSpecializationExpr( 12889 const ConceptSpecializationExpr *E) { 12890 return Success(E->isSatisfied(), E); 12891 } 12892 12893 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 12894 return Success(E->isSatisfied(), E); 12895 } 12896 12897 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12898 switch (E->getOpcode()) { 12899 default: 12900 // Invalid unary operators 12901 return Error(E); 12902 case UO_Plus: 12903 // The result is just the value. 12904 return Visit(E->getSubExpr()); 12905 case UO_Minus: { 12906 if (!Visit(E->getSubExpr())) return false; 12907 if (!Result.isFixedPoint()) 12908 return Error(E); 12909 bool Overflowed; 12910 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 12911 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 12912 return false; 12913 return Success(Negated, E); 12914 } 12915 case UO_LNot: { 12916 bool bres; 12917 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12918 return false; 12919 return Success(!bres, E); 12920 } 12921 } 12922 } 12923 12924 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 12925 const Expr *SubExpr = E->getSubExpr(); 12926 QualType DestType = E->getType(); 12927 assert(DestType->isFixedPointType() && 12928 "Expected destination type to be a fixed point type"); 12929 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 12930 12931 switch (E->getCastKind()) { 12932 case CK_FixedPointCast: { 12933 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 12934 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12935 return false; 12936 bool Overflowed; 12937 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 12938 if (Overflowed) { 12939 if (Info.checkingForUndefinedBehavior()) 12940 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 12941 diag::warn_fixedpoint_constant_overflow) 12942 << Result.toString() << E->getType(); 12943 else if (!HandleOverflow(Info, E, Result, E->getType())) 12944 return false; 12945 } 12946 return Success(Result, E); 12947 } 12948 case CK_IntegralToFixedPoint: { 12949 APSInt Src; 12950 if (!EvaluateInteger(SubExpr, Src, Info)) 12951 return false; 12952 12953 bool Overflowed; 12954 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 12955 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 12956 12957 if (Overflowed) { 12958 if (Info.checkingForUndefinedBehavior()) 12959 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 12960 diag::warn_fixedpoint_constant_overflow) 12961 << IntResult.toString() << E->getType(); 12962 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 12963 return false; 12964 } 12965 12966 return Success(IntResult, E); 12967 } 12968 case CK_NoOp: 12969 case CK_LValueToRValue: 12970 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12971 default: 12972 return Error(E); 12973 } 12974 } 12975 12976 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12977 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 12978 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12979 12980 const Expr *LHS = E->getLHS(); 12981 const Expr *RHS = E->getRHS(); 12982 FixedPointSemantics ResultFXSema = 12983 Info.Ctx.getFixedPointSemantics(E->getType()); 12984 12985 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 12986 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 12987 return false; 12988 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 12989 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 12990 return false; 12991 12992 bool OpOverflow = false, ConversionOverflow = false; 12993 APFixedPoint Result(LHSFX.getSemantics()); 12994 switch (E->getOpcode()) { 12995 case BO_Add: { 12996 Result = LHSFX.add(RHSFX, &OpOverflow) 12997 .convert(ResultFXSema, &ConversionOverflow); 12998 break; 12999 } 13000 case BO_Sub: { 13001 Result = LHSFX.sub(RHSFX, &OpOverflow) 13002 .convert(ResultFXSema, &ConversionOverflow); 13003 break; 13004 } 13005 case BO_Mul: { 13006 Result = LHSFX.mul(RHSFX, &OpOverflow) 13007 .convert(ResultFXSema, &ConversionOverflow); 13008 break; 13009 } 13010 case BO_Div: { 13011 if (RHSFX.getValue() == 0) { 13012 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13013 return false; 13014 } 13015 Result = LHSFX.div(RHSFX, &OpOverflow) 13016 .convert(ResultFXSema, &ConversionOverflow); 13017 break; 13018 } 13019 case BO_Shl: 13020 case BO_Shr: { 13021 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13022 llvm::APSInt RHSVal = RHSFX.getValue(); 13023 13024 unsigned ShiftBW = 13025 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13026 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13027 // Embedded-C 4.1.6.2.2: 13028 // The right operand must be nonnegative and less than the total number 13029 // of (nonpadding) bits of the fixed-point operand ... 13030 if (RHSVal.isNegative()) 13031 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13032 else if (Amt != RHSVal) 13033 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13034 << RHSVal << E->getType() << ShiftBW; 13035 13036 if (E->getOpcode() == BO_Shl) 13037 Result = LHSFX.shl(Amt, &OpOverflow); 13038 else 13039 Result = LHSFX.shr(Amt, &OpOverflow); 13040 break; 13041 } 13042 default: 13043 return false; 13044 } 13045 if (OpOverflow || ConversionOverflow) { 13046 if (Info.checkingForUndefinedBehavior()) 13047 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13048 diag::warn_fixedpoint_constant_overflow) 13049 << Result.toString() << E->getType(); 13050 else if (!HandleOverflow(Info, E, Result, E->getType())) 13051 return false; 13052 } 13053 return Success(Result, E); 13054 } 13055 13056 //===----------------------------------------------------------------------===// 13057 // Float Evaluation 13058 //===----------------------------------------------------------------------===// 13059 13060 namespace { 13061 class FloatExprEvaluator 13062 : public ExprEvaluatorBase<FloatExprEvaluator> { 13063 APFloat &Result; 13064 public: 13065 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13066 : ExprEvaluatorBaseTy(info), Result(result) {} 13067 13068 bool Success(const APValue &V, const Expr *e) { 13069 Result = V.getFloat(); 13070 return true; 13071 } 13072 13073 bool ZeroInitialization(const Expr *E) { 13074 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13075 return true; 13076 } 13077 13078 bool VisitCallExpr(const CallExpr *E); 13079 13080 bool VisitUnaryOperator(const UnaryOperator *E); 13081 bool VisitBinaryOperator(const BinaryOperator *E); 13082 bool VisitFloatingLiteral(const FloatingLiteral *E); 13083 bool VisitCastExpr(const CastExpr *E); 13084 13085 bool VisitUnaryReal(const UnaryOperator *E); 13086 bool VisitUnaryImag(const UnaryOperator *E); 13087 13088 // FIXME: Missing: array subscript of vector, member of vector 13089 }; 13090 } // end anonymous namespace 13091 13092 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13093 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13094 return FloatExprEvaluator(Info, Result).Visit(E); 13095 } 13096 13097 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13098 QualType ResultTy, 13099 const Expr *Arg, 13100 bool SNaN, 13101 llvm::APFloat &Result) { 13102 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13103 if (!S) return false; 13104 13105 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13106 13107 llvm::APInt fill; 13108 13109 // Treat empty strings as if they were zero. 13110 if (S->getString().empty()) 13111 fill = llvm::APInt(32, 0); 13112 else if (S->getString().getAsInteger(0, fill)) 13113 return false; 13114 13115 if (Context.getTargetInfo().isNan2008()) { 13116 if (SNaN) 13117 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13118 else 13119 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13120 } else { 13121 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13122 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13123 // a different encoding to what became a standard in 2008, and for pre- 13124 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13125 // sNaN. This is now known as "legacy NaN" encoding. 13126 if (SNaN) 13127 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13128 else 13129 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13130 } 13131 13132 return true; 13133 } 13134 13135 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13136 switch (E->getBuiltinCallee()) { 13137 default: 13138 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13139 13140 case Builtin::BI__builtin_huge_val: 13141 case Builtin::BI__builtin_huge_valf: 13142 case Builtin::BI__builtin_huge_vall: 13143 case Builtin::BI__builtin_huge_valf128: 13144 case Builtin::BI__builtin_inf: 13145 case Builtin::BI__builtin_inff: 13146 case Builtin::BI__builtin_infl: 13147 case Builtin::BI__builtin_inff128: { 13148 const llvm::fltSemantics &Sem = 13149 Info.Ctx.getFloatTypeSemantics(E->getType()); 13150 Result = llvm::APFloat::getInf(Sem); 13151 return true; 13152 } 13153 13154 case Builtin::BI__builtin_nans: 13155 case Builtin::BI__builtin_nansf: 13156 case Builtin::BI__builtin_nansl: 13157 case Builtin::BI__builtin_nansf128: 13158 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13159 true, Result)) 13160 return Error(E); 13161 return true; 13162 13163 case Builtin::BI__builtin_nan: 13164 case Builtin::BI__builtin_nanf: 13165 case Builtin::BI__builtin_nanl: 13166 case Builtin::BI__builtin_nanf128: 13167 // If this is __builtin_nan() turn this into a nan, otherwise we 13168 // can't constant fold it. 13169 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13170 false, Result)) 13171 return Error(E); 13172 return true; 13173 13174 case Builtin::BI__builtin_fabs: 13175 case Builtin::BI__builtin_fabsf: 13176 case Builtin::BI__builtin_fabsl: 13177 case Builtin::BI__builtin_fabsf128: 13178 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13179 return false; 13180 13181 if (Result.isNegative()) 13182 Result.changeSign(); 13183 return true; 13184 13185 // FIXME: Builtin::BI__builtin_powi 13186 // FIXME: Builtin::BI__builtin_powif 13187 // FIXME: Builtin::BI__builtin_powil 13188 13189 case Builtin::BI__builtin_copysign: 13190 case Builtin::BI__builtin_copysignf: 13191 case Builtin::BI__builtin_copysignl: 13192 case Builtin::BI__builtin_copysignf128: { 13193 APFloat RHS(0.); 13194 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13195 !EvaluateFloat(E->getArg(1), RHS, Info)) 13196 return false; 13197 Result.copySign(RHS); 13198 return true; 13199 } 13200 } 13201 } 13202 13203 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13204 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13205 ComplexValue CV; 13206 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13207 return false; 13208 Result = CV.FloatReal; 13209 return true; 13210 } 13211 13212 return Visit(E->getSubExpr()); 13213 } 13214 13215 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13216 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13217 ComplexValue CV; 13218 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13219 return false; 13220 Result = CV.FloatImag; 13221 return true; 13222 } 13223 13224 VisitIgnoredValue(E->getSubExpr()); 13225 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13226 Result = llvm::APFloat::getZero(Sem); 13227 return true; 13228 } 13229 13230 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13231 switch (E->getOpcode()) { 13232 default: return Error(E); 13233 case UO_Plus: 13234 return EvaluateFloat(E->getSubExpr(), Result, Info); 13235 case UO_Minus: 13236 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13237 return false; 13238 Result.changeSign(); 13239 return true; 13240 } 13241 } 13242 13243 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13244 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13245 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13246 13247 APFloat RHS(0.0); 13248 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13249 if (!LHSOK && !Info.noteFailure()) 13250 return false; 13251 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13252 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13253 } 13254 13255 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13256 Result = E->getValue(); 13257 return true; 13258 } 13259 13260 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13261 const Expr* SubExpr = E->getSubExpr(); 13262 13263 switch (E->getCastKind()) { 13264 default: 13265 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13266 13267 case CK_IntegralToFloating: { 13268 APSInt IntResult; 13269 return EvaluateInteger(SubExpr, IntResult, Info) && 13270 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 13271 E->getType(), Result); 13272 } 13273 13274 case CK_FloatingCast: { 13275 if (!Visit(SubExpr)) 13276 return false; 13277 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13278 Result); 13279 } 13280 13281 case CK_FloatingComplexToReal: { 13282 ComplexValue V; 13283 if (!EvaluateComplex(SubExpr, V, Info)) 13284 return false; 13285 Result = V.getComplexFloatReal(); 13286 return true; 13287 } 13288 } 13289 } 13290 13291 //===----------------------------------------------------------------------===// 13292 // Complex Evaluation (for float and integer) 13293 //===----------------------------------------------------------------------===// 13294 13295 namespace { 13296 class ComplexExprEvaluator 13297 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13298 ComplexValue &Result; 13299 13300 public: 13301 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13302 : ExprEvaluatorBaseTy(info), Result(Result) {} 13303 13304 bool Success(const APValue &V, const Expr *e) { 13305 Result.setFrom(V); 13306 return true; 13307 } 13308 13309 bool ZeroInitialization(const Expr *E); 13310 13311 //===--------------------------------------------------------------------===// 13312 // Visitor Methods 13313 //===--------------------------------------------------------------------===// 13314 13315 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13316 bool VisitCastExpr(const CastExpr *E); 13317 bool VisitBinaryOperator(const BinaryOperator *E); 13318 bool VisitUnaryOperator(const UnaryOperator *E); 13319 bool VisitInitListExpr(const InitListExpr *E); 13320 bool VisitCallExpr(const CallExpr *E); 13321 }; 13322 } // end anonymous namespace 13323 13324 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13325 EvalInfo &Info) { 13326 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13327 return ComplexExprEvaluator(Info, Result).Visit(E); 13328 } 13329 13330 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13331 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13332 if (ElemTy->isRealFloatingType()) { 13333 Result.makeComplexFloat(); 13334 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13335 Result.FloatReal = Zero; 13336 Result.FloatImag = Zero; 13337 } else { 13338 Result.makeComplexInt(); 13339 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13340 Result.IntReal = Zero; 13341 Result.IntImag = Zero; 13342 } 13343 return true; 13344 } 13345 13346 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13347 const Expr* SubExpr = E->getSubExpr(); 13348 13349 if (SubExpr->getType()->isRealFloatingType()) { 13350 Result.makeComplexFloat(); 13351 APFloat &Imag = Result.FloatImag; 13352 if (!EvaluateFloat(SubExpr, Imag, Info)) 13353 return false; 13354 13355 Result.FloatReal = APFloat(Imag.getSemantics()); 13356 return true; 13357 } else { 13358 assert(SubExpr->getType()->isIntegerType() && 13359 "Unexpected imaginary literal."); 13360 13361 Result.makeComplexInt(); 13362 APSInt &Imag = Result.IntImag; 13363 if (!EvaluateInteger(SubExpr, Imag, Info)) 13364 return false; 13365 13366 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13367 return true; 13368 } 13369 } 13370 13371 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13372 13373 switch (E->getCastKind()) { 13374 case CK_BitCast: 13375 case CK_BaseToDerived: 13376 case CK_DerivedToBase: 13377 case CK_UncheckedDerivedToBase: 13378 case CK_Dynamic: 13379 case CK_ToUnion: 13380 case CK_ArrayToPointerDecay: 13381 case CK_FunctionToPointerDecay: 13382 case CK_NullToPointer: 13383 case CK_NullToMemberPointer: 13384 case CK_BaseToDerivedMemberPointer: 13385 case CK_DerivedToBaseMemberPointer: 13386 case CK_MemberPointerToBoolean: 13387 case CK_ReinterpretMemberPointer: 13388 case CK_ConstructorConversion: 13389 case CK_IntegralToPointer: 13390 case CK_PointerToIntegral: 13391 case CK_PointerToBoolean: 13392 case CK_ToVoid: 13393 case CK_VectorSplat: 13394 case CK_IntegralCast: 13395 case CK_BooleanToSignedIntegral: 13396 case CK_IntegralToBoolean: 13397 case CK_IntegralToFloating: 13398 case CK_FloatingToIntegral: 13399 case CK_FloatingToBoolean: 13400 case CK_FloatingCast: 13401 case CK_CPointerToObjCPointerCast: 13402 case CK_BlockPointerToObjCPointerCast: 13403 case CK_AnyPointerToBlockPointerCast: 13404 case CK_ObjCObjectLValueCast: 13405 case CK_FloatingComplexToReal: 13406 case CK_FloatingComplexToBoolean: 13407 case CK_IntegralComplexToReal: 13408 case CK_IntegralComplexToBoolean: 13409 case CK_ARCProduceObject: 13410 case CK_ARCConsumeObject: 13411 case CK_ARCReclaimReturnedObject: 13412 case CK_ARCExtendBlockObject: 13413 case CK_CopyAndAutoreleaseBlockObject: 13414 case CK_BuiltinFnToFnPtr: 13415 case CK_ZeroToOCLOpaqueType: 13416 case CK_NonAtomicToAtomic: 13417 case CK_AddressSpaceConversion: 13418 case CK_IntToOCLSampler: 13419 case CK_FixedPointCast: 13420 case CK_FixedPointToBoolean: 13421 case CK_FixedPointToIntegral: 13422 case CK_IntegralToFixedPoint: 13423 llvm_unreachable("invalid cast kind for complex value"); 13424 13425 case CK_LValueToRValue: 13426 case CK_AtomicToNonAtomic: 13427 case CK_NoOp: 13428 case CK_LValueToRValueBitCast: 13429 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13430 13431 case CK_Dependent: 13432 case CK_LValueBitCast: 13433 case CK_UserDefinedConversion: 13434 return Error(E); 13435 13436 case CK_FloatingRealToComplex: { 13437 APFloat &Real = Result.FloatReal; 13438 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13439 return false; 13440 13441 Result.makeComplexFloat(); 13442 Result.FloatImag = APFloat(Real.getSemantics()); 13443 return true; 13444 } 13445 13446 case CK_FloatingComplexCast: { 13447 if (!Visit(E->getSubExpr())) 13448 return false; 13449 13450 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13451 QualType From 13452 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13453 13454 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13455 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13456 } 13457 13458 case CK_FloatingComplexToIntegralComplex: { 13459 if (!Visit(E->getSubExpr())) 13460 return false; 13461 13462 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13463 QualType From 13464 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13465 Result.makeComplexInt(); 13466 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13467 To, Result.IntReal) && 13468 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13469 To, Result.IntImag); 13470 } 13471 13472 case CK_IntegralRealToComplex: { 13473 APSInt &Real = Result.IntReal; 13474 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13475 return false; 13476 13477 Result.makeComplexInt(); 13478 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13479 return true; 13480 } 13481 13482 case CK_IntegralComplexCast: { 13483 if (!Visit(E->getSubExpr())) 13484 return false; 13485 13486 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13487 QualType From 13488 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13489 13490 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13491 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13492 return true; 13493 } 13494 13495 case CK_IntegralComplexToFloatingComplex: { 13496 if (!Visit(E->getSubExpr())) 13497 return false; 13498 13499 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13500 QualType From 13501 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13502 Result.makeComplexFloat(); 13503 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13504 To, Result.FloatReal) && 13505 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13506 To, Result.FloatImag); 13507 } 13508 } 13509 13510 llvm_unreachable("unknown cast resulting in complex value"); 13511 } 13512 13513 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13514 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13515 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13516 13517 // Track whether the LHS or RHS is real at the type system level. When this is 13518 // the case we can simplify our evaluation strategy. 13519 bool LHSReal = false, RHSReal = false; 13520 13521 bool LHSOK; 13522 if (E->getLHS()->getType()->isRealFloatingType()) { 13523 LHSReal = true; 13524 APFloat &Real = Result.FloatReal; 13525 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13526 if (LHSOK) { 13527 Result.makeComplexFloat(); 13528 Result.FloatImag = APFloat(Real.getSemantics()); 13529 } 13530 } else { 13531 LHSOK = Visit(E->getLHS()); 13532 } 13533 if (!LHSOK && !Info.noteFailure()) 13534 return false; 13535 13536 ComplexValue RHS; 13537 if (E->getRHS()->getType()->isRealFloatingType()) { 13538 RHSReal = true; 13539 APFloat &Real = RHS.FloatReal; 13540 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13541 return false; 13542 RHS.makeComplexFloat(); 13543 RHS.FloatImag = APFloat(Real.getSemantics()); 13544 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13545 return false; 13546 13547 assert(!(LHSReal && RHSReal) && 13548 "Cannot have both operands of a complex operation be real."); 13549 switch (E->getOpcode()) { 13550 default: return Error(E); 13551 case BO_Add: 13552 if (Result.isComplexFloat()) { 13553 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13554 APFloat::rmNearestTiesToEven); 13555 if (LHSReal) 13556 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13557 else if (!RHSReal) 13558 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13559 APFloat::rmNearestTiesToEven); 13560 } else { 13561 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13562 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13563 } 13564 break; 13565 case BO_Sub: 13566 if (Result.isComplexFloat()) { 13567 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13568 APFloat::rmNearestTiesToEven); 13569 if (LHSReal) { 13570 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13571 Result.getComplexFloatImag().changeSign(); 13572 } else if (!RHSReal) { 13573 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13574 APFloat::rmNearestTiesToEven); 13575 } 13576 } else { 13577 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13578 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13579 } 13580 break; 13581 case BO_Mul: 13582 if (Result.isComplexFloat()) { 13583 // This is an implementation of complex multiplication according to the 13584 // constraints laid out in C11 Annex G. The implementation uses the 13585 // following naming scheme: 13586 // (a + ib) * (c + id) 13587 ComplexValue LHS = Result; 13588 APFloat &A = LHS.getComplexFloatReal(); 13589 APFloat &B = LHS.getComplexFloatImag(); 13590 APFloat &C = RHS.getComplexFloatReal(); 13591 APFloat &D = RHS.getComplexFloatImag(); 13592 APFloat &ResR = Result.getComplexFloatReal(); 13593 APFloat &ResI = Result.getComplexFloatImag(); 13594 if (LHSReal) { 13595 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13596 ResR = A * C; 13597 ResI = A * D; 13598 } else if (RHSReal) { 13599 ResR = C * A; 13600 ResI = C * B; 13601 } else { 13602 // In the fully general case, we need to handle NaNs and infinities 13603 // robustly. 13604 APFloat AC = A * C; 13605 APFloat BD = B * D; 13606 APFloat AD = A * D; 13607 APFloat BC = B * C; 13608 ResR = AC - BD; 13609 ResI = AD + BC; 13610 if (ResR.isNaN() && ResI.isNaN()) { 13611 bool Recalc = false; 13612 if (A.isInfinity() || B.isInfinity()) { 13613 A = APFloat::copySign( 13614 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13615 B = APFloat::copySign( 13616 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13617 if (C.isNaN()) 13618 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13619 if (D.isNaN()) 13620 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13621 Recalc = true; 13622 } 13623 if (C.isInfinity() || D.isInfinity()) { 13624 C = APFloat::copySign( 13625 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13626 D = APFloat::copySign( 13627 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13628 if (A.isNaN()) 13629 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13630 if (B.isNaN()) 13631 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13632 Recalc = true; 13633 } 13634 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 13635 AD.isInfinity() || BC.isInfinity())) { 13636 if (A.isNaN()) 13637 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13638 if (B.isNaN()) 13639 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13640 if (C.isNaN()) 13641 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13642 if (D.isNaN()) 13643 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13644 Recalc = true; 13645 } 13646 if (Recalc) { 13647 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 13648 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 13649 } 13650 } 13651 } 13652 } else { 13653 ComplexValue LHS = Result; 13654 Result.getComplexIntReal() = 13655 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 13656 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 13657 Result.getComplexIntImag() = 13658 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 13659 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 13660 } 13661 break; 13662 case BO_Div: 13663 if (Result.isComplexFloat()) { 13664 // This is an implementation of complex division according to the 13665 // constraints laid out in C11 Annex G. The implementation uses the 13666 // following naming scheme: 13667 // (a + ib) / (c + id) 13668 ComplexValue LHS = Result; 13669 APFloat &A = LHS.getComplexFloatReal(); 13670 APFloat &B = LHS.getComplexFloatImag(); 13671 APFloat &C = RHS.getComplexFloatReal(); 13672 APFloat &D = RHS.getComplexFloatImag(); 13673 APFloat &ResR = Result.getComplexFloatReal(); 13674 APFloat &ResI = Result.getComplexFloatImag(); 13675 if (RHSReal) { 13676 ResR = A / C; 13677 ResI = B / C; 13678 } else { 13679 if (LHSReal) { 13680 // No real optimizations we can do here, stub out with zero. 13681 B = APFloat::getZero(A.getSemantics()); 13682 } 13683 int DenomLogB = 0; 13684 APFloat MaxCD = maxnum(abs(C), abs(D)); 13685 if (MaxCD.isFinite()) { 13686 DenomLogB = ilogb(MaxCD); 13687 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 13688 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 13689 } 13690 APFloat Denom = C * C + D * D; 13691 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 13692 APFloat::rmNearestTiesToEven); 13693 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 13694 APFloat::rmNearestTiesToEven); 13695 if (ResR.isNaN() && ResI.isNaN()) { 13696 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 13697 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 13698 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 13699 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 13700 D.isFinite()) { 13701 A = APFloat::copySign( 13702 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13703 B = APFloat::copySign( 13704 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13705 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 13706 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 13707 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 13708 C = APFloat::copySign( 13709 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13710 D = APFloat::copySign( 13711 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13712 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 13713 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 13714 } 13715 } 13716 } 13717 } else { 13718 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 13719 return Error(E, diag::note_expr_divide_by_zero); 13720 13721 ComplexValue LHS = Result; 13722 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 13723 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 13724 Result.getComplexIntReal() = 13725 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 13726 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 13727 Result.getComplexIntImag() = 13728 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 13729 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 13730 } 13731 break; 13732 } 13733 13734 return true; 13735 } 13736 13737 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13738 // Get the operand value into 'Result'. 13739 if (!Visit(E->getSubExpr())) 13740 return false; 13741 13742 switch (E->getOpcode()) { 13743 default: 13744 return Error(E); 13745 case UO_Extension: 13746 return true; 13747 case UO_Plus: 13748 // The result is always just the subexpr. 13749 return true; 13750 case UO_Minus: 13751 if (Result.isComplexFloat()) { 13752 Result.getComplexFloatReal().changeSign(); 13753 Result.getComplexFloatImag().changeSign(); 13754 } 13755 else { 13756 Result.getComplexIntReal() = -Result.getComplexIntReal(); 13757 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13758 } 13759 return true; 13760 case UO_Not: 13761 if (Result.isComplexFloat()) 13762 Result.getComplexFloatImag().changeSign(); 13763 else 13764 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13765 return true; 13766 } 13767 } 13768 13769 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 13770 if (E->getNumInits() == 2) { 13771 if (E->getType()->isComplexType()) { 13772 Result.makeComplexFloat(); 13773 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 13774 return false; 13775 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 13776 return false; 13777 } else { 13778 Result.makeComplexInt(); 13779 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 13780 return false; 13781 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 13782 return false; 13783 } 13784 return true; 13785 } 13786 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 13787 } 13788 13789 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 13790 switch (E->getBuiltinCallee()) { 13791 case Builtin::BI__builtin_complex: 13792 Result.makeComplexFloat(); 13793 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 13794 return false; 13795 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 13796 return false; 13797 return true; 13798 13799 default: 13800 break; 13801 } 13802 13803 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13804 } 13805 13806 //===----------------------------------------------------------------------===// 13807 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 13808 // implicit conversion. 13809 //===----------------------------------------------------------------------===// 13810 13811 namespace { 13812 class AtomicExprEvaluator : 13813 public ExprEvaluatorBase<AtomicExprEvaluator> { 13814 const LValue *This; 13815 APValue &Result; 13816 public: 13817 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 13818 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 13819 13820 bool Success(const APValue &V, const Expr *E) { 13821 Result = V; 13822 return true; 13823 } 13824 13825 bool ZeroInitialization(const Expr *E) { 13826 ImplicitValueInitExpr VIE( 13827 E->getType()->castAs<AtomicType>()->getValueType()); 13828 // For atomic-qualified class (and array) types in C++, initialize the 13829 // _Atomic-wrapped subobject directly, in-place. 13830 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 13831 : Evaluate(Result, Info, &VIE); 13832 } 13833 13834 bool VisitCastExpr(const CastExpr *E) { 13835 switch (E->getCastKind()) { 13836 default: 13837 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13838 case CK_NonAtomicToAtomic: 13839 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 13840 : Evaluate(Result, Info, E->getSubExpr()); 13841 } 13842 } 13843 }; 13844 } // end anonymous namespace 13845 13846 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 13847 EvalInfo &Info) { 13848 assert(E->isRValue() && E->getType()->isAtomicType()); 13849 return AtomicExprEvaluator(Info, This, Result).Visit(E); 13850 } 13851 13852 //===----------------------------------------------------------------------===// 13853 // Void expression evaluation, primarily for a cast to void on the LHS of a 13854 // comma operator 13855 //===----------------------------------------------------------------------===// 13856 13857 namespace { 13858 class VoidExprEvaluator 13859 : public ExprEvaluatorBase<VoidExprEvaluator> { 13860 public: 13861 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 13862 13863 bool Success(const APValue &V, const Expr *e) { return true; } 13864 13865 bool ZeroInitialization(const Expr *E) { return true; } 13866 13867 bool VisitCastExpr(const CastExpr *E) { 13868 switch (E->getCastKind()) { 13869 default: 13870 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13871 case CK_ToVoid: 13872 VisitIgnoredValue(E->getSubExpr()); 13873 return true; 13874 } 13875 } 13876 13877 bool VisitCallExpr(const CallExpr *E) { 13878 switch (E->getBuiltinCallee()) { 13879 case Builtin::BI__assume: 13880 case Builtin::BI__builtin_assume: 13881 // The argument is not evaluated! 13882 return true; 13883 13884 case Builtin::BI__builtin_operator_delete: 13885 return HandleOperatorDeleteCall(Info, E); 13886 13887 default: 13888 break; 13889 } 13890 13891 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13892 } 13893 13894 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 13895 }; 13896 } // end anonymous namespace 13897 13898 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 13899 // We cannot speculatively evaluate a delete expression. 13900 if (Info.SpeculativeEvaluationDepth) 13901 return false; 13902 13903 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 13904 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 13905 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13906 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 13907 return false; 13908 } 13909 13910 const Expr *Arg = E->getArgument(); 13911 13912 LValue Pointer; 13913 if (!EvaluatePointer(Arg, Pointer, Info)) 13914 return false; 13915 if (Pointer.Designator.Invalid) 13916 return false; 13917 13918 // Deleting a null pointer has no effect. 13919 if (Pointer.isNullPointer()) { 13920 // This is the only case where we need to produce an extension warning: 13921 // the only other way we can succeed is if we find a dynamic allocation, 13922 // and we will have warned when we allocated it in that case. 13923 if (!Info.getLangOpts().CPlusPlus20) 13924 Info.CCEDiag(E, diag::note_constexpr_new); 13925 return true; 13926 } 13927 13928 Optional<DynAlloc *> Alloc = CheckDeleteKind( 13929 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 13930 if (!Alloc) 13931 return false; 13932 QualType AllocType = Pointer.Base.getDynamicAllocType(); 13933 13934 // For the non-array case, the designator must be empty if the static type 13935 // does not have a virtual destructor. 13936 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 13937 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 13938 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 13939 << Arg->getType()->getPointeeType() << AllocType; 13940 return false; 13941 } 13942 13943 // For a class type with a virtual destructor, the selected operator delete 13944 // is the one looked up when building the destructor. 13945 if (!E->isArrayForm() && !E->isGlobalDelete()) { 13946 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 13947 if (VirtualDelete && 13948 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 13949 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13950 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 13951 return false; 13952 } 13953 } 13954 13955 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 13956 (*Alloc)->Value, AllocType)) 13957 return false; 13958 13959 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 13960 // The element was already erased. This means the destructor call also 13961 // deleted the object. 13962 // FIXME: This probably results in undefined behavior before we get this 13963 // far, and should be diagnosed elsewhere first. 13964 Info.FFDiag(E, diag::note_constexpr_double_delete); 13965 return false; 13966 } 13967 13968 return true; 13969 } 13970 13971 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 13972 assert(E->isRValue() && E->getType()->isVoidType()); 13973 return VoidExprEvaluator(Info).Visit(E); 13974 } 13975 13976 //===----------------------------------------------------------------------===// 13977 // Top level Expr::EvaluateAsRValue method. 13978 //===----------------------------------------------------------------------===// 13979 13980 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 13981 // In C, function designators are not lvalues, but we evaluate them as if they 13982 // are. 13983 QualType T = E->getType(); 13984 if (E->isGLValue() || T->isFunctionType()) { 13985 LValue LV; 13986 if (!EvaluateLValue(E, LV, Info)) 13987 return false; 13988 LV.moveInto(Result); 13989 } else if (T->isVectorType()) { 13990 if (!EvaluateVector(E, Result, Info)) 13991 return false; 13992 } else if (T->isIntegralOrEnumerationType()) { 13993 if (!IntExprEvaluator(Info, Result).Visit(E)) 13994 return false; 13995 } else if (T->hasPointerRepresentation()) { 13996 LValue LV; 13997 if (!EvaluatePointer(E, LV, Info)) 13998 return false; 13999 LV.moveInto(Result); 14000 } else if (T->isRealFloatingType()) { 14001 llvm::APFloat F(0.0); 14002 if (!EvaluateFloat(E, F, Info)) 14003 return false; 14004 Result = APValue(F); 14005 } else if (T->isAnyComplexType()) { 14006 ComplexValue C; 14007 if (!EvaluateComplex(E, C, Info)) 14008 return false; 14009 C.moveInto(Result); 14010 } else if (T->isFixedPointType()) { 14011 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14012 } else if (T->isMemberPointerType()) { 14013 MemberPtr P; 14014 if (!EvaluateMemberPointer(E, P, Info)) 14015 return false; 14016 P.moveInto(Result); 14017 return true; 14018 } else if (T->isArrayType()) { 14019 LValue LV; 14020 APValue &Value = 14021 Info.CurrentCall->createTemporary(E, T, false, LV); 14022 if (!EvaluateArray(E, LV, Value, Info)) 14023 return false; 14024 Result = Value; 14025 } else if (T->isRecordType()) { 14026 LValue LV; 14027 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 14028 if (!EvaluateRecord(E, LV, Value, Info)) 14029 return false; 14030 Result = Value; 14031 } else if (T->isVoidType()) { 14032 if (!Info.getLangOpts().CPlusPlus11) 14033 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14034 << E->getType(); 14035 if (!EvaluateVoid(E, Info)) 14036 return false; 14037 } else if (T->isAtomicType()) { 14038 QualType Unqual = T.getAtomicUnqualifiedType(); 14039 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14040 LValue LV; 14041 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 14042 if (!EvaluateAtomic(E, &LV, Value, Info)) 14043 return false; 14044 } else { 14045 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14046 return false; 14047 } 14048 } else if (Info.getLangOpts().CPlusPlus11) { 14049 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14050 return false; 14051 } else { 14052 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14053 return false; 14054 } 14055 14056 return true; 14057 } 14058 14059 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14060 /// cases, the in-place evaluation is essential, since later initializers for 14061 /// an object can indirectly refer to subobjects which were initialized earlier. 14062 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14063 const Expr *E, bool AllowNonLiteralTypes) { 14064 assert(!E->isValueDependent()); 14065 14066 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14067 return false; 14068 14069 if (E->isRValue()) { 14070 // Evaluate arrays and record types in-place, so that later initializers can 14071 // refer to earlier-initialized members of the object. 14072 QualType T = E->getType(); 14073 if (T->isArrayType()) 14074 return EvaluateArray(E, This, Result, Info); 14075 else if (T->isRecordType()) 14076 return EvaluateRecord(E, This, Result, Info); 14077 else if (T->isAtomicType()) { 14078 QualType Unqual = T.getAtomicUnqualifiedType(); 14079 if (Unqual->isArrayType() || Unqual->isRecordType()) 14080 return EvaluateAtomic(E, &This, Result, Info); 14081 } 14082 } 14083 14084 // For any other type, in-place evaluation is unimportant. 14085 return Evaluate(Result, Info, E); 14086 } 14087 14088 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14089 /// lvalue-to-rvalue cast if it is an lvalue. 14090 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14091 if (Info.EnableNewConstInterp) { 14092 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14093 return false; 14094 } else { 14095 if (E->getType().isNull()) 14096 return false; 14097 14098 if (!CheckLiteralType(Info, E)) 14099 return false; 14100 14101 if (!::Evaluate(Result, Info, E)) 14102 return false; 14103 14104 if (E->isGLValue()) { 14105 LValue LV; 14106 LV.setFrom(Info.Ctx, Result); 14107 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14108 return false; 14109 } 14110 } 14111 14112 // Check this core constant expression is a constant expression. 14113 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 14114 CheckMemoryLeaks(Info); 14115 } 14116 14117 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14118 const ASTContext &Ctx, bool &IsConst) { 14119 // Fast-path evaluations of integer literals, since we sometimes see files 14120 // containing vast quantities of these. 14121 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14122 Result.Val = APValue(APSInt(L->getValue(), 14123 L->getType()->isUnsignedIntegerType())); 14124 IsConst = true; 14125 return true; 14126 } 14127 14128 // This case should be rare, but we need to check it before we check on 14129 // the type below. 14130 if (Exp->getType().isNull()) { 14131 IsConst = false; 14132 return true; 14133 } 14134 14135 // FIXME: Evaluating values of large array and record types can cause 14136 // performance problems. Only do so in C++11 for now. 14137 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14138 Exp->getType()->isRecordType()) && 14139 !Ctx.getLangOpts().CPlusPlus11) { 14140 IsConst = false; 14141 return true; 14142 } 14143 return false; 14144 } 14145 14146 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14147 Expr::SideEffectsKind SEK) { 14148 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14149 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14150 } 14151 14152 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14153 const ASTContext &Ctx, EvalInfo &Info) { 14154 bool IsConst; 14155 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14156 return IsConst; 14157 14158 return EvaluateAsRValue(Info, E, Result.Val); 14159 } 14160 14161 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14162 const ASTContext &Ctx, 14163 Expr::SideEffectsKind AllowSideEffects, 14164 EvalInfo &Info) { 14165 if (!E->getType()->isIntegralOrEnumerationType()) 14166 return false; 14167 14168 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14169 !ExprResult.Val.isInt() || 14170 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14171 return false; 14172 14173 return true; 14174 } 14175 14176 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14177 const ASTContext &Ctx, 14178 Expr::SideEffectsKind AllowSideEffects, 14179 EvalInfo &Info) { 14180 if (!E->getType()->isFixedPointType()) 14181 return false; 14182 14183 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14184 return false; 14185 14186 if (!ExprResult.Val.isFixedPoint() || 14187 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14188 return false; 14189 14190 return true; 14191 } 14192 14193 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14194 /// any crazy technique (that has nothing to do with language standards) that 14195 /// we want to. If this function returns true, it returns the folded constant 14196 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14197 /// will be applied to the result. 14198 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14199 bool InConstantContext) const { 14200 assert(!isValueDependent() && 14201 "Expression evaluator can't be called on a dependent expression."); 14202 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14203 Info.InConstantContext = InConstantContext; 14204 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14205 } 14206 14207 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14208 bool InConstantContext) const { 14209 assert(!isValueDependent() && 14210 "Expression evaluator can't be called on a dependent expression."); 14211 EvalResult Scratch; 14212 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14213 HandleConversionToBool(Scratch.Val, Result); 14214 } 14215 14216 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14217 SideEffectsKind AllowSideEffects, 14218 bool InConstantContext) const { 14219 assert(!isValueDependent() && 14220 "Expression evaluator can't be called on a dependent expression."); 14221 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14222 Info.InConstantContext = InConstantContext; 14223 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14224 } 14225 14226 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14227 SideEffectsKind AllowSideEffects, 14228 bool InConstantContext) const { 14229 assert(!isValueDependent() && 14230 "Expression evaluator can't be called on a dependent expression."); 14231 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14232 Info.InConstantContext = InConstantContext; 14233 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14234 } 14235 14236 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14237 SideEffectsKind AllowSideEffects, 14238 bool InConstantContext) const { 14239 assert(!isValueDependent() && 14240 "Expression evaluator can't be called on a dependent expression."); 14241 14242 if (!getType()->isRealFloatingType()) 14243 return false; 14244 14245 EvalResult ExprResult; 14246 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14247 !ExprResult.Val.isFloat() || 14248 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14249 return false; 14250 14251 Result = ExprResult.Val.getFloat(); 14252 return true; 14253 } 14254 14255 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14256 bool InConstantContext) const { 14257 assert(!isValueDependent() && 14258 "Expression evaluator can't be called on a dependent expression."); 14259 14260 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14261 Info.InConstantContext = InConstantContext; 14262 LValue LV; 14263 CheckedTemporaries CheckedTemps; 14264 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14265 Result.HasSideEffects || 14266 !CheckLValueConstantExpression(Info, getExprLoc(), 14267 Ctx.getLValueReferenceType(getType()), LV, 14268 Expr::EvaluateForCodeGen, CheckedTemps)) 14269 return false; 14270 14271 LV.moveInto(Result.Val); 14272 return true; 14273 } 14274 14275 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 14276 const ASTContext &Ctx, bool InPlace) const { 14277 assert(!isValueDependent() && 14278 "Expression evaluator can't be called on a dependent expression."); 14279 14280 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14281 EvalInfo Info(Ctx, Result, EM); 14282 Info.InConstantContext = true; 14283 14284 if (InPlace) { 14285 Info.setEvaluatingDecl(this, Result.Val); 14286 LValue LVal; 14287 LVal.set(this); 14288 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 14289 Result.HasSideEffects) 14290 return false; 14291 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 14292 return false; 14293 14294 if (!Info.discardCleanups()) 14295 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14296 14297 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14298 Result.Val, Usage) && 14299 CheckMemoryLeaks(Info); 14300 } 14301 14302 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14303 const VarDecl *VD, 14304 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14305 assert(!isValueDependent() && 14306 "Expression evaluator can't be called on a dependent expression."); 14307 14308 // FIXME: Evaluating initializers for large array and record types can cause 14309 // performance problems. Only do so in C++11 for now. 14310 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14311 !Ctx.getLangOpts().CPlusPlus11) 14312 return false; 14313 14314 Expr::EvalStatus EStatus; 14315 EStatus.Diag = &Notes; 14316 14317 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 14318 ? EvalInfo::EM_ConstantExpression 14319 : EvalInfo::EM_ConstantFold); 14320 Info.setEvaluatingDecl(VD, Value); 14321 Info.InConstantContext = true; 14322 14323 SourceLocation DeclLoc = VD->getLocation(); 14324 QualType DeclTy = VD->getType(); 14325 14326 if (Info.EnableNewConstInterp) { 14327 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14328 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14329 return false; 14330 } else { 14331 LValue LVal; 14332 LVal.set(VD); 14333 14334 if (!EvaluateInPlace(Value, Info, LVal, this, 14335 /*AllowNonLiteralTypes=*/true) || 14336 EStatus.HasSideEffects) 14337 return false; 14338 14339 // At this point, any lifetime-extended temporaries are completely 14340 // initialized. 14341 Info.performLifetimeExtension(); 14342 14343 if (!Info.discardCleanups()) 14344 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14345 } 14346 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 14347 CheckMemoryLeaks(Info); 14348 } 14349 14350 bool VarDecl::evaluateDestruction( 14351 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14352 Expr::EvalStatus EStatus; 14353 EStatus.Diag = &Notes; 14354 14355 // Make a copy of the value for the destructor to mutate, if we know it. 14356 // Otherwise, treat the value as default-initialized; if the destructor works 14357 // anyway, then the destruction is constant (and must be essentially empty). 14358 APValue DestroyedValue; 14359 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14360 DestroyedValue = *getEvaluatedValue(); 14361 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14362 return false; 14363 14364 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 14365 Info.setEvaluatingDecl(this, DestroyedValue, 14366 EvalInfo::EvaluatingDeclKind::Dtor); 14367 Info.InConstantContext = true; 14368 14369 SourceLocation DeclLoc = getLocation(); 14370 QualType DeclTy = getType(); 14371 14372 LValue LVal; 14373 LVal.set(this); 14374 14375 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 14376 EStatus.HasSideEffects) 14377 return false; 14378 14379 if (!Info.discardCleanups()) 14380 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14381 14382 ensureEvaluatedStmt()->HasConstantDestruction = true; 14383 return true; 14384 } 14385 14386 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14387 /// constant folded, but discard the result. 14388 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14389 assert(!isValueDependent() && 14390 "Expression evaluator can't be called on a dependent expression."); 14391 14392 EvalResult Result; 14393 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14394 !hasUnacceptableSideEffect(Result, SEK); 14395 } 14396 14397 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14398 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14399 assert(!isValueDependent() && 14400 "Expression evaluator can't be called on a dependent expression."); 14401 14402 EvalResult EVResult; 14403 EVResult.Diag = Diag; 14404 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14405 Info.InConstantContext = true; 14406 14407 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14408 (void)Result; 14409 assert(Result && "Could not evaluate expression"); 14410 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14411 14412 return EVResult.Val.getInt(); 14413 } 14414 14415 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14416 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14417 assert(!isValueDependent() && 14418 "Expression evaluator can't be called on a dependent expression."); 14419 14420 EvalResult EVResult; 14421 EVResult.Diag = Diag; 14422 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14423 Info.InConstantContext = true; 14424 Info.CheckingForUndefinedBehavior = true; 14425 14426 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14427 (void)Result; 14428 assert(Result && "Could not evaluate expression"); 14429 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14430 14431 return EVResult.Val.getInt(); 14432 } 14433 14434 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14435 assert(!isValueDependent() && 14436 "Expression evaluator can't be called on a dependent expression."); 14437 14438 bool IsConst; 14439 EvalResult EVResult; 14440 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14441 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14442 Info.CheckingForUndefinedBehavior = true; 14443 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14444 } 14445 } 14446 14447 bool Expr::EvalResult::isGlobalLValue() const { 14448 assert(Val.isLValue()); 14449 return IsGlobalLValue(Val.getLValueBase()); 14450 } 14451 14452 14453 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14454 /// an integer constant expression. 14455 14456 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14457 /// comma, etc 14458 14459 // CheckICE - This function does the fundamental ICE checking: the returned 14460 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14461 // and a (possibly null) SourceLocation indicating the location of the problem. 14462 // 14463 // Note that to reduce code duplication, this helper does no evaluation 14464 // itself; the caller checks whether the expression is evaluatable, and 14465 // in the rare cases where CheckICE actually cares about the evaluated 14466 // value, it calls into Evaluate. 14467 14468 namespace { 14469 14470 enum ICEKind { 14471 /// This expression is an ICE. 14472 IK_ICE, 14473 /// This expression is not an ICE, but if it isn't evaluated, it's 14474 /// a legal subexpression for an ICE. This return value is used to handle 14475 /// the comma operator in C99 mode, and non-constant subexpressions. 14476 IK_ICEIfUnevaluated, 14477 /// This expression is not an ICE, and is not a legal subexpression for one. 14478 IK_NotICE 14479 }; 14480 14481 struct ICEDiag { 14482 ICEKind Kind; 14483 SourceLocation Loc; 14484 14485 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14486 }; 14487 14488 } 14489 14490 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14491 14492 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14493 14494 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14495 Expr::EvalResult EVResult; 14496 Expr::EvalStatus Status; 14497 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14498 14499 Info.InConstantContext = true; 14500 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14501 !EVResult.Val.isInt()) 14502 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14503 14504 return NoDiag(); 14505 } 14506 14507 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14508 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14509 if (!E->getType()->isIntegralOrEnumerationType()) 14510 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14511 14512 switch (E->getStmtClass()) { 14513 #define ABSTRACT_STMT(Node) 14514 #define STMT(Node, Base) case Expr::Node##Class: 14515 #define EXPR(Node, Base) 14516 #include "clang/AST/StmtNodes.inc" 14517 case Expr::PredefinedExprClass: 14518 case Expr::FloatingLiteralClass: 14519 case Expr::ImaginaryLiteralClass: 14520 case Expr::StringLiteralClass: 14521 case Expr::ArraySubscriptExprClass: 14522 case Expr::MatrixSubscriptExprClass: 14523 case Expr::OMPArraySectionExprClass: 14524 case Expr::OMPArrayShapingExprClass: 14525 case Expr::OMPIteratorExprClass: 14526 case Expr::MemberExprClass: 14527 case Expr::CompoundAssignOperatorClass: 14528 case Expr::CompoundLiteralExprClass: 14529 case Expr::ExtVectorElementExprClass: 14530 case Expr::DesignatedInitExprClass: 14531 case Expr::ArrayInitLoopExprClass: 14532 case Expr::ArrayInitIndexExprClass: 14533 case Expr::NoInitExprClass: 14534 case Expr::DesignatedInitUpdateExprClass: 14535 case Expr::ImplicitValueInitExprClass: 14536 case Expr::ParenListExprClass: 14537 case Expr::VAArgExprClass: 14538 case Expr::AddrLabelExprClass: 14539 case Expr::StmtExprClass: 14540 case Expr::CXXMemberCallExprClass: 14541 case Expr::CUDAKernelCallExprClass: 14542 case Expr::CXXAddrspaceCastExprClass: 14543 case Expr::CXXDynamicCastExprClass: 14544 case Expr::CXXTypeidExprClass: 14545 case Expr::CXXUuidofExprClass: 14546 case Expr::MSPropertyRefExprClass: 14547 case Expr::MSPropertySubscriptExprClass: 14548 case Expr::CXXNullPtrLiteralExprClass: 14549 case Expr::UserDefinedLiteralClass: 14550 case Expr::CXXThisExprClass: 14551 case Expr::CXXThrowExprClass: 14552 case Expr::CXXNewExprClass: 14553 case Expr::CXXDeleteExprClass: 14554 case Expr::CXXPseudoDestructorExprClass: 14555 case Expr::UnresolvedLookupExprClass: 14556 case Expr::TypoExprClass: 14557 case Expr::RecoveryExprClass: 14558 case Expr::DependentScopeDeclRefExprClass: 14559 case Expr::CXXConstructExprClass: 14560 case Expr::CXXInheritedCtorInitExprClass: 14561 case Expr::CXXStdInitializerListExprClass: 14562 case Expr::CXXBindTemporaryExprClass: 14563 case Expr::ExprWithCleanupsClass: 14564 case Expr::CXXTemporaryObjectExprClass: 14565 case Expr::CXXUnresolvedConstructExprClass: 14566 case Expr::CXXDependentScopeMemberExprClass: 14567 case Expr::UnresolvedMemberExprClass: 14568 case Expr::ObjCStringLiteralClass: 14569 case Expr::ObjCBoxedExprClass: 14570 case Expr::ObjCArrayLiteralClass: 14571 case Expr::ObjCDictionaryLiteralClass: 14572 case Expr::ObjCEncodeExprClass: 14573 case Expr::ObjCMessageExprClass: 14574 case Expr::ObjCSelectorExprClass: 14575 case Expr::ObjCProtocolExprClass: 14576 case Expr::ObjCIvarRefExprClass: 14577 case Expr::ObjCPropertyRefExprClass: 14578 case Expr::ObjCSubscriptRefExprClass: 14579 case Expr::ObjCIsaExprClass: 14580 case Expr::ObjCAvailabilityCheckExprClass: 14581 case Expr::ShuffleVectorExprClass: 14582 case Expr::ConvertVectorExprClass: 14583 case Expr::BlockExprClass: 14584 case Expr::NoStmtClass: 14585 case Expr::OpaqueValueExprClass: 14586 case Expr::PackExpansionExprClass: 14587 case Expr::SubstNonTypeTemplateParmPackExprClass: 14588 case Expr::FunctionParmPackExprClass: 14589 case Expr::AsTypeExprClass: 14590 case Expr::ObjCIndirectCopyRestoreExprClass: 14591 case Expr::MaterializeTemporaryExprClass: 14592 case Expr::PseudoObjectExprClass: 14593 case Expr::AtomicExprClass: 14594 case Expr::LambdaExprClass: 14595 case Expr::CXXFoldExprClass: 14596 case Expr::CoawaitExprClass: 14597 case Expr::DependentCoawaitExprClass: 14598 case Expr::CoyieldExprClass: 14599 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14600 14601 case Expr::InitListExprClass: { 14602 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14603 // form "T x = { a };" is equivalent to "T x = a;". 14604 // Unless we're initializing a reference, T is a scalar as it is known to be 14605 // of integral or enumeration type. 14606 if (E->isRValue()) 14607 if (cast<InitListExpr>(E)->getNumInits() == 1) 14608 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 14609 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14610 } 14611 14612 case Expr::SizeOfPackExprClass: 14613 case Expr::GNUNullExprClass: 14614 case Expr::SourceLocExprClass: 14615 return NoDiag(); 14616 14617 case Expr::SubstNonTypeTemplateParmExprClass: 14618 return 14619 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 14620 14621 case Expr::ConstantExprClass: 14622 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 14623 14624 case Expr::ParenExprClass: 14625 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 14626 case Expr::GenericSelectionExprClass: 14627 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 14628 case Expr::IntegerLiteralClass: 14629 case Expr::FixedPointLiteralClass: 14630 case Expr::CharacterLiteralClass: 14631 case Expr::ObjCBoolLiteralExprClass: 14632 case Expr::CXXBoolLiteralExprClass: 14633 case Expr::CXXScalarValueInitExprClass: 14634 case Expr::TypeTraitExprClass: 14635 case Expr::ConceptSpecializationExprClass: 14636 case Expr::RequiresExprClass: 14637 case Expr::ArrayTypeTraitExprClass: 14638 case Expr::ExpressionTraitExprClass: 14639 case Expr::CXXNoexceptExprClass: 14640 return NoDiag(); 14641 case Expr::CallExprClass: 14642 case Expr::CXXOperatorCallExprClass: { 14643 // C99 6.6/3 allows function calls within unevaluated subexpressions of 14644 // constant expressions, but they can never be ICEs because an ICE cannot 14645 // contain an operand of (pointer to) function type. 14646 const CallExpr *CE = cast<CallExpr>(E); 14647 if (CE->getBuiltinCallee()) 14648 return CheckEvalInICE(E, Ctx); 14649 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14650 } 14651 case Expr::CXXRewrittenBinaryOperatorClass: 14652 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 14653 Ctx); 14654 case Expr::DeclRefExprClass: { 14655 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 14656 return NoDiag(); 14657 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 14658 if (Ctx.getLangOpts().CPlusPlus && 14659 D && IsConstNonVolatile(D->getType())) { 14660 // Parameter variables are never constants. Without this check, 14661 // getAnyInitializer() can find a default argument, which leads 14662 // to chaos. 14663 if (isa<ParmVarDecl>(D)) 14664 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14665 14666 // C++ 7.1.5.1p2 14667 // A variable of non-volatile const-qualified integral or enumeration 14668 // type initialized by an ICE can be used in ICEs. 14669 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 14670 if (!Dcl->getType()->isIntegralOrEnumerationType()) 14671 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14672 14673 const VarDecl *VD; 14674 // Look for a declaration of this variable that has an initializer, and 14675 // check whether it is an ICE. 14676 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 14677 return NoDiag(); 14678 else 14679 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14680 } 14681 } 14682 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14683 } 14684 case Expr::UnaryOperatorClass: { 14685 const UnaryOperator *Exp = cast<UnaryOperator>(E); 14686 switch (Exp->getOpcode()) { 14687 case UO_PostInc: 14688 case UO_PostDec: 14689 case UO_PreInc: 14690 case UO_PreDec: 14691 case UO_AddrOf: 14692 case UO_Deref: 14693 case UO_Coawait: 14694 // C99 6.6/3 allows increment and decrement within unevaluated 14695 // subexpressions of constant expressions, but they can never be ICEs 14696 // because an ICE cannot contain an lvalue operand. 14697 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14698 case UO_Extension: 14699 case UO_LNot: 14700 case UO_Plus: 14701 case UO_Minus: 14702 case UO_Not: 14703 case UO_Real: 14704 case UO_Imag: 14705 return CheckICE(Exp->getSubExpr(), Ctx); 14706 } 14707 llvm_unreachable("invalid unary operator class"); 14708 } 14709 case Expr::OffsetOfExprClass: { 14710 // Note that per C99, offsetof must be an ICE. And AFAIK, using 14711 // EvaluateAsRValue matches the proposed gcc behavior for cases like 14712 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 14713 // compliance: we should warn earlier for offsetof expressions with 14714 // array subscripts that aren't ICEs, and if the array subscripts 14715 // are ICEs, the value of the offsetof must be an integer constant. 14716 return CheckEvalInICE(E, Ctx); 14717 } 14718 case Expr::UnaryExprOrTypeTraitExprClass: { 14719 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 14720 if ((Exp->getKind() == UETT_SizeOf) && 14721 Exp->getTypeOfArgument()->isVariableArrayType()) 14722 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14723 return NoDiag(); 14724 } 14725 case Expr::BinaryOperatorClass: { 14726 const BinaryOperator *Exp = cast<BinaryOperator>(E); 14727 switch (Exp->getOpcode()) { 14728 case BO_PtrMemD: 14729 case BO_PtrMemI: 14730 case BO_Assign: 14731 case BO_MulAssign: 14732 case BO_DivAssign: 14733 case BO_RemAssign: 14734 case BO_AddAssign: 14735 case BO_SubAssign: 14736 case BO_ShlAssign: 14737 case BO_ShrAssign: 14738 case BO_AndAssign: 14739 case BO_XorAssign: 14740 case BO_OrAssign: 14741 // C99 6.6/3 allows assignments within unevaluated subexpressions of 14742 // constant expressions, but they can never be ICEs because an ICE cannot 14743 // contain an lvalue operand. 14744 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14745 14746 case BO_Mul: 14747 case BO_Div: 14748 case BO_Rem: 14749 case BO_Add: 14750 case BO_Sub: 14751 case BO_Shl: 14752 case BO_Shr: 14753 case BO_LT: 14754 case BO_GT: 14755 case BO_LE: 14756 case BO_GE: 14757 case BO_EQ: 14758 case BO_NE: 14759 case BO_And: 14760 case BO_Xor: 14761 case BO_Or: 14762 case BO_Comma: 14763 case BO_Cmp: { 14764 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14765 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14766 if (Exp->getOpcode() == BO_Div || 14767 Exp->getOpcode() == BO_Rem) { 14768 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 14769 // we don't evaluate one. 14770 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 14771 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 14772 if (REval == 0) 14773 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14774 if (REval.isSigned() && REval.isAllOnesValue()) { 14775 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 14776 if (LEval.isMinSignedValue()) 14777 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14778 } 14779 } 14780 } 14781 if (Exp->getOpcode() == BO_Comma) { 14782 if (Ctx.getLangOpts().C99) { 14783 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 14784 // if it isn't evaluated. 14785 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 14786 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14787 } else { 14788 // In both C89 and C++, commas in ICEs are illegal. 14789 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14790 } 14791 } 14792 return Worst(LHSResult, RHSResult); 14793 } 14794 case BO_LAnd: 14795 case BO_LOr: { 14796 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14797 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14798 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 14799 // Rare case where the RHS has a comma "side-effect"; we need 14800 // to actually check the condition to see whether the side 14801 // with the comma is evaluated. 14802 if ((Exp->getOpcode() == BO_LAnd) != 14803 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 14804 return RHSResult; 14805 return NoDiag(); 14806 } 14807 14808 return Worst(LHSResult, RHSResult); 14809 } 14810 } 14811 llvm_unreachable("invalid binary operator kind"); 14812 } 14813 case Expr::ImplicitCastExprClass: 14814 case Expr::CStyleCastExprClass: 14815 case Expr::CXXFunctionalCastExprClass: 14816 case Expr::CXXStaticCastExprClass: 14817 case Expr::CXXReinterpretCastExprClass: 14818 case Expr::CXXConstCastExprClass: 14819 case Expr::ObjCBridgedCastExprClass: { 14820 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 14821 if (isa<ExplicitCastExpr>(E)) { 14822 if (const FloatingLiteral *FL 14823 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 14824 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 14825 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 14826 APSInt IgnoredVal(DestWidth, !DestSigned); 14827 bool Ignored; 14828 // If the value does not fit in the destination type, the behavior is 14829 // undefined, so we are not required to treat it as a constant 14830 // expression. 14831 if (FL->getValue().convertToInteger(IgnoredVal, 14832 llvm::APFloat::rmTowardZero, 14833 &Ignored) & APFloat::opInvalidOp) 14834 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14835 return NoDiag(); 14836 } 14837 } 14838 switch (cast<CastExpr>(E)->getCastKind()) { 14839 case CK_LValueToRValue: 14840 case CK_AtomicToNonAtomic: 14841 case CK_NonAtomicToAtomic: 14842 case CK_NoOp: 14843 case CK_IntegralToBoolean: 14844 case CK_IntegralCast: 14845 return CheckICE(SubExpr, Ctx); 14846 default: 14847 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14848 } 14849 } 14850 case Expr::BinaryConditionalOperatorClass: { 14851 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 14852 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 14853 if (CommonResult.Kind == IK_NotICE) return CommonResult; 14854 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14855 if (FalseResult.Kind == IK_NotICE) return FalseResult; 14856 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 14857 if (FalseResult.Kind == IK_ICEIfUnevaluated && 14858 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 14859 return FalseResult; 14860 } 14861 case Expr::ConditionalOperatorClass: { 14862 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 14863 // If the condition (ignoring parens) is a __builtin_constant_p call, 14864 // then only the true side is actually considered in an integer constant 14865 // expression, and it is fully evaluated. This is an important GNU 14866 // extension. See GCC PR38377 for discussion. 14867 if (const CallExpr *CallCE 14868 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 14869 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 14870 return CheckEvalInICE(E, Ctx); 14871 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 14872 if (CondResult.Kind == IK_NotICE) 14873 return CondResult; 14874 14875 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 14876 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14877 14878 if (TrueResult.Kind == IK_NotICE) 14879 return TrueResult; 14880 if (FalseResult.Kind == IK_NotICE) 14881 return FalseResult; 14882 if (CondResult.Kind == IK_ICEIfUnevaluated) 14883 return CondResult; 14884 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 14885 return NoDiag(); 14886 // Rare case where the diagnostics depend on which side is evaluated 14887 // Note that if we get here, CondResult is 0, and at least one of 14888 // TrueResult and FalseResult is non-zero. 14889 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 14890 return FalseResult; 14891 return TrueResult; 14892 } 14893 case Expr::CXXDefaultArgExprClass: 14894 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 14895 case Expr::CXXDefaultInitExprClass: 14896 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 14897 case Expr::ChooseExprClass: { 14898 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 14899 } 14900 case Expr::BuiltinBitCastExprClass: { 14901 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 14902 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14903 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 14904 } 14905 } 14906 14907 llvm_unreachable("Invalid StmtClass!"); 14908 } 14909 14910 /// Evaluate an expression as a C++11 integral constant expression. 14911 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 14912 const Expr *E, 14913 llvm::APSInt *Value, 14914 SourceLocation *Loc) { 14915 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14916 if (Loc) *Loc = E->getExprLoc(); 14917 return false; 14918 } 14919 14920 APValue Result; 14921 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 14922 return false; 14923 14924 if (!Result.isInt()) { 14925 if (Loc) *Loc = E->getExprLoc(); 14926 return false; 14927 } 14928 14929 if (Value) *Value = Result.getInt(); 14930 return true; 14931 } 14932 14933 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 14934 SourceLocation *Loc) const { 14935 assert(!isValueDependent() && 14936 "Expression evaluator can't be called on a dependent expression."); 14937 14938 if (Ctx.getLangOpts().CPlusPlus11) 14939 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 14940 14941 ICEDiag D = CheckICE(this, Ctx); 14942 if (D.Kind != IK_ICE) { 14943 if (Loc) *Loc = D.Loc; 14944 return false; 14945 } 14946 return true; 14947 } 14948 14949 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 14950 SourceLocation *Loc, 14951 bool isEvaluated) const { 14952 assert(!isValueDependent() && 14953 "Expression evaluator can't be called on a dependent expression."); 14954 14955 APSInt Value; 14956 14957 if (Ctx.getLangOpts().CPlusPlus11) { 14958 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 14959 return Value; 14960 return None; 14961 } 14962 14963 if (!isIntegerConstantExpr(Ctx, Loc)) 14964 return None; 14965 14966 // The only possible side-effects here are due to UB discovered in the 14967 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 14968 // required to treat the expression as an ICE, so we produce the folded 14969 // value. 14970 EvalResult ExprResult; 14971 Expr::EvalStatus Status; 14972 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 14973 Info.InConstantContext = true; 14974 14975 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 14976 llvm_unreachable("ICE cannot be evaluated!"); 14977 14978 return ExprResult.Val.getInt(); 14979 } 14980 14981 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 14982 assert(!isValueDependent() && 14983 "Expression evaluator can't be called on a dependent expression."); 14984 14985 return CheckICE(this, Ctx).Kind == IK_ICE; 14986 } 14987 14988 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 14989 SourceLocation *Loc) const { 14990 assert(!isValueDependent() && 14991 "Expression evaluator can't be called on a dependent expression."); 14992 14993 // We support this checking in C++98 mode in order to diagnose compatibility 14994 // issues. 14995 assert(Ctx.getLangOpts().CPlusPlus); 14996 14997 // Build evaluation settings. 14998 Expr::EvalStatus Status; 14999 SmallVector<PartialDiagnosticAt, 8> Diags; 15000 Status.Diag = &Diags; 15001 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15002 15003 APValue Scratch; 15004 bool IsConstExpr = 15005 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15006 // FIXME: We don't produce a diagnostic for this, but the callers that 15007 // call us on arbitrary full-expressions should generally not care. 15008 Info.discardCleanups() && !Status.HasSideEffects; 15009 15010 if (!Diags.empty()) { 15011 IsConstExpr = false; 15012 if (Loc) *Loc = Diags[0].first; 15013 } else if (!IsConstExpr) { 15014 // FIXME: This shouldn't happen. 15015 if (Loc) *Loc = getExprLoc(); 15016 } 15017 15018 return IsConstExpr; 15019 } 15020 15021 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15022 const FunctionDecl *Callee, 15023 ArrayRef<const Expr*> Args, 15024 const Expr *This) const { 15025 assert(!isValueDependent() && 15026 "Expression evaluator can't be called on a dependent expression."); 15027 15028 Expr::EvalStatus Status; 15029 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15030 Info.InConstantContext = true; 15031 15032 LValue ThisVal; 15033 const LValue *ThisPtr = nullptr; 15034 if (This) { 15035 #ifndef NDEBUG 15036 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15037 assert(MD && "Don't provide `this` for non-methods."); 15038 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15039 #endif 15040 if (!This->isValueDependent() && 15041 EvaluateObjectArgument(Info, This, ThisVal) && 15042 !Info.EvalStatus.HasSideEffects) 15043 ThisPtr = &ThisVal; 15044 15045 // Ignore any side-effects from a failed evaluation. This is safe because 15046 // they can't interfere with any other argument evaluation. 15047 Info.EvalStatus.HasSideEffects = false; 15048 } 15049 15050 ArgVector ArgValues(Args.size()); 15051 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15052 I != E; ++I) { 15053 if ((*I)->isValueDependent() || 15054 !Evaluate(ArgValues[I - Args.begin()], Info, *I) || 15055 Info.EvalStatus.HasSideEffects) 15056 // If evaluation fails, throw away the argument entirely. 15057 ArgValues[I - Args.begin()] = APValue(); 15058 15059 // Ignore any side-effects from a failed evaluation. This is safe because 15060 // they can't interfere with any other argument evaluation. 15061 Info.EvalStatus.HasSideEffects = false; 15062 } 15063 15064 // Parameter cleanups happen in the caller and are not part of this 15065 // evaluation. 15066 Info.discardCleanups(); 15067 Info.EvalStatus.HasSideEffects = false; 15068 15069 // Build fake call to Callee. 15070 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 15071 ArgValues.data()); 15072 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15073 FullExpressionRAII Scope(Info); 15074 return Evaluate(Value, Info, this) && Scope.destroy() && 15075 !Info.EvalStatus.HasSideEffects; 15076 } 15077 15078 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15079 SmallVectorImpl< 15080 PartialDiagnosticAt> &Diags) { 15081 // FIXME: It would be useful to check constexpr function templates, but at the 15082 // moment the constant expression evaluator cannot cope with the non-rigorous 15083 // ASTs which we build for dependent expressions. 15084 if (FD->isDependentContext()) 15085 return true; 15086 15087 // Bail out if a constexpr constructor has an initializer that contains an 15088 // error. We deliberately don't produce a diagnostic, as we have produced a 15089 // relevant diagnostic when parsing the error initializer. 15090 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15091 for (const auto *InitExpr : Ctor->inits()) { 15092 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 15093 return false; 15094 } 15095 } 15096 Expr::EvalStatus Status; 15097 Status.Diag = &Diags; 15098 15099 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15100 Info.InConstantContext = true; 15101 Info.CheckingPotentialConstantExpression = true; 15102 15103 // The constexpr VM attempts to compile all methods to bytecode here. 15104 if (Info.EnableNewConstInterp) { 15105 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15106 return Diags.empty(); 15107 } 15108 15109 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15110 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15111 15112 // Fabricate an arbitrary expression on the stack and pretend that it 15113 // is a temporary being used as the 'this' pointer. 15114 LValue This; 15115 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15116 This.set({&VIE, Info.CurrentCall->Index}); 15117 15118 ArrayRef<const Expr*> Args; 15119 15120 APValue Scratch; 15121 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15122 // Evaluate the call as a constant initializer, to allow the construction 15123 // of objects of non-literal types. 15124 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15125 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15126 } else { 15127 SourceLocation Loc = FD->getLocation(); 15128 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15129 Args, FD->getBody(), Info, Scratch, nullptr); 15130 } 15131 15132 return Diags.empty(); 15133 } 15134 15135 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15136 const FunctionDecl *FD, 15137 SmallVectorImpl< 15138 PartialDiagnosticAt> &Diags) { 15139 assert(!E->isValueDependent() && 15140 "Expression evaluator can't be called on a dependent expression."); 15141 15142 Expr::EvalStatus Status; 15143 Status.Diag = &Diags; 15144 15145 EvalInfo Info(FD->getASTContext(), Status, 15146 EvalInfo::EM_ConstantExpressionUnevaluated); 15147 Info.InConstantContext = true; 15148 Info.CheckingPotentialConstantExpression = true; 15149 15150 // Fabricate a call stack frame to give the arguments a plausible cover story. 15151 ArrayRef<const Expr*> Args; 15152 ArgVector ArgValues(0); 15153 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 15154 (void)Success; 15155 assert(Success && 15156 "Failed to set up arguments for potential constant evaluation"); 15157 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 15158 15159 APValue ResultScratch; 15160 Evaluate(ResultScratch, Info, E); 15161 return Diags.empty(); 15162 } 15163 15164 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15165 unsigned Type) const { 15166 if (!getType()->isPointerType()) 15167 return false; 15168 15169 Expr::EvalStatus Status; 15170 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15171 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15172 } 15173