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 "ExprConstShared.h" 36 #include "Interp/Context.h" 37 #include "Interp/Frame.h" 38 #include "Interp/State.h" 39 #include "clang/AST/APValue.h" 40 #include "clang/AST/ASTContext.h" 41 #include "clang/AST/ASTDiagnostic.h" 42 #include "clang/AST/ASTLambda.h" 43 #include "clang/AST/Attr.h" 44 #include "clang/AST/CXXInheritance.h" 45 #include "clang/AST/CharUnits.h" 46 #include "clang/AST/CurrentSourceLocExprScope.h" 47 #include "clang/AST/Expr.h" 48 #include "clang/AST/OSLog.h" 49 #include "clang/AST/OptionalDiagnostic.h" 50 #include "clang/AST/RecordLayout.h" 51 #include "clang/AST/StmtVisitor.h" 52 #include "clang/AST/TypeLoc.h" 53 #include "clang/Basic/Builtins.h" 54 #include "clang/Basic/DiagnosticSema.h" 55 #include "clang/Basic/TargetInfo.h" 56 #include "llvm/ADT/APFixedPoint.h" 57 #include "llvm/ADT/SmallBitVector.h" 58 #include "llvm/ADT/StringExtras.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/SaveAndRestore.h" 61 #include "llvm/Support/TimeProfiler.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include <cstring> 64 #include <functional> 65 #include <optional> 66 67 #define DEBUG_TYPE "exprconstant" 68 69 using namespace clang; 70 using llvm::APFixedPoint; 71 using llvm::APInt; 72 using llvm::APSInt; 73 using llvm::APFloat; 74 using llvm::FixedPointSemantics; 75 76 namespace { 77 struct LValue; 78 class CallStackFrame; 79 class EvalInfo; 80 81 using SourceLocExprScopeGuard = 82 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 83 84 static QualType getType(APValue::LValueBase B) { 85 return B.getType(); 86 } 87 88 /// Get an LValue path entry, which is known to not be an array index, as a 89 /// field declaration. 90 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 91 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 92 } 93 /// Get an LValue path entry, which is known to not be an array index, as a 94 /// base class declaration. 95 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 96 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 97 } 98 /// Determine whether this LValue path entry for a base class names a virtual 99 /// base class. 100 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 101 return E.getAsBaseOrMember().getInt(); 102 } 103 104 /// Given an expression, determine the type used to store the result of 105 /// evaluating that expression. 106 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 107 if (E->isPRValue()) 108 return E->getType(); 109 return Ctx.getLValueReferenceType(E->getType()); 110 } 111 112 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 114 if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) 115 return DirectCallee->getAttr<AllocSizeAttr>(); 116 if (const Decl *IndirectCallee = CE->getCalleeDecl()) 117 return IndirectCallee->getAttr<AllocSizeAttr>(); 118 return nullptr; 119 } 120 121 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 122 /// This will look through a single cast. 123 /// 124 /// Returns null if we couldn't unwrap a function with alloc_size. 125 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 126 if (!E->getType()->isPointerType()) 127 return nullptr; 128 129 E = E->IgnoreParens(); 130 // If we're doing a variable assignment from e.g. malloc(N), there will 131 // probably be a cast of some kind. In exotic cases, we might also see a 132 // top-level ExprWithCleanups. Ignore them either way. 133 if (const auto *FE = dyn_cast<FullExpr>(E)) 134 E = FE->getSubExpr()->IgnoreParens(); 135 136 if (const auto *Cast = dyn_cast<CastExpr>(E)) 137 E = Cast->getSubExpr()->IgnoreParens(); 138 139 if (const auto *CE = dyn_cast<CallExpr>(E)) 140 return getAllocSizeAttr(CE) ? CE : nullptr; 141 return nullptr; 142 } 143 144 /// Determines whether or not the given Base contains a call to a function 145 /// with the alloc_size attribute. 146 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 147 const auto *E = Base.dyn_cast<const Expr *>(); 148 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 149 } 150 151 /// Determines whether the given kind of constant expression is only ever 152 /// used for name mangling. If so, it's permitted to reference things that we 153 /// can't generate code for (in particular, dllimported functions). 154 static bool isForManglingOnly(ConstantExprKind Kind) { 155 switch (Kind) { 156 case ConstantExprKind::Normal: 157 case ConstantExprKind::ClassTemplateArgument: 158 case ConstantExprKind::ImmediateInvocation: 159 // Note that non-type template arguments of class type are emitted as 160 // template parameter objects. 161 return false; 162 163 case ConstantExprKind::NonClassTemplateArgument: 164 return true; 165 } 166 llvm_unreachable("unknown ConstantExprKind"); 167 } 168 169 static bool isTemplateArgument(ConstantExprKind Kind) { 170 switch (Kind) { 171 case ConstantExprKind::Normal: 172 case ConstantExprKind::ImmediateInvocation: 173 return false; 174 175 case ConstantExprKind::ClassTemplateArgument: 176 case ConstantExprKind::NonClassTemplateArgument: 177 return true; 178 } 179 llvm_unreachable("unknown ConstantExprKind"); 180 } 181 182 /// The bound to claim that an array of unknown bound has. 183 /// The value in MostDerivedArraySize is undefined in this case. So, set it 184 /// to an arbitrary value that's likely to loudly break things if it's used. 185 static const uint64_t AssumedSizeForUnsizedArray = 186 std::numeric_limits<uint64_t>::max() / 2; 187 188 /// Determines if an LValue with the given LValueBase will have an unsized 189 /// array in its designator. 190 /// Find the path length and type of the most-derived subobject in the given 191 /// path, and find the size of the containing array, if any. 192 static unsigned 193 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 194 ArrayRef<APValue::LValuePathEntry> Path, 195 uint64_t &ArraySize, QualType &Type, bool &IsArray, 196 bool &FirstEntryIsUnsizedArray) { 197 // This only accepts LValueBases from APValues, and APValues don't support 198 // arrays that lack size info. 199 assert(!isBaseAnAllocSizeCall(Base) && 200 "Unsized arrays shouldn't appear here"); 201 unsigned MostDerivedLength = 0; 202 Type = getType(Base); 203 204 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 205 if (Type->isArrayType()) { 206 const ArrayType *AT = Ctx.getAsArrayType(Type); 207 Type = AT->getElementType(); 208 MostDerivedLength = I + 1; 209 IsArray = true; 210 211 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 212 ArraySize = CAT->getSize().getZExtValue(); 213 } else { 214 assert(I == 0 && "unexpected unsized array designator"); 215 FirstEntryIsUnsizedArray = true; 216 ArraySize = AssumedSizeForUnsizedArray; 217 } 218 } else if (Type->isAnyComplexType()) { 219 const ComplexType *CT = Type->castAs<ComplexType>(); 220 Type = CT->getElementType(); 221 ArraySize = 2; 222 MostDerivedLength = I + 1; 223 IsArray = true; 224 } else if (const FieldDecl *FD = getAsField(Path[I])) { 225 Type = FD->getType(); 226 ArraySize = 0; 227 MostDerivedLength = I + 1; 228 IsArray = false; 229 } else { 230 // Path[I] describes a base class. 231 ArraySize = 0; 232 IsArray = false; 233 } 234 } 235 return MostDerivedLength; 236 } 237 238 /// A path from a glvalue to a subobject of that glvalue. 239 struct SubobjectDesignator { 240 /// True if the subobject was named in a manner not supported by C++11. Such 241 /// lvalues can still be folded, but they are not core constant expressions 242 /// and we cannot perform lvalue-to-rvalue conversions on them. 243 unsigned Invalid : 1; 244 245 /// Is this a pointer one past the end of an object? 246 unsigned IsOnePastTheEnd : 1; 247 248 /// Indicator of whether the first entry is an unsized array. 249 unsigned FirstEntryIsAnUnsizedArray : 1; 250 251 /// Indicator of whether the most-derived object is an array element. 252 unsigned MostDerivedIsArrayElement : 1; 253 254 /// The length of the path to the most-derived object of which this is a 255 /// subobject. 256 unsigned MostDerivedPathLength : 28; 257 258 /// The size of the array of which the most-derived object is an element. 259 /// This will always be 0 if the most-derived object is not an array 260 /// element. 0 is not an indicator of whether or not the most-derived object 261 /// is an array, however, because 0-length arrays are allowed. 262 /// 263 /// If the current array is an unsized array, the value of this is 264 /// undefined. 265 uint64_t MostDerivedArraySize; 266 267 /// The type of the most derived object referred to by this address. 268 QualType MostDerivedType; 269 270 typedef APValue::LValuePathEntry PathEntry; 271 272 /// The entries on the path from the glvalue to the designated subobject. 273 SmallVector<PathEntry, 8> Entries; 274 275 SubobjectDesignator() : Invalid(true) {} 276 277 explicit SubobjectDesignator(QualType T) 278 : Invalid(false), IsOnePastTheEnd(false), 279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 280 MostDerivedPathLength(0), MostDerivedArraySize(0), 281 MostDerivedType(T) {} 282 283 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 284 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 286 MostDerivedPathLength(0), MostDerivedArraySize(0) { 287 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 288 if (!Invalid) { 289 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 290 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 291 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 292 if (V.getLValueBase()) { 293 bool IsArray = false; 294 bool FirstIsUnsizedArray = false; 295 MostDerivedPathLength = findMostDerivedSubobject( 296 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 297 MostDerivedType, IsArray, FirstIsUnsizedArray); 298 MostDerivedIsArrayElement = IsArray; 299 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 300 } 301 } 302 } 303 304 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 305 unsigned NewLength) { 306 if (Invalid) 307 return; 308 309 assert(Base && "cannot truncate path for null pointer"); 310 assert(NewLength <= Entries.size() && "not a truncation"); 311 312 if (NewLength == Entries.size()) 313 return; 314 Entries.resize(NewLength); 315 316 bool IsArray = false; 317 bool FirstIsUnsizedArray = false; 318 MostDerivedPathLength = findMostDerivedSubobject( 319 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 320 FirstIsUnsizedArray); 321 MostDerivedIsArrayElement = IsArray; 322 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 323 } 324 325 void setInvalid() { 326 Invalid = true; 327 Entries.clear(); 328 } 329 330 /// Determine whether the most derived subobject is an array without a 331 /// known bound. 332 bool isMostDerivedAnUnsizedArray() const { 333 assert(!Invalid && "Calling this makes no sense on invalid designators"); 334 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 335 } 336 337 /// Determine what the most derived array's size is. Results in an assertion 338 /// failure if the most derived array lacks a size. 339 uint64_t getMostDerivedArraySize() const { 340 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 341 return MostDerivedArraySize; 342 } 343 344 /// Determine whether this is a one-past-the-end pointer. 345 bool isOnePastTheEnd() const { 346 assert(!Invalid); 347 if (IsOnePastTheEnd) 348 return true; 349 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 350 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 351 MostDerivedArraySize) 352 return true; 353 return false; 354 } 355 356 /// Get the range of valid index adjustments in the form 357 /// {maximum value that can be subtracted from this pointer, 358 /// maximum value that can be added to this pointer} 359 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 360 if (Invalid || isMostDerivedAnUnsizedArray()) 361 return {0, 0}; 362 363 // [expr.add]p4: For the purposes of these operators, a pointer to a 364 // nonarray object behaves the same as a pointer to the first element of 365 // an array of length one with the type of the object as its element type. 366 bool IsArray = MostDerivedPathLength == Entries.size() && 367 MostDerivedIsArrayElement; 368 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 369 : (uint64_t)IsOnePastTheEnd; 370 uint64_t ArraySize = 371 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 372 return {ArrayIndex, ArraySize - ArrayIndex}; 373 } 374 375 /// Check that this refers to a valid subobject. 376 bool isValidSubobject() const { 377 if (Invalid) 378 return false; 379 return !isOnePastTheEnd(); 380 } 381 /// Check that this refers to a valid subobject, and if not, produce a 382 /// relevant diagnostic and set the designator as invalid. 383 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 384 385 /// Get the type of the designated object. 386 QualType getType(ASTContext &Ctx) const { 387 assert(!Invalid && "invalid designator has no subobject type"); 388 return MostDerivedPathLength == Entries.size() 389 ? MostDerivedType 390 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 391 } 392 393 /// Update this designator to refer to the first element within this array. 394 void addArrayUnchecked(const ConstantArrayType *CAT) { 395 Entries.push_back(PathEntry::ArrayIndex(0)); 396 397 // This is a most-derived object. 398 MostDerivedType = CAT->getElementType(); 399 MostDerivedIsArrayElement = true; 400 MostDerivedArraySize = CAT->getSize().getZExtValue(); 401 MostDerivedPathLength = Entries.size(); 402 } 403 /// Update this designator to refer to the first element within the array of 404 /// elements of type T. This is an array of unknown size. 405 void addUnsizedArrayUnchecked(QualType ElemTy) { 406 Entries.push_back(PathEntry::ArrayIndex(0)); 407 408 MostDerivedType = ElemTy; 409 MostDerivedIsArrayElement = true; 410 // The value in MostDerivedArraySize is undefined in this case. So, set it 411 // to an arbitrary value that's likely to loudly break things if it's 412 // used. 413 MostDerivedArraySize = AssumedSizeForUnsizedArray; 414 MostDerivedPathLength = Entries.size(); 415 } 416 /// Update this designator to refer to the given base or member of this 417 /// object. 418 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 419 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 420 421 // If this isn't a base class, it's a new most-derived object. 422 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 423 MostDerivedType = FD->getType(); 424 MostDerivedIsArrayElement = false; 425 MostDerivedArraySize = 0; 426 MostDerivedPathLength = Entries.size(); 427 } 428 } 429 /// Update this designator to refer to the given complex component. 430 void addComplexUnchecked(QualType EltTy, bool Imag) { 431 Entries.push_back(PathEntry::ArrayIndex(Imag)); 432 433 // This is technically a most-derived object, though in practice this 434 // is unlikely to matter. 435 MostDerivedType = EltTy; 436 MostDerivedIsArrayElement = true; 437 MostDerivedArraySize = 2; 438 MostDerivedPathLength = Entries.size(); 439 } 440 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 441 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 442 const APSInt &N); 443 /// Add N to the address of this subobject. 444 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 445 if (Invalid || !N) return; 446 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 447 if (isMostDerivedAnUnsizedArray()) { 448 diagnoseUnsizedArrayPointerArithmetic(Info, E); 449 // Can't verify -- trust that the user is doing the right thing (or if 450 // not, trust that the caller will catch the bad behavior). 451 // FIXME: Should we reject if this overflows, at least? 452 Entries.back() = PathEntry::ArrayIndex( 453 Entries.back().getAsArrayIndex() + TruncatedN); 454 return; 455 } 456 457 // [expr.add]p4: For the purposes of these operators, a pointer to a 458 // nonarray object behaves the same as a pointer to the first element of 459 // an array of length one with the type of the object as its element type. 460 bool IsArray = MostDerivedPathLength == Entries.size() && 461 MostDerivedIsArrayElement; 462 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 463 : (uint64_t)IsOnePastTheEnd; 464 uint64_t ArraySize = 465 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 466 467 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 468 // Calculate the actual index in a wide enough type, so we can include 469 // it in the note. 470 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 471 (llvm::APInt&)N += ArrayIndex; 472 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 473 diagnosePointerArithmetic(Info, E, N); 474 setInvalid(); 475 return; 476 } 477 478 ArrayIndex += TruncatedN; 479 assert(ArrayIndex <= ArraySize && 480 "bounds check succeeded for out-of-bounds index"); 481 482 if (IsArray) 483 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 484 else 485 IsOnePastTheEnd = (ArrayIndex != 0); 486 } 487 }; 488 489 /// A scope at the end of which an object can need to be destroyed. 490 enum class ScopeKind { 491 Block, 492 FullExpression, 493 Call 494 }; 495 496 /// A reference to a particular call and its arguments. 497 struct CallRef { 498 CallRef() : OrigCallee(), CallIndex(0), Version() {} 499 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 500 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 501 502 explicit operator bool() const { return OrigCallee; } 503 504 /// Get the parameter that the caller initialized, corresponding to the 505 /// given parameter in the callee. 506 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 507 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 508 : PVD; 509 } 510 511 /// The callee at the point where the arguments were evaluated. This might 512 /// be different from the actual callee (a different redeclaration, or a 513 /// virtual override), but this function's parameters are the ones that 514 /// appear in the parameter map. 515 const FunctionDecl *OrigCallee; 516 /// The call index of the frame that holds the argument values. 517 unsigned CallIndex; 518 /// The version of the parameters corresponding to this call. 519 unsigned Version; 520 }; 521 522 /// A stack frame in the constexpr call stack. 523 class CallStackFrame : public interp::Frame { 524 public: 525 EvalInfo &Info; 526 527 /// Parent - The caller of this stack frame. 528 CallStackFrame *Caller; 529 530 /// Callee - The function which was called. 531 const FunctionDecl *Callee; 532 533 /// This - The binding for the this pointer in this call, if any. 534 const LValue *This; 535 536 /// CallExpr - The syntactical structure of member function calls 537 const Expr *CallExpr; 538 539 /// Information on how to find the arguments to this call. Our arguments 540 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 541 /// key and this value as the version. 542 CallRef Arguments; 543 544 /// Source location information about the default argument or default 545 /// initializer expression we're evaluating, if any. 546 CurrentSourceLocExprScope CurSourceLocExprScope; 547 548 // Note that we intentionally use std::map here so that references to 549 // values are stable. 550 typedef std::pair<const void *, unsigned> MapKeyTy; 551 typedef std::map<MapKeyTy, APValue> MapTy; 552 /// Temporaries - Temporary lvalues materialized within this stack frame. 553 MapTy Temporaries; 554 555 /// CallRange - The source range of the call expression for this call. 556 SourceRange CallRange; 557 558 /// Index - The call index of this call. 559 unsigned Index; 560 561 /// The stack of integers for tracking version numbers for temporaries. 562 SmallVector<unsigned, 2> TempVersionStack = {1}; 563 unsigned CurTempVersion = TempVersionStack.back(); 564 565 unsigned getTempVersion() const { return TempVersionStack.back(); } 566 567 void pushTempVersion() { 568 TempVersionStack.push_back(++CurTempVersion); 569 } 570 571 void popTempVersion() { 572 TempVersionStack.pop_back(); 573 } 574 575 CallRef createCall(const FunctionDecl *Callee) { 576 return {Callee, Index, ++CurTempVersion}; 577 } 578 579 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 580 // on the overall stack usage of deeply-recursing constexpr evaluations. 581 // (We should cache this map rather than recomputing it repeatedly.) 582 // But let's try this and see how it goes; we can look into caching the map 583 // as a later change. 584 585 /// LambdaCaptureFields - Mapping from captured variables/this to 586 /// corresponding data members in the closure class. 587 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields; 588 FieldDecl *LambdaThisCaptureField = nullptr; 589 590 CallStackFrame(EvalInfo &Info, SourceRange CallRange, 591 const FunctionDecl *Callee, const LValue *This, 592 const Expr *CallExpr, CallRef Arguments); 593 ~CallStackFrame(); 594 595 // Return the temporary for Key whose version number is Version. 596 APValue *getTemporary(const void *Key, unsigned Version) { 597 MapKeyTy KV(Key, Version); 598 auto LB = Temporaries.lower_bound(KV); 599 if (LB != Temporaries.end() && LB->first == KV) 600 return &LB->second; 601 return nullptr; 602 } 603 604 // Return the current temporary for Key in the map. 605 APValue *getCurrentTemporary(const void *Key) { 606 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 607 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 608 return &std::prev(UB)->second; 609 return nullptr; 610 } 611 612 // Return the version number of the current temporary for Key. 613 unsigned getCurrentTemporaryVersion(const void *Key) const { 614 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 615 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 616 return std::prev(UB)->first.second; 617 return 0; 618 } 619 620 /// Allocate storage for an object of type T in this stack frame. 621 /// Populates LV with a handle to the created object. Key identifies 622 /// the temporary within the stack frame, and must not be reused without 623 /// bumping the temporary version number. 624 template<typename KeyT> 625 APValue &createTemporary(const KeyT *Key, QualType T, 626 ScopeKind Scope, LValue &LV); 627 628 /// Allocate storage for a parameter of a function call made in this frame. 629 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 630 631 void describe(llvm::raw_ostream &OS) const override; 632 633 Frame *getCaller() const override { return Caller; } 634 SourceRange getCallRange() const override { return CallRange; } 635 const FunctionDecl *getCallee() const override { return Callee; } 636 637 bool isStdFunction() const { 638 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 639 if (DC->isStdNamespace()) 640 return true; 641 return false; 642 } 643 644 /// Whether we're in a context where [[msvc::constexpr]] evaluation is 645 /// permitted. See MSConstexprDocs for description of permitted contexts. 646 bool CanEvalMSConstexpr = false; 647 648 private: 649 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 650 ScopeKind Scope); 651 }; 652 653 /// Temporarily override 'this'. 654 class ThisOverrideRAII { 655 public: 656 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 657 : Frame(Frame), OldThis(Frame.This) { 658 if (Enable) 659 Frame.This = NewThis; 660 } 661 ~ThisOverrideRAII() { 662 Frame.This = OldThis; 663 } 664 private: 665 CallStackFrame &Frame; 666 const LValue *OldThis; 667 }; 668 669 // A shorthand time trace scope struct, prints source range, for example 670 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}} 671 class ExprTimeTraceScope { 672 public: 673 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name) 674 : TimeScope(Name, [E, &Ctx] { 675 return E->getSourceRange().printToString(Ctx.getSourceManager()); 676 }) {} 677 678 private: 679 llvm::TimeTraceScope TimeScope; 680 }; 681 682 /// RAII object used to change the current ability of 683 /// [[msvc::constexpr]] evaulation. 684 struct MSConstexprContextRAII { 685 CallStackFrame &Frame; 686 bool OldValue; 687 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value) 688 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) { 689 Frame.CanEvalMSConstexpr = Value; 690 } 691 692 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; } 693 }; 694 } 695 696 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 697 const LValue &This, QualType ThisType); 698 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 699 APValue::LValueBase LVBase, APValue &Value, 700 QualType T); 701 702 namespace { 703 /// A cleanup, and a flag indicating whether it is lifetime-extended. 704 class Cleanup { 705 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 706 APValue::LValueBase Base; 707 QualType T; 708 709 public: 710 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 711 ScopeKind Scope) 712 : Value(Val, Scope), Base(Base), T(T) {} 713 714 /// Determine whether this cleanup should be performed at the end of the 715 /// given kind of scope. 716 bool isDestroyedAtEndOf(ScopeKind K) const { 717 return (int)Value.getInt() >= (int)K; 718 } 719 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 720 if (RunDestructors) { 721 SourceLocation Loc; 722 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 723 Loc = VD->getLocation(); 724 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 725 Loc = E->getExprLoc(); 726 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 727 } 728 *Value.getPointer() = APValue(); 729 return true; 730 } 731 732 bool hasSideEffect() { 733 return T.isDestructedType(); 734 } 735 }; 736 737 /// A reference to an object whose construction we are currently evaluating. 738 struct ObjectUnderConstruction { 739 APValue::LValueBase Base; 740 ArrayRef<APValue::LValuePathEntry> Path; 741 friend bool operator==(const ObjectUnderConstruction &LHS, 742 const ObjectUnderConstruction &RHS) { 743 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 744 } 745 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 746 return llvm::hash_combine(Obj.Base, Obj.Path); 747 } 748 }; 749 enum class ConstructionPhase { 750 None, 751 Bases, 752 AfterBases, 753 AfterFields, 754 Destroying, 755 DestroyingBases 756 }; 757 } 758 759 namespace llvm { 760 template<> struct DenseMapInfo<ObjectUnderConstruction> { 761 using Base = DenseMapInfo<APValue::LValueBase>; 762 static ObjectUnderConstruction getEmptyKey() { 763 return {Base::getEmptyKey(), {}}; } 764 static ObjectUnderConstruction getTombstoneKey() { 765 return {Base::getTombstoneKey(), {}}; 766 } 767 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 768 return hash_value(Object); 769 } 770 static bool isEqual(const ObjectUnderConstruction &LHS, 771 const ObjectUnderConstruction &RHS) { 772 return LHS == RHS; 773 } 774 }; 775 } 776 777 namespace { 778 /// A dynamically-allocated heap object. 779 struct DynAlloc { 780 /// The value of this heap-allocated object. 781 APValue Value; 782 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 783 /// or a CallExpr (the latter is for direct calls to operator new inside 784 /// std::allocator<T>::allocate). 785 const Expr *AllocExpr = nullptr; 786 787 enum Kind { 788 New, 789 ArrayNew, 790 StdAllocator 791 }; 792 793 /// Get the kind of the allocation. This must match between allocation 794 /// and deallocation. 795 Kind getKind() const { 796 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 797 return NE->isArray() ? ArrayNew : New; 798 assert(isa<CallExpr>(AllocExpr)); 799 return StdAllocator; 800 } 801 }; 802 803 struct DynAllocOrder { 804 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 805 return L.getIndex() < R.getIndex(); 806 } 807 }; 808 809 /// EvalInfo - This is a private struct used by the evaluator to capture 810 /// information about a subexpression as it is folded. It retains information 811 /// about the AST context, but also maintains information about the folded 812 /// expression. 813 /// 814 /// If an expression could be evaluated, it is still possible it is not a C 815 /// "integer constant expression" or constant expression. If not, this struct 816 /// captures information about how and why not. 817 /// 818 /// One bit of information passed *into* the request for constant folding 819 /// indicates whether the subexpression is "evaluated" or not according to C 820 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 821 /// evaluate the expression regardless of what the RHS is, but C only allows 822 /// certain things in certain situations. 823 class EvalInfo : public interp::State { 824 public: 825 ASTContext &Ctx; 826 827 /// EvalStatus - Contains information about the evaluation. 828 Expr::EvalStatus &EvalStatus; 829 830 /// CurrentCall - The top of the constexpr call stack. 831 CallStackFrame *CurrentCall; 832 833 /// CallStackDepth - The number of calls in the call stack right now. 834 unsigned CallStackDepth; 835 836 /// NextCallIndex - The next call index to assign. 837 unsigned NextCallIndex; 838 839 /// StepsLeft - The remaining number of evaluation steps we're permitted 840 /// to perform. This is essentially a limit for the number of statements 841 /// we will evaluate. 842 unsigned StepsLeft; 843 844 /// Enable the experimental new constant interpreter. If an expression is 845 /// not supported by the interpreter, an error is triggered. 846 bool EnableNewConstInterp; 847 848 /// BottomFrame - The frame in which evaluation started. This must be 849 /// initialized after CurrentCall and CallStackDepth. 850 CallStackFrame BottomFrame; 851 852 /// A stack of values whose lifetimes end at the end of some surrounding 853 /// evaluation frame. 854 llvm::SmallVector<Cleanup, 16> CleanupStack; 855 856 /// EvaluatingDecl - This is the declaration whose initializer is being 857 /// evaluated, if any. 858 APValue::LValueBase EvaluatingDecl; 859 860 enum class EvaluatingDeclKind { 861 None, 862 /// We're evaluating the construction of EvaluatingDecl. 863 Ctor, 864 /// We're evaluating the destruction of EvaluatingDecl. 865 Dtor, 866 }; 867 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 868 869 /// EvaluatingDeclValue - This is the value being constructed for the 870 /// declaration whose initializer is being evaluated, if any. 871 APValue *EvaluatingDeclValue; 872 873 /// Set of objects that are currently being constructed. 874 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 875 ObjectsUnderConstruction; 876 877 /// Current heap allocations, along with the location where each was 878 /// allocated. We use std::map here because we need stable addresses 879 /// for the stored APValues. 880 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 881 882 /// The number of heap allocations performed so far in this evaluation. 883 unsigned NumHeapAllocs = 0; 884 885 struct EvaluatingConstructorRAII { 886 EvalInfo &EI; 887 ObjectUnderConstruction Object; 888 bool DidInsert; 889 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 890 bool HasBases) 891 : EI(EI), Object(Object) { 892 DidInsert = 893 EI.ObjectsUnderConstruction 894 .insert({Object, HasBases ? ConstructionPhase::Bases 895 : ConstructionPhase::AfterBases}) 896 .second; 897 } 898 void finishedConstructingBases() { 899 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 900 } 901 void finishedConstructingFields() { 902 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 903 } 904 ~EvaluatingConstructorRAII() { 905 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 906 } 907 }; 908 909 struct EvaluatingDestructorRAII { 910 EvalInfo &EI; 911 ObjectUnderConstruction Object; 912 bool DidInsert; 913 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 914 : EI(EI), Object(Object) { 915 DidInsert = EI.ObjectsUnderConstruction 916 .insert({Object, ConstructionPhase::Destroying}) 917 .second; 918 } 919 void startedDestroyingBases() { 920 EI.ObjectsUnderConstruction[Object] = 921 ConstructionPhase::DestroyingBases; 922 } 923 ~EvaluatingDestructorRAII() { 924 if (DidInsert) 925 EI.ObjectsUnderConstruction.erase(Object); 926 } 927 }; 928 929 ConstructionPhase 930 isEvaluatingCtorDtor(APValue::LValueBase Base, 931 ArrayRef<APValue::LValuePathEntry> Path) { 932 return ObjectsUnderConstruction.lookup({Base, Path}); 933 } 934 935 /// If we're currently speculatively evaluating, the outermost call stack 936 /// depth at which we can mutate state, otherwise 0. 937 unsigned SpeculativeEvaluationDepth = 0; 938 939 /// The current array initialization index, if we're performing array 940 /// initialization. 941 uint64_t ArrayInitIndex = -1; 942 943 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 944 /// notes attached to it will also be stored, otherwise they will not be. 945 bool HasActiveDiagnostic; 946 947 /// Have we emitted a diagnostic explaining why we couldn't constant 948 /// fold (not just why it's not strictly a constant expression)? 949 bool HasFoldFailureDiagnostic; 950 951 /// Whether we're checking that an expression is a potential constant 952 /// expression. If so, do not fail on constructs that could become constant 953 /// later on (such as a use of an undefined global). 954 bool CheckingPotentialConstantExpression = false; 955 956 /// Whether we're checking for an expression that has undefined behavior. 957 /// If so, we will produce warnings if we encounter an operation that is 958 /// always undefined. 959 /// 960 /// Note that we still need to evaluate the expression normally when this 961 /// is set; this is used when evaluating ICEs in C. 962 bool CheckingForUndefinedBehavior = false; 963 964 enum EvaluationMode { 965 /// Evaluate as a constant expression. Stop if we find that the expression 966 /// is not a constant expression. 967 EM_ConstantExpression, 968 969 /// Evaluate as a constant expression. Stop if we find that the expression 970 /// is not a constant expression. Some expressions can be retried in the 971 /// optimizer if we don't constant fold them here, but in an unevaluated 972 /// context we try to fold them immediately since the optimizer never 973 /// gets a chance to look at it. 974 EM_ConstantExpressionUnevaluated, 975 976 /// Fold the expression to a constant. Stop if we hit a side-effect that 977 /// we can't model. 978 EM_ConstantFold, 979 980 /// Evaluate in any way we know how. Don't worry about side-effects that 981 /// can't be modeled. 982 EM_IgnoreSideEffects, 983 } EvalMode; 984 985 /// Are we checking whether the expression is a potential constant 986 /// expression? 987 bool checkingPotentialConstantExpression() const override { 988 return CheckingPotentialConstantExpression; 989 } 990 991 /// Are we checking an expression for overflow? 992 // FIXME: We should check for any kind of undefined or suspicious behavior 993 // in such constructs, not just overflow. 994 bool checkingForUndefinedBehavior() const override { 995 return CheckingForUndefinedBehavior; 996 } 997 998 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 999 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 1000 CallStackDepth(0), NextCallIndex(1), 1001 StepsLeft(C.getLangOpts().ConstexprStepLimit), 1002 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 1003 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr, 1004 /*This=*/nullptr, 1005 /*CallExpr=*/nullptr, CallRef()), 1006 EvaluatingDecl((const ValueDecl *)nullptr), 1007 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 1008 HasFoldFailureDiagnostic(false), EvalMode(Mode) {} 1009 1010 ~EvalInfo() { 1011 discardCleanups(); 1012 } 1013 1014 ASTContext &getCtx() const override { return Ctx; } 1015 1016 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 1017 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 1018 EvaluatingDecl = Base; 1019 IsEvaluatingDecl = EDK; 1020 EvaluatingDeclValue = &Value; 1021 } 1022 1023 bool CheckCallLimit(SourceLocation Loc) { 1024 // Don't perform any constexpr calls (other than the call we're checking) 1025 // when checking a potential constant expression. 1026 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 1027 return false; 1028 if (NextCallIndex == 0) { 1029 // NextCallIndex has wrapped around. 1030 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1031 return false; 1032 } 1033 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1034 return true; 1035 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1036 << getLangOpts().ConstexprCallDepth; 1037 return false; 1038 } 1039 1040 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth, 1041 uint64_t ElemCount, bool Diag) { 1042 // FIXME: GH63562 1043 // APValue stores array extents as unsigned, 1044 // so anything that is greater that unsigned would overflow when 1045 // constructing the array, we catch this here. 1046 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) || 1047 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) { 1048 if (Diag) 1049 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount; 1050 return false; 1051 } 1052 1053 // FIXME: GH63562 1054 // Arrays allocate an APValue per element. 1055 // We use the number of constexpr steps as a proxy for the maximum size 1056 // of arrays to avoid exhausting the system resources, as initialization 1057 // of each element is likely to take some number of steps anyway. 1058 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit; 1059 if (ElemCount > Limit) { 1060 if (Diag) 1061 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits) 1062 << ElemCount << Limit; 1063 return false; 1064 } 1065 return true; 1066 } 1067 1068 std::pair<CallStackFrame *, unsigned> 1069 getCallFrameAndDepth(unsigned CallIndex) { 1070 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1071 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1072 // be null in this loop. 1073 unsigned Depth = CallStackDepth; 1074 CallStackFrame *Frame = CurrentCall; 1075 while (Frame->Index > CallIndex) { 1076 Frame = Frame->Caller; 1077 --Depth; 1078 } 1079 if (Frame->Index == CallIndex) 1080 return {Frame, Depth}; 1081 return {nullptr, 0}; 1082 } 1083 1084 bool nextStep(const Stmt *S) { 1085 if (!StepsLeft) { 1086 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1087 return false; 1088 } 1089 --StepsLeft; 1090 return true; 1091 } 1092 1093 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1094 1095 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) { 1096 std::optional<DynAlloc *> Result; 1097 auto It = HeapAllocs.find(DA); 1098 if (It != HeapAllocs.end()) 1099 Result = &It->second; 1100 return Result; 1101 } 1102 1103 /// Get the allocated storage for the given parameter of the given call. 1104 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1105 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1106 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1107 : nullptr; 1108 } 1109 1110 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1111 struct StdAllocatorCaller { 1112 unsigned FrameIndex; 1113 QualType ElemType; 1114 explicit operator bool() const { return FrameIndex != 0; }; 1115 }; 1116 1117 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1118 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1119 Call = Call->Caller) { 1120 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1121 if (!MD) 1122 continue; 1123 const IdentifierInfo *FnII = MD->getIdentifier(); 1124 if (!FnII || !FnII->isStr(FnName)) 1125 continue; 1126 1127 const auto *CTSD = 1128 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1129 if (!CTSD) 1130 continue; 1131 1132 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1133 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1134 if (CTSD->isInStdNamespace() && ClassII && 1135 ClassII->isStr("allocator") && TAL.size() >= 1 && 1136 TAL[0].getKind() == TemplateArgument::Type) 1137 return {Call->Index, TAL[0].getAsType()}; 1138 } 1139 1140 return {}; 1141 } 1142 1143 void performLifetimeExtension() { 1144 // Disable the cleanups for lifetime-extended temporaries. 1145 llvm::erase_if(CleanupStack, [](Cleanup &C) { 1146 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); 1147 }); 1148 } 1149 1150 /// Throw away any remaining cleanups at the end of evaluation. If any 1151 /// cleanups would have had a side-effect, note that as an unmodeled 1152 /// side-effect and return false. Otherwise, return true. 1153 bool discardCleanups() { 1154 for (Cleanup &C : CleanupStack) { 1155 if (C.hasSideEffect() && !noteSideEffect()) { 1156 CleanupStack.clear(); 1157 return false; 1158 } 1159 } 1160 CleanupStack.clear(); 1161 return true; 1162 } 1163 1164 private: 1165 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1166 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1167 1168 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1169 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1170 1171 void setFoldFailureDiagnostic(bool Flag) override { 1172 HasFoldFailureDiagnostic = Flag; 1173 } 1174 1175 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1176 1177 // If we have a prior diagnostic, it will be noting that the expression 1178 // isn't a constant expression. This diagnostic is more important, 1179 // unless we require this evaluation to produce a constant expression. 1180 // 1181 // FIXME: We might want to show both diagnostics to the user in 1182 // EM_ConstantFold mode. 1183 bool hasPriorDiagnostic() override { 1184 if (!EvalStatus.Diag->empty()) { 1185 switch (EvalMode) { 1186 case EM_ConstantFold: 1187 case EM_IgnoreSideEffects: 1188 if (!HasFoldFailureDiagnostic) 1189 break; 1190 // We've already failed to fold something. Keep that diagnostic. 1191 [[fallthrough]]; 1192 case EM_ConstantExpression: 1193 case EM_ConstantExpressionUnevaluated: 1194 setActiveDiagnostic(false); 1195 return true; 1196 } 1197 } 1198 return false; 1199 } 1200 1201 unsigned getCallStackDepth() override { return CallStackDepth; } 1202 1203 public: 1204 /// Should we continue evaluation after encountering a side-effect that we 1205 /// couldn't model? 1206 bool keepEvaluatingAfterSideEffect() { 1207 switch (EvalMode) { 1208 case EM_IgnoreSideEffects: 1209 return true; 1210 1211 case EM_ConstantExpression: 1212 case EM_ConstantExpressionUnevaluated: 1213 case EM_ConstantFold: 1214 // By default, assume any side effect might be valid in some other 1215 // evaluation of this expression from a different context. 1216 return checkingPotentialConstantExpression() || 1217 checkingForUndefinedBehavior(); 1218 } 1219 llvm_unreachable("Missed EvalMode case"); 1220 } 1221 1222 /// Note that we have had a side-effect, and determine whether we should 1223 /// keep evaluating. 1224 bool noteSideEffect() { 1225 EvalStatus.HasSideEffects = true; 1226 return keepEvaluatingAfterSideEffect(); 1227 } 1228 1229 /// Should we continue evaluation after encountering undefined behavior? 1230 bool keepEvaluatingAfterUndefinedBehavior() { 1231 switch (EvalMode) { 1232 case EM_IgnoreSideEffects: 1233 case EM_ConstantFold: 1234 return true; 1235 1236 case EM_ConstantExpression: 1237 case EM_ConstantExpressionUnevaluated: 1238 return checkingForUndefinedBehavior(); 1239 } 1240 llvm_unreachable("Missed EvalMode case"); 1241 } 1242 1243 /// Note that we hit something that was technically undefined behavior, but 1244 /// that we can evaluate past it (such as signed overflow or floating-point 1245 /// division by zero.) 1246 bool noteUndefinedBehavior() override { 1247 EvalStatus.HasUndefinedBehavior = true; 1248 return keepEvaluatingAfterUndefinedBehavior(); 1249 } 1250 1251 /// Should we continue evaluation as much as possible after encountering a 1252 /// construct which can't be reduced to a value? 1253 bool keepEvaluatingAfterFailure() const override { 1254 if (!StepsLeft) 1255 return false; 1256 1257 switch (EvalMode) { 1258 case EM_ConstantExpression: 1259 case EM_ConstantExpressionUnevaluated: 1260 case EM_ConstantFold: 1261 case EM_IgnoreSideEffects: 1262 return checkingPotentialConstantExpression() || 1263 checkingForUndefinedBehavior(); 1264 } 1265 llvm_unreachable("Missed EvalMode case"); 1266 } 1267 1268 /// Notes that we failed to evaluate an expression that other expressions 1269 /// directly depend on, and determine if we should keep evaluating. This 1270 /// should only be called if we actually intend to keep evaluating. 1271 /// 1272 /// Call noteSideEffect() instead if we may be able to ignore the value that 1273 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1274 /// 1275 /// (Foo(), 1) // use noteSideEffect 1276 /// (Foo() || true) // use noteSideEffect 1277 /// Foo() + 1 // use noteFailure 1278 [[nodiscard]] bool noteFailure() { 1279 // Failure when evaluating some expression often means there is some 1280 // subexpression whose evaluation was skipped. Therefore, (because we 1281 // don't track whether we skipped an expression when unwinding after an 1282 // evaluation failure) every evaluation failure that bubbles up from a 1283 // subexpression implies that a side-effect has potentially happened. We 1284 // skip setting the HasSideEffects flag to true until we decide to 1285 // continue evaluating after that point, which happens here. 1286 bool KeepGoing = keepEvaluatingAfterFailure(); 1287 EvalStatus.HasSideEffects |= KeepGoing; 1288 return KeepGoing; 1289 } 1290 1291 class ArrayInitLoopIndex { 1292 EvalInfo &Info; 1293 uint64_t OuterIndex; 1294 1295 public: 1296 ArrayInitLoopIndex(EvalInfo &Info) 1297 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1298 Info.ArrayInitIndex = 0; 1299 } 1300 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1301 1302 operator uint64_t&() { return Info.ArrayInitIndex; } 1303 }; 1304 }; 1305 1306 /// Object used to treat all foldable expressions as constant expressions. 1307 struct FoldConstant { 1308 EvalInfo &Info; 1309 bool Enabled; 1310 bool HadNoPriorDiags; 1311 EvalInfo::EvaluationMode OldMode; 1312 1313 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1314 : Info(Info), 1315 Enabled(Enabled), 1316 HadNoPriorDiags(Info.EvalStatus.Diag && 1317 Info.EvalStatus.Diag->empty() && 1318 !Info.EvalStatus.HasSideEffects), 1319 OldMode(Info.EvalMode) { 1320 if (Enabled) 1321 Info.EvalMode = EvalInfo::EM_ConstantFold; 1322 } 1323 void keepDiagnostics() { Enabled = false; } 1324 ~FoldConstant() { 1325 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1326 !Info.EvalStatus.HasSideEffects) 1327 Info.EvalStatus.Diag->clear(); 1328 Info.EvalMode = OldMode; 1329 } 1330 }; 1331 1332 /// RAII object used to set the current evaluation mode to ignore 1333 /// side-effects. 1334 struct IgnoreSideEffectsRAII { 1335 EvalInfo &Info; 1336 EvalInfo::EvaluationMode OldMode; 1337 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1338 : Info(Info), OldMode(Info.EvalMode) { 1339 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1340 } 1341 1342 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1343 }; 1344 1345 /// RAII object used to optionally suppress diagnostics and side-effects from 1346 /// a speculative evaluation. 1347 class SpeculativeEvaluationRAII { 1348 EvalInfo *Info = nullptr; 1349 Expr::EvalStatus OldStatus; 1350 unsigned OldSpeculativeEvaluationDepth = 0; 1351 1352 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1353 Info = Other.Info; 1354 OldStatus = Other.OldStatus; 1355 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1356 Other.Info = nullptr; 1357 } 1358 1359 void maybeRestoreState() { 1360 if (!Info) 1361 return; 1362 1363 Info->EvalStatus = OldStatus; 1364 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1365 } 1366 1367 public: 1368 SpeculativeEvaluationRAII() = default; 1369 1370 SpeculativeEvaluationRAII( 1371 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1372 : Info(&Info), OldStatus(Info.EvalStatus), 1373 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1374 Info.EvalStatus.Diag = NewDiag; 1375 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1376 } 1377 1378 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1379 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1380 moveFromAndCancel(std::move(Other)); 1381 } 1382 1383 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1384 maybeRestoreState(); 1385 moveFromAndCancel(std::move(Other)); 1386 return *this; 1387 } 1388 1389 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1390 }; 1391 1392 /// RAII object wrapping a full-expression or block scope, and handling 1393 /// the ending of the lifetime of temporaries created within it. 1394 template<ScopeKind Kind> 1395 class ScopeRAII { 1396 EvalInfo &Info; 1397 unsigned OldStackSize; 1398 public: 1399 ScopeRAII(EvalInfo &Info) 1400 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1401 // Push a new temporary version. This is needed to distinguish between 1402 // temporaries created in different iterations of a loop. 1403 Info.CurrentCall->pushTempVersion(); 1404 } 1405 bool destroy(bool RunDestructors = true) { 1406 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1407 OldStackSize = -1U; 1408 return OK; 1409 } 1410 ~ScopeRAII() { 1411 if (OldStackSize != -1U) 1412 destroy(false); 1413 // Body moved to a static method to encourage the compiler to inline away 1414 // instances of this class. 1415 Info.CurrentCall->popTempVersion(); 1416 } 1417 private: 1418 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1419 unsigned OldStackSize) { 1420 assert(OldStackSize <= Info.CleanupStack.size() && 1421 "running cleanups out of order?"); 1422 1423 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1424 // for a full-expression scope. 1425 bool Success = true; 1426 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1427 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1428 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1429 Success = false; 1430 break; 1431 } 1432 } 1433 } 1434 1435 // Compact any retained cleanups. 1436 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1437 if (Kind != ScopeKind::Block) 1438 NewEnd = 1439 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1440 return C.isDestroyedAtEndOf(Kind); 1441 }); 1442 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1443 return Success; 1444 } 1445 }; 1446 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1447 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1448 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1449 } 1450 1451 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1452 CheckSubobjectKind CSK) { 1453 if (Invalid) 1454 return false; 1455 if (isOnePastTheEnd()) { 1456 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1457 << CSK; 1458 setInvalid(); 1459 return false; 1460 } 1461 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1462 // must actually be at least one array element; even a VLA cannot have a 1463 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1464 return true; 1465 } 1466 1467 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1468 const Expr *E) { 1469 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1470 // Do not set the designator as invalid: we can represent this situation, 1471 // and correct handling of __builtin_object_size requires us to do so. 1472 } 1473 1474 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1475 const Expr *E, 1476 const APSInt &N) { 1477 // If we're complaining, we must be able to statically determine the size of 1478 // the most derived array. 1479 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1480 Info.CCEDiag(E, diag::note_constexpr_array_index) 1481 << N << /*array*/ 0 1482 << static_cast<unsigned>(getMostDerivedArraySize()); 1483 else 1484 Info.CCEDiag(E, diag::note_constexpr_array_index) 1485 << N << /*non-array*/ 1; 1486 setInvalid(); 1487 } 1488 1489 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange, 1490 const FunctionDecl *Callee, const LValue *This, 1491 const Expr *CallExpr, CallRef Call) 1492 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1493 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange), 1494 Index(Info.NextCallIndex++) { 1495 Info.CurrentCall = this; 1496 ++Info.CallStackDepth; 1497 } 1498 1499 CallStackFrame::~CallStackFrame() { 1500 assert(Info.CurrentCall == this && "calls retired out of order"); 1501 --Info.CallStackDepth; 1502 Info.CurrentCall = Caller; 1503 } 1504 1505 static bool isRead(AccessKinds AK) { 1506 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1507 } 1508 1509 static bool isModification(AccessKinds AK) { 1510 switch (AK) { 1511 case AK_Read: 1512 case AK_ReadObjectRepresentation: 1513 case AK_MemberCall: 1514 case AK_DynamicCast: 1515 case AK_TypeId: 1516 return false; 1517 case AK_Assign: 1518 case AK_Increment: 1519 case AK_Decrement: 1520 case AK_Construct: 1521 case AK_Destroy: 1522 return true; 1523 } 1524 llvm_unreachable("unknown access kind"); 1525 } 1526 1527 static bool isAnyAccess(AccessKinds AK) { 1528 return isRead(AK) || isModification(AK); 1529 } 1530 1531 /// Is this an access per the C++ definition? 1532 static bool isFormalAccess(AccessKinds AK) { 1533 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1534 } 1535 1536 /// Is this kind of axcess valid on an indeterminate object value? 1537 static bool isValidIndeterminateAccess(AccessKinds AK) { 1538 switch (AK) { 1539 case AK_Read: 1540 case AK_Increment: 1541 case AK_Decrement: 1542 // These need the object's value. 1543 return false; 1544 1545 case AK_ReadObjectRepresentation: 1546 case AK_Assign: 1547 case AK_Construct: 1548 case AK_Destroy: 1549 // Construction and destruction don't need the value. 1550 return true; 1551 1552 case AK_MemberCall: 1553 case AK_DynamicCast: 1554 case AK_TypeId: 1555 // These aren't really meaningful on scalars. 1556 return true; 1557 } 1558 llvm_unreachable("unknown access kind"); 1559 } 1560 1561 namespace { 1562 struct ComplexValue { 1563 private: 1564 bool IsInt; 1565 1566 public: 1567 APSInt IntReal, IntImag; 1568 APFloat FloatReal, FloatImag; 1569 1570 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1571 1572 void makeComplexFloat() { IsInt = false; } 1573 bool isComplexFloat() const { return !IsInt; } 1574 APFloat &getComplexFloatReal() { return FloatReal; } 1575 APFloat &getComplexFloatImag() { return FloatImag; } 1576 1577 void makeComplexInt() { IsInt = true; } 1578 bool isComplexInt() const { return IsInt; } 1579 APSInt &getComplexIntReal() { return IntReal; } 1580 APSInt &getComplexIntImag() { return IntImag; } 1581 1582 void moveInto(APValue &v) const { 1583 if (isComplexFloat()) 1584 v = APValue(FloatReal, FloatImag); 1585 else 1586 v = APValue(IntReal, IntImag); 1587 } 1588 void setFrom(const APValue &v) { 1589 assert(v.isComplexFloat() || v.isComplexInt()); 1590 if (v.isComplexFloat()) { 1591 makeComplexFloat(); 1592 FloatReal = v.getComplexFloatReal(); 1593 FloatImag = v.getComplexFloatImag(); 1594 } else { 1595 makeComplexInt(); 1596 IntReal = v.getComplexIntReal(); 1597 IntImag = v.getComplexIntImag(); 1598 } 1599 } 1600 }; 1601 1602 struct LValue { 1603 APValue::LValueBase Base; 1604 CharUnits Offset; 1605 SubobjectDesignator Designator; 1606 bool IsNullPtr : 1; 1607 bool InvalidBase : 1; 1608 1609 const APValue::LValueBase getLValueBase() const { return Base; } 1610 CharUnits &getLValueOffset() { return Offset; } 1611 const CharUnits &getLValueOffset() const { return Offset; } 1612 SubobjectDesignator &getLValueDesignator() { return Designator; } 1613 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1614 bool isNullPointer() const { return IsNullPtr;} 1615 1616 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1617 unsigned getLValueVersion() const { return Base.getVersion(); } 1618 1619 void moveInto(APValue &V) const { 1620 if (Designator.Invalid) 1621 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1622 else { 1623 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1624 V = APValue(Base, Offset, Designator.Entries, 1625 Designator.IsOnePastTheEnd, IsNullPtr); 1626 } 1627 } 1628 void setFrom(ASTContext &Ctx, const APValue &V) { 1629 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1630 Base = V.getLValueBase(); 1631 Offset = V.getLValueOffset(); 1632 InvalidBase = false; 1633 Designator = SubobjectDesignator(Ctx, V); 1634 IsNullPtr = V.isNullPointer(); 1635 } 1636 1637 void set(APValue::LValueBase B, bool BInvalid = false) { 1638 #ifndef NDEBUG 1639 // We only allow a few types of invalid bases. Enforce that here. 1640 if (BInvalid) { 1641 const auto *E = B.get<const Expr *>(); 1642 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1643 "Unexpected type of invalid base"); 1644 } 1645 #endif 1646 1647 Base = B; 1648 Offset = CharUnits::fromQuantity(0); 1649 InvalidBase = BInvalid; 1650 Designator = SubobjectDesignator(getType(B)); 1651 IsNullPtr = false; 1652 } 1653 1654 void setNull(ASTContext &Ctx, QualType PointerTy) { 1655 Base = (const ValueDecl *)nullptr; 1656 Offset = 1657 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1658 InvalidBase = false; 1659 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1660 IsNullPtr = true; 1661 } 1662 1663 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1664 set(B, true); 1665 } 1666 1667 std::string toString(ASTContext &Ctx, QualType T) const { 1668 APValue Printable; 1669 moveInto(Printable); 1670 return Printable.getAsString(Ctx, T); 1671 } 1672 1673 private: 1674 // Check that this LValue is not based on a null pointer. If it is, produce 1675 // a diagnostic and mark the designator as invalid. 1676 template <typename GenDiagType> 1677 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1678 if (Designator.Invalid) 1679 return false; 1680 if (IsNullPtr) { 1681 GenDiag(); 1682 Designator.setInvalid(); 1683 return false; 1684 } 1685 return true; 1686 } 1687 1688 public: 1689 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1690 CheckSubobjectKind CSK) { 1691 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1692 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1693 }); 1694 } 1695 1696 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1697 AccessKinds AK) { 1698 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1699 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1700 }); 1701 } 1702 1703 // Check this LValue refers to an object. If not, set the designator to be 1704 // invalid and emit a diagnostic. 1705 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1706 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1707 Designator.checkSubobject(Info, E, CSK); 1708 } 1709 1710 void addDecl(EvalInfo &Info, const Expr *E, 1711 const Decl *D, bool Virtual = false) { 1712 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1713 Designator.addDeclUnchecked(D, Virtual); 1714 } 1715 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1716 if (!Designator.Entries.empty()) { 1717 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1718 Designator.setInvalid(); 1719 return; 1720 } 1721 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1722 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1723 Designator.FirstEntryIsAnUnsizedArray = true; 1724 Designator.addUnsizedArrayUnchecked(ElemTy); 1725 } 1726 } 1727 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1728 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1729 Designator.addArrayUnchecked(CAT); 1730 } 1731 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1732 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1733 Designator.addComplexUnchecked(EltTy, Imag); 1734 } 1735 void clearIsNullPointer() { 1736 IsNullPtr = false; 1737 } 1738 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1739 const APSInt &Index, CharUnits ElementSize) { 1740 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1741 // but we're not required to diagnose it and it's valid in C++.) 1742 if (!Index) 1743 return; 1744 1745 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1746 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1747 // offsets. 1748 uint64_t Offset64 = Offset.getQuantity(); 1749 uint64_t ElemSize64 = ElementSize.getQuantity(); 1750 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1751 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1752 1753 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1754 Designator.adjustIndex(Info, E, Index); 1755 clearIsNullPointer(); 1756 } 1757 void adjustOffset(CharUnits N) { 1758 Offset += N; 1759 if (N.getQuantity()) 1760 clearIsNullPointer(); 1761 } 1762 }; 1763 1764 struct MemberPtr { 1765 MemberPtr() {} 1766 explicit MemberPtr(const ValueDecl *Decl) 1767 : DeclAndIsDerivedMember(Decl, false) {} 1768 1769 /// The member or (direct or indirect) field referred to by this member 1770 /// pointer, or 0 if this is a null member pointer. 1771 const ValueDecl *getDecl() const { 1772 return DeclAndIsDerivedMember.getPointer(); 1773 } 1774 /// Is this actually a member of some type derived from the relevant class? 1775 bool isDerivedMember() const { 1776 return DeclAndIsDerivedMember.getInt(); 1777 } 1778 /// Get the class which the declaration actually lives in. 1779 const CXXRecordDecl *getContainingRecord() const { 1780 return cast<CXXRecordDecl>( 1781 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1782 } 1783 1784 void moveInto(APValue &V) const { 1785 V = APValue(getDecl(), isDerivedMember(), Path); 1786 } 1787 void setFrom(const APValue &V) { 1788 assert(V.isMemberPointer()); 1789 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1790 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1791 Path.clear(); 1792 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1793 Path.insert(Path.end(), P.begin(), P.end()); 1794 } 1795 1796 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1797 /// whether the member is a member of some class derived from the class type 1798 /// of the member pointer. 1799 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1800 /// Path - The path of base/derived classes from the member declaration's 1801 /// class (exclusive) to the class type of the member pointer (inclusive). 1802 SmallVector<const CXXRecordDecl*, 4> Path; 1803 1804 /// Perform a cast towards the class of the Decl (either up or down the 1805 /// hierarchy). 1806 bool castBack(const CXXRecordDecl *Class) { 1807 assert(!Path.empty()); 1808 const CXXRecordDecl *Expected; 1809 if (Path.size() >= 2) 1810 Expected = Path[Path.size() - 2]; 1811 else 1812 Expected = getContainingRecord(); 1813 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1814 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1815 // if B does not contain the original member and is not a base or 1816 // derived class of the class containing the original member, the result 1817 // of the cast is undefined. 1818 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1819 // (D::*). We consider that to be a language defect. 1820 return false; 1821 } 1822 Path.pop_back(); 1823 return true; 1824 } 1825 /// Perform a base-to-derived member pointer cast. 1826 bool castToDerived(const CXXRecordDecl *Derived) { 1827 if (!getDecl()) 1828 return true; 1829 if (!isDerivedMember()) { 1830 Path.push_back(Derived); 1831 return true; 1832 } 1833 if (!castBack(Derived)) 1834 return false; 1835 if (Path.empty()) 1836 DeclAndIsDerivedMember.setInt(false); 1837 return true; 1838 } 1839 /// Perform a derived-to-base member pointer cast. 1840 bool castToBase(const CXXRecordDecl *Base) { 1841 if (!getDecl()) 1842 return true; 1843 if (Path.empty()) 1844 DeclAndIsDerivedMember.setInt(true); 1845 if (isDerivedMember()) { 1846 Path.push_back(Base); 1847 return true; 1848 } 1849 return castBack(Base); 1850 } 1851 }; 1852 1853 /// Compare two member pointers, which are assumed to be of the same type. 1854 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1855 if (!LHS.getDecl() || !RHS.getDecl()) 1856 return !LHS.getDecl() && !RHS.getDecl(); 1857 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1858 return false; 1859 return LHS.Path == RHS.Path; 1860 } 1861 } 1862 1863 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1864 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1865 const LValue &This, const Expr *E, 1866 bool AllowNonLiteralTypes = false); 1867 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1868 bool InvalidBaseOK = false); 1869 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1870 bool InvalidBaseOK = false); 1871 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1872 EvalInfo &Info); 1873 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1874 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1875 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1876 EvalInfo &Info); 1877 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1878 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1879 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1880 EvalInfo &Info); 1881 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1882 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 1883 EvalInfo &Info); 1884 1885 /// Evaluate an integer or fixed point expression into an APResult. 1886 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1887 EvalInfo &Info); 1888 1889 /// Evaluate only a fixed point expression into an APResult. 1890 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1891 EvalInfo &Info); 1892 1893 //===----------------------------------------------------------------------===// 1894 // Misc utilities 1895 //===----------------------------------------------------------------------===// 1896 1897 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1898 /// preserving its value (by extending by up to one bit as needed). 1899 static void negateAsSigned(APSInt &Int) { 1900 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1901 Int = Int.extend(Int.getBitWidth() + 1); 1902 Int.setIsSigned(true); 1903 } 1904 Int = -Int; 1905 } 1906 1907 template<typename KeyT> 1908 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1909 ScopeKind Scope, LValue &LV) { 1910 unsigned Version = getTempVersion(); 1911 APValue::LValueBase Base(Key, Index, Version); 1912 LV.set(Base); 1913 return createLocal(Base, Key, T, Scope); 1914 } 1915 1916 /// Allocate storage for a parameter of a function call made in this frame. 1917 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1918 LValue &LV) { 1919 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1920 APValue::LValueBase Base(PVD, Index, Args.Version); 1921 LV.set(Base); 1922 // We always destroy parameters at the end of the call, even if we'd allow 1923 // them to live to the end of the full-expression at runtime, in order to 1924 // give portable results and match other compilers. 1925 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1926 } 1927 1928 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1929 QualType T, ScopeKind Scope) { 1930 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1931 unsigned Version = Base.getVersion(); 1932 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1933 assert(Result.isAbsent() && "local created multiple times"); 1934 1935 // If we're creating a local immediately in the operand of a speculative 1936 // evaluation, don't register a cleanup to be run outside the speculative 1937 // evaluation context, since we won't actually be able to initialize this 1938 // object. 1939 if (Index <= Info.SpeculativeEvaluationDepth) { 1940 if (T.isDestructedType()) 1941 Info.noteSideEffect(); 1942 } else { 1943 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1944 } 1945 return Result; 1946 } 1947 1948 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1949 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1950 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1951 return nullptr; 1952 } 1953 1954 DynamicAllocLValue DA(NumHeapAllocs++); 1955 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1956 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1957 std::forward_as_tuple(DA), std::tuple<>()); 1958 assert(Result.second && "reused a heap alloc index?"); 1959 Result.first->second.AllocExpr = E; 1960 return &Result.first->second.Value; 1961 } 1962 1963 /// Produce a string describing the given constexpr call. 1964 void CallStackFrame::describe(raw_ostream &Out) const { 1965 unsigned ArgIndex = 0; 1966 bool IsMemberCall = 1967 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) && 1968 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction(); 1969 1970 if (!IsMemberCall) 1971 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(), 1972 /*Qualified=*/false); 1973 1974 if (This && IsMemberCall) { 1975 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) { 1976 const Expr *Object = MCE->getImplicitObjectArgument(); 1977 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(), 1978 /*Indentation=*/0); 1979 if (Object->getType()->isPointerType()) 1980 Out << "->"; 1981 else 1982 Out << "."; 1983 } else if (const auto *OCE = 1984 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) { 1985 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, 1986 Info.Ctx.getPrintingPolicy(), 1987 /*Indentation=*/0); 1988 Out << "."; 1989 } else { 1990 APValue Val; 1991 This->moveInto(Val); 1992 Val.printPretty( 1993 Out, Info.Ctx, 1994 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType)); 1995 Out << "."; 1996 } 1997 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(), 1998 /*Qualified=*/false); 1999 IsMemberCall = false; 2000 } 2001 2002 Out << '('; 2003 2004 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 2005 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 2006 if (ArgIndex > (unsigned)IsMemberCall) 2007 Out << ", "; 2008 2009 const ParmVarDecl *Param = *I; 2010 APValue *V = Info.getParamSlot(Arguments, Param); 2011 if (V) 2012 V->printPretty(Out, Info.Ctx, Param->getType()); 2013 else 2014 Out << "<...>"; 2015 2016 if (ArgIndex == 0 && IsMemberCall) 2017 Out << "->" << *Callee << '('; 2018 } 2019 2020 Out << ')'; 2021 } 2022 2023 /// Evaluate an expression to see if it had side-effects, and discard its 2024 /// result. 2025 /// \return \c true if the caller should keep evaluating. 2026 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 2027 assert(!E->isValueDependent()); 2028 APValue Scratch; 2029 if (!Evaluate(Scratch, Info, E)) 2030 // We don't need the value, but we might have skipped a side effect here. 2031 return Info.noteSideEffect(); 2032 return true; 2033 } 2034 2035 /// Should this call expression be treated as a no-op? 2036 static bool IsNoOpCall(const CallExpr *E) { 2037 unsigned Builtin = E->getBuiltinCallee(); 2038 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 2039 Builtin == Builtin::BI__builtin___NSStringMakeConstantString || 2040 Builtin == Builtin::BI__builtin_function_start); 2041 } 2042 2043 static bool IsGlobalLValue(APValue::LValueBase B) { 2044 // C++11 [expr.const]p3 An address constant expression is a prvalue core 2045 // constant expression of pointer type that evaluates to... 2046 2047 // ... a null pointer value, or a prvalue core constant expression of type 2048 // std::nullptr_t. 2049 if (!B) 2050 return true; 2051 2052 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 2053 // ... the address of an object with static storage duration, 2054 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 2055 return VD->hasGlobalStorage(); 2056 if (isa<TemplateParamObjectDecl>(D)) 2057 return true; 2058 // ... the address of a function, 2059 // ... the address of a GUID [MS extension], 2060 // ... the address of an unnamed global constant 2061 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D); 2062 } 2063 2064 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 2065 return true; 2066 2067 const Expr *E = B.get<const Expr*>(); 2068 switch (E->getStmtClass()) { 2069 default: 2070 return false; 2071 case Expr::CompoundLiteralExprClass: { 2072 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 2073 return CLE->isFileScope() && CLE->isLValue(); 2074 } 2075 case Expr::MaterializeTemporaryExprClass: 2076 // A materialized temporary might have been lifetime-extended to static 2077 // storage duration. 2078 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 2079 // A string literal has static storage duration. 2080 case Expr::StringLiteralClass: 2081 case Expr::PredefinedExprClass: 2082 case Expr::ObjCStringLiteralClass: 2083 case Expr::ObjCEncodeExprClass: 2084 return true; 2085 case Expr::ObjCBoxedExprClass: 2086 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2087 case Expr::CallExprClass: 2088 return IsNoOpCall(cast<CallExpr>(E)); 2089 // For GCC compatibility, &&label has static storage duration. 2090 case Expr::AddrLabelExprClass: 2091 return true; 2092 // A Block literal expression may be used as the initialization value for 2093 // Block variables at global or local static scope. 2094 case Expr::BlockExprClass: 2095 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2096 // The APValue generated from a __builtin_source_location will be emitted as a 2097 // literal. 2098 case Expr::SourceLocExprClass: 2099 return true; 2100 case Expr::ImplicitValueInitExprClass: 2101 // FIXME: 2102 // We can never form an lvalue with an implicit value initialization as its 2103 // base through expression evaluation, so these only appear in one case: the 2104 // implicit variable declaration we invent when checking whether a constexpr 2105 // constructor can produce a constant expression. We must assume that such 2106 // an expression might be a global lvalue. 2107 return true; 2108 } 2109 } 2110 2111 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2112 return LVal.Base.dyn_cast<const ValueDecl*>(); 2113 } 2114 2115 static bool IsLiteralLValue(const LValue &Value) { 2116 if (Value.getLValueCallIndex()) 2117 return false; 2118 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2119 return E && !isa<MaterializeTemporaryExpr>(E); 2120 } 2121 2122 static bool IsWeakLValue(const LValue &Value) { 2123 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2124 return Decl && Decl->isWeak(); 2125 } 2126 2127 static bool isZeroSized(const LValue &Value) { 2128 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2129 if (Decl && isa<VarDecl>(Decl)) { 2130 QualType Ty = Decl->getType(); 2131 if (Ty->isArrayType()) 2132 return Ty->isIncompleteType() || 2133 Decl->getASTContext().getTypeSize(Ty) == 0; 2134 } 2135 return false; 2136 } 2137 2138 static bool HasSameBase(const LValue &A, const LValue &B) { 2139 if (!A.getLValueBase()) 2140 return !B.getLValueBase(); 2141 if (!B.getLValueBase()) 2142 return false; 2143 2144 if (A.getLValueBase().getOpaqueValue() != 2145 B.getLValueBase().getOpaqueValue()) 2146 return false; 2147 2148 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2149 A.getLValueVersion() == B.getLValueVersion(); 2150 } 2151 2152 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2153 assert(Base && "no location for a null lvalue"); 2154 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2155 2156 // For a parameter, find the corresponding call stack frame (if it still 2157 // exists), and point at the parameter of the function definition we actually 2158 // invoked. 2159 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2160 unsigned Idx = PVD->getFunctionScopeIndex(); 2161 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2162 if (F->Arguments.CallIndex == Base.getCallIndex() && 2163 F->Arguments.Version == Base.getVersion() && F->Callee && 2164 Idx < F->Callee->getNumParams()) { 2165 VD = F->Callee->getParamDecl(Idx); 2166 break; 2167 } 2168 } 2169 } 2170 2171 if (VD) 2172 Info.Note(VD->getLocation(), diag::note_declared_at); 2173 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2174 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2175 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2176 // FIXME: Produce a note for dangling pointers too. 2177 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA)) 2178 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2179 diag::note_constexpr_dynamic_alloc_here); 2180 } 2181 2182 // We have no information to show for a typeid(T) object. 2183 } 2184 2185 enum class CheckEvaluationResultKind { 2186 ConstantExpression, 2187 FullyInitialized, 2188 }; 2189 2190 /// Materialized temporaries that we've already checked to determine if they're 2191 /// initializsed by a constant expression. 2192 using CheckedTemporaries = 2193 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2194 2195 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2196 EvalInfo &Info, SourceLocation DiagLoc, 2197 QualType Type, const APValue &Value, 2198 ConstantExprKind Kind, 2199 const FieldDecl *SubobjectDecl, 2200 CheckedTemporaries &CheckedTemps); 2201 2202 /// Check that this reference or pointer core constant expression is a valid 2203 /// value for an address or reference constant expression. Return true if we 2204 /// can fold this expression, whether or not it's a constant expression. 2205 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2206 QualType Type, const LValue &LVal, 2207 ConstantExprKind Kind, 2208 CheckedTemporaries &CheckedTemps) { 2209 bool IsReferenceType = Type->isReferenceType(); 2210 2211 APValue::LValueBase Base = LVal.getLValueBase(); 2212 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2213 2214 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2215 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2216 2217 // Additional restrictions apply in a template argument. We only enforce the 2218 // C++20 restrictions here; additional syntactic and semantic restrictions 2219 // are applied elsewhere. 2220 if (isTemplateArgument(Kind)) { 2221 int InvalidBaseKind = -1; 2222 StringRef Ident; 2223 if (Base.is<TypeInfoLValue>()) 2224 InvalidBaseKind = 0; 2225 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2226 InvalidBaseKind = 1; 2227 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2228 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2229 InvalidBaseKind = 2; 2230 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2231 InvalidBaseKind = 3; 2232 Ident = PE->getIdentKindName(); 2233 } 2234 2235 if (InvalidBaseKind != -1) { 2236 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2237 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2238 << Ident; 2239 return false; 2240 } 2241 } 2242 2243 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD); 2244 FD && FD->isImmediateFunction()) { 2245 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2246 << !Type->isAnyPointerType(); 2247 Info.Note(FD->getLocation(), diag::note_declared_at); 2248 return false; 2249 } 2250 2251 // Check that the object is a global. Note that the fake 'this' object we 2252 // manufacture when checking potential constant expressions is conservatively 2253 // assumed to be global here. 2254 if (!IsGlobalLValue(Base)) { 2255 if (Info.getLangOpts().CPlusPlus11) { 2256 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2257 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD 2258 << BaseVD; 2259 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD); 2260 if (VarD && VarD->isConstexpr()) { 2261 // Non-static local constexpr variables have unintuitive semantics: 2262 // constexpr int a = 1; 2263 // constexpr const int *p = &a; 2264 // ... is invalid because the address of 'a' is not constant. Suggest 2265 // adding a 'static' in this case. 2266 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2267 << VarD 2268 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2269 } else { 2270 NoteLValueLocation(Info, Base); 2271 } 2272 } else { 2273 Info.FFDiag(Loc); 2274 } 2275 // Don't allow references to temporaries to escape. 2276 return false; 2277 } 2278 assert((Info.checkingPotentialConstantExpression() || 2279 LVal.getLValueCallIndex() == 0) && 2280 "have call index for global lvalue"); 2281 2282 if (Base.is<DynamicAllocLValue>()) { 2283 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2284 << IsReferenceType << !Designator.Entries.empty(); 2285 NoteLValueLocation(Info, Base); 2286 return false; 2287 } 2288 2289 if (BaseVD) { 2290 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2291 // Check if this is a thread-local variable. 2292 if (Var->getTLSKind()) 2293 // FIXME: Diagnostic! 2294 return false; 2295 2296 // A dllimport variable never acts like a constant, unless we're 2297 // evaluating a value for use only in name mangling. 2298 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2299 // FIXME: Diagnostic! 2300 return false; 2301 2302 // In CUDA/HIP device compilation, only device side variables have 2303 // constant addresses. 2304 if (Info.getCtx().getLangOpts().CUDA && 2305 Info.getCtx().getLangOpts().CUDAIsDevice && 2306 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) { 2307 if ((!Var->hasAttr<CUDADeviceAttr>() && 2308 !Var->hasAttr<CUDAConstantAttr>() && 2309 !Var->getType()->isCUDADeviceBuiltinSurfaceType() && 2310 !Var->getType()->isCUDADeviceBuiltinTextureType()) || 2311 Var->hasAttr<HIPManagedAttr>()) 2312 return false; 2313 } 2314 } 2315 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2316 // __declspec(dllimport) must be handled very carefully: 2317 // We must never initialize an expression with the thunk in C++. 2318 // Doing otherwise would allow the same id-expression to yield 2319 // different addresses for the same function in different translation 2320 // units. However, this means that we must dynamically initialize the 2321 // expression with the contents of the import address table at runtime. 2322 // 2323 // The C language has no notion of ODR; furthermore, it has no notion of 2324 // dynamic initialization. This means that we are permitted to 2325 // perform initialization with the address of the thunk. 2326 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2327 FD->hasAttr<DLLImportAttr>()) 2328 // FIXME: Diagnostic! 2329 return false; 2330 } 2331 } else if (const auto *MTE = 2332 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2333 if (CheckedTemps.insert(MTE).second) { 2334 QualType TempType = getType(Base); 2335 if (TempType.isDestructedType()) { 2336 Info.FFDiag(MTE->getExprLoc(), 2337 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2338 << TempType; 2339 return false; 2340 } 2341 2342 APValue *V = MTE->getOrCreateValue(false); 2343 assert(V && "evasluation result refers to uninitialised temporary"); 2344 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2345 Info, MTE->getExprLoc(), TempType, *V, Kind, 2346 /*SubobjectDecl=*/nullptr, CheckedTemps)) 2347 return false; 2348 } 2349 } 2350 2351 // Allow address constant expressions to be past-the-end pointers. This is 2352 // an extension: the standard requires them to point to an object. 2353 if (!IsReferenceType) 2354 return true; 2355 2356 // A reference constant expression must refer to an object. 2357 if (!Base) { 2358 // FIXME: diagnostic 2359 Info.CCEDiag(Loc); 2360 return true; 2361 } 2362 2363 // Does this refer one past the end of some object? 2364 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2365 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2366 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2367 NoteLValueLocation(Info, Base); 2368 } 2369 2370 return true; 2371 } 2372 2373 /// Member pointers are constant expressions unless they point to a 2374 /// non-virtual dllimport member function. 2375 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2376 SourceLocation Loc, 2377 QualType Type, 2378 const APValue &Value, 2379 ConstantExprKind Kind) { 2380 const ValueDecl *Member = Value.getMemberPointerDecl(); 2381 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2382 if (!FD) 2383 return true; 2384 if (FD->isImmediateFunction()) { 2385 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2386 Info.Note(FD->getLocation(), diag::note_declared_at); 2387 return false; 2388 } 2389 return isForManglingOnly(Kind) || FD->isVirtual() || 2390 !FD->hasAttr<DLLImportAttr>(); 2391 } 2392 2393 /// Check that this core constant expression is of literal type, and if not, 2394 /// produce an appropriate diagnostic. 2395 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2396 const LValue *This = nullptr) { 2397 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2398 return true; 2399 2400 // C++1y: A constant initializer for an object o [...] may also invoke 2401 // constexpr constructors for o and its subobjects even if those objects 2402 // are of non-literal class types. 2403 // 2404 // C++11 missed this detail for aggregates, so classes like this: 2405 // struct foo_t { union { int i; volatile int j; } u; }; 2406 // are not (obviously) initializable like so: 2407 // __attribute__((__require_constant_initialization__)) 2408 // static const foo_t x = {{0}}; 2409 // because "i" is a subobject with non-literal initialization (due to the 2410 // volatile member of the union). See: 2411 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2412 // Therefore, we use the C++1y behavior. 2413 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2414 return true; 2415 2416 // Prvalue constant expressions must be of literal types. 2417 if (Info.getLangOpts().CPlusPlus11) 2418 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2419 << E->getType(); 2420 else 2421 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2422 return false; 2423 } 2424 2425 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2426 EvalInfo &Info, SourceLocation DiagLoc, 2427 QualType Type, const APValue &Value, 2428 ConstantExprKind Kind, 2429 const FieldDecl *SubobjectDecl, 2430 CheckedTemporaries &CheckedTemps) { 2431 if (!Value.hasValue()) { 2432 if (SubobjectDecl) { 2433 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2434 << /*(name)*/ 1 << SubobjectDecl; 2435 Info.Note(SubobjectDecl->getLocation(), 2436 diag::note_constexpr_subobject_declared_here); 2437 } else { 2438 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2439 << /*of type*/ 0 << Type; 2440 } 2441 return false; 2442 } 2443 2444 // We allow _Atomic(T) to be initialized from anything that T can be 2445 // initialized from. 2446 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2447 Type = AT->getValueType(); 2448 2449 // Core issue 1454: For a literal constant expression of array or class type, 2450 // each subobject of its value shall have been initialized by a constant 2451 // expression. 2452 if (Value.isArray()) { 2453 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2454 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2455 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2456 Value.getArrayInitializedElt(I), Kind, 2457 SubobjectDecl, CheckedTemps)) 2458 return false; 2459 } 2460 if (!Value.hasArrayFiller()) 2461 return true; 2462 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2463 Value.getArrayFiller(), Kind, SubobjectDecl, 2464 CheckedTemps); 2465 } 2466 if (Value.isUnion() && Value.getUnionField()) { 2467 return CheckEvaluationResult( 2468 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2469 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps); 2470 } 2471 if (Value.isStruct()) { 2472 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2473 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2474 unsigned BaseIndex = 0; 2475 for (const CXXBaseSpecifier &BS : CD->bases()) { 2476 const APValue &BaseValue = Value.getStructBase(BaseIndex); 2477 if (!BaseValue.hasValue()) { 2478 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc(); 2479 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base) 2480 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc()); 2481 return false; 2482 } 2483 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue, 2484 Kind, /*SubobjectDecl=*/nullptr, 2485 CheckedTemps)) 2486 return false; 2487 ++BaseIndex; 2488 } 2489 } 2490 for (const auto *I : RD->fields()) { 2491 if (I->isUnnamedBitfield()) 2492 continue; 2493 2494 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2495 Value.getStructField(I->getFieldIndex()), Kind, 2496 I, CheckedTemps)) 2497 return false; 2498 } 2499 } 2500 2501 if (Value.isLValue() && 2502 CERK == CheckEvaluationResultKind::ConstantExpression) { 2503 LValue LVal; 2504 LVal.setFrom(Info.Ctx, Value); 2505 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2506 CheckedTemps); 2507 } 2508 2509 if (Value.isMemberPointer() && 2510 CERK == CheckEvaluationResultKind::ConstantExpression) 2511 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2512 2513 // Everything else is fine. 2514 return true; 2515 } 2516 2517 /// Check that this core constant expression value is a valid value for a 2518 /// constant expression. If not, report an appropriate diagnostic. Does not 2519 /// check that the expression is of literal type. 2520 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2521 QualType Type, const APValue &Value, 2522 ConstantExprKind Kind) { 2523 // Nothing to check for a constant expression of type 'cv void'. 2524 if (Type->isVoidType()) 2525 return true; 2526 2527 CheckedTemporaries CheckedTemps; 2528 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2529 Info, DiagLoc, Type, Value, Kind, 2530 /*SubobjectDecl=*/nullptr, CheckedTemps); 2531 } 2532 2533 /// Check that this evaluated value is fully-initialized and can be loaded by 2534 /// an lvalue-to-rvalue conversion. 2535 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2536 QualType Type, const APValue &Value) { 2537 CheckedTemporaries CheckedTemps; 2538 return CheckEvaluationResult( 2539 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2540 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps); 2541 } 2542 2543 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2544 /// "the allocated storage is deallocated within the evaluation". 2545 static bool CheckMemoryLeaks(EvalInfo &Info) { 2546 if (!Info.HeapAllocs.empty()) { 2547 // We can still fold to a constant despite a compile-time memory leak, 2548 // so long as the heap allocation isn't referenced in the result (we check 2549 // that in CheckConstantExpression). 2550 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2551 diag::note_constexpr_memory_leak) 2552 << unsigned(Info.HeapAllocs.size() - 1); 2553 } 2554 return true; 2555 } 2556 2557 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2558 // A null base expression indicates a null pointer. These are always 2559 // evaluatable, and they are false unless the offset is zero. 2560 if (!Value.getLValueBase()) { 2561 // TODO: Should a non-null pointer with an offset of zero evaluate to true? 2562 Result = !Value.getLValueOffset().isZero(); 2563 return true; 2564 } 2565 2566 // We have a non-null base. These are generally known to be true, but if it's 2567 // a weak declaration it can be null at runtime. 2568 Result = true; 2569 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2570 return !Decl || !Decl->isWeak(); 2571 } 2572 2573 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2574 // TODO: This function should produce notes if it fails. 2575 switch (Val.getKind()) { 2576 case APValue::None: 2577 case APValue::Indeterminate: 2578 return false; 2579 case APValue::Int: 2580 Result = Val.getInt().getBoolValue(); 2581 return true; 2582 case APValue::FixedPoint: 2583 Result = Val.getFixedPoint().getBoolValue(); 2584 return true; 2585 case APValue::Float: 2586 Result = !Val.getFloat().isZero(); 2587 return true; 2588 case APValue::ComplexInt: 2589 Result = Val.getComplexIntReal().getBoolValue() || 2590 Val.getComplexIntImag().getBoolValue(); 2591 return true; 2592 case APValue::ComplexFloat: 2593 Result = !Val.getComplexFloatReal().isZero() || 2594 !Val.getComplexFloatImag().isZero(); 2595 return true; 2596 case APValue::LValue: 2597 return EvalPointerValueAsBool(Val, Result); 2598 case APValue::MemberPointer: 2599 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) { 2600 return false; 2601 } 2602 Result = Val.getMemberPointerDecl(); 2603 return true; 2604 case APValue::Vector: 2605 case APValue::Array: 2606 case APValue::Struct: 2607 case APValue::Union: 2608 case APValue::AddrLabelDiff: 2609 return false; 2610 } 2611 2612 llvm_unreachable("unknown APValue kind"); 2613 } 2614 2615 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2616 EvalInfo &Info) { 2617 assert(!E->isValueDependent()); 2618 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2619 APValue Val; 2620 if (!Evaluate(Val, Info, E)) 2621 return false; 2622 return HandleConversionToBool(Val, Result); 2623 } 2624 2625 template<typename T> 2626 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2627 const T &SrcValue, QualType DestType) { 2628 Info.CCEDiag(E, diag::note_constexpr_overflow) 2629 << SrcValue << DestType; 2630 return Info.noteUndefinedBehavior(); 2631 } 2632 2633 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2634 QualType SrcType, const APFloat &Value, 2635 QualType DestType, APSInt &Result) { 2636 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2637 // Determine whether we are converting to unsigned or signed. 2638 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2639 2640 Result = APSInt(DestWidth, !DestSigned); 2641 bool ignored; 2642 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2643 & APFloat::opInvalidOp) 2644 return HandleOverflow(Info, E, Value, DestType); 2645 return true; 2646 } 2647 2648 /// Get rounding mode to use in evaluation of the specified expression. 2649 /// 2650 /// If rounding mode is unknown at compile time, still try to evaluate the 2651 /// expression. If the result is exact, it does not depend on rounding mode. 2652 /// So return "tonearest" mode instead of "dynamic". 2653 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) { 2654 llvm::RoundingMode RM = 2655 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2656 if (RM == llvm::RoundingMode::Dynamic) 2657 RM = llvm::RoundingMode::NearestTiesToEven; 2658 return RM; 2659 } 2660 2661 /// Check if the given evaluation result is allowed for constant evaluation. 2662 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2663 APFloat::opStatus St) { 2664 // In a constant context, assume that any dynamic rounding mode or FP 2665 // exception state matches the default floating-point environment. 2666 if (Info.InConstantContext) 2667 return true; 2668 2669 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2670 if ((St & APFloat::opInexact) && 2671 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2672 // Inexact result means that it depends on rounding mode. If the requested 2673 // mode is dynamic, the evaluation cannot be made in compile time. 2674 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2675 return false; 2676 } 2677 2678 if ((St != APFloat::opOK) && 2679 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2680 FPO.getExceptionMode() != LangOptions::FPE_Ignore || 2681 FPO.getAllowFEnvAccess())) { 2682 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2683 return false; 2684 } 2685 2686 if ((St & APFloat::opStatus::opInvalidOp) && 2687 FPO.getExceptionMode() != LangOptions::FPE_Ignore) { 2688 // There is no usefully definable result. 2689 Info.FFDiag(E); 2690 return false; 2691 } 2692 2693 // FIXME: if: 2694 // - evaluation triggered other FP exception, and 2695 // - exception mode is not "ignore", and 2696 // - the expression being evaluated is not a part of global variable 2697 // initializer, 2698 // the evaluation probably need to be rejected. 2699 return true; 2700 } 2701 2702 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2703 QualType SrcType, QualType DestType, 2704 APFloat &Result) { 2705 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2706 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 2707 APFloat::opStatus St; 2708 APFloat Value = Result; 2709 bool ignored; 2710 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2711 return checkFloatingPointResult(Info, E, St); 2712 } 2713 2714 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2715 QualType DestType, QualType SrcType, 2716 const APSInt &Value) { 2717 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2718 // Figure out if this is a truncate, extend or noop cast. 2719 // If the input is signed, do a sign extend, noop, or truncate. 2720 APSInt Result = Value.extOrTrunc(DestWidth); 2721 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2722 if (DestType->isBooleanType()) 2723 Result = Value.getBoolValue(); 2724 return Result; 2725 } 2726 2727 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2728 const FPOptions FPO, 2729 QualType SrcType, const APSInt &Value, 2730 QualType DestType, APFloat &Result) { 2731 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2732 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 2733 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM); 2734 return checkFloatingPointResult(Info, E, St); 2735 } 2736 2737 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2738 APValue &Value, const FieldDecl *FD) { 2739 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2740 2741 if (!Value.isInt()) { 2742 // Trying to store a pointer-cast-to-integer into a bitfield. 2743 // FIXME: In this case, we should provide the diagnostic for casting 2744 // a pointer to an integer. 2745 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2746 Info.FFDiag(E); 2747 return false; 2748 } 2749 2750 APSInt &Int = Value.getInt(); 2751 unsigned OldBitWidth = Int.getBitWidth(); 2752 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2753 if (NewBitWidth < OldBitWidth) 2754 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2755 return true; 2756 } 2757 2758 /// Perform the given integer operation, which is known to need at most BitWidth 2759 /// bits, and check for overflow in the original type (if that type was not an 2760 /// unsigned type). 2761 template<typename Operation> 2762 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2763 const APSInt &LHS, const APSInt &RHS, 2764 unsigned BitWidth, Operation Op, 2765 APSInt &Result) { 2766 if (LHS.isUnsigned()) { 2767 Result = Op(LHS, RHS); 2768 return true; 2769 } 2770 2771 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2772 Result = Value.trunc(LHS.getBitWidth()); 2773 if (Result.extend(BitWidth) != Value) { 2774 if (Info.checkingForUndefinedBehavior()) 2775 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2776 diag::warn_integer_constant_overflow) 2777 << toString(Result, 10) << E->getType() << E->getSourceRange(); 2778 return HandleOverflow(Info, E, Value, E->getType()); 2779 } 2780 return true; 2781 } 2782 2783 /// Perform the given binary integer operation. 2784 static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, 2785 const APSInt &LHS, BinaryOperatorKind Opcode, 2786 APSInt RHS, APSInt &Result) { 2787 bool HandleOverflowResult = true; 2788 switch (Opcode) { 2789 default: 2790 Info.FFDiag(E); 2791 return false; 2792 case BO_Mul: 2793 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2794 std::multiplies<APSInt>(), Result); 2795 case BO_Add: 2796 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2797 std::plus<APSInt>(), Result); 2798 case BO_Sub: 2799 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2800 std::minus<APSInt>(), Result); 2801 case BO_And: Result = LHS & RHS; return true; 2802 case BO_Xor: Result = LHS ^ RHS; return true; 2803 case BO_Or: Result = LHS | RHS; return true; 2804 case BO_Div: 2805 case BO_Rem: 2806 if (RHS == 0) { 2807 Info.FFDiag(E, diag::note_expr_divide_by_zero) 2808 << E->getRHS()->getSourceRange(); 2809 return false; 2810 } 2811 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2812 // this operation and gives the two's complement result. 2813 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && 2814 LHS.isMinSignedValue()) 2815 HandleOverflowResult = HandleOverflow( 2816 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType()); 2817 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2818 return HandleOverflowResult; 2819 case BO_Shl: { 2820 if (Info.getLangOpts().OpenCL) 2821 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2822 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2823 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2824 RHS.isUnsigned()); 2825 else if (RHS.isSigned() && RHS.isNegative()) { 2826 // During constant-folding, a negative shift is an opposite shift. Such 2827 // a shift is not a constant expression. 2828 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2829 RHS = -RHS; 2830 goto shift_right; 2831 } 2832 shift_left: 2833 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2834 // the shifted type. 2835 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2836 if (SA != RHS) { 2837 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2838 << RHS << E->getType() << LHS.getBitWidth(); 2839 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2840 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2841 // operand, and must not overflow the corresponding unsigned type. 2842 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2843 // E1 x 2^E2 module 2^N. 2844 if (LHS.isNegative()) 2845 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2846 else if (LHS.countl_zero() < SA) 2847 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2848 } 2849 Result = LHS << SA; 2850 return true; 2851 } 2852 case BO_Shr: { 2853 if (Info.getLangOpts().OpenCL) 2854 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2855 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2856 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2857 RHS.isUnsigned()); 2858 else if (RHS.isSigned() && RHS.isNegative()) { 2859 // During constant-folding, a negative shift is an opposite shift. Such a 2860 // shift is not a constant expression. 2861 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2862 RHS = -RHS; 2863 goto shift_left; 2864 } 2865 shift_right: 2866 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2867 // shifted type. 2868 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2869 if (SA != RHS) 2870 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2871 << RHS << E->getType() << LHS.getBitWidth(); 2872 Result = LHS >> SA; 2873 return true; 2874 } 2875 2876 case BO_LT: Result = LHS < RHS; return true; 2877 case BO_GT: Result = LHS > RHS; return true; 2878 case BO_LE: Result = LHS <= RHS; return true; 2879 case BO_GE: Result = LHS >= RHS; return true; 2880 case BO_EQ: Result = LHS == RHS; return true; 2881 case BO_NE: Result = LHS != RHS; return true; 2882 case BO_Cmp: 2883 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2884 } 2885 } 2886 2887 /// Perform the given binary floating-point operation, in-place, on LHS. 2888 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2889 APFloat &LHS, BinaryOperatorKind Opcode, 2890 const APFloat &RHS) { 2891 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 2892 APFloat::opStatus St; 2893 switch (Opcode) { 2894 default: 2895 Info.FFDiag(E); 2896 return false; 2897 case BO_Mul: 2898 St = LHS.multiply(RHS, RM); 2899 break; 2900 case BO_Add: 2901 St = LHS.add(RHS, RM); 2902 break; 2903 case BO_Sub: 2904 St = LHS.subtract(RHS, RM); 2905 break; 2906 case BO_Div: 2907 // [expr.mul]p4: 2908 // If the second operand of / or % is zero the behavior is undefined. 2909 if (RHS.isZero()) 2910 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2911 St = LHS.divide(RHS, RM); 2912 break; 2913 } 2914 2915 // [expr.pre]p4: 2916 // If during the evaluation of an expression, the result is not 2917 // mathematically defined [...], the behavior is undefined. 2918 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2919 if (LHS.isNaN()) { 2920 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2921 return Info.noteUndefinedBehavior(); 2922 } 2923 2924 return checkFloatingPointResult(Info, E, St); 2925 } 2926 2927 static bool handleLogicalOpForVector(const APInt &LHSValue, 2928 BinaryOperatorKind Opcode, 2929 const APInt &RHSValue, APInt &Result) { 2930 bool LHS = (LHSValue != 0); 2931 bool RHS = (RHSValue != 0); 2932 2933 if (Opcode == BO_LAnd) 2934 Result = LHS && RHS; 2935 else 2936 Result = LHS || RHS; 2937 return true; 2938 } 2939 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2940 BinaryOperatorKind Opcode, 2941 const APFloat &RHSValue, APInt &Result) { 2942 bool LHS = !LHSValue.isZero(); 2943 bool RHS = !RHSValue.isZero(); 2944 2945 if (Opcode == BO_LAnd) 2946 Result = LHS && RHS; 2947 else 2948 Result = LHS || RHS; 2949 return true; 2950 } 2951 2952 static bool handleLogicalOpForVector(const APValue &LHSValue, 2953 BinaryOperatorKind Opcode, 2954 const APValue &RHSValue, APInt &Result) { 2955 // The result is always an int type, however operands match the first. 2956 if (LHSValue.getKind() == APValue::Int) 2957 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2958 RHSValue.getInt(), Result); 2959 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2960 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2961 RHSValue.getFloat(), Result); 2962 } 2963 2964 template <typename APTy> 2965 static bool 2966 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2967 const APTy &RHSValue, APInt &Result) { 2968 switch (Opcode) { 2969 default: 2970 llvm_unreachable("unsupported binary operator"); 2971 case BO_EQ: 2972 Result = (LHSValue == RHSValue); 2973 break; 2974 case BO_NE: 2975 Result = (LHSValue != RHSValue); 2976 break; 2977 case BO_LT: 2978 Result = (LHSValue < RHSValue); 2979 break; 2980 case BO_GT: 2981 Result = (LHSValue > RHSValue); 2982 break; 2983 case BO_LE: 2984 Result = (LHSValue <= RHSValue); 2985 break; 2986 case BO_GE: 2987 Result = (LHSValue >= RHSValue); 2988 break; 2989 } 2990 2991 // The boolean operations on these vector types use an instruction that 2992 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 2993 // to -1 to make sure that we produce the correct value. 2994 Result.negate(); 2995 2996 return true; 2997 } 2998 2999 static bool handleCompareOpForVector(const APValue &LHSValue, 3000 BinaryOperatorKind Opcode, 3001 const APValue &RHSValue, APInt &Result) { 3002 // The result is always an int type, however operands match the first. 3003 if (LHSValue.getKind() == APValue::Int) 3004 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 3005 RHSValue.getInt(), Result); 3006 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 3007 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 3008 RHSValue.getFloat(), Result); 3009 } 3010 3011 // Perform binary operations for vector types, in place on the LHS. 3012 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 3013 BinaryOperatorKind Opcode, 3014 APValue &LHSValue, 3015 const APValue &RHSValue) { 3016 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 3017 "Operation not supported on vector types"); 3018 3019 const auto *VT = E->getType()->castAs<VectorType>(); 3020 unsigned NumElements = VT->getNumElements(); 3021 QualType EltTy = VT->getElementType(); 3022 3023 // In the cases (typically C as I've observed) where we aren't evaluating 3024 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 3025 // just give up. 3026 if (!LHSValue.isVector()) { 3027 assert(LHSValue.isLValue() && 3028 "A vector result that isn't a vector OR uncalculated LValue"); 3029 Info.FFDiag(E); 3030 return false; 3031 } 3032 3033 assert(LHSValue.getVectorLength() == NumElements && 3034 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 3035 3036 SmallVector<APValue, 4> ResultElements; 3037 3038 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 3039 APValue LHSElt = LHSValue.getVectorElt(EltNum); 3040 APValue RHSElt = RHSValue.getVectorElt(EltNum); 3041 3042 if (EltTy->isIntegerType()) { 3043 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 3044 EltTy->isUnsignedIntegerType()}; 3045 bool Success = true; 3046 3047 if (BinaryOperator::isLogicalOp(Opcode)) 3048 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3049 else if (BinaryOperator::isComparisonOp(Opcode)) 3050 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3051 else 3052 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 3053 RHSElt.getInt(), EltResult); 3054 3055 if (!Success) { 3056 Info.FFDiag(E); 3057 return false; 3058 } 3059 ResultElements.emplace_back(EltResult); 3060 3061 } else if (EltTy->isFloatingType()) { 3062 assert(LHSElt.getKind() == APValue::Float && 3063 RHSElt.getKind() == APValue::Float && 3064 "Mismatched LHS/RHS/Result Type"); 3065 APFloat LHSFloat = LHSElt.getFloat(); 3066 3067 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3068 RHSElt.getFloat())) { 3069 Info.FFDiag(E); 3070 return false; 3071 } 3072 3073 ResultElements.emplace_back(LHSFloat); 3074 } 3075 } 3076 3077 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3078 return true; 3079 } 3080 3081 /// Cast an lvalue referring to a base subobject to a derived class, by 3082 /// truncating the lvalue's path to the given length. 3083 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3084 const RecordDecl *TruncatedType, 3085 unsigned TruncatedElements) { 3086 SubobjectDesignator &D = Result.Designator; 3087 3088 // Check we actually point to a derived class object. 3089 if (TruncatedElements == D.Entries.size()) 3090 return true; 3091 assert(TruncatedElements >= D.MostDerivedPathLength && 3092 "not casting to a derived class"); 3093 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3094 return false; 3095 3096 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3097 const RecordDecl *RD = TruncatedType; 3098 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3099 if (RD->isInvalidDecl()) return false; 3100 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3101 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3102 if (isVirtualBaseClass(D.Entries[I])) 3103 Result.Offset -= Layout.getVBaseClassOffset(Base); 3104 else 3105 Result.Offset -= Layout.getBaseClassOffset(Base); 3106 RD = Base; 3107 } 3108 D.Entries.resize(TruncatedElements); 3109 return true; 3110 } 3111 3112 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3113 const CXXRecordDecl *Derived, 3114 const CXXRecordDecl *Base, 3115 const ASTRecordLayout *RL = nullptr) { 3116 if (!RL) { 3117 if (Derived->isInvalidDecl()) return false; 3118 RL = &Info.Ctx.getASTRecordLayout(Derived); 3119 } 3120 3121 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3122 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3123 return true; 3124 } 3125 3126 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3127 const CXXRecordDecl *DerivedDecl, 3128 const CXXBaseSpecifier *Base) { 3129 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3130 3131 if (!Base->isVirtual()) 3132 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3133 3134 SubobjectDesignator &D = Obj.Designator; 3135 if (D.Invalid) 3136 return false; 3137 3138 // Extract most-derived object and corresponding type. 3139 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3140 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3141 return false; 3142 3143 // Find the virtual base class. 3144 if (DerivedDecl->isInvalidDecl()) return false; 3145 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3146 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3147 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3148 return true; 3149 } 3150 3151 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3152 QualType Type, LValue &Result) { 3153 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3154 PathE = E->path_end(); 3155 PathI != PathE; ++PathI) { 3156 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3157 *PathI)) 3158 return false; 3159 Type = (*PathI)->getType(); 3160 } 3161 return true; 3162 } 3163 3164 /// Cast an lvalue referring to a derived class to a known base subobject. 3165 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3166 const CXXRecordDecl *DerivedRD, 3167 const CXXRecordDecl *BaseRD) { 3168 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3169 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3170 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3171 llvm_unreachable("Class must be derived from the passed in base class!"); 3172 3173 for (CXXBasePathElement &Elem : Paths.front()) 3174 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3175 return false; 3176 return true; 3177 } 3178 3179 /// Update LVal to refer to the given field, which must be a member of the type 3180 /// currently described by LVal. 3181 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3182 const FieldDecl *FD, 3183 const ASTRecordLayout *RL = nullptr) { 3184 if (!RL) { 3185 if (FD->getParent()->isInvalidDecl()) return false; 3186 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3187 } 3188 3189 unsigned I = FD->getFieldIndex(); 3190 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3191 LVal.addDecl(Info, E, FD); 3192 return true; 3193 } 3194 3195 /// Update LVal to refer to the given indirect field. 3196 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3197 LValue &LVal, 3198 const IndirectFieldDecl *IFD) { 3199 for (const auto *C : IFD->chain()) 3200 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3201 return false; 3202 return true; 3203 } 3204 3205 enum class SizeOfType { 3206 SizeOf, 3207 DataSizeOf, 3208 }; 3209 3210 /// Get the size of the given type in char units. 3211 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, 3212 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) { 3213 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3214 // extension. 3215 if (Type->isVoidType() || Type->isFunctionType()) { 3216 Size = CharUnits::One(); 3217 return true; 3218 } 3219 3220 if (Type->isDependentType()) { 3221 Info.FFDiag(Loc); 3222 return false; 3223 } 3224 3225 if (!Type->isConstantSizeType()) { 3226 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3227 // FIXME: Better diagnostic. 3228 Info.FFDiag(Loc); 3229 return false; 3230 } 3231 3232 if (SOT == SizeOfType::SizeOf) 3233 Size = Info.Ctx.getTypeSizeInChars(Type); 3234 else 3235 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width; 3236 return true; 3237 } 3238 3239 /// Update a pointer value to model pointer arithmetic. 3240 /// \param Info - Information about the ongoing evaluation. 3241 /// \param E - The expression being evaluated, for diagnostic purposes. 3242 /// \param LVal - The pointer value to be updated. 3243 /// \param EltTy - The pointee type represented by LVal. 3244 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3245 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3246 LValue &LVal, QualType EltTy, 3247 APSInt Adjustment) { 3248 CharUnits SizeOfPointee; 3249 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3250 return false; 3251 3252 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3253 return true; 3254 } 3255 3256 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3257 LValue &LVal, QualType EltTy, 3258 int64_t Adjustment) { 3259 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3260 APSInt::get(Adjustment)); 3261 } 3262 3263 /// Update an lvalue to refer to a component of a complex number. 3264 /// \param Info - Information about the ongoing evaluation. 3265 /// \param LVal - The lvalue to be updated. 3266 /// \param EltTy - The complex number's component type. 3267 /// \param Imag - False for the real component, true for the imaginary. 3268 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3269 LValue &LVal, QualType EltTy, 3270 bool Imag) { 3271 if (Imag) { 3272 CharUnits SizeOfComponent; 3273 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3274 return false; 3275 LVal.Offset += SizeOfComponent; 3276 } 3277 LVal.addComplex(Info, E, EltTy, Imag); 3278 return true; 3279 } 3280 3281 /// Try to evaluate the initializer for a variable declaration. 3282 /// 3283 /// \param Info Information about the ongoing evaluation. 3284 /// \param E An expression to be used when printing diagnostics. 3285 /// \param VD The variable whose initializer should be obtained. 3286 /// \param Version The version of the variable within the frame. 3287 /// \param Frame The frame in which the variable was created. Must be null 3288 /// if this variable is not local to the evaluation. 3289 /// \param Result Filled in with a pointer to the value of the variable. 3290 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3291 const VarDecl *VD, CallStackFrame *Frame, 3292 unsigned Version, APValue *&Result) { 3293 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3294 3295 // If this is a local variable, dig out its value. 3296 if (Frame) { 3297 Result = Frame->getTemporary(VD, Version); 3298 if (Result) 3299 return true; 3300 3301 if (!isa<ParmVarDecl>(VD)) { 3302 // Assume variables referenced within a lambda's call operator that were 3303 // not declared within the call operator are captures and during checking 3304 // of a potential constant expression, assume they are unknown constant 3305 // expressions. 3306 assert(isLambdaCallOperator(Frame->Callee) && 3307 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3308 "missing value for local variable"); 3309 if (Info.checkingPotentialConstantExpression()) 3310 return false; 3311 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3312 // still reachable at all? 3313 Info.FFDiag(E->getBeginLoc(), 3314 diag::note_unimplemented_constexpr_lambda_feature_ast) 3315 << "captures not currently allowed"; 3316 return false; 3317 } 3318 } 3319 3320 // If we're currently evaluating the initializer of this declaration, use that 3321 // in-flight value. 3322 if (Info.EvaluatingDecl == Base) { 3323 Result = Info.EvaluatingDeclValue; 3324 return true; 3325 } 3326 3327 if (isa<ParmVarDecl>(VD)) { 3328 // Assume parameters of a potential constant expression are usable in 3329 // constant expressions. 3330 if (!Info.checkingPotentialConstantExpression() || 3331 !Info.CurrentCall->Callee || 3332 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3333 if (Info.getLangOpts().CPlusPlus11) { 3334 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3335 << VD; 3336 NoteLValueLocation(Info, Base); 3337 } else { 3338 Info.FFDiag(E); 3339 } 3340 } 3341 return false; 3342 } 3343 3344 if (E->isValueDependent()) 3345 return false; 3346 3347 // Dig out the initializer, and use the declaration which it's attached to. 3348 // FIXME: We should eventually check whether the variable has a reachable 3349 // initializing declaration. 3350 const Expr *Init = VD->getAnyInitializer(VD); 3351 if (!Init) { 3352 // Don't diagnose during potential constant expression checking; an 3353 // initializer might be added later. 3354 if (!Info.checkingPotentialConstantExpression()) { 3355 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3356 << VD; 3357 NoteLValueLocation(Info, Base); 3358 } 3359 return false; 3360 } 3361 3362 if (Init->isValueDependent()) { 3363 // The DeclRefExpr is not value-dependent, but the variable it refers to 3364 // has a value-dependent initializer. This should only happen in 3365 // constant-folding cases, where the variable is not actually of a suitable 3366 // type for use in a constant expression (otherwise the DeclRefExpr would 3367 // have been value-dependent too), so diagnose that. 3368 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3369 if (!Info.checkingPotentialConstantExpression()) { 3370 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3371 ? diag::note_constexpr_ltor_non_constexpr 3372 : diag::note_constexpr_ltor_non_integral, 1) 3373 << VD << VD->getType(); 3374 NoteLValueLocation(Info, Base); 3375 } 3376 return false; 3377 } 3378 3379 // Check that we can fold the initializer. In C++, we will have already done 3380 // this in the cases where it matters for conformance. 3381 if (!VD->evaluateValue()) { 3382 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3383 NoteLValueLocation(Info, Base); 3384 return false; 3385 } 3386 3387 // Check that the variable is actually usable in constant expressions. For a 3388 // const integral variable or a reference, we might have a non-constant 3389 // initializer that we can nonetheless evaluate the initializer for. Such 3390 // variables are not usable in constant expressions. In C++98, the 3391 // initializer also syntactically needs to be an ICE. 3392 // 3393 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3394 // expressions here; doing so would regress diagnostics for things like 3395 // reading from a volatile constexpr variable. 3396 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3397 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3398 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3399 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3400 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3401 NoteLValueLocation(Info, Base); 3402 } 3403 3404 // Never use the initializer of a weak variable, not even for constant 3405 // folding. We can't be sure that this is the definition that will be used. 3406 if (VD->isWeak()) { 3407 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3408 NoteLValueLocation(Info, Base); 3409 return false; 3410 } 3411 3412 Result = VD->getEvaluatedValue(); 3413 return true; 3414 } 3415 3416 /// Get the base index of the given base class within an APValue representing 3417 /// the given derived class. 3418 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3419 const CXXRecordDecl *Base) { 3420 Base = Base->getCanonicalDecl(); 3421 unsigned Index = 0; 3422 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3423 E = Derived->bases_end(); I != E; ++I, ++Index) { 3424 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3425 return Index; 3426 } 3427 3428 llvm_unreachable("base class missing from derived class's bases list"); 3429 } 3430 3431 /// Extract the value of a character from a string literal. 3432 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3433 uint64_t Index) { 3434 assert(!isa<SourceLocExpr>(Lit) && 3435 "SourceLocExpr should have already been converted to a StringLiteral"); 3436 3437 // FIXME: Support MakeStringConstant 3438 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3439 std::string Str; 3440 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3441 assert(Index <= Str.size() && "Index too large"); 3442 return APSInt::getUnsigned(Str.c_str()[Index]); 3443 } 3444 3445 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3446 Lit = PE->getFunctionName(); 3447 const StringLiteral *S = cast<StringLiteral>(Lit); 3448 const ConstantArrayType *CAT = 3449 Info.Ctx.getAsConstantArrayType(S->getType()); 3450 assert(CAT && "string literal isn't an array"); 3451 QualType CharType = CAT->getElementType(); 3452 assert(CharType->isIntegerType() && "unexpected character type"); 3453 APSInt Value(Info.Ctx.getTypeSize(CharType), 3454 CharType->isUnsignedIntegerType()); 3455 if (Index < S->getLength()) 3456 Value = S->getCodeUnit(Index); 3457 return Value; 3458 } 3459 3460 // Expand a string literal into an array of characters. 3461 // 3462 // FIXME: This is inefficient; we should probably introduce something similar 3463 // to the LLVM ConstantDataArray to make this cheaper. 3464 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3465 APValue &Result, 3466 QualType AllocType = QualType()) { 3467 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3468 AllocType.isNull() ? S->getType() : AllocType); 3469 assert(CAT && "string literal isn't an array"); 3470 QualType CharType = CAT->getElementType(); 3471 assert(CharType->isIntegerType() && "unexpected character type"); 3472 3473 unsigned Elts = CAT->getSize().getZExtValue(); 3474 Result = APValue(APValue::UninitArray(), 3475 std::min(S->getLength(), Elts), Elts); 3476 APSInt Value(Info.Ctx.getTypeSize(CharType), 3477 CharType->isUnsignedIntegerType()); 3478 if (Result.hasArrayFiller()) 3479 Result.getArrayFiller() = APValue(Value); 3480 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3481 Value = S->getCodeUnit(I); 3482 Result.getArrayInitializedElt(I) = APValue(Value); 3483 } 3484 } 3485 3486 // Expand an array so that it has more than Index filled elements. 3487 static void expandArray(APValue &Array, unsigned Index) { 3488 unsigned Size = Array.getArraySize(); 3489 assert(Index < Size); 3490 3491 // Always at least double the number of elements for which we store a value. 3492 unsigned OldElts = Array.getArrayInitializedElts(); 3493 unsigned NewElts = std::max(Index+1, OldElts * 2); 3494 NewElts = std::min(Size, std::max(NewElts, 8u)); 3495 3496 // Copy the data across. 3497 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3498 for (unsigned I = 0; I != OldElts; ++I) 3499 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3500 for (unsigned I = OldElts; I != NewElts; ++I) 3501 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3502 if (NewValue.hasArrayFiller()) 3503 NewValue.getArrayFiller() = Array.getArrayFiller(); 3504 Array.swap(NewValue); 3505 } 3506 3507 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3508 /// conversion. If it's of class type, we may assume that the copy operation 3509 /// is trivial. Note that this is never true for a union type with fields 3510 /// (because the copy always "reads" the active member) and always true for 3511 /// a non-class type. 3512 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3513 static bool isReadByLvalueToRvalueConversion(QualType T) { 3514 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3515 return !RD || isReadByLvalueToRvalueConversion(RD); 3516 } 3517 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3518 // FIXME: A trivial copy of a union copies the object representation, even if 3519 // the union is empty. 3520 if (RD->isUnion()) 3521 return !RD->field_empty(); 3522 if (RD->isEmpty()) 3523 return false; 3524 3525 for (auto *Field : RD->fields()) 3526 if (!Field->isUnnamedBitfield() && 3527 isReadByLvalueToRvalueConversion(Field->getType())) 3528 return true; 3529 3530 for (auto &BaseSpec : RD->bases()) 3531 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3532 return true; 3533 3534 return false; 3535 } 3536 3537 /// Diagnose an attempt to read from any unreadable field within the specified 3538 /// type, which might be a class type. 3539 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3540 QualType T) { 3541 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3542 if (!RD) 3543 return false; 3544 3545 if (!RD->hasMutableFields()) 3546 return false; 3547 3548 for (auto *Field : RD->fields()) { 3549 // If we're actually going to read this field in some way, then it can't 3550 // be mutable. If we're in a union, then assigning to a mutable field 3551 // (even an empty one) can change the active member, so that's not OK. 3552 // FIXME: Add core issue number for the union case. 3553 if (Field->isMutable() && 3554 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3555 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3556 Info.Note(Field->getLocation(), diag::note_declared_at); 3557 return true; 3558 } 3559 3560 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3561 return true; 3562 } 3563 3564 for (auto &BaseSpec : RD->bases()) 3565 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3566 return true; 3567 3568 // All mutable fields were empty, and thus not actually read. 3569 return false; 3570 } 3571 3572 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3573 APValue::LValueBase Base, 3574 bool MutableSubobject = false) { 3575 // A temporary or transient heap allocation we created. 3576 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3577 return true; 3578 3579 switch (Info.IsEvaluatingDecl) { 3580 case EvalInfo::EvaluatingDeclKind::None: 3581 return false; 3582 3583 case EvalInfo::EvaluatingDeclKind::Ctor: 3584 // The variable whose initializer we're evaluating. 3585 if (Info.EvaluatingDecl == Base) 3586 return true; 3587 3588 // A temporary lifetime-extended by the variable whose initializer we're 3589 // evaluating. 3590 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3591 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3592 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3593 return false; 3594 3595 case EvalInfo::EvaluatingDeclKind::Dtor: 3596 // C++2a [expr.const]p6: 3597 // [during constant destruction] the lifetime of a and its non-mutable 3598 // subobjects (but not its mutable subobjects) [are] considered to start 3599 // within e. 3600 if (MutableSubobject || Base != Info.EvaluatingDecl) 3601 return false; 3602 // FIXME: We can meaningfully extend this to cover non-const objects, but 3603 // we will need special handling: we should be able to access only 3604 // subobjects of such objects that are themselves declared const. 3605 QualType T = getType(Base); 3606 return T.isConstQualified() || T->isReferenceType(); 3607 } 3608 3609 llvm_unreachable("unknown evaluating decl kind"); 3610 } 3611 3612 static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, 3613 SourceLocation CallLoc = {}) { 3614 return Info.CheckArraySize( 3615 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc, 3616 CAT->getNumAddressingBits(Info.Ctx), CAT->getSize().getZExtValue(), 3617 /*Diag=*/true); 3618 } 3619 3620 namespace { 3621 /// A handle to a complete object (an object that is not a subobject of 3622 /// another object). 3623 struct CompleteObject { 3624 /// The identity of the object. 3625 APValue::LValueBase Base; 3626 /// The value of the complete object. 3627 APValue *Value; 3628 /// The type of the complete object. 3629 QualType Type; 3630 3631 CompleteObject() : Value(nullptr) {} 3632 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3633 : Base(Base), Value(Value), Type(Type) {} 3634 3635 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3636 // If this isn't a "real" access (eg, if it's just accessing the type 3637 // info), allow it. We assume the type doesn't change dynamically for 3638 // subobjects of constexpr objects (even though we'd hit UB here if it 3639 // did). FIXME: Is this right? 3640 if (!isAnyAccess(AK)) 3641 return true; 3642 3643 // In C++14 onwards, it is permitted to read a mutable member whose 3644 // lifetime began within the evaluation. 3645 // FIXME: Should we also allow this in C++11? 3646 if (!Info.getLangOpts().CPlusPlus14) 3647 return false; 3648 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3649 } 3650 3651 explicit operator bool() const { return !Type.isNull(); } 3652 }; 3653 } // end anonymous namespace 3654 3655 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3656 bool IsMutable = false) { 3657 // C++ [basic.type.qualifier]p1: 3658 // - A const object is an object of type const T or a non-mutable subobject 3659 // of a const object. 3660 if (ObjType.isConstQualified() && !IsMutable) 3661 SubobjType.addConst(); 3662 // - A volatile object is an object of type const T or a subobject of a 3663 // volatile object. 3664 if (ObjType.isVolatileQualified()) 3665 SubobjType.addVolatile(); 3666 return SubobjType; 3667 } 3668 3669 /// Find the designated sub-object of an rvalue. 3670 template<typename SubobjectHandler> 3671 typename SubobjectHandler::result_type 3672 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3673 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3674 if (Sub.Invalid) 3675 // A diagnostic will have already been produced. 3676 return handler.failed(); 3677 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3678 if (Info.getLangOpts().CPlusPlus11) 3679 Info.FFDiag(E, Sub.isOnePastTheEnd() 3680 ? diag::note_constexpr_access_past_end 3681 : diag::note_constexpr_access_unsized_array) 3682 << handler.AccessKind; 3683 else 3684 Info.FFDiag(E); 3685 return handler.failed(); 3686 } 3687 3688 APValue *O = Obj.Value; 3689 QualType ObjType = Obj.Type; 3690 const FieldDecl *LastField = nullptr; 3691 const FieldDecl *VolatileField = nullptr; 3692 3693 // Walk the designator's path to find the subobject. 3694 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3695 // Reading an indeterminate value is undefined, but assigning over one is OK. 3696 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3697 (O->isIndeterminate() && 3698 !isValidIndeterminateAccess(handler.AccessKind))) { 3699 if (!Info.checkingPotentialConstantExpression()) 3700 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3701 << handler.AccessKind << O->isIndeterminate() 3702 << E->getSourceRange(); 3703 return handler.failed(); 3704 } 3705 3706 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3707 // const and volatile semantics are not applied on an object under 3708 // {con,de}struction. 3709 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3710 ObjType->isRecordType() && 3711 Info.isEvaluatingCtorDtor( 3712 Obj.Base, 3713 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) != 3714 ConstructionPhase::None) { 3715 ObjType = Info.Ctx.getCanonicalType(ObjType); 3716 ObjType.removeLocalConst(); 3717 ObjType.removeLocalVolatile(); 3718 } 3719 3720 // If this is our last pass, check that the final object type is OK. 3721 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3722 // Accesses to volatile objects are prohibited. 3723 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3724 if (Info.getLangOpts().CPlusPlus) { 3725 int DiagKind; 3726 SourceLocation Loc; 3727 const NamedDecl *Decl = nullptr; 3728 if (VolatileField) { 3729 DiagKind = 2; 3730 Loc = VolatileField->getLocation(); 3731 Decl = VolatileField; 3732 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3733 DiagKind = 1; 3734 Loc = VD->getLocation(); 3735 Decl = VD; 3736 } else { 3737 DiagKind = 0; 3738 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3739 Loc = E->getExprLoc(); 3740 } 3741 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3742 << handler.AccessKind << DiagKind << Decl; 3743 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3744 } else { 3745 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3746 } 3747 return handler.failed(); 3748 } 3749 3750 // If we are reading an object of class type, there may still be more 3751 // things we need to check: if there are any mutable subobjects, we 3752 // cannot perform this read. (This only happens when performing a trivial 3753 // copy or assignment.) 3754 if (ObjType->isRecordType() && 3755 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3756 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3757 return handler.failed(); 3758 } 3759 3760 if (I == N) { 3761 if (!handler.found(*O, ObjType)) 3762 return false; 3763 3764 // If we modified a bit-field, truncate it to the right width. 3765 if (isModification(handler.AccessKind) && 3766 LastField && LastField->isBitField() && 3767 !truncateBitfieldValue(Info, E, *O, LastField)) 3768 return false; 3769 3770 return true; 3771 } 3772 3773 LastField = nullptr; 3774 if (ObjType->isArrayType()) { 3775 // Next subobject is an array element. 3776 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3777 assert(CAT && "vla in literal type?"); 3778 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3779 if (CAT->getSize().ule(Index)) { 3780 // Note, it should not be possible to form a pointer with a valid 3781 // designator which points more than one past the end of the array. 3782 if (Info.getLangOpts().CPlusPlus11) 3783 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3784 << handler.AccessKind; 3785 else 3786 Info.FFDiag(E); 3787 return handler.failed(); 3788 } 3789 3790 ObjType = CAT->getElementType(); 3791 3792 if (O->getArrayInitializedElts() > Index) 3793 O = &O->getArrayInitializedElt(Index); 3794 else if (!isRead(handler.AccessKind)) { 3795 if (!CheckArraySize(Info, CAT, E->getExprLoc())) 3796 return handler.failed(); 3797 3798 expandArray(*O, Index); 3799 O = &O->getArrayInitializedElt(Index); 3800 } else 3801 O = &O->getArrayFiller(); 3802 } else if (ObjType->isAnyComplexType()) { 3803 // Next subobject is a complex number. 3804 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3805 if (Index > 1) { 3806 if (Info.getLangOpts().CPlusPlus11) 3807 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3808 << handler.AccessKind; 3809 else 3810 Info.FFDiag(E); 3811 return handler.failed(); 3812 } 3813 3814 ObjType = getSubobjectType( 3815 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3816 3817 assert(I == N - 1 && "extracting subobject of scalar?"); 3818 if (O->isComplexInt()) { 3819 return handler.found(Index ? O->getComplexIntImag() 3820 : O->getComplexIntReal(), ObjType); 3821 } else { 3822 assert(O->isComplexFloat()); 3823 return handler.found(Index ? O->getComplexFloatImag() 3824 : O->getComplexFloatReal(), ObjType); 3825 } 3826 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3827 if (Field->isMutable() && 3828 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3829 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3830 << handler.AccessKind << Field; 3831 Info.Note(Field->getLocation(), diag::note_declared_at); 3832 return handler.failed(); 3833 } 3834 3835 // Next subobject is a class, struct or union field. 3836 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3837 if (RD->isUnion()) { 3838 const FieldDecl *UnionField = O->getUnionField(); 3839 if (!UnionField || 3840 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3841 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3842 // Placement new onto an inactive union member makes it active. 3843 O->setUnion(Field, APValue()); 3844 } else { 3845 // FIXME: If O->getUnionValue() is absent, report that there's no 3846 // active union member rather than reporting the prior active union 3847 // member. We'll need to fix nullptr_t to not use APValue() as its 3848 // representation first. 3849 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3850 << handler.AccessKind << Field << !UnionField << UnionField; 3851 return handler.failed(); 3852 } 3853 } 3854 O = &O->getUnionValue(); 3855 } else 3856 O = &O->getStructField(Field->getFieldIndex()); 3857 3858 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3859 LastField = Field; 3860 if (Field->getType().isVolatileQualified()) 3861 VolatileField = Field; 3862 } else { 3863 // Next subobject is a base class. 3864 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3865 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3866 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3867 3868 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3869 } 3870 } 3871 } 3872 3873 namespace { 3874 struct ExtractSubobjectHandler { 3875 EvalInfo &Info; 3876 const Expr *E; 3877 APValue &Result; 3878 const AccessKinds AccessKind; 3879 3880 typedef bool result_type; 3881 bool failed() { return false; } 3882 bool found(APValue &Subobj, QualType SubobjType) { 3883 Result = Subobj; 3884 if (AccessKind == AK_ReadObjectRepresentation) 3885 return true; 3886 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3887 } 3888 bool found(APSInt &Value, QualType SubobjType) { 3889 Result = APValue(Value); 3890 return true; 3891 } 3892 bool found(APFloat &Value, QualType SubobjType) { 3893 Result = APValue(Value); 3894 return true; 3895 } 3896 }; 3897 } // end anonymous namespace 3898 3899 /// Extract the designated sub-object of an rvalue. 3900 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3901 const CompleteObject &Obj, 3902 const SubobjectDesignator &Sub, APValue &Result, 3903 AccessKinds AK = AK_Read) { 3904 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3905 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3906 return findSubobject(Info, E, Obj, Sub, Handler); 3907 } 3908 3909 namespace { 3910 struct ModifySubobjectHandler { 3911 EvalInfo &Info; 3912 APValue &NewVal; 3913 const Expr *E; 3914 3915 typedef bool result_type; 3916 static const AccessKinds AccessKind = AK_Assign; 3917 3918 bool checkConst(QualType QT) { 3919 // Assigning to a const object has undefined behavior. 3920 if (QT.isConstQualified()) { 3921 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3922 return false; 3923 } 3924 return true; 3925 } 3926 3927 bool failed() { return false; } 3928 bool found(APValue &Subobj, QualType SubobjType) { 3929 if (!checkConst(SubobjType)) 3930 return false; 3931 // We've been given ownership of NewVal, so just swap it in. 3932 Subobj.swap(NewVal); 3933 return true; 3934 } 3935 bool found(APSInt &Value, QualType SubobjType) { 3936 if (!checkConst(SubobjType)) 3937 return false; 3938 if (!NewVal.isInt()) { 3939 // Maybe trying to write a cast pointer value into a complex? 3940 Info.FFDiag(E); 3941 return false; 3942 } 3943 Value = NewVal.getInt(); 3944 return true; 3945 } 3946 bool found(APFloat &Value, QualType SubobjType) { 3947 if (!checkConst(SubobjType)) 3948 return false; 3949 Value = NewVal.getFloat(); 3950 return true; 3951 } 3952 }; 3953 } // end anonymous namespace 3954 3955 const AccessKinds ModifySubobjectHandler::AccessKind; 3956 3957 /// Update the designated sub-object of an rvalue to the given value. 3958 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3959 const CompleteObject &Obj, 3960 const SubobjectDesignator &Sub, 3961 APValue &NewVal) { 3962 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3963 return findSubobject(Info, E, Obj, Sub, Handler); 3964 } 3965 3966 /// Find the position where two subobject designators diverge, or equivalently 3967 /// the length of the common initial subsequence. 3968 static unsigned FindDesignatorMismatch(QualType ObjType, 3969 const SubobjectDesignator &A, 3970 const SubobjectDesignator &B, 3971 bool &WasArrayIndex) { 3972 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3973 for (/**/; I != N; ++I) { 3974 if (!ObjType.isNull() && 3975 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3976 // Next subobject is an array element. 3977 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3978 WasArrayIndex = true; 3979 return I; 3980 } 3981 if (ObjType->isAnyComplexType()) 3982 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3983 else 3984 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3985 } else { 3986 if (A.Entries[I].getAsBaseOrMember() != 3987 B.Entries[I].getAsBaseOrMember()) { 3988 WasArrayIndex = false; 3989 return I; 3990 } 3991 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3992 // Next subobject is a field. 3993 ObjType = FD->getType(); 3994 else 3995 // Next subobject is a base class. 3996 ObjType = QualType(); 3997 } 3998 } 3999 WasArrayIndex = false; 4000 return I; 4001 } 4002 4003 /// Determine whether the given subobject designators refer to elements of the 4004 /// same array object. 4005 static bool AreElementsOfSameArray(QualType ObjType, 4006 const SubobjectDesignator &A, 4007 const SubobjectDesignator &B) { 4008 if (A.Entries.size() != B.Entries.size()) 4009 return false; 4010 4011 bool IsArray = A.MostDerivedIsArrayElement; 4012 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 4013 // A is a subobject of the array element. 4014 return false; 4015 4016 // If A (and B) designates an array element, the last entry will be the array 4017 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 4018 // of length 1' case, and the entire path must match. 4019 bool WasArrayIndex; 4020 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 4021 return CommonLength >= A.Entries.size() - IsArray; 4022 } 4023 4024 /// Find the complete object to which an LValue refers. 4025 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 4026 AccessKinds AK, const LValue &LVal, 4027 QualType LValType) { 4028 if (LVal.InvalidBase) { 4029 Info.FFDiag(E); 4030 return CompleteObject(); 4031 } 4032 4033 if (!LVal.Base) { 4034 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 4035 return CompleteObject(); 4036 } 4037 4038 CallStackFrame *Frame = nullptr; 4039 unsigned Depth = 0; 4040 if (LVal.getLValueCallIndex()) { 4041 std::tie(Frame, Depth) = 4042 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 4043 if (!Frame) { 4044 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 4045 << AK << LVal.Base.is<const ValueDecl*>(); 4046 NoteLValueLocation(Info, LVal.Base); 4047 return CompleteObject(); 4048 } 4049 } 4050 4051 bool IsAccess = isAnyAccess(AK); 4052 4053 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 4054 // is not a constant expression (even if the object is non-volatile). We also 4055 // apply this rule to C++98, in order to conform to the expected 'volatile' 4056 // semantics. 4057 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 4058 if (Info.getLangOpts().CPlusPlus) 4059 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 4060 << AK << LValType; 4061 else 4062 Info.FFDiag(E); 4063 return CompleteObject(); 4064 } 4065 4066 // Compute value storage location and type of base object. 4067 APValue *BaseVal = nullptr; 4068 QualType BaseType = getType(LVal.Base); 4069 4070 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 4071 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4072 // This is the object whose initializer we're evaluating, so its lifetime 4073 // started in the current evaluation. 4074 BaseVal = Info.EvaluatingDeclValue; 4075 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4076 // Allow reading from a GUID declaration. 4077 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4078 if (isModification(AK)) { 4079 // All the remaining cases do not permit modification of the object. 4080 Info.FFDiag(E, diag::note_constexpr_modify_global); 4081 return CompleteObject(); 4082 } 4083 APValue &V = GD->getAsAPValue(); 4084 if (V.isAbsent()) { 4085 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4086 << GD->getType(); 4087 return CompleteObject(); 4088 } 4089 return CompleteObject(LVal.Base, &V, GD->getType()); 4090 } 4091 4092 // Allow reading the APValue from an UnnamedGlobalConstantDecl. 4093 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) { 4094 if (isModification(AK)) { 4095 Info.FFDiag(E, diag::note_constexpr_modify_global); 4096 return CompleteObject(); 4097 } 4098 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()), 4099 GCD->getType()); 4100 } 4101 4102 // Allow reading from template parameter objects. 4103 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4104 if (isModification(AK)) { 4105 Info.FFDiag(E, diag::note_constexpr_modify_global); 4106 return CompleteObject(); 4107 } 4108 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4109 TPO->getType()); 4110 } 4111 4112 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4113 // In C++11, constexpr, non-volatile variables initialized with constant 4114 // expressions are constant expressions too. Inside constexpr functions, 4115 // parameters are constant expressions even if they're non-const. 4116 // In C++1y, objects local to a constant expression (those with a Frame) are 4117 // both readable and writable inside constant expressions. 4118 // In C, such things can also be folded, although they are not ICEs. 4119 const VarDecl *VD = dyn_cast<VarDecl>(D); 4120 if (VD) { 4121 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4122 VD = VDef; 4123 } 4124 if (!VD || VD->isInvalidDecl()) { 4125 Info.FFDiag(E); 4126 return CompleteObject(); 4127 } 4128 4129 bool IsConstant = BaseType.isConstant(Info.Ctx); 4130 4131 // Unless we're looking at a local variable or argument in a constexpr call, 4132 // the variable we're reading must be const. 4133 if (!Frame) { 4134 if (IsAccess && isa<ParmVarDecl>(VD)) { 4135 // Access of a parameter that's not associated with a frame isn't going 4136 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4137 // suitable diagnostic. 4138 } else if (Info.getLangOpts().CPlusPlus14 && 4139 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4140 // OK, we can read and modify an object if we're in the process of 4141 // evaluating its initializer, because its lifetime began in this 4142 // evaluation. 4143 } else if (isModification(AK)) { 4144 // All the remaining cases do not permit modification of the object. 4145 Info.FFDiag(E, diag::note_constexpr_modify_global); 4146 return CompleteObject(); 4147 } else if (VD->isConstexpr()) { 4148 // OK, we can read this variable. 4149 } else if (BaseType->isIntegralOrEnumerationType()) { 4150 if (!IsConstant) { 4151 if (!IsAccess) 4152 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4153 if (Info.getLangOpts().CPlusPlus) { 4154 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4155 Info.Note(VD->getLocation(), diag::note_declared_at); 4156 } else { 4157 Info.FFDiag(E); 4158 } 4159 return CompleteObject(); 4160 } 4161 } else if (!IsAccess) { 4162 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4163 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4164 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4165 // This variable might end up being constexpr. Don't diagnose it yet. 4166 } else if (IsConstant) { 4167 // Keep evaluating to see what we can do. In particular, we support 4168 // folding of const floating-point types, in order to make static const 4169 // data members of such types (supported as an extension) more useful. 4170 if (Info.getLangOpts().CPlusPlus) { 4171 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4172 ? diag::note_constexpr_ltor_non_constexpr 4173 : diag::note_constexpr_ltor_non_integral, 1) 4174 << VD << BaseType; 4175 Info.Note(VD->getLocation(), diag::note_declared_at); 4176 } else { 4177 Info.CCEDiag(E); 4178 } 4179 } else { 4180 // Never allow reading a non-const value. 4181 if (Info.getLangOpts().CPlusPlus) { 4182 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4183 ? diag::note_constexpr_ltor_non_constexpr 4184 : diag::note_constexpr_ltor_non_integral, 1) 4185 << VD << BaseType; 4186 Info.Note(VD->getLocation(), diag::note_declared_at); 4187 } else { 4188 Info.FFDiag(E); 4189 } 4190 return CompleteObject(); 4191 } 4192 } 4193 4194 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4195 return CompleteObject(); 4196 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4197 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 4198 if (!Alloc) { 4199 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4200 return CompleteObject(); 4201 } 4202 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4203 LVal.Base.getDynamicAllocType()); 4204 } else { 4205 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4206 4207 if (!Frame) { 4208 if (const MaterializeTemporaryExpr *MTE = 4209 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4210 assert(MTE->getStorageDuration() == SD_Static && 4211 "should have a frame for a non-global materialized temporary"); 4212 4213 // C++20 [expr.const]p4: [DR2126] 4214 // An object or reference is usable in constant expressions if it is 4215 // - a temporary object of non-volatile const-qualified literal type 4216 // whose lifetime is extended to that of a variable that is usable 4217 // in constant expressions 4218 // 4219 // C++20 [expr.const]p5: 4220 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4221 // - a non-volatile glvalue that refers to an object that is usable 4222 // in constant expressions, or 4223 // - a non-volatile glvalue of literal type that refers to a 4224 // non-volatile object whose lifetime began within the evaluation 4225 // of E; 4226 // 4227 // C++11 misses the 'began within the evaluation of e' check and 4228 // instead allows all temporaries, including things like: 4229 // int &&r = 1; 4230 // int x = ++r; 4231 // constexpr int k = r; 4232 // Therefore we use the C++14-onwards rules in C++11 too. 4233 // 4234 // Note that temporaries whose lifetimes began while evaluating a 4235 // variable's constructor are not usable while evaluating the 4236 // corresponding destructor, not even if they're of const-qualified 4237 // types. 4238 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4239 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4240 if (!IsAccess) 4241 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4242 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4243 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4244 return CompleteObject(); 4245 } 4246 4247 BaseVal = MTE->getOrCreateValue(false); 4248 assert(BaseVal && "got reference to unevaluated temporary"); 4249 } else { 4250 if (!IsAccess) 4251 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4252 APValue Val; 4253 LVal.moveInto(Val); 4254 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4255 << AK 4256 << Val.getAsString(Info.Ctx, 4257 Info.Ctx.getLValueReferenceType(LValType)); 4258 NoteLValueLocation(Info, LVal.Base); 4259 return CompleteObject(); 4260 } 4261 } else { 4262 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4263 assert(BaseVal && "missing value for temporary"); 4264 } 4265 } 4266 4267 // In C++14, we can't safely access any mutable state when we might be 4268 // evaluating after an unmodeled side effect. Parameters are modeled as state 4269 // in the caller, but aren't visible once the call returns, so they can be 4270 // modified in a speculatively-evaluated call. 4271 // 4272 // FIXME: Not all local state is mutable. Allow local constant subobjects 4273 // to be read here (but take care with 'mutable' fields). 4274 unsigned VisibleDepth = Depth; 4275 if (llvm::isa_and_nonnull<ParmVarDecl>( 4276 LVal.Base.dyn_cast<const ValueDecl *>())) 4277 ++VisibleDepth; 4278 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4279 Info.EvalStatus.HasSideEffects) || 4280 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4281 return CompleteObject(); 4282 4283 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4284 } 4285 4286 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4287 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4288 /// glvalue referred to by an entity of reference type. 4289 /// 4290 /// \param Info - Information about the ongoing evaluation. 4291 /// \param Conv - The expression for which we are performing the conversion. 4292 /// Used for diagnostics. 4293 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4294 /// case of a non-class type). 4295 /// \param LVal - The glvalue on which we are attempting to perform this action. 4296 /// \param RVal - The produced value will be placed here. 4297 /// \param WantObjectRepresentation - If true, we're looking for the object 4298 /// representation rather than the value, and in particular, 4299 /// there is no requirement that the result be fully initialized. 4300 static bool 4301 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4302 const LValue &LVal, APValue &RVal, 4303 bool WantObjectRepresentation = false) { 4304 if (LVal.Designator.Invalid) 4305 return false; 4306 4307 // Check for special cases where there is no existing APValue to look at. 4308 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4309 4310 AccessKinds AK = 4311 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4312 4313 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4314 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4315 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4316 // initializer until now for such expressions. Such an expression can't be 4317 // an ICE in C, so this only matters for fold. 4318 if (Type.isVolatileQualified()) { 4319 Info.FFDiag(Conv); 4320 return false; 4321 } 4322 4323 APValue Lit; 4324 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4325 return false; 4326 4327 // According to GCC info page: 4328 // 4329 // 6.28 Compound Literals 4330 // 4331 // As an optimization, G++ sometimes gives array compound literals longer 4332 // lifetimes: when the array either appears outside a function or has a 4333 // const-qualified type. If foo and its initializer had elements of type 4334 // char *const rather than char *, or if foo were a global variable, the 4335 // array would have static storage duration. But it is probably safest 4336 // just to avoid the use of array compound literals in C++ code. 4337 // 4338 // Obey that rule by checking constness for converted array types. 4339 4340 QualType CLETy = CLE->getType(); 4341 if (CLETy->isArrayType() && !Type->isArrayType()) { 4342 if (!CLETy.isConstant(Info.Ctx)) { 4343 Info.FFDiag(Conv); 4344 Info.Note(CLE->getExprLoc(), diag::note_declared_at); 4345 return false; 4346 } 4347 } 4348 4349 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4350 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4351 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4352 // Special-case character extraction so we don't have to construct an 4353 // APValue for the whole string. 4354 assert(LVal.Designator.Entries.size() <= 1 && 4355 "Can only read characters from string literals"); 4356 if (LVal.Designator.Entries.empty()) { 4357 // Fail for now for LValue to RValue conversion of an array. 4358 // (This shouldn't show up in C/C++, but it could be triggered by a 4359 // weird EvaluateAsRValue call from a tool.) 4360 Info.FFDiag(Conv); 4361 return false; 4362 } 4363 if (LVal.Designator.isOnePastTheEnd()) { 4364 if (Info.getLangOpts().CPlusPlus11) 4365 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4366 else 4367 Info.FFDiag(Conv); 4368 return false; 4369 } 4370 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4371 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4372 return true; 4373 } 4374 } 4375 4376 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4377 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4378 } 4379 4380 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4381 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4382 QualType LValType, APValue &Val) { 4383 if (LVal.Designator.Invalid) 4384 return false; 4385 4386 if (!Info.getLangOpts().CPlusPlus14) { 4387 Info.FFDiag(E); 4388 return false; 4389 } 4390 4391 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4392 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4393 } 4394 4395 namespace { 4396 struct CompoundAssignSubobjectHandler { 4397 EvalInfo &Info; 4398 const CompoundAssignOperator *E; 4399 QualType PromotedLHSType; 4400 BinaryOperatorKind Opcode; 4401 const APValue &RHS; 4402 4403 static const AccessKinds AccessKind = AK_Assign; 4404 4405 typedef bool result_type; 4406 4407 bool checkConst(QualType QT) { 4408 // Assigning to a const object has undefined behavior. 4409 if (QT.isConstQualified()) { 4410 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4411 return false; 4412 } 4413 return true; 4414 } 4415 4416 bool failed() { return false; } 4417 bool found(APValue &Subobj, QualType SubobjType) { 4418 switch (Subobj.getKind()) { 4419 case APValue::Int: 4420 return found(Subobj.getInt(), SubobjType); 4421 case APValue::Float: 4422 return found(Subobj.getFloat(), SubobjType); 4423 case APValue::ComplexInt: 4424 case APValue::ComplexFloat: 4425 // FIXME: Implement complex compound assignment. 4426 Info.FFDiag(E); 4427 return false; 4428 case APValue::LValue: 4429 return foundPointer(Subobj, SubobjType); 4430 case APValue::Vector: 4431 return foundVector(Subobj, SubobjType); 4432 case APValue::Indeterminate: 4433 Info.FFDiag(E, diag::note_constexpr_access_uninit) 4434 << /*read of=*/0 << /*uninitialized object=*/1 4435 << E->getLHS()->getSourceRange(); 4436 return false; 4437 default: 4438 // FIXME: can this happen? 4439 Info.FFDiag(E); 4440 return false; 4441 } 4442 } 4443 4444 bool foundVector(APValue &Value, QualType SubobjType) { 4445 if (!checkConst(SubobjType)) 4446 return false; 4447 4448 if (!SubobjType->isVectorType()) { 4449 Info.FFDiag(E); 4450 return false; 4451 } 4452 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4453 } 4454 4455 bool found(APSInt &Value, QualType SubobjType) { 4456 if (!checkConst(SubobjType)) 4457 return false; 4458 4459 if (!SubobjType->isIntegerType()) { 4460 // We don't support compound assignment on integer-cast-to-pointer 4461 // values. 4462 Info.FFDiag(E); 4463 return false; 4464 } 4465 4466 if (RHS.isInt()) { 4467 APSInt LHS = 4468 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4469 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4470 return false; 4471 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4472 return true; 4473 } else if (RHS.isFloat()) { 4474 const FPOptions FPO = E->getFPFeaturesInEffect( 4475 Info.Ctx.getLangOpts()); 4476 APFloat FValue(0.0); 4477 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4478 PromotedLHSType, FValue) && 4479 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4480 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4481 Value); 4482 } 4483 4484 Info.FFDiag(E); 4485 return false; 4486 } 4487 bool found(APFloat &Value, QualType SubobjType) { 4488 return checkConst(SubobjType) && 4489 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4490 Value) && 4491 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4492 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4493 } 4494 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4495 if (!checkConst(SubobjType)) 4496 return false; 4497 4498 QualType PointeeType; 4499 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4500 PointeeType = PT->getPointeeType(); 4501 4502 if (PointeeType.isNull() || !RHS.isInt() || 4503 (Opcode != BO_Add && Opcode != BO_Sub)) { 4504 Info.FFDiag(E); 4505 return false; 4506 } 4507 4508 APSInt Offset = RHS.getInt(); 4509 if (Opcode == BO_Sub) 4510 negateAsSigned(Offset); 4511 4512 LValue LVal; 4513 LVal.setFrom(Info.Ctx, Subobj); 4514 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4515 return false; 4516 LVal.moveInto(Subobj); 4517 return true; 4518 } 4519 }; 4520 } // end anonymous namespace 4521 4522 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4523 4524 /// Perform a compound assignment of LVal <op>= RVal. 4525 static bool handleCompoundAssignment(EvalInfo &Info, 4526 const CompoundAssignOperator *E, 4527 const LValue &LVal, QualType LValType, 4528 QualType PromotedLValType, 4529 BinaryOperatorKind Opcode, 4530 const APValue &RVal) { 4531 if (LVal.Designator.Invalid) 4532 return false; 4533 4534 if (!Info.getLangOpts().CPlusPlus14) { 4535 Info.FFDiag(E); 4536 return false; 4537 } 4538 4539 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4540 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4541 RVal }; 4542 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4543 } 4544 4545 namespace { 4546 struct IncDecSubobjectHandler { 4547 EvalInfo &Info; 4548 const UnaryOperator *E; 4549 AccessKinds AccessKind; 4550 APValue *Old; 4551 4552 typedef bool result_type; 4553 4554 bool checkConst(QualType QT) { 4555 // Assigning to a const object has undefined behavior. 4556 if (QT.isConstQualified()) { 4557 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4558 return false; 4559 } 4560 return true; 4561 } 4562 4563 bool failed() { return false; } 4564 bool found(APValue &Subobj, QualType SubobjType) { 4565 // Stash the old value. Also clear Old, so we don't clobber it later 4566 // if we're post-incrementing a complex. 4567 if (Old) { 4568 *Old = Subobj; 4569 Old = nullptr; 4570 } 4571 4572 switch (Subobj.getKind()) { 4573 case APValue::Int: 4574 return found(Subobj.getInt(), SubobjType); 4575 case APValue::Float: 4576 return found(Subobj.getFloat(), SubobjType); 4577 case APValue::ComplexInt: 4578 return found(Subobj.getComplexIntReal(), 4579 SubobjType->castAs<ComplexType>()->getElementType() 4580 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4581 case APValue::ComplexFloat: 4582 return found(Subobj.getComplexFloatReal(), 4583 SubobjType->castAs<ComplexType>()->getElementType() 4584 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4585 case APValue::LValue: 4586 return foundPointer(Subobj, SubobjType); 4587 default: 4588 // FIXME: can this happen? 4589 Info.FFDiag(E); 4590 return false; 4591 } 4592 } 4593 bool found(APSInt &Value, QualType SubobjType) { 4594 if (!checkConst(SubobjType)) 4595 return false; 4596 4597 if (!SubobjType->isIntegerType()) { 4598 // We don't support increment / decrement on integer-cast-to-pointer 4599 // values. 4600 Info.FFDiag(E); 4601 return false; 4602 } 4603 4604 if (Old) *Old = APValue(Value); 4605 4606 // bool arithmetic promotes to int, and the conversion back to bool 4607 // doesn't reduce mod 2^n, so special-case it. 4608 if (SubobjType->isBooleanType()) { 4609 if (AccessKind == AK_Increment) 4610 Value = 1; 4611 else 4612 Value = !Value; 4613 return true; 4614 } 4615 4616 bool WasNegative = Value.isNegative(); 4617 if (AccessKind == AK_Increment) { 4618 ++Value; 4619 4620 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4621 APSInt ActualValue(Value, /*IsUnsigned*/true); 4622 return HandleOverflow(Info, E, ActualValue, SubobjType); 4623 } 4624 } else { 4625 --Value; 4626 4627 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4628 unsigned BitWidth = Value.getBitWidth(); 4629 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4630 ActualValue.setBit(BitWidth); 4631 return HandleOverflow(Info, E, ActualValue, SubobjType); 4632 } 4633 } 4634 return true; 4635 } 4636 bool found(APFloat &Value, QualType SubobjType) { 4637 if (!checkConst(SubobjType)) 4638 return false; 4639 4640 if (Old) *Old = APValue(Value); 4641 4642 APFloat One(Value.getSemantics(), 1); 4643 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 4644 APFloat::opStatus St; 4645 if (AccessKind == AK_Increment) 4646 St = Value.add(One, RM); 4647 else 4648 St = Value.subtract(One, RM); 4649 return checkFloatingPointResult(Info, E, St); 4650 } 4651 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4652 if (!checkConst(SubobjType)) 4653 return false; 4654 4655 QualType PointeeType; 4656 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4657 PointeeType = PT->getPointeeType(); 4658 else { 4659 Info.FFDiag(E); 4660 return false; 4661 } 4662 4663 LValue LVal; 4664 LVal.setFrom(Info.Ctx, Subobj); 4665 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4666 AccessKind == AK_Increment ? 1 : -1)) 4667 return false; 4668 LVal.moveInto(Subobj); 4669 return true; 4670 } 4671 }; 4672 } // end anonymous namespace 4673 4674 /// Perform an increment or decrement on LVal. 4675 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4676 QualType LValType, bool IsIncrement, APValue *Old) { 4677 if (LVal.Designator.Invalid) 4678 return false; 4679 4680 if (!Info.getLangOpts().CPlusPlus14) { 4681 Info.FFDiag(E); 4682 return false; 4683 } 4684 4685 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4686 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4687 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4688 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4689 } 4690 4691 /// Build an lvalue for the object argument of a member function call. 4692 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4693 LValue &This) { 4694 if (Object->getType()->isPointerType() && Object->isPRValue()) 4695 return EvaluatePointer(Object, This, Info); 4696 4697 if (Object->isGLValue()) 4698 return EvaluateLValue(Object, This, Info); 4699 4700 if (Object->getType()->isLiteralType(Info.Ctx)) 4701 return EvaluateTemporary(Object, This, Info); 4702 4703 if (Object->getType()->isRecordType() && Object->isPRValue()) 4704 return EvaluateTemporary(Object, This, Info); 4705 4706 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4707 return false; 4708 } 4709 4710 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4711 /// lvalue referring to the result. 4712 /// 4713 /// \param Info - Information about the ongoing evaluation. 4714 /// \param LV - An lvalue referring to the base of the member pointer. 4715 /// \param RHS - The member pointer expression. 4716 /// \param IncludeMember - Specifies whether the member itself is included in 4717 /// the resulting LValue subobject designator. This is not possible when 4718 /// creating a bound member function. 4719 /// \return The field or method declaration to which the member pointer refers, 4720 /// or 0 if evaluation fails. 4721 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4722 QualType LVType, 4723 LValue &LV, 4724 const Expr *RHS, 4725 bool IncludeMember = true) { 4726 MemberPtr MemPtr; 4727 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4728 return nullptr; 4729 4730 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4731 // member value, the behavior is undefined. 4732 if (!MemPtr.getDecl()) { 4733 // FIXME: Specific diagnostic. 4734 Info.FFDiag(RHS); 4735 return nullptr; 4736 } 4737 4738 if (MemPtr.isDerivedMember()) { 4739 // This is a member of some derived class. Truncate LV appropriately. 4740 // The end of the derived-to-base path for the base object must match the 4741 // derived-to-base path for the member pointer. 4742 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4743 LV.Designator.Entries.size()) { 4744 Info.FFDiag(RHS); 4745 return nullptr; 4746 } 4747 unsigned PathLengthToMember = 4748 LV.Designator.Entries.size() - MemPtr.Path.size(); 4749 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4750 const CXXRecordDecl *LVDecl = getAsBaseClass( 4751 LV.Designator.Entries[PathLengthToMember + I]); 4752 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4753 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4754 Info.FFDiag(RHS); 4755 return nullptr; 4756 } 4757 } 4758 4759 // Truncate the lvalue to the appropriate derived class. 4760 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4761 PathLengthToMember)) 4762 return nullptr; 4763 } else if (!MemPtr.Path.empty()) { 4764 // Extend the LValue path with the member pointer's path. 4765 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4766 MemPtr.Path.size() + IncludeMember); 4767 4768 // Walk down to the appropriate base class. 4769 if (const PointerType *PT = LVType->getAs<PointerType>()) 4770 LVType = PT->getPointeeType(); 4771 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4772 assert(RD && "member pointer access on non-class-type expression"); 4773 // The first class in the path is that of the lvalue. 4774 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4775 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4776 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4777 return nullptr; 4778 RD = Base; 4779 } 4780 // Finally cast to the class containing the member. 4781 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4782 MemPtr.getContainingRecord())) 4783 return nullptr; 4784 } 4785 4786 // Add the member. Note that we cannot build bound member functions here. 4787 if (IncludeMember) { 4788 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4789 if (!HandleLValueMember(Info, RHS, LV, FD)) 4790 return nullptr; 4791 } else if (const IndirectFieldDecl *IFD = 4792 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4793 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4794 return nullptr; 4795 } else { 4796 llvm_unreachable("can't construct reference to bound member function"); 4797 } 4798 } 4799 4800 return MemPtr.getDecl(); 4801 } 4802 4803 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4804 const BinaryOperator *BO, 4805 LValue &LV, 4806 bool IncludeMember = true) { 4807 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4808 4809 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4810 if (Info.noteFailure()) { 4811 MemberPtr MemPtr; 4812 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4813 } 4814 return nullptr; 4815 } 4816 4817 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4818 BO->getRHS(), IncludeMember); 4819 } 4820 4821 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4822 /// the provided lvalue, which currently refers to the base object. 4823 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4824 LValue &Result) { 4825 SubobjectDesignator &D = Result.Designator; 4826 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4827 return false; 4828 4829 QualType TargetQT = E->getType(); 4830 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4831 TargetQT = PT->getPointeeType(); 4832 4833 // Check this cast lands within the final derived-to-base subobject path. 4834 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4835 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4836 << D.MostDerivedType << TargetQT; 4837 return false; 4838 } 4839 4840 // Check the type of the final cast. We don't need to check the path, 4841 // since a cast can only be formed if the path is unique. 4842 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4843 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4844 const CXXRecordDecl *FinalType; 4845 if (NewEntriesSize == D.MostDerivedPathLength) 4846 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4847 else 4848 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4849 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4850 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4851 << D.MostDerivedType << TargetQT; 4852 return false; 4853 } 4854 4855 // Truncate the lvalue to the appropriate derived class. 4856 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4857 } 4858 4859 /// Get the value to use for a default-initialized object of type T. 4860 /// Return false if it encounters something invalid. 4861 static bool handleDefaultInitValue(QualType T, APValue &Result) { 4862 bool Success = true; 4863 4864 // If there is already a value present don't overwrite it. 4865 if (!Result.isAbsent()) 4866 return true; 4867 4868 if (auto *RD = T->getAsCXXRecordDecl()) { 4869 if (RD->isInvalidDecl()) { 4870 Result = APValue(); 4871 return false; 4872 } 4873 if (RD->isUnion()) { 4874 Result = APValue((const FieldDecl *)nullptr); 4875 return true; 4876 } 4877 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4878 std::distance(RD->field_begin(), RD->field_end())); 4879 4880 unsigned Index = 0; 4881 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4882 End = RD->bases_end(); 4883 I != End; ++I, ++Index) 4884 Success &= 4885 handleDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4886 4887 for (const auto *I : RD->fields()) { 4888 if (I->isUnnamedBitfield()) 4889 continue; 4890 Success &= handleDefaultInitValue( 4891 I->getType(), Result.getStructField(I->getFieldIndex())); 4892 } 4893 return Success; 4894 } 4895 4896 if (auto *AT = 4897 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4898 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4899 if (Result.hasArrayFiller()) 4900 Success &= 4901 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4902 4903 return Success; 4904 } 4905 4906 Result = APValue::IndeterminateValue(); 4907 return true; 4908 } 4909 4910 namespace { 4911 enum EvalStmtResult { 4912 /// Evaluation failed. 4913 ESR_Failed, 4914 /// Hit a 'return' statement. 4915 ESR_Returned, 4916 /// Evaluation succeeded. 4917 ESR_Succeeded, 4918 /// Hit a 'continue' statement. 4919 ESR_Continue, 4920 /// Hit a 'break' statement. 4921 ESR_Break, 4922 /// Still scanning for 'case' or 'default' statement. 4923 ESR_CaseNotFound 4924 }; 4925 } 4926 4927 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4928 if (VD->isInvalidDecl()) 4929 return false; 4930 // We don't need to evaluate the initializer for a static local. 4931 if (!VD->hasLocalStorage()) 4932 return true; 4933 4934 LValue Result; 4935 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4936 ScopeKind::Block, Result); 4937 4938 const Expr *InitE = VD->getInit(); 4939 if (!InitE) { 4940 if (VD->getType()->isDependentType()) 4941 return Info.noteSideEffect(); 4942 return handleDefaultInitValue(VD->getType(), Val); 4943 } 4944 if (InitE->isValueDependent()) 4945 return false; 4946 4947 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4948 // Wipe out any partially-computed value, to allow tracking that this 4949 // evaluation failed. 4950 Val = APValue(); 4951 return false; 4952 } 4953 4954 return true; 4955 } 4956 4957 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4958 bool OK = true; 4959 4960 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4961 OK &= EvaluateVarDecl(Info, VD); 4962 4963 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4964 for (auto *BD : DD->bindings()) 4965 if (auto *VD = BD->getHoldingVar()) 4966 OK &= EvaluateDecl(Info, VD); 4967 4968 return OK; 4969 } 4970 4971 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4972 assert(E->isValueDependent()); 4973 if (Info.noteSideEffect()) 4974 return true; 4975 assert(E->containsErrors() && "valid value-dependent expression should never " 4976 "reach invalid code path."); 4977 return false; 4978 } 4979 4980 /// Evaluate a condition (either a variable declaration or an expression). 4981 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4982 const Expr *Cond, bool &Result) { 4983 if (Cond->isValueDependent()) 4984 return false; 4985 FullExpressionRAII Scope(Info); 4986 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4987 return false; 4988 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4989 return false; 4990 return Scope.destroy(); 4991 } 4992 4993 namespace { 4994 /// A location where the result (returned value) of evaluating a 4995 /// statement should be stored. 4996 struct StmtResult { 4997 /// The APValue that should be filled in with the returned value. 4998 APValue &Value; 4999 /// The location containing the result, if any (used to support RVO). 5000 const LValue *Slot; 5001 }; 5002 5003 struct TempVersionRAII { 5004 CallStackFrame &Frame; 5005 5006 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 5007 Frame.pushTempVersion(); 5008 } 5009 5010 ~TempVersionRAII() { 5011 Frame.popTempVersion(); 5012 } 5013 }; 5014 5015 } 5016 5017 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 5018 const Stmt *S, 5019 const SwitchCase *SC = nullptr); 5020 5021 /// Evaluate the body of a loop, and translate the result as appropriate. 5022 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 5023 const Stmt *Body, 5024 const SwitchCase *Case = nullptr) { 5025 BlockScopeRAII Scope(Info); 5026 5027 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 5028 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 5029 ESR = ESR_Failed; 5030 5031 switch (ESR) { 5032 case ESR_Break: 5033 return ESR_Succeeded; 5034 case ESR_Succeeded: 5035 case ESR_Continue: 5036 return ESR_Continue; 5037 case ESR_Failed: 5038 case ESR_Returned: 5039 case ESR_CaseNotFound: 5040 return ESR; 5041 } 5042 llvm_unreachable("Invalid EvalStmtResult!"); 5043 } 5044 5045 /// Evaluate a switch statement. 5046 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 5047 const SwitchStmt *SS) { 5048 BlockScopeRAII Scope(Info); 5049 5050 // Evaluate the switch condition. 5051 APSInt Value; 5052 { 5053 if (const Stmt *Init = SS->getInit()) { 5054 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5055 if (ESR != ESR_Succeeded) { 5056 if (ESR != ESR_Failed && !Scope.destroy()) 5057 ESR = ESR_Failed; 5058 return ESR; 5059 } 5060 } 5061 5062 FullExpressionRAII CondScope(Info); 5063 if (SS->getConditionVariable() && 5064 !EvaluateDecl(Info, SS->getConditionVariable())) 5065 return ESR_Failed; 5066 if (SS->getCond()->isValueDependent()) { 5067 // We don't know what the value is, and which branch should jump to. 5068 EvaluateDependentExpr(SS->getCond(), Info); 5069 return ESR_Failed; 5070 } 5071 if (!EvaluateInteger(SS->getCond(), Value, Info)) 5072 return ESR_Failed; 5073 5074 if (!CondScope.destroy()) 5075 return ESR_Failed; 5076 } 5077 5078 // Find the switch case corresponding to the value of the condition. 5079 // FIXME: Cache this lookup. 5080 const SwitchCase *Found = nullptr; 5081 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 5082 SC = SC->getNextSwitchCase()) { 5083 if (isa<DefaultStmt>(SC)) { 5084 Found = SC; 5085 continue; 5086 } 5087 5088 const CaseStmt *CS = cast<CaseStmt>(SC); 5089 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 5090 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 5091 : LHS; 5092 if (LHS <= Value && Value <= RHS) { 5093 Found = SC; 5094 break; 5095 } 5096 } 5097 5098 if (!Found) 5099 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5100 5101 // Search the switch body for the switch case and evaluate it from there. 5102 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 5103 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 5104 return ESR_Failed; 5105 5106 switch (ESR) { 5107 case ESR_Break: 5108 return ESR_Succeeded; 5109 case ESR_Succeeded: 5110 case ESR_Continue: 5111 case ESR_Failed: 5112 case ESR_Returned: 5113 return ESR; 5114 case ESR_CaseNotFound: 5115 // This can only happen if the switch case is nested within a statement 5116 // expression. We have no intention of supporting that. 5117 Info.FFDiag(Found->getBeginLoc(), 5118 diag::note_constexpr_stmt_expr_unsupported); 5119 return ESR_Failed; 5120 } 5121 llvm_unreachable("Invalid EvalStmtResult!"); 5122 } 5123 5124 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) { 5125 // An expression E is a core constant expression unless the evaluation of E 5126 // would evaluate one of the following: [C++23] - a control flow that passes 5127 // through a declaration of a variable with static or thread storage duration 5128 // unless that variable is usable in constant expressions. 5129 if (VD->isLocalVarDecl() && VD->isStaticLocal() && 5130 !VD->isUsableInConstantExpressions(Info.Ctx)) { 5131 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local) 5132 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD; 5133 return false; 5134 } 5135 return true; 5136 } 5137 5138 // Evaluate a statement. 5139 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 5140 const Stmt *S, const SwitchCase *Case) { 5141 if (!Info.nextStep(S)) 5142 return ESR_Failed; 5143 5144 // If we're hunting down a 'case' or 'default' label, recurse through 5145 // substatements until we hit the label. 5146 if (Case) { 5147 switch (S->getStmtClass()) { 5148 case Stmt::CompoundStmtClass: 5149 // FIXME: Precompute which substatement of a compound statement we 5150 // would jump to, and go straight there rather than performing a 5151 // linear scan each time. 5152 case Stmt::LabelStmtClass: 5153 case Stmt::AttributedStmtClass: 5154 case Stmt::DoStmtClass: 5155 break; 5156 5157 case Stmt::CaseStmtClass: 5158 case Stmt::DefaultStmtClass: 5159 if (Case == S) 5160 Case = nullptr; 5161 break; 5162 5163 case Stmt::IfStmtClass: { 5164 // FIXME: Precompute which side of an 'if' we would jump to, and go 5165 // straight there rather than scanning both sides. 5166 const IfStmt *IS = cast<IfStmt>(S); 5167 5168 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5169 // preceded by our switch label. 5170 BlockScopeRAII Scope(Info); 5171 5172 // Step into the init statement in case it brings an (uninitialized) 5173 // variable into scope. 5174 if (const Stmt *Init = IS->getInit()) { 5175 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5176 if (ESR != ESR_CaseNotFound) { 5177 assert(ESR != ESR_Succeeded); 5178 return ESR; 5179 } 5180 } 5181 5182 // Condition variable must be initialized if it exists. 5183 // FIXME: We can skip evaluating the body if there's a condition 5184 // variable, as there can't be any case labels within it. 5185 // (The same is true for 'for' statements.) 5186 5187 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5188 if (ESR == ESR_Failed) 5189 return ESR; 5190 if (ESR != ESR_CaseNotFound) 5191 return Scope.destroy() ? ESR : ESR_Failed; 5192 if (!IS->getElse()) 5193 return ESR_CaseNotFound; 5194 5195 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5196 if (ESR == ESR_Failed) 5197 return ESR; 5198 if (ESR != ESR_CaseNotFound) 5199 return Scope.destroy() ? ESR : ESR_Failed; 5200 return ESR_CaseNotFound; 5201 } 5202 5203 case Stmt::WhileStmtClass: { 5204 EvalStmtResult ESR = 5205 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5206 if (ESR != ESR_Continue) 5207 return ESR; 5208 break; 5209 } 5210 5211 case Stmt::ForStmtClass: { 5212 const ForStmt *FS = cast<ForStmt>(S); 5213 BlockScopeRAII Scope(Info); 5214 5215 // Step into the init statement in case it brings an (uninitialized) 5216 // variable into scope. 5217 if (const Stmt *Init = FS->getInit()) { 5218 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5219 if (ESR != ESR_CaseNotFound) { 5220 assert(ESR != ESR_Succeeded); 5221 return ESR; 5222 } 5223 } 5224 5225 EvalStmtResult ESR = 5226 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5227 if (ESR != ESR_Continue) 5228 return ESR; 5229 if (const auto *Inc = FS->getInc()) { 5230 if (Inc->isValueDependent()) { 5231 if (!EvaluateDependentExpr(Inc, Info)) 5232 return ESR_Failed; 5233 } else { 5234 FullExpressionRAII IncScope(Info); 5235 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5236 return ESR_Failed; 5237 } 5238 } 5239 break; 5240 } 5241 5242 case Stmt::DeclStmtClass: { 5243 // Start the lifetime of any uninitialized variables we encounter. They 5244 // might be used by the selected branch of the switch. 5245 const DeclStmt *DS = cast<DeclStmt>(S); 5246 for (const auto *D : DS->decls()) { 5247 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5248 if (!CheckLocalVariableDeclaration(Info, VD)) 5249 return ESR_Failed; 5250 if (VD->hasLocalStorage() && !VD->getInit()) 5251 if (!EvaluateVarDecl(Info, VD)) 5252 return ESR_Failed; 5253 // FIXME: If the variable has initialization that can't be jumped 5254 // over, bail out of any immediately-surrounding compound-statement 5255 // too. There can't be any case labels here. 5256 } 5257 } 5258 return ESR_CaseNotFound; 5259 } 5260 5261 default: 5262 return ESR_CaseNotFound; 5263 } 5264 } 5265 5266 switch (S->getStmtClass()) { 5267 default: 5268 if (const Expr *E = dyn_cast<Expr>(S)) { 5269 if (E->isValueDependent()) { 5270 if (!EvaluateDependentExpr(E, Info)) 5271 return ESR_Failed; 5272 } else { 5273 // Don't bother evaluating beyond an expression-statement which couldn't 5274 // be evaluated. 5275 // FIXME: Do we need the FullExpressionRAII object here? 5276 // VisitExprWithCleanups should create one when necessary. 5277 FullExpressionRAII Scope(Info); 5278 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5279 return ESR_Failed; 5280 } 5281 return ESR_Succeeded; 5282 } 5283 5284 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange(); 5285 return ESR_Failed; 5286 5287 case Stmt::NullStmtClass: 5288 return ESR_Succeeded; 5289 5290 case Stmt::DeclStmtClass: { 5291 const DeclStmt *DS = cast<DeclStmt>(S); 5292 for (const auto *D : DS->decls()) { 5293 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 5294 if (VD && !CheckLocalVariableDeclaration(Info, VD)) 5295 return ESR_Failed; 5296 // Each declaration initialization is its own full-expression. 5297 FullExpressionRAII Scope(Info); 5298 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5299 return ESR_Failed; 5300 if (!Scope.destroy()) 5301 return ESR_Failed; 5302 } 5303 return ESR_Succeeded; 5304 } 5305 5306 case Stmt::ReturnStmtClass: { 5307 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5308 FullExpressionRAII Scope(Info); 5309 if (RetExpr && RetExpr->isValueDependent()) { 5310 EvaluateDependentExpr(RetExpr, Info); 5311 // We know we returned, but we don't know what the value is. 5312 return ESR_Failed; 5313 } 5314 if (RetExpr && 5315 !(Result.Slot 5316 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5317 : Evaluate(Result.Value, Info, RetExpr))) 5318 return ESR_Failed; 5319 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5320 } 5321 5322 case Stmt::CompoundStmtClass: { 5323 BlockScopeRAII Scope(Info); 5324 5325 const CompoundStmt *CS = cast<CompoundStmt>(S); 5326 for (const auto *BI : CS->body()) { 5327 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5328 if (ESR == ESR_Succeeded) 5329 Case = nullptr; 5330 else if (ESR != ESR_CaseNotFound) { 5331 if (ESR != ESR_Failed && !Scope.destroy()) 5332 return ESR_Failed; 5333 return ESR; 5334 } 5335 } 5336 if (Case) 5337 return ESR_CaseNotFound; 5338 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5339 } 5340 5341 case Stmt::IfStmtClass: { 5342 const IfStmt *IS = cast<IfStmt>(S); 5343 5344 // Evaluate the condition, as either a var decl or as an expression. 5345 BlockScopeRAII Scope(Info); 5346 if (const Stmt *Init = IS->getInit()) { 5347 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5348 if (ESR != ESR_Succeeded) { 5349 if (ESR != ESR_Failed && !Scope.destroy()) 5350 return ESR_Failed; 5351 return ESR; 5352 } 5353 } 5354 bool Cond; 5355 if (IS->isConsteval()) { 5356 Cond = IS->isNonNegatedConsteval(); 5357 // If we are not in a constant context, if consteval should not evaluate 5358 // to true. 5359 if (!Info.InConstantContext) 5360 Cond = !Cond; 5361 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5362 Cond)) 5363 return ESR_Failed; 5364 5365 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5366 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5367 if (ESR != ESR_Succeeded) { 5368 if (ESR != ESR_Failed && !Scope.destroy()) 5369 return ESR_Failed; 5370 return ESR; 5371 } 5372 } 5373 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5374 } 5375 5376 case Stmt::WhileStmtClass: { 5377 const WhileStmt *WS = cast<WhileStmt>(S); 5378 while (true) { 5379 BlockScopeRAII Scope(Info); 5380 bool Continue; 5381 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5382 Continue)) 5383 return ESR_Failed; 5384 if (!Continue) 5385 break; 5386 5387 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5388 if (ESR != ESR_Continue) { 5389 if (ESR != ESR_Failed && !Scope.destroy()) 5390 return ESR_Failed; 5391 return ESR; 5392 } 5393 if (!Scope.destroy()) 5394 return ESR_Failed; 5395 } 5396 return ESR_Succeeded; 5397 } 5398 5399 case Stmt::DoStmtClass: { 5400 const DoStmt *DS = cast<DoStmt>(S); 5401 bool Continue; 5402 do { 5403 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5404 if (ESR != ESR_Continue) 5405 return ESR; 5406 Case = nullptr; 5407 5408 if (DS->getCond()->isValueDependent()) { 5409 EvaluateDependentExpr(DS->getCond(), Info); 5410 // Bailout as we don't know whether to keep going or terminate the loop. 5411 return ESR_Failed; 5412 } 5413 FullExpressionRAII CondScope(Info); 5414 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5415 !CondScope.destroy()) 5416 return ESR_Failed; 5417 } while (Continue); 5418 return ESR_Succeeded; 5419 } 5420 5421 case Stmt::ForStmtClass: { 5422 const ForStmt *FS = cast<ForStmt>(S); 5423 BlockScopeRAII ForScope(Info); 5424 if (FS->getInit()) { 5425 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5426 if (ESR != ESR_Succeeded) { 5427 if (ESR != ESR_Failed && !ForScope.destroy()) 5428 return ESR_Failed; 5429 return ESR; 5430 } 5431 } 5432 while (true) { 5433 BlockScopeRAII IterScope(Info); 5434 bool Continue = true; 5435 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5436 FS->getCond(), Continue)) 5437 return ESR_Failed; 5438 if (!Continue) 5439 break; 5440 5441 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5442 if (ESR != ESR_Continue) { 5443 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5444 return ESR_Failed; 5445 return ESR; 5446 } 5447 5448 if (const auto *Inc = FS->getInc()) { 5449 if (Inc->isValueDependent()) { 5450 if (!EvaluateDependentExpr(Inc, Info)) 5451 return ESR_Failed; 5452 } else { 5453 FullExpressionRAII IncScope(Info); 5454 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5455 return ESR_Failed; 5456 } 5457 } 5458 5459 if (!IterScope.destroy()) 5460 return ESR_Failed; 5461 } 5462 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5463 } 5464 5465 case Stmt::CXXForRangeStmtClass: { 5466 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5467 BlockScopeRAII Scope(Info); 5468 5469 // Evaluate the init-statement if present. 5470 if (FS->getInit()) { 5471 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5472 if (ESR != ESR_Succeeded) { 5473 if (ESR != ESR_Failed && !Scope.destroy()) 5474 return ESR_Failed; 5475 return ESR; 5476 } 5477 } 5478 5479 // Initialize the __range variable. 5480 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5481 if (ESR != ESR_Succeeded) { 5482 if (ESR != ESR_Failed && !Scope.destroy()) 5483 return ESR_Failed; 5484 return ESR; 5485 } 5486 5487 // In error-recovery cases it's possible to get here even if we failed to 5488 // synthesize the __begin and __end variables. 5489 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5490 return ESR_Failed; 5491 5492 // Create the __begin and __end iterators. 5493 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5494 if (ESR != ESR_Succeeded) { 5495 if (ESR != ESR_Failed && !Scope.destroy()) 5496 return ESR_Failed; 5497 return ESR; 5498 } 5499 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5500 if (ESR != ESR_Succeeded) { 5501 if (ESR != ESR_Failed && !Scope.destroy()) 5502 return ESR_Failed; 5503 return ESR; 5504 } 5505 5506 while (true) { 5507 // Condition: __begin != __end. 5508 { 5509 if (FS->getCond()->isValueDependent()) { 5510 EvaluateDependentExpr(FS->getCond(), Info); 5511 // We don't know whether to keep going or terminate the loop. 5512 return ESR_Failed; 5513 } 5514 bool Continue = true; 5515 FullExpressionRAII CondExpr(Info); 5516 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5517 return ESR_Failed; 5518 if (!Continue) 5519 break; 5520 } 5521 5522 // User's variable declaration, initialized by *__begin. 5523 BlockScopeRAII InnerScope(Info); 5524 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5525 if (ESR != ESR_Succeeded) { 5526 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5527 return ESR_Failed; 5528 return ESR; 5529 } 5530 5531 // Loop body. 5532 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5533 if (ESR != ESR_Continue) { 5534 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5535 return ESR_Failed; 5536 return ESR; 5537 } 5538 if (FS->getInc()->isValueDependent()) { 5539 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5540 return ESR_Failed; 5541 } else { 5542 // Increment: ++__begin 5543 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5544 return ESR_Failed; 5545 } 5546 5547 if (!InnerScope.destroy()) 5548 return ESR_Failed; 5549 } 5550 5551 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5552 } 5553 5554 case Stmt::SwitchStmtClass: 5555 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5556 5557 case Stmt::ContinueStmtClass: 5558 return ESR_Continue; 5559 5560 case Stmt::BreakStmtClass: 5561 return ESR_Break; 5562 5563 case Stmt::LabelStmtClass: 5564 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5565 5566 case Stmt::AttributedStmtClass: { 5567 const auto *AS = cast<AttributedStmt>(S); 5568 const auto *SS = AS->getSubStmt(); 5569 MSConstexprContextRAII ConstexprContext( 5570 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) && 5571 isa<ReturnStmt>(SS)); 5572 return EvaluateStmt(Result, Info, SS, Case); 5573 } 5574 5575 case Stmt::CaseStmtClass: 5576 case Stmt::DefaultStmtClass: 5577 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5578 case Stmt::CXXTryStmtClass: 5579 // Evaluate try blocks by evaluating all sub statements. 5580 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5581 } 5582 } 5583 5584 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5585 /// default constructor. If so, we'll fold it whether or not it's marked as 5586 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5587 /// so we need special handling. 5588 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5589 const CXXConstructorDecl *CD, 5590 bool IsValueInitialization) { 5591 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5592 return false; 5593 5594 // Value-initialization does not call a trivial default constructor, so such a 5595 // call is a core constant expression whether or not the constructor is 5596 // constexpr. 5597 if (!CD->isConstexpr() && !IsValueInitialization) { 5598 if (Info.getLangOpts().CPlusPlus11) { 5599 // FIXME: If DiagDecl is an implicitly-declared special member function, 5600 // we should be much more explicit about why it's not constexpr. 5601 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5602 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5603 Info.Note(CD->getLocation(), diag::note_declared_at); 5604 } else { 5605 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5606 } 5607 } 5608 return true; 5609 } 5610 5611 /// CheckConstexprFunction - Check that a function can be called in a constant 5612 /// expression. 5613 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5614 const FunctionDecl *Declaration, 5615 const FunctionDecl *Definition, 5616 const Stmt *Body) { 5617 // Potential constant expressions can contain calls to declared, but not yet 5618 // defined, constexpr functions. 5619 if (Info.checkingPotentialConstantExpression() && !Definition && 5620 Declaration->isConstexpr()) 5621 return false; 5622 5623 // Bail out if the function declaration itself is invalid. We will 5624 // have produced a relevant diagnostic while parsing it, so just 5625 // note the problematic sub-expression. 5626 if (Declaration->isInvalidDecl()) { 5627 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5628 return false; 5629 } 5630 5631 // DR1872: An instantiated virtual constexpr function can't be called in a 5632 // constant expression (prior to C++20). We can still constant-fold such a 5633 // call. 5634 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5635 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5636 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5637 5638 if (Definition && Definition->isInvalidDecl()) { 5639 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5640 return false; 5641 } 5642 5643 // Can we evaluate this function call? 5644 if (Definition && Body && 5645 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr && 5646 Definition->hasAttr<MSConstexprAttr>()))) 5647 return true; 5648 5649 if (Info.getLangOpts().CPlusPlus11) { 5650 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5651 5652 // If this function is not constexpr because it is an inherited 5653 // non-constexpr constructor, diagnose that directly. 5654 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5655 if (CD && CD->isInheritingConstructor()) { 5656 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5657 if (!Inherited->isConstexpr()) 5658 DiagDecl = CD = Inherited; 5659 } 5660 5661 // FIXME: If DiagDecl is an implicitly-declared special member function 5662 // or an inheriting constructor, we should be much more explicit about why 5663 // it's not constexpr. 5664 if (CD && CD->isInheritingConstructor()) 5665 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5666 << CD->getInheritedConstructor().getConstructor()->getParent(); 5667 else 5668 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5669 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5670 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5671 } else { 5672 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5673 } 5674 return false; 5675 } 5676 5677 namespace { 5678 struct CheckDynamicTypeHandler { 5679 AccessKinds AccessKind; 5680 typedef bool result_type; 5681 bool failed() { return false; } 5682 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5683 bool found(APSInt &Value, QualType SubobjType) { return true; } 5684 bool found(APFloat &Value, QualType SubobjType) { return true; } 5685 }; 5686 } // end anonymous namespace 5687 5688 /// Check that we can access the notional vptr of an object / determine its 5689 /// dynamic type. 5690 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5691 AccessKinds AK, bool Polymorphic) { 5692 if (This.Designator.Invalid) 5693 return false; 5694 5695 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5696 5697 if (!Obj) 5698 return false; 5699 5700 if (!Obj.Value) { 5701 // The object is not usable in constant expressions, so we can't inspect 5702 // its value to see if it's in-lifetime or what the active union members 5703 // are. We can still check for a one-past-the-end lvalue. 5704 if (This.Designator.isOnePastTheEnd() || 5705 This.Designator.isMostDerivedAnUnsizedArray()) { 5706 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5707 ? diag::note_constexpr_access_past_end 5708 : diag::note_constexpr_access_unsized_array) 5709 << AK; 5710 return false; 5711 } else if (Polymorphic) { 5712 // Conservatively refuse to perform a polymorphic operation if we would 5713 // not be able to read a notional 'vptr' value. 5714 APValue Val; 5715 This.moveInto(Val); 5716 QualType StarThisType = 5717 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5718 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5719 << AK << Val.getAsString(Info.Ctx, StarThisType); 5720 return false; 5721 } 5722 return true; 5723 } 5724 5725 CheckDynamicTypeHandler Handler{AK}; 5726 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5727 } 5728 5729 /// Check that the pointee of the 'this' pointer in a member function call is 5730 /// either within its lifetime or in its period of construction or destruction. 5731 static bool 5732 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5733 const LValue &This, 5734 const CXXMethodDecl *NamedMember) { 5735 return checkDynamicType( 5736 Info, E, This, 5737 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5738 } 5739 5740 struct DynamicType { 5741 /// The dynamic class type of the object. 5742 const CXXRecordDecl *Type; 5743 /// The corresponding path length in the lvalue. 5744 unsigned PathLength; 5745 }; 5746 5747 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5748 unsigned PathLength) { 5749 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5750 Designator.Entries.size() && "invalid path length"); 5751 return (PathLength == Designator.MostDerivedPathLength) 5752 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5753 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5754 } 5755 5756 /// Determine the dynamic type of an object. 5757 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info, 5758 const Expr *E, 5759 LValue &This, 5760 AccessKinds AK) { 5761 // If we don't have an lvalue denoting an object of class type, there is no 5762 // meaningful dynamic type. (We consider objects of non-class type to have no 5763 // dynamic type.) 5764 if (!checkDynamicType(Info, E, This, AK, true)) 5765 return std::nullopt; 5766 5767 // Refuse to compute a dynamic type in the presence of virtual bases. This 5768 // shouldn't happen other than in constant-folding situations, since literal 5769 // types can't have virtual bases. 5770 // 5771 // Note that consumers of DynamicType assume that the type has no virtual 5772 // bases, and will need modifications if this restriction is relaxed. 5773 const CXXRecordDecl *Class = 5774 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5775 if (!Class || Class->getNumVBases()) { 5776 Info.FFDiag(E); 5777 return std::nullopt; 5778 } 5779 5780 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5781 // binary search here instead. But the overwhelmingly common case is that 5782 // we're not in the middle of a constructor, so it probably doesn't matter 5783 // in practice. 5784 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5785 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5786 PathLength <= Path.size(); ++PathLength) { 5787 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5788 Path.slice(0, PathLength))) { 5789 case ConstructionPhase::Bases: 5790 case ConstructionPhase::DestroyingBases: 5791 // We're constructing or destroying a base class. This is not the dynamic 5792 // type. 5793 break; 5794 5795 case ConstructionPhase::None: 5796 case ConstructionPhase::AfterBases: 5797 case ConstructionPhase::AfterFields: 5798 case ConstructionPhase::Destroying: 5799 // We've finished constructing the base classes and not yet started 5800 // destroying them again, so this is the dynamic type. 5801 return DynamicType{getBaseClassType(This.Designator, PathLength), 5802 PathLength}; 5803 } 5804 } 5805 5806 // CWG issue 1517: we're constructing a base class of the object described by 5807 // 'This', so that object has not yet begun its period of construction and 5808 // any polymorphic operation on it results in undefined behavior. 5809 Info.FFDiag(E); 5810 return std::nullopt; 5811 } 5812 5813 /// Perform virtual dispatch. 5814 static const CXXMethodDecl *HandleVirtualDispatch( 5815 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5816 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5817 std::optional<DynamicType> DynType = ComputeDynamicType( 5818 Info, E, This, 5819 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5820 if (!DynType) 5821 return nullptr; 5822 5823 // Find the final overrider. It must be declared in one of the classes on the 5824 // path from the dynamic type to the static type. 5825 // FIXME: If we ever allow literal types to have virtual base classes, that 5826 // won't be true. 5827 const CXXMethodDecl *Callee = Found; 5828 unsigned PathLength = DynType->PathLength; 5829 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5830 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5831 const CXXMethodDecl *Overrider = 5832 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5833 if (Overrider) { 5834 Callee = Overrider; 5835 break; 5836 } 5837 } 5838 5839 // C++2a [class.abstract]p6: 5840 // the effect of making a virtual call to a pure virtual function [...] is 5841 // undefined 5842 if (Callee->isPure()) { 5843 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5844 Info.Note(Callee->getLocation(), diag::note_declared_at); 5845 return nullptr; 5846 } 5847 5848 // If necessary, walk the rest of the path to determine the sequence of 5849 // covariant adjustment steps to apply. 5850 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5851 Found->getReturnType())) { 5852 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5853 for (unsigned CovariantPathLength = PathLength + 1; 5854 CovariantPathLength != This.Designator.Entries.size(); 5855 ++CovariantPathLength) { 5856 const CXXRecordDecl *NextClass = 5857 getBaseClassType(This.Designator, CovariantPathLength); 5858 const CXXMethodDecl *Next = 5859 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5860 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5861 Next->getReturnType(), CovariantAdjustmentPath.back())) 5862 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5863 } 5864 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5865 CovariantAdjustmentPath.back())) 5866 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5867 } 5868 5869 // Perform 'this' adjustment. 5870 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5871 return nullptr; 5872 5873 return Callee; 5874 } 5875 5876 /// Perform the adjustment from a value returned by a virtual function to 5877 /// a value of the statically expected type, which may be a pointer or 5878 /// reference to a base class of the returned type. 5879 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5880 APValue &Result, 5881 ArrayRef<QualType> Path) { 5882 assert(Result.isLValue() && 5883 "unexpected kind of APValue for covariant return"); 5884 if (Result.isNullPointer()) 5885 return true; 5886 5887 LValue LVal; 5888 LVal.setFrom(Info.Ctx, Result); 5889 5890 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5891 for (unsigned I = 1; I != Path.size(); ++I) { 5892 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5893 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5894 if (OldClass != NewClass && 5895 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5896 return false; 5897 OldClass = NewClass; 5898 } 5899 5900 LVal.moveInto(Result); 5901 return true; 5902 } 5903 5904 /// Determine whether \p Base, which is known to be a direct base class of 5905 /// \p Derived, is a public base class. 5906 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5907 const CXXRecordDecl *Base) { 5908 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5909 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5910 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5911 return BaseSpec.getAccessSpecifier() == AS_public; 5912 } 5913 llvm_unreachable("Base is not a direct base of Derived"); 5914 } 5915 5916 /// Apply the given dynamic cast operation on the provided lvalue. 5917 /// 5918 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5919 /// to find a suitable target subobject. 5920 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5921 LValue &Ptr) { 5922 // We can't do anything with a non-symbolic pointer value. 5923 SubobjectDesignator &D = Ptr.Designator; 5924 if (D.Invalid) 5925 return false; 5926 5927 // C++ [expr.dynamic.cast]p6: 5928 // If v is a null pointer value, the result is a null pointer value. 5929 if (Ptr.isNullPointer() && !E->isGLValue()) 5930 return true; 5931 5932 // For all the other cases, we need the pointer to point to an object within 5933 // its lifetime / period of construction / destruction, and we need to know 5934 // its dynamic type. 5935 std::optional<DynamicType> DynType = 5936 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5937 if (!DynType) 5938 return false; 5939 5940 // C++ [expr.dynamic.cast]p7: 5941 // If T is "pointer to cv void", then the result is a pointer to the most 5942 // derived object 5943 if (E->getType()->isVoidPointerType()) 5944 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5945 5946 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5947 assert(C && "dynamic_cast target is not void pointer nor class"); 5948 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5949 5950 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5951 // C++ [expr.dynamic.cast]p9: 5952 if (!E->isGLValue()) { 5953 // The value of a failed cast to pointer type is the null pointer value 5954 // of the required result type. 5955 Ptr.setNull(Info.Ctx, E->getType()); 5956 return true; 5957 } 5958 5959 // A failed cast to reference type throws [...] std::bad_cast. 5960 unsigned DiagKind; 5961 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5962 DynType->Type->isDerivedFrom(C))) 5963 DiagKind = 0; 5964 else if (!Paths || Paths->begin() == Paths->end()) 5965 DiagKind = 1; 5966 else if (Paths->isAmbiguous(CQT)) 5967 DiagKind = 2; 5968 else { 5969 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5970 DiagKind = 3; 5971 } 5972 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5973 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5974 << Info.Ctx.getRecordType(DynType->Type) 5975 << E->getType().getUnqualifiedType(); 5976 return false; 5977 }; 5978 5979 // Runtime check, phase 1: 5980 // Walk from the base subobject towards the derived object looking for the 5981 // target type. 5982 for (int PathLength = Ptr.Designator.Entries.size(); 5983 PathLength >= (int)DynType->PathLength; --PathLength) { 5984 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5985 if (declaresSameEntity(Class, C)) 5986 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5987 // We can only walk across public inheritance edges. 5988 if (PathLength > (int)DynType->PathLength && 5989 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5990 Class)) 5991 return RuntimeCheckFailed(nullptr); 5992 } 5993 5994 // Runtime check, phase 2: 5995 // Search the dynamic type for an unambiguous public base of type C. 5996 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5997 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5998 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5999 Paths.front().Access == AS_public) { 6000 // Downcast to the dynamic type... 6001 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 6002 return false; 6003 // ... then upcast to the chosen base class subobject. 6004 for (CXXBasePathElement &Elem : Paths.front()) 6005 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 6006 return false; 6007 return true; 6008 } 6009 6010 // Otherwise, the runtime check fails. 6011 return RuntimeCheckFailed(&Paths); 6012 } 6013 6014 namespace { 6015 struct StartLifetimeOfUnionMemberHandler { 6016 EvalInfo &Info; 6017 const Expr *LHSExpr; 6018 const FieldDecl *Field; 6019 bool DuringInit; 6020 bool Failed = false; 6021 static const AccessKinds AccessKind = AK_Assign; 6022 6023 typedef bool result_type; 6024 bool failed() { return Failed; } 6025 bool found(APValue &Subobj, QualType SubobjType) { 6026 // We are supposed to perform no initialization but begin the lifetime of 6027 // the object. We interpret that as meaning to do what default 6028 // initialization of the object would do if all constructors involved were 6029 // trivial: 6030 // * All base, non-variant member, and array element subobjects' lifetimes 6031 // begin 6032 // * No variant members' lifetimes begin 6033 // * All scalar subobjects whose lifetimes begin have indeterminate values 6034 assert(SubobjType->isUnionType()); 6035 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 6036 // This union member is already active. If it's also in-lifetime, there's 6037 // nothing to do. 6038 if (Subobj.getUnionValue().hasValue()) 6039 return true; 6040 } else if (DuringInit) { 6041 // We're currently in the process of initializing a different union 6042 // member. If we carried on, that initialization would attempt to 6043 // store to an inactive union member, resulting in undefined behavior. 6044 Info.FFDiag(LHSExpr, 6045 diag::note_constexpr_union_member_change_during_init); 6046 return false; 6047 } 6048 APValue Result; 6049 Failed = !handleDefaultInitValue(Field->getType(), Result); 6050 Subobj.setUnion(Field, Result); 6051 return true; 6052 } 6053 bool found(APSInt &Value, QualType SubobjType) { 6054 llvm_unreachable("wrong value kind for union object"); 6055 } 6056 bool found(APFloat &Value, QualType SubobjType) { 6057 llvm_unreachable("wrong value kind for union object"); 6058 } 6059 }; 6060 } // end anonymous namespace 6061 6062 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 6063 6064 /// Handle a builtin simple-assignment or a call to a trivial assignment 6065 /// operator whose left-hand side might involve a union member access. If it 6066 /// does, implicitly start the lifetime of any accessed union elements per 6067 /// C++20 [class.union]5. 6068 static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, 6069 const Expr *LHSExpr, 6070 const LValue &LHS) { 6071 if (LHS.InvalidBase || LHS.Designator.Invalid) 6072 return false; 6073 6074 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 6075 // C++ [class.union]p5: 6076 // define the set S(E) of subexpressions of E as follows: 6077 unsigned PathLength = LHS.Designator.Entries.size(); 6078 for (const Expr *E = LHSExpr; E != nullptr;) { 6079 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 6080 if (auto *ME = dyn_cast<MemberExpr>(E)) { 6081 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 6082 // Note that we can't implicitly start the lifetime of a reference, 6083 // so we don't need to proceed any further if we reach one. 6084 if (!FD || FD->getType()->isReferenceType()) 6085 break; 6086 6087 // ... and also contains A.B if B names a union member ... 6088 if (FD->getParent()->isUnion()) { 6089 // ... of a non-class, non-array type, or of a class type with a 6090 // trivial default constructor that is not deleted, or an array of 6091 // such types. 6092 auto *RD = 6093 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 6094 if (!RD || RD->hasTrivialDefaultConstructor()) 6095 UnionPathLengths.push_back({PathLength - 1, FD}); 6096 } 6097 6098 E = ME->getBase(); 6099 --PathLength; 6100 assert(declaresSameEntity(FD, 6101 LHS.Designator.Entries[PathLength] 6102 .getAsBaseOrMember().getPointer())); 6103 6104 // -- If E is of the form A[B] and is interpreted as a built-in array 6105 // subscripting operator, S(E) is [S(the array operand, if any)]. 6106 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 6107 // Step over an ArrayToPointerDecay implicit cast. 6108 auto *Base = ASE->getBase()->IgnoreImplicit(); 6109 if (!Base->getType()->isArrayType()) 6110 break; 6111 6112 E = Base; 6113 --PathLength; 6114 6115 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6116 // Step over a derived-to-base conversion. 6117 E = ICE->getSubExpr(); 6118 if (ICE->getCastKind() == CK_NoOp) 6119 continue; 6120 if (ICE->getCastKind() != CK_DerivedToBase && 6121 ICE->getCastKind() != CK_UncheckedDerivedToBase) 6122 break; 6123 // Walk path backwards as we walk up from the base to the derived class. 6124 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 6125 if (Elt->isVirtual()) { 6126 // A class with virtual base classes never has a trivial default 6127 // constructor, so S(E) is empty in this case. 6128 E = nullptr; 6129 break; 6130 } 6131 6132 --PathLength; 6133 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 6134 LHS.Designator.Entries[PathLength] 6135 .getAsBaseOrMember().getPointer())); 6136 } 6137 6138 // -- Otherwise, S(E) is empty. 6139 } else { 6140 break; 6141 } 6142 } 6143 6144 // Common case: no unions' lifetimes are started. 6145 if (UnionPathLengths.empty()) 6146 return true; 6147 6148 // if modification of X [would access an inactive union member], an object 6149 // of the type of X is implicitly created 6150 CompleteObject Obj = 6151 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 6152 if (!Obj) 6153 return false; 6154 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 6155 llvm::reverse(UnionPathLengths)) { 6156 // Form a designator for the union object. 6157 SubobjectDesignator D = LHS.Designator; 6158 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 6159 6160 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 6161 ConstructionPhase::AfterBases; 6162 StartLifetimeOfUnionMemberHandler StartLifetime{ 6163 Info, LHSExpr, LengthAndField.second, DuringInit}; 6164 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 6165 return false; 6166 } 6167 6168 return true; 6169 } 6170 6171 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 6172 CallRef Call, EvalInfo &Info, 6173 bool NonNull = false) { 6174 LValue LV; 6175 // Create the parameter slot and register its destruction. For a vararg 6176 // argument, create a temporary. 6177 // FIXME: For calling conventions that destroy parameters in the callee, 6178 // should we consider performing destruction when the function returns 6179 // instead? 6180 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6181 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6182 ScopeKind::Call, LV); 6183 if (!EvaluateInPlace(V, Info, LV, Arg)) 6184 return false; 6185 6186 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6187 // undefined behavior, so is non-constant. 6188 if (NonNull && V.isLValue() && V.isNullPointer()) { 6189 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6190 return false; 6191 } 6192 6193 return true; 6194 } 6195 6196 /// Evaluate the arguments to a function call. 6197 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6198 EvalInfo &Info, const FunctionDecl *Callee, 6199 bool RightToLeft = false) { 6200 bool Success = true; 6201 llvm::SmallBitVector ForbiddenNullArgs; 6202 if (Callee->hasAttr<NonNullAttr>()) { 6203 ForbiddenNullArgs.resize(Args.size()); 6204 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6205 if (!Attr->args_size()) { 6206 ForbiddenNullArgs.set(); 6207 break; 6208 } else 6209 for (auto Idx : Attr->args()) { 6210 unsigned ASTIdx = Idx.getASTIndex(); 6211 if (ASTIdx >= Args.size()) 6212 continue; 6213 ForbiddenNullArgs[ASTIdx] = true; 6214 } 6215 } 6216 } 6217 for (unsigned I = 0; I < Args.size(); I++) { 6218 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6219 const ParmVarDecl *PVD = 6220 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6221 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6222 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6223 // If we're checking for a potential constant expression, evaluate all 6224 // initializers even if some of them fail. 6225 if (!Info.noteFailure()) 6226 return false; 6227 Success = false; 6228 } 6229 } 6230 return Success; 6231 } 6232 6233 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6234 /// constructor or assignment operator. 6235 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6236 const Expr *E, APValue &Result, 6237 bool CopyObjectRepresentation) { 6238 // Find the reference argument. 6239 CallStackFrame *Frame = Info.CurrentCall; 6240 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6241 if (!RefValue) { 6242 Info.FFDiag(E); 6243 return false; 6244 } 6245 6246 // Copy out the contents of the RHS object. 6247 LValue RefLValue; 6248 RefLValue.setFrom(Info.Ctx, *RefValue); 6249 return handleLValueToRValueConversion( 6250 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6251 CopyObjectRepresentation); 6252 } 6253 6254 /// Evaluate a function call. 6255 static bool HandleFunctionCall(SourceLocation CallLoc, 6256 const FunctionDecl *Callee, const LValue *This, 6257 const Expr *E, ArrayRef<const Expr *> Args, 6258 CallRef Call, const Stmt *Body, EvalInfo &Info, 6259 APValue &Result, const LValue *ResultSlot) { 6260 if (!Info.CheckCallLimit(CallLoc)) 6261 return false; 6262 6263 CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call); 6264 6265 // For a trivial copy or move assignment, perform an APValue copy. This is 6266 // essential for unions, where the operations performed by the assignment 6267 // operator cannot be represented as statements. 6268 // 6269 // Skip this for non-union classes with no fields; in that case, the defaulted 6270 // copy/move does not actually read the object. 6271 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6272 if (MD && MD->isDefaulted() && 6273 (MD->getParent()->isUnion() || 6274 (MD->isTrivial() && 6275 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6276 assert(This && 6277 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6278 APValue RHSValue; 6279 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6280 MD->getParent()->isUnion())) 6281 return false; 6282 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6283 RHSValue)) 6284 return false; 6285 This->moveInto(Result); 6286 return true; 6287 } else if (MD && isLambdaCallOperator(MD)) { 6288 // We're in a lambda; determine the lambda capture field maps unless we're 6289 // just constexpr checking a lambda's call operator. constexpr checking is 6290 // done before the captures have been added to the closure object (unless 6291 // we're inferring constexpr-ness), so we don't have access to them in this 6292 // case. But since we don't need the captures to constexpr check, we can 6293 // just ignore them. 6294 if (!Info.checkingPotentialConstantExpression()) 6295 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6296 Frame.LambdaThisCaptureField); 6297 } 6298 6299 StmtResult Ret = {Result, ResultSlot}; 6300 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6301 if (ESR == ESR_Succeeded) { 6302 if (Callee->getReturnType()->isVoidType()) 6303 return true; 6304 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6305 } 6306 return ESR == ESR_Returned; 6307 } 6308 6309 /// Evaluate a constructor call. 6310 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6311 CallRef Call, 6312 const CXXConstructorDecl *Definition, 6313 EvalInfo &Info, APValue &Result) { 6314 SourceLocation CallLoc = E->getExprLoc(); 6315 if (!Info.CheckCallLimit(CallLoc)) 6316 return false; 6317 6318 const CXXRecordDecl *RD = Definition->getParent(); 6319 if (RD->getNumVBases()) { 6320 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6321 return false; 6322 } 6323 6324 EvalInfo::EvaluatingConstructorRAII EvalObj( 6325 Info, 6326 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6327 RD->getNumBases()); 6328 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call); 6329 6330 // FIXME: Creating an APValue just to hold a nonexistent return value is 6331 // wasteful. 6332 APValue RetVal; 6333 StmtResult Ret = {RetVal, nullptr}; 6334 6335 // If it's a delegating constructor, delegate. 6336 if (Definition->isDelegatingConstructor()) { 6337 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6338 if ((*I)->getInit()->isValueDependent()) { 6339 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6340 return false; 6341 } else { 6342 FullExpressionRAII InitScope(Info); 6343 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6344 !InitScope.destroy()) 6345 return false; 6346 } 6347 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6348 } 6349 6350 // For a trivial copy or move constructor, perform an APValue copy. This is 6351 // essential for unions (or classes with anonymous union members), where the 6352 // operations performed by the constructor cannot be represented by 6353 // ctor-initializers. 6354 // 6355 // Skip this for empty non-union classes; we should not perform an 6356 // lvalue-to-rvalue conversion on them because their copy constructor does not 6357 // actually read them. 6358 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6359 (Definition->getParent()->isUnion() || 6360 (Definition->isTrivial() && 6361 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6362 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6363 Definition->getParent()->isUnion()); 6364 } 6365 6366 // Reserve space for the struct members. 6367 if (!Result.hasValue()) { 6368 if (!RD->isUnion()) 6369 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6370 std::distance(RD->field_begin(), RD->field_end())); 6371 else 6372 // A union starts with no active member. 6373 Result = APValue((const FieldDecl*)nullptr); 6374 } 6375 6376 if (RD->isInvalidDecl()) return false; 6377 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6378 6379 // A scope for temporaries lifetime-extended by reference members. 6380 BlockScopeRAII LifetimeExtendedScope(Info); 6381 6382 bool Success = true; 6383 unsigned BasesSeen = 0; 6384 #ifndef NDEBUG 6385 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6386 #endif 6387 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6388 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6389 // We might be initializing the same field again if this is an indirect 6390 // field initialization. 6391 if (FieldIt == RD->field_end() || 6392 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6393 assert(Indirect && "fields out of order?"); 6394 return; 6395 } 6396 6397 // Default-initialize any fields with no explicit initializer. 6398 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6399 assert(FieldIt != RD->field_end() && "missing field?"); 6400 if (!FieldIt->isUnnamedBitfield()) 6401 Success &= handleDefaultInitValue( 6402 FieldIt->getType(), 6403 Result.getStructField(FieldIt->getFieldIndex())); 6404 } 6405 ++FieldIt; 6406 }; 6407 for (const auto *I : Definition->inits()) { 6408 LValue Subobject = This; 6409 LValue SubobjectParent = This; 6410 APValue *Value = &Result; 6411 6412 // Determine the subobject to initialize. 6413 FieldDecl *FD = nullptr; 6414 if (I->isBaseInitializer()) { 6415 QualType BaseType(I->getBaseClass(), 0); 6416 #ifndef NDEBUG 6417 // Non-virtual base classes are initialized in the order in the class 6418 // definition. We have already checked for virtual base classes. 6419 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6420 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6421 "base class initializers not in expected order"); 6422 ++BaseIt; 6423 #endif 6424 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6425 BaseType->getAsCXXRecordDecl(), &Layout)) 6426 return false; 6427 Value = &Result.getStructBase(BasesSeen++); 6428 } else if ((FD = I->getMember())) { 6429 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6430 return false; 6431 if (RD->isUnion()) { 6432 Result = APValue(FD); 6433 Value = &Result.getUnionValue(); 6434 } else { 6435 SkipToField(FD, false); 6436 Value = &Result.getStructField(FD->getFieldIndex()); 6437 } 6438 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6439 // Walk the indirect field decl's chain to find the object to initialize, 6440 // and make sure we've initialized every step along it. 6441 auto IndirectFieldChain = IFD->chain(); 6442 for (auto *C : IndirectFieldChain) { 6443 FD = cast<FieldDecl>(C); 6444 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6445 // Switch the union field if it differs. This happens if we had 6446 // preceding zero-initialization, and we're now initializing a union 6447 // subobject other than the first. 6448 // FIXME: In this case, the values of the other subobjects are 6449 // specified, since zero-initialization sets all padding bits to zero. 6450 if (!Value->hasValue() || 6451 (Value->isUnion() && Value->getUnionField() != FD)) { 6452 if (CD->isUnion()) 6453 *Value = APValue(FD); 6454 else 6455 // FIXME: This immediately starts the lifetime of all members of 6456 // an anonymous struct. It would be preferable to strictly start 6457 // member lifetime in initialization order. 6458 Success &= 6459 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6460 } 6461 // Store Subobject as its parent before updating it for the last element 6462 // in the chain. 6463 if (C == IndirectFieldChain.back()) 6464 SubobjectParent = Subobject; 6465 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6466 return false; 6467 if (CD->isUnion()) 6468 Value = &Value->getUnionValue(); 6469 else { 6470 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6471 SkipToField(FD, true); 6472 Value = &Value->getStructField(FD->getFieldIndex()); 6473 } 6474 } 6475 } else { 6476 llvm_unreachable("unknown base initializer kind"); 6477 } 6478 6479 // Need to override This for implicit field initializers as in this case 6480 // This refers to innermost anonymous struct/union containing initializer, 6481 // not to currently constructed class. 6482 const Expr *Init = I->getInit(); 6483 if (Init->isValueDependent()) { 6484 if (!EvaluateDependentExpr(Init, Info)) 6485 return false; 6486 } else { 6487 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6488 isa<CXXDefaultInitExpr>(Init)); 6489 FullExpressionRAII InitScope(Info); 6490 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6491 (FD && FD->isBitField() && 6492 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6493 // If we're checking for a potential constant expression, evaluate all 6494 // initializers even if some of them fail. 6495 if (!Info.noteFailure()) 6496 return false; 6497 Success = false; 6498 } 6499 } 6500 6501 // This is the point at which the dynamic type of the object becomes this 6502 // class type. 6503 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6504 EvalObj.finishedConstructingBases(); 6505 } 6506 6507 // Default-initialize any remaining fields. 6508 if (!RD->isUnion()) { 6509 for (; FieldIt != RD->field_end(); ++FieldIt) { 6510 if (!FieldIt->isUnnamedBitfield()) 6511 Success &= handleDefaultInitValue( 6512 FieldIt->getType(), 6513 Result.getStructField(FieldIt->getFieldIndex())); 6514 } 6515 } 6516 6517 EvalObj.finishedConstructingFields(); 6518 6519 return Success && 6520 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6521 LifetimeExtendedScope.destroy(); 6522 } 6523 6524 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6525 ArrayRef<const Expr*> Args, 6526 const CXXConstructorDecl *Definition, 6527 EvalInfo &Info, APValue &Result) { 6528 CallScopeRAII CallScope(Info); 6529 CallRef Call = Info.CurrentCall->createCall(Definition); 6530 if (!EvaluateArgs(Args, Call, Info, Definition)) 6531 return false; 6532 6533 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6534 CallScope.destroy(); 6535 } 6536 6537 static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, 6538 const LValue &This, APValue &Value, 6539 QualType T) { 6540 // Objects can only be destroyed while they're within their lifetimes. 6541 // FIXME: We have no representation for whether an object of type nullptr_t 6542 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6543 // as indeterminate instead? 6544 if (Value.isAbsent() && !T->isNullPtrType()) { 6545 APValue Printable; 6546 This.moveInto(Printable); 6547 Info.FFDiag(CallRange.getBegin(), 6548 diag::note_constexpr_destroy_out_of_lifetime) 6549 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6550 return false; 6551 } 6552 6553 // Invent an expression for location purposes. 6554 // FIXME: We shouldn't need to do this. 6555 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue); 6556 6557 // For arrays, destroy elements right-to-left. 6558 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6559 uint64_t Size = CAT->getSize().getZExtValue(); 6560 QualType ElemT = CAT->getElementType(); 6561 6562 if (!CheckArraySize(Info, CAT, CallRange.getBegin())) 6563 return false; 6564 6565 LValue ElemLV = This; 6566 ElemLV.addArray(Info, &LocE, CAT); 6567 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6568 return false; 6569 6570 // Ensure that we have actual array elements available to destroy; the 6571 // destructors might mutate the value, so we can't run them on the array 6572 // filler. 6573 if (Size && Size > Value.getArrayInitializedElts()) 6574 expandArray(Value, Value.getArraySize() - 1); 6575 6576 for (; Size != 0; --Size) { 6577 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6578 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6579 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT)) 6580 return false; 6581 } 6582 6583 // End the lifetime of this array now. 6584 Value = APValue(); 6585 return true; 6586 } 6587 6588 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6589 if (!RD) { 6590 if (T.isDestructedType()) { 6591 Info.FFDiag(CallRange.getBegin(), 6592 diag::note_constexpr_unsupported_destruction) 6593 << T; 6594 return false; 6595 } 6596 6597 Value = APValue(); 6598 return true; 6599 } 6600 6601 if (RD->getNumVBases()) { 6602 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD; 6603 return false; 6604 } 6605 6606 const CXXDestructorDecl *DD = RD->getDestructor(); 6607 if (!DD && !RD->hasTrivialDestructor()) { 6608 Info.FFDiag(CallRange.getBegin()); 6609 return false; 6610 } 6611 6612 if (!DD || DD->isTrivial() || 6613 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6614 // A trivial destructor just ends the lifetime of the object. Check for 6615 // this case before checking for a body, because we might not bother 6616 // building a body for a trivial destructor. Note that it doesn't matter 6617 // whether the destructor is constexpr in this case; all trivial 6618 // destructors are constexpr. 6619 // 6620 // If an anonymous union would be destroyed, some enclosing destructor must 6621 // have been explicitly defined, and the anonymous union destruction should 6622 // have no effect. 6623 Value = APValue(); 6624 return true; 6625 } 6626 6627 if (!Info.CheckCallLimit(CallRange.getBegin())) 6628 return false; 6629 6630 const FunctionDecl *Definition = nullptr; 6631 const Stmt *Body = DD->getBody(Definition); 6632 6633 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body)) 6634 return false; 6635 6636 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr, 6637 CallRef()); 6638 6639 // We're now in the period of destruction of this object. 6640 unsigned BasesLeft = RD->getNumBases(); 6641 EvalInfo::EvaluatingDestructorRAII EvalObj( 6642 Info, 6643 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6644 if (!EvalObj.DidInsert) { 6645 // C++2a [class.dtor]p19: 6646 // the behavior is undefined if the destructor is invoked for an object 6647 // whose lifetime has ended 6648 // (Note that formally the lifetime ends when the period of destruction 6649 // begins, even though certain uses of the object remain valid until the 6650 // period of destruction ends.) 6651 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy); 6652 return false; 6653 } 6654 6655 // FIXME: Creating an APValue just to hold a nonexistent return value is 6656 // wasteful. 6657 APValue RetVal; 6658 StmtResult Ret = {RetVal, nullptr}; 6659 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6660 return false; 6661 6662 // A union destructor does not implicitly destroy its members. 6663 if (RD->isUnion()) 6664 return true; 6665 6666 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6667 6668 // We don't have a good way to iterate fields in reverse, so collect all the 6669 // fields first and then walk them backwards. 6670 SmallVector<FieldDecl*, 16> Fields(RD->fields()); 6671 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6672 if (FD->isUnnamedBitfield()) 6673 continue; 6674 6675 LValue Subobject = This; 6676 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6677 return false; 6678 6679 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6680 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue, 6681 FD->getType())) 6682 return false; 6683 } 6684 6685 if (BasesLeft != 0) 6686 EvalObj.startedDestroyingBases(); 6687 6688 // Destroy base classes in reverse order. 6689 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6690 --BasesLeft; 6691 6692 QualType BaseType = Base.getType(); 6693 LValue Subobject = This; 6694 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6695 BaseType->getAsCXXRecordDecl(), &Layout)) 6696 return false; 6697 6698 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6699 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue, 6700 BaseType)) 6701 return false; 6702 } 6703 assert(BasesLeft == 0 && "NumBases was wrong?"); 6704 6705 // The period of destruction ends now. The object is gone. 6706 Value = APValue(); 6707 return true; 6708 } 6709 6710 namespace { 6711 struct DestroyObjectHandler { 6712 EvalInfo &Info; 6713 const Expr *E; 6714 const LValue &This; 6715 const AccessKinds AccessKind; 6716 6717 typedef bool result_type; 6718 bool failed() { return false; } 6719 bool found(APValue &Subobj, QualType SubobjType) { 6720 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj, 6721 SubobjType); 6722 } 6723 bool found(APSInt &Value, QualType SubobjType) { 6724 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6725 return false; 6726 } 6727 bool found(APFloat &Value, QualType SubobjType) { 6728 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6729 return false; 6730 } 6731 }; 6732 } 6733 6734 /// Perform a destructor or pseudo-destructor call on the given object, which 6735 /// might in general not be a complete object. 6736 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6737 const LValue &This, QualType ThisType) { 6738 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6739 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6740 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6741 } 6742 6743 /// Destroy and end the lifetime of the given complete object. 6744 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6745 APValue::LValueBase LVBase, APValue &Value, 6746 QualType T) { 6747 // If we've had an unmodeled side-effect, we can't rely on mutable state 6748 // (such as the object we're about to destroy) being correct. 6749 if (Info.EvalStatus.HasSideEffects) 6750 return false; 6751 6752 LValue LV; 6753 LV.set({LVBase}); 6754 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6755 } 6756 6757 /// Perform a call to 'operator new' or to `__builtin_operator_new'. 6758 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6759 LValue &Result) { 6760 if (Info.checkingPotentialConstantExpression() || 6761 Info.SpeculativeEvaluationDepth) 6762 return false; 6763 6764 // This is permitted only within a call to std::allocator<T>::allocate. 6765 auto Caller = Info.getStdAllocatorCaller("allocate"); 6766 if (!Caller) { 6767 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6768 ? diag::note_constexpr_new_untyped 6769 : diag::note_constexpr_new); 6770 return false; 6771 } 6772 6773 QualType ElemType = Caller.ElemType; 6774 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6775 Info.FFDiag(E->getExprLoc(), 6776 diag::note_constexpr_new_not_complete_object_type) 6777 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6778 return false; 6779 } 6780 6781 APSInt ByteSize; 6782 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6783 return false; 6784 bool IsNothrow = false; 6785 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6786 EvaluateIgnoredValue(Info, E->getArg(I)); 6787 IsNothrow |= E->getType()->isNothrowT(); 6788 } 6789 6790 CharUnits ElemSize; 6791 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6792 return false; 6793 APInt Size, Remainder; 6794 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6795 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6796 if (Remainder != 0) { 6797 // This likely indicates a bug in the implementation of 'std::allocator'. 6798 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6799 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6800 return false; 6801 } 6802 6803 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(), 6804 Size.getZExtValue(), /*Diag=*/!IsNothrow)) { 6805 if (IsNothrow) { 6806 Result.setNull(Info.Ctx, E->getType()); 6807 return true; 6808 } 6809 return false; 6810 } 6811 6812 QualType AllocType = Info.Ctx.getConstantArrayType( 6813 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0); 6814 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6815 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6816 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6817 return true; 6818 } 6819 6820 static bool hasVirtualDestructor(QualType T) { 6821 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6822 if (CXXDestructorDecl *DD = RD->getDestructor()) 6823 return DD->isVirtual(); 6824 return false; 6825 } 6826 6827 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6828 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6829 if (CXXDestructorDecl *DD = RD->getDestructor()) 6830 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6831 return nullptr; 6832 } 6833 6834 /// Check that the given object is a suitable pointer to a heap allocation that 6835 /// still exists and is of the right kind for the purpose of a deletion. 6836 /// 6837 /// On success, returns the heap allocation to deallocate. On failure, produces 6838 /// a diagnostic and returns std::nullopt. 6839 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6840 const LValue &Pointer, 6841 DynAlloc::Kind DeallocKind) { 6842 auto PointerAsString = [&] { 6843 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6844 }; 6845 6846 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6847 if (!DA) { 6848 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6849 << PointerAsString(); 6850 if (Pointer.Base) 6851 NoteLValueLocation(Info, Pointer.Base); 6852 return std::nullopt; 6853 } 6854 6855 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6856 if (!Alloc) { 6857 Info.FFDiag(E, diag::note_constexpr_double_delete); 6858 return std::nullopt; 6859 } 6860 6861 if (DeallocKind != (*Alloc)->getKind()) { 6862 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6863 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6864 << DeallocKind << (*Alloc)->getKind() << AllocType; 6865 NoteLValueLocation(Info, Pointer.Base); 6866 return std::nullopt; 6867 } 6868 6869 bool Subobject = false; 6870 if (DeallocKind == DynAlloc::New) { 6871 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6872 Pointer.Designator.isOnePastTheEnd(); 6873 } else { 6874 Subobject = Pointer.Designator.Entries.size() != 1 || 6875 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6876 } 6877 if (Subobject) { 6878 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6879 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6880 return std::nullopt; 6881 } 6882 6883 return Alloc; 6884 } 6885 6886 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6887 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6888 if (Info.checkingPotentialConstantExpression() || 6889 Info.SpeculativeEvaluationDepth) 6890 return false; 6891 6892 // This is permitted only within a call to std::allocator<T>::deallocate. 6893 if (!Info.getStdAllocatorCaller("deallocate")) { 6894 Info.FFDiag(E->getExprLoc()); 6895 return true; 6896 } 6897 6898 LValue Pointer; 6899 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6900 return false; 6901 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6902 EvaluateIgnoredValue(Info, E->getArg(I)); 6903 6904 if (Pointer.Designator.Invalid) 6905 return false; 6906 6907 // Deleting a null pointer would have no effect, but it's not permitted by 6908 // std::allocator<T>::deallocate's contract. 6909 if (Pointer.isNullPointer()) { 6910 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6911 return true; 6912 } 6913 6914 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6915 return false; 6916 6917 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6918 return true; 6919 } 6920 6921 //===----------------------------------------------------------------------===// 6922 // Generic Evaluation 6923 //===----------------------------------------------------------------------===// 6924 namespace { 6925 6926 class BitCastBuffer { 6927 // FIXME: We're going to need bit-level granularity when we support 6928 // bit-fields. 6929 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6930 // we don't support a host or target where that is the case. Still, we should 6931 // use a more generic type in case we ever do. 6932 SmallVector<std::optional<unsigned char>, 32> Bytes; 6933 6934 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6935 "Need at least 8 bit unsigned char"); 6936 6937 bool TargetIsLittleEndian; 6938 6939 public: 6940 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6941 : Bytes(Width.getQuantity()), 6942 TargetIsLittleEndian(TargetIsLittleEndian) {} 6943 6944 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width, 6945 SmallVectorImpl<unsigned char> &Output) const { 6946 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6947 // If a byte of an integer is uninitialized, then the whole integer is 6948 // uninitialized. 6949 if (!Bytes[I.getQuantity()]) 6950 return false; 6951 Output.push_back(*Bytes[I.getQuantity()]); 6952 } 6953 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6954 std::reverse(Output.begin(), Output.end()); 6955 return true; 6956 } 6957 6958 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6959 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6960 std::reverse(Input.begin(), Input.end()); 6961 6962 size_t Index = 0; 6963 for (unsigned char Byte : Input) { 6964 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6965 Bytes[Offset.getQuantity() + Index] = Byte; 6966 ++Index; 6967 } 6968 } 6969 6970 size_t size() { return Bytes.size(); } 6971 }; 6972 6973 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6974 /// target would represent the value at runtime. 6975 class APValueToBufferConverter { 6976 EvalInfo &Info; 6977 BitCastBuffer Buffer; 6978 const CastExpr *BCE; 6979 6980 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6981 const CastExpr *BCE) 6982 : Info(Info), 6983 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6984 BCE(BCE) {} 6985 6986 bool visit(const APValue &Val, QualType Ty) { 6987 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6988 } 6989 6990 // Write out Val with type Ty into Buffer starting at Offset. 6991 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6992 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6993 6994 // As a special case, nullptr_t has an indeterminate value. 6995 if (Ty->isNullPtrType()) 6996 return true; 6997 6998 // Dig through Src to find the byte at SrcOffset. 6999 switch (Val.getKind()) { 7000 case APValue::Indeterminate: 7001 case APValue::None: 7002 return true; 7003 7004 case APValue::Int: 7005 return visitInt(Val.getInt(), Ty, Offset); 7006 case APValue::Float: 7007 return visitFloat(Val.getFloat(), Ty, Offset); 7008 case APValue::Array: 7009 return visitArray(Val, Ty, Offset); 7010 case APValue::Struct: 7011 return visitRecord(Val, Ty, Offset); 7012 case APValue::Vector: 7013 return visitVector(Val, Ty, Offset); 7014 7015 case APValue::ComplexInt: 7016 case APValue::ComplexFloat: 7017 case APValue::FixedPoint: 7018 // FIXME: We should support these. 7019 7020 case APValue::Union: 7021 case APValue::MemberPointer: 7022 case APValue::AddrLabelDiff: { 7023 Info.FFDiag(BCE->getBeginLoc(), 7024 diag::note_constexpr_bit_cast_unsupported_type) 7025 << Ty; 7026 return false; 7027 } 7028 7029 case APValue::LValue: 7030 llvm_unreachable("LValue subobject in bit_cast?"); 7031 } 7032 llvm_unreachable("Unhandled APValue::ValueKind"); 7033 } 7034 7035 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 7036 const RecordDecl *RD = Ty->getAsRecordDecl(); 7037 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7038 7039 // Visit the base classes. 7040 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7041 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7042 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7043 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7044 7045 if (!visitRecord(Val.getStructBase(I), BS.getType(), 7046 Layout.getBaseClassOffset(BaseDecl) + Offset)) 7047 return false; 7048 } 7049 } 7050 7051 // Visit the fields. 7052 unsigned FieldIdx = 0; 7053 for (FieldDecl *FD : RD->fields()) { 7054 if (FD->isBitField()) { 7055 Info.FFDiag(BCE->getBeginLoc(), 7056 diag::note_constexpr_bit_cast_unsupported_bitfield); 7057 return false; 7058 } 7059 7060 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7061 7062 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 7063 "only bit-fields can have sub-char alignment"); 7064 CharUnits FieldOffset = 7065 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 7066 QualType FieldTy = FD->getType(); 7067 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 7068 return false; 7069 ++FieldIdx; 7070 } 7071 7072 return true; 7073 } 7074 7075 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 7076 const auto *CAT = 7077 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 7078 if (!CAT) 7079 return false; 7080 7081 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 7082 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 7083 unsigned ArraySize = Val.getArraySize(); 7084 // First, initialize the initialized elements. 7085 for (unsigned I = 0; I != NumInitializedElts; ++I) { 7086 const APValue &SubObj = Val.getArrayInitializedElt(I); 7087 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 7088 return false; 7089 } 7090 7091 // Next, initialize the rest of the array using the filler. 7092 if (Val.hasArrayFiller()) { 7093 const APValue &Filler = Val.getArrayFiller(); 7094 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 7095 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 7096 return false; 7097 } 7098 } 7099 7100 return true; 7101 } 7102 7103 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) { 7104 const VectorType *VTy = Ty->castAs<VectorType>(); 7105 QualType EltTy = VTy->getElementType(); 7106 unsigned NElts = VTy->getNumElements(); 7107 unsigned EltSize = 7108 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy); 7109 7110 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) { 7111 // The vector's size in bits is not a multiple of the target's byte size, 7112 // so its layout is unspecified. For now, we'll simply treat these cases 7113 // as unsupported (this should only be possible with OpenCL bool vectors 7114 // whose element count isn't a multiple of the byte size). 7115 Info.FFDiag(BCE->getBeginLoc(), 7116 diag::note_constexpr_bit_cast_invalid_vector) 7117 << Ty.getCanonicalType() << EltSize << NElts 7118 << Info.Ctx.getCharWidth(); 7119 return false; 7120 } 7121 7122 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) == 7123 &APFloat::x87DoubleExtended()) { 7124 // The layout for x86_fp80 vectors seems to be handled very inconsistently 7125 // by both clang and LLVM, so for now we won't allow bit_casts involving 7126 // it in a constexpr context. 7127 Info.FFDiag(BCE->getBeginLoc(), 7128 diag::note_constexpr_bit_cast_unsupported_type) 7129 << EltTy; 7130 return false; 7131 } 7132 7133 if (VTy->isExtVectorBoolType()) { 7134 // Special handling for OpenCL bool vectors: 7135 // Since these vectors are stored as packed bits, but we can't write 7136 // individual bits to the BitCastBuffer, we'll buffer all of the elements 7137 // together into an appropriately sized APInt and write them all out at 7138 // once. Because we don't accept vectors where NElts * EltSize isn't a 7139 // multiple of the char size, there will be no padding space, so we don't 7140 // have to worry about writing data which should have been left 7141 // uninitialized. 7142 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 7143 7144 llvm::APInt Res = llvm::APInt::getZero(NElts); 7145 for (unsigned I = 0; I < NElts; ++I) { 7146 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt(); 7147 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 && 7148 "bool vector element must be 1-bit unsigned integer!"); 7149 7150 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I); 7151 } 7152 7153 SmallVector<uint8_t, 8> Bytes(NElts / 8); 7154 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8); 7155 Buffer.writeObject(Offset, Bytes); 7156 } else { 7157 // Iterate over each of the elements and write them out to the buffer at 7158 // the appropriate offset. 7159 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy); 7160 for (unsigned I = 0; I < NElts; ++I) { 7161 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars)) 7162 return false; 7163 } 7164 } 7165 7166 return true; 7167 } 7168 7169 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 7170 APSInt AdjustedVal = Val; 7171 unsigned Width = AdjustedVal.getBitWidth(); 7172 if (Ty->isBooleanType()) { 7173 Width = Info.Ctx.getTypeSize(Ty); 7174 AdjustedVal = AdjustedVal.extend(Width); 7175 } 7176 7177 SmallVector<uint8_t, 8> Bytes(Width / 8); 7178 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 7179 Buffer.writeObject(Offset, Bytes); 7180 return true; 7181 } 7182 7183 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 7184 APSInt AsInt(Val.bitcastToAPInt()); 7185 return visitInt(AsInt, Ty, Offset); 7186 } 7187 7188 public: 7189 static std::optional<BitCastBuffer> 7190 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) { 7191 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 7192 APValueToBufferConverter Converter(Info, DstSize, BCE); 7193 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 7194 return std::nullopt; 7195 return Converter.Buffer; 7196 } 7197 }; 7198 7199 /// Write an BitCastBuffer into an APValue. 7200 class BufferToAPValueConverter { 7201 EvalInfo &Info; 7202 const BitCastBuffer &Buffer; 7203 const CastExpr *BCE; 7204 7205 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 7206 const CastExpr *BCE) 7207 : Info(Info), Buffer(Buffer), BCE(BCE) {} 7208 7209 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 7210 // with an invalid type, so anything left is a deficiency on our part (FIXME). 7211 // Ideally this will be unreachable. 7212 std::nullopt_t unsupportedType(QualType Ty) { 7213 Info.FFDiag(BCE->getBeginLoc(), 7214 diag::note_constexpr_bit_cast_unsupported_type) 7215 << Ty; 7216 return std::nullopt; 7217 } 7218 7219 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) { 7220 Info.FFDiag(BCE->getBeginLoc(), 7221 diag::note_constexpr_bit_cast_unrepresentable_value) 7222 << Ty << toString(Val, /*Radix=*/10); 7223 return std::nullopt; 7224 } 7225 7226 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 7227 const EnumType *EnumSugar = nullptr) { 7228 if (T->isNullPtrType()) { 7229 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 7230 return APValue((Expr *)nullptr, 7231 /*Offset=*/CharUnits::fromQuantity(NullValue), 7232 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 7233 } 7234 7235 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 7236 7237 // Work around floating point types that contain unused padding bytes. This 7238 // is really just `long double` on x86, which is the only fundamental type 7239 // with padding bytes. 7240 if (T->isRealFloatingType()) { 7241 const llvm::fltSemantics &Semantics = 7242 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7243 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 7244 assert(NumBits % 8 == 0); 7245 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 7246 if (NumBytes != SizeOf) 7247 SizeOf = NumBytes; 7248 } 7249 7250 SmallVector<uint8_t, 8> Bytes; 7251 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7252 // If this is std::byte or unsigned char, then its okay to store an 7253 // indeterminate value. 7254 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7255 bool IsUChar = 7256 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7257 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7258 if (!IsStdByte && !IsUChar) { 7259 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7260 Info.FFDiag(BCE->getExprLoc(), 7261 diag::note_constexpr_bit_cast_indet_dest) 7262 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7263 return std::nullopt; 7264 } 7265 7266 return APValue::IndeterminateValue(); 7267 } 7268 7269 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7270 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7271 7272 if (T->isIntegralOrEnumerationType()) { 7273 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7274 7275 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7276 if (IntWidth != Val.getBitWidth()) { 7277 APSInt Truncated = Val.trunc(IntWidth); 7278 if (Truncated.extend(Val.getBitWidth()) != Val) 7279 return unrepresentableValue(QualType(T, 0), Val); 7280 Val = Truncated; 7281 } 7282 7283 return APValue(Val); 7284 } 7285 7286 if (T->isRealFloatingType()) { 7287 const llvm::fltSemantics &Semantics = 7288 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7289 return APValue(APFloat(Semantics, Val)); 7290 } 7291 7292 return unsupportedType(QualType(T, 0)); 7293 } 7294 7295 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7296 const RecordDecl *RD = RTy->getAsRecordDecl(); 7297 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7298 7299 unsigned NumBases = 0; 7300 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7301 NumBases = CXXRD->getNumBases(); 7302 7303 APValue ResultVal(APValue::UninitStruct(), NumBases, 7304 std::distance(RD->field_begin(), RD->field_end())); 7305 7306 // Visit the base classes. 7307 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7308 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7309 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7310 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7311 if (BaseDecl->isEmpty() || 7312 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7313 continue; 7314 7315 std::optional<APValue> SubObj = visitType( 7316 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7317 if (!SubObj) 7318 return std::nullopt; 7319 ResultVal.getStructBase(I) = *SubObj; 7320 } 7321 } 7322 7323 // Visit the fields. 7324 unsigned FieldIdx = 0; 7325 for (FieldDecl *FD : RD->fields()) { 7326 // FIXME: We don't currently support bit-fields. A lot of the logic for 7327 // this is in CodeGen, so we need to factor it around. 7328 if (FD->isBitField()) { 7329 Info.FFDiag(BCE->getBeginLoc(), 7330 diag::note_constexpr_bit_cast_unsupported_bitfield); 7331 return std::nullopt; 7332 } 7333 7334 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7335 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7336 7337 CharUnits FieldOffset = 7338 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7339 Offset; 7340 QualType FieldTy = FD->getType(); 7341 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7342 if (!SubObj) 7343 return std::nullopt; 7344 ResultVal.getStructField(FieldIdx) = *SubObj; 7345 ++FieldIdx; 7346 } 7347 7348 return ResultVal; 7349 } 7350 7351 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7352 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7353 assert(!RepresentationType.isNull() && 7354 "enum forward decl should be caught by Sema"); 7355 const auto *AsBuiltin = 7356 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7357 // Recurse into the underlying type. Treat std::byte transparently as 7358 // unsigned char. 7359 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7360 } 7361 7362 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7363 size_t Size = Ty->getSize().getLimitedValue(); 7364 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7365 7366 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7367 for (size_t I = 0; I != Size; ++I) { 7368 std::optional<APValue> ElementValue = 7369 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7370 if (!ElementValue) 7371 return std::nullopt; 7372 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7373 } 7374 7375 return ArrayValue; 7376 } 7377 7378 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) { 7379 QualType EltTy = VTy->getElementType(); 7380 unsigned NElts = VTy->getNumElements(); 7381 unsigned EltSize = 7382 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy); 7383 7384 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) { 7385 // The vector's size in bits is not a multiple of the target's byte size, 7386 // so its layout is unspecified. For now, we'll simply treat these cases 7387 // as unsupported (this should only be possible with OpenCL bool vectors 7388 // whose element count isn't a multiple of the byte size). 7389 Info.FFDiag(BCE->getBeginLoc(), 7390 diag::note_constexpr_bit_cast_invalid_vector) 7391 << QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth(); 7392 return std::nullopt; 7393 } 7394 7395 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) == 7396 &APFloat::x87DoubleExtended()) { 7397 // The layout for x86_fp80 vectors seems to be handled very inconsistently 7398 // by both clang and LLVM, so for now we won't allow bit_casts involving 7399 // it in a constexpr context. 7400 Info.FFDiag(BCE->getBeginLoc(), 7401 diag::note_constexpr_bit_cast_unsupported_type) 7402 << EltTy; 7403 return std::nullopt; 7404 } 7405 7406 SmallVector<APValue, 4> Elts; 7407 Elts.reserve(NElts); 7408 if (VTy->isExtVectorBoolType()) { 7409 // Special handling for OpenCL bool vectors: 7410 // Since these vectors are stored as packed bits, but we can't read 7411 // individual bits from the BitCastBuffer, we'll buffer all of the 7412 // elements together into an appropriately sized APInt and write them all 7413 // out at once. Because we don't accept vectors where NElts * EltSize 7414 // isn't a multiple of the char size, there will be no padding space, so 7415 // we don't have to worry about reading any padding data which didn't 7416 // actually need to be accessed. 7417 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 7418 7419 SmallVector<uint8_t, 8> Bytes; 7420 Bytes.reserve(NElts / 8); 7421 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes)) 7422 return std::nullopt; 7423 7424 APSInt SValInt(NElts, true); 7425 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size()); 7426 7427 for (unsigned I = 0; I < NElts; ++I) { 7428 llvm::APInt Elt = 7429 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize); 7430 Elts.emplace_back( 7431 APSInt(std::move(Elt), !EltTy->isSignedIntegerType())); 7432 } 7433 } else { 7434 // Iterate over each of the elements and read them from the buffer at 7435 // the appropriate offset. 7436 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy); 7437 for (unsigned I = 0; I < NElts; ++I) { 7438 std::optional<APValue> EltValue = 7439 visitType(EltTy, Offset + I * EltSizeChars); 7440 if (!EltValue) 7441 return std::nullopt; 7442 Elts.push_back(std::move(*EltValue)); 7443 } 7444 } 7445 7446 return APValue(Elts.data(), Elts.size()); 7447 } 7448 7449 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7450 return unsupportedType(QualType(Ty, 0)); 7451 } 7452 7453 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7454 QualType Can = Ty.getCanonicalType(); 7455 7456 switch (Can->getTypeClass()) { 7457 #define TYPE(Class, Base) \ 7458 case Type::Class: \ 7459 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7460 #define ABSTRACT_TYPE(Class, Base) 7461 #define NON_CANONICAL_TYPE(Class, Base) \ 7462 case Type::Class: \ 7463 llvm_unreachable("non-canonical type should be impossible!"); 7464 #define DEPENDENT_TYPE(Class, Base) \ 7465 case Type::Class: \ 7466 llvm_unreachable( \ 7467 "dependent types aren't supported in the constant evaluator!"); 7468 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7469 case Type::Class: \ 7470 llvm_unreachable("either dependent or not canonical!"); 7471 #include "clang/AST/TypeNodes.inc" 7472 } 7473 llvm_unreachable("Unhandled Type::TypeClass"); 7474 } 7475 7476 public: 7477 // Pull out a full value of type DstType. 7478 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7479 const CastExpr *BCE) { 7480 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7481 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7482 } 7483 }; 7484 7485 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7486 QualType Ty, EvalInfo *Info, 7487 const ASTContext &Ctx, 7488 bool CheckingDest) { 7489 Ty = Ty.getCanonicalType(); 7490 7491 auto diag = [&](int Reason) { 7492 if (Info) 7493 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7494 << CheckingDest << (Reason == 4) << Reason; 7495 return false; 7496 }; 7497 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7498 if (Info) 7499 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7500 << NoteTy << Construct << Ty; 7501 return false; 7502 }; 7503 7504 if (Ty->isUnionType()) 7505 return diag(0); 7506 if (Ty->isPointerType()) 7507 return diag(1); 7508 if (Ty->isMemberPointerType()) 7509 return diag(2); 7510 if (Ty.isVolatileQualified()) 7511 return diag(3); 7512 7513 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7514 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7515 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7516 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7517 CheckingDest)) 7518 return note(1, BS.getType(), BS.getBeginLoc()); 7519 } 7520 for (FieldDecl *FD : Record->fields()) { 7521 if (FD->getType()->isReferenceType()) 7522 return diag(4); 7523 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7524 CheckingDest)) 7525 return note(0, FD->getType(), FD->getBeginLoc()); 7526 } 7527 } 7528 7529 if (Ty->isArrayType() && 7530 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7531 Info, Ctx, CheckingDest)) 7532 return false; 7533 7534 return true; 7535 } 7536 7537 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7538 const ASTContext &Ctx, 7539 const CastExpr *BCE) { 7540 bool DestOK = checkBitCastConstexprEligibilityType( 7541 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7542 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7543 BCE->getBeginLoc(), 7544 BCE->getSubExpr()->getType(), Info, Ctx, false); 7545 return SourceOK; 7546 } 7547 7548 static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7549 const APValue &SourceRValue, 7550 const CastExpr *BCE) { 7551 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7552 "no host or target supports non 8-bit chars"); 7553 7554 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7555 return false; 7556 7557 // Read out SourceValue into a char buffer. 7558 std::optional<BitCastBuffer> Buffer = 7559 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7560 if (!Buffer) 7561 return false; 7562 7563 // Write out the buffer into a new APValue. 7564 std::optional<APValue> MaybeDestValue = 7565 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7566 if (!MaybeDestValue) 7567 return false; 7568 7569 DestValue = std::move(*MaybeDestValue); 7570 return true; 7571 } 7572 7573 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7574 APValue &SourceValue, 7575 const CastExpr *BCE) { 7576 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7577 "no host or target supports non 8-bit chars"); 7578 assert(SourceValue.isLValue() && 7579 "LValueToRValueBitcast requires an lvalue operand!"); 7580 7581 LValue SourceLValue; 7582 APValue SourceRValue; 7583 SourceLValue.setFrom(Info.Ctx, SourceValue); 7584 if (!handleLValueToRValueConversion( 7585 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7586 SourceRValue, /*WantObjectRepresentation=*/true)) 7587 return false; 7588 7589 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE); 7590 } 7591 7592 template <class Derived> 7593 class ExprEvaluatorBase 7594 : public ConstStmtVisitor<Derived, bool> { 7595 private: 7596 Derived &getDerived() { return static_cast<Derived&>(*this); } 7597 bool DerivedSuccess(const APValue &V, const Expr *E) { 7598 return getDerived().Success(V, E); 7599 } 7600 bool DerivedZeroInitialization(const Expr *E) { 7601 return getDerived().ZeroInitialization(E); 7602 } 7603 7604 // Check whether a conditional operator with a non-constant condition is a 7605 // potential constant expression. If neither arm is a potential constant 7606 // expression, then the conditional operator is not either. 7607 template<typename ConditionalOperator> 7608 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7609 assert(Info.checkingPotentialConstantExpression()); 7610 7611 // Speculatively evaluate both arms. 7612 SmallVector<PartialDiagnosticAt, 8> Diag; 7613 { 7614 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7615 StmtVisitorTy::Visit(E->getFalseExpr()); 7616 if (Diag.empty()) 7617 return; 7618 } 7619 7620 { 7621 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7622 Diag.clear(); 7623 StmtVisitorTy::Visit(E->getTrueExpr()); 7624 if (Diag.empty()) 7625 return; 7626 } 7627 7628 Error(E, diag::note_constexpr_conditional_never_const); 7629 } 7630 7631 7632 template<typename ConditionalOperator> 7633 bool HandleConditionalOperator(const ConditionalOperator *E) { 7634 bool BoolResult; 7635 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7636 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7637 CheckPotentialConstantConditional(E); 7638 return false; 7639 } 7640 if (Info.noteFailure()) { 7641 StmtVisitorTy::Visit(E->getTrueExpr()); 7642 StmtVisitorTy::Visit(E->getFalseExpr()); 7643 } 7644 return false; 7645 } 7646 7647 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7648 return StmtVisitorTy::Visit(EvalExpr); 7649 } 7650 7651 protected: 7652 EvalInfo &Info; 7653 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7654 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7655 7656 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7657 return Info.CCEDiag(E, D); 7658 } 7659 7660 bool ZeroInitialization(const Expr *E) { return Error(E); } 7661 7662 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) { 7663 unsigned BuiltinOp = E->getBuiltinCallee(); 7664 return BuiltinOp != 0 && 7665 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp); 7666 } 7667 7668 public: 7669 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7670 7671 EvalInfo &getEvalInfo() { return Info; } 7672 7673 /// Report an evaluation error. This should only be called when an error is 7674 /// first discovered. When propagating an error, just return false. 7675 bool Error(const Expr *E, diag::kind D) { 7676 Info.FFDiag(E, D) << E->getSourceRange(); 7677 return false; 7678 } 7679 bool Error(const Expr *E) { 7680 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7681 } 7682 7683 bool VisitStmt(const Stmt *) { 7684 llvm_unreachable("Expression evaluator should not be called on stmts"); 7685 } 7686 bool VisitExpr(const Expr *E) { 7687 return Error(E); 7688 } 7689 7690 bool VisitPredefinedExpr(const PredefinedExpr *E) { 7691 return StmtVisitorTy::Visit(E->getFunctionName()); 7692 } 7693 bool VisitConstantExpr(const ConstantExpr *E) { 7694 if (E->hasAPValueResult()) 7695 return DerivedSuccess(E->getAPValueResult(), E); 7696 7697 return StmtVisitorTy::Visit(E->getSubExpr()); 7698 } 7699 7700 bool VisitParenExpr(const ParenExpr *E) 7701 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7702 bool VisitUnaryExtension(const UnaryOperator *E) 7703 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7704 bool VisitUnaryPlus(const UnaryOperator *E) 7705 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7706 bool VisitChooseExpr(const ChooseExpr *E) 7707 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7708 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7709 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7710 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7711 { return StmtVisitorTy::Visit(E->getReplacement()); } 7712 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7713 TempVersionRAII RAII(*Info.CurrentCall); 7714 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7715 return StmtVisitorTy::Visit(E->getExpr()); 7716 } 7717 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7718 TempVersionRAII RAII(*Info.CurrentCall); 7719 // The initializer may not have been parsed yet, or might be erroneous. 7720 if (!E->getExpr()) 7721 return Error(E); 7722 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7723 return StmtVisitorTy::Visit(E->getExpr()); 7724 } 7725 7726 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7727 FullExpressionRAII Scope(Info); 7728 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7729 } 7730 7731 // Temporaries are registered when created, so we don't care about 7732 // CXXBindTemporaryExpr. 7733 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7734 return StmtVisitorTy::Visit(E->getSubExpr()); 7735 } 7736 7737 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7738 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7739 return static_cast<Derived*>(this)->VisitCastExpr(E); 7740 } 7741 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7742 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7743 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7744 return static_cast<Derived*>(this)->VisitCastExpr(E); 7745 } 7746 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7747 return static_cast<Derived*>(this)->VisitCastExpr(E); 7748 } 7749 7750 bool VisitBinaryOperator(const BinaryOperator *E) { 7751 switch (E->getOpcode()) { 7752 default: 7753 return Error(E); 7754 7755 case BO_Comma: 7756 VisitIgnoredValue(E->getLHS()); 7757 return StmtVisitorTy::Visit(E->getRHS()); 7758 7759 case BO_PtrMemD: 7760 case BO_PtrMemI: { 7761 LValue Obj; 7762 if (!HandleMemberPointerAccess(Info, E, Obj)) 7763 return false; 7764 APValue Result; 7765 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7766 return false; 7767 return DerivedSuccess(Result, E); 7768 } 7769 } 7770 } 7771 7772 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7773 return StmtVisitorTy::Visit(E->getSemanticForm()); 7774 } 7775 7776 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7777 // Evaluate and cache the common expression. We treat it as a temporary, 7778 // even though it's not quite the same thing. 7779 LValue CommonLV; 7780 if (!Evaluate(Info.CurrentCall->createTemporary( 7781 E->getOpaqueValue(), 7782 getStorageType(Info.Ctx, E->getOpaqueValue()), 7783 ScopeKind::FullExpression, CommonLV), 7784 Info, E->getCommon())) 7785 return false; 7786 7787 return HandleConditionalOperator(E); 7788 } 7789 7790 bool VisitConditionalOperator(const ConditionalOperator *E) { 7791 bool IsBcpCall = false; 7792 // If the condition (ignoring parens) is a __builtin_constant_p call, 7793 // the result is a constant expression if it can be folded without 7794 // side-effects. This is an important GNU extension. See GCC PR38377 7795 // for discussion. 7796 if (const CallExpr *CallCE = 7797 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7798 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7799 IsBcpCall = true; 7800 7801 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7802 // constant expression; we can't check whether it's potentially foldable. 7803 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7804 // it would return 'false' in this mode. 7805 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7806 return false; 7807 7808 FoldConstant Fold(Info, IsBcpCall); 7809 if (!HandleConditionalOperator(E)) { 7810 Fold.keepDiagnostics(); 7811 return false; 7812 } 7813 7814 return true; 7815 } 7816 7817 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7818 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E); 7819 Value && !Value->isAbsent()) 7820 return DerivedSuccess(*Value, E); 7821 7822 const Expr *Source = E->getSourceExpr(); 7823 if (!Source) 7824 return Error(E); 7825 if (Source == E) { 7826 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7827 return Error(E); 7828 } 7829 return StmtVisitorTy::Visit(Source); 7830 } 7831 7832 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7833 for (const Expr *SemE : E->semantics()) { 7834 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7835 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7836 // result expression: there could be two different LValues that would 7837 // refer to the same object in that case, and we can't model that. 7838 if (SemE == E->getResultExpr()) 7839 return Error(E); 7840 7841 // Unique OVEs get evaluated if and when we encounter them when 7842 // emitting the rest of the semantic form, rather than eagerly. 7843 if (OVE->isUnique()) 7844 continue; 7845 7846 LValue LV; 7847 if (!Evaluate(Info.CurrentCall->createTemporary( 7848 OVE, getStorageType(Info.Ctx, OVE), 7849 ScopeKind::FullExpression, LV), 7850 Info, OVE->getSourceExpr())) 7851 return false; 7852 } else if (SemE == E->getResultExpr()) { 7853 if (!StmtVisitorTy::Visit(SemE)) 7854 return false; 7855 } else { 7856 if (!EvaluateIgnoredValue(Info, SemE)) 7857 return false; 7858 } 7859 } 7860 return true; 7861 } 7862 7863 bool VisitCallExpr(const CallExpr *E) { 7864 APValue Result; 7865 if (!handleCallExpr(E, Result, nullptr)) 7866 return false; 7867 return DerivedSuccess(Result, E); 7868 } 7869 7870 bool handleCallExpr(const CallExpr *E, APValue &Result, 7871 const LValue *ResultSlot) { 7872 CallScopeRAII CallScope(Info); 7873 7874 const Expr *Callee = E->getCallee()->IgnoreParens(); 7875 QualType CalleeType = Callee->getType(); 7876 7877 const FunctionDecl *FD = nullptr; 7878 LValue *This = nullptr, ThisVal; 7879 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs()); 7880 bool HasQualifier = false; 7881 7882 CallRef Call; 7883 7884 // Extract function decl and 'this' pointer from the callee. 7885 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7886 const CXXMethodDecl *Member = nullptr; 7887 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7888 // Explicit bound member calls, such as x.f() or p->g(); 7889 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7890 return false; 7891 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7892 if (!Member) 7893 return Error(Callee); 7894 This = &ThisVal; 7895 HasQualifier = ME->hasQualifier(); 7896 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7897 // Indirect bound member calls ('.*' or '->*'). 7898 const ValueDecl *D = 7899 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7900 if (!D) 7901 return false; 7902 Member = dyn_cast<CXXMethodDecl>(D); 7903 if (!Member) 7904 return Error(Callee); 7905 This = &ThisVal; 7906 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7907 if (!Info.getLangOpts().CPlusPlus20) 7908 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7909 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7910 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7911 } else 7912 return Error(Callee); 7913 FD = Member; 7914 } else if (CalleeType->isFunctionPointerType()) { 7915 LValue CalleeLV; 7916 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7917 return false; 7918 7919 if (!CalleeLV.getLValueOffset().isZero()) 7920 return Error(Callee); 7921 if (CalleeLV.isNullPointer()) { 7922 Info.FFDiag(Callee, diag::note_constexpr_null_callee) 7923 << const_cast<Expr *>(Callee); 7924 return false; 7925 } 7926 FD = dyn_cast_or_null<FunctionDecl>( 7927 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7928 if (!FD) 7929 return Error(Callee); 7930 // Don't call function pointers which have been cast to some other type. 7931 // Per DR (no number yet), the caller and callee can differ in noexcept. 7932 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7933 CalleeType->getPointeeType(), FD->getType())) { 7934 return Error(E); 7935 } 7936 7937 // For an (overloaded) assignment expression, evaluate the RHS before the 7938 // LHS. 7939 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7940 if (OCE && OCE->isAssignmentOp()) { 7941 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7942 Call = Info.CurrentCall->createCall(FD); 7943 bool HasThis = false; 7944 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 7945 HasThis = MD->isImplicitObjectMemberFunction(); 7946 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD, 7947 /*RightToLeft=*/true)) 7948 return false; 7949 } 7950 7951 // Overloaded operator calls to member functions are represented as normal 7952 // calls with '*this' as the first argument. 7953 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7954 if (MD && MD->isImplicitObjectMemberFunction()) { 7955 // FIXME: When selecting an implicit conversion for an overloaded 7956 // operator delete, we sometimes try to evaluate calls to conversion 7957 // operators without a 'this' parameter! 7958 if (Args.empty()) 7959 return Error(E); 7960 7961 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7962 return false; 7963 This = &ThisVal; 7964 7965 // If this is syntactically a simple assignment using a trivial 7966 // assignment operator, start the lifetimes of union members as needed, 7967 // per C++20 [class.union]5. 7968 if (Info.getLangOpts().CPlusPlus20 && OCE && 7969 OCE->getOperator() == OO_Equal && MD->isTrivial() && 7970 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal)) 7971 return false; 7972 7973 Args = Args.slice(1); 7974 } else if (MD && MD->isLambdaStaticInvoker()) { 7975 // Map the static invoker for the lambda back to the call operator. 7976 // Conveniently, we don't have to slice out the 'this' argument (as is 7977 // being done for the non-static case), since a static member function 7978 // doesn't have an implicit argument passed in. 7979 const CXXRecordDecl *ClosureClass = MD->getParent(); 7980 assert( 7981 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7982 "Number of captures must be zero for conversion to function-ptr"); 7983 7984 const CXXMethodDecl *LambdaCallOp = 7985 ClosureClass->getLambdaCallOperator(); 7986 7987 // Set 'FD', the function that will be called below, to the call 7988 // operator. If the closure object represents a generic lambda, find 7989 // the corresponding specialization of the call operator. 7990 7991 if (ClosureClass->isGenericLambda()) { 7992 assert(MD->isFunctionTemplateSpecialization() && 7993 "A generic lambda's static-invoker function must be a " 7994 "template specialization"); 7995 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7996 FunctionTemplateDecl *CallOpTemplate = 7997 LambdaCallOp->getDescribedFunctionTemplate(); 7998 void *InsertPos = nullptr; 7999 FunctionDecl *CorrespondingCallOpSpecialization = 8000 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 8001 assert(CorrespondingCallOpSpecialization && 8002 "We must always have a function call operator specialization " 8003 "that corresponds to our static invoker specialization"); 8004 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 8005 } else 8006 FD = LambdaCallOp; 8007 } else if (FD->isReplaceableGlobalAllocationFunction()) { 8008 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 8009 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 8010 LValue Ptr; 8011 if (!HandleOperatorNewCall(Info, E, Ptr)) 8012 return false; 8013 Ptr.moveInto(Result); 8014 return CallScope.destroy(); 8015 } else { 8016 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 8017 } 8018 } 8019 } else 8020 return Error(E); 8021 8022 // Evaluate the arguments now if we've not already done so. 8023 if (!Call) { 8024 Call = Info.CurrentCall->createCall(FD); 8025 if (!EvaluateArgs(Args, Call, Info, FD)) 8026 return false; 8027 } 8028 8029 SmallVector<QualType, 4> CovariantAdjustmentPath; 8030 if (This) { 8031 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 8032 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 8033 // Perform virtual dispatch, if necessary. 8034 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 8035 CovariantAdjustmentPath); 8036 if (!FD) 8037 return false; 8038 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) { 8039 // Check that the 'this' pointer points to an object of the right type. 8040 // FIXME: If this is an assignment operator call, we may need to change 8041 // the active union member before we check this. 8042 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 8043 return false; 8044 } 8045 } 8046 8047 // Destructor calls are different enough that they have their own codepath. 8048 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 8049 assert(This && "no 'this' pointer for destructor call"); 8050 return HandleDestruction(Info, E, *This, 8051 Info.Ctx.getRecordType(DD->getParent())) && 8052 CallScope.destroy(); 8053 } 8054 8055 const FunctionDecl *Definition = nullptr; 8056 Stmt *Body = FD->getBody(Definition); 8057 8058 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 8059 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call, 8060 Body, Info, Result, ResultSlot)) 8061 return false; 8062 8063 if (!CovariantAdjustmentPath.empty() && 8064 !HandleCovariantReturnAdjustment(Info, E, Result, 8065 CovariantAdjustmentPath)) 8066 return false; 8067 8068 return CallScope.destroy(); 8069 } 8070 8071 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8072 return StmtVisitorTy::Visit(E->getInitializer()); 8073 } 8074 bool VisitInitListExpr(const InitListExpr *E) { 8075 if (E->getNumInits() == 0) 8076 return DerivedZeroInitialization(E); 8077 if (E->getNumInits() == 1) 8078 return StmtVisitorTy::Visit(E->getInit(0)); 8079 return Error(E); 8080 } 8081 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 8082 return DerivedZeroInitialization(E); 8083 } 8084 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 8085 return DerivedZeroInitialization(E); 8086 } 8087 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 8088 return DerivedZeroInitialization(E); 8089 } 8090 8091 /// A member expression where the object is a prvalue is itself a prvalue. 8092 bool VisitMemberExpr(const MemberExpr *E) { 8093 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 8094 "missing temporary materialization conversion"); 8095 assert(!E->isArrow() && "missing call to bound member function?"); 8096 8097 APValue Val; 8098 if (!Evaluate(Val, Info, E->getBase())) 8099 return false; 8100 8101 QualType BaseTy = E->getBase()->getType(); 8102 8103 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 8104 if (!FD) return Error(E); 8105 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 8106 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 8107 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 8108 8109 // Note: there is no lvalue base here. But this case should only ever 8110 // happen in C or in C++98, where we cannot be evaluating a constexpr 8111 // constructor, which is the only case the base matters. 8112 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 8113 SubobjectDesignator Designator(BaseTy); 8114 Designator.addDeclUnchecked(FD); 8115 8116 APValue Result; 8117 return extractSubobject(Info, E, Obj, Designator, Result) && 8118 DerivedSuccess(Result, E); 8119 } 8120 8121 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 8122 APValue Val; 8123 if (!Evaluate(Val, Info, E->getBase())) 8124 return false; 8125 8126 if (Val.isVector()) { 8127 SmallVector<uint32_t, 4> Indices; 8128 E->getEncodedElementAccess(Indices); 8129 if (Indices.size() == 1) { 8130 // Return scalar. 8131 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 8132 } else { 8133 // Construct new APValue vector. 8134 SmallVector<APValue, 4> Elts; 8135 for (unsigned I = 0; I < Indices.size(); ++I) { 8136 Elts.push_back(Val.getVectorElt(Indices[I])); 8137 } 8138 APValue VecResult(Elts.data(), Indices.size()); 8139 return DerivedSuccess(VecResult, E); 8140 } 8141 } 8142 8143 return false; 8144 } 8145 8146 bool VisitCastExpr(const CastExpr *E) { 8147 switch (E->getCastKind()) { 8148 default: 8149 break; 8150 8151 case CK_AtomicToNonAtomic: { 8152 APValue AtomicVal; 8153 // This does not need to be done in place even for class/array types: 8154 // atomic-to-non-atomic conversion implies copying the object 8155 // representation. 8156 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 8157 return false; 8158 return DerivedSuccess(AtomicVal, E); 8159 } 8160 8161 case CK_NoOp: 8162 case CK_UserDefinedConversion: 8163 return StmtVisitorTy::Visit(E->getSubExpr()); 8164 8165 case CK_LValueToRValue: { 8166 LValue LVal; 8167 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 8168 return false; 8169 APValue RVal; 8170 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8171 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8172 LVal, RVal)) 8173 return false; 8174 return DerivedSuccess(RVal, E); 8175 } 8176 case CK_LValueToRValueBitCast: { 8177 APValue DestValue, SourceValue; 8178 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 8179 return false; 8180 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 8181 return false; 8182 return DerivedSuccess(DestValue, E); 8183 } 8184 8185 case CK_AddressSpaceConversion: { 8186 APValue Value; 8187 if (!Evaluate(Value, Info, E->getSubExpr())) 8188 return false; 8189 return DerivedSuccess(Value, E); 8190 } 8191 } 8192 8193 return Error(E); 8194 } 8195 8196 bool VisitUnaryPostInc(const UnaryOperator *UO) { 8197 return VisitUnaryPostIncDec(UO); 8198 } 8199 bool VisitUnaryPostDec(const UnaryOperator *UO) { 8200 return VisitUnaryPostIncDec(UO); 8201 } 8202 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 8203 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8204 return Error(UO); 8205 8206 LValue LVal; 8207 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 8208 return false; 8209 APValue RVal; 8210 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 8211 UO->isIncrementOp(), &RVal)) 8212 return false; 8213 return DerivedSuccess(RVal, UO); 8214 } 8215 8216 bool VisitStmtExpr(const StmtExpr *E) { 8217 // We will have checked the full-expressions inside the statement expression 8218 // when they were completed, and don't need to check them again now. 8219 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior, 8220 false); 8221 8222 const CompoundStmt *CS = E->getSubStmt(); 8223 if (CS->body_empty()) 8224 return true; 8225 8226 BlockScopeRAII Scope(Info); 8227 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 8228 BE = CS->body_end(); 8229 /**/; ++BI) { 8230 if (BI + 1 == BE) { 8231 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 8232 if (!FinalExpr) { 8233 Info.FFDiag((*BI)->getBeginLoc(), 8234 diag::note_constexpr_stmt_expr_unsupported); 8235 return false; 8236 } 8237 return this->Visit(FinalExpr) && Scope.destroy(); 8238 } 8239 8240 APValue ReturnValue; 8241 StmtResult Result = { ReturnValue, nullptr }; 8242 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 8243 if (ESR != ESR_Succeeded) { 8244 // FIXME: If the statement-expression terminated due to 'return', 8245 // 'break', or 'continue', it would be nice to propagate that to 8246 // the outer statement evaluation rather than bailing out. 8247 if (ESR != ESR_Failed) 8248 Info.FFDiag((*BI)->getBeginLoc(), 8249 diag::note_constexpr_stmt_expr_unsupported); 8250 return false; 8251 } 8252 } 8253 8254 llvm_unreachable("Return from function from the loop above."); 8255 } 8256 8257 /// Visit a value which is evaluated, but whose value is ignored. 8258 void VisitIgnoredValue(const Expr *E) { 8259 EvaluateIgnoredValue(Info, E); 8260 } 8261 8262 /// Potentially visit a MemberExpr's base expression. 8263 void VisitIgnoredBaseExpression(const Expr *E) { 8264 // While MSVC doesn't evaluate the base expression, it does diagnose the 8265 // presence of side-effecting behavior. 8266 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 8267 return; 8268 VisitIgnoredValue(E); 8269 } 8270 }; 8271 8272 } // namespace 8273 8274 //===----------------------------------------------------------------------===// 8275 // Common base class for lvalue and temporary evaluation. 8276 //===----------------------------------------------------------------------===// 8277 namespace { 8278 template<class Derived> 8279 class LValueExprEvaluatorBase 8280 : public ExprEvaluatorBase<Derived> { 8281 protected: 8282 LValue &Result; 8283 bool InvalidBaseOK; 8284 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 8285 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 8286 8287 bool Success(APValue::LValueBase B) { 8288 Result.set(B); 8289 return true; 8290 } 8291 8292 bool evaluatePointer(const Expr *E, LValue &Result) { 8293 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 8294 } 8295 8296 public: 8297 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 8298 : ExprEvaluatorBaseTy(Info), Result(Result), 8299 InvalidBaseOK(InvalidBaseOK) {} 8300 8301 bool Success(const APValue &V, const Expr *E) { 8302 Result.setFrom(this->Info.Ctx, V); 8303 return true; 8304 } 8305 8306 bool VisitMemberExpr(const MemberExpr *E) { 8307 // Handle non-static data members. 8308 QualType BaseTy; 8309 bool EvalOK; 8310 if (E->isArrow()) { 8311 EvalOK = evaluatePointer(E->getBase(), Result); 8312 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 8313 } else if (E->getBase()->isPRValue()) { 8314 assert(E->getBase()->getType()->isRecordType()); 8315 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 8316 BaseTy = E->getBase()->getType(); 8317 } else { 8318 EvalOK = this->Visit(E->getBase()); 8319 BaseTy = E->getBase()->getType(); 8320 } 8321 if (!EvalOK) { 8322 if (!InvalidBaseOK) 8323 return false; 8324 Result.setInvalid(E); 8325 return true; 8326 } 8327 8328 const ValueDecl *MD = E->getMemberDecl(); 8329 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 8330 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 8331 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 8332 (void)BaseTy; 8333 if (!HandleLValueMember(this->Info, E, Result, FD)) 8334 return false; 8335 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 8336 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 8337 return false; 8338 } else 8339 return this->Error(E); 8340 8341 if (MD->getType()->isReferenceType()) { 8342 APValue RefValue; 8343 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 8344 RefValue)) 8345 return false; 8346 return Success(RefValue, E); 8347 } 8348 return true; 8349 } 8350 8351 bool VisitBinaryOperator(const BinaryOperator *E) { 8352 switch (E->getOpcode()) { 8353 default: 8354 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8355 8356 case BO_PtrMemD: 8357 case BO_PtrMemI: 8358 return HandleMemberPointerAccess(this->Info, E, Result); 8359 } 8360 } 8361 8362 bool VisitCastExpr(const CastExpr *E) { 8363 switch (E->getCastKind()) { 8364 default: 8365 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8366 8367 case CK_DerivedToBase: 8368 case CK_UncheckedDerivedToBase: 8369 if (!this->Visit(E->getSubExpr())) 8370 return false; 8371 8372 // Now figure out the necessary offset to add to the base LV to get from 8373 // the derived class to the base class. 8374 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8375 Result); 8376 } 8377 } 8378 }; 8379 } 8380 8381 //===----------------------------------------------------------------------===// 8382 // LValue Evaluation 8383 // 8384 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8385 // function designators (in C), decl references to void objects (in C), and 8386 // temporaries (if building with -Wno-address-of-temporary). 8387 // 8388 // LValue evaluation produces values comprising a base expression of one of the 8389 // following types: 8390 // - Declarations 8391 // * VarDecl 8392 // * FunctionDecl 8393 // - Literals 8394 // * CompoundLiteralExpr in C (and in global scope in C++) 8395 // * StringLiteral 8396 // * PredefinedExpr 8397 // * ObjCStringLiteralExpr 8398 // * ObjCEncodeExpr 8399 // * AddrLabelExpr 8400 // * BlockExpr 8401 // * CallExpr for a MakeStringConstant builtin 8402 // - typeid(T) expressions, as TypeInfoLValues 8403 // - Locals and temporaries 8404 // * MaterializeTemporaryExpr 8405 // * Any Expr, with a CallIndex indicating the function in which the temporary 8406 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8407 // from the AST (FIXME). 8408 // * A MaterializeTemporaryExpr that has static storage duration, with no 8409 // CallIndex, for a lifetime-extended temporary. 8410 // * The ConstantExpr that is currently being evaluated during evaluation of an 8411 // immediate invocation. 8412 // plus an offset in bytes. 8413 //===----------------------------------------------------------------------===// 8414 namespace { 8415 class LValueExprEvaluator 8416 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8417 public: 8418 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8419 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8420 8421 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8422 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8423 8424 bool VisitCallExpr(const CallExpr *E); 8425 bool VisitDeclRefExpr(const DeclRefExpr *E); 8426 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8427 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8428 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8429 bool VisitMemberExpr(const MemberExpr *E); 8430 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8431 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8432 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8433 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8434 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8435 bool VisitUnaryDeref(const UnaryOperator *E); 8436 bool VisitUnaryReal(const UnaryOperator *E); 8437 bool VisitUnaryImag(const UnaryOperator *E); 8438 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8439 return VisitUnaryPreIncDec(UO); 8440 } 8441 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8442 return VisitUnaryPreIncDec(UO); 8443 } 8444 bool VisitBinAssign(const BinaryOperator *BO); 8445 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8446 8447 bool VisitCastExpr(const CastExpr *E) { 8448 switch (E->getCastKind()) { 8449 default: 8450 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8451 8452 case CK_LValueBitCast: 8453 this->CCEDiag(E, diag::note_constexpr_invalid_cast) 8454 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 8455 if (!Visit(E->getSubExpr())) 8456 return false; 8457 Result.Designator.setInvalid(); 8458 return true; 8459 8460 case CK_BaseToDerived: 8461 if (!Visit(E->getSubExpr())) 8462 return false; 8463 return HandleBaseToDerivedCast(Info, E, Result); 8464 8465 case CK_Dynamic: 8466 if (!Visit(E->getSubExpr())) 8467 return false; 8468 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8469 } 8470 } 8471 }; 8472 } // end anonymous namespace 8473 8474 /// Evaluate an expression as an lvalue. This can be legitimately called on 8475 /// expressions which are not glvalues, in three cases: 8476 /// * function designators in C, and 8477 /// * "extern void" objects 8478 /// * @selector() expressions in Objective-C 8479 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8480 bool InvalidBaseOK) { 8481 assert(!E->isValueDependent()); 8482 assert(E->isGLValue() || E->getType()->isFunctionType() || 8483 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens())); 8484 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8485 } 8486 8487 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8488 const NamedDecl *D = E->getDecl(); 8489 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl, 8490 UnnamedGlobalConstantDecl>(D)) 8491 return Success(cast<ValueDecl>(D)); 8492 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8493 return VisitVarDecl(E, VD); 8494 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8495 return Visit(BD->getBinding()); 8496 return Error(E); 8497 } 8498 8499 8500 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8501 8502 // If we are within a lambda's call operator, check whether the 'VD' referred 8503 // to within 'E' actually represents a lambda-capture that maps to a 8504 // data-member/field within the closure object, and if so, evaluate to the 8505 // field or what the field refers to. 8506 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8507 isa<DeclRefExpr>(E) && 8508 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8509 // We don't always have a complete capture-map when checking or inferring if 8510 // the function call operator meets the requirements of a constexpr function 8511 // - but we don't need to evaluate the captures to determine constexprness 8512 // (dcl.constexpr C++17). 8513 if (Info.checkingPotentialConstantExpression()) 8514 return false; 8515 8516 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8517 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee); 8518 8519 // Static lambda function call operators can't have captures. We already 8520 // diagnosed this, so bail out here. 8521 if (MD->isStatic()) { 8522 assert(Info.CurrentCall->This == nullptr && 8523 "This should not be set for a static call operator"); 8524 return false; 8525 } 8526 8527 // Start with 'Result' referring to the complete closure object... 8528 if (MD->isExplicitObjectMemberFunction()) { 8529 APValue *RefValue = 8530 Info.getParamSlot(Info.CurrentCall->Arguments, MD->getParamDecl(0)); 8531 Result.setFrom(Info.Ctx, *RefValue); 8532 } else 8533 Result = *Info.CurrentCall->This; 8534 8535 // ... then update it to refer to the field of the closure object 8536 // that represents the capture. 8537 if (!HandleLValueMember(Info, E, Result, FD)) 8538 return false; 8539 // And if the field is of reference type, update 'Result' to refer to what 8540 // the field refers to. 8541 if (FD->getType()->isReferenceType()) { 8542 APValue RVal; 8543 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8544 RVal)) 8545 return false; 8546 Result.setFrom(Info.Ctx, RVal); 8547 } 8548 return true; 8549 } 8550 } 8551 8552 CallStackFrame *Frame = nullptr; 8553 unsigned Version = 0; 8554 if (VD->hasLocalStorage()) { 8555 // Only if a local variable was declared in the function currently being 8556 // evaluated, do we expect to be able to find its value in the current 8557 // frame. (Otherwise it was likely declared in an enclosing context and 8558 // could either have a valid evaluatable value (for e.g. a constexpr 8559 // variable) or be ill-formed (and trigger an appropriate evaluation 8560 // diagnostic)). 8561 CallStackFrame *CurrFrame = Info.CurrentCall; 8562 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8563 // Function parameters are stored in some caller's frame. (Usually the 8564 // immediate caller, but for an inherited constructor they may be more 8565 // distant.) 8566 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8567 if (CurrFrame->Arguments) { 8568 VD = CurrFrame->Arguments.getOrigParam(PVD); 8569 Frame = 8570 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8571 Version = CurrFrame->Arguments.Version; 8572 } 8573 } else { 8574 Frame = CurrFrame; 8575 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8576 } 8577 } 8578 } 8579 8580 if (!VD->getType()->isReferenceType()) { 8581 if (Frame) { 8582 Result.set({VD, Frame->Index, Version}); 8583 return true; 8584 } 8585 return Success(VD); 8586 } 8587 8588 if (!Info.getLangOpts().CPlusPlus11) { 8589 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8590 << VD << VD->getType(); 8591 Info.Note(VD->getLocation(), diag::note_declared_at); 8592 } 8593 8594 APValue *V; 8595 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8596 return false; 8597 if (!V->hasValue()) { 8598 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8599 // adjust the diagnostic to say that. 8600 if (!Info.checkingPotentialConstantExpression()) 8601 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8602 return false; 8603 } 8604 return Success(*V, E); 8605 } 8606 8607 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) { 8608 if (!IsConstantEvaluatedBuiltinCall(E)) 8609 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8610 8611 switch (E->getBuiltinCallee()) { 8612 default: 8613 return false; 8614 case Builtin::BIas_const: 8615 case Builtin::BIforward: 8616 case Builtin::BIforward_like: 8617 case Builtin::BImove: 8618 case Builtin::BImove_if_noexcept: 8619 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr()) 8620 return Visit(E->getArg(0)); 8621 break; 8622 } 8623 8624 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8625 } 8626 8627 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8628 const MaterializeTemporaryExpr *E) { 8629 // Walk through the expression to find the materialized temporary itself. 8630 SmallVector<const Expr *, 2> CommaLHSs; 8631 SmallVector<SubobjectAdjustment, 2> Adjustments; 8632 const Expr *Inner = 8633 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8634 8635 // If we passed any comma operators, evaluate their LHSs. 8636 for (const Expr *E : CommaLHSs) 8637 if (!EvaluateIgnoredValue(Info, E)) 8638 return false; 8639 8640 // A materialized temporary with static storage duration can appear within the 8641 // result of a constant expression evaluation, so we need to preserve its 8642 // value for use outside this evaluation. 8643 APValue *Value; 8644 if (E->getStorageDuration() == SD_Static) { 8645 if (Info.EvalMode == EvalInfo::EM_ConstantFold) 8646 return false; 8647 // FIXME: What about SD_Thread? 8648 Value = E->getOrCreateValue(true); 8649 *Value = APValue(); 8650 Result.set(E); 8651 } else { 8652 Value = &Info.CurrentCall->createTemporary( 8653 E, Inner->getType(), 8654 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8655 : ScopeKind::Block, 8656 Result); 8657 } 8658 8659 QualType Type = Inner->getType(); 8660 8661 // Materialize the temporary itself. 8662 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8663 *Value = APValue(); 8664 return false; 8665 } 8666 8667 // Adjust our lvalue to refer to the desired subobject. 8668 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8669 --I; 8670 switch (Adjustments[I].Kind) { 8671 case SubobjectAdjustment::DerivedToBaseAdjustment: 8672 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8673 Type, Result)) 8674 return false; 8675 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8676 break; 8677 8678 case SubobjectAdjustment::FieldAdjustment: 8679 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8680 return false; 8681 Type = Adjustments[I].Field->getType(); 8682 break; 8683 8684 case SubobjectAdjustment::MemberPointerAdjustment: 8685 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8686 Adjustments[I].Ptr.RHS)) 8687 return false; 8688 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8689 break; 8690 } 8691 } 8692 8693 return true; 8694 } 8695 8696 bool 8697 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8698 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8699 "lvalue compound literal in c++?"); 8700 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8701 // only see this when folding in C, so there's no standard to follow here. 8702 return Success(E); 8703 } 8704 8705 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8706 TypeInfoLValue TypeInfo; 8707 8708 if (!E->isPotentiallyEvaluated()) { 8709 if (E->isTypeOperand()) 8710 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8711 else 8712 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8713 } else { 8714 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8715 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8716 << E->getExprOperand()->getType() 8717 << E->getExprOperand()->getSourceRange(); 8718 } 8719 8720 if (!Visit(E->getExprOperand())) 8721 return false; 8722 8723 std::optional<DynamicType> DynType = 8724 ComputeDynamicType(Info, E, Result, AK_TypeId); 8725 if (!DynType) 8726 return false; 8727 8728 TypeInfo = 8729 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8730 } 8731 8732 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8733 } 8734 8735 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8736 return Success(E->getGuidDecl()); 8737 } 8738 8739 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8740 // Handle static data members. 8741 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8742 VisitIgnoredBaseExpression(E->getBase()); 8743 return VisitVarDecl(E, VD); 8744 } 8745 8746 // Handle static member functions. 8747 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8748 if (MD->isStatic()) { 8749 VisitIgnoredBaseExpression(E->getBase()); 8750 return Success(MD); 8751 } 8752 } 8753 8754 // Handle non-static data members. 8755 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8756 } 8757 8758 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8759 // FIXME: Deal with vectors as array subscript bases. 8760 if (E->getBase()->getType()->isVectorType() || 8761 E->getBase()->getType()->isSveVLSBuiltinType()) 8762 return Error(E); 8763 8764 APSInt Index; 8765 bool Success = true; 8766 8767 // C++17's rules require us to evaluate the LHS first, regardless of which 8768 // side is the base. 8769 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8770 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8771 : !EvaluateInteger(SubExpr, Index, Info)) { 8772 if (!Info.noteFailure()) 8773 return false; 8774 Success = false; 8775 } 8776 } 8777 8778 return Success && 8779 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8780 } 8781 8782 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8783 return evaluatePointer(E->getSubExpr(), Result); 8784 } 8785 8786 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8787 if (!Visit(E->getSubExpr())) 8788 return false; 8789 // __real is a no-op on scalar lvalues. 8790 if (E->getSubExpr()->getType()->isAnyComplexType()) 8791 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8792 return true; 8793 } 8794 8795 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8796 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8797 "lvalue __imag__ on scalar?"); 8798 if (!Visit(E->getSubExpr())) 8799 return false; 8800 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8801 return true; 8802 } 8803 8804 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8805 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8806 return Error(UO); 8807 8808 if (!this->Visit(UO->getSubExpr())) 8809 return false; 8810 8811 return handleIncDec( 8812 this->Info, UO, Result, UO->getSubExpr()->getType(), 8813 UO->isIncrementOp(), nullptr); 8814 } 8815 8816 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8817 const CompoundAssignOperator *CAO) { 8818 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8819 return Error(CAO); 8820 8821 bool Success = true; 8822 8823 // C++17 onwards require that we evaluate the RHS first. 8824 APValue RHS; 8825 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8826 if (!Info.noteFailure()) 8827 return false; 8828 Success = false; 8829 } 8830 8831 // The overall lvalue result is the result of evaluating the LHS. 8832 if (!this->Visit(CAO->getLHS()) || !Success) 8833 return false; 8834 8835 return handleCompoundAssignment( 8836 this->Info, CAO, 8837 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8838 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8839 } 8840 8841 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8842 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8843 return Error(E); 8844 8845 bool Success = true; 8846 8847 // C++17 onwards require that we evaluate the RHS first. 8848 APValue NewVal; 8849 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8850 if (!Info.noteFailure()) 8851 return false; 8852 Success = false; 8853 } 8854 8855 if (!this->Visit(E->getLHS()) || !Success) 8856 return false; 8857 8858 if (Info.getLangOpts().CPlusPlus20 && 8859 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8860 return false; 8861 8862 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8863 NewVal); 8864 } 8865 8866 //===----------------------------------------------------------------------===// 8867 // Pointer Evaluation 8868 //===----------------------------------------------------------------------===// 8869 8870 /// Attempts to compute the number of bytes available at the pointer 8871 /// returned by a function with the alloc_size attribute. Returns true if we 8872 /// were successful. Places an unsigned number into `Result`. 8873 /// 8874 /// This expects the given CallExpr to be a call to a function with an 8875 /// alloc_size attribute. 8876 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8877 const CallExpr *Call, 8878 llvm::APInt &Result) { 8879 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8880 8881 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8882 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8883 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8884 if (Call->getNumArgs() <= SizeArgNo) 8885 return false; 8886 8887 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8888 Expr::EvalResult ExprResult; 8889 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8890 return false; 8891 Into = ExprResult.Val.getInt(); 8892 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8893 return false; 8894 Into = Into.zext(BitsInSizeT); 8895 return true; 8896 }; 8897 8898 APSInt SizeOfElem; 8899 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8900 return false; 8901 8902 if (!AllocSize->getNumElemsParam().isValid()) { 8903 Result = std::move(SizeOfElem); 8904 return true; 8905 } 8906 8907 APSInt NumberOfElems; 8908 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8909 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8910 return false; 8911 8912 bool Overflow; 8913 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8914 if (Overflow) 8915 return false; 8916 8917 Result = std::move(BytesAvailable); 8918 return true; 8919 } 8920 8921 /// Convenience function. LVal's base must be a call to an alloc_size 8922 /// function. 8923 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8924 const LValue &LVal, 8925 llvm::APInt &Result) { 8926 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8927 "Can't get the size of a non alloc_size function"); 8928 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8929 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8930 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8931 } 8932 8933 /// Attempts to evaluate the given LValueBase as the result of a call to 8934 /// a function with the alloc_size attribute. If it was possible to do so, this 8935 /// function will return true, make Result's Base point to said function call, 8936 /// and mark Result's Base as invalid. 8937 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8938 LValue &Result) { 8939 if (Base.isNull()) 8940 return false; 8941 8942 // Because we do no form of static analysis, we only support const variables. 8943 // 8944 // Additionally, we can't support parameters, nor can we support static 8945 // variables (in the latter case, use-before-assign isn't UB; in the former, 8946 // we have no clue what they'll be assigned to). 8947 const auto *VD = 8948 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8949 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8950 return false; 8951 8952 const Expr *Init = VD->getAnyInitializer(); 8953 if (!Init || Init->getType().isNull()) 8954 return false; 8955 8956 const Expr *E = Init->IgnoreParens(); 8957 if (!tryUnwrapAllocSizeCall(E)) 8958 return false; 8959 8960 // Store E instead of E unwrapped so that the type of the LValue's base is 8961 // what the user wanted. 8962 Result.setInvalid(E); 8963 8964 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8965 Result.addUnsizedArray(Info, E, Pointee); 8966 return true; 8967 } 8968 8969 namespace { 8970 class PointerExprEvaluator 8971 : public ExprEvaluatorBase<PointerExprEvaluator> { 8972 LValue &Result; 8973 bool InvalidBaseOK; 8974 8975 bool Success(const Expr *E) { 8976 Result.set(E); 8977 return true; 8978 } 8979 8980 bool evaluateLValue(const Expr *E, LValue &Result) { 8981 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8982 } 8983 8984 bool evaluatePointer(const Expr *E, LValue &Result) { 8985 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8986 } 8987 8988 bool visitNonBuiltinCallExpr(const CallExpr *E); 8989 public: 8990 8991 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8992 : ExprEvaluatorBaseTy(info), Result(Result), 8993 InvalidBaseOK(InvalidBaseOK) {} 8994 8995 bool Success(const APValue &V, const Expr *E) { 8996 Result.setFrom(Info.Ctx, V); 8997 return true; 8998 } 8999 bool ZeroInitialization(const Expr *E) { 9000 Result.setNull(Info.Ctx, E->getType()); 9001 return true; 9002 } 9003 9004 bool VisitBinaryOperator(const BinaryOperator *E); 9005 bool VisitCastExpr(const CastExpr* E); 9006 bool VisitUnaryAddrOf(const UnaryOperator *E); 9007 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 9008 { return Success(E); } 9009 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 9010 if (E->isExpressibleAsConstantInitializer()) 9011 return Success(E); 9012 if (Info.noteFailure()) 9013 EvaluateIgnoredValue(Info, E->getSubExpr()); 9014 return Error(E); 9015 } 9016 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 9017 { return Success(E); } 9018 bool VisitCallExpr(const CallExpr *E); 9019 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 9020 bool VisitBlockExpr(const BlockExpr *E) { 9021 if (!E->getBlockDecl()->hasCaptures()) 9022 return Success(E); 9023 return Error(E); 9024 } 9025 bool VisitCXXThisExpr(const CXXThisExpr *E) { 9026 // Can't look at 'this' when checking a potential constant expression. 9027 if (Info.checkingPotentialConstantExpression()) 9028 return false; 9029 if (!Info.CurrentCall->This) { 9030 if (Info.getLangOpts().CPlusPlus11) 9031 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 9032 else 9033 Info.FFDiag(E); 9034 return false; 9035 } 9036 Result = *Info.CurrentCall->This; 9037 9038 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 9039 // Ensure we actually have captured 'this'. If something was wrong with 9040 // 'this' capture, the error would have been previously reported. 9041 // Otherwise we can be inside of a default initialization of an object 9042 // declared by lambda's body, so no need to return false. 9043 if (!Info.CurrentCall->LambdaThisCaptureField) 9044 return true; 9045 9046 // If we have captured 'this', the 'this' expression refers 9047 // to the enclosing '*this' object (either by value or reference) which is 9048 // either copied into the closure object's field that represents the 9049 // '*this' or refers to '*this'. 9050 // Update 'Result' to refer to the data member/field of the closure object 9051 // that represents the '*this' capture. 9052 if (!HandleLValueMember(Info, E, Result, 9053 Info.CurrentCall->LambdaThisCaptureField)) 9054 return false; 9055 // If we captured '*this' by reference, replace the field with its referent. 9056 if (Info.CurrentCall->LambdaThisCaptureField->getType() 9057 ->isPointerType()) { 9058 APValue RVal; 9059 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 9060 RVal)) 9061 return false; 9062 9063 Result.setFrom(Info.Ctx, RVal); 9064 } 9065 } 9066 return true; 9067 } 9068 9069 bool VisitCXXNewExpr(const CXXNewExpr *E); 9070 9071 bool VisitSourceLocExpr(const SourceLocExpr *E) { 9072 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?"); 9073 APValue LValResult = E->EvaluateInContext( 9074 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 9075 Result.setFrom(Info.Ctx, LValResult); 9076 return true; 9077 } 9078 9079 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 9080 std::string ResultStr = E->ComputeName(Info.Ctx); 9081 9082 QualType CharTy = Info.Ctx.CharTy.withConst(); 9083 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 9084 ResultStr.size() + 1); 9085 QualType ArrayTy = Info.Ctx.getConstantArrayType( 9086 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0); 9087 9088 StringLiteral *SL = 9089 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary, 9090 /*Pascal*/ false, ArrayTy, E->getLocation()); 9091 9092 evaluateLValue(SL, Result); 9093 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 9094 return true; 9095 } 9096 9097 // FIXME: Missing: @protocol, @selector 9098 }; 9099 } // end anonymous namespace 9100 9101 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 9102 bool InvalidBaseOK) { 9103 assert(!E->isValueDependent()); 9104 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 9105 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 9106 } 9107 9108 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9109 if (E->getOpcode() != BO_Add && 9110 E->getOpcode() != BO_Sub) 9111 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9112 9113 const Expr *PExp = E->getLHS(); 9114 const Expr *IExp = E->getRHS(); 9115 if (IExp->getType()->isPointerType()) 9116 std::swap(PExp, IExp); 9117 9118 bool EvalPtrOK = evaluatePointer(PExp, Result); 9119 if (!EvalPtrOK && !Info.noteFailure()) 9120 return false; 9121 9122 llvm::APSInt Offset; 9123 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 9124 return false; 9125 9126 if (E->getOpcode() == BO_Sub) 9127 negateAsSigned(Offset); 9128 9129 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 9130 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 9131 } 9132 9133 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9134 return evaluateLValue(E->getSubExpr(), Result); 9135 } 9136 9137 // Is the provided decl 'std::source_location::current'? 9138 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) { 9139 if (!FD) 9140 return false; 9141 const IdentifierInfo *FnII = FD->getIdentifier(); 9142 if (!FnII || !FnII->isStr("current")) 9143 return false; 9144 9145 const auto *RD = dyn_cast<RecordDecl>(FD->getParent()); 9146 if (!RD) 9147 return false; 9148 9149 const IdentifierInfo *ClassII = RD->getIdentifier(); 9150 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location"); 9151 } 9152 9153 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9154 const Expr *SubExpr = E->getSubExpr(); 9155 9156 switch (E->getCastKind()) { 9157 default: 9158 break; 9159 case CK_BitCast: 9160 case CK_CPointerToObjCPointerCast: 9161 case CK_BlockPointerToObjCPointerCast: 9162 case CK_AnyPointerToBlockPointerCast: 9163 case CK_AddressSpaceConversion: 9164 if (!Visit(SubExpr)) 9165 return false; 9166 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 9167 // permitted in constant expressions in C++11. Bitcasts from cv void* are 9168 // also static_casts, but we disallow them as a resolution to DR1312. 9169 if (!E->getType()->isVoidPointerType()) { 9170 // In some circumstances, we permit casting from void* to cv1 T*, when the 9171 // actual pointee object is actually a cv2 T. 9172 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid && 9173 !Result.IsNullPtr; 9174 bool VoidPtrCastMaybeOK = 9175 HasValidResult && 9176 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 9177 E->getType()->getPointeeType()); 9178 // 1. We'll allow it in std::allocator::allocate, and anything which that 9179 // calls. 9180 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s 9181 // <source_location> header. Fixed in GCC 12 and later (2022-04-??). 9182 // We'll allow it in the body of std::source_location::current. GCC's 9183 // implementation had a parameter of type `void*`, and casts from 9184 // that back to `const __impl*` in its body. 9185 if (VoidPtrCastMaybeOK && 9186 (Info.getStdAllocatorCaller("allocate") || 9187 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) || 9188 Info.getLangOpts().CPlusPlus26)) { 9189 // Permitted. 9190 } else { 9191 if (SubExpr->getType()->isVoidPointerType()) { 9192 if (HasValidResult) 9193 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast) 9194 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26 9195 << Result.Designator.getType(Info.Ctx).getCanonicalType() 9196 << E->getType()->getPointeeType(); 9197 else 9198 CCEDiag(E, diag::note_constexpr_invalid_cast) 9199 << 3 << SubExpr->getType(); 9200 } else 9201 CCEDiag(E, diag::note_constexpr_invalid_cast) 9202 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 9203 Result.Designator.setInvalid(); 9204 } 9205 } 9206 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 9207 ZeroInitialization(E); 9208 return true; 9209 9210 case CK_DerivedToBase: 9211 case CK_UncheckedDerivedToBase: 9212 if (!evaluatePointer(E->getSubExpr(), Result)) 9213 return false; 9214 if (!Result.Base && Result.Offset.isZero()) 9215 return true; 9216 9217 // Now figure out the necessary offset to add to the base LV to get from 9218 // the derived class to the base class. 9219 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 9220 castAs<PointerType>()->getPointeeType(), 9221 Result); 9222 9223 case CK_BaseToDerived: 9224 if (!Visit(E->getSubExpr())) 9225 return false; 9226 if (!Result.Base && Result.Offset.isZero()) 9227 return true; 9228 return HandleBaseToDerivedCast(Info, E, Result); 9229 9230 case CK_Dynamic: 9231 if (!Visit(E->getSubExpr())) 9232 return false; 9233 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 9234 9235 case CK_NullToPointer: 9236 VisitIgnoredValue(E->getSubExpr()); 9237 return ZeroInitialization(E); 9238 9239 case CK_IntegralToPointer: { 9240 CCEDiag(E, diag::note_constexpr_invalid_cast) 9241 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 9242 9243 APValue Value; 9244 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 9245 break; 9246 9247 if (Value.isInt()) { 9248 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 9249 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 9250 Result.Base = (Expr*)nullptr; 9251 Result.InvalidBase = false; 9252 Result.Offset = CharUnits::fromQuantity(N); 9253 Result.Designator.setInvalid(); 9254 Result.IsNullPtr = false; 9255 return true; 9256 } else { 9257 // Cast is of an lvalue, no need to change value. 9258 Result.setFrom(Info.Ctx, Value); 9259 return true; 9260 } 9261 } 9262 9263 case CK_ArrayToPointerDecay: { 9264 if (SubExpr->isGLValue()) { 9265 if (!evaluateLValue(SubExpr, Result)) 9266 return false; 9267 } else { 9268 APValue &Value = Info.CurrentCall->createTemporary( 9269 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 9270 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 9271 return false; 9272 } 9273 // The result is a pointer to the first element of the array. 9274 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 9275 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 9276 Result.addArray(Info, E, CAT); 9277 else 9278 Result.addUnsizedArray(Info, E, AT->getElementType()); 9279 return true; 9280 } 9281 9282 case CK_FunctionToPointerDecay: 9283 return evaluateLValue(SubExpr, Result); 9284 9285 case CK_LValueToRValue: { 9286 LValue LVal; 9287 if (!evaluateLValue(E->getSubExpr(), LVal)) 9288 return false; 9289 9290 APValue RVal; 9291 // Note, we use the subexpression's type in order to retain cv-qualifiers. 9292 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 9293 LVal, RVal)) 9294 return InvalidBaseOK && 9295 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 9296 return Success(RVal, E); 9297 } 9298 } 9299 9300 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9301 } 9302 9303 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 9304 UnaryExprOrTypeTrait ExprKind) { 9305 // C++ [expr.alignof]p3: 9306 // When alignof is applied to a reference type, the result is the 9307 // alignment of the referenced type. 9308 T = T.getNonReferenceType(); 9309 9310 if (T.getQualifiers().hasUnaligned()) 9311 return CharUnits::One(); 9312 9313 const bool AlignOfReturnsPreferred = 9314 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 9315 9316 // __alignof is defined to return the preferred alignment. 9317 // Before 8, clang returned the preferred alignment for alignof and _Alignof 9318 // as well. 9319 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 9320 return Info.Ctx.toCharUnitsFromBits( 9321 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 9322 // alignof and _Alignof are defined to return the ABI alignment. 9323 else if (ExprKind == UETT_AlignOf) 9324 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 9325 else 9326 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 9327 } 9328 9329 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 9330 UnaryExprOrTypeTrait ExprKind) { 9331 E = E->IgnoreParens(); 9332 9333 // The kinds of expressions that we have special-case logic here for 9334 // should be kept up to date with the special checks for those 9335 // expressions in Sema. 9336 9337 // alignof decl is always accepted, even if it doesn't make sense: we default 9338 // to 1 in those cases. 9339 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9340 return Info.Ctx.getDeclAlign(DRE->getDecl(), 9341 /*RefAsPointee*/true); 9342 9343 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 9344 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 9345 /*RefAsPointee*/true); 9346 9347 return GetAlignOfType(Info, E->getType(), ExprKind); 9348 } 9349 9350 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 9351 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 9352 return Info.Ctx.getDeclAlign(VD); 9353 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 9354 return GetAlignOfExpr(Info, E, UETT_AlignOf); 9355 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 9356 } 9357 9358 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 9359 /// __builtin_is_aligned and __builtin_assume_aligned. 9360 static bool getAlignmentArgument(const Expr *E, QualType ForType, 9361 EvalInfo &Info, APSInt &Alignment) { 9362 if (!EvaluateInteger(E, Alignment, Info)) 9363 return false; 9364 if (Alignment < 0 || !Alignment.isPowerOf2()) { 9365 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 9366 return false; 9367 } 9368 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 9369 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 9370 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 9371 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 9372 << MaxValue << ForType << Alignment; 9373 return false; 9374 } 9375 // Ensure both alignment and source value have the same bit width so that we 9376 // don't assert when computing the resulting value. 9377 APSInt ExtAlignment = 9378 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 9379 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 9380 "Alignment should not be changed by ext/trunc"); 9381 Alignment = ExtAlignment; 9382 assert(Alignment.getBitWidth() == SrcWidth); 9383 return true; 9384 } 9385 9386 // To be clear: this happily visits unsupported builtins. Better name welcomed. 9387 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 9388 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 9389 return true; 9390 9391 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 9392 return false; 9393 9394 Result.setInvalid(E); 9395 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 9396 Result.addUnsizedArray(Info, E, PointeeTy); 9397 return true; 9398 } 9399 9400 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 9401 if (!IsConstantEvaluatedBuiltinCall(E)) 9402 return visitNonBuiltinCallExpr(E); 9403 return VisitBuiltinCallExpr(E, E->getBuiltinCallee()); 9404 } 9405 9406 // Determine if T is a character type for which we guarantee that 9407 // sizeof(T) == 1. 9408 static bool isOneByteCharacterType(QualType T) { 9409 return T->isCharType() || T->isChar8Type(); 9410 } 9411 9412 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9413 unsigned BuiltinOp) { 9414 if (IsNoOpCall(E)) 9415 return Success(E); 9416 9417 switch (BuiltinOp) { 9418 case Builtin::BIaddressof: 9419 case Builtin::BI__addressof: 9420 case Builtin::BI__builtin_addressof: 9421 return evaluateLValue(E->getArg(0), Result); 9422 case Builtin::BI__builtin_assume_aligned: { 9423 // We need to be very careful here because: if the pointer does not have the 9424 // asserted alignment, then the behavior is undefined, and undefined 9425 // behavior is non-constant. 9426 if (!evaluatePointer(E->getArg(0), Result)) 9427 return false; 9428 9429 LValue OffsetResult(Result); 9430 APSInt Alignment; 9431 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9432 Alignment)) 9433 return false; 9434 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 9435 9436 if (E->getNumArgs() > 2) { 9437 APSInt Offset; 9438 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9439 return false; 9440 9441 int64_t AdditionalOffset = -Offset.getZExtValue(); 9442 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9443 } 9444 9445 // If there is a base object, then it must have the correct alignment. 9446 if (OffsetResult.Base) { 9447 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9448 9449 if (BaseAlignment < Align) { 9450 Result.Designator.setInvalid(); 9451 // FIXME: Add support to Diagnostic for long / long long. 9452 CCEDiag(E->getArg(0), 9453 diag::note_constexpr_baa_insufficient_alignment) << 0 9454 << (unsigned)BaseAlignment.getQuantity() 9455 << (unsigned)Align.getQuantity(); 9456 return false; 9457 } 9458 } 9459 9460 // The offset must also have the correct alignment. 9461 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9462 Result.Designator.setInvalid(); 9463 9464 (OffsetResult.Base 9465 ? CCEDiag(E->getArg(0), 9466 diag::note_constexpr_baa_insufficient_alignment) << 1 9467 : CCEDiag(E->getArg(0), 9468 diag::note_constexpr_baa_value_insufficient_alignment)) 9469 << (int)OffsetResult.Offset.getQuantity() 9470 << (unsigned)Align.getQuantity(); 9471 return false; 9472 } 9473 9474 return true; 9475 } 9476 case Builtin::BI__builtin_align_up: 9477 case Builtin::BI__builtin_align_down: { 9478 if (!evaluatePointer(E->getArg(0), Result)) 9479 return false; 9480 APSInt Alignment; 9481 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9482 Alignment)) 9483 return false; 9484 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9485 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9486 // For align_up/align_down, we can return the same value if the alignment 9487 // is known to be greater or equal to the requested value. 9488 if (PtrAlign.getQuantity() >= Alignment) 9489 return true; 9490 9491 // The alignment could be greater than the minimum at run-time, so we cannot 9492 // infer much about the resulting pointer value. One case is possible: 9493 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9494 // can infer the correct index if the requested alignment is smaller than 9495 // the base alignment so we can perform the computation on the offset. 9496 if (BaseAlignment.getQuantity() >= Alignment) { 9497 assert(Alignment.getBitWidth() <= 64 && 9498 "Cannot handle > 64-bit address-space"); 9499 uint64_t Alignment64 = Alignment.getZExtValue(); 9500 CharUnits NewOffset = CharUnits::fromQuantity( 9501 BuiltinOp == Builtin::BI__builtin_align_down 9502 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9503 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9504 Result.adjustOffset(NewOffset - Result.Offset); 9505 // TODO: diagnose out-of-bounds values/only allow for arrays? 9506 return true; 9507 } 9508 // Otherwise, we cannot constant-evaluate the result. 9509 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9510 << Alignment; 9511 return false; 9512 } 9513 case Builtin::BI__builtin_operator_new: 9514 return HandleOperatorNewCall(Info, E, Result); 9515 case Builtin::BI__builtin_launder: 9516 return evaluatePointer(E->getArg(0), Result); 9517 case Builtin::BIstrchr: 9518 case Builtin::BIwcschr: 9519 case Builtin::BImemchr: 9520 case Builtin::BIwmemchr: 9521 if (Info.getLangOpts().CPlusPlus11) 9522 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9523 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 9524 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 9525 else 9526 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9527 [[fallthrough]]; 9528 case Builtin::BI__builtin_strchr: 9529 case Builtin::BI__builtin_wcschr: 9530 case Builtin::BI__builtin_memchr: 9531 case Builtin::BI__builtin_char_memchr: 9532 case Builtin::BI__builtin_wmemchr: { 9533 if (!Visit(E->getArg(0))) 9534 return false; 9535 APSInt Desired; 9536 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9537 return false; 9538 uint64_t MaxLength = uint64_t(-1); 9539 if (BuiltinOp != Builtin::BIstrchr && 9540 BuiltinOp != Builtin::BIwcschr && 9541 BuiltinOp != Builtin::BI__builtin_strchr && 9542 BuiltinOp != Builtin::BI__builtin_wcschr) { 9543 APSInt N; 9544 if (!EvaluateInteger(E->getArg(2), N, Info)) 9545 return false; 9546 MaxLength = N.getZExtValue(); 9547 } 9548 // We cannot find the value if there are no candidates to match against. 9549 if (MaxLength == 0u) 9550 return ZeroInitialization(E); 9551 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9552 Result.Designator.Invalid) 9553 return false; 9554 QualType CharTy = Result.Designator.getType(Info.Ctx); 9555 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9556 BuiltinOp == Builtin::BI__builtin_memchr; 9557 assert(IsRawByte || 9558 Info.Ctx.hasSameUnqualifiedType( 9559 CharTy, E->getArg(0)->getType()->getPointeeType())); 9560 // Pointers to const void may point to objects of incomplete type. 9561 if (IsRawByte && CharTy->isIncompleteType()) { 9562 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9563 return false; 9564 } 9565 // Give up on byte-oriented matching against multibyte elements. 9566 // FIXME: We can compare the bytes in the correct order. 9567 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9568 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9569 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str() 9570 << CharTy; 9571 return false; 9572 } 9573 // Figure out what value we're actually looking for (after converting to 9574 // the corresponding unsigned type if necessary). 9575 uint64_t DesiredVal; 9576 bool StopAtNull = false; 9577 switch (BuiltinOp) { 9578 case Builtin::BIstrchr: 9579 case Builtin::BI__builtin_strchr: 9580 // strchr compares directly to the passed integer, and therefore 9581 // always fails if given an int that is not a char. 9582 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9583 E->getArg(1)->getType(), 9584 Desired), 9585 Desired)) 9586 return ZeroInitialization(E); 9587 StopAtNull = true; 9588 [[fallthrough]]; 9589 case Builtin::BImemchr: 9590 case Builtin::BI__builtin_memchr: 9591 case Builtin::BI__builtin_char_memchr: 9592 // memchr compares by converting both sides to unsigned char. That's also 9593 // correct for strchr if we get this far (to cope with plain char being 9594 // unsigned in the strchr case). 9595 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9596 break; 9597 9598 case Builtin::BIwcschr: 9599 case Builtin::BI__builtin_wcschr: 9600 StopAtNull = true; 9601 [[fallthrough]]; 9602 case Builtin::BIwmemchr: 9603 case Builtin::BI__builtin_wmemchr: 9604 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9605 DesiredVal = Desired.getZExtValue(); 9606 break; 9607 } 9608 9609 for (; MaxLength; --MaxLength) { 9610 APValue Char; 9611 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9612 !Char.isInt()) 9613 return false; 9614 if (Char.getInt().getZExtValue() == DesiredVal) 9615 return true; 9616 if (StopAtNull && !Char.getInt()) 9617 break; 9618 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9619 return false; 9620 } 9621 // Not found: return nullptr. 9622 return ZeroInitialization(E); 9623 } 9624 9625 case Builtin::BImemcpy: 9626 case Builtin::BImemmove: 9627 case Builtin::BIwmemcpy: 9628 case Builtin::BIwmemmove: 9629 if (Info.getLangOpts().CPlusPlus11) 9630 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9631 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 9632 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 9633 else 9634 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9635 [[fallthrough]]; 9636 case Builtin::BI__builtin_memcpy: 9637 case Builtin::BI__builtin_memmove: 9638 case Builtin::BI__builtin_wmemcpy: 9639 case Builtin::BI__builtin_wmemmove: { 9640 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9641 BuiltinOp == Builtin::BIwmemmove || 9642 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9643 BuiltinOp == Builtin::BI__builtin_wmemmove; 9644 bool Move = BuiltinOp == Builtin::BImemmove || 9645 BuiltinOp == Builtin::BIwmemmove || 9646 BuiltinOp == Builtin::BI__builtin_memmove || 9647 BuiltinOp == Builtin::BI__builtin_wmemmove; 9648 9649 // The result of mem* is the first argument. 9650 if (!Visit(E->getArg(0))) 9651 return false; 9652 LValue Dest = Result; 9653 9654 LValue Src; 9655 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9656 return false; 9657 9658 APSInt N; 9659 if (!EvaluateInteger(E->getArg(2), N, Info)) 9660 return false; 9661 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9662 9663 // If the size is zero, we treat this as always being a valid no-op. 9664 // (Even if one of the src and dest pointers is null.) 9665 if (!N) 9666 return true; 9667 9668 // Otherwise, if either of the operands is null, we can't proceed. Don't 9669 // try to determine the type of the copied objects, because there aren't 9670 // any. 9671 if (!Src.Base || !Dest.Base) { 9672 APValue Val; 9673 (!Src.Base ? Src : Dest).moveInto(Val); 9674 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9675 << Move << WChar << !!Src.Base 9676 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9677 return false; 9678 } 9679 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9680 return false; 9681 9682 // We require that Src and Dest are both pointers to arrays of 9683 // trivially-copyable type. (For the wide version, the designator will be 9684 // invalid if the designated object is not a wchar_t.) 9685 QualType T = Dest.Designator.getType(Info.Ctx); 9686 QualType SrcT = Src.Designator.getType(Info.Ctx); 9687 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9688 // FIXME: Consider using our bit_cast implementation to support this. 9689 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9690 return false; 9691 } 9692 if (T->isIncompleteType()) { 9693 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9694 return false; 9695 } 9696 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9697 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9698 return false; 9699 } 9700 9701 // Figure out how many T's we're copying. 9702 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9703 if (TSize == 0) 9704 return false; 9705 if (!WChar) { 9706 uint64_t Remainder; 9707 llvm::APInt OrigN = N; 9708 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9709 if (Remainder) { 9710 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9711 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9712 << (unsigned)TSize; 9713 return false; 9714 } 9715 } 9716 9717 // Check that the copying will remain within the arrays, just so that we 9718 // can give a more meaningful diagnostic. This implicitly also checks that 9719 // N fits into 64 bits. 9720 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9721 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9722 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9723 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9724 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9725 << toString(N, 10, /*Signed*/false); 9726 return false; 9727 } 9728 uint64_t NElems = N.getZExtValue(); 9729 uint64_t NBytes = NElems * TSize; 9730 9731 // Check for overlap. 9732 int Direction = 1; 9733 if (HasSameBase(Src, Dest)) { 9734 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9735 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9736 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9737 // Dest is inside the source region. 9738 if (!Move) { 9739 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9740 return false; 9741 } 9742 // For memmove and friends, copy backwards. 9743 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9744 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9745 return false; 9746 Direction = -1; 9747 } else if (!Move && SrcOffset >= DestOffset && 9748 SrcOffset - DestOffset < NBytes) { 9749 // Src is inside the destination region for memcpy: invalid. 9750 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9751 return false; 9752 } 9753 } 9754 9755 while (true) { 9756 APValue Val; 9757 // FIXME: Set WantObjectRepresentation to true if we're copying a 9758 // char-like type? 9759 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9760 !handleAssignment(Info, E, Dest, T, Val)) 9761 return false; 9762 // Do not iterate past the last element; if we're copying backwards, that 9763 // might take us off the start of the array. 9764 if (--NElems == 0) 9765 return true; 9766 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9767 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9768 return false; 9769 } 9770 } 9771 9772 default: 9773 return false; 9774 } 9775 } 9776 9777 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9778 APValue &Result, const InitListExpr *ILE, 9779 QualType AllocType); 9780 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9781 APValue &Result, 9782 const CXXConstructExpr *CCE, 9783 QualType AllocType); 9784 9785 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9786 if (!Info.getLangOpts().CPlusPlus20) 9787 Info.CCEDiag(E, diag::note_constexpr_new); 9788 9789 // We cannot speculatively evaluate a delete expression. 9790 if (Info.SpeculativeEvaluationDepth) 9791 return false; 9792 9793 FunctionDecl *OperatorNew = E->getOperatorNew(); 9794 9795 bool IsNothrow = false; 9796 bool IsPlacement = false; 9797 if (OperatorNew->isReservedGlobalPlacementOperator() && 9798 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9799 // FIXME Support array placement new. 9800 assert(E->getNumPlacementArgs() == 1); 9801 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9802 return false; 9803 if (Result.Designator.Invalid) 9804 return false; 9805 IsPlacement = true; 9806 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9807 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9808 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9809 return false; 9810 } else if (E->getNumPlacementArgs()) { 9811 // The only new-placement list we support is of the form (std::nothrow). 9812 // 9813 // FIXME: There is no restriction on this, but it's not clear that any 9814 // other form makes any sense. We get here for cases such as: 9815 // 9816 // new (std::align_val_t{N}) X(int) 9817 // 9818 // (which should presumably be valid only if N is a multiple of 9819 // alignof(int), and in any case can't be deallocated unless N is 9820 // alignof(X) and X has new-extended alignment). 9821 if (E->getNumPlacementArgs() != 1 || 9822 !E->getPlacementArg(0)->getType()->isNothrowT()) 9823 return Error(E, diag::note_constexpr_new_placement); 9824 9825 LValue Nothrow; 9826 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9827 return false; 9828 IsNothrow = true; 9829 } 9830 9831 const Expr *Init = E->getInitializer(); 9832 const InitListExpr *ResizedArrayILE = nullptr; 9833 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9834 bool ValueInit = false; 9835 9836 QualType AllocType = E->getAllocatedType(); 9837 if (std::optional<const Expr *> ArraySize = E->getArraySize()) { 9838 const Expr *Stripped = *ArraySize; 9839 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9840 Stripped = ICE->getSubExpr()) 9841 if (ICE->getCastKind() != CK_NoOp && 9842 ICE->getCastKind() != CK_IntegralCast) 9843 break; 9844 9845 llvm::APSInt ArrayBound; 9846 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9847 return false; 9848 9849 // C++ [expr.new]p9: 9850 // The expression is erroneous if: 9851 // -- [...] its value before converting to size_t [or] applying the 9852 // second standard conversion sequence is less than zero 9853 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9854 if (IsNothrow) 9855 return ZeroInitialization(E); 9856 9857 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9858 << ArrayBound << (*ArraySize)->getSourceRange(); 9859 return false; 9860 } 9861 9862 // -- its value is such that the size of the allocated object would 9863 // exceed the implementation-defined limit 9864 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(), 9865 ConstantArrayType::getNumAddressingBits( 9866 Info.Ctx, AllocType, ArrayBound), 9867 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) { 9868 if (IsNothrow) 9869 return ZeroInitialization(E); 9870 return false; 9871 } 9872 9873 // -- the new-initializer is a braced-init-list and the number of 9874 // array elements for which initializers are provided [...] 9875 // exceeds the number of elements to initialize 9876 if (!Init) { 9877 // No initialization is performed. 9878 } else if (isa<CXXScalarValueInitExpr>(Init) || 9879 isa<ImplicitValueInitExpr>(Init)) { 9880 ValueInit = true; 9881 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9882 ResizedArrayCCE = CCE; 9883 } else { 9884 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9885 assert(CAT && "unexpected type for array initializer"); 9886 9887 unsigned Bits = 9888 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9889 llvm::APInt InitBound = CAT->getSize().zext(Bits); 9890 llvm::APInt AllocBound = ArrayBound.zext(Bits); 9891 if (InitBound.ugt(AllocBound)) { 9892 if (IsNothrow) 9893 return ZeroInitialization(E); 9894 9895 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9896 << toString(AllocBound, 10, /*Signed=*/false) 9897 << toString(InitBound, 10, /*Signed=*/false) 9898 << (*ArraySize)->getSourceRange(); 9899 return false; 9900 } 9901 9902 // If the sizes differ, we must have an initializer list, and we need 9903 // special handling for this case when we initialize. 9904 if (InitBound != AllocBound) 9905 ResizedArrayILE = cast<InitListExpr>(Init); 9906 } 9907 9908 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9909 ArraySizeModifier::Normal, 0); 9910 } else { 9911 assert(!AllocType->isArrayType() && 9912 "array allocation with non-array new"); 9913 } 9914 9915 APValue *Val; 9916 if (IsPlacement) { 9917 AccessKinds AK = AK_Construct; 9918 struct FindObjectHandler { 9919 EvalInfo &Info; 9920 const Expr *E; 9921 QualType AllocType; 9922 const AccessKinds AccessKind; 9923 APValue *Value; 9924 9925 typedef bool result_type; 9926 bool failed() { return false; } 9927 bool found(APValue &Subobj, QualType SubobjType) { 9928 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9929 // old name of the object to be used to name the new object. 9930 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9931 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9932 SubobjType << AllocType; 9933 return false; 9934 } 9935 Value = &Subobj; 9936 return true; 9937 } 9938 bool found(APSInt &Value, QualType SubobjType) { 9939 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9940 return false; 9941 } 9942 bool found(APFloat &Value, QualType SubobjType) { 9943 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9944 return false; 9945 } 9946 } Handler = {Info, E, AllocType, AK, nullptr}; 9947 9948 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9949 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9950 return false; 9951 9952 Val = Handler.Value; 9953 9954 // [basic.life]p1: 9955 // The lifetime of an object o of type T ends when [...] the storage 9956 // which the object occupies is [...] reused by an object that is not 9957 // nested within o (6.6.2). 9958 *Val = APValue(); 9959 } else { 9960 // Perform the allocation and obtain a pointer to the resulting object. 9961 Val = Info.createHeapAlloc(E, AllocType, Result); 9962 if (!Val) 9963 return false; 9964 } 9965 9966 if (ValueInit) { 9967 ImplicitValueInitExpr VIE(AllocType); 9968 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9969 return false; 9970 } else if (ResizedArrayILE) { 9971 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9972 AllocType)) 9973 return false; 9974 } else if (ResizedArrayCCE) { 9975 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9976 AllocType)) 9977 return false; 9978 } else if (Init) { 9979 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9980 return false; 9981 } else if (!handleDefaultInitValue(AllocType, *Val)) { 9982 return false; 9983 } 9984 9985 // Array new returns a pointer to the first element, not a pointer to the 9986 // array. 9987 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9988 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9989 9990 return true; 9991 } 9992 //===----------------------------------------------------------------------===// 9993 // Member Pointer Evaluation 9994 //===----------------------------------------------------------------------===// 9995 9996 namespace { 9997 class MemberPointerExprEvaluator 9998 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9999 MemberPtr &Result; 10000 10001 bool Success(const ValueDecl *D) { 10002 Result = MemberPtr(D); 10003 return true; 10004 } 10005 public: 10006 10007 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 10008 : ExprEvaluatorBaseTy(Info), Result(Result) {} 10009 10010 bool Success(const APValue &V, const Expr *E) { 10011 Result.setFrom(V); 10012 return true; 10013 } 10014 bool ZeroInitialization(const Expr *E) { 10015 return Success((const ValueDecl*)nullptr); 10016 } 10017 10018 bool VisitCastExpr(const CastExpr *E); 10019 bool VisitUnaryAddrOf(const UnaryOperator *E); 10020 }; 10021 } // end anonymous namespace 10022 10023 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 10024 EvalInfo &Info) { 10025 assert(!E->isValueDependent()); 10026 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 10027 return MemberPointerExprEvaluator(Info, Result).Visit(E); 10028 } 10029 10030 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 10031 switch (E->getCastKind()) { 10032 default: 10033 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10034 10035 case CK_NullToMemberPointer: 10036 VisitIgnoredValue(E->getSubExpr()); 10037 return ZeroInitialization(E); 10038 10039 case CK_BaseToDerivedMemberPointer: { 10040 if (!Visit(E->getSubExpr())) 10041 return false; 10042 if (E->path_empty()) 10043 return true; 10044 // Base-to-derived member pointer casts store the path in derived-to-base 10045 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 10046 // the wrong end of the derived->base arc, so stagger the path by one class. 10047 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 10048 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 10049 PathI != PathE; ++PathI) { 10050 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 10051 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 10052 if (!Result.castToDerived(Derived)) 10053 return Error(E); 10054 } 10055 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 10056 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 10057 return Error(E); 10058 return true; 10059 } 10060 10061 case CK_DerivedToBaseMemberPointer: 10062 if (!Visit(E->getSubExpr())) 10063 return false; 10064 for (CastExpr::path_const_iterator PathI = E->path_begin(), 10065 PathE = E->path_end(); PathI != PathE; ++PathI) { 10066 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 10067 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 10068 if (!Result.castToBase(Base)) 10069 return Error(E); 10070 } 10071 return true; 10072 } 10073 } 10074 10075 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 10076 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 10077 // member can be formed. 10078 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 10079 } 10080 10081 //===----------------------------------------------------------------------===// 10082 // Record Evaluation 10083 //===----------------------------------------------------------------------===// 10084 10085 namespace { 10086 class RecordExprEvaluator 10087 : public ExprEvaluatorBase<RecordExprEvaluator> { 10088 const LValue &This; 10089 APValue &Result; 10090 public: 10091 10092 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 10093 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 10094 10095 bool Success(const APValue &V, const Expr *E) { 10096 Result = V; 10097 return true; 10098 } 10099 bool ZeroInitialization(const Expr *E) { 10100 return ZeroInitialization(E, E->getType()); 10101 } 10102 bool ZeroInitialization(const Expr *E, QualType T); 10103 10104 bool VisitCallExpr(const CallExpr *E) { 10105 return handleCallExpr(E, Result, &This); 10106 } 10107 bool VisitCastExpr(const CastExpr *E); 10108 bool VisitInitListExpr(const InitListExpr *E); 10109 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10110 return VisitCXXConstructExpr(E, E->getType()); 10111 } 10112 bool VisitLambdaExpr(const LambdaExpr *E); 10113 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 10114 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 10115 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 10116 bool VisitBinCmp(const BinaryOperator *E); 10117 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E); 10118 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit, 10119 ArrayRef<Expr *> Args); 10120 }; 10121 } 10122 10123 /// Perform zero-initialization on an object of non-union class type. 10124 /// C++11 [dcl.init]p5: 10125 /// To zero-initialize an object or reference of type T means: 10126 /// [...] 10127 /// -- if T is a (possibly cv-qualified) non-union class type, 10128 /// each non-static data member and each base-class subobject is 10129 /// zero-initialized 10130 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 10131 const RecordDecl *RD, 10132 const LValue &This, APValue &Result) { 10133 assert(!RD->isUnion() && "Expected non-union class type"); 10134 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 10135 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 10136 std::distance(RD->field_begin(), RD->field_end())); 10137 10138 if (RD->isInvalidDecl()) return false; 10139 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 10140 10141 if (CD) { 10142 unsigned Index = 0; 10143 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 10144 End = CD->bases_end(); I != End; ++I, ++Index) { 10145 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 10146 LValue Subobject = This; 10147 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 10148 return false; 10149 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 10150 Result.getStructBase(Index))) 10151 return false; 10152 } 10153 } 10154 10155 for (const auto *I : RD->fields()) { 10156 // -- if T is a reference type, no initialization is performed. 10157 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 10158 continue; 10159 10160 LValue Subobject = This; 10161 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 10162 return false; 10163 10164 ImplicitValueInitExpr VIE(I->getType()); 10165 if (!EvaluateInPlace( 10166 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 10167 return false; 10168 } 10169 10170 return true; 10171 } 10172 10173 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 10174 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 10175 if (RD->isInvalidDecl()) return false; 10176 if (RD->isUnion()) { 10177 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 10178 // object's first non-static named data member is zero-initialized 10179 RecordDecl::field_iterator I = RD->field_begin(); 10180 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 10181 ++I; 10182 if (I == RD->field_end()) { 10183 Result = APValue((const FieldDecl*)nullptr); 10184 return true; 10185 } 10186 10187 LValue Subobject = This; 10188 if (!HandleLValueMember(Info, E, Subobject, *I)) 10189 return false; 10190 Result = APValue(*I); 10191 ImplicitValueInitExpr VIE(I->getType()); 10192 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 10193 } 10194 10195 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 10196 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 10197 return false; 10198 } 10199 10200 return HandleClassZeroInitialization(Info, E, RD, This, Result); 10201 } 10202 10203 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 10204 switch (E->getCastKind()) { 10205 default: 10206 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10207 10208 case CK_ConstructorConversion: 10209 return Visit(E->getSubExpr()); 10210 10211 case CK_DerivedToBase: 10212 case CK_UncheckedDerivedToBase: { 10213 APValue DerivedObject; 10214 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 10215 return false; 10216 if (!DerivedObject.isStruct()) 10217 return Error(E->getSubExpr()); 10218 10219 // Derived-to-base rvalue conversion: just slice off the derived part. 10220 APValue *Value = &DerivedObject; 10221 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 10222 for (CastExpr::path_const_iterator PathI = E->path_begin(), 10223 PathE = E->path_end(); PathI != PathE; ++PathI) { 10224 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 10225 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 10226 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 10227 RD = Base; 10228 } 10229 Result = *Value; 10230 return true; 10231 } 10232 } 10233 } 10234 10235 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10236 if (E->isTransparent()) 10237 return Visit(E->getInit(0)); 10238 return VisitCXXParenListOrInitListExpr(E, E->inits()); 10239 } 10240 10241 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr( 10242 const Expr *ExprToVisit, ArrayRef<Expr *> Args) { 10243 const RecordDecl *RD = 10244 ExprToVisit->getType()->castAs<RecordType>()->getDecl(); 10245 if (RD->isInvalidDecl()) return false; 10246 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 10247 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 10248 10249 EvalInfo::EvaluatingConstructorRAII EvalObj( 10250 Info, 10251 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 10252 CXXRD && CXXRD->getNumBases()); 10253 10254 if (RD->isUnion()) { 10255 const FieldDecl *Field; 10256 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) { 10257 Field = ILE->getInitializedFieldInUnion(); 10258 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) { 10259 Field = PLIE->getInitializedFieldInUnion(); 10260 } else { 10261 llvm_unreachable( 10262 "Expression is neither an init list nor a C++ paren list"); 10263 } 10264 10265 Result = APValue(Field); 10266 if (!Field) 10267 return true; 10268 10269 // If the initializer list for a union does not contain any elements, the 10270 // first element of the union is value-initialized. 10271 // FIXME: The element should be initialized from an initializer list. 10272 // Is this difference ever observable for initializer lists which 10273 // we don't build? 10274 ImplicitValueInitExpr VIE(Field->getType()); 10275 const Expr *InitExpr = Args.empty() ? &VIE : Args[0]; 10276 10277 LValue Subobject = This; 10278 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 10279 return false; 10280 10281 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 10282 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 10283 isa<CXXDefaultInitExpr>(InitExpr)); 10284 10285 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 10286 if (Field->isBitField()) 10287 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 10288 Field); 10289 return true; 10290 } 10291 10292 return false; 10293 } 10294 10295 if (!Result.hasValue()) 10296 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 10297 std::distance(RD->field_begin(), RD->field_end())); 10298 unsigned ElementNo = 0; 10299 bool Success = true; 10300 10301 // Initialize base classes. 10302 if (CXXRD && CXXRD->getNumBases()) { 10303 for (const auto &Base : CXXRD->bases()) { 10304 assert(ElementNo < Args.size() && "missing init for base class"); 10305 const Expr *Init = Args[ElementNo]; 10306 10307 LValue Subobject = This; 10308 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 10309 return false; 10310 10311 APValue &FieldVal = Result.getStructBase(ElementNo); 10312 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 10313 if (!Info.noteFailure()) 10314 return false; 10315 Success = false; 10316 } 10317 ++ElementNo; 10318 } 10319 10320 EvalObj.finishedConstructingBases(); 10321 } 10322 10323 // Initialize members. 10324 for (const auto *Field : RD->fields()) { 10325 // Anonymous bit-fields are not considered members of the class for 10326 // purposes of aggregate initialization. 10327 if (Field->isUnnamedBitfield()) 10328 continue; 10329 10330 LValue Subobject = This; 10331 10332 bool HaveInit = ElementNo < Args.size(); 10333 10334 // FIXME: Diagnostics here should point to the end of the initializer 10335 // list, not the start. 10336 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit, 10337 Subobject, Field, &Layout)) 10338 return false; 10339 10340 // Perform an implicit value-initialization for members beyond the end of 10341 // the initializer list. 10342 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 10343 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE; 10344 10345 if (Field->getType()->isIncompleteArrayType()) { 10346 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) { 10347 if (!CAT->getSize().isZero()) { 10348 // Bail out for now. This might sort of "work", but the rest of the 10349 // code isn't really prepared to handle it. 10350 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array); 10351 return false; 10352 } 10353 } 10354 } 10355 10356 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 10357 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 10358 isa<CXXDefaultInitExpr>(Init)); 10359 10360 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10361 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 10362 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 10363 FieldVal, Field))) { 10364 if (!Info.noteFailure()) 10365 return false; 10366 Success = false; 10367 } 10368 } 10369 10370 EvalObj.finishedConstructingFields(); 10371 10372 return Success; 10373 } 10374 10375 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10376 QualType T) { 10377 // Note that E's type is not necessarily the type of our class here; we might 10378 // be initializing an array element instead. 10379 const CXXConstructorDecl *FD = E->getConstructor(); 10380 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 10381 10382 bool ZeroInit = E->requiresZeroInitialization(); 10383 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 10384 // If we've already performed zero-initialization, we're already done. 10385 if (Result.hasValue()) 10386 return true; 10387 10388 if (ZeroInit) 10389 return ZeroInitialization(E, T); 10390 10391 return handleDefaultInitValue(T, Result); 10392 } 10393 10394 const FunctionDecl *Definition = nullptr; 10395 auto Body = FD->getBody(Definition); 10396 10397 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10398 return false; 10399 10400 // Avoid materializing a temporary for an elidable copy/move constructor. 10401 if (E->isElidable() && !ZeroInit) { 10402 // FIXME: This only handles the simplest case, where the source object 10403 // is passed directly as the first argument to the constructor. 10404 // This should also handle stepping though implicit casts and 10405 // and conversion sequences which involve two steps, with a 10406 // conversion operator followed by a converting constructor. 10407 const Expr *SrcObj = E->getArg(0); 10408 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 10409 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 10410 if (const MaterializeTemporaryExpr *ME = 10411 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 10412 return Visit(ME->getSubExpr()); 10413 } 10414 10415 if (ZeroInit && !ZeroInitialization(E, T)) 10416 return false; 10417 10418 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs()); 10419 return HandleConstructorCall(E, This, Args, 10420 cast<CXXConstructorDecl>(Definition), Info, 10421 Result); 10422 } 10423 10424 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 10425 const CXXInheritedCtorInitExpr *E) { 10426 if (!Info.CurrentCall) { 10427 assert(Info.checkingPotentialConstantExpression()); 10428 return false; 10429 } 10430 10431 const CXXConstructorDecl *FD = E->getConstructor(); 10432 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 10433 return false; 10434 10435 const FunctionDecl *Definition = nullptr; 10436 auto Body = FD->getBody(Definition); 10437 10438 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10439 return false; 10440 10441 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 10442 cast<CXXConstructorDecl>(Definition), Info, 10443 Result); 10444 } 10445 10446 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 10447 const CXXStdInitializerListExpr *E) { 10448 const ConstantArrayType *ArrayType = 10449 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 10450 10451 LValue Array; 10452 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 10453 return false; 10454 10455 assert(ArrayType && "unexpected type for array initializer"); 10456 10457 // Get a pointer to the first element of the array. 10458 Array.addArray(Info, E, ArrayType); 10459 10460 auto InvalidType = [&] { 10461 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 10462 << E->getType(); 10463 return false; 10464 }; 10465 10466 // FIXME: Perform the checks on the field types in SemaInit. 10467 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10468 RecordDecl::field_iterator Field = Record->field_begin(); 10469 if (Field == Record->field_end()) 10470 return InvalidType(); 10471 10472 // Start pointer. 10473 if (!Field->getType()->isPointerType() || 10474 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10475 ArrayType->getElementType())) 10476 return InvalidType(); 10477 10478 // FIXME: What if the initializer_list type has base classes, etc? 10479 Result = APValue(APValue::UninitStruct(), 0, 2); 10480 Array.moveInto(Result.getStructField(0)); 10481 10482 if (++Field == Record->field_end()) 10483 return InvalidType(); 10484 10485 if (Field->getType()->isPointerType() && 10486 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10487 ArrayType->getElementType())) { 10488 // End pointer. 10489 if (!HandleLValueArrayAdjustment(Info, E, Array, 10490 ArrayType->getElementType(), 10491 ArrayType->getSize().getZExtValue())) 10492 return false; 10493 Array.moveInto(Result.getStructField(1)); 10494 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10495 // Length. 10496 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10497 else 10498 return InvalidType(); 10499 10500 if (++Field != Record->field_end()) 10501 return InvalidType(); 10502 10503 return true; 10504 } 10505 10506 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10507 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10508 if (ClosureClass->isInvalidDecl()) 10509 return false; 10510 10511 const size_t NumFields = 10512 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10513 10514 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10515 E->capture_init_end()) && 10516 "The number of lambda capture initializers should equal the number of " 10517 "fields within the closure type"); 10518 10519 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10520 // Iterate through all the lambda's closure object's fields and initialize 10521 // them. 10522 auto *CaptureInitIt = E->capture_init_begin(); 10523 bool Success = true; 10524 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10525 for (const auto *Field : ClosureClass->fields()) { 10526 assert(CaptureInitIt != E->capture_init_end()); 10527 // Get the initializer for this field 10528 Expr *const CurFieldInit = *CaptureInitIt++; 10529 10530 // If there is no initializer, either this is a VLA or an error has 10531 // occurred. 10532 if (!CurFieldInit) 10533 return Error(E); 10534 10535 LValue Subobject = This; 10536 10537 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10538 return false; 10539 10540 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10541 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10542 if (!Info.keepEvaluatingAfterFailure()) 10543 return false; 10544 Success = false; 10545 } 10546 } 10547 return Success; 10548 } 10549 10550 static bool EvaluateRecord(const Expr *E, const LValue &This, 10551 APValue &Result, EvalInfo &Info) { 10552 assert(!E->isValueDependent()); 10553 assert(E->isPRValue() && E->getType()->isRecordType() && 10554 "can't evaluate expression as a record rvalue"); 10555 return RecordExprEvaluator(Info, This, Result).Visit(E); 10556 } 10557 10558 //===----------------------------------------------------------------------===// 10559 // Temporary Evaluation 10560 // 10561 // Temporaries are represented in the AST as rvalues, but generally behave like 10562 // lvalues. The full-object of which the temporary is a subobject is implicitly 10563 // materialized so that a reference can bind to it. 10564 //===----------------------------------------------------------------------===// 10565 namespace { 10566 class TemporaryExprEvaluator 10567 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10568 public: 10569 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10570 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10571 10572 /// Visit an expression which constructs the value of this temporary. 10573 bool VisitConstructExpr(const Expr *E) { 10574 APValue &Value = Info.CurrentCall->createTemporary( 10575 E, E->getType(), ScopeKind::FullExpression, Result); 10576 return EvaluateInPlace(Value, Info, Result, E); 10577 } 10578 10579 bool VisitCastExpr(const CastExpr *E) { 10580 switch (E->getCastKind()) { 10581 default: 10582 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10583 10584 case CK_ConstructorConversion: 10585 return VisitConstructExpr(E->getSubExpr()); 10586 } 10587 } 10588 bool VisitInitListExpr(const InitListExpr *E) { 10589 return VisitConstructExpr(E); 10590 } 10591 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10592 return VisitConstructExpr(E); 10593 } 10594 bool VisitCallExpr(const CallExpr *E) { 10595 return VisitConstructExpr(E); 10596 } 10597 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10598 return VisitConstructExpr(E); 10599 } 10600 bool VisitLambdaExpr(const LambdaExpr *E) { 10601 return VisitConstructExpr(E); 10602 } 10603 }; 10604 } // end anonymous namespace 10605 10606 /// Evaluate an expression of record type as a temporary. 10607 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10608 assert(!E->isValueDependent()); 10609 assert(E->isPRValue() && E->getType()->isRecordType()); 10610 return TemporaryExprEvaluator(Info, Result).Visit(E); 10611 } 10612 10613 //===----------------------------------------------------------------------===// 10614 // Vector Evaluation 10615 //===----------------------------------------------------------------------===// 10616 10617 namespace { 10618 class VectorExprEvaluator 10619 : public ExprEvaluatorBase<VectorExprEvaluator> { 10620 APValue &Result; 10621 public: 10622 10623 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10624 : ExprEvaluatorBaseTy(info), Result(Result) {} 10625 10626 bool Success(ArrayRef<APValue> V, const Expr *E) { 10627 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10628 // FIXME: remove this APValue copy. 10629 Result = APValue(V.data(), V.size()); 10630 return true; 10631 } 10632 bool Success(const APValue &V, const Expr *E) { 10633 assert(V.isVector()); 10634 Result = V; 10635 return true; 10636 } 10637 bool ZeroInitialization(const Expr *E); 10638 10639 bool VisitUnaryReal(const UnaryOperator *E) 10640 { return Visit(E->getSubExpr()); } 10641 bool VisitCastExpr(const CastExpr* E); 10642 bool VisitInitListExpr(const InitListExpr *E); 10643 bool VisitUnaryImag(const UnaryOperator *E); 10644 bool VisitBinaryOperator(const BinaryOperator *E); 10645 bool VisitUnaryOperator(const UnaryOperator *E); 10646 // FIXME: Missing: conditional operator (for GNU 10647 // conditional select), shufflevector, ExtVectorElementExpr 10648 }; 10649 } // end anonymous namespace 10650 10651 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10652 assert(E->isPRValue() && E->getType()->isVectorType() && 10653 "not a vector prvalue"); 10654 return VectorExprEvaluator(Info, Result).Visit(E); 10655 } 10656 10657 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10658 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10659 unsigned NElts = VTy->getNumElements(); 10660 10661 const Expr *SE = E->getSubExpr(); 10662 QualType SETy = SE->getType(); 10663 10664 switch (E->getCastKind()) { 10665 case CK_VectorSplat: { 10666 APValue Val = APValue(); 10667 if (SETy->isIntegerType()) { 10668 APSInt IntResult; 10669 if (!EvaluateInteger(SE, IntResult, Info)) 10670 return false; 10671 Val = APValue(std::move(IntResult)); 10672 } else if (SETy->isRealFloatingType()) { 10673 APFloat FloatResult(0.0); 10674 if (!EvaluateFloat(SE, FloatResult, Info)) 10675 return false; 10676 Val = APValue(std::move(FloatResult)); 10677 } else { 10678 return Error(E); 10679 } 10680 10681 // Splat and create vector APValue. 10682 SmallVector<APValue, 4> Elts(NElts, Val); 10683 return Success(Elts, E); 10684 } 10685 case CK_BitCast: { 10686 APValue SVal; 10687 if (!Evaluate(SVal, Info, SE)) 10688 return false; 10689 10690 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) { 10691 // Give up if the input isn't an int, float, or vector. For example, we 10692 // reject "(v4i16)(intptr_t)&a". 10693 Info.FFDiag(E, diag::note_constexpr_invalid_cast) 10694 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 10695 return false; 10696 } 10697 10698 if (!handleRValueToRValueBitCast(Info, Result, SVal, E)) 10699 return false; 10700 10701 return true; 10702 } 10703 default: 10704 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10705 } 10706 } 10707 10708 bool 10709 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10710 const VectorType *VT = E->getType()->castAs<VectorType>(); 10711 unsigned NumInits = E->getNumInits(); 10712 unsigned NumElements = VT->getNumElements(); 10713 10714 QualType EltTy = VT->getElementType(); 10715 SmallVector<APValue, 4> Elements; 10716 10717 // The number of initializers can be less than the number of 10718 // vector elements. For OpenCL, this can be due to nested vector 10719 // initialization. For GCC compatibility, missing trailing elements 10720 // should be initialized with zeroes. 10721 unsigned CountInits = 0, CountElts = 0; 10722 while (CountElts < NumElements) { 10723 // Handle nested vector initialization. 10724 if (CountInits < NumInits 10725 && E->getInit(CountInits)->getType()->isVectorType()) { 10726 APValue v; 10727 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10728 return Error(E); 10729 unsigned vlen = v.getVectorLength(); 10730 for (unsigned j = 0; j < vlen; j++) 10731 Elements.push_back(v.getVectorElt(j)); 10732 CountElts += vlen; 10733 } else if (EltTy->isIntegerType()) { 10734 llvm::APSInt sInt(32); 10735 if (CountInits < NumInits) { 10736 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10737 return false; 10738 } else // trailing integer zero. 10739 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10740 Elements.push_back(APValue(sInt)); 10741 CountElts++; 10742 } else { 10743 llvm::APFloat f(0.0); 10744 if (CountInits < NumInits) { 10745 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10746 return false; 10747 } else // trailing float zero. 10748 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10749 Elements.push_back(APValue(f)); 10750 CountElts++; 10751 } 10752 CountInits++; 10753 } 10754 return Success(Elements, E); 10755 } 10756 10757 bool 10758 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10759 const auto *VT = E->getType()->castAs<VectorType>(); 10760 QualType EltTy = VT->getElementType(); 10761 APValue ZeroElement; 10762 if (EltTy->isIntegerType()) 10763 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10764 else 10765 ZeroElement = 10766 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10767 10768 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10769 return Success(Elements, E); 10770 } 10771 10772 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10773 VisitIgnoredValue(E->getSubExpr()); 10774 return ZeroInitialization(E); 10775 } 10776 10777 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10778 BinaryOperatorKind Op = E->getOpcode(); 10779 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10780 "Operation not supported on vector types"); 10781 10782 if (Op == BO_Comma) 10783 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10784 10785 Expr *LHS = E->getLHS(); 10786 Expr *RHS = E->getRHS(); 10787 10788 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10789 "Must both be vector types"); 10790 // Checking JUST the types are the same would be fine, except shifts don't 10791 // need to have their types be the same (since you always shift by an int). 10792 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10793 E->getType()->castAs<VectorType>()->getNumElements() && 10794 RHS->getType()->castAs<VectorType>()->getNumElements() == 10795 E->getType()->castAs<VectorType>()->getNumElements() && 10796 "All operands must be the same size."); 10797 10798 APValue LHSValue; 10799 APValue RHSValue; 10800 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10801 if (!LHSOK && !Info.noteFailure()) 10802 return false; 10803 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10804 return false; 10805 10806 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10807 return false; 10808 10809 return Success(LHSValue, E); 10810 } 10811 10812 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, 10813 QualType ResultTy, 10814 UnaryOperatorKind Op, 10815 APValue Elt) { 10816 switch (Op) { 10817 case UO_Plus: 10818 // Nothing to do here. 10819 return Elt; 10820 case UO_Minus: 10821 if (Elt.getKind() == APValue::Int) { 10822 Elt.getInt().negate(); 10823 } else { 10824 assert(Elt.getKind() == APValue::Float && 10825 "Vector can only be int or float type"); 10826 Elt.getFloat().changeSign(); 10827 } 10828 return Elt; 10829 case UO_Not: 10830 // This is only valid for integral types anyway, so we don't have to handle 10831 // float here. 10832 assert(Elt.getKind() == APValue::Int && 10833 "Vector operator ~ can only be int"); 10834 Elt.getInt().flipAllBits(); 10835 return Elt; 10836 case UO_LNot: { 10837 if (Elt.getKind() == APValue::Int) { 10838 Elt.getInt() = !Elt.getInt(); 10839 // operator ! on vectors returns -1 for 'truth', so negate it. 10840 Elt.getInt().negate(); 10841 return Elt; 10842 } 10843 assert(Elt.getKind() == APValue::Float && 10844 "Vector can only be int or float type"); 10845 // Float types result in an int of the same size, but -1 for true, or 0 for 10846 // false. 10847 APSInt EltResult{Ctx.getIntWidth(ResultTy), 10848 ResultTy->isUnsignedIntegerType()}; 10849 if (Elt.getFloat().isZero()) 10850 EltResult.setAllBits(); 10851 else 10852 EltResult.clearAllBits(); 10853 10854 return APValue{EltResult}; 10855 } 10856 default: 10857 // FIXME: Implement the rest of the unary operators. 10858 return std::nullopt; 10859 } 10860 } 10861 10862 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10863 Expr *SubExpr = E->getSubExpr(); 10864 const auto *VD = SubExpr->getType()->castAs<VectorType>(); 10865 // This result element type differs in the case of negating a floating point 10866 // vector, since the result type is the a vector of the equivilant sized 10867 // integer. 10868 const QualType ResultEltTy = VD->getElementType(); 10869 UnaryOperatorKind Op = E->getOpcode(); 10870 10871 APValue SubExprValue; 10872 if (!Evaluate(SubExprValue, Info, SubExpr)) 10873 return false; 10874 10875 // FIXME: This vector evaluator someday needs to be changed to be LValue 10876 // aware/keep LValue information around, rather than dealing with just vector 10877 // types directly. Until then, we cannot handle cases where the operand to 10878 // these unary operators is an LValue. The only case I've been able to see 10879 // cause this is operator++ assigning to a member expression (only valid in 10880 // altivec compilations) in C mode, so this shouldn't limit us too much. 10881 if (SubExprValue.isLValue()) 10882 return false; 10883 10884 assert(SubExprValue.getVectorLength() == VD->getNumElements() && 10885 "Vector length doesn't match type?"); 10886 10887 SmallVector<APValue, 4> ResultElements; 10888 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { 10889 std::optional<APValue> Elt = handleVectorUnaryOperator( 10890 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); 10891 if (!Elt) 10892 return false; 10893 ResultElements.push_back(*Elt); 10894 } 10895 return Success(APValue(ResultElements.data(), ResultElements.size()), E); 10896 } 10897 10898 //===----------------------------------------------------------------------===// 10899 // Array Evaluation 10900 //===----------------------------------------------------------------------===// 10901 10902 namespace { 10903 class ArrayExprEvaluator 10904 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10905 const LValue &This; 10906 APValue &Result; 10907 public: 10908 10909 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10910 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10911 10912 bool Success(const APValue &V, const Expr *E) { 10913 assert(V.isArray() && "expected array"); 10914 Result = V; 10915 return true; 10916 } 10917 10918 bool ZeroInitialization(const Expr *E) { 10919 const ConstantArrayType *CAT = 10920 Info.Ctx.getAsConstantArrayType(E->getType()); 10921 if (!CAT) { 10922 if (E->getType()->isIncompleteArrayType()) { 10923 // We can be asked to zero-initialize a flexible array member; this 10924 // is represented as an ImplicitValueInitExpr of incomplete array 10925 // type. In this case, the array has zero elements. 10926 Result = APValue(APValue::UninitArray(), 0, 0); 10927 return true; 10928 } 10929 // FIXME: We could handle VLAs here. 10930 return Error(E); 10931 } 10932 10933 Result = APValue(APValue::UninitArray(), 0, 10934 CAT->getSize().getZExtValue()); 10935 if (!Result.hasArrayFiller()) 10936 return true; 10937 10938 // Zero-initialize all elements. 10939 LValue Subobject = This; 10940 Subobject.addArray(Info, E, CAT); 10941 ImplicitValueInitExpr VIE(CAT->getElementType()); 10942 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10943 } 10944 10945 bool VisitCallExpr(const CallExpr *E) { 10946 return handleCallExpr(E, Result, &This); 10947 } 10948 bool VisitInitListExpr(const InitListExpr *E, 10949 QualType AllocType = QualType()); 10950 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10951 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10952 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10953 const LValue &Subobject, 10954 APValue *Value, QualType Type); 10955 bool VisitStringLiteral(const StringLiteral *E, 10956 QualType AllocType = QualType()) { 10957 expandStringLiteral(Info, E, Result, AllocType); 10958 return true; 10959 } 10960 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E); 10961 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit, 10962 ArrayRef<Expr *> Args, 10963 const Expr *ArrayFiller, 10964 QualType AllocType = QualType()); 10965 }; 10966 } // end anonymous namespace 10967 10968 static bool EvaluateArray(const Expr *E, const LValue &This, 10969 APValue &Result, EvalInfo &Info) { 10970 assert(!E->isValueDependent()); 10971 assert(E->isPRValue() && E->getType()->isArrayType() && 10972 "not an array prvalue"); 10973 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10974 } 10975 10976 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10977 APValue &Result, const InitListExpr *ILE, 10978 QualType AllocType) { 10979 assert(!ILE->isValueDependent()); 10980 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10981 "not an array prvalue"); 10982 return ArrayExprEvaluator(Info, This, Result) 10983 .VisitInitListExpr(ILE, AllocType); 10984 } 10985 10986 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10987 APValue &Result, 10988 const CXXConstructExpr *CCE, 10989 QualType AllocType) { 10990 assert(!CCE->isValueDependent()); 10991 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10992 "not an array prvalue"); 10993 return ArrayExprEvaluator(Info, This, Result) 10994 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10995 } 10996 10997 // Return true iff the given array filler may depend on the element index. 10998 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10999 // For now, just allow non-class value-initialization and initialization 11000 // lists comprised of them. 11001 if (isa<ImplicitValueInitExpr>(FillerExpr)) 11002 return false; 11003 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 11004 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 11005 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 11006 return true; 11007 } 11008 11009 if (ILE->hasArrayFiller() && 11010 MaybeElementDependentArrayFiller(ILE->getArrayFiller())) 11011 return true; 11012 11013 return false; 11014 } 11015 return true; 11016 } 11017 11018 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 11019 QualType AllocType) { 11020 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 11021 AllocType.isNull() ? E->getType() : AllocType); 11022 if (!CAT) 11023 return Error(E); 11024 11025 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 11026 // an appropriately-typed string literal enclosed in braces. 11027 if (E->isStringLiteralInit()) { 11028 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 11029 // FIXME: Support ObjCEncodeExpr here once we support it in 11030 // ArrayExprEvaluator generally. 11031 if (!SL) 11032 return Error(E); 11033 return VisitStringLiteral(SL, AllocType); 11034 } 11035 // Any other transparent list init will need proper handling of the 11036 // AllocType; we can't just recurse to the inner initializer. 11037 assert(!E->isTransparent() && 11038 "transparent array list initialization is not string literal init?"); 11039 11040 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(), 11041 AllocType); 11042 } 11043 11044 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr( 11045 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller, 11046 QualType AllocType) { 11047 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 11048 AllocType.isNull() ? ExprToVisit->getType() : AllocType); 11049 11050 bool Success = true; 11051 11052 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 11053 "zero-initialized array shouldn't have any initialized elts"); 11054 APValue Filler; 11055 if (Result.isArray() && Result.hasArrayFiller()) 11056 Filler = Result.getArrayFiller(); 11057 11058 unsigned NumEltsToInit = Args.size(); 11059 unsigned NumElts = CAT->getSize().getZExtValue(); 11060 11061 // If the initializer might depend on the array index, run it for each 11062 // array element. 11063 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller)) 11064 NumEltsToInit = NumElts; 11065 11066 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 11067 << NumEltsToInit << ".\n"); 11068 11069 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 11070 11071 // If the array was previously zero-initialized, preserve the 11072 // zero-initialized values. 11073 if (Filler.hasValue()) { 11074 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 11075 Result.getArrayInitializedElt(I) = Filler; 11076 if (Result.hasArrayFiller()) 11077 Result.getArrayFiller() = Filler; 11078 } 11079 11080 LValue Subobject = This; 11081 Subobject.addArray(Info, ExprToVisit, CAT); 11082 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 11083 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller; 11084 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 11085 Info, Subobject, Init) || 11086 !HandleLValueArrayAdjustment(Info, Init, Subobject, 11087 CAT->getElementType(), 1)) { 11088 if (!Info.noteFailure()) 11089 return false; 11090 Success = false; 11091 } 11092 } 11093 11094 if (!Result.hasArrayFiller()) 11095 return Success; 11096 11097 // If we get here, we have a trivial filler, which we can just evaluate 11098 // once and splat over the rest of the array elements. 11099 assert(ArrayFiller && "no array filler for incomplete init list"); 11100 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 11101 ArrayFiller) && 11102 Success; 11103 } 11104 11105 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 11106 LValue CommonLV; 11107 if (E->getCommonExpr() && 11108 !Evaluate(Info.CurrentCall->createTemporary( 11109 E->getCommonExpr(), 11110 getStorageType(Info.Ctx, E->getCommonExpr()), 11111 ScopeKind::FullExpression, CommonLV), 11112 Info, E->getCommonExpr()->getSourceExpr())) 11113 return false; 11114 11115 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 11116 11117 uint64_t Elements = CAT->getSize().getZExtValue(); 11118 Result = APValue(APValue::UninitArray(), Elements, Elements); 11119 11120 LValue Subobject = This; 11121 Subobject.addArray(Info, E, CAT); 11122 11123 bool Success = true; 11124 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 11125 // C++ [class.temporary]/5 11126 // There are four contexts in which temporaries are destroyed at a different 11127 // point than the end of the full-expression. [...] The second context is 11128 // when a copy constructor is called to copy an element of an array while 11129 // the entire array is copied [...]. In either case, if the constructor has 11130 // one or more default arguments, the destruction of every temporary created 11131 // in a default argument is sequenced before the construction of the next 11132 // array element, if any. 11133 FullExpressionRAII Scope(Info); 11134 11135 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 11136 Info, Subobject, E->getSubExpr()) || 11137 !HandleLValueArrayAdjustment(Info, E, Subobject, 11138 CAT->getElementType(), 1)) { 11139 if (!Info.noteFailure()) 11140 return false; 11141 Success = false; 11142 } 11143 11144 // Make sure we run the destructors too. 11145 Scope.destroy(); 11146 } 11147 11148 return Success; 11149 } 11150 11151 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 11152 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 11153 } 11154 11155 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 11156 const LValue &Subobject, 11157 APValue *Value, 11158 QualType Type) { 11159 bool HadZeroInit = Value->hasValue(); 11160 11161 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 11162 unsigned FinalSize = CAT->getSize().getZExtValue(); 11163 11164 // Preserve the array filler if we had prior zero-initialization. 11165 APValue Filler = 11166 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 11167 : APValue(); 11168 11169 *Value = APValue(APValue::UninitArray(), 0, FinalSize); 11170 if (FinalSize == 0) 11171 return true; 11172 11173 bool HasTrivialConstructor = CheckTrivialDefaultConstructor( 11174 Info, E->getExprLoc(), E->getConstructor(), 11175 E->requiresZeroInitialization()); 11176 LValue ArrayElt = Subobject; 11177 ArrayElt.addArray(Info, E, CAT); 11178 // We do the whole initialization in two passes, first for just one element, 11179 // then for the whole array. It's possible we may find out we can't do const 11180 // init in the first pass, in which case we avoid allocating a potentially 11181 // large array. We don't do more passes because expanding array requires 11182 // copying the data, which is wasteful. 11183 for (const unsigned N : {1u, FinalSize}) { 11184 unsigned OldElts = Value->getArrayInitializedElts(); 11185 if (OldElts == N) 11186 break; 11187 11188 // Expand the array to appropriate size. 11189 APValue NewValue(APValue::UninitArray(), N, FinalSize); 11190 for (unsigned I = 0; I < OldElts; ++I) 11191 NewValue.getArrayInitializedElt(I).swap( 11192 Value->getArrayInitializedElt(I)); 11193 Value->swap(NewValue); 11194 11195 if (HadZeroInit) 11196 for (unsigned I = OldElts; I < N; ++I) 11197 Value->getArrayInitializedElt(I) = Filler; 11198 11199 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) { 11200 // If we have a trivial constructor, only evaluate it once and copy 11201 // the result into all the array elements. 11202 APValue &FirstResult = Value->getArrayInitializedElt(0); 11203 for (unsigned I = OldElts; I < FinalSize; ++I) 11204 Value->getArrayInitializedElt(I) = FirstResult; 11205 } else { 11206 for (unsigned I = OldElts; I < N; ++I) { 11207 if (!VisitCXXConstructExpr(E, ArrayElt, 11208 &Value->getArrayInitializedElt(I), 11209 CAT->getElementType()) || 11210 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 11211 CAT->getElementType(), 1)) 11212 return false; 11213 // When checking for const initilization any diagnostic is considered 11214 // an error. 11215 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && 11216 !Info.keepEvaluatingAfterFailure()) 11217 return false; 11218 } 11219 } 11220 } 11221 11222 return true; 11223 } 11224 11225 if (!Type->isRecordType()) 11226 return Error(E); 11227 11228 return RecordExprEvaluator(Info, Subobject, *Value) 11229 .VisitCXXConstructExpr(E, Type); 11230 } 11231 11232 bool ArrayExprEvaluator::VisitCXXParenListInitExpr( 11233 const CXXParenListInitExpr *E) { 11234 assert(dyn_cast<ConstantArrayType>(E->getType()) && 11235 "Expression result is not a constant array type"); 11236 11237 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(), 11238 E->getArrayFiller()); 11239 } 11240 11241 //===----------------------------------------------------------------------===// 11242 // Integer Evaluation 11243 // 11244 // As a GNU extension, we support casting pointers to sufficiently-wide integer 11245 // types and back in constant folding. Integer values are thus represented 11246 // either as an integer-valued APValue, or as an lvalue-valued APValue. 11247 //===----------------------------------------------------------------------===// 11248 11249 namespace { 11250 class IntExprEvaluator 11251 : public ExprEvaluatorBase<IntExprEvaluator> { 11252 APValue &Result; 11253 public: 11254 IntExprEvaluator(EvalInfo &info, APValue &result) 11255 : ExprEvaluatorBaseTy(info), Result(result) {} 11256 11257 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 11258 assert(E->getType()->isIntegralOrEnumerationType() && 11259 "Invalid evaluation result."); 11260 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 11261 "Invalid evaluation result."); 11262 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 11263 "Invalid evaluation result."); 11264 Result = APValue(SI); 11265 return true; 11266 } 11267 bool Success(const llvm::APSInt &SI, const Expr *E) { 11268 return Success(SI, E, Result); 11269 } 11270 11271 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 11272 assert(E->getType()->isIntegralOrEnumerationType() && 11273 "Invalid evaluation result."); 11274 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 11275 "Invalid evaluation result."); 11276 Result = APValue(APSInt(I)); 11277 Result.getInt().setIsUnsigned( 11278 E->getType()->isUnsignedIntegerOrEnumerationType()); 11279 return true; 11280 } 11281 bool Success(const llvm::APInt &I, const Expr *E) { 11282 return Success(I, E, Result); 11283 } 11284 11285 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11286 assert(E->getType()->isIntegralOrEnumerationType() && 11287 "Invalid evaluation result."); 11288 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 11289 return true; 11290 } 11291 bool Success(uint64_t Value, const Expr *E) { 11292 return Success(Value, E, Result); 11293 } 11294 11295 bool Success(CharUnits Size, const Expr *E) { 11296 return Success(Size.getQuantity(), E); 11297 } 11298 11299 bool Success(const APValue &V, const Expr *E) { 11300 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 11301 Result = V; 11302 return true; 11303 } 11304 return Success(V.getInt(), E); 11305 } 11306 11307 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 11308 11309 //===--------------------------------------------------------------------===// 11310 // Visitor Methods 11311 //===--------------------------------------------------------------------===// 11312 11313 bool VisitIntegerLiteral(const IntegerLiteral *E) { 11314 return Success(E->getValue(), E); 11315 } 11316 bool VisitCharacterLiteral(const CharacterLiteral *E) { 11317 return Success(E->getValue(), E); 11318 } 11319 11320 bool CheckReferencedDecl(const Expr *E, const Decl *D); 11321 bool VisitDeclRefExpr(const DeclRefExpr *E) { 11322 if (CheckReferencedDecl(E, E->getDecl())) 11323 return true; 11324 11325 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 11326 } 11327 bool VisitMemberExpr(const MemberExpr *E) { 11328 if (CheckReferencedDecl(E, E->getMemberDecl())) { 11329 VisitIgnoredBaseExpression(E->getBase()); 11330 return true; 11331 } 11332 11333 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 11334 } 11335 11336 bool VisitCallExpr(const CallExpr *E); 11337 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 11338 bool VisitBinaryOperator(const BinaryOperator *E); 11339 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 11340 bool VisitUnaryOperator(const UnaryOperator *E); 11341 11342 bool VisitCastExpr(const CastExpr* E); 11343 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 11344 11345 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 11346 return Success(E->getValue(), E); 11347 } 11348 11349 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 11350 return Success(E->getValue(), E); 11351 } 11352 11353 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 11354 if (Info.ArrayInitIndex == uint64_t(-1)) { 11355 // We were asked to evaluate this subexpression independent of the 11356 // enclosing ArrayInitLoopExpr. We can't do that. 11357 Info.FFDiag(E); 11358 return false; 11359 } 11360 return Success(Info.ArrayInitIndex, E); 11361 } 11362 11363 // Note, GNU defines __null as an integer, not a pointer. 11364 bool VisitGNUNullExpr(const GNUNullExpr *E) { 11365 return ZeroInitialization(E); 11366 } 11367 11368 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 11369 return Success(E->getValue(), E); 11370 } 11371 11372 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 11373 return Success(E->getValue(), E); 11374 } 11375 11376 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 11377 return Success(E->getValue(), E); 11378 } 11379 11380 bool VisitUnaryReal(const UnaryOperator *E); 11381 bool VisitUnaryImag(const UnaryOperator *E); 11382 11383 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 11384 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 11385 bool VisitSourceLocExpr(const SourceLocExpr *E); 11386 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 11387 bool VisitRequiresExpr(const RequiresExpr *E); 11388 // FIXME: Missing: array subscript of vector, member of vector 11389 }; 11390 11391 class FixedPointExprEvaluator 11392 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 11393 APValue &Result; 11394 11395 public: 11396 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 11397 : ExprEvaluatorBaseTy(info), Result(result) {} 11398 11399 bool Success(const llvm::APInt &I, const Expr *E) { 11400 return Success( 11401 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11402 } 11403 11404 bool Success(uint64_t Value, const Expr *E) { 11405 return Success( 11406 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11407 } 11408 11409 bool Success(const APValue &V, const Expr *E) { 11410 return Success(V.getFixedPoint(), E); 11411 } 11412 11413 bool Success(const APFixedPoint &V, const Expr *E) { 11414 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 11415 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 11416 "Invalid evaluation result."); 11417 Result = APValue(V); 11418 return true; 11419 } 11420 11421 //===--------------------------------------------------------------------===// 11422 // Visitor Methods 11423 //===--------------------------------------------------------------------===// 11424 11425 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 11426 return Success(E->getValue(), E); 11427 } 11428 11429 bool VisitCastExpr(const CastExpr *E); 11430 bool VisitUnaryOperator(const UnaryOperator *E); 11431 bool VisitBinaryOperator(const BinaryOperator *E); 11432 }; 11433 } // end anonymous namespace 11434 11435 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 11436 /// produce either the integer value or a pointer. 11437 /// 11438 /// GCC has a heinous extension which folds casts between pointer types and 11439 /// pointer-sized integral types. We support this by allowing the evaluation of 11440 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 11441 /// Some simple arithmetic on such values is supported (they are treated much 11442 /// like char*). 11443 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 11444 EvalInfo &Info) { 11445 assert(!E->isValueDependent()); 11446 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 11447 return IntExprEvaluator(Info, Result).Visit(E); 11448 } 11449 11450 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 11451 assert(!E->isValueDependent()); 11452 APValue Val; 11453 if (!EvaluateIntegerOrLValue(E, Val, Info)) 11454 return false; 11455 if (!Val.isInt()) { 11456 // FIXME: It would be better to produce the diagnostic for casting 11457 // a pointer to an integer. 11458 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11459 return false; 11460 } 11461 Result = Val.getInt(); 11462 return true; 11463 } 11464 11465 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 11466 APValue Evaluated = E->EvaluateInContext( 11467 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 11468 return Success(Evaluated, E); 11469 } 11470 11471 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 11472 EvalInfo &Info) { 11473 assert(!E->isValueDependent()); 11474 if (E->getType()->isFixedPointType()) { 11475 APValue Val; 11476 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 11477 return false; 11478 if (!Val.isFixedPoint()) 11479 return false; 11480 11481 Result = Val.getFixedPoint(); 11482 return true; 11483 } 11484 return false; 11485 } 11486 11487 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 11488 EvalInfo &Info) { 11489 assert(!E->isValueDependent()); 11490 if (E->getType()->isIntegerType()) { 11491 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 11492 APSInt Val; 11493 if (!EvaluateInteger(E, Val, Info)) 11494 return false; 11495 Result = APFixedPoint(Val, FXSema); 11496 return true; 11497 } else if (E->getType()->isFixedPointType()) { 11498 return EvaluateFixedPoint(E, Result, Info); 11499 } 11500 return false; 11501 } 11502 11503 /// Check whether the given declaration can be directly converted to an integral 11504 /// rvalue. If not, no diagnostic is produced; there are other things we can 11505 /// try. 11506 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 11507 // Enums are integer constant exprs. 11508 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 11509 // Check for signedness/width mismatches between E type and ECD value. 11510 bool SameSign = (ECD->getInitVal().isSigned() 11511 == E->getType()->isSignedIntegerOrEnumerationType()); 11512 bool SameWidth = (ECD->getInitVal().getBitWidth() 11513 == Info.Ctx.getIntWidth(E->getType())); 11514 if (SameSign && SameWidth) 11515 return Success(ECD->getInitVal(), E); 11516 else { 11517 // Get rid of mismatch (otherwise Success assertions will fail) 11518 // by computing a new value matching the type of E. 11519 llvm::APSInt Val = ECD->getInitVal(); 11520 if (!SameSign) 11521 Val.setIsSigned(!ECD->getInitVal().isSigned()); 11522 if (!SameWidth) 11523 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 11524 return Success(Val, E); 11525 } 11526 } 11527 return false; 11528 } 11529 11530 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11531 /// as GCC. 11532 GCCTypeClass EvaluateBuiltinClassifyType(QualType T, 11533 const LangOptions &LangOpts) { 11534 assert(!T->isDependentType() && "unexpected dependent type"); 11535 11536 QualType CanTy = T.getCanonicalType(); 11537 11538 switch (CanTy->getTypeClass()) { 11539 #define TYPE(ID, BASE) 11540 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 11541 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 11542 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 11543 #include "clang/AST/TypeNodes.inc" 11544 case Type::Auto: 11545 case Type::DeducedTemplateSpecialization: 11546 llvm_unreachable("unexpected non-canonical or dependent type"); 11547 11548 case Type::Builtin: 11549 switch (cast<BuiltinType>(CanTy)->getKind()) { 11550 #define BUILTIN_TYPE(ID, SINGLETON_ID) 11551 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 11552 case BuiltinType::ID: return GCCTypeClass::Integer; 11553 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 11554 case BuiltinType::ID: return GCCTypeClass::RealFloat; 11555 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 11556 case BuiltinType::ID: break; 11557 #include "clang/AST/BuiltinTypes.def" 11558 case BuiltinType::Void: 11559 return GCCTypeClass::Void; 11560 11561 case BuiltinType::Bool: 11562 return GCCTypeClass::Bool; 11563 11564 case BuiltinType::Char_U: 11565 case BuiltinType::UChar: 11566 case BuiltinType::WChar_U: 11567 case BuiltinType::Char8: 11568 case BuiltinType::Char16: 11569 case BuiltinType::Char32: 11570 case BuiltinType::UShort: 11571 case BuiltinType::UInt: 11572 case BuiltinType::ULong: 11573 case BuiltinType::ULongLong: 11574 case BuiltinType::UInt128: 11575 return GCCTypeClass::Integer; 11576 11577 case BuiltinType::UShortAccum: 11578 case BuiltinType::UAccum: 11579 case BuiltinType::ULongAccum: 11580 case BuiltinType::UShortFract: 11581 case BuiltinType::UFract: 11582 case BuiltinType::ULongFract: 11583 case BuiltinType::SatUShortAccum: 11584 case BuiltinType::SatUAccum: 11585 case BuiltinType::SatULongAccum: 11586 case BuiltinType::SatUShortFract: 11587 case BuiltinType::SatUFract: 11588 case BuiltinType::SatULongFract: 11589 return GCCTypeClass::None; 11590 11591 case BuiltinType::NullPtr: 11592 11593 case BuiltinType::ObjCId: 11594 case BuiltinType::ObjCClass: 11595 case BuiltinType::ObjCSel: 11596 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11597 case BuiltinType::Id: 11598 #include "clang/Basic/OpenCLImageTypes.def" 11599 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11600 case BuiltinType::Id: 11601 #include "clang/Basic/OpenCLExtensionTypes.def" 11602 case BuiltinType::OCLSampler: 11603 case BuiltinType::OCLEvent: 11604 case BuiltinType::OCLClkEvent: 11605 case BuiltinType::OCLQueue: 11606 case BuiltinType::OCLReserveID: 11607 #define SVE_TYPE(Name, Id, SingletonId) \ 11608 case BuiltinType::Id: 11609 #include "clang/Basic/AArch64SVEACLETypes.def" 11610 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11611 case BuiltinType::Id: 11612 #include "clang/Basic/PPCTypes.def" 11613 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11614 #include "clang/Basic/RISCVVTypes.def" 11615 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11616 #include "clang/Basic/WebAssemblyReferenceTypes.def" 11617 return GCCTypeClass::None; 11618 11619 case BuiltinType::Dependent: 11620 llvm_unreachable("unexpected dependent type"); 11621 }; 11622 llvm_unreachable("unexpected placeholder type"); 11623 11624 case Type::Enum: 11625 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11626 11627 case Type::Pointer: 11628 case Type::ConstantArray: 11629 case Type::VariableArray: 11630 case Type::IncompleteArray: 11631 case Type::FunctionNoProto: 11632 case Type::FunctionProto: 11633 return GCCTypeClass::Pointer; 11634 11635 case Type::MemberPointer: 11636 return CanTy->isMemberDataPointerType() 11637 ? GCCTypeClass::PointerToDataMember 11638 : GCCTypeClass::PointerToMemberFunction; 11639 11640 case Type::Complex: 11641 return GCCTypeClass::Complex; 11642 11643 case Type::Record: 11644 return CanTy->isUnionType() ? GCCTypeClass::Union 11645 : GCCTypeClass::ClassOrStruct; 11646 11647 case Type::Atomic: 11648 // GCC classifies _Atomic T the same as T. 11649 return EvaluateBuiltinClassifyType( 11650 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11651 11652 case Type::Vector: 11653 case Type::ExtVector: 11654 return GCCTypeClass::Vector; 11655 11656 case Type::BlockPointer: 11657 case Type::ConstantMatrix: 11658 case Type::ObjCObject: 11659 case Type::ObjCInterface: 11660 case Type::ObjCObjectPointer: 11661 case Type::Pipe: 11662 // Classify all other types that don't fit into the regular 11663 // classification the same way. 11664 return GCCTypeClass::None; 11665 11666 case Type::BitInt: 11667 return GCCTypeClass::BitInt; 11668 11669 case Type::LValueReference: 11670 case Type::RValueReference: 11671 llvm_unreachable("invalid type for expression"); 11672 } 11673 11674 llvm_unreachable("unexpected type class"); 11675 } 11676 11677 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11678 /// as GCC. 11679 static GCCTypeClass 11680 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11681 // If no argument was supplied, default to None. This isn't 11682 // ideal, however it is what gcc does. 11683 if (E->getNumArgs() == 0) 11684 return GCCTypeClass::None; 11685 11686 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11687 // being an ICE, but still folds it to a constant using the type of the first 11688 // argument. 11689 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11690 } 11691 11692 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11693 /// __builtin_constant_p when applied to the given pointer. 11694 /// 11695 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11696 /// or it points to the first character of a string literal. 11697 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11698 APValue::LValueBase Base = LV.getLValueBase(); 11699 if (Base.isNull()) { 11700 // A null base is acceptable. 11701 return true; 11702 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11703 if (!isa<StringLiteral>(E)) 11704 return false; 11705 return LV.getLValueOffset().isZero(); 11706 } else if (Base.is<TypeInfoLValue>()) { 11707 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11708 // evaluate to true. 11709 return true; 11710 } else { 11711 // Any other base is not constant enough for GCC. 11712 return false; 11713 } 11714 } 11715 11716 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11717 /// GCC as we can manage. 11718 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11719 // This evaluation is not permitted to have side-effects, so evaluate it in 11720 // a speculative evaluation context. 11721 SpeculativeEvaluationRAII SpeculativeEval(Info); 11722 11723 // Constant-folding is always enabled for the operand of __builtin_constant_p 11724 // (even when the enclosing evaluation context otherwise requires a strict 11725 // language-specific constant expression). 11726 FoldConstant Fold(Info, true); 11727 11728 QualType ArgType = Arg->getType(); 11729 11730 // __builtin_constant_p always has one operand. The rules which gcc follows 11731 // are not precisely documented, but are as follows: 11732 // 11733 // - If the operand is of integral, floating, complex or enumeration type, 11734 // and can be folded to a known value of that type, it returns 1. 11735 // - If the operand can be folded to a pointer to the first character 11736 // of a string literal (or such a pointer cast to an integral type) 11737 // or to a null pointer or an integer cast to a pointer, it returns 1. 11738 // 11739 // Otherwise, it returns 0. 11740 // 11741 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11742 // its support for this did not work prior to GCC 9 and is not yet well 11743 // understood. 11744 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11745 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11746 ArgType->isNullPtrType()) { 11747 APValue V; 11748 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11749 Fold.keepDiagnostics(); 11750 return false; 11751 } 11752 11753 // For a pointer (possibly cast to integer), there are special rules. 11754 if (V.getKind() == APValue::LValue) 11755 return EvaluateBuiltinConstantPForLValue(V); 11756 11757 // Otherwise, any constant value is good enough. 11758 return V.hasValue(); 11759 } 11760 11761 // Anything else isn't considered to be sufficiently constant. 11762 return false; 11763 } 11764 11765 /// Retrieves the "underlying object type" of the given expression, 11766 /// as used by __builtin_object_size. 11767 static QualType getObjectType(APValue::LValueBase B) { 11768 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11769 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11770 return VD->getType(); 11771 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11772 if (isa<CompoundLiteralExpr>(E)) 11773 return E->getType(); 11774 } else if (B.is<TypeInfoLValue>()) { 11775 return B.getTypeInfoType(); 11776 } else if (B.is<DynamicAllocLValue>()) { 11777 return B.getDynamicAllocType(); 11778 } 11779 11780 return QualType(); 11781 } 11782 11783 /// A more selective version of E->IgnoreParenCasts for 11784 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11785 /// to change the type of E. 11786 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11787 /// 11788 /// Always returns an RValue with a pointer representation. 11789 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11790 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11791 11792 auto *NoParens = E->IgnoreParens(); 11793 auto *Cast = dyn_cast<CastExpr>(NoParens); 11794 if (Cast == nullptr) 11795 return NoParens; 11796 11797 // We only conservatively allow a few kinds of casts, because this code is 11798 // inherently a simple solution that seeks to support the common case. 11799 auto CastKind = Cast->getCastKind(); 11800 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11801 CastKind != CK_AddressSpaceConversion) 11802 return NoParens; 11803 11804 auto *SubExpr = Cast->getSubExpr(); 11805 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11806 return NoParens; 11807 return ignorePointerCastsAndParens(SubExpr); 11808 } 11809 11810 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11811 /// record layout. e.g. 11812 /// struct { struct { int a, b; } fst, snd; } obj; 11813 /// obj.fst // no 11814 /// obj.snd // yes 11815 /// obj.fst.a // no 11816 /// obj.fst.b // no 11817 /// obj.snd.a // no 11818 /// obj.snd.b // yes 11819 /// 11820 /// Please note: this function is specialized for how __builtin_object_size 11821 /// views "objects". 11822 /// 11823 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11824 /// correct result, it will always return true. 11825 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11826 assert(!LVal.Designator.Invalid); 11827 11828 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11829 const RecordDecl *Parent = FD->getParent(); 11830 Invalid = Parent->isInvalidDecl(); 11831 if (Invalid || Parent->isUnion()) 11832 return true; 11833 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11834 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11835 }; 11836 11837 auto &Base = LVal.getLValueBase(); 11838 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11839 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11840 bool Invalid; 11841 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11842 return Invalid; 11843 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11844 for (auto *FD : IFD->chain()) { 11845 bool Invalid; 11846 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11847 return Invalid; 11848 } 11849 } 11850 } 11851 11852 unsigned I = 0; 11853 QualType BaseType = getType(Base); 11854 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11855 // If we don't know the array bound, conservatively assume we're looking at 11856 // the final array element. 11857 ++I; 11858 if (BaseType->isIncompleteArrayType()) 11859 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11860 else 11861 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11862 } 11863 11864 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11865 const auto &Entry = LVal.Designator.Entries[I]; 11866 if (BaseType->isArrayType()) { 11867 // Because __builtin_object_size treats arrays as objects, we can ignore 11868 // the index iff this is the last array in the Designator. 11869 if (I + 1 == E) 11870 return true; 11871 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11872 uint64_t Index = Entry.getAsArrayIndex(); 11873 if (Index + 1 != CAT->getSize()) 11874 return false; 11875 BaseType = CAT->getElementType(); 11876 } else if (BaseType->isAnyComplexType()) { 11877 const auto *CT = BaseType->castAs<ComplexType>(); 11878 uint64_t Index = Entry.getAsArrayIndex(); 11879 if (Index != 1) 11880 return false; 11881 BaseType = CT->getElementType(); 11882 } else if (auto *FD = getAsField(Entry)) { 11883 bool Invalid; 11884 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11885 return Invalid; 11886 BaseType = FD->getType(); 11887 } else { 11888 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11889 return false; 11890 } 11891 } 11892 return true; 11893 } 11894 11895 /// Tests to see if the LValue has a user-specified designator (that isn't 11896 /// necessarily valid). Note that this always returns 'true' if the LValue has 11897 /// an unsized array as its first designator entry, because there's currently no 11898 /// way to tell if the user typed *foo or foo[0]. 11899 static bool refersToCompleteObject(const LValue &LVal) { 11900 if (LVal.Designator.Invalid) 11901 return false; 11902 11903 if (!LVal.Designator.Entries.empty()) 11904 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11905 11906 if (!LVal.InvalidBase) 11907 return true; 11908 11909 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11910 // the LValueBase. 11911 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11912 return !E || !isa<MemberExpr>(E); 11913 } 11914 11915 /// Attempts to detect a user writing into a piece of memory that's impossible 11916 /// to figure out the size of by just using types. 11917 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11918 const SubobjectDesignator &Designator = LVal.Designator; 11919 // Notes: 11920 // - Users can only write off of the end when we have an invalid base. Invalid 11921 // bases imply we don't know where the memory came from. 11922 // - We used to be a bit more aggressive here; we'd only be conservative if 11923 // the array at the end was flexible, or if it had 0 or 1 elements. This 11924 // broke some common standard library extensions (PR30346), but was 11925 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11926 // with some sort of list. OTOH, it seems that GCC is always 11927 // conservative with the last element in structs (if it's an array), so our 11928 // current behavior is more compatible than an explicit list approach would 11929 // be. 11930 auto isFlexibleArrayMember = [&] { 11931 using FAMKind = LangOptions::StrictFlexArraysLevelKind; 11932 FAMKind StrictFlexArraysLevel = 11933 Ctx.getLangOpts().getStrictFlexArraysLevel(); 11934 11935 if (Designator.isMostDerivedAnUnsizedArray()) 11936 return true; 11937 11938 if (StrictFlexArraysLevel == FAMKind::Default) 11939 return true; 11940 11941 if (Designator.getMostDerivedArraySize() == 0 && 11942 StrictFlexArraysLevel != FAMKind::IncompleteOnly) 11943 return true; 11944 11945 if (Designator.getMostDerivedArraySize() == 1 && 11946 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete) 11947 return true; 11948 11949 return false; 11950 }; 11951 11952 return LVal.InvalidBase && 11953 Designator.Entries.size() == Designator.MostDerivedPathLength && 11954 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() && 11955 isDesignatorAtObjectEnd(Ctx, LVal); 11956 } 11957 11958 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11959 /// Fails if the conversion would cause loss of precision. 11960 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11961 CharUnits &Result) { 11962 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11963 if (Int.ugt(CharUnitsMax)) 11964 return false; 11965 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11966 return true; 11967 } 11968 11969 /// If we're evaluating the object size of an instance of a struct that 11970 /// contains a flexible array member, add the size of the initializer. 11971 static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, 11972 const LValue &LV, CharUnits &Size) { 11973 if (!T.isNull() && T->isStructureType() && 11974 T->getAsStructureType()->getDecl()->hasFlexibleArrayMember()) 11975 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>()) 11976 if (const auto *VD = dyn_cast<VarDecl>(V)) 11977 if (VD->hasInit()) 11978 Size += VD->getFlexibleArrayInitChars(Info.Ctx); 11979 } 11980 11981 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11982 /// determine how many bytes exist from the beginning of the object to either 11983 /// the end of the current subobject, or the end of the object itself, depending 11984 /// on what the LValue looks like + the value of Type. 11985 /// 11986 /// If this returns false, the value of Result is undefined. 11987 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11988 unsigned Type, const LValue &LVal, 11989 CharUnits &EndOffset) { 11990 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11991 11992 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11993 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11994 return false; 11995 return HandleSizeof(Info, ExprLoc, Ty, Result); 11996 }; 11997 11998 // We want to evaluate the size of the entire object. This is a valid fallback 11999 // for when Type=1 and the designator is invalid, because we're asked for an 12000 // upper-bound. 12001 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 12002 // Type=3 wants a lower bound, so we can't fall back to this. 12003 if (Type == 3 && !DetermineForCompleteObject) 12004 return false; 12005 12006 llvm::APInt APEndOffset; 12007 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 12008 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 12009 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 12010 12011 if (LVal.InvalidBase) 12012 return false; 12013 12014 QualType BaseTy = getObjectType(LVal.getLValueBase()); 12015 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset); 12016 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset); 12017 return Ret; 12018 } 12019 12020 // We want to evaluate the size of a subobject. 12021 const SubobjectDesignator &Designator = LVal.Designator; 12022 12023 // The following is a moderately common idiom in C: 12024 // 12025 // struct Foo { int a; char c[1]; }; 12026 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 12027 // strcpy(&F->c[0], Bar); 12028 // 12029 // In order to not break too much legacy code, we need to support it. 12030 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 12031 // If we can resolve this to an alloc_size call, we can hand that back, 12032 // because we know for certain how many bytes there are to write to. 12033 llvm::APInt APEndOffset; 12034 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 12035 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 12036 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 12037 12038 // If we cannot determine the size of the initial allocation, then we can't 12039 // given an accurate upper-bound. However, we are still able to give 12040 // conservative lower-bounds for Type=3. 12041 if (Type == 1) 12042 return false; 12043 } 12044 12045 CharUnits BytesPerElem; 12046 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 12047 return false; 12048 12049 // According to the GCC documentation, we want the size of the subobject 12050 // denoted by the pointer. But that's not quite right -- what we actually 12051 // want is the size of the immediately-enclosing array, if there is one. 12052 int64_t ElemsRemaining; 12053 if (Designator.MostDerivedIsArrayElement && 12054 Designator.Entries.size() == Designator.MostDerivedPathLength) { 12055 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 12056 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 12057 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 12058 } else { 12059 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 12060 } 12061 12062 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 12063 return true; 12064 } 12065 12066 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 12067 /// returns true and stores the result in @p Size. 12068 /// 12069 /// If @p WasError is non-null, this will report whether the failure to evaluate 12070 /// is to be treated as an Error in IntExprEvaluator. 12071 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 12072 EvalInfo &Info, uint64_t &Size) { 12073 // Determine the denoted object. 12074 LValue LVal; 12075 { 12076 // The operand of __builtin_object_size is never evaluated for side-effects. 12077 // If there are any, but we can determine the pointed-to object anyway, then 12078 // ignore the side-effects. 12079 SpeculativeEvaluationRAII SpeculativeEval(Info); 12080 IgnoreSideEffectsRAII Fold(Info); 12081 12082 if (E->isGLValue()) { 12083 // It's possible for us to be given GLValues if we're called via 12084 // Expr::tryEvaluateObjectSize. 12085 APValue RVal; 12086 if (!EvaluateAsRValue(Info, E, RVal)) 12087 return false; 12088 LVal.setFrom(Info.Ctx, RVal); 12089 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 12090 /*InvalidBaseOK=*/true)) 12091 return false; 12092 } 12093 12094 // If we point to before the start of the object, there are no accessible 12095 // bytes. 12096 if (LVal.getLValueOffset().isNegative()) { 12097 Size = 0; 12098 return true; 12099 } 12100 12101 CharUnits EndOffset; 12102 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 12103 return false; 12104 12105 // If we've fallen outside of the end offset, just pretend there's nothing to 12106 // write to/read from. 12107 if (EndOffset <= LVal.getLValueOffset()) 12108 Size = 0; 12109 else 12110 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 12111 return true; 12112 } 12113 12114 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 12115 if (!IsConstantEvaluatedBuiltinCall(E)) 12116 return ExprEvaluatorBaseTy::VisitCallExpr(E); 12117 return VisitBuiltinCallExpr(E, E->getBuiltinCallee()); 12118 } 12119 12120 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 12121 APValue &Val, APSInt &Alignment) { 12122 QualType SrcTy = E->getArg(0)->getType(); 12123 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 12124 return false; 12125 // Even though we are evaluating integer expressions we could get a pointer 12126 // argument for the __builtin_is_aligned() case. 12127 if (SrcTy->isPointerType()) { 12128 LValue Ptr; 12129 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 12130 return false; 12131 Ptr.moveInto(Val); 12132 } else if (!SrcTy->isIntegralOrEnumerationType()) { 12133 Info.FFDiag(E->getArg(0)); 12134 return false; 12135 } else { 12136 APSInt SrcInt; 12137 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 12138 return false; 12139 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 12140 "Bit widths must be the same"); 12141 Val = APValue(SrcInt); 12142 } 12143 assert(Val.hasValue()); 12144 return true; 12145 } 12146 12147 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 12148 unsigned BuiltinOp) { 12149 switch (BuiltinOp) { 12150 default: 12151 return false; 12152 12153 case Builtin::BI__builtin_dynamic_object_size: 12154 case Builtin::BI__builtin_object_size: { 12155 // The type was checked when we built the expression. 12156 unsigned Type = 12157 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 12158 assert(Type <= 3 && "unexpected type"); 12159 12160 uint64_t Size; 12161 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 12162 return Success(Size, E); 12163 12164 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 12165 return Success((Type & 2) ? 0 : -1, E); 12166 12167 // Expression had no side effects, but we couldn't statically determine the 12168 // size of the referenced object. 12169 switch (Info.EvalMode) { 12170 case EvalInfo::EM_ConstantExpression: 12171 case EvalInfo::EM_ConstantFold: 12172 case EvalInfo::EM_IgnoreSideEffects: 12173 // Leave it to IR generation. 12174 return Error(E); 12175 case EvalInfo::EM_ConstantExpressionUnevaluated: 12176 // Reduce it to a constant now. 12177 return Success((Type & 2) ? 0 : -1, E); 12178 } 12179 12180 llvm_unreachable("unexpected EvalMode"); 12181 } 12182 12183 case Builtin::BI__builtin_os_log_format_buffer_size: { 12184 analyze_os_log::OSLogBufferLayout Layout; 12185 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 12186 return Success(Layout.size().getQuantity(), E); 12187 } 12188 12189 case Builtin::BI__builtin_is_aligned: { 12190 APValue Src; 12191 APSInt Alignment; 12192 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 12193 return false; 12194 if (Src.isLValue()) { 12195 // If we evaluated a pointer, check the minimum known alignment. 12196 LValue Ptr; 12197 Ptr.setFrom(Info.Ctx, Src); 12198 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 12199 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 12200 // We can return true if the known alignment at the computed offset is 12201 // greater than the requested alignment. 12202 assert(PtrAlign.isPowerOfTwo()); 12203 assert(Alignment.isPowerOf2()); 12204 if (PtrAlign.getQuantity() >= Alignment) 12205 return Success(1, E); 12206 // If the alignment is not known to be sufficient, some cases could still 12207 // be aligned at run time. However, if the requested alignment is less or 12208 // equal to the base alignment and the offset is not aligned, we know that 12209 // the run-time value can never be aligned. 12210 if (BaseAlignment.getQuantity() >= Alignment && 12211 PtrAlign.getQuantity() < Alignment) 12212 return Success(0, E); 12213 // Otherwise we can't infer whether the value is sufficiently aligned. 12214 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 12215 // in cases where we can't fully evaluate the pointer. 12216 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 12217 << Alignment; 12218 return false; 12219 } 12220 assert(Src.isInt()); 12221 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 12222 } 12223 case Builtin::BI__builtin_align_up: { 12224 APValue Src; 12225 APSInt Alignment; 12226 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 12227 return false; 12228 if (!Src.isInt()) 12229 return Error(E); 12230 APSInt AlignedVal = 12231 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 12232 Src.getInt().isUnsigned()); 12233 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 12234 return Success(AlignedVal, E); 12235 } 12236 case Builtin::BI__builtin_align_down: { 12237 APValue Src; 12238 APSInt Alignment; 12239 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 12240 return false; 12241 if (!Src.isInt()) 12242 return Error(E); 12243 APSInt AlignedVal = 12244 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 12245 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 12246 return Success(AlignedVal, E); 12247 } 12248 12249 case Builtin::BI__builtin_bitreverse8: 12250 case Builtin::BI__builtin_bitreverse16: 12251 case Builtin::BI__builtin_bitreverse32: 12252 case Builtin::BI__builtin_bitreverse64: { 12253 APSInt Val; 12254 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12255 return false; 12256 12257 return Success(Val.reverseBits(), E); 12258 } 12259 12260 case Builtin::BI__builtin_bswap16: 12261 case Builtin::BI__builtin_bswap32: 12262 case Builtin::BI__builtin_bswap64: { 12263 APSInt Val; 12264 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12265 return false; 12266 12267 return Success(Val.byteSwap(), E); 12268 } 12269 12270 case Builtin::BI__builtin_classify_type: 12271 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 12272 12273 case Builtin::BI__builtin_clrsb: 12274 case Builtin::BI__builtin_clrsbl: 12275 case Builtin::BI__builtin_clrsbll: { 12276 APSInt Val; 12277 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12278 return false; 12279 12280 return Success(Val.getBitWidth() - Val.getSignificantBits(), E); 12281 } 12282 12283 case Builtin::BI__builtin_clz: 12284 case Builtin::BI__builtin_clzl: 12285 case Builtin::BI__builtin_clzll: 12286 case Builtin::BI__builtin_clzs: 12287 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes 12288 case Builtin::BI__lzcnt: 12289 case Builtin::BI__lzcnt64: { 12290 APSInt Val; 12291 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12292 return false; 12293 12294 // When the argument is 0, the result of GCC builtins is undefined, whereas 12295 // for Microsoft intrinsics, the result is the bit-width of the argument. 12296 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 && 12297 BuiltinOp != Builtin::BI__lzcnt && 12298 BuiltinOp != Builtin::BI__lzcnt64; 12299 12300 if (ZeroIsUndefined && !Val) 12301 return Error(E); 12302 12303 return Success(Val.countl_zero(), E); 12304 } 12305 12306 case Builtin::BI__builtin_constant_p: { 12307 const Expr *Arg = E->getArg(0); 12308 if (EvaluateBuiltinConstantP(Info, Arg)) 12309 return Success(true, E); 12310 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 12311 // Outside a constant context, eagerly evaluate to false in the presence 12312 // of side-effects in order to avoid -Wunsequenced false-positives in 12313 // a branch on __builtin_constant_p(expr). 12314 return Success(false, E); 12315 } 12316 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12317 return false; 12318 } 12319 12320 case Builtin::BI__builtin_is_constant_evaluated: { 12321 const auto *Callee = Info.CurrentCall->getCallee(); 12322 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 12323 (Info.CallStackDepth == 1 || 12324 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 12325 Callee->getIdentifier() && 12326 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 12327 // FIXME: Find a better way to avoid duplicated diagnostics. 12328 if (Info.EvalStatus.Diag) 12329 Info.report((Info.CallStackDepth == 1) 12330 ? E->getExprLoc() 12331 : Info.CurrentCall->getCallRange().getBegin(), 12332 diag::warn_is_constant_evaluated_always_true_constexpr) 12333 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 12334 : "std::is_constant_evaluated"); 12335 } 12336 12337 return Success(Info.InConstantContext, E); 12338 } 12339 12340 case Builtin::BI__builtin_ctz: 12341 case Builtin::BI__builtin_ctzl: 12342 case Builtin::BI__builtin_ctzll: 12343 case Builtin::BI__builtin_ctzs: { 12344 APSInt Val; 12345 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12346 return false; 12347 if (!Val) 12348 return Error(E); 12349 12350 return Success(Val.countr_zero(), E); 12351 } 12352 12353 case Builtin::BI__builtin_eh_return_data_regno: { 12354 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 12355 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 12356 return Success(Operand, E); 12357 } 12358 12359 case Builtin::BI__builtin_expect: 12360 case Builtin::BI__builtin_expect_with_probability: 12361 return Visit(E->getArg(0)); 12362 12363 case Builtin::BI__builtin_ffs: 12364 case Builtin::BI__builtin_ffsl: 12365 case Builtin::BI__builtin_ffsll: { 12366 APSInt Val; 12367 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12368 return false; 12369 12370 unsigned N = Val.countr_zero(); 12371 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 12372 } 12373 12374 case Builtin::BI__builtin_fpclassify: { 12375 APFloat Val(0.0); 12376 if (!EvaluateFloat(E->getArg(5), Val, Info)) 12377 return false; 12378 unsigned Arg; 12379 switch (Val.getCategory()) { 12380 case APFloat::fcNaN: Arg = 0; break; 12381 case APFloat::fcInfinity: Arg = 1; break; 12382 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 12383 case APFloat::fcZero: Arg = 4; break; 12384 } 12385 return Visit(E->getArg(Arg)); 12386 } 12387 12388 case Builtin::BI__builtin_isinf_sign: { 12389 APFloat Val(0.0); 12390 return EvaluateFloat(E->getArg(0), Val, Info) && 12391 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 12392 } 12393 12394 case Builtin::BI__builtin_isinf: { 12395 APFloat Val(0.0); 12396 return EvaluateFloat(E->getArg(0), Val, Info) && 12397 Success(Val.isInfinity() ? 1 : 0, E); 12398 } 12399 12400 case Builtin::BI__builtin_isfinite: { 12401 APFloat Val(0.0); 12402 return EvaluateFloat(E->getArg(0), Val, Info) && 12403 Success(Val.isFinite() ? 1 : 0, E); 12404 } 12405 12406 case Builtin::BI__builtin_isnan: { 12407 APFloat Val(0.0); 12408 return EvaluateFloat(E->getArg(0), Val, Info) && 12409 Success(Val.isNaN() ? 1 : 0, E); 12410 } 12411 12412 case Builtin::BI__builtin_isnormal: { 12413 APFloat Val(0.0); 12414 return EvaluateFloat(E->getArg(0), Val, Info) && 12415 Success(Val.isNormal() ? 1 : 0, E); 12416 } 12417 12418 case Builtin::BI__builtin_issubnormal: { 12419 APFloat Val(0.0); 12420 return EvaluateFloat(E->getArg(0), Val, Info) && 12421 Success(Val.isDenormal() ? 1 : 0, E); 12422 } 12423 12424 case Builtin::BI__builtin_iszero: { 12425 APFloat Val(0.0); 12426 return EvaluateFloat(E->getArg(0), Val, Info) && 12427 Success(Val.isZero() ? 1 : 0, E); 12428 } 12429 12430 case Builtin::BI__builtin_issignaling: { 12431 APFloat Val(0.0); 12432 return EvaluateFloat(E->getArg(0), Val, Info) && 12433 Success(Val.isSignaling() ? 1 : 0, E); 12434 } 12435 12436 case Builtin::BI__builtin_isfpclass: { 12437 APSInt MaskVal; 12438 if (!EvaluateInteger(E->getArg(1), MaskVal, Info)) 12439 return false; 12440 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue()); 12441 APFloat Val(0.0); 12442 return EvaluateFloat(E->getArg(0), Val, Info) && 12443 Success((Val.classify() & Test) ? 1 : 0, E); 12444 } 12445 12446 case Builtin::BI__builtin_parity: 12447 case Builtin::BI__builtin_parityl: 12448 case Builtin::BI__builtin_parityll: { 12449 APSInt Val; 12450 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12451 return false; 12452 12453 return Success(Val.popcount() % 2, E); 12454 } 12455 12456 case Builtin::BI__builtin_popcount: 12457 case Builtin::BI__builtin_popcountl: 12458 case Builtin::BI__builtin_popcountll: 12459 case Builtin::BI__popcnt16: // Microsoft variants of popcount 12460 case Builtin::BI__popcnt: 12461 case Builtin::BI__popcnt64: { 12462 APSInt Val; 12463 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12464 return false; 12465 12466 return Success(Val.popcount(), E); 12467 } 12468 12469 case Builtin::BI__builtin_rotateleft8: 12470 case Builtin::BI__builtin_rotateleft16: 12471 case Builtin::BI__builtin_rotateleft32: 12472 case Builtin::BI__builtin_rotateleft64: 12473 case Builtin::BI_rotl8: // Microsoft variants of rotate right 12474 case Builtin::BI_rotl16: 12475 case Builtin::BI_rotl: 12476 case Builtin::BI_lrotl: 12477 case Builtin::BI_rotl64: { 12478 APSInt Val, Amt; 12479 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12480 !EvaluateInteger(E->getArg(1), Amt, Info)) 12481 return false; 12482 12483 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 12484 } 12485 12486 case Builtin::BI__builtin_rotateright8: 12487 case Builtin::BI__builtin_rotateright16: 12488 case Builtin::BI__builtin_rotateright32: 12489 case Builtin::BI__builtin_rotateright64: 12490 case Builtin::BI_rotr8: // Microsoft variants of rotate right 12491 case Builtin::BI_rotr16: 12492 case Builtin::BI_rotr: 12493 case Builtin::BI_lrotr: 12494 case Builtin::BI_rotr64: { 12495 APSInt Val, Amt; 12496 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12497 !EvaluateInteger(E->getArg(1), Amt, Info)) 12498 return false; 12499 12500 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 12501 } 12502 12503 case Builtin::BIstrlen: 12504 case Builtin::BIwcslen: 12505 // A call to strlen is not a constant expression. 12506 if (Info.getLangOpts().CPlusPlus11) 12507 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12508 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 12509 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 12510 else 12511 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12512 [[fallthrough]]; 12513 case Builtin::BI__builtin_strlen: 12514 case Builtin::BI__builtin_wcslen: { 12515 // As an extension, we support __builtin_strlen() as a constant expression, 12516 // and support folding strlen() to a constant. 12517 uint64_t StrLen; 12518 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 12519 return Success(StrLen, E); 12520 return false; 12521 } 12522 12523 case Builtin::BIstrcmp: 12524 case Builtin::BIwcscmp: 12525 case Builtin::BIstrncmp: 12526 case Builtin::BIwcsncmp: 12527 case Builtin::BImemcmp: 12528 case Builtin::BIbcmp: 12529 case Builtin::BIwmemcmp: 12530 // A call to strlen is not a constant expression. 12531 if (Info.getLangOpts().CPlusPlus11) 12532 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12533 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 12534 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 12535 else 12536 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12537 [[fallthrough]]; 12538 case Builtin::BI__builtin_strcmp: 12539 case Builtin::BI__builtin_wcscmp: 12540 case Builtin::BI__builtin_strncmp: 12541 case Builtin::BI__builtin_wcsncmp: 12542 case Builtin::BI__builtin_memcmp: 12543 case Builtin::BI__builtin_bcmp: 12544 case Builtin::BI__builtin_wmemcmp: { 12545 LValue String1, String2; 12546 if (!EvaluatePointer(E->getArg(0), String1, Info) || 12547 !EvaluatePointer(E->getArg(1), String2, Info)) 12548 return false; 12549 12550 uint64_t MaxLength = uint64_t(-1); 12551 if (BuiltinOp != Builtin::BIstrcmp && 12552 BuiltinOp != Builtin::BIwcscmp && 12553 BuiltinOp != Builtin::BI__builtin_strcmp && 12554 BuiltinOp != Builtin::BI__builtin_wcscmp) { 12555 APSInt N; 12556 if (!EvaluateInteger(E->getArg(2), N, Info)) 12557 return false; 12558 MaxLength = N.getZExtValue(); 12559 } 12560 12561 // Empty substrings compare equal by definition. 12562 if (MaxLength == 0u) 12563 return Success(0, E); 12564 12565 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12566 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12567 String1.Designator.Invalid || String2.Designator.Invalid) 12568 return false; 12569 12570 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 12571 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 12572 12573 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 12574 BuiltinOp == Builtin::BIbcmp || 12575 BuiltinOp == Builtin::BI__builtin_memcmp || 12576 BuiltinOp == Builtin::BI__builtin_bcmp; 12577 12578 assert(IsRawByte || 12579 (Info.Ctx.hasSameUnqualifiedType( 12580 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 12581 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 12582 12583 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 12584 // 'char8_t', but no other types. 12585 if (IsRawByte && 12586 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 12587 // FIXME: Consider using our bit_cast implementation to support this. 12588 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 12589 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str() 12590 << CharTy1 << CharTy2; 12591 return false; 12592 } 12593 12594 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 12595 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 12596 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 12597 Char1.isInt() && Char2.isInt(); 12598 }; 12599 const auto &AdvanceElems = [&] { 12600 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 12601 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 12602 }; 12603 12604 bool StopAtNull = 12605 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 12606 BuiltinOp != Builtin::BIwmemcmp && 12607 BuiltinOp != Builtin::BI__builtin_memcmp && 12608 BuiltinOp != Builtin::BI__builtin_bcmp && 12609 BuiltinOp != Builtin::BI__builtin_wmemcmp); 12610 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 12611 BuiltinOp == Builtin::BIwcsncmp || 12612 BuiltinOp == Builtin::BIwmemcmp || 12613 BuiltinOp == Builtin::BI__builtin_wcscmp || 12614 BuiltinOp == Builtin::BI__builtin_wcsncmp || 12615 BuiltinOp == Builtin::BI__builtin_wmemcmp; 12616 12617 for (; MaxLength; --MaxLength) { 12618 APValue Char1, Char2; 12619 if (!ReadCurElems(Char1, Char2)) 12620 return false; 12621 if (Char1.getInt().ne(Char2.getInt())) { 12622 if (IsWide) // wmemcmp compares with wchar_t signedness. 12623 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 12624 // memcmp always compares unsigned chars. 12625 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 12626 } 12627 if (StopAtNull && !Char1.getInt()) 12628 return Success(0, E); 12629 assert(!(StopAtNull && !Char2.getInt())); 12630 if (!AdvanceElems()) 12631 return false; 12632 } 12633 // We hit the strncmp / memcmp limit. 12634 return Success(0, E); 12635 } 12636 12637 case Builtin::BI__atomic_always_lock_free: 12638 case Builtin::BI__atomic_is_lock_free: 12639 case Builtin::BI__c11_atomic_is_lock_free: { 12640 APSInt SizeVal; 12641 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 12642 return false; 12643 12644 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12645 // of two less than or equal to the maximum inline atomic width, we know it 12646 // is lock-free. If the size isn't a power of two, or greater than the 12647 // maximum alignment where we promote atomics, we know it is not lock-free 12648 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12649 // the answer can only be determined at runtime; for example, 16-byte 12650 // atomics have lock-free implementations on some, but not all, 12651 // x86-64 processors. 12652 12653 // Check power-of-two. 12654 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12655 if (Size.isPowerOfTwo()) { 12656 // Check against inlining width. 12657 unsigned InlineWidthBits = 12658 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12659 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12660 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12661 Size == CharUnits::One() || 12662 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12663 Expr::NPC_NeverValueDependent)) 12664 // OK, we will inline appropriately-aligned operations of this size, 12665 // and _Atomic(T) is appropriately-aligned. 12666 return Success(1, E); 12667 12668 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12669 castAs<PointerType>()->getPointeeType(); 12670 if (!PointeeType->isIncompleteType() && 12671 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12672 // OK, we will inline operations on this object. 12673 return Success(1, E); 12674 } 12675 } 12676 } 12677 12678 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12679 Success(0, E) : Error(E); 12680 } 12681 case Builtin::BI__builtin_add_overflow: 12682 case Builtin::BI__builtin_sub_overflow: 12683 case Builtin::BI__builtin_mul_overflow: 12684 case Builtin::BI__builtin_sadd_overflow: 12685 case Builtin::BI__builtin_uadd_overflow: 12686 case Builtin::BI__builtin_uaddl_overflow: 12687 case Builtin::BI__builtin_uaddll_overflow: 12688 case Builtin::BI__builtin_usub_overflow: 12689 case Builtin::BI__builtin_usubl_overflow: 12690 case Builtin::BI__builtin_usubll_overflow: 12691 case Builtin::BI__builtin_umul_overflow: 12692 case Builtin::BI__builtin_umull_overflow: 12693 case Builtin::BI__builtin_umulll_overflow: 12694 case Builtin::BI__builtin_saddl_overflow: 12695 case Builtin::BI__builtin_saddll_overflow: 12696 case Builtin::BI__builtin_ssub_overflow: 12697 case Builtin::BI__builtin_ssubl_overflow: 12698 case Builtin::BI__builtin_ssubll_overflow: 12699 case Builtin::BI__builtin_smul_overflow: 12700 case Builtin::BI__builtin_smull_overflow: 12701 case Builtin::BI__builtin_smulll_overflow: { 12702 LValue ResultLValue; 12703 APSInt LHS, RHS; 12704 12705 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12706 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12707 !EvaluateInteger(E->getArg(1), RHS, Info) || 12708 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12709 return false; 12710 12711 APSInt Result; 12712 bool DidOverflow = false; 12713 12714 // If the types don't have to match, enlarge all 3 to the largest of them. 12715 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12716 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12717 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12718 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12719 ResultType->isSignedIntegerOrEnumerationType(); 12720 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12721 ResultType->isSignedIntegerOrEnumerationType(); 12722 uint64_t LHSSize = LHS.getBitWidth(); 12723 uint64_t RHSSize = RHS.getBitWidth(); 12724 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12725 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12726 12727 // Add an additional bit if the signedness isn't uniformly agreed to. We 12728 // could do this ONLY if there is a signed and an unsigned that both have 12729 // MaxBits, but the code to check that is pretty nasty. The issue will be 12730 // caught in the shrink-to-result later anyway. 12731 if (IsSigned && !AllSigned) 12732 ++MaxBits; 12733 12734 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12735 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12736 Result = APSInt(MaxBits, !IsSigned); 12737 } 12738 12739 // Find largest int. 12740 switch (BuiltinOp) { 12741 default: 12742 llvm_unreachable("Invalid value for BuiltinOp"); 12743 case Builtin::BI__builtin_add_overflow: 12744 case Builtin::BI__builtin_sadd_overflow: 12745 case Builtin::BI__builtin_saddl_overflow: 12746 case Builtin::BI__builtin_saddll_overflow: 12747 case Builtin::BI__builtin_uadd_overflow: 12748 case Builtin::BI__builtin_uaddl_overflow: 12749 case Builtin::BI__builtin_uaddll_overflow: 12750 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12751 : LHS.uadd_ov(RHS, DidOverflow); 12752 break; 12753 case Builtin::BI__builtin_sub_overflow: 12754 case Builtin::BI__builtin_ssub_overflow: 12755 case Builtin::BI__builtin_ssubl_overflow: 12756 case Builtin::BI__builtin_ssubll_overflow: 12757 case Builtin::BI__builtin_usub_overflow: 12758 case Builtin::BI__builtin_usubl_overflow: 12759 case Builtin::BI__builtin_usubll_overflow: 12760 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12761 : LHS.usub_ov(RHS, DidOverflow); 12762 break; 12763 case Builtin::BI__builtin_mul_overflow: 12764 case Builtin::BI__builtin_smul_overflow: 12765 case Builtin::BI__builtin_smull_overflow: 12766 case Builtin::BI__builtin_smulll_overflow: 12767 case Builtin::BI__builtin_umul_overflow: 12768 case Builtin::BI__builtin_umull_overflow: 12769 case Builtin::BI__builtin_umulll_overflow: 12770 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12771 : LHS.umul_ov(RHS, DidOverflow); 12772 break; 12773 } 12774 12775 // In the case where multiple sizes are allowed, truncate and see if 12776 // the values are the same. 12777 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12778 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12779 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12780 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12781 // since it will give us the behavior of a TruncOrSelf in the case where 12782 // its parameter <= its size. We previously set Result to be at least the 12783 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12784 // will work exactly like TruncOrSelf. 12785 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12786 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12787 12788 if (!APSInt::isSameValue(Temp, Result)) 12789 DidOverflow = true; 12790 Result = Temp; 12791 } 12792 12793 APValue APV{Result}; 12794 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12795 return false; 12796 return Success(DidOverflow, E); 12797 } 12798 } 12799 } 12800 12801 /// Determine whether this is a pointer past the end of the complete 12802 /// object referred to by the lvalue. 12803 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12804 const LValue &LV) { 12805 // A null pointer can be viewed as being "past the end" but we don't 12806 // choose to look at it that way here. 12807 if (!LV.getLValueBase()) 12808 return false; 12809 12810 // If the designator is valid and refers to a subobject, we're not pointing 12811 // past the end. 12812 if (!LV.getLValueDesignator().Invalid && 12813 !LV.getLValueDesignator().isOnePastTheEnd()) 12814 return false; 12815 12816 // A pointer to an incomplete type might be past-the-end if the type's size is 12817 // zero. We cannot tell because the type is incomplete. 12818 QualType Ty = getType(LV.getLValueBase()); 12819 if (Ty->isIncompleteType()) 12820 return true; 12821 12822 // We're a past-the-end pointer if we point to the byte after the object, 12823 // no matter what our type or path is. 12824 auto Size = Ctx.getTypeSizeInChars(Ty); 12825 return LV.getLValueOffset() == Size; 12826 } 12827 12828 namespace { 12829 12830 /// Data recursive integer evaluator of certain binary operators. 12831 /// 12832 /// We use a data recursive algorithm for binary operators so that we are able 12833 /// to handle extreme cases of chained binary operators without causing stack 12834 /// overflow. 12835 class DataRecursiveIntBinOpEvaluator { 12836 struct EvalResult { 12837 APValue Val; 12838 bool Failed = false; 12839 12840 EvalResult() = default; 12841 12842 void swap(EvalResult &RHS) { 12843 Val.swap(RHS.Val); 12844 Failed = RHS.Failed; 12845 RHS.Failed = false; 12846 } 12847 }; 12848 12849 struct Job { 12850 const Expr *E; 12851 EvalResult LHSResult; // meaningful only for binary operator expression. 12852 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12853 12854 Job() = default; 12855 Job(Job &&) = default; 12856 12857 void startSpeculativeEval(EvalInfo &Info) { 12858 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12859 } 12860 12861 private: 12862 SpeculativeEvaluationRAII SpecEvalRAII; 12863 }; 12864 12865 SmallVector<Job, 16> Queue; 12866 12867 IntExprEvaluator &IntEval; 12868 EvalInfo &Info; 12869 APValue &FinalResult; 12870 12871 public: 12872 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12873 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12874 12875 /// True if \param E is a binary operator that we are going to handle 12876 /// data recursively. 12877 /// We handle binary operators that are comma, logical, or that have operands 12878 /// with integral or enumeration type. 12879 static bool shouldEnqueue(const BinaryOperator *E) { 12880 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12881 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12882 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12883 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12884 } 12885 12886 bool Traverse(const BinaryOperator *E) { 12887 enqueue(E); 12888 EvalResult PrevResult; 12889 while (!Queue.empty()) 12890 process(PrevResult); 12891 12892 if (PrevResult.Failed) return false; 12893 12894 FinalResult.swap(PrevResult.Val); 12895 return true; 12896 } 12897 12898 private: 12899 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12900 return IntEval.Success(Value, E, Result); 12901 } 12902 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12903 return IntEval.Success(Value, E, Result); 12904 } 12905 bool Error(const Expr *E) { 12906 return IntEval.Error(E); 12907 } 12908 bool Error(const Expr *E, diag::kind D) { 12909 return IntEval.Error(E, D); 12910 } 12911 12912 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12913 return Info.CCEDiag(E, D); 12914 } 12915 12916 // Returns true if visiting the RHS is necessary, false otherwise. 12917 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12918 bool &SuppressRHSDiags); 12919 12920 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12921 const BinaryOperator *E, APValue &Result); 12922 12923 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12924 Result.Failed = !Evaluate(Result.Val, Info, E); 12925 if (Result.Failed) 12926 Result.Val = APValue(); 12927 } 12928 12929 void process(EvalResult &Result); 12930 12931 void enqueue(const Expr *E) { 12932 E = E->IgnoreParens(); 12933 Queue.resize(Queue.size()+1); 12934 Queue.back().E = E; 12935 Queue.back().Kind = Job::AnyExprKind; 12936 } 12937 }; 12938 12939 } 12940 12941 bool DataRecursiveIntBinOpEvaluator:: 12942 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12943 bool &SuppressRHSDiags) { 12944 if (E->getOpcode() == BO_Comma) { 12945 // Ignore LHS but note if we could not evaluate it. 12946 if (LHSResult.Failed) 12947 return Info.noteSideEffect(); 12948 return true; 12949 } 12950 12951 if (E->isLogicalOp()) { 12952 bool LHSAsBool; 12953 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12954 // We were able to evaluate the LHS, see if we can get away with not 12955 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12956 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12957 Success(LHSAsBool, E, LHSResult.Val); 12958 return false; // Ignore RHS 12959 } 12960 } else { 12961 LHSResult.Failed = true; 12962 12963 // Since we weren't able to evaluate the left hand side, it 12964 // might have had side effects. 12965 if (!Info.noteSideEffect()) 12966 return false; 12967 12968 // We can't evaluate the LHS; however, sometimes the result 12969 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12970 // Don't ignore RHS and suppress diagnostics from this arm. 12971 SuppressRHSDiags = true; 12972 } 12973 12974 return true; 12975 } 12976 12977 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12978 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12979 12980 if (LHSResult.Failed && !Info.noteFailure()) 12981 return false; // Ignore RHS; 12982 12983 return true; 12984 } 12985 12986 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12987 bool IsSub) { 12988 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12989 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12990 // offsets. 12991 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12992 CharUnits &Offset = LVal.getLValueOffset(); 12993 uint64_t Offset64 = Offset.getQuantity(); 12994 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12995 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12996 : Offset64 + Index64); 12997 } 12998 12999 bool DataRecursiveIntBinOpEvaluator:: 13000 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 13001 const BinaryOperator *E, APValue &Result) { 13002 if (E->getOpcode() == BO_Comma) { 13003 if (RHSResult.Failed) 13004 return false; 13005 Result = RHSResult.Val; 13006 return true; 13007 } 13008 13009 if (E->isLogicalOp()) { 13010 bool lhsResult, rhsResult; 13011 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 13012 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 13013 13014 if (LHSIsOK) { 13015 if (RHSIsOK) { 13016 if (E->getOpcode() == BO_LOr) 13017 return Success(lhsResult || rhsResult, E, Result); 13018 else 13019 return Success(lhsResult && rhsResult, E, Result); 13020 } 13021 } else { 13022 if (RHSIsOK) { 13023 // We can't evaluate the LHS; however, sometimes the result 13024 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 13025 if (rhsResult == (E->getOpcode() == BO_LOr)) 13026 return Success(rhsResult, E, Result); 13027 } 13028 } 13029 13030 return false; 13031 } 13032 13033 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 13034 E->getRHS()->getType()->isIntegralOrEnumerationType()); 13035 13036 if (LHSResult.Failed || RHSResult.Failed) 13037 return false; 13038 13039 const APValue &LHSVal = LHSResult.Val; 13040 const APValue &RHSVal = RHSResult.Val; 13041 13042 // Handle cases like (unsigned long)&a + 4. 13043 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 13044 Result = LHSVal; 13045 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 13046 return true; 13047 } 13048 13049 // Handle cases like 4 + (unsigned long)&a 13050 if (E->getOpcode() == BO_Add && 13051 RHSVal.isLValue() && LHSVal.isInt()) { 13052 Result = RHSVal; 13053 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 13054 return true; 13055 } 13056 13057 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 13058 // Handle (intptr_t)&&A - (intptr_t)&&B. 13059 if (!LHSVal.getLValueOffset().isZero() || 13060 !RHSVal.getLValueOffset().isZero()) 13061 return false; 13062 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 13063 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 13064 if (!LHSExpr || !RHSExpr) 13065 return false; 13066 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13067 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13068 if (!LHSAddrExpr || !RHSAddrExpr) 13069 return false; 13070 // Make sure both labels come from the same function. 13071 if (LHSAddrExpr->getLabel()->getDeclContext() != 13072 RHSAddrExpr->getLabel()->getDeclContext()) 13073 return false; 13074 Result = APValue(LHSAddrExpr, RHSAddrExpr); 13075 return true; 13076 } 13077 13078 // All the remaining cases expect both operands to be an integer 13079 if (!LHSVal.isInt() || !RHSVal.isInt()) 13080 return Error(E); 13081 13082 // Set up the width and signedness manually, in case it can't be deduced 13083 // from the operation we're performing. 13084 // FIXME: Don't do this in the cases where we can deduce it. 13085 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 13086 E->getType()->isUnsignedIntegerOrEnumerationType()); 13087 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 13088 RHSVal.getInt(), Value)) 13089 return false; 13090 return Success(Value, E, Result); 13091 } 13092 13093 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 13094 Job &job = Queue.back(); 13095 13096 switch (job.Kind) { 13097 case Job::AnyExprKind: { 13098 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 13099 if (shouldEnqueue(Bop)) { 13100 job.Kind = Job::BinOpKind; 13101 enqueue(Bop->getLHS()); 13102 return; 13103 } 13104 } 13105 13106 EvaluateExpr(job.E, Result); 13107 Queue.pop_back(); 13108 return; 13109 } 13110 13111 case Job::BinOpKind: { 13112 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 13113 bool SuppressRHSDiags = false; 13114 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 13115 Queue.pop_back(); 13116 return; 13117 } 13118 if (SuppressRHSDiags) 13119 job.startSpeculativeEval(Info); 13120 job.LHSResult.swap(Result); 13121 job.Kind = Job::BinOpVisitedLHSKind; 13122 enqueue(Bop->getRHS()); 13123 return; 13124 } 13125 13126 case Job::BinOpVisitedLHSKind: { 13127 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 13128 EvalResult RHS; 13129 RHS.swap(Result); 13130 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 13131 Queue.pop_back(); 13132 return; 13133 } 13134 } 13135 13136 llvm_unreachable("Invalid Job::Kind!"); 13137 } 13138 13139 namespace { 13140 enum class CmpResult { 13141 Unequal, 13142 Less, 13143 Equal, 13144 Greater, 13145 Unordered, 13146 }; 13147 } 13148 13149 template <class SuccessCB, class AfterCB> 13150 static bool 13151 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 13152 SuccessCB &&Success, AfterCB &&DoAfter) { 13153 assert(!E->isValueDependent()); 13154 assert(E->isComparisonOp() && "expected comparison operator"); 13155 assert((E->getOpcode() == BO_Cmp || 13156 E->getType()->isIntegralOrEnumerationType()) && 13157 "unsupported binary expression evaluation"); 13158 auto Error = [&](const Expr *E) { 13159 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 13160 return false; 13161 }; 13162 13163 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 13164 bool IsEquality = E->isEqualityOp(); 13165 13166 QualType LHSTy = E->getLHS()->getType(); 13167 QualType RHSTy = E->getRHS()->getType(); 13168 13169 if (LHSTy->isIntegralOrEnumerationType() && 13170 RHSTy->isIntegralOrEnumerationType()) { 13171 APSInt LHS, RHS; 13172 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 13173 if (!LHSOK && !Info.noteFailure()) 13174 return false; 13175 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 13176 return false; 13177 if (LHS < RHS) 13178 return Success(CmpResult::Less, E); 13179 if (LHS > RHS) 13180 return Success(CmpResult::Greater, E); 13181 return Success(CmpResult::Equal, E); 13182 } 13183 13184 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 13185 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 13186 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 13187 13188 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 13189 if (!LHSOK && !Info.noteFailure()) 13190 return false; 13191 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 13192 return false; 13193 if (LHSFX < RHSFX) 13194 return Success(CmpResult::Less, E); 13195 if (LHSFX > RHSFX) 13196 return Success(CmpResult::Greater, E); 13197 return Success(CmpResult::Equal, E); 13198 } 13199 13200 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 13201 ComplexValue LHS, RHS; 13202 bool LHSOK; 13203 if (E->isAssignmentOp()) { 13204 LValue LV; 13205 EvaluateLValue(E->getLHS(), LV, Info); 13206 LHSOK = false; 13207 } else if (LHSTy->isRealFloatingType()) { 13208 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 13209 if (LHSOK) { 13210 LHS.makeComplexFloat(); 13211 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 13212 } 13213 } else { 13214 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 13215 } 13216 if (!LHSOK && !Info.noteFailure()) 13217 return false; 13218 13219 if (E->getRHS()->getType()->isRealFloatingType()) { 13220 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 13221 return false; 13222 RHS.makeComplexFloat(); 13223 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 13224 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13225 return false; 13226 13227 if (LHS.isComplexFloat()) { 13228 APFloat::cmpResult CR_r = 13229 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 13230 APFloat::cmpResult CR_i = 13231 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 13232 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 13233 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 13234 } else { 13235 assert(IsEquality && "invalid complex comparison"); 13236 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 13237 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 13238 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 13239 } 13240 } 13241 13242 if (LHSTy->isRealFloatingType() && 13243 RHSTy->isRealFloatingType()) { 13244 APFloat RHS(0.0), LHS(0.0); 13245 13246 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 13247 if (!LHSOK && !Info.noteFailure()) 13248 return false; 13249 13250 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 13251 return false; 13252 13253 assert(E->isComparisonOp() && "Invalid binary operator!"); 13254 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 13255 if (!Info.InConstantContext && 13256 APFloatCmpResult == APFloat::cmpUnordered && 13257 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 13258 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 13259 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 13260 return false; 13261 } 13262 auto GetCmpRes = [&]() { 13263 switch (APFloatCmpResult) { 13264 case APFloat::cmpEqual: 13265 return CmpResult::Equal; 13266 case APFloat::cmpLessThan: 13267 return CmpResult::Less; 13268 case APFloat::cmpGreaterThan: 13269 return CmpResult::Greater; 13270 case APFloat::cmpUnordered: 13271 return CmpResult::Unordered; 13272 } 13273 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 13274 }; 13275 return Success(GetCmpRes(), E); 13276 } 13277 13278 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 13279 LValue LHSValue, RHSValue; 13280 13281 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13282 if (!LHSOK && !Info.noteFailure()) 13283 return false; 13284 13285 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13286 return false; 13287 13288 // Reject differing bases from the normal codepath; we special-case 13289 // comparisons to null. 13290 if (!HasSameBase(LHSValue, RHSValue)) { 13291 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) { 13292 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType()); 13293 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType()); 13294 Info.FFDiag(E, DiagID) 13295 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS); 13296 return false; 13297 }; 13298 // Inequalities and subtractions between unrelated pointers have 13299 // unspecified or undefined behavior. 13300 if (!IsEquality) 13301 return DiagComparison( 13302 diag::note_constexpr_pointer_comparison_unspecified); 13303 // A constant address may compare equal to the address of a symbol. 13304 // The one exception is that address of an object cannot compare equal 13305 // to a null pointer constant. 13306 // TODO: Should we restrict this to actual null pointers, and exclude the 13307 // case of zero cast to pointer type? 13308 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 13309 (!RHSValue.Base && !RHSValue.Offset.isZero())) 13310 return DiagComparison(diag::note_constexpr_pointer_constant_comparison, 13311 !RHSValue.Base); 13312 // It's implementation-defined whether distinct literals will have 13313 // distinct addresses. In clang, the result of such a comparison is 13314 // unspecified, so it is not a constant expression. However, we do know 13315 // that the address of a literal will be non-null. 13316 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 13317 LHSValue.Base && RHSValue.Base) 13318 return DiagComparison(diag::note_constexpr_literal_comparison); 13319 // We can't tell whether weak symbols will end up pointing to the same 13320 // object. 13321 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 13322 return DiagComparison(diag::note_constexpr_pointer_weak_comparison, 13323 !IsWeakLValue(LHSValue)); 13324 // We can't compare the address of the start of one object with the 13325 // past-the-end address of another object, per C++ DR1652. 13326 if (LHSValue.Base && LHSValue.Offset.isZero() && 13327 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) 13328 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end, 13329 true); 13330 if (RHSValue.Base && RHSValue.Offset.isZero() && 13331 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)) 13332 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end, 13333 false); 13334 // We can't tell whether an object is at the same address as another 13335 // zero sized object. 13336 if ((RHSValue.Base && isZeroSized(LHSValue)) || 13337 (LHSValue.Base && isZeroSized(RHSValue))) 13338 return DiagComparison( 13339 diag::note_constexpr_pointer_comparison_zero_sized); 13340 return Success(CmpResult::Unequal, E); 13341 } 13342 13343 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13344 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13345 13346 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13347 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13348 13349 // C++11 [expr.rel]p3: 13350 // Pointers to void (after pointer conversions) can be compared, with a 13351 // result defined as follows: If both pointers represent the same 13352 // address or are both the null pointer value, the result is true if the 13353 // operator is <= or >= and false otherwise; otherwise the result is 13354 // unspecified. 13355 // We interpret this as applying to pointers to *cv* void. 13356 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 13357 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 13358 13359 // C++11 [expr.rel]p2: 13360 // - If two pointers point to non-static data members of the same object, 13361 // or to subobjects or array elements fo such members, recursively, the 13362 // pointer to the later declared member compares greater provided the 13363 // two members have the same access control and provided their class is 13364 // not a union. 13365 // [...] 13366 // - Otherwise pointer comparisons are unspecified. 13367 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 13368 bool WasArrayIndex; 13369 unsigned Mismatch = FindDesignatorMismatch( 13370 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 13371 // At the point where the designators diverge, the comparison has a 13372 // specified value if: 13373 // - we are comparing array indices 13374 // - we are comparing fields of a union, or fields with the same access 13375 // Otherwise, the result is unspecified and thus the comparison is not a 13376 // constant expression. 13377 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 13378 Mismatch < RHSDesignator.Entries.size()) { 13379 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 13380 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 13381 if (!LF && !RF) 13382 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 13383 else if (!LF) 13384 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 13385 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 13386 << RF->getParent() << RF; 13387 else if (!RF) 13388 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 13389 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 13390 << LF->getParent() << LF; 13391 else if (!LF->getParent()->isUnion() && 13392 LF->getAccess() != RF->getAccess()) 13393 Info.CCEDiag(E, 13394 diag::note_constexpr_pointer_comparison_differing_access) 13395 << LF << LF->getAccess() << RF << RF->getAccess() 13396 << LF->getParent(); 13397 } 13398 } 13399 13400 // The comparison here must be unsigned, and performed with the same 13401 // width as the pointer. 13402 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 13403 uint64_t CompareLHS = LHSOffset.getQuantity(); 13404 uint64_t CompareRHS = RHSOffset.getQuantity(); 13405 assert(PtrSize <= 64 && "Unexpected pointer width"); 13406 uint64_t Mask = ~0ULL >> (64 - PtrSize); 13407 CompareLHS &= Mask; 13408 CompareRHS &= Mask; 13409 13410 // If there is a base and this is a relational operator, we can only 13411 // compare pointers within the object in question; otherwise, the result 13412 // depends on where the object is located in memory. 13413 if (!LHSValue.Base.isNull() && IsRelational) { 13414 QualType BaseTy = getType(LHSValue.Base); 13415 if (BaseTy->isIncompleteType()) 13416 return Error(E); 13417 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 13418 uint64_t OffsetLimit = Size.getQuantity(); 13419 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 13420 return Error(E); 13421 } 13422 13423 if (CompareLHS < CompareRHS) 13424 return Success(CmpResult::Less, E); 13425 if (CompareLHS > CompareRHS) 13426 return Success(CmpResult::Greater, E); 13427 return Success(CmpResult::Equal, E); 13428 } 13429 13430 if (LHSTy->isMemberPointerType()) { 13431 assert(IsEquality && "unexpected member pointer operation"); 13432 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 13433 13434 MemberPtr LHSValue, RHSValue; 13435 13436 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 13437 if (!LHSOK && !Info.noteFailure()) 13438 return false; 13439 13440 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13441 return false; 13442 13443 // If either operand is a pointer to a weak function, the comparison is not 13444 // constant. 13445 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) { 13446 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison) 13447 << LHSValue.getDecl(); 13448 return false; 13449 } 13450 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) { 13451 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison) 13452 << RHSValue.getDecl(); 13453 return false; 13454 } 13455 13456 // C++11 [expr.eq]p2: 13457 // If both operands are null, they compare equal. Otherwise if only one is 13458 // null, they compare unequal. 13459 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 13460 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 13461 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 13462 } 13463 13464 // Otherwise if either is a pointer to a virtual member function, the 13465 // result is unspecified. 13466 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 13467 if (MD->isVirtual()) 13468 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 13469 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 13470 if (MD->isVirtual()) 13471 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 13472 13473 // Otherwise they compare equal if and only if they would refer to the 13474 // same member of the same most derived object or the same subobject if 13475 // they were dereferenced with a hypothetical object of the associated 13476 // class type. 13477 bool Equal = LHSValue == RHSValue; 13478 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 13479 } 13480 13481 if (LHSTy->isNullPtrType()) { 13482 assert(E->isComparisonOp() && "unexpected nullptr operation"); 13483 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 13484 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 13485 // are compared, the result is true of the operator is <=, >= or ==, and 13486 // false otherwise. 13487 LValue Res; 13488 if (!EvaluatePointer(E->getLHS(), Res, Info) || 13489 !EvaluatePointer(E->getRHS(), Res, Info)) 13490 return false; 13491 return Success(CmpResult::Equal, E); 13492 } 13493 13494 return DoAfter(); 13495 } 13496 13497 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 13498 if (!CheckLiteralType(Info, E)) 13499 return false; 13500 13501 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13502 ComparisonCategoryResult CCR; 13503 switch (CR) { 13504 case CmpResult::Unequal: 13505 llvm_unreachable("should never produce Unequal for three-way comparison"); 13506 case CmpResult::Less: 13507 CCR = ComparisonCategoryResult::Less; 13508 break; 13509 case CmpResult::Equal: 13510 CCR = ComparisonCategoryResult::Equal; 13511 break; 13512 case CmpResult::Greater: 13513 CCR = ComparisonCategoryResult::Greater; 13514 break; 13515 case CmpResult::Unordered: 13516 CCR = ComparisonCategoryResult::Unordered; 13517 break; 13518 } 13519 // Evaluation succeeded. Lookup the information for the comparison category 13520 // type and fetch the VarDecl for the result. 13521 const ComparisonCategoryInfo &CmpInfo = 13522 Info.Ctx.CompCategories.getInfoForType(E->getType()); 13523 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 13524 // Check and evaluate the result as a constant expression. 13525 LValue LV; 13526 LV.set(VD); 13527 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 13528 return false; 13529 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 13530 ConstantExprKind::Normal); 13531 }; 13532 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13533 return ExprEvaluatorBaseTy::VisitBinCmp(E); 13534 }); 13535 } 13536 13537 bool RecordExprEvaluator::VisitCXXParenListInitExpr( 13538 const CXXParenListInitExpr *E) { 13539 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs()); 13540 } 13541 13542 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13543 // We don't support assignment in C. C++ assignments don't get here because 13544 // assignment is an lvalue in C++. 13545 if (E->isAssignmentOp()) { 13546 Error(E); 13547 if (!Info.noteFailure()) 13548 return false; 13549 } 13550 13551 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 13552 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 13553 13554 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 13555 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 13556 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 13557 13558 if (E->isComparisonOp()) { 13559 // Evaluate builtin binary comparisons by evaluating them as three-way 13560 // comparisons and then translating the result. 13561 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13562 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 13563 "should only produce Unequal for equality comparisons"); 13564 bool IsEqual = CR == CmpResult::Equal, 13565 IsLess = CR == CmpResult::Less, 13566 IsGreater = CR == CmpResult::Greater; 13567 auto Op = E->getOpcode(); 13568 switch (Op) { 13569 default: 13570 llvm_unreachable("unsupported binary operator"); 13571 case BO_EQ: 13572 case BO_NE: 13573 return Success(IsEqual == (Op == BO_EQ), E); 13574 case BO_LT: 13575 return Success(IsLess, E); 13576 case BO_GT: 13577 return Success(IsGreater, E); 13578 case BO_LE: 13579 return Success(IsEqual || IsLess, E); 13580 case BO_GE: 13581 return Success(IsEqual || IsGreater, E); 13582 } 13583 }; 13584 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13585 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13586 }); 13587 } 13588 13589 QualType LHSTy = E->getLHS()->getType(); 13590 QualType RHSTy = E->getRHS()->getType(); 13591 13592 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 13593 E->getOpcode() == BO_Sub) { 13594 LValue LHSValue, RHSValue; 13595 13596 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13597 if (!LHSOK && !Info.noteFailure()) 13598 return false; 13599 13600 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13601 return false; 13602 13603 // Reject differing bases from the normal codepath; we special-case 13604 // comparisons to null. 13605 if (!HasSameBase(LHSValue, RHSValue)) { 13606 // Handle &&A - &&B. 13607 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 13608 return Error(E); 13609 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 13610 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 13611 if (!LHSExpr || !RHSExpr) 13612 return Error(E); 13613 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13614 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13615 if (!LHSAddrExpr || !RHSAddrExpr) 13616 return Error(E); 13617 // Make sure both labels come from the same function. 13618 if (LHSAddrExpr->getLabel()->getDeclContext() != 13619 RHSAddrExpr->getLabel()->getDeclContext()) 13620 return Error(E); 13621 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 13622 } 13623 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13624 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13625 13626 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13627 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13628 13629 // C++11 [expr.add]p6: 13630 // Unless both pointers point to elements of the same array object, or 13631 // one past the last element of the array object, the behavior is 13632 // undefined. 13633 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 13634 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 13635 RHSDesignator)) 13636 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 13637 13638 QualType Type = E->getLHS()->getType(); 13639 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 13640 13641 CharUnits ElementSize; 13642 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 13643 return false; 13644 13645 // As an extension, a type may have zero size (empty struct or union in 13646 // C, array of zero length). Pointer subtraction in such cases has 13647 // undefined behavior, so is not constant. 13648 if (ElementSize.isZero()) { 13649 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 13650 << ElementType; 13651 return false; 13652 } 13653 13654 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 13655 // and produce incorrect results when it overflows. Such behavior 13656 // appears to be non-conforming, but is common, so perhaps we should 13657 // assume the standard intended for such cases to be undefined behavior 13658 // and check for them. 13659 13660 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 13661 // overflow in the final conversion to ptrdiff_t. 13662 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 13663 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 13664 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 13665 false); 13666 APSInt TrueResult = (LHS - RHS) / ElemSize; 13667 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 13668 13669 if (Result.extend(65) != TrueResult && 13670 !HandleOverflow(Info, E, TrueResult, E->getType())) 13671 return false; 13672 return Success(Result, E); 13673 } 13674 13675 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13676 } 13677 13678 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 13679 /// a result as the expression's type. 13680 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13681 const UnaryExprOrTypeTraitExpr *E) { 13682 switch(E->getKind()) { 13683 case UETT_PreferredAlignOf: 13684 case UETT_AlignOf: { 13685 if (E->isArgumentType()) 13686 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13687 E); 13688 else 13689 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13690 E); 13691 } 13692 13693 case UETT_VecStep: { 13694 QualType Ty = E->getTypeOfArgument(); 13695 13696 if (Ty->isVectorType()) { 13697 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13698 13699 // The vec_step built-in functions that take a 3-component 13700 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13701 if (n == 3) 13702 n = 4; 13703 13704 return Success(n, E); 13705 } else 13706 return Success(1, E); 13707 } 13708 13709 case UETT_DataSizeOf: 13710 case UETT_SizeOf: { 13711 QualType SrcTy = E->getTypeOfArgument(); 13712 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13713 // the result is the size of the referenced type." 13714 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13715 SrcTy = Ref->getPointeeType(); 13716 13717 CharUnits Sizeof; 13718 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof, 13719 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf 13720 : SizeOfType::SizeOf)) { 13721 return false; 13722 } 13723 return Success(Sizeof, E); 13724 } 13725 case UETT_OpenMPRequiredSimdAlign: 13726 assert(E->isArgumentType()); 13727 return Success( 13728 Info.Ctx.toCharUnitsFromBits( 13729 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13730 .getQuantity(), 13731 E); 13732 case UETT_VectorElements: { 13733 QualType Ty = E->getTypeOfArgument(); 13734 // If the vector has a fixed size, we can determine the number of elements 13735 // at compile time. 13736 if (Ty->isVectorType()) 13737 return Success(Ty->castAs<VectorType>()->getNumElements(), E); 13738 13739 assert(Ty->isSizelessVectorType()); 13740 if (Info.InConstantContext) 13741 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements) 13742 << E->getSourceRange(); 13743 13744 return false; 13745 } 13746 } 13747 13748 llvm_unreachable("unknown expr/type trait"); 13749 } 13750 13751 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13752 CharUnits Result; 13753 unsigned n = OOE->getNumComponents(); 13754 if (n == 0) 13755 return Error(OOE); 13756 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13757 for (unsigned i = 0; i != n; ++i) { 13758 OffsetOfNode ON = OOE->getComponent(i); 13759 switch (ON.getKind()) { 13760 case OffsetOfNode::Array: { 13761 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13762 APSInt IdxResult; 13763 if (!EvaluateInteger(Idx, IdxResult, Info)) 13764 return false; 13765 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13766 if (!AT) 13767 return Error(OOE); 13768 CurrentType = AT->getElementType(); 13769 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13770 Result += IdxResult.getSExtValue() * ElementSize; 13771 break; 13772 } 13773 13774 case OffsetOfNode::Field: { 13775 FieldDecl *MemberDecl = ON.getField(); 13776 const RecordType *RT = CurrentType->getAs<RecordType>(); 13777 if (!RT) 13778 return Error(OOE); 13779 RecordDecl *RD = RT->getDecl(); 13780 if (RD->isInvalidDecl()) return false; 13781 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13782 unsigned i = MemberDecl->getFieldIndex(); 13783 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13784 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13785 CurrentType = MemberDecl->getType().getNonReferenceType(); 13786 break; 13787 } 13788 13789 case OffsetOfNode::Identifier: 13790 llvm_unreachable("dependent __builtin_offsetof"); 13791 13792 case OffsetOfNode::Base: { 13793 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13794 if (BaseSpec->isVirtual()) 13795 return Error(OOE); 13796 13797 // Find the layout of the class whose base we are looking into. 13798 const RecordType *RT = CurrentType->getAs<RecordType>(); 13799 if (!RT) 13800 return Error(OOE); 13801 RecordDecl *RD = RT->getDecl(); 13802 if (RD->isInvalidDecl()) return false; 13803 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13804 13805 // Find the base class itself. 13806 CurrentType = BaseSpec->getType(); 13807 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13808 if (!BaseRT) 13809 return Error(OOE); 13810 13811 // Add the offset to the base. 13812 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13813 break; 13814 } 13815 } 13816 } 13817 return Success(Result, OOE); 13818 } 13819 13820 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13821 switch (E->getOpcode()) { 13822 default: 13823 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13824 // See C99 6.6p3. 13825 return Error(E); 13826 case UO_Extension: 13827 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13828 // If so, we could clear the diagnostic ID. 13829 return Visit(E->getSubExpr()); 13830 case UO_Plus: 13831 // The result is just the value. 13832 return Visit(E->getSubExpr()); 13833 case UO_Minus: { 13834 if (!Visit(E->getSubExpr())) 13835 return false; 13836 if (!Result.isInt()) return Error(E); 13837 const APSInt &Value = Result.getInt(); 13838 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) { 13839 if (Info.checkingForUndefinedBehavior()) 13840 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13841 diag::warn_integer_constant_overflow) 13842 << toString(Value, 10) << E->getType() << E->getSourceRange(); 13843 13844 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13845 E->getType())) 13846 return false; 13847 } 13848 return Success(-Value, E); 13849 } 13850 case UO_Not: { 13851 if (!Visit(E->getSubExpr())) 13852 return false; 13853 if (!Result.isInt()) return Error(E); 13854 return Success(~Result.getInt(), E); 13855 } 13856 case UO_LNot: { 13857 bool bres; 13858 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13859 return false; 13860 return Success(!bres, E); 13861 } 13862 } 13863 } 13864 13865 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13866 /// result type is integer. 13867 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13868 const Expr *SubExpr = E->getSubExpr(); 13869 QualType DestType = E->getType(); 13870 QualType SrcType = SubExpr->getType(); 13871 13872 switch (E->getCastKind()) { 13873 case CK_BaseToDerived: 13874 case CK_DerivedToBase: 13875 case CK_UncheckedDerivedToBase: 13876 case CK_Dynamic: 13877 case CK_ToUnion: 13878 case CK_ArrayToPointerDecay: 13879 case CK_FunctionToPointerDecay: 13880 case CK_NullToPointer: 13881 case CK_NullToMemberPointer: 13882 case CK_BaseToDerivedMemberPointer: 13883 case CK_DerivedToBaseMemberPointer: 13884 case CK_ReinterpretMemberPointer: 13885 case CK_ConstructorConversion: 13886 case CK_IntegralToPointer: 13887 case CK_ToVoid: 13888 case CK_VectorSplat: 13889 case CK_IntegralToFloating: 13890 case CK_FloatingCast: 13891 case CK_CPointerToObjCPointerCast: 13892 case CK_BlockPointerToObjCPointerCast: 13893 case CK_AnyPointerToBlockPointerCast: 13894 case CK_ObjCObjectLValueCast: 13895 case CK_FloatingRealToComplex: 13896 case CK_FloatingComplexToReal: 13897 case CK_FloatingComplexCast: 13898 case CK_FloatingComplexToIntegralComplex: 13899 case CK_IntegralRealToComplex: 13900 case CK_IntegralComplexCast: 13901 case CK_IntegralComplexToFloatingComplex: 13902 case CK_BuiltinFnToFnPtr: 13903 case CK_ZeroToOCLOpaqueType: 13904 case CK_NonAtomicToAtomic: 13905 case CK_AddressSpaceConversion: 13906 case CK_IntToOCLSampler: 13907 case CK_FloatingToFixedPoint: 13908 case CK_FixedPointToFloating: 13909 case CK_FixedPointCast: 13910 case CK_IntegralToFixedPoint: 13911 case CK_MatrixCast: 13912 llvm_unreachable("invalid cast kind for integral value"); 13913 13914 case CK_BitCast: 13915 case CK_Dependent: 13916 case CK_LValueBitCast: 13917 case CK_ARCProduceObject: 13918 case CK_ARCConsumeObject: 13919 case CK_ARCReclaimReturnedObject: 13920 case CK_ARCExtendBlockObject: 13921 case CK_CopyAndAutoreleaseBlockObject: 13922 return Error(E); 13923 13924 case CK_UserDefinedConversion: 13925 case CK_LValueToRValue: 13926 case CK_AtomicToNonAtomic: 13927 case CK_NoOp: 13928 case CK_LValueToRValueBitCast: 13929 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13930 13931 case CK_MemberPointerToBoolean: 13932 case CK_PointerToBoolean: 13933 case CK_IntegralToBoolean: 13934 case CK_FloatingToBoolean: 13935 case CK_BooleanToSignedIntegral: 13936 case CK_FloatingComplexToBoolean: 13937 case CK_IntegralComplexToBoolean: { 13938 bool BoolResult; 13939 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13940 return false; 13941 uint64_t IntResult = BoolResult; 13942 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13943 IntResult = (uint64_t)-1; 13944 return Success(IntResult, E); 13945 } 13946 13947 case CK_FixedPointToIntegral: { 13948 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13949 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13950 return false; 13951 bool Overflowed; 13952 llvm::APSInt Result = Src.convertToInt( 13953 Info.Ctx.getIntWidth(DestType), 13954 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13955 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13956 return false; 13957 return Success(Result, E); 13958 } 13959 13960 case CK_FixedPointToBoolean: { 13961 // Unsigned padding does not affect this. 13962 APValue Val; 13963 if (!Evaluate(Val, Info, SubExpr)) 13964 return false; 13965 return Success(Val.getFixedPoint().getBoolValue(), E); 13966 } 13967 13968 case CK_IntegralCast: { 13969 if (!Visit(SubExpr)) 13970 return false; 13971 13972 if (!Result.isInt()) { 13973 // Allow casts of address-of-label differences if they are no-ops 13974 // or narrowing. (The narrowing case isn't actually guaranteed to 13975 // be constant-evaluatable except in some narrow cases which are hard 13976 // to detect here. We let it through on the assumption the user knows 13977 // what they are doing.) 13978 if (Result.isAddrLabelDiff()) 13979 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13980 // Only allow casts of lvalues if they are lossless. 13981 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13982 } 13983 13984 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext && 13985 Info.EvalMode == EvalInfo::EM_ConstantExpression && 13986 DestType->isEnumeralType()) { 13987 13988 bool ConstexprVar = true; 13989 13990 // We know if we are here that we are in a context that we might require 13991 // a constant expression or a context that requires a constant 13992 // value. But if we are initializing a value we don't know if it is a 13993 // constexpr variable or not. We can check the EvaluatingDecl to determine 13994 // if it constexpr or not. If not then we don't want to emit a diagnostic. 13995 if (const auto *VD = dyn_cast_or_null<VarDecl>( 13996 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) 13997 ConstexprVar = VD->isConstexpr(); 13998 13999 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType()); 14000 const EnumDecl *ED = ET->getDecl(); 14001 // Check that the value is within the range of the enumeration values. 14002 // 14003 // This corressponds to [expr.static.cast]p10 which says: 14004 // A value of integral or enumeration type can be explicitly converted 14005 // to a complete enumeration type ... If the enumeration type does not 14006 // have a fixed underlying type, the value is unchanged if the original 14007 // value is within the range of the enumeration values ([dcl.enum]), and 14008 // otherwise, the behavior is undefined. 14009 // 14010 // This was resolved as part of DR2338 which has CD5 status. 14011 if (!ED->isFixed()) { 14012 llvm::APInt Min; 14013 llvm::APInt Max; 14014 14015 ED->getValueRange(Max, Min); 14016 --Max; 14017 14018 if (ED->getNumNegativeBits() && ConstexprVar && 14019 (Max.slt(Result.getInt().getSExtValue()) || 14020 Min.sgt(Result.getInt().getSExtValue()))) 14021 Info.Ctx.getDiagnostics().Report( 14022 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range) 14023 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue() 14024 << Max.getSExtValue() << ED; 14025 else if (!ED->getNumNegativeBits() && ConstexprVar && 14026 Max.ult(Result.getInt().getZExtValue())) 14027 Info.Ctx.getDiagnostics().Report( 14028 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range) 14029 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue() 14030 << Max.getZExtValue() << ED; 14031 } 14032 } 14033 14034 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 14035 Result.getInt()), E); 14036 } 14037 14038 case CK_PointerToIntegral: { 14039 CCEDiag(E, diag::note_constexpr_invalid_cast) 14040 << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange(); 14041 14042 LValue LV; 14043 if (!EvaluatePointer(SubExpr, LV, Info)) 14044 return false; 14045 14046 if (LV.getLValueBase()) { 14047 // Only allow based lvalue casts if they are lossless. 14048 // FIXME: Allow a larger integer size than the pointer size, and allow 14049 // narrowing back down to pointer width in subsequent integral casts. 14050 // FIXME: Check integer type's active bits, not its type size. 14051 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 14052 return Error(E); 14053 14054 LV.Designator.setInvalid(); 14055 LV.moveInto(Result); 14056 return true; 14057 } 14058 14059 APSInt AsInt; 14060 APValue V; 14061 LV.moveInto(V); 14062 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 14063 llvm_unreachable("Can't cast this!"); 14064 14065 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 14066 } 14067 14068 case CK_IntegralComplexToReal: { 14069 ComplexValue C; 14070 if (!EvaluateComplex(SubExpr, C, Info)) 14071 return false; 14072 return Success(C.getComplexIntReal(), E); 14073 } 14074 14075 case CK_FloatingToIntegral: { 14076 APFloat F(0.0); 14077 if (!EvaluateFloat(SubExpr, F, Info)) 14078 return false; 14079 14080 APSInt Value; 14081 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 14082 return false; 14083 return Success(Value, E); 14084 } 14085 } 14086 14087 llvm_unreachable("unknown cast resulting in integral value"); 14088 } 14089 14090 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 14091 if (E->getSubExpr()->getType()->isAnyComplexType()) { 14092 ComplexValue LV; 14093 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 14094 return false; 14095 if (!LV.isComplexInt()) 14096 return Error(E); 14097 return Success(LV.getComplexIntReal(), E); 14098 } 14099 14100 return Visit(E->getSubExpr()); 14101 } 14102 14103 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 14104 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 14105 ComplexValue LV; 14106 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 14107 return false; 14108 if (!LV.isComplexInt()) 14109 return Error(E); 14110 return Success(LV.getComplexIntImag(), E); 14111 } 14112 14113 VisitIgnoredValue(E->getSubExpr()); 14114 return Success(0, E); 14115 } 14116 14117 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 14118 return Success(E->getPackLength(), E); 14119 } 14120 14121 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 14122 return Success(E->getValue(), E); 14123 } 14124 14125 bool IntExprEvaluator::VisitConceptSpecializationExpr( 14126 const ConceptSpecializationExpr *E) { 14127 return Success(E->isSatisfied(), E); 14128 } 14129 14130 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 14131 return Success(E->isSatisfied(), E); 14132 } 14133 14134 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14135 switch (E->getOpcode()) { 14136 default: 14137 // Invalid unary operators 14138 return Error(E); 14139 case UO_Plus: 14140 // The result is just the value. 14141 return Visit(E->getSubExpr()); 14142 case UO_Minus: { 14143 if (!Visit(E->getSubExpr())) return false; 14144 if (!Result.isFixedPoint()) 14145 return Error(E); 14146 bool Overflowed; 14147 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 14148 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 14149 return false; 14150 return Success(Negated, E); 14151 } 14152 case UO_LNot: { 14153 bool bres; 14154 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 14155 return false; 14156 return Success(!bres, E); 14157 } 14158 } 14159 } 14160 14161 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 14162 const Expr *SubExpr = E->getSubExpr(); 14163 QualType DestType = E->getType(); 14164 assert(DestType->isFixedPointType() && 14165 "Expected destination type to be a fixed point type"); 14166 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 14167 14168 switch (E->getCastKind()) { 14169 case CK_FixedPointCast: { 14170 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 14171 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 14172 return false; 14173 bool Overflowed; 14174 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 14175 if (Overflowed) { 14176 if (Info.checkingForUndefinedBehavior()) 14177 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 14178 diag::warn_fixedpoint_constant_overflow) 14179 << Result.toString() << E->getType(); 14180 if (!HandleOverflow(Info, E, Result, E->getType())) 14181 return false; 14182 } 14183 return Success(Result, E); 14184 } 14185 case CK_IntegralToFixedPoint: { 14186 APSInt Src; 14187 if (!EvaluateInteger(SubExpr, Src, Info)) 14188 return false; 14189 14190 bool Overflowed; 14191 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 14192 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 14193 14194 if (Overflowed) { 14195 if (Info.checkingForUndefinedBehavior()) 14196 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 14197 diag::warn_fixedpoint_constant_overflow) 14198 << IntResult.toString() << E->getType(); 14199 if (!HandleOverflow(Info, E, IntResult, E->getType())) 14200 return false; 14201 } 14202 14203 return Success(IntResult, E); 14204 } 14205 case CK_FloatingToFixedPoint: { 14206 APFloat Src(0.0); 14207 if (!EvaluateFloat(SubExpr, Src, Info)) 14208 return false; 14209 14210 bool Overflowed; 14211 APFixedPoint Result = APFixedPoint::getFromFloatValue( 14212 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 14213 14214 if (Overflowed) { 14215 if (Info.checkingForUndefinedBehavior()) 14216 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 14217 diag::warn_fixedpoint_constant_overflow) 14218 << Result.toString() << E->getType(); 14219 if (!HandleOverflow(Info, E, Result, E->getType())) 14220 return false; 14221 } 14222 14223 return Success(Result, E); 14224 } 14225 case CK_NoOp: 14226 case CK_LValueToRValue: 14227 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14228 default: 14229 return Error(E); 14230 } 14231 } 14232 14233 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14234 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14235 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14236 14237 const Expr *LHS = E->getLHS(); 14238 const Expr *RHS = E->getRHS(); 14239 FixedPointSemantics ResultFXSema = 14240 Info.Ctx.getFixedPointSemantics(E->getType()); 14241 14242 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 14243 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 14244 return false; 14245 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 14246 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 14247 return false; 14248 14249 bool OpOverflow = false, ConversionOverflow = false; 14250 APFixedPoint Result(LHSFX.getSemantics()); 14251 switch (E->getOpcode()) { 14252 case BO_Add: { 14253 Result = LHSFX.add(RHSFX, &OpOverflow) 14254 .convert(ResultFXSema, &ConversionOverflow); 14255 break; 14256 } 14257 case BO_Sub: { 14258 Result = LHSFX.sub(RHSFX, &OpOverflow) 14259 .convert(ResultFXSema, &ConversionOverflow); 14260 break; 14261 } 14262 case BO_Mul: { 14263 Result = LHSFX.mul(RHSFX, &OpOverflow) 14264 .convert(ResultFXSema, &ConversionOverflow); 14265 break; 14266 } 14267 case BO_Div: { 14268 if (RHSFX.getValue() == 0) { 14269 Info.FFDiag(E, diag::note_expr_divide_by_zero); 14270 return false; 14271 } 14272 Result = LHSFX.div(RHSFX, &OpOverflow) 14273 .convert(ResultFXSema, &ConversionOverflow); 14274 break; 14275 } 14276 case BO_Shl: 14277 case BO_Shr: { 14278 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 14279 llvm::APSInt RHSVal = RHSFX.getValue(); 14280 14281 unsigned ShiftBW = 14282 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 14283 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 14284 // Embedded-C 4.1.6.2.2: 14285 // The right operand must be nonnegative and less than the total number 14286 // of (nonpadding) bits of the fixed-point operand ... 14287 if (RHSVal.isNegative()) 14288 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 14289 else if (Amt != RHSVal) 14290 Info.CCEDiag(E, diag::note_constexpr_large_shift) 14291 << RHSVal << E->getType() << ShiftBW; 14292 14293 if (E->getOpcode() == BO_Shl) 14294 Result = LHSFX.shl(Amt, &OpOverflow); 14295 else 14296 Result = LHSFX.shr(Amt, &OpOverflow); 14297 break; 14298 } 14299 default: 14300 return false; 14301 } 14302 if (OpOverflow || ConversionOverflow) { 14303 if (Info.checkingForUndefinedBehavior()) 14304 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 14305 diag::warn_fixedpoint_constant_overflow) 14306 << Result.toString() << E->getType(); 14307 if (!HandleOverflow(Info, E, Result, E->getType())) 14308 return false; 14309 } 14310 return Success(Result, E); 14311 } 14312 14313 //===----------------------------------------------------------------------===// 14314 // Float Evaluation 14315 //===----------------------------------------------------------------------===// 14316 14317 namespace { 14318 class FloatExprEvaluator 14319 : public ExprEvaluatorBase<FloatExprEvaluator> { 14320 APFloat &Result; 14321 public: 14322 FloatExprEvaluator(EvalInfo &info, APFloat &result) 14323 : ExprEvaluatorBaseTy(info), Result(result) {} 14324 14325 bool Success(const APValue &V, const Expr *e) { 14326 Result = V.getFloat(); 14327 return true; 14328 } 14329 14330 bool ZeroInitialization(const Expr *E) { 14331 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 14332 return true; 14333 } 14334 14335 bool VisitCallExpr(const CallExpr *E); 14336 14337 bool VisitUnaryOperator(const UnaryOperator *E); 14338 bool VisitBinaryOperator(const BinaryOperator *E); 14339 bool VisitFloatingLiteral(const FloatingLiteral *E); 14340 bool VisitCastExpr(const CastExpr *E); 14341 14342 bool VisitUnaryReal(const UnaryOperator *E); 14343 bool VisitUnaryImag(const UnaryOperator *E); 14344 14345 // FIXME: Missing: array subscript of vector, member of vector 14346 }; 14347 } // end anonymous namespace 14348 14349 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 14350 assert(!E->isValueDependent()); 14351 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 14352 return FloatExprEvaluator(Info, Result).Visit(E); 14353 } 14354 14355 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 14356 QualType ResultTy, 14357 const Expr *Arg, 14358 bool SNaN, 14359 llvm::APFloat &Result) { 14360 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 14361 if (!S) return false; 14362 14363 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 14364 14365 llvm::APInt fill; 14366 14367 // Treat empty strings as if they were zero. 14368 if (S->getString().empty()) 14369 fill = llvm::APInt(32, 0); 14370 else if (S->getString().getAsInteger(0, fill)) 14371 return false; 14372 14373 if (Context.getTargetInfo().isNan2008()) { 14374 if (SNaN) 14375 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 14376 else 14377 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 14378 } else { 14379 // Prior to IEEE 754-2008, architectures were allowed to choose whether 14380 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 14381 // a different encoding to what became a standard in 2008, and for pre- 14382 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 14383 // sNaN. This is now known as "legacy NaN" encoding. 14384 if (SNaN) 14385 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 14386 else 14387 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 14388 } 14389 14390 return true; 14391 } 14392 14393 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 14394 if (!IsConstantEvaluatedBuiltinCall(E)) 14395 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14396 14397 switch (E->getBuiltinCallee()) { 14398 default: 14399 return false; 14400 14401 case Builtin::BI__builtin_huge_val: 14402 case Builtin::BI__builtin_huge_valf: 14403 case Builtin::BI__builtin_huge_vall: 14404 case Builtin::BI__builtin_huge_valf16: 14405 case Builtin::BI__builtin_huge_valf128: 14406 case Builtin::BI__builtin_inf: 14407 case Builtin::BI__builtin_inff: 14408 case Builtin::BI__builtin_infl: 14409 case Builtin::BI__builtin_inff16: 14410 case Builtin::BI__builtin_inff128: { 14411 const llvm::fltSemantics &Sem = 14412 Info.Ctx.getFloatTypeSemantics(E->getType()); 14413 Result = llvm::APFloat::getInf(Sem); 14414 return true; 14415 } 14416 14417 case Builtin::BI__builtin_nans: 14418 case Builtin::BI__builtin_nansf: 14419 case Builtin::BI__builtin_nansl: 14420 case Builtin::BI__builtin_nansf16: 14421 case Builtin::BI__builtin_nansf128: 14422 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 14423 true, Result)) 14424 return Error(E); 14425 return true; 14426 14427 case Builtin::BI__builtin_nan: 14428 case Builtin::BI__builtin_nanf: 14429 case Builtin::BI__builtin_nanl: 14430 case Builtin::BI__builtin_nanf16: 14431 case Builtin::BI__builtin_nanf128: 14432 // If this is __builtin_nan() turn this into a nan, otherwise we 14433 // can't constant fold it. 14434 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 14435 false, Result)) 14436 return Error(E); 14437 return true; 14438 14439 case Builtin::BI__builtin_fabs: 14440 case Builtin::BI__builtin_fabsf: 14441 case Builtin::BI__builtin_fabsl: 14442 case Builtin::BI__builtin_fabsf128: 14443 // The C standard says "fabs raises no floating-point exceptions, 14444 // even if x is a signaling NaN. The returned value is independent of 14445 // the current rounding direction mode." Therefore constant folding can 14446 // proceed without regard to the floating point settings. 14447 // Reference, WG14 N2478 F.10.4.3 14448 if (!EvaluateFloat(E->getArg(0), Result, Info)) 14449 return false; 14450 14451 if (Result.isNegative()) 14452 Result.changeSign(); 14453 return true; 14454 14455 case Builtin::BI__arithmetic_fence: 14456 return EvaluateFloat(E->getArg(0), Result, Info); 14457 14458 // FIXME: Builtin::BI__builtin_powi 14459 // FIXME: Builtin::BI__builtin_powif 14460 // FIXME: Builtin::BI__builtin_powil 14461 14462 case Builtin::BI__builtin_copysign: 14463 case Builtin::BI__builtin_copysignf: 14464 case Builtin::BI__builtin_copysignl: 14465 case Builtin::BI__builtin_copysignf128: { 14466 APFloat RHS(0.); 14467 if (!EvaluateFloat(E->getArg(0), Result, Info) || 14468 !EvaluateFloat(E->getArg(1), RHS, Info)) 14469 return false; 14470 Result.copySign(RHS); 14471 return true; 14472 } 14473 14474 case Builtin::BI__builtin_fmax: 14475 case Builtin::BI__builtin_fmaxf: 14476 case Builtin::BI__builtin_fmaxl: 14477 case Builtin::BI__builtin_fmaxf16: 14478 case Builtin::BI__builtin_fmaxf128: { 14479 // TODO: Handle sNaN. 14480 APFloat RHS(0.); 14481 if (!EvaluateFloat(E->getArg(0), Result, Info) || 14482 !EvaluateFloat(E->getArg(1), RHS, Info)) 14483 return false; 14484 // When comparing zeroes, return +0.0 if one of the zeroes is positive. 14485 if (Result.isZero() && RHS.isZero() && Result.isNegative()) 14486 Result = RHS; 14487 else if (Result.isNaN() || RHS > Result) 14488 Result = RHS; 14489 return true; 14490 } 14491 14492 case Builtin::BI__builtin_fmin: 14493 case Builtin::BI__builtin_fminf: 14494 case Builtin::BI__builtin_fminl: 14495 case Builtin::BI__builtin_fminf16: 14496 case Builtin::BI__builtin_fminf128: { 14497 // TODO: Handle sNaN. 14498 APFloat RHS(0.); 14499 if (!EvaluateFloat(E->getArg(0), Result, Info) || 14500 !EvaluateFloat(E->getArg(1), RHS, Info)) 14501 return false; 14502 // When comparing zeroes, return -0.0 if one of the zeroes is negative. 14503 if (Result.isZero() && RHS.isZero() && RHS.isNegative()) 14504 Result = RHS; 14505 else if (Result.isNaN() || RHS < Result) 14506 Result = RHS; 14507 return true; 14508 } 14509 } 14510 } 14511 14512 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 14513 if (E->getSubExpr()->getType()->isAnyComplexType()) { 14514 ComplexValue CV; 14515 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 14516 return false; 14517 Result = CV.FloatReal; 14518 return true; 14519 } 14520 14521 return Visit(E->getSubExpr()); 14522 } 14523 14524 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 14525 if (E->getSubExpr()->getType()->isAnyComplexType()) { 14526 ComplexValue CV; 14527 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 14528 return false; 14529 Result = CV.FloatImag; 14530 return true; 14531 } 14532 14533 VisitIgnoredValue(E->getSubExpr()); 14534 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 14535 Result = llvm::APFloat::getZero(Sem); 14536 return true; 14537 } 14538 14539 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14540 switch (E->getOpcode()) { 14541 default: return Error(E); 14542 case UO_Plus: 14543 return EvaluateFloat(E->getSubExpr(), Result, Info); 14544 case UO_Minus: 14545 // In C standard, WG14 N2478 F.3 p4 14546 // "the unary - raises no floating point exceptions, 14547 // even if the operand is signalling." 14548 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 14549 return false; 14550 Result.changeSign(); 14551 return true; 14552 } 14553 } 14554 14555 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14556 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14557 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14558 14559 APFloat RHS(0.0); 14560 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 14561 if (!LHSOK && !Info.noteFailure()) 14562 return false; 14563 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 14564 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 14565 } 14566 14567 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 14568 Result = E->getValue(); 14569 return true; 14570 } 14571 14572 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 14573 const Expr* SubExpr = E->getSubExpr(); 14574 14575 switch (E->getCastKind()) { 14576 default: 14577 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14578 14579 case CK_IntegralToFloating: { 14580 APSInt IntResult; 14581 const FPOptions FPO = E->getFPFeaturesInEffect( 14582 Info.Ctx.getLangOpts()); 14583 return EvaluateInteger(SubExpr, IntResult, Info) && 14584 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 14585 IntResult, E->getType(), Result); 14586 } 14587 14588 case CK_FixedPointToFloating: { 14589 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 14590 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 14591 return false; 14592 Result = 14593 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 14594 return true; 14595 } 14596 14597 case CK_FloatingCast: { 14598 if (!Visit(SubExpr)) 14599 return false; 14600 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 14601 Result); 14602 } 14603 14604 case CK_FloatingComplexToReal: { 14605 ComplexValue V; 14606 if (!EvaluateComplex(SubExpr, V, Info)) 14607 return false; 14608 Result = V.getComplexFloatReal(); 14609 return true; 14610 } 14611 } 14612 } 14613 14614 //===----------------------------------------------------------------------===// 14615 // Complex Evaluation (for float and integer) 14616 //===----------------------------------------------------------------------===// 14617 14618 namespace { 14619 class ComplexExprEvaluator 14620 : public ExprEvaluatorBase<ComplexExprEvaluator> { 14621 ComplexValue &Result; 14622 14623 public: 14624 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 14625 : ExprEvaluatorBaseTy(info), Result(Result) {} 14626 14627 bool Success(const APValue &V, const Expr *e) { 14628 Result.setFrom(V); 14629 return true; 14630 } 14631 14632 bool ZeroInitialization(const Expr *E); 14633 14634 //===--------------------------------------------------------------------===// 14635 // Visitor Methods 14636 //===--------------------------------------------------------------------===// 14637 14638 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 14639 bool VisitCastExpr(const CastExpr *E); 14640 bool VisitBinaryOperator(const BinaryOperator *E); 14641 bool VisitUnaryOperator(const UnaryOperator *E); 14642 bool VisitInitListExpr(const InitListExpr *E); 14643 bool VisitCallExpr(const CallExpr *E); 14644 }; 14645 } // end anonymous namespace 14646 14647 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 14648 EvalInfo &Info) { 14649 assert(!E->isValueDependent()); 14650 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 14651 return ComplexExprEvaluator(Info, Result).Visit(E); 14652 } 14653 14654 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 14655 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 14656 if (ElemTy->isRealFloatingType()) { 14657 Result.makeComplexFloat(); 14658 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 14659 Result.FloatReal = Zero; 14660 Result.FloatImag = Zero; 14661 } else { 14662 Result.makeComplexInt(); 14663 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 14664 Result.IntReal = Zero; 14665 Result.IntImag = Zero; 14666 } 14667 return true; 14668 } 14669 14670 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 14671 const Expr* SubExpr = E->getSubExpr(); 14672 14673 if (SubExpr->getType()->isRealFloatingType()) { 14674 Result.makeComplexFloat(); 14675 APFloat &Imag = Result.FloatImag; 14676 if (!EvaluateFloat(SubExpr, Imag, Info)) 14677 return false; 14678 14679 Result.FloatReal = APFloat(Imag.getSemantics()); 14680 return true; 14681 } else { 14682 assert(SubExpr->getType()->isIntegerType() && 14683 "Unexpected imaginary literal."); 14684 14685 Result.makeComplexInt(); 14686 APSInt &Imag = Result.IntImag; 14687 if (!EvaluateInteger(SubExpr, Imag, Info)) 14688 return false; 14689 14690 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 14691 return true; 14692 } 14693 } 14694 14695 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 14696 14697 switch (E->getCastKind()) { 14698 case CK_BitCast: 14699 case CK_BaseToDerived: 14700 case CK_DerivedToBase: 14701 case CK_UncheckedDerivedToBase: 14702 case CK_Dynamic: 14703 case CK_ToUnion: 14704 case CK_ArrayToPointerDecay: 14705 case CK_FunctionToPointerDecay: 14706 case CK_NullToPointer: 14707 case CK_NullToMemberPointer: 14708 case CK_BaseToDerivedMemberPointer: 14709 case CK_DerivedToBaseMemberPointer: 14710 case CK_MemberPointerToBoolean: 14711 case CK_ReinterpretMemberPointer: 14712 case CK_ConstructorConversion: 14713 case CK_IntegralToPointer: 14714 case CK_PointerToIntegral: 14715 case CK_PointerToBoolean: 14716 case CK_ToVoid: 14717 case CK_VectorSplat: 14718 case CK_IntegralCast: 14719 case CK_BooleanToSignedIntegral: 14720 case CK_IntegralToBoolean: 14721 case CK_IntegralToFloating: 14722 case CK_FloatingToIntegral: 14723 case CK_FloatingToBoolean: 14724 case CK_FloatingCast: 14725 case CK_CPointerToObjCPointerCast: 14726 case CK_BlockPointerToObjCPointerCast: 14727 case CK_AnyPointerToBlockPointerCast: 14728 case CK_ObjCObjectLValueCast: 14729 case CK_FloatingComplexToReal: 14730 case CK_FloatingComplexToBoolean: 14731 case CK_IntegralComplexToReal: 14732 case CK_IntegralComplexToBoolean: 14733 case CK_ARCProduceObject: 14734 case CK_ARCConsumeObject: 14735 case CK_ARCReclaimReturnedObject: 14736 case CK_ARCExtendBlockObject: 14737 case CK_CopyAndAutoreleaseBlockObject: 14738 case CK_BuiltinFnToFnPtr: 14739 case CK_ZeroToOCLOpaqueType: 14740 case CK_NonAtomicToAtomic: 14741 case CK_AddressSpaceConversion: 14742 case CK_IntToOCLSampler: 14743 case CK_FloatingToFixedPoint: 14744 case CK_FixedPointToFloating: 14745 case CK_FixedPointCast: 14746 case CK_FixedPointToBoolean: 14747 case CK_FixedPointToIntegral: 14748 case CK_IntegralToFixedPoint: 14749 case CK_MatrixCast: 14750 llvm_unreachable("invalid cast kind for complex value"); 14751 14752 case CK_LValueToRValue: 14753 case CK_AtomicToNonAtomic: 14754 case CK_NoOp: 14755 case CK_LValueToRValueBitCast: 14756 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14757 14758 case CK_Dependent: 14759 case CK_LValueBitCast: 14760 case CK_UserDefinedConversion: 14761 return Error(E); 14762 14763 case CK_FloatingRealToComplex: { 14764 APFloat &Real = Result.FloatReal; 14765 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 14766 return false; 14767 14768 Result.makeComplexFloat(); 14769 Result.FloatImag = APFloat(Real.getSemantics()); 14770 return true; 14771 } 14772 14773 case CK_FloatingComplexCast: { 14774 if (!Visit(E->getSubExpr())) 14775 return false; 14776 14777 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14778 QualType From 14779 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14780 14781 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 14782 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 14783 } 14784 14785 case CK_FloatingComplexToIntegralComplex: { 14786 if (!Visit(E->getSubExpr())) 14787 return false; 14788 14789 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14790 QualType From 14791 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14792 Result.makeComplexInt(); 14793 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 14794 To, Result.IntReal) && 14795 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 14796 To, Result.IntImag); 14797 } 14798 14799 case CK_IntegralRealToComplex: { 14800 APSInt &Real = Result.IntReal; 14801 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14802 return false; 14803 14804 Result.makeComplexInt(); 14805 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14806 return true; 14807 } 14808 14809 case CK_IntegralComplexCast: { 14810 if (!Visit(E->getSubExpr())) 14811 return false; 14812 14813 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14814 QualType From 14815 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14816 14817 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14818 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14819 return true; 14820 } 14821 14822 case CK_IntegralComplexToFloatingComplex: { 14823 if (!Visit(E->getSubExpr())) 14824 return false; 14825 14826 const FPOptions FPO = E->getFPFeaturesInEffect( 14827 Info.Ctx.getLangOpts()); 14828 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14829 QualType From 14830 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14831 Result.makeComplexFloat(); 14832 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14833 To, Result.FloatReal) && 14834 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14835 To, Result.FloatImag); 14836 } 14837 } 14838 14839 llvm_unreachable("unknown cast resulting in complex value"); 14840 } 14841 14842 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14843 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14844 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14845 14846 // Track whether the LHS or RHS is real at the type system level. When this is 14847 // the case we can simplify our evaluation strategy. 14848 bool LHSReal = false, RHSReal = false; 14849 14850 bool LHSOK; 14851 if (E->getLHS()->getType()->isRealFloatingType()) { 14852 LHSReal = true; 14853 APFloat &Real = Result.FloatReal; 14854 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14855 if (LHSOK) { 14856 Result.makeComplexFloat(); 14857 Result.FloatImag = APFloat(Real.getSemantics()); 14858 } 14859 } else { 14860 LHSOK = Visit(E->getLHS()); 14861 } 14862 if (!LHSOK && !Info.noteFailure()) 14863 return false; 14864 14865 ComplexValue RHS; 14866 if (E->getRHS()->getType()->isRealFloatingType()) { 14867 RHSReal = true; 14868 APFloat &Real = RHS.FloatReal; 14869 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14870 return false; 14871 RHS.makeComplexFloat(); 14872 RHS.FloatImag = APFloat(Real.getSemantics()); 14873 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14874 return false; 14875 14876 assert(!(LHSReal && RHSReal) && 14877 "Cannot have both operands of a complex operation be real."); 14878 switch (E->getOpcode()) { 14879 default: return Error(E); 14880 case BO_Add: 14881 if (Result.isComplexFloat()) { 14882 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14883 APFloat::rmNearestTiesToEven); 14884 if (LHSReal) 14885 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14886 else if (!RHSReal) 14887 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14888 APFloat::rmNearestTiesToEven); 14889 } else { 14890 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14891 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14892 } 14893 break; 14894 case BO_Sub: 14895 if (Result.isComplexFloat()) { 14896 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14897 APFloat::rmNearestTiesToEven); 14898 if (LHSReal) { 14899 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14900 Result.getComplexFloatImag().changeSign(); 14901 } else if (!RHSReal) { 14902 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14903 APFloat::rmNearestTiesToEven); 14904 } 14905 } else { 14906 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14907 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14908 } 14909 break; 14910 case BO_Mul: 14911 if (Result.isComplexFloat()) { 14912 // This is an implementation of complex multiplication according to the 14913 // constraints laid out in C11 Annex G. The implementation uses the 14914 // following naming scheme: 14915 // (a + ib) * (c + id) 14916 ComplexValue LHS = Result; 14917 APFloat &A = LHS.getComplexFloatReal(); 14918 APFloat &B = LHS.getComplexFloatImag(); 14919 APFloat &C = RHS.getComplexFloatReal(); 14920 APFloat &D = RHS.getComplexFloatImag(); 14921 APFloat &ResR = Result.getComplexFloatReal(); 14922 APFloat &ResI = Result.getComplexFloatImag(); 14923 if (LHSReal) { 14924 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14925 ResR = A * C; 14926 ResI = A * D; 14927 } else if (RHSReal) { 14928 ResR = C * A; 14929 ResI = C * B; 14930 } else { 14931 // In the fully general case, we need to handle NaNs and infinities 14932 // robustly. 14933 APFloat AC = A * C; 14934 APFloat BD = B * D; 14935 APFloat AD = A * D; 14936 APFloat BC = B * C; 14937 ResR = AC - BD; 14938 ResI = AD + BC; 14939 if (ResR.isNaN() && ResI.isNaN()) { 14940 bool Recalc = false; 14941 if (A.isInfinity() || B.isInfinity()) { 14942 A = APFloat::copySign( 14943 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14944 B = APFloat::copySign( 14945 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14946 if (C.isNaN()) 14947 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14948 if (D.isNaN()) 14949 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14950 Recalc = true; 14951 } 14952 if (C.isInfinity() || D.isInfinity()) { 14953 C = APFloat::copySign( 14954 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14955 D = APFloat::copySign( 14956 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14957 if (A.isNaN()) 14958 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14959 if (B.isNaN()) 14960 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14961 Recalc = true; 14962 } 14963 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14964 AD.isInfinity() || BC.isInfinity())) { 14965 if (A.isNaN()) 14966 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14967 if (B.isNaN()) 14968 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14969 if (C.isNaN()) 14970 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14971 if (D.isNaN()) 14972 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14973 Recalc = true; 14974 } 14975 if (Recalc) { 14976 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14977 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14978 } 14979 } 14980 } 14981 } else { 14982 ComplexValue LHS = Result; 14983 Result.getComplexIntReal() = 14984 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14985 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14986 Result.getComplexIntImag() = 14987 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14988 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14989 } 14990 break; 14991 case BO_Div: 14992 if (Result.isComplexFloat()) { 14993 // This is an implementation of complex division according to the 14994 // constraints laid out in C11 Annex G. The implementation uses the 14995 // following naming scheme: 14996 // (a + ib) / (c + id) 14997 ComplexValue LHS = Result; 14998 APFloat &A = LHS.getComplexFloatReal(); 14999 APFloat &B = LHS.getComplexFloatImag(); 15000 APFloat &C = RHS.getComplexFloatReal(); 15001 APFloat &D = RHS.getComplexFloatImag(); 15002 APFloat &ResR = Result.getComplexFloatReal(); 15003 APFloat &ResI = Result.getComplexFloatImag(); 15004 if (RHSReal) { 15005 ResR = A / C; 15006 ResI = B / C; 15007 } else { 15008 if (LHSReal) { 15009 // No real optimizations we can do here, stub out with zero. 15010 B = APFloat::getZero(A.getSemantics()); 15011 } 15012 int DenomLogB = 0; 15013 APFloat MaxCD = maxnum(abs(C), abs(D)); 15014 if (MaxCD.isFinite()) { 15015 DenomLogB = ilogb(MaxCD); 15016 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 15017 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 15018 } 15019 APFloat Denom = C * C + D * D; 15020 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 15021 APFloat::rmNearestTiesToEven); 15022 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 15023 APFloat::rmNearestTiesToEven); 15024 if (ResR.isNaN() && ResI.isNaN()) { 15025 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 15026 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 15027 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 15028 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 15029 D.isFinite()) { 15030 A = APFloat::copySign( 15031 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 15032 B = APFloat::copySign( 15033 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 15034 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 15035 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 15036 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 15037 C = APFloat::copySign( 15038 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 15039 D = APFloat::copySign( 15040 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 15041 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 15042 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 15043 } 15044 } 15045 } 15046 } else { 15047 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 15048 return Error(E, diag::note_expr_divide_by_zero); 15049 15050 ComplexValue LHS = Result; 15051 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 15052 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 15053 Result.getComplexIntReal() = 15054 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 15055 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 15056 Result.getComplexIntImag() = 15057 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 15058 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 15059 } 15060 break; 15061 } 15062 15063 return true; 15064 } 15065 15066 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 15067 // Get the operand value into 'Result'. 15068 if (!Visit(E->getSubExpr())) 15069 return false; 15070 15071 switch (E->getOpcode()) { 15072 default: 15073 return Error(E); 15074 case UO_Extension: 15075 return true; 15076 case UO_Plus: 15077 // The result is always just the subexpr. 15078 return true; 15079 case UO_Minus: 15080 if (Result.isComplexFloat()) { 15081 Result.getComplexFloatReal().changeSign(); 15082 Result.getComplexFloatImag().changeSign(); 15083 } 15084 else { 15085 Result.getComplexIntReal() = -Result.getComplexIntReal(); 15086 Result.getComplexIntImag() = -Result.getComplexIntImag(); 15087 } 15088 return true; 15089 case UO_Not: 15090 if (Result.isComplexFloat()) 15091 Result.getComplexFloatImag().changeSign(); 15092 else 15093 Result.getComplexIntImag() = -Result.getComplexIntImag(); 15094 return true; 15095 } 15096 } 15097 15098 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 15099 if (E->getNumInits() == 2) { 15100 if (E->getType()->isComplexType()) { 15101 Result.makeComplexFloat(); 15102 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 15103 return false; 15104 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 15105 return false; 15106 } else { 15107 Result.makeComplexInt(); 15108 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 15109 return false; 15110 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 15111 return false; 15112 } 15113 return true; 15114 } 15115 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 15116 } 15117 15118 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 15119 if (!IsConstantEvaluatedBuiltinCall(E)) 15120 return ExprEvaluatorBaseTy::VisitCallExpr(E); 15121 15122 switch (E->getBuiltinCallee()) { 15123 case Builtin::BI__builtin_complex: 15124 Result.makeComplexFloat(); 15125 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 15126 return false; 15127 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 15128 return false; 15129 return true; 15130 15131 default: 15132 return false; 15133 } 15134 } 15135 15136 //===----------------------------------------------------------------------===// 15137 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 15138 // implicit conversion. 15139 //===----------------------------------------------------------------------===// 15140 15141 namespace { 15142 class AtomicExprEvaluator : 15143 public ExprEvaluatorBase<AtomicExprEvaluator> { 15144 const LValue *This; 15145 APValue &Result; 15146 public: 15147 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 15148 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 15149 15150 bool Success(const APValue &V, const Expr *E) { 15151 Result = V; 15152 return true; 15153 } 15154 15155 bool ZeroInitialization(const Expr *E) { 15156 ImplicitValueInitExpr VIE( 15157 E->getType()->castAs<AtomicType>()->getValueType()); 15158 // For atomic-qualified class (and array) types in C++, initialize the 15159 // _Atomic-wrapped subobject directly, in-place. 15160 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 15161 : Evaluate(Result, Info, &VIE); 15162 } 15163 15164 bool VisitCastExpr(const CastExpr *E) { 15165 switch (E->getCastKind()) { 15166 default: 15167 return ExprEvaluatorBaseTy::VisitCastExpr(E); 15168 case CK_NullToPointer: 15169 VisitIgnoredValue(E->getSubExpr()); 15170 return ZeroInitialization(E); 15171 case CK_NonAtomicToAtomic: 15172 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 15173 : Evaluate(Result, Info, E->getSubExpr()); 15174 } 15175 } 15176 }; 15177 } // end anonymous namespace 15178 15179 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 15180 EvalInfo &Info) { 15181 assert(!E->isValueDependent()); 15182 assert(E->isPRValue() && E->getType()->isAtomicType()); 15183 return AtomicExprEvaluator(Info, This, Result).Visit(E); 15184 } 15185 15186 //===----------------------------------------------------------------------===// 15187 // Void expression evaluation, primarily for a cast to void on the LHS of a 15188 // comma operator 15189 //===----------------------------------------------------------------------===// 15190 15191 namespace { 15192 class VoidExprEvaluator 15193 : public ExprEvaluatorBase<VoidExprEvaluator> { 15194 public: 15195 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 15196 15197 bool Success(const APValue &V, const Expr *e) { return true; } 15198 15199 bool ZeroInitialization(const Expr *E) { return true; } 15200 15201 bool VisitCastExpr(const CastExpr *E) { 15202 switch (E->getCastKind()) { 15203 default: 15204 return ExprEvaluatorBaseTy::VisitCastExpr(E); 15205 case CK_ToVoid: 15206 VisitIgnoredValue(E->getSubExpr()); 15207 return true; 15208 } 15209 } 15210 15211 bool VisitCallExpr(const CallExpr *E) { 15212 if (!IsConstantEvaluatedBuiltinCall(E)) 15213 return ExprEvaluatorBaseTy::VisitCallExpr(E); 15214 15215 switch (E->getBuiltinCallee()) { 15216 case Builtin::BI__assume: 15217 case Builtin::BI__builtin_assume: 15218 // The argument is not evaluated! 15219 return true; 15220 15221 case Builtin::BI__builtin_operator_delete: 15222 return HandleOperatorDeleteCall(Info, E); 15223 15224 default: 15225 return false; 15226 } 15227 } 15228 15229 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 15230 }; 15231 } // end anonymous namespace 15232 15233 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 15234 // We cannot speculatively evaluate a delete expression. 15235 if (Info.SpeculativeEvaluationDepth) 15236 return false; 15237 15238 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 15239 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 15240 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 15241 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 15242 return false; 15243 } 15244 15245 const Expr *Arg = E->getArgument(); 15246 15247 LValue Pointer; 15248 if (!EvaluatePointer(Arg, Pointer, Info)) 15249 return false; 15250 if (Pointer.Designator.Invalid) 15251 return false; 15252 15253 // Deleting a null pointer has no effect. 15254 if (Pointer.isNullPointer()) { 15255 // This is the only case where we need to produce an extension warning: 15256 // the only other way we can succeed is if we find a dynamic allocation, 15257 // and we will have warned when we allocated it in that case. 15258 if (!Info.getLangOpts().CPlusPlus20) 15259 Info.CCEDiag(E, diag::note_constexpr_new); 15260 return true; 15261 } 15262 15263 std::optional<DynAlloc *> Alloc = CheckDeleteKind( 15264 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 15265 if (!Alloc) 15266 return false; 15267 QualType AllocType = Pointer.Base.getDynamicAllocType(); 15268 15269 // For the non-array case, the designator must be empty if the static type 15270 // does not have a virtual destructor. 15271 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 15272 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 15273 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 15274 << Arg->getType()->getPointeeType() << AllocType; 15275 return false; 15276 } 15277 15278 // For a class type with a virtual destructor, the selected operator delete 15279 // is the one looked up when building the destructor. 15280 if (!E->isArrayForm() && !E->isGlobalDelete()) { 15281 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 15282 if (VirtualDelete && 15283 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 15284 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 15285 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 15286 return false; 15287 } 15288 } 15289 15290 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 15291 (*Alloc)->Value, AllocType)) 15292 return false; 15293 15294 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 15295 // The element was already erased. This means the destructor call also 15296 // deleted the object. 15297 // FIXME: This probably results in undefined behavior before we get this 15298 // far, and should be diagnosed elsewhere first. 15299 Info.FFDiag(E, diag::note_constexpr_double_delete); 15300 return false; 15301 } 15302 15303 return true; 15304 } 15305 15306 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 15307 assert(!E->isValueDependent()); 15308 assert(E->isPRValue() && E->getType()->isVoidType()); 15309 return VoidExprEvaluator(Info).Visit(E); 15310 } 15311 15312 //===----------------------------------------------------------------------===// 15313 // Top level Expr::EvaluateAsRValue method. 15314 //===----------------------------------------------------------------------===// 15315 15316 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 15317 assert(!E->isValueDependent()); 15318 // In C, function designators are not lvalues, but we evaluate them as if they 15319 // are. 15320 QualType T = E->getType(); 15321 if (E->isGLValue() || T->isFunctionType()) { 15322 LValue LV; 15323 if (!EvaluateLValue(E, LV, Info)) 15324 return false; 15325 LV.moveInto(Result); 15326 } else if (T->isVectorType()) { 15327 if (!EvaluateVector(E, Result, Info)) 15328 return false; 15329 } else if (T->isIntegralOrEnumerationType()) { 15330 if (!IntExprEvaluator(Info, Result).Visit(E)) 15331 return false; 15332 } else if (T->hasPointerRepresentation()) { 15333 LValue LV; 15334 if (!EvaluatePointer(E, LV, Info)) 15335 return false; 15336 LV.moveInto(Result); 15337 } else if (T->isRealFloatingType()) { 15338 llvm::APFloat F(0.0); 15339 if (!EvaluateFloat(E, F, Info)) 15340 return false; 15341 Result = APValue(F); 15342 } else if (T->isAnyComplexType()) { 15343 ComplexValue C; 15344 if (!EvaluateComplex(E, C, Info)) 15345 return false; 15346 C.moveInto(Result); 15347 } else if (T->isFixedPointType()) { 15348 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 15349 } else if (T->isMemberPointerType()) { 15350 MemberPtr P; 15351 if (!EvaluateMemberPointer(E, P, Info)) 15352 return false; 15353 P.moveInto(Result); 15354 return true; 15355 } else if (T->isArrayType()) { 15356 LValue LV; 15357 APValue &Value = 15358 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 15359 if (!EvaluateArray(E, LV, Value, Info)) 15360 return false; 15361 Result = Value; 15362 } else if (T->isRecordType()) { 15363 LValue LV; 15364 APValue &Value = 15365 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 15366 if (!EvaluateRecord(E, LV, Value, Info)) 15367 return false; 15368 Result = Value; 15369 } else if (T->isVoidType()) { 15370 if (!Info.getLangOpts().CPlusPlus11) 15371 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 15372 << E->getType(); 15373 if (!EvaluateVoid(E, Info)) 15374 return false; 15375 } else if (T->isAtomicType()) { 15376 QualType Unqual = T.getAtomicUnqualifiedType(); 15377 if (Unqual->isArrayType() || Unqual->isRecordType()) { 15378 LValue LV; 15379 APValue &Value = Info.CurrentCall->createTemporary( 15380 E, Unqual, ScopeKind::FullExpression, LV); 15381 if (!EvaluateAtomic(E, &LV, Value, Info)) 15382 return false; 15383 Result = Value; 15384 } else { 15385 if (!EvaluateAtomic(E, nullptr, Result, Info)) 15386 return false; 15387 } 15388 } else if (Info.getLangOpts().CPlusPlus11) { 15389 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 15390 return false; 15391 } else { 15392 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 15393 return false; 15394 } 15395 15396 return true; 15397 } 15398 15399 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 15400 /// cases, the in-place evaluation is essential, since later initializers for 15401 /// an object can indirectly refer to subobjects which were initialized earlier. 15402 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 15403 const Expr *E, bool AllowNonLiteralTypes) { 15404 assert(!E->isValueDependent()); 15405 15406 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 15407 return false; 15408 15409 if (E->isPRValue()) { 15410 // Evaluate arrays and record types in-place, so that later initializers can 15411 // refer to earlier-initialized members of the object. 15412 QualType T = E->getType(); 15413 if (T->isArrayType()) 15414 return EvaluateArray(E, This, Result, Info); 15415 else if (T->isRecordType()) 15416 return EvaluateRecord(E, This, Result, Info); 15417 else if (T->isAtomicType()) { 15418 QualType Unqual = T.getAtomicUnqualifiedType(); 15419 if (Unqual->isArrayType() || Unqual->isRecordType()) 15420 return EvaluateAtomic(E, &This, Result, Info); 15421 } 15422 } 15423 15424 // For any other type, in-place evaluation is unimportant. 15425 return Evaluate(Result, Info, E); 15426 } 15427 15428 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 15429 /// lvalue-to-rvalue cast if it is an lvalue. 15430 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 15431 assert(!E->isValueDependent()); 15432 15433 if (E->getType().isNull()) 15434 return false; 15435 15436 if (!CheckLiteralType(Info, E)) 15437 return false; 15438 15439 if (Info.EnableNewConstInterp) { 15440 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 15441 return false; 15442 } else { 15443 if (!::Evaluate(Result, Info, E)) 15444 return false; 15445 } 15446 15447 // Implicit lvalue-to-rvalue cast. 15448 if (E->isGLValue()) { 15449 LValue LV; 15450 LV.setFrom(Info.Ctx, Result); 15451 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 15452 return false; 15453 } 15454 15455 // Check this core constant expression is a constant expression. 15456 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 15457 ConstantExprKind::Normal) && 15458 CheckMemoryLeaks(Info); 15459 } 15460 15461 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 15462 const ASTContext &Ctx, bool &IsConst) { 15463 // Fast-path evaluations of integer literals, since we sometimes see files 15464 // containing vast quantities of these. 15465 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 15466 Result.Val = APValue(APSInt(L->getValue(), 15467 L->getType()->isUnsignedIntegerType())); 15468 IsConst = true; 15469 return true; 15470 } 15471 15472 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) { 15473 Result.Val = APValue(APSInt(APInt(1, L->getValue()))); 15474 IsConst = true; 15475 return true; 15476 } 15477 15478 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) { 15479 if (CE->hasAPValueResult()) { 15480 Result.Val = CE->getAPValueResult(); 15481 IsConst = true; 15482 return true; 15483 } 15484 15485 // The SubExpr is usually just an IntegerLiteral. 15486 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst); 15487 } 15488 15489 // This case should be rare, but we need to check it before we check on 15490 // the type below. 15491 if (Exp->getType().isNull()) { 15492 IsConst = false; 15493 return true; 15494 } 15495 15496 return false; 15497 } 15498 15499 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 15500 Expr::SideEffectsKind SEK) { 15501 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 15502 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 15503 } 15504 15505 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 15506 const ASTContext &Ctx, EvalInfo &Info) { 15507 assert(!E->isValueDependent()); 15508 bool IsConst; 15509 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 15510 return IsConst; 15511 15512 return EvaluateAsRValue(Info, E, Result.Val); 15513 } 15514 15515 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 15516 const ASTContext &Ctx, 15517 Expr::SideEffectsKind AllowSideEffects, 15518 EvalInfo &Info) { 15519 assert(!E->isValueDependent()); 15520 if (!E->getType()->isIntegralOrEnumerationType()) 15521 return false; 15522 15523 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 15524 !ExprResult.Val.isInt() || 15525 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15526 return false; 15527 15528 return true; 15529 } 15530 15531 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 15532 const ASTContext &Ctx, 15533 Expr::SideEffectsKind AllowSideEffects, 15534 EvalInfo &Info) { 15535 assert(!E->isValueDependent()); 15536 if (!E->getType()->isFixedPointType()) 15537 return false; 15538 15539 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 15540 return false; 15541 15542 if (!ExprResult.Val.isFixedPoint() || 15543 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15544 return false; 15545 15546 return true; 15547 } 15548 15549 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 15550 /// any crazy technique (that has nothing to do with language standards) that 15551 /// we want to. If this function returns true, it returns the folded constant 15552 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 15553 /// will be applied to the result. 15554 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 15555 bool InConstantContext) const { 15556 assert(!isValueDependent() && 15557 "Expression evaluator can't be called on a dependent expression."); 15558 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue"); 15559 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15560 Info.InConstantContext = InConstantContext; 15561 return ::EvaluateAsRValue(this, Result, Ctx, Info); 15562 } 15563 15564 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 15565 bool InConstantContext) const { 15566 assert(!isValueDependent() && 15567 "Expression evaluator can't be called on a dependent expression."); 15568 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition"); 15569 EvalResult Scratch; 15570 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 15571 HandleConversionToBool(Scratch.Val, Result); 15572 } 15573 15574 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 15575 SideEffectsKind AllowSideEffects, 15576 bool InConstantContext) const { 15577 assert(!isValueDependent() && 15578 "Expression evaluator can't be called on a dependent expression."); 15579 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt"); 15580 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15581 Info.InConstantContext = InConstantContext; 15582 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 15583 } 15584 15585 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 15586 SideEffectsKind AllowSideEffects, 15587 bool InConstantContext) const { 15588 assert(!isValueDependent() && 15589 "Expression evaluator can't be called on a dependent expression."); 15590 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint"); 15591 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15592 Info.InConstantContext = InConstantContext; 15593 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 15594 } 15595 15596 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 15597 SideEffectsKind AllowSideEffects, 15598 bool InConstantContext) const { 15599 assert(!isValueDependent() && 15600 "Expression evaluator can't be called on a dependent expression."); 15601 15602 if (!getType()->isRealFloatingType()) 15603 return false; 15604 15605 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat"); 15606 EvalResult ExprResult; 15607 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 15608 !ExprResult.Val.isFloat() || 15609 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15610 return false; 15611 15612 Result = ExprResult.Val.getFloat(); 15613 return true; 15614 } 15615 15616 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 15617 bool InConstantContext) const { 15618 assert(!isValueDependent() && 15619 "Expression evaluator can't be called on a dependent expression."); 15620 15621 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue"); 15622 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 15623 Info.InConstantContext = InConstantContext; 15624 LValue LV; 15625 CheckedTemporaries CheckedTemps; 15626 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 15627 Result.HasSideEffects || 15628 !CheckLValueConstantExpression(Info, getExprLoc(), 15629 Ctx.getLValueReferenceType(getType()), LV, 15630 ConstantExprKind::Normal, CheckedTemps)) 15631 return false; 15632 15633 LV.moveInto(Result.Val); 15634 return true; 15635 } 15636 15637 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 15638 APValue DestroyedValue, QualType Type, 15639 SourceLocation Loc, Expr::EvalStatus &EStatus, 15640 bool IsConstantDestruction) { 15641 EvalInfo Info(Ctx, EStatus, 15642 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 15643 : EvalInfo::EM_ConstantFold); 15644 Info.setEvaluatingDecl(Base, DestroyedValue, 15645 EvalInfo::EvaluatingDeclKind::Dtor); 15646 Info.InConstantContext = IsConstantDestruction; 15647 15648 LValue LVal; 15649 LVal.set(Base); 15650 15651 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 15652 EStatus.HasSideEffects) 15653 return false; 15654 15655 if (!Info.discardCleanups()) 15656 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15657 15658 return true; 15659 } 15660 15661 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 15662 ConstantExprKind Kind) const { 15663 assert(!isValueDependent() && 15664 "Expression evaluator can't be called on a dependent expression."); 15665 bool IsConst; 15666 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue()) 15667 return true; 15668 15669 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr"); 15670 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 15671 EvalInfo Info(Ctx, Result, EM); 15672 Info.InConstantContext = true; 15673 15674 // The type of the object we're initializing is 'const T' for a class NTTP. 15675 QualType T = getType(); 15676 if (Kind == ConstantExprKind::ClassTemplateArgument) 15677 T.addConst(); 15678 15679 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 15680 // represent the result of the evaluation. CheckConstantExpression ensures 15681 // this doesn't escape. 15682 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 15683 APValue::LValueBase Base(&BaseMTE); 15684 Info.setEvaluatingDecl(Base, Result.Val); 15685 15686 if (Info.EnableNewConstInterp) { 15687 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val)) 15688 return false; 15689 } else { 15690 LValue LVal; 15691 LVal.set(Base); 15692 // C++23 [intro.execution]/p5 15693 // A full-expression is [...] a constant-expression 15694 // So we need to make sure temporary objects are destroyed after having 15695 // evaluating the expression (per C++23 [class.temporary]/p4). 15696 FullExpressionRAII Scope(Info); 15697 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 15698 Result.HasSideEffects || !Scope.destroy()) 15699 return false; 15700 15701 if (!Info.discardCleanups()) 15702 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15703 } 15704 15705 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 15706 Result.Val, Kind)) 15707 return false; 15708 if (!CheckMemoryLeaks(Info)) 15709 return false; 15710 15711 // If this is a class template argument, it's required to have constant 15712 // destruction too. 15713 if (Kind == ConstantExprKind::ClassTemplateArgument && 15714 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 15715 true) || 15716 Result.HasSideEffects)) { 15717 // FIXME: Prefix a note to indicate that the problem is lack of constant 15718 // destruction. 15719 return false; 15720 } 15721 15722 return true; 15723 } 15724 15725 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 15726 const VarDecl *VD, 15727 SmallVectorImpl<PartialDiagnosticAt> &Notes, 15728 bool IsConstantInitialization) const { 15729 assert(!isValueDependent() && 15730 "Expression evaluator can't be called on a dependent expression."); 15731 15732 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] { 15733 std::string Name; 15734 llvm::raw_string_ostream OS(Name); 15735 VD->printQualifiedName(OS); 15736 return Name; 15737 }); 15738 15739 Expr::EvalStatus EStatus; 15740 EStatus.Diag = &Notes; 15741 15742 EvalInfo Info(Ctx, EStatus, 15743 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus) 15744 ? EvalInfo::EM_ConstantExpression 15745 : EvalInfo::EM_ConstantFold); 15746 Info.setEvaluatingDecl(VD, Value); 15747 Info.InConstantContext = IsConstantInitialization; 15748 15749 if (Info.EnableNewConstInterp) { 15750 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 15751 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 15752 return false; 15753 } else { 15754 LValue LVal; 15755 LVal.set(VD); 15756 15757 if (!EvaluateInPlace(Value, Info, LVal, this, 15758 /*AllowNonLiteralTypes=*/true) || 15759 EStatus.HasSideEffects) 15760 return false; 15761 15762 // At this point, any lifetime-extended temporaries are completely 15763 // initialized. 15764 Info.performLifetimeExtension(); 15765 15766 if (!Info.discardCleanups()) 15767 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15768 } 15769 15770 SourceLocation DeclLoc = VD->getLocation(); 15771 QualType DeclTy = VD->getType(); 15772 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 15773 ConstantExprKind::Normal) && 15774 CheckMemoryLeaks(Info); 15775 } 15776 15777 bool VarDecl::evaluateDestruction( 15778 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15779 Expr::EvalStatus EStatus; 15780 EStatus.Diag = &Notes; 15781 15782 // Only treat the destruction as constant destruction if we formally have 15783 // constant initialization (or are usable in a constant expression). 15784 bool IsConstantDestruction = hasConstantInitialization(); 15785 15786 // Make a copy of the value for the destructor to mutate, if we know it. 15787 // Otherwise, treat the value as default-initialized; if the destructor works 15788 // anyway, then the destruction is constant (and must be essentially empty). 15789 APValue DestroyedValue; 15790 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 15791 DestroyedValue = *getEvaluatedValue(); 15792 else if (!handleDefaultInitValue(getType(), DestroyedValue)) 15793 return false; 15794 15795 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 15796 getType(), getLocation(), EStatus, 15797 IsConstantDestruction) || 15798 EStatus.HasSideEffects) 15799 return false; 15800 15801 ensureEvaluatedStmt()->HasConstantDestruction = true; 15802 return true; 15803 } 15804 15805 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 15806 /// constant folded, but discard the result. 15807 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 15808 assert(!isValueDependent() && 15809 "Expression evaluator can't be called on a dependent expression."); 15810 15811 EvalResult Result; 15812 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 15813 !hasUnacceptableSideEffect(Result, SEK); 15814 } 15815 15816 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 15817 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15818 assert(!isValueDependent() && 15819 "Expression evaluator can't be called on a dependent expression."); 15820 15821 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt"); 15822 EvalResult EVResult; 15823 EVResult.Diag = Diag; 15824 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15825 Info.InConstantContext = true; 15826 15827 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 15828 (void)Result; 15829 assert(Result && "Could not evaluate expression"); 15830 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15831 15832 return EVResult.Val.getInt(); 15833 } 15834 15835 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 15836 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15837 assert(!isValueDependent() && 15838 "Expression evaluator can't be called on a dependent expression."); 15839 15840 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow"); 15841 EvalResult EVResult; 15842 EVResult.Diag = Diag; 15843 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15844 Info.InConstantContext = true; 15845 Info.CheckingForUndefinedBehavior = true; 15846 15847 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15848 (void)Result; 15849 assert(Result && "Could not evaluate expression"); 15850 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15851 15852 return EVResult.Val.getInt(); 15853 } 15854 15855 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15856 assert(!isValueDependent() && 15857 "Expression evaluator can't be called on a dependent expression."); 15858 15859 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow"); 15860 bool IsConst; 15861 EvalResult EVResult; 15862 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15863 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15864 Info.CheckingForUndefinedBehavior = true; 15865 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15866 } 15867 } 15868 15869 bool Expr::EvalResult::isGlobalLValue() const { 15870 assert(Val.isLValue()); 15871 return IsGlobalLValue(Val.getLValueBase()); 15872 } 15873 15874 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15875 /// an integer constant expression. 15876 15877 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15878 /// comma, etc 15879 15880 // CheckICE - This function does the fundamental ICE checking: the returned 15881 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15882 // and a (possibly null) SourceLocation indicating the location of the problem. 15883 // 15884 // Note that to reduce code duplication, this helper does no evaluation 15885 // itself; the caller checks whether the expression is evaluatable, and 15886 // in the rare cases where CheckICE actually cares about the evaluated 15887 // value, it calls into Evaluate. 15888 15889 namespace { 15890 15891 enum ICEKind { 15892 /// This expression is an ICE. 15893 IK_ICE, 15894 /// This expression is not an ICE, but if it isn't evaluated, it's 15895 /// a legal subexpression for an ICE. This return value is used to handle 15896 /// the comma operator in C99 mode, and non-constant subexpressions. 15897 IK_ICEIfUnevaluated, 15898 /// This expression is not an ICE, and is not a legal subexpression for one. 15899 IK_NotICE 15900 }; 15901 15902 struct ICEDiag { 15903 ICEKind Kind; 15904 SourceLocation Loc; 15905 15906 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15907 }; 15908 15909 } 15910 15911 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15912 15913 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15914 15915 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15916 Expr::EvalResult EVResult; 15917 Expr::EvalStatus Status; 15918 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15919 15920 Info.InConstantContext = true; 15921 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15922 !EVResult.Val.isInt()) 15923 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15924 15925 return NoDiag(); 15926 } 15927 15928 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15929 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15930 if (!E->getType()->isIntegralOrEnumerationType()) 15931 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15932 15933 switch (E->getStmtClass()) { 15934 #define ABSTRACT_STMT(Node) 15935 #define STMT(Node, Base) case Expr::Node##Class: 15936 #define EXPR(Node, Base) 15937 #include "clang/AST/StmtNodes.inc" 15938 case Expr::PredefinedExprClass: 15939 case Expr::FloatingLiteralClass: 15940 case Expr::ImaginaryLiteralClass: 15941 case Expr::StringLiteralClass: 15942 case Expr::ArraySubscriptExprClass: 15943 case Expr::MatrixSubscriptExprClass: 15944 case Expr::OMPArraySectionExprClass: 15945 case Expr::OMPArrayShapingExprClass: 15946 case Expr::OMPIteratorExprClass: 15947 case Expr::MemberExprClass: 15948 case Expr::CompoundAssignOperatorClass: 15949 case Expr::CompoundLiteralExprClass: 15950 case Expr::ExtVectorElementExprClass: 15951 case Expr::DesignatedInitExprClass: 15952 case Expr::ArrayInitLoopExprClass: 15953 case Expr::ArrayInitIndexExprClass: 15954 case Expr::NoInitExprClass: 15955 case Expr::DesignatedInitUpdateExprClass: 15956 case Expr::ImplicitValueInitExprClass: 15957 case Expr::ParenListExprClass: 15958 case Expr::VAArgExprClass: 15959 case Expr::AddrLabelExprClass: 15960 case Expr::StmtExprClass: 15961 case Expr::CXXMemberCallExprClass: 15962 case Expr::CUDAKernelCallExprClass: 15963 case Expr::CXXAddrspaceCastExprClass: 15964 case Expr::CXXDynamicCastExprClass: 15965 case Expr::CXXTypeidExprClass: 15966 case Expr::CXXUuidofExprClass: 15967 case Expr::MSPropertyRefExprClass: 15968 case Expr::MSPropertySubscriptExprClass: 15969 case Expr::CXXNullPtrLiteralExprClass: 15970 case Expr::UserDefinedLiteralClass: 15971 case Expr::CXXThisExprClass: 15972 case Expr::CXXThrowExprClass: 15973 case Expr::CXXNewExprClass: 15974 case Expr::CXXDeleteExprClass: 15975 case Expr::CXXPseudoDestructorExprClass: 15976 case Expr::UnresolvedLookupExprClass: 15977 case Expr::TypoExprClass: 15978 case Expr::RecoveryExprClass: 15979 case Expr::DependentScopeDeclRefExprClass: 15980 case Expr::CXXConstructExprClass: 15981 case Expr::CXXInheritedCtorInitExprClass: 15982 case Expr::CXXStdInitializerListExprClass: 15983 case Expr::CXXBindTemporaryExprClass: 15984 case Expr::ExprWithCleanupsClass: 15985 case Expr::CXXTemporaryObjectExprClass: 15986 case Expr::CXXUnresolvedConstructExprClass: 15987 case Expr::CXXDependentScopeMemberExprClass: 15988 case Expr::UnresolvedMemberExprClass: 15989 case Expr::ObjCStringLiteralClass: 15990 case Expr::ObjCBoxedExprClass: 15991 case Expr::ObjCArrayLiteralClass: 15992 case Expr::ObjCDictionaryLiteralClass: 15993 case Expr::ObjCEncodeExprClass: 15994 case Expr::ObjCMessageExprClass: 15995 case Expr::ObjCSelectorExprClass: 15996 case Expr::ObjCProtocolExprClass: 15997 case Expr::ObjCIvarRefExprClass: 15998 case Expr::ObjCPropertyRefExprClass: 15999 case Expr::ObjCSubscriptRefExprClass: 16000 case Expr::ObjCIsaExprClass: 16001 case Expr::ObjCAvailabilityCheckExprClass: 16002 case Expr::ShuffleVectorExprClass: 16003 case Expr::ConvertVectorExprClass: 16004 case Expr::BlockExprClass: 16005 case Expr::NoStmtClass: 16006 case Expr::OpaqueValueExprClass: 16007 case Expr::PackExpansionExprClass: 16008 case Expr::SubstNonTypeTemplateParmPackExprClass: 16009 case Expr::FunctionParmPackExprClass: 16010 case Expr::AsTypeExprClass: 16011 case Expr::ObjCIndirectCopyRestoreExprClass: 16012 case Expr::MaterializeTemporaryExprClass: 16013 case Expr::PseudoObjectExprClass: 16014 case Expr::AtomicExprClass: 16015 case Expr::LambdaExprClass: 16016 case Expr::CXXFoldExprClass: 16017 case Expr::CoawaitExprClass: 16018 case Expr::DependentCoawaitExprClass: 16019 case Expr::CoyieldExprClass: 16020 case Expr::SYCLUniqueStableNameExprClass: 16021 case Expr::CXXParenListInitExprClass: 16022 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16023 16024 case Expr::InitListExprClass: { 16025 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 16026 // form "T x = { a };" is equivalent to "T x = a;". 16027 // Unless we're initializing a reference, T is a scalar as it is known to be 16028 // of integral or enumeration type. 16029 if (E->isPRValue()) 16030 if (cast<InitListExpr>(E)->getNumInits() == 1) 16031 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 16032 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16033 } 16034 16035 case Expr::SizeOfPackExprClass: 16036 case Expr::GNUNullExprClass: 16037 case Expr::SourceLocExprClass: 16038 return NoDiag(); 16039 16040 case Expr::SubstNonTypeTemplateParmExprClass: 16041 return 16042 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 16043 16044 case Expr::ConstantExprClass: 16045 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 16046 16047 case Expr::ParenExprClass: 16048 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 16049 case Expr::GenericSelectionExprClass: 16050 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 16051 case Expr::IntegerLiteralClass: 16052 case Expr::FixedPointLiteralClass: 16053 case Expr::CharacterLiteralClass: 16054 case Expr::ObjCBoolLiteralExprClass: 16055 case Expr::CXXBoolLiteralExprClass: 16056 case Expr::CXXScalarValueInitExprClass: 16057 case Expr::TypeTraitExprClass: 16058 case Expr::ConceptSpecializationExprClass: 16059 case Expr::RequiresExprClass: 16060 case Expr::ArrayTypeTraitExprClass: 16061 case Expr::ExpressionTraitExprClass: 16062 case Expr::CXXNoexceptExprClass: 16063 return NoDiag(); 16064 case Expr::CallExprClass: 16065 case Expr::CXXOperatorCallExprClass: { 16066 // C99 6.6/3 allows function calls within unevaluated subexpressions of 16067 // constant expressions, but they can never be ICEs because an ICE cannot 16068 // contain an operand of (pointer to) function type. 16069 const CallExpr *CE = cast<CallExpr>(E); 16070 if (CE->getBuiltinCallee()) 16071 return CheckEvalInICE(E, Ctx); 16072 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16073 } 16074 case Expr::CXXRewrittenBinaryOperatorClass: 16075 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 16076 Ctx); 16077 case Expr::DeclRefExprClass: { 16078 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 16079 if (isa<EnumConstantDecl>(D)) 16080 return NoDiag(); 16081 16082 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 16083 // integer variables in constant expressions: 16084 // 16085 // C++ 7.1.5.1p2 16086 // A variable of non-volatile const-qualified integral or enumeration 16087 // type initialized by an ICE can be used in ICEs. 16088 // 16089 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 16090 // that mode, use of reference variables should not be allowed. 16091 const VarDecl *VD = dyn_cast<VarDecl>(D); 16092 if (VD && VD->isUsableInConstantExpressions(Ctx) && 16093 !VD->getType()->isReferenceType()) 16094 return NoDiag(); 16095 16096 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16097 } 16098 case Expr::UnaryOperatorClass: { 16099 const UnaryOperator *Exp = cast<UnaryOperator>(E); 16100 switch (Exp->getOpcode()) { 16101 case UO_PostInc: 16102 case UO_PostDec: 16103 case UO_PreInc: 16104 case UO_PreDec: 16105 case UO_AddrOf: 16106 case UO_Deref: 16107 case UO_Coawait: 16108 // C99 6.6/3 allows increment and decrement within unevaluated 16109 // subexpressions of constant expressions, but they can never be ICEs 16110 // because an ICE cannot contain an lvalue operand. 16111 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16112 case UO_Extension: 16113 case UO_LNot: 16114 case UO_Plus: 16115 case UO_Minus: 16116 case UO_Not: 16117 case UO_Real: 16118 case UO_Imag: 16119 return CheckICE(Exp->getSubExpr(), Ctx); 16120 } 16121 llvm_unreachable("invalid unary operator class"); 16122 } 16123 case Expr::OffsetOfExprClass: { 16124 // Note that per C99, offsetof must be an ICE. And AFAIK, using 16125 // EvaluateAsRValue matches the proposed gcc behavior for cases like 16126 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 16127 // compliance: we should warn earlier for offsetof expressions with 16128 // array subscripts that aren't ICEs, and if the array subscripts 16129 // are ICEs, the value of the offsetof must be an integer constant. 16130 return CheckEvalInICE(E, Ctx); 16131 } 16132 case Expr::UnaryExprOrTypeTraitExprClass: { 16133 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 16134 if ((Exp->getKind() == UETT_SizeOf) && 16135 Exp->getTypeOfArgument()->isVariableArrayType()) 16136 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16137 return NoDiag(); 16138 } 16139 case Expr::BinaryOperatorClass: { 16140 const BinaryOperator *Exp = cast<BinaryOperator>(E); 16141 switch (Exp->getOpcode()) { 16142 case BO_PtrMemD: 16143 case BO_PtrMemI: 16144 case BO_Assign: 16145 case BO_MulAssign: 16146 case BO_DivAssign: 16147 case BO_RemAssign: 16148 case BO_AddAssign: 16149 case BO_SubAssign: 16150 case BO_ShlAssign: 16151 case BO_ShrAssign: 16152 case BO_AndAssign: 16153 case BO_XorAssign: 16154 case BO_OrAssign: 16155 // C99 6.6/3 allows assignments within unevaluated subexpressions of 16156 // constant expressions, but they can never be ICEs because an ICE cannot 16157 // contain an lvalue operand. 16158 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16159 16160 case BO_Mul: 16161 case BO_Div: 16162 case BO_Rem: 16163 case BO_Add: 16164 case BO_Sub: 16165 case BO_Shl: 16166 case BO_Shr: 16167 case BO_LT: 16168 case BO_GT: 16169 case BO_LE: 16170 case BO_GE: 16171 case BO_EQ: 16172 case BO_NE: 16173 case BO_And: 16174 case BO_Xor: 16175 case BO_Or: 16176 case BO_Comma: 16177 case BO_Cmp: { 16178 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 16179 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 16180 if (Exp->getOpcode() == BO_Div || 16181 Exp->getOpcode() == BO_Rem) { 16182 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 16183 // we don't evaluate one. 16184 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 16185 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 16186 if (REval == 0) 16187 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 16188 if (REval.isSigned() && REval.isAllOnes()) { 16189 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 16190 if (LEval.isMinSignedValue()) 16191 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 16192 } 16193 } 16194 } 16195 if (Exp->getOpcode() == BO_Comma) { 16196 if (Ctx.getLangOpts().C99) { 16197 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 16198 // if it isn't evaluated. 16199 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 16200 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 16201 } else { 16202 // In both C89 and C++, commas in ICEs are illegal. 16203 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16204 } 16205 } 16206 return Worst(LHSResult, RHSResult); 16207 } 16208 case BO_LAnd: 16209 case BO_LOr: { 16210 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 16211 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 16212 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 16213 // Rare case where the RHS has a comma "side-effect"; we need 16214 // to actually check the condition to see whether the side 16215 // with the comma is evaluated. 16216 if ((Exp->getOpcode() == BO_LAnd) != 16217 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 16218 return RHSResult; 16219 return NoDiag(); 16220 } 16221 16222 return Worst(LHSResult, RHSResult); 16223 } 16224 } 16225 llvm_unreachable("invalid binary operator kind"); 16226 } 16227 case Expr::ImplicitCastExprClass: 16228 case Expr::CStyleCastExprClass: 16229 case Expr::CXXFunctionalCastExprClass: 16230 case Expr::CXXStaticCastExprClass: 16231 case Expr::CXXReinterpretCastExprClass: 16232 case Expr::CXXConstCastExprClass: 16233 case Expr::ObjCBridgedCastExprClass: { 16234 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 16235 if (isa<ExplicitCastExpr>(E)) { 16236 if (const FloatingLiteral *FL 16237 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 16238 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 16239 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 16240 APSInt IgnoredVal(DestWidth, !DestSigned); 16241 bool Ignored; 16242 // If the value does not fit in the destination type, the behavior is 16243 // undefined, so we are not required to treat it as a constant 16244 // expression. 16245 if (FL->getValue().convertToInteger(IgnoredVal, 16246 llvm::APFloat::rmTowardZero, 16247 &Ignored) & APFloat::opInvalidOp) 16248 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16249 return NoDiag(); 16250 } 16251 } 16252 switch (cast<CastExpr>(E)->getCastKind()) { 16253 case CK_LValueToRValue: 16254 case CK_AtomicToNonAtomic: 16255 case CK_NonAtomicToAtomic: 16256 case CK_NoOp: 16257 case CK_IntegralToBoolean: 16258 case CK_IntegralCast: 16259 return CheckICE(SubExpr, Ctx); 16260 default: 16261 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16262 } 16263 } 16264 case Expr::BinaryConditionalOperatorClass: { 16265 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 16266 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 16267 if (CommonResult.Kind == IK_NotICE) return CommonResult; 16268 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 16269 if (FalseResult.Kind == IK_NotICE) return FalseResult; 16270 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 16271 if (FalseResult.Kind == IK_ICEIfUnevaluated && 16272 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 16273 return FalseResult; 16274 } 16275 case Expr::ConditionalOperatorClass: { 16276 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 16277 // If the condition (ignoring parens) is a __builtin_constant_p call, 16278 // then only the true side is actually considered in an integer constant 16279 // expression, and it is fully evaluated. This is an important GNU 16280 // extension. See GCC PR38377 for discussion. 16281 if (const CallExpr *CallCE 16282 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 16283 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 16284 return CheckEvalInICE(E, Ctx); 16285 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 16286 if (CondResult.Kind == IK_NotICE) 16287 return CondResult; 16288 16289 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 16290 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 16291 16292 if (TrueResult.Kind == IK_NotICE) 16293 return TrueResult; 16294 if (FalseResult.Kind == IK_NotICE) 16295 return FalseResult; 16296 if (CondResult.Kind == IK_ICEIfUnevaluated) 16297 return CondResult; 16298 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 16299 return NoDiag(); 16300 // Rare case where the diagnostics depend on which side is evaluated 16301 // Note that if we get here, CondResult is 0, and at least one of 16302 // TrueResult and FalseResult is non-zero. 16303 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 16304 return FalseResult; 16305 return TrueResult; 16306 } 16307 case Expr::CXXDefaultArgExprClass: 16308 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 16309 case Expr::CXXDefaultInitExprClass: 16310 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 16311 case Expr::ChooseExprClass: { 16312 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 16313 } 16314 case Expr::BuiltinBitCastExprClass: { 16315 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 16316 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16317 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 16318 } 16319 } 16320 16321 llvm_unreachable("Invalid StmtClass!"); 16322 } 16323 16324 /// Evaluate an expression as a C++11 integral constant expression. 16325 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 16326 const Expr *E, 16327 llvm::APSInt *Value, 16328 SourceLocation *Loc) { 16329 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16330 if (Loc) *Loc = E->getExprLoc(); 16331 return false; 16332 } 16333 16334 APValue Result; 16335 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 16336 return false; 16337 16338 if (!Result.isInt()) { 16339 if (Loc) *Loc = E->getExprLoc(); 16340 return false; 16341 } 16342 16343 if (Value) *Value = Result.getInt(); 16344 return true; 16345 } 16346 16347 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 16348 SourceLocation *Loc) const { 16349 assert(!isValueDependent() && 16350 "Expression evaluator can't be called on a dependent expression."); 16351 16352 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr"); 16353 16354 if (Ctx.getLangOpts().CPlusPlus11) 16355 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 16356 16357 ICEDiag D = CheckICE(this, Ctx); 16358 if (D.Kind != IK_ICE) { 16359 if (Loc) *Loc = D.Loc; 16360 return false; 16361 } 16362 return true; 16363 } 16364 16365 std::optional<llvm::APSInt> 16366 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const { 16367 if (isValueDependent()) { 16368 // Expression evaluator can't succeed on a dependent expression. 16369 return std::nullopt; 16370 } 16371 16372 APSInt Value; 16373 16374 if (Ctx.getLangOpts().CPlusPlus11) { 16375 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 16376 return Value; 16377 return std::nullopt; 16378 } 16379 16380 if (!isIntegerConstantExpr(Ctx, Loc)) 16381 return std::nullopt; 16382 16383 // The only possible side-effects here are due to UB discovered in the 16384 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 16385 // required to treat the expression as an ICE, so we produce the folded 16386 // value. 16387 EvalResult ExprResult; 16388 Expr::EvalStatus Status; 16389 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 16390 Info.InConstantContext = true; 16391 16392 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 16393 llvm_unreachable("ICE cannot be evaluated!"); 16394 16395 return ExprResult.Val.getInt(); 16396 } 16397 16398 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 16399 assert(!isValueDependent() && 16400 "Expression evaluator can't be called on a dependent expression."); 16401 16402 return CheckICE(this, Ctx).Kind == IK_ICE; 16403 } 16404 16405 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 16406 SourceLocation *Loc) const { 16407 assert(!isValueDependent() && 16408 "Expression evaluator can't be called on a dependent expression."); 16409 16410 // We support this checking in C++98 mode in order to diagnose compatibility 16411 // issues. 16412 assert(Ctx.getLangOpts().CPlusPlus); 16413 16414 // Build evaluation settings. 16415 Expr::EvalStatus Status; 16416 SmallVector<PartialDiagnosticAt, 8> Diags; 16417 Status.Diag = &Diags; 16418 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 16419 16420 APValue Scratch; 16421 bool IsConstExpr = 16422 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 16423 // FIXME: We don't produce a diagnostic for this, but the callers that 16424 // call us on arbitrary full-expressions should generally not care. 16425 Info.discardCleanups() && !Status.HasSideEffects; 16426 16427 if (!Diags.empty()) { 16428 IsConstExpr = false; 16429 if (Loc) *Loc = Diags[0].first; 16430 } else if (!IsConstExpr) { 16431 // FIXME: This shouldn't happen. 16432 if (Loc) *Loc = getExprLoc(); 16433 } 16434 16435 return IsConstExpr; 16436 } 16437 16438 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 16439 const FunctionDecl *Callee, 16440 ArrayRef<const Expr*> Args, 16441 const Expr *This) const { 16442 assert(!isValueDependent() && 16443 "Expression evaluator can't be called on a dependent expression."); 16444 16445 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] { 16446 std::string Name; 16447 llvm::raw_string_ostream OS(Name); 16448 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(), 16449 /*Qualified=*/true); 16450 return Name; 16451 }); 16452 16453 Expr::EvalStatus Status; 16454 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 16455 Info.InConstantContext = true; 16456 16457 LValue ThisVal; 16458 const LValue *ThisPtr = nullptr; 16459 if (This) { 16460 #ifndef NDEBUG 16461 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 16462 assert(MD && "Don't provide `this` for non-methods."); 16463 assert(MD->isImplicitObjectMemberFunction() && 16464 "Don't provide `this` for methods without an implicit object."); 16465 #endif 16466 if (!This->isValueDependent() && 16467 EvaluateObjectArgument(Info, This, ThisVal) && 16468 !Info.EvalStatus.HasSideEffects) 16469 ThisPtr = &ThisVal; 16470 16471 // Ignore any side-effects from a failed evaluation. This is safe because 16472 // they can't interfere with any other argument evaluation. 16473 Info.EvalStatus.HasSideEffects = false; 16474 } 16475 16476 CallRef Call = Info.CurrentCall->createCall(Callee); 16477 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 16478 I != E; ++I) { 16479 unsigned Idx = I - Args.begin(); 16480 if (Idx >= Callee->getNumParams()) 16481 break; 16482 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 16483 if ((*I)->isValueDependent() || 16484 !EvaluateCallArg(PVD, *I, Call, Info) || 16485 Info.EvalStatus.HasSideEffects) { 16486 // If evaluation fails, throw away the argument entirely. 16487 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 16488 *Slot = APValue(); 16489 } 16490 16491 // Ignore any side-effects from a failed evaluation. This is safe because 16492 // they can't interfere with any other argument evaluation. 16493 Info.EvalStatus.HasSideEffects = false; 16494 } 16495 16496 // Parameter cleanups happen in the caller and are not part of this 16497 // evaluation. 16498 Info.discardCleanups(); 16499 Info.EvalStatus.HasSideEffects = false; 16500 16501 // Build fake call to Callee. 16502 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This, 16503 Call); 16504 // FIXME: Missing ExprWithCleanups in enable_if conditions? 16505 FullExpressionRAII Scope(Info); 16506 return Evaluate(Value, Info, this) && Scope.destroy() && 16507 !Info.EvalStatus.HasSideEffects; 16508 } 16509 16510 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 16511 SmallVectorImpl< 16512 PartialDiagnosticAt> &Diags) { 16513 // FIXME: It would be useful to check constexpr function templates, but at the 16514 // moment the constant expression evaluator cannot cope with the non-rigorous 16515 // ASTs which we build for dependent expressions. 16516 if (FD->isDependentContext()) 16517 return true; 16518 16519 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] { 16520 std::string Name; 16521 llvm::raw_string_ostream OS(Name); 16522 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(), 16523 /*Qualified=*/true); 16524 return Name; 16525 }); 16526 16527 Expr::EvalStatus Status; 16528 Status.Diag = &Diags; 16529 16530 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 16531 Info.InConstantContext = true; 16532 Info.CheckingPotentialConstantExpression = true; 16533 16534 // The constexpr VM attempts to compile all methods to bytecode here. 16535 if (Info.EnableNewConstInterp) { 16536 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 16537 return Diags.empty(); 16538 } 16539 16540 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 16541 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 16542 16543 // Fabricate an arbitrary expression on the stack and pretend that it 16544 // is a temporary being used as the 'this' pointer. 16545 LValue This; 16546 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 16547 This.set({&VIE, Info.CurrentCall->Index}); 16548 16549 ArrayRef<const Expr*> Args; 16550 16551 APValue Scratch; 16552 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 16553 // Evaluate the call as a constant initializer, to allow the construction 16554 // of objects of non-literal types. 16555 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 16556 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 16557 } else { 16558 SourceLocation Loc = FD->getLocation(); 16559 HandleFunctionCall( 16560 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr, 16561 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch, 16562 /*ResultSlot=*/nullptr); 16563 } 16564 16565 return Diags.empty(); 16566 } 16567 16568 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 16569 const FunctionDecl *FD, 16570 SmallVectorImpl< 16571 PartialDiagnosticAt> &Diags) { 16572 assert(!E->isValueDependent() && 16573 "Expression evaluator can't be called on a dependent expression."); 16574 16575 Expr::EvalStatus Status; 16576 Status.Diag = &Diags; 16577 16578 EvalInfo Info(FD->getASTContext(), Status, 16579 EvalInfo::EM_ConstantExpressionUnevaluated); 16580 Info.InConstantContext = true; 16581 Info.CheckingPotentialConstantExpression = true; 16582 16583 // Fabricate a call stack frame to give the arguments a plausible cover story. 16584 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr, 16585 /*CallExpr=*/nullptr, CallRef()); 16586 16587 APValue ResultScratch; 16588 Evaluate(ResultScratch, Info, E); 16589 return Diags.empty(); 16590 } 16591 16592 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 16593 unsigned Type) const { 16594 if (!getType()->isPointerType()) 16595 return false; 16596 16597 Expr::EvalStatus Status; 16598 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 16599 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 16600 } 16601 16602 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 16603 EvalInfo &Info) { 16604 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 16605 return false; 16606 16607 LValue String; 16608 16609 if (!EvaluatePointer(E, String, Info)) 16610 return false; 16611 16612 QualType CharTy = E->getType()->getPointeeType(); 16613 16614 // Fast path: if it's a string literal, search the string value. 16615 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 16616 String.getLValueBase().dyn_cast<const Expr *>())) { 16617 StringRef Str = S->getBytes(); 16618 int64_t Off = String.Offset.getQuantity(); 16619 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 16620 S->getCharByteWidth() == 1 && 16621 // FIXME: Add fast-path for wchar_t too. 16622 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 16623 Str = Str.substr(Off); 16624 16625 StringRef::size_type Pos = Str.find(0); 16626 if (Pos != StringRef::npos) 16627 Str = Str.substr(0, Pos); 16628 16629 Result = Str.size(); 16630 return true; 16631 } 16632 16633 // Fall through to slow path. 16634 } 16635 16636 // Slow path: scan the bytes of the string looking for the terminating 0. 16637 for (uint64_t Strlen = 0; /**/; ++Strlen) { 16638 APValue Char; 16639 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 16640 !Char.isInt()) 16641 return false; 16642 if (!Char.getInt()) { 16643 Result = Strlen; 16644 return true; 16645 } 16646 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 16647 return false; 16648 } 16649 } 16650 16651 bool Expr::EvaluateCharRangeAsString(std::string &Result, 16652 const Expr *SizeExpression, 16653 const Expr *PtrExpression, ASTContext &Ctx, 16654 EvalResult &Status) const { 16655 LValue String; 16656 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 16657 Info.InConstantContext = true; 16658 16659 FullExpressionRAII Scope(Info); 16660 APSInt SizeValue; 16661 if (!::EvaluateInteger(SizeExpression, SizeValue, Info)) 16662 return false; 16663 16664 int64_t Size = SizeValue.getExtValue(); 16665 16666 if (!::EvaluatePointer(PtrExpression, String, Info)) 16667 return false; 16668 16669 QualType CharTy = PtrExpression->getType()->getPointeeType(); 16670 for (int64_t I = 0; I < Size; ++I) { 16671 APValue Char; 16672 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String, 16673 Char)) 16674 return false; 16675 16676 APSInt C = Char.getInt(); 16677 Result.push_back(static_cast<char>(C.getExtValue())); 16678 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1)) 16679 return false; 16680 } 16681 if (!Scope.destroy()) 16682 return false; 16683 16684 if (!CheckMemoryLeaks(Info)) 16685 return false; 16686 16687 return true; 16688 } 16689 16690 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 16691 Expr::EvalStatus Status; 16692 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 16693 return EvaluateBuiltinStrLen(this, Result, Info); 16694 } 16695