1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/DiagnosticSema.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "llvm/ADT/APFixedPoint.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/ADT/StringExtras.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/SaveAndRestore.h" 60 #include "llvm/Support/TimeProfiler.h" 61 #include "llvm/Support/raw_ostream.h" 62 #include <cstring> 63 #include <functional> 64 #include <optional> 65 66 #define DEBUG_TYPE "exprconstant" 67 68 using namespace clang; 69 using llvm::APFixedPoint; 70 using llvm::APInt; 71 using llvm::APSInt; 72 using llvm::APFloat; 73 using llvm::FixedPointSemantics; 74 75 namespace { 76 struct LValue; 77 class CallStackFrame; 78 class EvalInfo; 79 80 using SourceLocExprScopeGuard = 81 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 82 83 static QualType getType(APValue::LValueBase B) { 84 return B.getType(); 85 } 86 87 /// Get an LValue path entry, which is known to not be an array index, as a 88 /// field declaration. 89 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 90 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 91 } 92 /// Get an LValue path entry, which is known to not be an array index, as a 93 /// base class declaration. 94 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 95 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 96 } 97 /// Determine whether this LValue path entry for a base class names a virtual 98 /// base class. 99 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 100 return E.getAsBaseOrMember().getInt(); 101 } 102 103 /// Given an expression, determine the type used to store the result of 104 /// evaluating that expression. 105 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 106 if (E->isPRValue()) 107 return E->getType(); 108 return Ctx.getLValueReferenceType(E->getType()); 109 } 110 111 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 112 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 113 if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) 114 return DirectCallee->getAttr<AllocSizeAttr>(); 115 if (const Decl *IndirectCallee = CE->getCalleeDecl()) 116 return IndirectCallee->getAttr<AllocSizeAttr>(); 117 return nullptr; 118 } 119 120 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 121 /// This will look through a single cast. 122 /// 123 /// Returns null if we couldn't unwrap a function with alloc_size. 124 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 125 if (!E->getType()->isPointerType()) 126 return nullptr; 127 128 E = E->IgnoreParens(); 129 // If we're doing a variable assignment from e.g. malloc(N), there will 130 // probably be a cast of some kind. In exotic cases, we might also see a 131 // top-level ExprWithCleanups. Ignore them either way. 132 if (const auto *FE = dyn_cast<FullExpr>(E)) 133 E = FE->getSubExpr()->IgnoreParens(); 134 135 if (const auto *Cast = dyn_cast<CastExpr>(E)) 136 E = Cast->getSubExpr()->IgnoreParens(); 137 138 if (const auto *CE = dyn_cast<CallExpr>(E)) 139 return getAllocSizeAttr(CE) ? CE : nullptr; 140 return nullptr; 141 } 142 143 /// Determines whether or not the given Base contains a call to a function 144 /// with the alloc_size attribute. 145 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 146 const auto *E = Base.dyn_cast<const Expr *>(); 147 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 148 } 149 150 /// Determines whether the given kind of constant expression is only ever 151 /// used for name mangling. If so, it's permitted to reference things that we 152 /// can't generate code for (in particular, dllimported functions). 153 static bool isForManglingOnly(ConstantExprKind Kind) { 154 switch (Kind) { 155 case ConstantExprKind::Normal: 156 case ConstantExprKind::ClassTemplateArgument: 157 case ConstantExprKind::ImmediateInvocation: 158 // Note that non-type template arguments of class type are emitted as 159 // template parameter objects. 160 return false; 161 162 case ConstantExprKind::NonClassTemplateArgument: 163 return true; 164 } 165 llvm_unreachable("unknown ConstantExprKind"); 166 } 167 168 static bool isTemplateArgument(ConstantExprKind Kind) { 169 switch (Kind) { 170 case ConstantExprKind::Normal: 171 case ConstantExprKind::ImmediateInvocation: 172 return false; 173 174 case ConstantExprKind::ClassTemplateArgument: 175 case ConstantExprKind::NonClassTemplateArgument: 176 return true; 177 } 178 llvm_unreachable("unknown ConstantExprKind"); 179 } 180 181 /// The bound to claim that an array of unknown bound has. 182 /// The value in MostDerivedArraySize is undefined in this case. So, set it 183 /// to an arbitrary value that's likely to loudly break things if it's used. 184 static const uint64_t AssumedSizeForUnsizedArray = 185 std::numeric_limits<uint64_t>::max() / 2; 186 187 /// Determines if an LValue with the given LValueBase will have an unsized 188 /// array in its designator. 189 /// Find the path length and type of the most-derived subobject in the given 190 /// path, and find the size of the containing array, if any. 191 static unsigned 192 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 193 ArrayRef<APValue::LValuePathEntry> Path, 194 uint64_t &ArraySize, QualType &Type, bool &IsArray, 195 bool &FirstEntryIsUnsizedArray) { 196 // This only accepts LValueBases from APValues, and APValues don't support 197 // arrays that lack size info. 198 assert(!isBaseAnAllocSizeCall(Base) && 199 "Unsized arrays shouldn't appear here"); 200 unsigned MostDerivedLength = 0; 201 Type = getType(Base); 202 203 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 204 if (Type->isArrayType()) { 205 const ArrayType *AT = Ctx.getAsArrayType(Type); 206 Type = AT->getElementType(); 207 MostDerivedLength = I + 1; 208 IsArray = true; 209 210 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 211 ArraySize = CAT->getSize().getZExtValue(); 212 } else { 213 assert(I == 0 && "unexpected unsized array designator"); 214 FirstEntryIsUnsizedArray = true; 215 ArraySize = AssumedSizeForUnsizedArray; 216 } 217 } else if (Type->isAnyComplexType()) { 218 const ComplexType *CT = Type->castAs<ComplexType>(); 219 Type = CT->getElementType(); 220 ArraySize = 2; 221 MostDerivedLength = I + 1; 222 IsArray = true; 223 } else if (const FieldDecl *FD = getAsField(Path[I])) { 224 Type = FD->getType(); 225 ArraySize = 0; 226 MostDerivedLength = I + 1; 227 IsArray = false; 228 } else { 229 // Path[I] describes a base class. 230 ArraySize = 0; 231 IsArray = false; 232 } 233 } 234 return MostDerivedLength; 235 } 236 237 /// A path from a glvalue to a subobject of that glvalue. 238 struct SubobjectDesignator { 239 /// True if the subobject was named in a manner not supported by C++11. Such 240 /// lvalues can still be folded, but they are not core constant expressions 241 /// and we cannot perform lvalue-to-rvalue conversions on them. 242 unsigned Invalid : 1; 243 244 /// Is this a pointer one past the end of an object? 245 unsigned IsOnePastTheEnd : 1; 246 247 /// Indicator of whether the first entry is an unsized array. 248 unsigned FirstEntryIsAnUnsizedArray : 1; 249 250 /// Indicator of whether the most-derived object is an array element. 251 unsigned MostDerivedIsArrayElement : 1; 252 253 /// The length of the path to the most-derived object of which this is a 254 /// subobject. 255 unsigned MostDerivedPathLength : 28; 256 257 /// The size of the array of which the most-derived object is an element. 258 /// This will always be 0 if the most-derived object is not an array 259 /// element. 0 is not an indicator of whether or not the most-derived object 260 /// is an array, however, because 0-length arrays are allowed. 261 /// 262 /// If the current array is an unsized array, the value of this is 263 /// undefined. 264 uint64_t MostDerivedArraySize; 265 266 /// The type of the most derived object referred to by this address. 267 QualType MostDerivedType; 268 269 typedef APValue::LValuePathEntry PathEntry; 270 271 /// The entries on the path from the glvalue to the designated subobject. 272 SmallVector<PathEntry, 8> Entries; 273 274 SubobjectDesignator() : Invalid(true) {} 275 276 explicit SubobjectDesignator(QualType T) 277 : Invalid(false), IsOnePastTheEnd(false), 278 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 279 MostDerivedPathLength(0), MostDerivedArraySize(0), 280 MostDerivedType(T) {} 281 282 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 283 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 284 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 285 MostDerivedPathLength(0), MostDerivedArraySize(0) { 286 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 287 if (!Invalid) { 288 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 289 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 290 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 291 if (V.getLValueBase()) { 292 bool IsArray = false; 293 bool FirstIsUnsizedArray = false; 294 MostDerivedPathLength = findMostDerivedSubobject( 295 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 296 MostDerivedType, IsArray, FirstIsUnsizedArray); 297 MostDerivedIsArrayElement = IsArray; 298 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 299 } 300 } 301 } 302 303 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 304 unsigned NewLength) { 305 if (Invalid) 306 return; 307 308 assert(Base && "cannot truncate path for null pointer"); 309 assert(NewLength <= Entries.size() && "not a truncation"); 310 311 if (NewLength == Entries.size()) 312 return; 313 Entries.resize(NewLength); 314 315 bool IsArray = false; 316 bool FirstIsUnsizedArray = false; 317 MostDerivedPathLength = findMostDerivedSubobject( 318 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 319 FirstIsUnsizedArray); 320 MostDerivedIsArrayElement = IsArray; 321 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 322 } 323 324 void setInvalid() { 325 Invalid = true; 326 Entries.clear(); 327 } 328 329 /// Determine whether the most derived subobject is an array without a 330 /// known bound. 331 bool isMostDerivedAnUnsizedArray() const { 332 assert(!Invalid && "Calling this makes no sense on invalid designators"); 333 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 334 } 335 336 /// Determine what the most derived array's size is. Results in an assertion 337 /// failure if the most derived array lacks a size. 338 uint64_t getMostDerivedArraySize() const { 339 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 340 return MostDerivedArraySize; 341 } 342 343 /// Determine whether this is a one-past-the-end pointer. 344 bool isOnePastTheEnd() const { 345 assert(!Invalid); 346 if (IsOnePastTheEnd) 347 return true; 348 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 349 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 350 MostDerivedArraySize) 351 return true; 352 return false; 353 } 354 355 /// Get the range of valid index adjustments in the form 356 /// {maximum value that can be subtracted from this pointer, 357 /// maximum value that can be added to this pointer} 358 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 359 if (Invalid || isMostDerivedAnUnsizedArray()) 360 return {0, 0}; 361 362 // [expr.add]p4: For the purposes of these operators, a pointer to a 363 // nonarray object behaves the same as a pointer to the first element of 364 // an array of length one with the type of the object as its element type. 365 bool IsArray = MostDerivedPathLength == Entries.size() && 366 MostDerivedIsArrayElement; 367 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 368 : (uint64_t)IsOnePastTheEnd; 369 uint64_t ArraySize = 370 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 371 return {ArrayIndex, ArraySize - ArrayIndex}; 372 } 373 374 /// Check that this refers to a valid subobject. 375 bool isValidSubobject() const { 376 if (Invalid) 377 return false; 378 return !isOnePastTheEnd(); 379 } 380 /// Check that this refers to a valid subobject, and if not, produce a 381 /// relevant diagnostic and set the designator as invalid. 382 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 383 384 /// Get the type of the designated object. 385 QualType getType(ASTContext &Ctx) const { 386 assert(!Invalid && "invalid designator has no subobject type"); 387 return MostDerivedPathLength == Entries.size() 388 ? MostDerivedType 389 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 390 } 391 392 /// Update this designator to refer to the first element within this array. 393 void addArrayUnchecked(const ConstantArrayType *CAT) { 394 Entries.push_back(PathEntry::ArrayIndex(0)); 395 396 // This is a most-derived object. 397 MostDerivedType = CAT->getElementType(); 398 MostDerivedIsArrayElement = true; 399 MostDerivedArraySize = CAT->getSize().getZExtValue(); 400 MostDerivedPathLength = Entries.size(); 401 } 402 /// Update this designator to refer to the first element within the array of 403 /// elements of type T. This is an array of unknown size. 404 void addUnsizedArrayUnchecked(QualType ElemTy) { 405 Entries.push_back(PathEntry::ArrayIndex(0)); 406 407 MostDerivedType = ElemTy; 408 MostDerivedIsArrayElement = true; 409 // The value in MostDerivedArraySize is undefined in this case. So, set it 410 // to an arbitrary value that's likely to loudly break things if it's 411 // used. 412 MostDerivedArraySize = AssumedSizeForUnsizedArray; 413 MostDerivedPathLength = Entries.size(); 414 } 415 /// Update this designator to refer to the given base or member of this 416 /// object. 417 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 418 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 419 420 // If this isn't a base class, it's a new most-derived object. 421 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 422 MostDerivedType = FD->getType(); 423 MostDerivedIsArrayElement = false; 424 MostDerivedArraySize = 0; 425 MostDerivedPathLength = Entries.size(); 426 } 427 } 428 /// Update this designator to refer to the given complex component. 429 void addComplexUnchecked(QualType EltTy, bool Imag) { 430 Entries.push_back(PathEntry::ArrayIndex(Imag)); 431 432 // This is technically a most-derived object, though in practice this 433 // is unlikely to matter. 434 MostDerivedType = EltTy; 435 MostDerivedIsArrayElement = true; 436 MostDerivedArraySize = 2; 437 MostDerivedPathLength = Entries.size(); 438 } 439 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 440 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 441 const APSInt &N); 442 /// Add N to the address of this subobject. 443 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 444 if (Invalid || !N) return; 445 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 446 if (isMostDerivedAnUnsizedArray()) { 447 diagnoseUnsizedArrayPointerArithmetic(Info, E); 448 // Can't verify -- trust that the user is doing the right thing (or if 449 // not, trust that the caller will catch the bad behavior). 450 // FIXME: Should we reject if this overflows, at least? 451 Entries.back() = PathEntry::ArrayIndex( 452 Entries.back().getAsArrayIndex() + TruncatedN); 453 return; 454 } 455 456 // [expr.add]p4: For the purposes of these operators, a pointer to a 457 // nonarray object behaves the same as a pointer to the first element of 458 // an array of length one with the type of the object as its element type. 459 bool IsArray = MostDerivedPathLength == Entries.size() && 460 MostDerivedIsArrayElement; 461 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 462 : (uint64_t)IsOnePastTheEnd; 463 uint64_t ArraySize = 464 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 465 466 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 467 // Calculate the actual index in a wide enough type, so we can include 468 // it in the note. 469 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 470 (llvm::APInt&)N += ArrayIndex; 471 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 472 diagnosePointerArithmetic(Info, E, N); 473 setInvalid(); 474 return; 475 } 476 477 ArrayIndex += TruncatedN; 478 assert(ArrayIndex <= ArraySize && 479 "bounds check succeeded for out-of-bounds index"); 480 481 if (IsArray) 482 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 483 else 484 IsOnePastTheEnd = (ArrayIndex != 0); 485 } 486 }; 487 488 /// A scope at the end of which an object can need to be destroyed. 489 enum class ScopeKind { 490 Block, 491 FullExpression, 492 Call 493 }; 494 495 /// A reference to a particular call and its arguments. 496 struct CallRef { 497 CallRef() : OrigCallee(), CallIndex(0), Version() {} 498 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 499 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 500 501 explicit operator bool() const { return OrigCallee; } 502 503 /// Get the parameter that the caller initialized, corresponding to the 504 /// given parameter in the callee. 505 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 506 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 507 : PVD; 508 } 509 510 /// The callee at the point where the arguments were evaluated. This might 511 /// be different from the actual callee (a different redeclaration, or a 512 /// virtual override), but this function's parameters are the ones that 513 /// appear in the parameter map. 514 const FunctionDecl *OrigCallee; 515 /// The call index of the frame that holds the argument values. 516 unsigned CallIndex; 517 /// The version of the parameters corresponding to this call. 518 unsigned Version; 519 }; 520 521 /// A stack frame in the constexpr call stack. 522 class CallStackFrame : public interp::Frame { 523 public: 524 EvalInfo &Info; 525 526 /// Parent - The caller of this stack frame. 527 CallStackFrame *Caller; 528 529 /// Callee - The function which was called. 530 const FunctionDecl *Callee; 531 532 /// This - The binding for the this pointer in this call, if any. 533 const LValue *This; 534 535 /// CallExpr - The syntactical structure of member function calls 536 const Expr *CallExpr; 537 538 /// Information on how to find the arguments to this call. Our arguments 539 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 540 /// key and this value as the version. 541 CallRef Arguments; 542 543 /// Source location information about the default argument or default 544 /// initializer expression we're evaluating, if any. 545 CurrentSourceLocExprScope CurSourceLocExprScope; 546 547 // Note that we intentionally use std::map here so that references to 548 // values are stable. 549 typedef std::pair<const void *, unsigned> MapKeyTy; 550 typedef std::map<MapKeyTy, APValue> MapTy; 551 /// Temporaries - Temporary lvalues materialized within this stack frame. 552 MapTy Temporaries; 553 554 /// CallLoc - The location of the call expression for this call. 555 SourceLocation CallLoc; 556 557 /// Index - The call index of this call. 558 unsigned Index; 559 560 /// The stack of integers for tracking version numbers for temporaries. 561 SmallVector<unsigned, 2> TempVersionStack = {1}; 562 unsigned CurTempVersion = TempVersionStack.back(); 563 564 unsigned getTempVersion() const { return TempVersionStack.back(); } 565 566 void pushTempVersion() { 567 TempVersionStack.push_back(++CurTempVersion); 568 } 569 570 void popTempVersion() { 571 TempVersionStack.pop_back(); 572 } 573 574 CallRef createCall(const FunctionDecl *Callee) { 575 return {Callee, Index, ++CurTempVersion}; 576 } 577 578 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 579 // on the overall stack usage of deeply-recursing constexpr evaluations. 580 // (We should cache this map rather than recomputing it repeatedly.) 581 // But let's try this and see how it goes; we can look into caching the map 582 // as a later change. 583 584 /// LambdaCaptureFields - Mapping from captured variables/this to 585 /// corresponding data members in the closure class. 586 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields; 587 FieldDecl *LambdaThisCaptureField = nullptr; 588 589 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 590 const FunctionDecl *Callee, const LValue *This, 591 const Expr *CallExpr, CallRef Arguments); 592 ~CallStackFrame(); 593 594 // Return the temporary for Key whose version number is Version. 595 APValue *getTemporary(const void *Key, unsigned Version) { 596 MapKeyTy KV(Key, Version); 597 auto LB = Temporaries.lower_bound(KV); 598 if (LB != Temporaries.end() && LB->first == KV) 599 return &LB->second; 600 return nullptr; 601 } 602 603 // Return the current temporary for Key in the map. 604 APValue *getCurrentTemporary(const void *Key) { 605 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 606 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 607 return &std::prev(UB)->second; 608 return nullptr; 609 } 610 611 // Return the version number of the current temporary for Key. 612 unsigned getCurrentTemporaryVersion(const void *Key) const { 613 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 614 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 615 return std::prev(UB)->first.second; 616 return 0; 617 } 618 619 /// Allocate storage for an object of type T in this stack frame. 620 /// Populates LV with a handle to the created object. Key identifies 621 /// the temporary within the stack frame, and must not be reused without 622 /// bumping the temporary version number. 623 template<typename KeyT> 624 APValue &createTemporary(const KeyT *Key, QualType T, 625 ScopeKind Scope, LValue &LV); 626 627 /// Allocate storage for a parameter of a function call made in this frame. 628 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 629 630 void describe(llvm::raw_ostream &OS) const override; 631 632 Frame *getCaller() const override { return Caller; } 633 SourceLocation getCallLocation() const override { return CallLoc; } 634 const FunctionDecl *getCallee() const override { return Callee; } 635 636 bool isStdFunction() const { 637 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 638 if (DC->isStdNamespace()) 639 return true; 640 return false; 641 } 642 643 private: 644 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 645 ScopeKind Scope); 646 }; 647 648 /// Temporarily override 'this'. 649 class ThisOverrideRAII { 650 public: 651 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 652 : Frame(Frame), OldThis(Frame.This) { 653 if (Enable) 654 Frame.This = NewThis; 655 } 656 ~ThisOverrideRAII() { 657 Frame.This = OldThis; 658 } 659 private: 660 CallStackFrame &Frame; 661 const LValue *OldThis; 662 }; 663 664 // A shorthand time trace scope struct, prints source range, for example 665 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}} 666 class ExprTimeTraceScope { 667 public: 668 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name) 669 : TimeScope(Name, [E, &Ctx] { 670 return E->getSourceRange().printToString(Ctx.getSourceManager()); 671 }) {} 672 673 private: 674 llvm::TimeTraceScope TimeScope; 675 }; 676 } 677 678 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 679 const LValue &This, QualType ThisType); 680 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 681 APValue::LValueBase LVBase, APValue &Value, 682 QualType T); 683 684 namespace { 685 /// A cleanup, and a flag indicating whether it is lifetime-extended. 686 class Cleanup { 687 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 688 APValue::LValueBase Base; 689 QualType T; 690 691 public: 692 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 693 ScopeKind Scope) 694 : Value(Val, Scope), Base(Base), T(T) {} 695 696 /// Determine whether this cleanup should be performed at the end of the 697 /// given kind of scope. 698 bool isDestroyedAtEndOf(ScopeKind K) const { 699 return (int)Value.getInt() >= (int)K; 700 } 701 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 702 if (RunDestructors) { 703 SourceLocation Loc; 704 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 705 Loc = VD->getLocation(); 706 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 707 Loc = E->getExprLoc(); 708 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 709 } 710 *Value.getPointer() = APValue(); 711 return true; 712 } 713 714 bool hasSideEffect() { 715 return T.isDestructedType(); 716 } 717 }; 718 719 /// A reference to an object whose construction we are currently evaluating. 720 struct ObjectUnderConstruction { 721 APValue::LValueBase Base; 722 ArrayRef<APValue::LValuePathEntry> Path; 723 friend bool operator==(const ObjectUnderConstruction &LHS, 724 const ObjectUnderConstruction &RHS) { 725 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 726 } 727 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 728 return llvm::hash_combine(Obj.Base, Obj.Path); 729 } 730 }; 731 enum class ConstructionPhase { 732 None, 733 Bases, 734 AfterBases, 735 AfterFields, 736 Destroying, 737 DestroyingBases 738 }; 739 } 740 741 namespace llvm { 742 template<> struct DenseMapInfo<ObjectUnderConstruction> { 743 using Base = DenseMapInfo<APValue::LValueBase>; 744 static ObjectUnderConstruction getEmptyKey() { 745 return {Base::getEmptyKey(), {}}; } 746 static ObjectUnderConstruction getTombstoneKey() { 747 return {Base::getTombstoneKey(), {}}; 748 } 749 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 750 return hash_value(Object); 751 } 752 static bool isEqual(const ObjectUnderConstruction &LHS, 753 const ObjectUnderConstruction &RHS) { 754 return LHS == RHS; 755 } 756 }; 757 } 758 759 namespace { 760 /// A dynamically-allocated heap object. 761 struct DynAlloc { 762 /// The value of this heap-allocated object. 763 APValue Value; 764 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 765 /// or a CallExpr (the latter is for direct calls to operator new inside 766 /// std::allocator<T>::allocate). 767 const Expr *AllocExpr = nullptr; 768 769 enum Kind { 770 New, 771 ArrayNew, 772 StdAllocator 773 }; 774 775 /// Get the kind of the allocation. This must match between allocation 776 /// and deallocation. 777 Kind getKind() const { 778 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 779 return NE->isArray() ? ArrayNew : New; 780 assert(isa<CallExpr>(AllocExpr)); 781 return StdAllocator; 782 } 783 }; 784 785 struct DynAllocOrder { 786 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 787 return L.getIndex() < R.getIndex(); 788 } 789 }; 790 791 /// EvalInfo - This is a private struct used by the evaluator to capture 792 /// information about a subexpression as it is folded. It retains information 793 /// about the AST context, but also maintains information about the folded 794 /// expression. 795 /// 796 /// If an expression could be evaluated, it is still possible it is not a C 797 /// "integer constant expression" or constant expression. If not, this struct 798 /// captures information about how and why not. 799 /// 800 /// One bit of information passed *into* the request for constant folding 801 /// indicates whether the subexpression is "evaluated" or not according to C 802 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 803 /// evaluate the expression regardless of what the RHS is, but C only allows 804 /// certain things in certain situations. 805 class EvalInfo : public interp::State { 806 public: 807 ASTContext &Ctx; 808 809 /// EvalStatus - Contains information about the evaluation. 810 Expr::EvalStatus &EvalStatus; 811 812 /// CurrentCall - The top of the constexpr call stack. 813 CallStackFrame *CurrentCall; 814 815 /// CallStackDepth - The number of calls in the call stack right now. 816 unsigned CallStackDepth; 817 818 /// NextCallIndex - The next call index to assign. 819 unsigned NextCallIndex; 820 821 /// StepsLeft - The remaining number of evaluation steps we're permitted 822 /// to perform. This is essentially a limit for the number of statements 823 /// we will evaluate. 824 unsigned StepsLeft; 825 826 /// Enable the experimental new constant interpreter. If an expression is 827 /// not supported by the interpreter, an error is triggered. 828 bool EnableNewConstInterp; 829 830 /// BottomFrame - The frame in which evaluation started. This must be 831 /// initialized after CurrentCall and CallStackDepth. 832 CallStackFrame BottomFrame; 833 834 /// A stack of values whose lifetimes end at the end of some surrounding 835 /// evaluation frame. 836 llvm::SmallVector<Cleanup, 16> CleanupStack; 837 838 /// EvaluatingDecl - This is the declaration whose initializer is being 839 /// evaluated, if any. 840 APValue::LValueBase EvaluatingDecl; 841 842 enum class EvaluatingDeclKind { 843 None, 844 /// We're evaluating the construction of EvaluatingDecl. 845 Ctor, 846 /// We're evaluating the destruction of EvaluatingDecl. 847 Dtor, 848 }; 849 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 850 851 /// EvaluatingDeclValue - This is the value being constructed for the 852 /// declaration whose initializer is being evaluated, if any. 853 APValue *EvaluatingDeclValue; 854 855 /// Set of objects that are currently being constructed. 856 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 857 ObjectsUnderConstruction; 858 859 /// Current heap allocations, along with the location where each was 860 /// allocated. We use std::map here because we need stable addresses 861 /// for the stored APValues. 862 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 863 864 /// The number of heap allocations performed so far in this evaluation. 865 unsigned NumHeapAllocs = 0; 866 867 struct EvaluatingConstructorRAII { 868 EvalInfo &EI; 869 ObjectUnderConstruction Object; 870 bool DidInsert; 871 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 872 bool HasBases) 873 : EI(EI), Object(Object) { 874 DidInsert = 875 EI.ObjectsUnderConstruction 876 .insert({Object, HasBases ? ConstructionPhase::Bases 877 : ConstructionPhase::AfterBases}) 878 .second; 879 } 880 void finishedConstructingBases() { 881 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 882 } 883 void finishedConstructingFields() { 884 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 885 } 886 ~EvaluatingConstructorRAII() { 887 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 888 } 889 }; 890 891 struct EvaluatingDestructorRAII { 892 EvalInfo &EI; 893 ObjectUnderConstruction Object; 894 bool DidInsert; 895 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 896 : EI(EI), Object(Object) { 897 DidInsert = EI.ObjectsUnderConstruction 898 .insert({Object, ConstructionPhase::Destroying}) 899 .second; 900 } 901 void startedDestroyingBases() { 902 EI.ObjectsUnderConstruction[Object] = 903 ConstructionPhase::DestroyingBases; 904 } 905 ~EvaluatingDestructorRAII() { 906 if (DidInsert) 907 EI.ObjectsUnderConstruction.erase(Object); 908 } 909 }; 910 911 ConstructionPhase 912 isEvaluatingCtorDtor(APValue::LValueBase Base, 913 ArrayRef<APValue::LValuePathEntry> Path) { 914 return ObjectsUnderConstruction.lookup({Base, Path}); 915 } 916 917 /// If we're currently speculatively evaluating, the outermost call stack 918 /// depth at which we can mutate state, otherwise 0. 919 unsigned SpeculativeEvaluationDepth = 0; 920 921 /// The current array initialization index, if we're performing array 922 /// initialization. 923 uint64_t ArrayInitIndex = -1; 924 925 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 926 /// notes attached to it will also be stored, otherwise they will not be. 927 bool HasActiveDiagnostic; 928 929 /// Have we emitted a diagnostic explaining why we couldn't constant 930 /// fold (not just why it's not strictly a constant expression)? 931 bool HasFoldFailureDiagnostic; 932 933 /// Whether we're checking that an expression is a potential constant 934 /// expression. If so, do not fail on constructs that could become constant 935 /// later on (such as a use of an undefined global). 936 bool CheckingPotentialConstantExpression = false; 937 938 /// Whether we're checking for an expression that has undefined behavior. 939 /// If so, we will produce warnings if we encounter an operation that is 940 /// always undefined. 941 /// 942 /// Note that we still need to evaluate the expression normally when this 943 /// is set; this is used when evaluating ICEs in C. 944 bool CheckingForUndefinedBehavior = false; 945 946 enum EvaluationMode { 947 /// Evaluate as a constant expression. Stop if we find that the expression 948 /// is not a constant expression. 949 EM_ConstantExpression, 950 951 /// Evaluate as a constant expression. Stop if we find that the expression 952 /// is not a constant expression. Some expressions can be retried in the 953 /// optimizer if we don't constant fold them here, but in an unevaluated 954 /// context we try to fold them immediately since the optimizer never 955 /// gets a chance to look at it. 956 EM_ConstantExpressionUnevaluated, 957 958 /// Fold the expression to a constant. Stop if we hit a side-effect that 959 /// we can't model. 960 EM_ConstantFold, 961 962 /// Evaluate in any way we know how. Don't worry about side-effects that 963 /// can't be modeled. 964 EM_IgnoreSideEffects, 965 } EvalMode; 966 967 /// Are we checking whether the expression is a potential constant 968 /// expression? 969 bool checkingPotentialConstantExpression() const override { 970 return CheckingPotentialConstantExpression; 971 } 972 973 /// Are we checking an expression for overflow? 974 // FIXME: We should check for any kind of undefined or suspicious behavior 975 // in such constructs, not just overflow. 976 bool checkingForUndefinedBehavior() const override { 977 return CheckingForUndefinedBehavior; 978 } 979 980 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 981 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 982 CallStackDepth(0), NextCallIndex(1), 983 StepsLeft(C.getLangOpts().ConstexprStepLimit), 984 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 985 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr, 986 /*This=*/nullptr, 987 /*CallExpr=*/nullptr, CallRef()), 988 EvaluatingDecl((const ValueDecl *)nullptr), 989 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 990 HasFoldFailureDiagnostic(false), EvalMode(Mode) {} 991 992 ~EvalInfo() { 993 discardCleanups(); 994 } 995 996 ASTContext &getCtx() const override { return Ctx; } 997 998 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 999 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 1000 EvaluatingDecl = Base; 1001 IsEvaluatingDecl = EDK; 1002 EvaluatingDeclValue = &Value; 1003 } 1004 1005 bool CheckCallLimit(SourceLocation Loc) { 1006 // Don't perform any constexpr calls (other than the call we're checking) 1007 // when checking a potential constant expression. 1008 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 1009 return false; 1010 if (NextCallIndex == 0) { 1011 // NextCallIndex has wrapped around. 1012 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1013 return false; 1014 } 1015 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1016 return true; 1017 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1018 << getLangOpts().ConstexprCallDepth; 1019 return false; 1020 } 1021 1022 std::pair<CallStackFrame *, unsigned> 1023 getCallFrameAndDepth(unsigned CallIndex) { 1024 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1025 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1026 // be null in this loop. 1027 unsigned Depth = CallStackDepth; 1028 CallStackFrame *Frame = CurrentCall; 1029 while (Frame->Index > CallIndex) { 1030 Frame = Frame->Caller; 1031 --Depth; 1032 } 1033 if (Frame->Index == CallIndex) 1034 return {Frame, Depth}; 1035 return {nullptr, 0}; 1036 } 1037 1038 bool nextStep(const Stmt *S) { 1039 if (!StepsLeft) { 1040 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1041 return false; 1042 } 1043 --StepsLeft; 1044 return true; 1045 } 1046 1047 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1048 1049 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) { 1050 std::optional<DynAlloc *> Result; 1051 auto It = HeapAllocs.find(DA); 1052 if (It != HeapAllocs.end()) 1053 Result = &It->second; 1054 return Result; 1055 } 1056 1057 /// Get the allocated storage for the given parameter of the given call. 1058 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1059 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1060 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1061 : nullptr; 1062 } 1063 1064 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1065 struct StdAllocatorCaller { 1066 unsigned FrameIndex; 1067 QualType ElemType; 1068 explicit operator bool() const { return FrameIndex != 0; }; 1069 }; 1070 1071 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1072 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1073 Call = Call->Caller) { 1074 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1075 if (!MD) 1076 continue; 1077 const IdentifierInfo *FnII = MD->getIdentifier(); 1078 if (!FnII || !FnII->isStr(FnName)) 1079 continue; 1080 1081 const auto *CTSD = 1082 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1083 if (!CTSD) 1084 continue; 1085 1086 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1087 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1088 if (CTSD->isInStdNamespace() && ClassII && 1089 ClassII->isStr("allocator") && TAL.size() >= 1 && 1090 TAL[0].getKind() == TemplateArgument::Type) 1091 return {Call->Index, TAL[0].getAsType()}; 1092 } 1093 1094 return {}; 1095 } 1096 1097 void performLifetimeExtension() { 1098 // Disable the cleanups for lifetime-extended temporaries. 1099 llvm::erase_if(CleanupStack, [](Cleanup &C) { 1100 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); 1101 }); 1102 } 1103 1104 /// Throw away any remaining cleanups at the end of evaluation. If any 1105 /// cleanups would have had a side-effect, note that as an unmodeled 1106 /// side-effect and return false. Otherwise, return true. 1107 bool discardCleanups() { 1108 for (Cleanup &C : CleanupStack) { 1109 if (C.hasSideEffect() && !noteSideEffect()) { 1110 CleanupStack.clear(); 1111 return false; 1112 } 1113 } 1114 CleanupStack.clear(); 1115 return true; 1116 } 1117 1118 private: 1119 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1120 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1121 1122 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1123 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1124 1125 void setFoldFailureDiagnostic(bool Flag) override { 1126 HasFoldFailureDiagnostic = Flag; 1127 } 1128 1129 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1130 1131 // If we have a prior diagnostic, it will be noting that the expression 1132 // isn't a constant expression. This diagnostic is more important, 1133 // unless we require this evaluation to produce a constant expression. 1134 // 1135 // FIXME: We might want to show both diagnostics to the user in 1136 // EM_ConstantFold mode. 1137 bool hasPriorDiagnostic() override { 1138 if (!EvalStatus.Diag->empty()) { 1139 switch (EvalMode) { 1140 case EM_ConstantFold: 1141 case EM_IgnoreSideEffects: 1142 if (!HasFoldFailureDiagnostic) 1143 break; 1144 // We've already failed to fold something. Keep that diagnostic. 1145 [[fallthrough]]; 1146 case EM_ConstantExpression: 1147 case EM_ConstantExpressionUnevaluated: 1148 setActiveDiagnostic(false); 1149 return true; 1150 } 1151 } 1152 return false; 1153 } 1154 1155 unsigned getCallStackDepth() override { return CallStackDepth; } 1156 1157 public: 1158 /// Should we continue evaluation after encountering a side-effect that we 1159 /// couldn't model? 1160 bool keepEvaluatingAfterSideEffect() { 1161 switch (EvalMode) { 1162 case EM_IgnoreSideEffects: 1163 return true; 1164 1165 case EM_ConstantExpression: 1166 case EM_ConstantExpressionUnevaluated: 1167 case EM_ConstantFold: 1168 // By default, assume any side effect might be valid in some other 1169 // evaluation of this expression from a different context. 1170 return checkingPotentialConstantExpression() || 1171 checkingForUndefinedBehavior(); 1172 } 1173 llvm_unreachable("Missed EvalMode case"); 1174 } 1175 1176 /// Note that we have had a side-effect, and determine whether we should 1177 /// keep evaluating. 1178 bool noteSideEffect() { 1179 EvalStatus.HasSideEffects = true; 1180 return keepEvaluatingAfterSideEffect(); 1181 } 1182 1183 /// Should we continue evaluation after encountering undefined behavior? 1184 bool keepEvaluatingAfterUndefinedBehavior() { 1185 switch (EvalMode) { 1186 case EM_IgnoreSideEffects: 1187 case EM_ConstantFold: 1188 return true; 1189 1190 case EM_ConstantExpression: 1191 case EM_ConstantExpressionUnevaluated: 1192 return checkingForUndefinedBehavior(); 1193 } 1194 llvm_unreachable("Missed EvalMode case"); 1195 } 1196 1197 /// Note that we hit something that was technically undefined behavior, but 1198 /// that we can evaluate past it (such as signed overflow or floating-point 1199 /// division by zero.) 1200 bool noteUndefinedBehavior() override { 1201 EvalStatus.HasUndefinedBehavior = true; 1202 return keepEvaluatingAfterUndefinedBehavior(); 1203 } 1204 1205 /// Should we continue evaluation as much as possible after encountering a 1206 /// construct which can't be reduced to a value? 1207 bool keepEvaluatingAfterFailure() const override { 1208 if (!StepsLeft) 1209 return false; 1210 1211 switch (EvalMode) { 1212 case EM_ConstantExpression: 1213 case EM_ConstantExpressionUnevaluated: 1214 case EM_ConstantFold: 1215 case EM_IgnoreSideEffects: 1216 return checkingPotentialConstantExpression() || 1217 checkingForUndefinedBehavior(); 1218 } 1219 llvm_unreachable("Missed EvalMode case"); 1220 } 1221 1222 /// Notes that we failed to evaluate an expression that other expressions 1223 /// directly depend on, and determine if we should keep evaluating. This 1224 /// should only be called if we actually intend to keep evaluating. 1225 /// 1226 /// Call noteSideEffect() instead if we may be able to ignore the value that 1227 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1228 /// 1229 /// (Foo(), 1) // use noteSideEffect 1230 /// (Foo() || true) // use noteSideEffect 1231 /// Foo() + 1 // use noteFailure 1232 [[nodiscard]] bool noteFailure() { 1233 // Failure when evaluating some expression often means there is some 1234 // subexpression whose evaluation was skipped. Therefore, (because we 1235 // don't track whether we skipped an expression when unwinding after an 1236 // evaluation failure) every evaluation failure that bubbles up from a 1237 // subexpression implies that a side-effect has potentially happened. We 1238 // skip setting the HasSideEffects flag to true until we decide to 1239 // continue evaluating after that point, which happens here. 1240 bool KeepGoing = keepEvaluatingAfterFailure(); 1241 EvalStatus.HasSideEffects |= KeepGoing; 1242 return KeepGoing; 1243 } 1244 1245 class ArrayInitLoopIndex { 1246 EvalInfo &Info; 1247 uint64_t OuterIndex; 1248 1249 public: 1250 ArrayInitLoopIndex(EvalInfo &Info) 1251 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1252 Info.ArrayInitIndex = 0; 1253 } 1254 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1255 1256 operator uint64_t&() { return Info.ArrayInitIndex; } 1257 }; 1258 }; 1259 1260 /// Object used to treat all foldable expressions as constant expressions. 1261 struct FoldConstant { 1262 EvalInfo &Info; 1263 bool Enabled; 1264 bool HadNoPriorDiags; 1265 EvalInfo::EvaluationMode OldMode; 1266 1267 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1268 : Info(Info), 1269 Enabled(Enabled), 1270 HadNoPriorDiags(Info.EvalStatus.Diag && 1271 Info.EvalStatus.Diag->empty() && 1272 !Info.EvalStatus.HasSideEffects), 1273 OldMode(Info.EvalMode) { 1274 if (Enabled) 1275 Info.EvalMode = EvalInfo::EM_ConstantFold; 1276 } 1277 void keepDiagnostics() { Enabled = false; } 1278 ~FoldConstant() { 1279 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1280 !Info.EvalStatus.HasSideEffects) 1281 Info.EvalStatus.Diag->clear(); 1282 Info.EvalMode = OldMode; 1283 } 1284 }; 1285 1286 /// RAII object used to set the current evaluation mode to ignore 1287 /// side-effects. 1288 struct IgnoreSideEffectsRAII { 1289 EvalInfo &Info; 1290 EvalInfo::EvaluationMode OldMode; 1291 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1292 : Info(Info), OldMode(Info.EvalMode) { 1293 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1294 } 1295 1296 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1297 }; 1298 1299 /// RAII object used to optionally suppress diagnostics and side-effects from 1300 /// a speculative evaluation. 1301 class SpeculativeEvaluationRAII { 1302 EvalInfo *Info = nullptr; 1303 Expr::EvalStatus OldStatus; 1304 unsigned OldSpeculativeEvaluationDepth = 0; 1305 1306 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1307 Info = Other.Info; 1308 OldStatus = Other.OldStatus; 1309 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1310 Other.Info = nullptr; 1311 } 1312 1313 void maybeRestoreState() { 1314 if (!Info) 1315 return; 1316 1317 Info->EvalStatus = OldStatus; 1318 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1319 } 1320 1321 public: 1322 SpeculativeEvaluationRAII() = default; 1323 1324 SpeculativeEvaluationRAII( 1325 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1326 : Info(&Info), OldStatus(Info.EvalStatus), 1327 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1328 Info.EvalStatus.Diag = NewDiag; 1329 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1330 } 1331 1332 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1333 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1334 moveFromAndCancel(std::move(Other)); 1335 } 1336 1337 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1338 maybeRestoreState(); 1339 moveFromAndCancel(std::move(Other)); 1340 return *this; 1341 } 1342 1343 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1344 }; 1345 1346 /// RAII object wrapping a full-expression or block scope, and handling 1347 /// the ending of the lifetime of temporaries created within it. 1348 template<ScopeKind Kind> 1349 class ScopeRAII { 1350 EvalInfo &Info; 1351 unsigned OldStackSize; 1352 public: 1353 ScopeRAII(EvalInfo &Info) 1354 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1355 // Push a new temporary version. This is needed to distinguish between 1356 // temporaries created in different iterations of a loop. 1357 Info.CurrentCall->pushTempVersion(); 1358 } 1359 bool destroy(bool RunDestructors = true) { 1360 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1361 OldStackSize = -1U; 1362 return OK; 1363 } 1364 ~ScopeRAII() { 1365 if (OldStackSize != -1U) 1366 destroy(false); 1367 // Body moved to a static method to encourage the compiler to inline away 1368 // instances of this class. 1369 Info.CurrentCall->popTempVersion(); 1370 } 1371 private: 1372 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1373 unsigned OldStackSize) { 1374 assert(OldStackSize <= Info.CleanupStack.size() && 1375 "running cleanups out of order?"); 1376 1377 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1378 // for a full-expression scope. 1379 bool Success = true; 1380 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1381 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1382 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1383 Success = false; 1384 break; 1385 } 1386 } 1387 } 1388 1389 // Compact any retained cleanups. 1390 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1391 if (Kind != ScopeKind::Block) 1392 NewEnd = 1393 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1394 return C.isDestroyedAtEndOf(Kind); 1395 }); 1396 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1397 return Success; 1398 } 1399 }; 1400 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1401 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1402 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1403 } 1404 1405 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1406 CheckSubobjectKind CSK) { 1407 if (Invalid) 1408 return false; 1409 if (isOnePastTheEnd()) { 1410 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1411 << CSK; 1412 setInvalid(); 1413 return false; 1414 } 1415 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1416 // must actually be at least one array element; even a VLA cannot have a 1417 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1418 return true; 1419 } 1420 1421 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1422 const Expr *E) { 1423 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1424 // Do not set the designator as invalid: we can represent this situation, 1425 // and correct handling of __builtin_object_size requires us to do so. 1426 } 1427 1428 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1429 const Expr *E, 1430 const APSInt &N) { 1431 // If we're complaining, we must be able to statically determine the size of 1432 // the most derived array. 1433 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1434 Info.CCEDiag(E, diag::note_constexpr_array_index) 1435 << N << /*array*/ 0 1436 << static_cast<unsigned>(getMostDerivedArraySize()); 1437 else 1438 Info.CCEDiag(E, diag::note_constexpr_array_index) 1439 << N << /*non-array*/ 1; 1440 setInvalid(); 1441 } 1442 1443 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1444 const FunctionDecl *Callee, const LValue *This, 1445 const Expr *CallExpr, CallRef Call) 1446 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1447 CallExpr(CallExpr), Arguments(Call), CallLoc(CallLoc), 1448 Index(Info.NextCallIndex++) { 1449 Info.CurrentCall = this; 1450 ++Info.CallStackDepth; 1451 } 1452 1453 CallStackFrame::~CallStackFrame() { 1454 assert(Info.CurrentCall == this && "calls retired out of order"); 1455 --Info.CallStackDepth; 1456 Info.CurrentCall = Caller; 1457 } 1458 1459 static bool isRead(AccessKinds AK) { 1460 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1461 } 1462 1463 static bool isModification(AccessKinds AK) { 1464 switch (AK) { 1465 case AK_Read: 1466 case AK_ReadObjectRepresentation: 1467 case AK_MemberCall: 1468 case AK_DynamicCast: 1469 case AK_TypeId: 1470 return false; 1471 case AK_Assign: 1472 case AK_Increment: 1473 case AK_Decrement: 1474 case AK_Construct: 1475 case AK_Destroy: 1476 return true; 1477 } 1478 llvm_unreachable("unknown access kind"); 1479 } 1480 1481 static bool isAnyAccess(AccessKinds AK) { 1482 return isRead(AK) || isModification(AK); 1483 } 1484 1485 /// Is this an access per the C++ definition? 1486 static bool isFormalAccess(AccessKinds AK) { 1487 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1488 } 1489 1490 /// Is this kind of axcess valid on an indeterminate object value? 1491 static bool isValidIndeterminateAccess(AccessKinds AK) { 1492 switch (AK) { 1493 case AK_Read: 1494 case AK_Increment: 1495 case AK_Decrement: 1496 // These need the object's value. 1497 return false; 1498 1499 case AK_ReadObjectRepresentation: 1500 case AK_Assign: 1501 case AK_Construct: 1502 case AK_Destroy: 1503 // Construction and destruction don't need the value. 1504 return true; 1505 1506 case AK_MemberCall: 1507 case AK_DynamicCast: 1508 case AK_TypeId: 1509 // These aren't really meaningful on scalars. 1510 return true; 1511 } 1512 llvm_unreachable("unknown access kind"); 1513 } 1514 1515 namespace { 1516 struct ComplexValue { 1517 private: 1518 bool IsInt; 1519 1520 public: 1521 APSInt IntReal, IntImag; 1522 APFloat FloatReal, FloatImag; 1523 1524 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1525 1526 void makeComplexFloat() { IsInt = false; } 1527 bool isComplexFloat() const { return !IsInt; } 1528 APFloat &getComplexFloatReal() { return FloatReal; } 1529 APFloat &getComplexFloatImag() { return FloatImag; } 1530 1531 void makeComplexInt() { IsInt = true; } 1532 bool isComplexInt() const { return IsInt; } 1533 APSInt &getComplexIntReal() { return IntReal; } 1534 APSInt &getComplexIntImag() { return IntImag; } 1535 1536 void moveInto(APValue &v) const { 1537 if (isComplexFloat()) 1538 v = APValue(FloatReal, FloatImag); 1539 else 1540 v = APValue(IntReal, IntImag); 1541 } 1542 void setFrom(const APValue &v) { 1543 assert(v.isComplexFloat() || v.isComplexInt()); 1544 if (v.isComplexFloat()) { 1545 makeComplexFloat(); 1546 FloatReal = v.getComplexFloatReal(); 1547 FloatImag = v.getComplexFloatImag(); 1548 } else { 1549 makeComplexInt(); 1550 IntReal = v.getComplexIntReal(); 1551 IntImag = v.getComplexIntImag(); 1552 } 1553 } 1554 }; 1555 1556 struct LValue { 1557 APValue::LValueBase Base; 1558 CharUnits Offset; 1559 SubobjectDesignator Designator; 1560 bool IsNullPtr : 1; 1561 bool InvalidBase : 1; 1562 1563 const APValue::LValueBase getLValueBase() const { return Base; } 1564 CharUnits &getLValueOffset() { return Offset; } 1565 const CharUnits &getLValueOffset() const { return Offset; } 1566 SubobjectDesignator &getLValueDesignator() { return Designator; } 1567 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1568 bool isNullPointer() const { return IsNullPtr;} 1569 1570 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1571 unsigned getLValueVersion() const { return Base.getVersion(); } 1572 1573 void moveInto(APValue &V) const { 1574 if (Designator.Invalid) 1575 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1576 else { 1577 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1578 V = APValue(Base, Offset, Designator.Entries, 1579 Designator.IsOnePastTheEnd, IsNullPtr); 1580 } 1581 } 1582 void setFrom(ASTContext &Ctx, const APValue &V) { 1583 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1584 Base = V.getLValueBase(); 1585 Offset = V.getLValueOffset(); 1586 InvalidBase = false; 1587 Designator = SubobjectDesignator(Ctx, V); 1588 IsNullPtr = V.isNullPointer(); 1589 } 1590 1591 void set(APValue::LValueBase B, bool BInvalid = false) { 1592 #ifndef NDEBUG 1593 // We only allow a few types of invalid bases. Enforce that here. 1594 if (BInvalid) { 1595 const auto *E = B.get<const Expr *>(); 1596 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1597 "Unexpected type of invalid base"); 1598 } 1599 #endif 1600 1601 Base = B; 1602 Offset = CharUnits::fromQuantity(0); 1603 InvalidBase = BInvalid; 1604 Designator = SubobjectDesignator(getType(B)); 1605 IsNullPtr = false; 1606 } 1607 1608 void setNull(ASTContext &Ctx, QualType PointerTy) { 1609 Base = (const ValueDecl *)nullptr; 1610 Offset = 1611 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1612 InvalidBase = false; 1613 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1614 IsNullPtr = true; 1615 } 1616 1617 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1618 set(B, true); 1619 } 1620 1621 std::string toString(ASTContext &Ctx, QualType T) const { 1622 APValue Printable; 1623 moveInto(Printable); 1624 return Printable.getAsString(Ctx, T); 1625 } 1626 1627 private: 1628 // Check that this LValue is not based on a null pointer. If it is, produce 1629 // a diagnostic and mark the designator as invalid. 1630 template <typename GenDiagType> 1631 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1632 if (Designator.Invalid) 1633 return false; 1634 if (IsNullPtr) { 1635 GenDiag(); 1636 Designator.setInvalid(); 1637 return false; 1638 } 1639 return true; 1640 } 1641 1642 public: 1643 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1644 CheckSubobjectKind CSK) { 1645 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1646 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1647 }); 1648 } 1649 1650 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1651 AccessKinds AK) { 1652 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1653 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1654 }); 1655 } 1656 1657 // Check this LValue refers to an object. If not, set the designator to be 1658 // invalid and emit a diagnostic. 1659 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1660 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1661 Designator.checkSubobject(Info, E, CSK); 1662 } 1663 1664 void addDecl(EvalInfo &Info, const Expr *E, 1665 const Decl *D, bool Virtual = false) { 1666 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1667 Designator.addDeclUnchecked(D, Virtual); 1668 } 1669 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1670 if (!Designator.Entries.empty()) { 1671 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1672 Designator.setInvalid(); 1673 return; 1674 } 1675 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1676 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1677 Designator.FirstEntryIsAnUnsizedArray = true; 1678 Designator.addUnsizedArrayUnchecked(ElemTy); 1679 } 1680 } 1681 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1682 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1683 Designator.addArrayUnchecked(CAT); 1684 } 1685 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1686 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1687 Designator.addComplexUnchecked(EltTy, Imag); 1688 } 1689 void clearIsNullPointer() { 1690 IsNullPtr = false; 1691 } 1692 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1693 const APSInt &Index, CharUnits ElementSize) { 1694 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1695 // but we're not required to diagnose it and it's valid in C++.) 1696 if (!Index) 1697 return; 1698 1699 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1700 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1701 // offsets. 1702 uint64_t Offset64 = Offset.getQuantity(); 1703 uint64_t ElemSize64 = ElementSize.getQuantity(); 1704 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1705 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1706 1707 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1708 Designator.adjustIndex(Info, E, Index); 1709 clearIsNullPointer(); 1710 } 1711 void adjustOffset(CharUnits N) { 1712 Offset += N; 1713 if (N.getQuantity()) 1714 clearIsNullPointer(); 1715 } 1716 }; 1717 1718 struct MemberPtr { 1719 MemberPtr() {} 1720 explicit MemberPtr(const ValueDecl *Decl) 1721 : DeclAndIsDerivedMember(Decl, false) {} 1722 1723 /// The member or (direct or indirect) field referred to by this member 1724 /// pointer, or 0 if this is a null member pointer. 1725 const ValueDecl *getDecl() const { 1726 return DeclAndIsDerivedMember.getPointer(); 1727 } 1728 /// Is this actually a member of some type derived from the relevant class? 1729 bool isDerivedMember() const { 1730 return DeclAndIsDerivedMember.getInt(); 1731 } 1732 /// Get the class which the declaration actually lives in. 1733 const CXXRecordDecl *getContainingRecord() const { 1734 return cast<CXXRecordDecl>( 1735 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1736 } 1737 1738 void moveInto(APValue &V) const { 1739 V = APValue(getDecl(), isDerivedMember(), Path); 1740 } 1741 void setFrom(const APValue &V) { 1742 assert(V.isMemberPointer()); 1743 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1744 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1745 Path.clear(); 1746 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1747 Path.insert(Path.end(), P.begin(), P.end()); 1748 } 1749 1750 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1751 /// whether the member is a member of some class derived from the class type 1752 /// of the member pointer. 1753 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1754 /// Path - The path of base/derived classes from the member declaration's 1755 /// class (exclusive) to the class type of the member pointer (inclusive). 1756 SmallVector<const CXXRecordDecl*, 4> Path; 1757 1758 /// Perform a cast towards the class of the Decl (either up or down the 1759 /// hierarchy). 1760 bool castBack(const CXXRecordDecl *Class) { 1761 assert(!Path.empty()); 1762 const CXXRecordDecl *Expected; 1763 if (Path.size() >= 2) 1764 Expected = Path[Path.size() - 2]; 1765 else 1766 Expected = getContainingRecord(); 1767 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1768 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1769 // if B does not contain the original member and is not a base or 1770 // derived class of the class containing the original member, the result 1771 // of the cast is undefined. 1772 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1773 // (D::*). We consider that to be a language defect. 1774 return false; 1775 } 1776 Path.pop_back(); 1777 return true; 1778 } 1779 /// Perform a base-to-derived member pointer cast. 1780 bool castToDerived(const CXXRecordDecl *Derived) { 1781 if (!getDecl()) 1782 return true; 1783 if (!isDerivedMember()) { 1784 Path.push_back(Derived); 1785 return true; 1786 } 1787 if (!castBack(Derived)) 1788 return false; 1789 if (Path.empty()) 1790 DeclAndIsDerivedMember.setInt(false); 1791 return true; 1792 } 1793 /// Perform a derived-to-base member pointer cast. 1794 bool castToBase(const CXXRecordDecl *Base) { 1795 if (!getDecl()) 1796 return true; 1797 if (Path.empty()) 1798 DeclAndIsDerivedMember.setInt(true); 1799 if (isDerivedMember()) { 1800 Path.push_back(Base); 1801 return true; 1802 } 1803 return castBack(Base); 1804 } 1805 }; 1806 1807 /// Compare two member pointers, which are assumed to be of the same type. 1808 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1809 if (!LHS.getDecl() || !RHS.getDecl()) 1810 return !LHS.getDecl() && !RHS.getDecl(); 1811 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1812 return false; 1813 return LHS.Path == RHS.Path; 1814 } 1815 } 1816 1817 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1818 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1819 const LValue &This, const Expr *E, 1820 bool AllowNonLiteralTypes = false); 1821 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1822 bool InvalidBaseOK = false); 1823 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1824 bool InvalidBaseOK = false); 1825 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1826 EvalInfo &Info); 1827 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1828 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1829 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1830 EvalInfo &Info); 1831 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1832 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1833 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1834 EvalInfo &Info); 1835 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1836 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 1837 EvalInfo &Info); 1838 1839 /// Evaluate an integer or fixed point expression into an APResult. 1840 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1841 EvalInfo &Info); 1842 1843 /// Evaluate only a fixed point expression into an APResult. 1844 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1845 EvalInfo &Info); 1846 1847 //===----------------------------------------------------------------------===// 1848 // Misc utilities 1849 //===----------------------------------------------------------------------===// 1850 1851 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1852 /// preserving its value (by extending by up to one bit as needed). 1853 static void negateAsSigned(APSInt &Int) { 1854 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1855 Int = Int.extend(Int.getBitWidth() + 1); 1856 Int.setIsSigned(true); 1857 } 1858 Int = -Int; 1859 } 1860 1861 template<typename KeyT> 1862 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1863 ScopeKind Scope, LValue &LV) { 1864 unsigned Version = getTempVersion(); 1865 APValue::LValueBase Base(Key, Index, Version); 1866 LV.set(Base); 1867 return createLocal(Base, Key, T, Scope); 1868 } 1869 1870 /// Allocate storage for a parameter of a function call made in this frame. 1871 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1872 LValue &LV) { 1873 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1874 APValue::LValueBase Base(PVD, Index, Args.Version); 1875 LV.set(Base); 1876 // We always destroy parameters at the end of the call, even if we'd allow 1877 // them to live to the end of the full-expression at runtime, in order to 1878 // give portable results and match other compilers. 1879 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1880 } 1881 1882 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1883 QualType T, ScopeKind Scope) { 1884 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1885 unsigned Version = Base.getVersion(); 1886 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1887 assert(Result.isAbsent() && "local created multiple times"); 1888 1889 // If we're creating a local immediately in the operand of a speculative 1890 // evaluation, don't register a cleanup to be run outside the speculative 1891 // evaluation context, since we won't actually be able to initialize this 1892 // object. 1893 if (Index <= Info.SpeculativeEvaluationDepth) { 1894 if (T.isDestructedType()) 1895 Info.noteSideEffect(); 1896 } else { 1897 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1898 } 1899 return Result; 1900 } 1901 1902 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1903 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1904 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1905 return nullptr; 1906 } 1907 1908 DynamicAllocLValue DA(NumHeapAllocs++); 1909 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1910 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1911 std::forward_as_tuple(DA), std::tuple<>()); 1912 assert(Result.second && "reused a heap alloc index?"); 1913 Result.first->second.AllocExpr = E; 1914 return &Result.first->second.Value; 1915 } 1916 1917 /// Produce a string describing the given constexpr call. 1918 void CallStackFrame::describe(raw_ostream &Out) const { 1919 unsigned ArgIndex = 0; 1920 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1921 !isa<CXXConstructorDecl>(Callee) && 1922 cast<CXXMethodDecl>(Callee)->isInstance(); 1923 1924 if (!IsMemberCall) 1925 Out << *Callee << '('; 1926 1927 if (This && IsMemberCall) { 1928 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) { 1929 const Expr *Object = MCE->getImplicitObjectArgument(); 1930 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(), 1931 /*Indentation=*/0); 1932 if (Object->getType()->isPointerType()) 1933 Out << "->"; 1934 else 1935 Out << "."; 1936 } else if (const auto *OCE = 1937 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) { 1938 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, 1939 Info.Ctx.getPrintingPolicy(), 1940 /*Indentation=*/0); 1941 Out << "."; 1942 } else { 1943 APValue Val; 1944 This->moveInto(Val); 1945 Val.printPretty( 1946 Out, Info.Ctx, 1947 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType)); 1948 Out << "."; 1949 } 1950 Out << *Callee << '('; 1951 IsMemberCall = false; 1952 } 1953 1954 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1955 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1956 if (ArgIndex > (unsigned)IsMemberCall) 1957 Out << ", "; 1958 1959 const ParmVarDecl *Param = *I; 1960 APValue *V = Info.getParamSlot(Arguments, Param); 1961 if (V) 1962 V->printPretty(Out, Info.Ctx, Param->getType()); 1963 else 1964 Out << "<...>"; 1965 1966 if (ArgIndex == 0 && IsMemberCall) 1967 Out << "->" << *Callee << '('; 1968 } 1969 1970 Out << ')'; 1971 } 1972 1973 /// Evaluate an expression to see if it had side-effects, and discard its 1974 /// result. 1975 /// \return \c true if the caller should keep evaluating. 1976 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1977 assert(!E->isValueDependent()); 1978 APValue Scratch; 1979 if (!Evaluate(Scratch, Info, E)) 1980 // We don't need the value, but we might have skipped a side effect here. 1981 return Info.noteSideEffect(); 1982 return true; 1983 } 1984 1985 /// Should this call expression be treated as a no-op? 1986 static bool IsNoOpCall(const CallExpr *E) { 1987 unsigned Builtin = E->getBuiltinCallee(); 1988 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1989 Builtin == Builtin::BI__builtin___NSStringMakeConstantString || 1990 Builtin == Builtin::BI__builtin_function_start); 1991 } 1992 1993 static bool IsGlobalLValue(APValue::LValueBase B) { 1994 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1995 // constant expression of pointer type that evaluates to... 1996 1997 // ... a null pointer value, or a prvalue core constant expression of type 1998 // std::nullptr_t. 1999 if (!B) 2000 return true; 2001 2002 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 2003 // ... the address of an object with static storage duration, 2004 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 2005 return VD->hasGlobalStorage(); 2006 if (isa<TemplateParamObjectDecl>(D)) 2007 return true; 2008 // ... the address of a function, 2009 // ... the address of a GUID [MS extension], 2010 // ... the address of an unnamed global constant 2011 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D); 2012 } 2013 2014 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 2015 return true; 2016 2017 const Expr *E = B.get<const Expr*>(); 2018 switch (E->getStmtClass()) { 2019 default: 2020 return false; 2021 case Expr::CompoundLiteralExprClass: { 2022 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 2023 return CLE->isFileScope() && CLE->isLValue(); 2024 } 2025 case Expr::MaterializeTemporaryExprClass: 2026 // A materialized temporary might have been lifetime-extended to static 2027 // storage duration. 2028 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 2029 // A string literal has static storage duration. 2030 case Expr::StringLiteralClass: 2031 case Expr::PredefinedExprClass: 2032 case Expr::ObjCStringLiteralClass: 2033 case Expr::ObjCEncodeExprClass: 2034 return true; 2035 case Expr::ObjCBoxedExprClass: 2036 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2037 case Expr::CallExprClass: 2038 return IsNoOpCall(cast<CallExpr>(E)); 2039 // For GCC compatibility, &&label has static storage duration. 2040 case Expr::AddrLabelExprClass: 2041 return true; 2042 // A Block literal expression may be used as the initialization value for 2043 // Block variables at global or local static scope. 2044 case Expr::BlockExprClass: 2045 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2046 // The APValue generated from a __builtin_source_location will be emitted as a 2047 // literal. 2048 case Expr::SourceLocExprClass: 2049 return true; 2050 case Expr::ImplicitValueInitExprClass: 2051 // FIXME: 2052 // We can never form an lvalue with an implicit value initialization as its 2053 // base through expression evaluation, so these only appear in one case: the 2054 // implicit variable declaration we invent when checking whether a constexpr 2055 // constructor can produce a constant expression. We must assume that such 2056 // an expression might be a global lvalue. 2057 return true; 2058 } 2059 } 2060 2061 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2062 return LVal.Base.dyn_cast<const ValueDecl*>(); 2063 } 2064 2065 static bool IsLiteralLValue(const LValue &Value) { 2066 if (Value.getLValueCallIndex()) 2067 return false; 2068 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2069 return E && !isa<MaterializeTemporaryExpr>(E); 2070 } 2071 2072 static bool IsWeakLValue(const LValue &Value) { 2073 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2074 return Decl && Decl->isWeak(); 2075 } 2076 2077 static bool isZeroSized(const LValue &Value) { 2078 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2079 if (Decl && isa<VarDecl>(Decl)) { 2080 QualType Ty = Decl->getType(); 2081 if (Ty->isArrayType()) 2082 return Ty->isIncompleteType() || 2083 Decl->getASTContext().getTypeSize(Ty) == 0; 2084 } 2085 return false; 2086 } 2087 2088 static bool HasSameBase(const LValue &A, const LValue &B) { 2089 if (!A.getLValueBase()) 2090 return !B.getLValueBase(); 2091 if (!B.getLValueBase()) 2092 return false; 2093 2094 if (A.getLValueBase().getOpaqueValue() != 2095 B.getLValueBase().getOpaqueValue()) 2096 return false; 2097 2098 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2099 A.getLValueVersion() == B.getLValueVersion(); 2100 } 2101 2102 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2103 assert(Base && "no location for a null lvalue"); 2104 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2105 2106 // For a parameter, find the corresponding call stack frame (if it still 2107 // exists), and point at the parameter of the function definition we actually 2108 // invoked. 2109 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2110 unsigned Idx = PVD->getFunctionScopeIndex(); 2111 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2112 if (F->Arguments.CallIndex == Base.getCallIndex() && 2113 F->Arguments.Version == Base.getVersion() && F->Callee && 2114 Idx < F->Callee->getNumParams()) { 2115 VD = F->Callee->getParamDecl(Idx); 2116 break; 2117 } 2118 } 2119 } 2120 2121 if (VD) 2122 Info.Note(VD->getLocation(), diag::note_declared_at); 2123 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2124 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2125 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2126 // FIXME: Produce a note for dangling pointers too. 2127 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA)) 2128 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2129 diag::note_constexpr_dynamic_alloc_here); 2130 } 2131 2132 // We have no information to show for a typeid(T) object. 2133 } 2134 2135 enum class CheckEvaluationResultKind { 2136 ConstantExpression, 2137 FullyInitialized, 2138 }; 2139 2140 /// Materialized temporaries that we've already checked to determine if they're 2141 /// initializsed by a constant expression. 2142 using CheckedTemporaries = 2143 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2144 2145 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2146 EvalInfo &Info, SourceLocation DiagLoc, 2147 QualType Type, const APValue &Value, 2148 ConstantExprKind Kind, 2149 const FieldDecl *SubobjectDecl, 2150 CheckedTemporaries &CheckedTemps); 2151 2152 /// Check that this reference or pointer core constant expression is a valid 2153 /// value for an address or reference constant expression. Return true if we 2154 /// can fold this expression, whether or not it's a constant expression. 2155 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2156 QualType Type, const LValue &LVal, 2157 ConstantExprKind Kind, 2158 CheckedTemporaries &CheckedTemps) { 2159 bool IsReferenceType = Type->isReferenceType(); 2160 2161 APValue::LValueBase Base = LVal.getLValueBase(); 2162 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2163 2164 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2165 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2166 2167 // Additional restrictions apply in a template argument. We only enforce the 2168 // C++20 restrictions here; additional syntactic and semantic restrictions 2169 // are applied elsewhere. 2170 if (isTemplateArgument(Kind)) { 2171 int InvalidBaseKind = -1; 2172 StringRef Ident; 2173 if (Base.is<TypeInfoLValue>()) 2174 InvalidBaseKind = 0; 2175 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2176 InvalidBaseKind = 1; 2177 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2178 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2179 InvalidBaseKind = 2; 2180 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2181 InvalidBaseKind = 3; 2182 Ident = PE->getIdentKindName(); 2183 } 2184 2185 if (InvalidBaseKind != -1) { 2186 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2187 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2188 << Ident; 2189 return false; 2190 } 2191 } 2192 2193 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD); 2194 FD && FD->isImmediateFunction()) { 2195 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2196 << !Type->isAnyPointerType(); 2197 Info.Note(FD->getLocation(), diag::note_declared_at); 2198 return false; 2199 } 2200 2201 // Check that the object is a global. Note that the fake 'this' object we 2202 // manufacture when checking potential constant expressions is conservatively 2203 // assumed to be global here. 2204 if (!IsGlobalLValue(Base)) { 2205 if (Info.getLangOpts().CPlusPlus11) { 2206 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2207 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD 2208 << BaseVD; 2209 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD); 2210 if (VarD && VarD->isConstexpr()) { 2211 // Non-static local constexpr variables have unintuitive semantics: 2212 // constexpr int a = 1; 2213 // constexpr const int *p = &a; 2214 // ... is invalid because the address of 'a' is not constant. Suggest 2215 // adding a 'static' in this case. 2216 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2217 << VarD 2218 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2219 } else { 2220 NoteLValueLocation(Info, Base); 2221 } 2222 } else { 2223 Info.FFDiag(Loc); 2224 } 2225 // Don't allow references to temporaries to escape. 2226 return false; 2227 } 2228 assert((Info.checkingPotentialConstantExpression() || 2229 LVal.getLValueCallIndex() == 0) && 2230 "have call index for global lvalue"); 2231 2232 if (Base.is<DynamicAllocLValue>()) { 2233 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2234 << IsReferenceType << !Designator.Entries.empty(); 2235 NoteLValueLocation(Info, Base); 2236 return false; 2237 } 2238 2239 if (BaseVD) { 2240 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2241 // Check if this is a thread-local variable. 2242 if (Var->getTLSKind()) 2243 // FIXME: Diagnostic! 2244 return false; 2245 2246 // A dllimport variable never acts like a constant, unless we're 2247 // evaluating a value for use only in name mangling. 2248 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2249 // FIXME: Diagnostic! 2250 return false; 2251 2252 // In CUDA/HIP device compilation, only device side variables have 2253 // constant addresses. 2254 if (Info.getCtx().getLangOpts().CUDA && 2255 Info.getCtx().getLangOpts().CUDAIsDevice && 2256 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) { 2257 if ((!Var->hasAttr<CUDADeviceAttr>() && 2258 !Var->hasAttr<CUDAConstantAttr>() && 2259 !Var->getType()->isCUDADeviceBuiltinSurfaceType() && 2260 !Var->getType()->isCUDADeviceBuiltinTextureType()) || 2261 Var->hasAttr<HIPManagedAttr>()) 2262 return false; 2263 } 2264 } 2265 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2266 // __declspec(dllimport) must be handled very carefully: 2267 // We must never initialize an expression with the thunk in C++. 2268 // Doing otherwise would allow the same id-expression to yield 2269 // different addresses for the same function in different translation 2270 // units. However, this means that we must dynamically initialize the 2271 // expression with the contents of the import address table at runtime. 2272 // 2273 // The C language has no notion of ODR; furthermore, it has no notion of 2274 // dynamic initialization. This means that we are permitted to 2275 // perform initialization with the address of the thunk. 2276 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2277 FD->hasAttr<DLLImportAttr>()) 2278 // FIXME: Diagnostic! 2279 return false; 2280 } 2281 } else if (const auto *MTE = 2282 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2283 if (CheckedTemps.insert(MTE).second) { 2284 QualType TempType = getType(Base); 2285 if (TempType.isDestructedType()) { 2286 Info.FFDiag(MTE->getExprLoc(), 2287 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2288 << TempType; 2289 return false; 2290 } 2291 2292 APValue *V = MTE->getOrCreateValue(false); 2293 assert(V && "evasluation result refers to uninitialised temporary"); 2294 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2295 Info, MTE->getExprLoc(), TempType, *V, Kind, 2296 /*SubobjectDecl=*/nullptr, CheckedTemps)) 2297 return false; 2298 } 2299 } 2300 2301 // Allow address constant expressions to be past-the-end pointers. This is 2302 // an extension: the standard requires them to point to an object. 2303 if (!IsReferenceType) 2304 return true; 2305 2306 // A reference constant expression must refer to an object. 2307 if (!Base) { 2308 // FIXME: diagnostic 2309 Info.CCEDiag(Loc); 2310 return true; 2311 } 2312 2313 // Does this refer one past the end of some object? 2314 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2315 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2316 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2317 NoteLValueLocation(Info, Base); 2318 } 2319 2320 return true; 2321 } 2322 2323 /// Member pointers are constant expressions unless they point to a 2324 /// non-virtual dllimport member function. 2325 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2326 SourceLocation Loc, 2327 QualType Type, 2328 const APValue &Value, 2329 ConstantExprKind Kind) { 2330 const ValueDecl *Member = Value.getMemberPointerDecl(); 2331 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2332 if (!FD) 2333 return true; 2334 if (FD->isImmediateFunction()) { 2335 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2336 Info.Note(FD->getLocation(), diag::note_declared_at); 2337 return false; 2338 } 2339 return isForManglingOnly(Kind) || FD->isVirtual() || 2340 !FD->hasAttr<DLLImportAttr>(); 2341 } 2342 2343 /// Check that this core constant expression is of literal type, and if not, 2344 /// produce an appropriate diagnostic. 2345 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2346 const LValue *This = nullptr) { 2347 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2348 return true; 2349 2350 // C++1y: A constant initializer for an object o [...] may also invoke 2351 // constexpr constructors for o and its subobjects even if those objects 2352 // are of non-literal class types. 2353 // 2354 // C++11 missed this detail for aggregates, so classes like this: 2355 // struct foo_t { union { int i; volatile int j; } u; }; 2356 // are not (obviously) initializable like so: 2357 // __attribute__((__require_constant_initialization__)) 2358 // static const foo_t x = {{0}}; 2359 // because "i" is a subobject with non-literal initialization (due to the 2360 // volatile member of the union). See: 2361 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2362 // Therefore, we use the C++1y behavior. 2363 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2364 return true; 2365 2366 // Prvalue constant expressions must be of literal types. 2367 if (Info.getLangOpts().CPlusPlus11) 2368 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2369 << E->getType(); 2370 else 2371 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2372 return false; 2373 } 2374 2375 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2376 EvalInfo &Info, SourceLocation DiagLoc, 2377 QualType Type, const APValue &Value, 2378 ConstantExprKind Kind, 2379 const FieldDecl *SubobjectDecl, 2380 CheckedTemporaries &CheckedTemps) { 2381 if (!Value.hasValue()) { 2382 assert(SubobjectDecl && "SubobjectDecl shall be non-null"); 2383 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl; 2384 Info.Note(SubobjectDecl->getLocation(), 2385 diag::note_constexpr_subobject_declared_here); 2386 return false; 2387 } 2388 2389 // We allow _Atomic(T) to be initialized from anything that T can be 2390 // initialized from. 2391 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2392 Type = AT->getValueType(); 2393 2394 // Core issue 1454: For a literal constant expression of array or class type, 2395 // each subobject of its value shall have been initialized by a constant 2396 // expression. 2397 if (Value.isArray()) { 2398 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2399 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2400 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2401 Value.getArrayInitializedElt(I), Kind, 2402 SubobjectDecl, CheckedTemps)) 2403 return false; 2404 } 2405 if (!Value.hasArrayFiller()) 2406 return true; 2407 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2408 Value.getArrayFiller(), Kind, SubobjectDecl, 2409 CheckedTemps); 2410 } 2411 if (Value.isUnion() && Value.getUnionField()) { 2412 return CheckEvaluationResult( 2413 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2414 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps); 2415 } 2416 if (Value.isStruct()) { 2417 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2418 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2419 unsigned BaseIndex = 0; 2420 for (const CXXBaseSpecifier &BS : CD->bases()) { 2421 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2422 Value.getStructBase(BaseIndex), Kind, 2423 /*SubobjectDecl=*/nullptr, CheckedTemps)) 2424 return false; 2425 ++BaseIndex; 2426 } 2427 } 2428 for (const auto *I : RD->fields()) { 2429 if (I->isUnnamedBitfield()) 2430 continue; 2431 2432 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2433 Value.getStructField(I->getFieldIndex()), Kind, 2434 I, CheckedTemps)) 2435 return false; 2436 } 2437 } 2438 2439 if (Value.isLValue() && 2440 CERK == CheckEvaluationResultKind::ConstantExpression) { 2441 LValue LVal; 2442 LVal.setFrom(Info.Ctx, Value); 2443 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2444 CheckedTemps); 2445 } 2446 2447 if (Value.isMemberPointer() && 2448 CERK == CheckEvaluationResultKind::ConstantExpression) 2449 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2450 2451 // Everything else is fine. 2452 return true; 2453 } 2454 2455 /// Check that this core constant expression value is a valid value for a 2456 /// constant expression. If not, report an appropriate diagnostic. Does not 2457 /// check that the expression is of literal type. 2458 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2459 QualType Type, const APValue &Value, 2460 ConstantExprKind Kind) { 2461 // Nothing to check for a constant expression of type 'cv void'. 2462 if (Type->isVoidType()) 2463 return true; 2464 2465 CheckedTemporaries CheckedTemps; 2466 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2467 Info, DiagLoc, Type, Value, Kind, 2468 /*SubobjectDecl=*/nullptr, CheckedTemps); 2469 } 2470 2471 /// Check that this evaluated value is fully-initialized and can be loaded by 2472 /// an lvalue-to-rvalue conversion. 2473 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2474 QualType Type, const APValue &Value) { 2475 CheckedTemporaries CheckedTemps; 2476 return CheckEvaluationResult( 2477 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2478 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps); 2479 } 2480 2481 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2482 /// "the allocated storage is deallocated within the evaluation". 2483 static bool CheckMemoryLeaks(EvalInfo &Info) { 2484 if (!Info.HeapAllocs.empty()) { 2485 // We can still fold to a constant despite a compile-time memory leak, 2486 // so long as the heap allocation isn't referenced in the result (we check 2487 // that in CheckConstantExpression). 2488 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2489 diag::note_constexpr_memory_leak) 2490 << unsigned(Info.HeapAllocs.size() - 1); 2491 } 2492 return true; 2493 } 2494 2495 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2496 // A null base expression indicates a null pointer. These are always 2497 // evaluatable, and they are false unless the offset is zero. 2498 if (!Value.getLValueBase()) { 2499 // TODO: Should a non-null pointer with an offset of zero evaluate to true? 2500 Result = !Value.getLValueOffset().isZero(); 2501 return true; 2502 } 2503 2504 // We have a non-null base. These are generally known to be true, but if it's 2505 // a weak declaration it can be null at runtime. 2506 Result = true; 2507 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2508 return !Decl || !Decl->isWeak(); 2509 } 2510 2511 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2512 // TODO: This function should produce notes if it fails. 2513 switch (Val.getKind()) { 2514 case APValue::None: 2515 case APValue::Indeterminate: 2516 return false; 2517 case APValue::Int: 2518 Result = Val.getInt().getBoolValue(); 2519 return true; 2520 case APValue::FixedPoint: 2521 Result = Val.getFixedPoint().getBoolValue(); 2522 return true; 2523 case APValue::Float: 2524 Result = !Val.getFloat().isZero(); 2525 return true; 2526 case APValue::ComplexInt: 2527 Result = Val.getComplexIntReal().getBoolValue() || 2528 Val.getComplexIntImag().getBoolValue(); 2529 return true; 2530 case APValue::ComplexFloat: 2531 Result = !Val.getComplexFloatReal().isZero() || 2532 !Val.getComplexFloatImag().isZero(); 2533 return true; 2534 case APValue::LValue: 2535 return EvalPointerValueAsBool(Val, Result); 2536 case APValue::MemberPointer: 2537 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) { 2538 return false; 2539 } 2540 Result = Val.getMemberPointerDecl(); 2541 return true; 2542 case APValue::Vector: 2543 case APValue::Array: 2544 case APValue::Struct: 2545 case APValue::Union: 2546 case APValue::AddrLabelDiff: 2547 return false; 2548 } 2549 2550 llvm_unreachable("unknown APValue kind"); 2551 } 2552 2553 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2554 EvalInfo &Info) { 2555 assert(!E->isValueDependent()); 2556 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2557 APValue Val; 2558 if (!Evaluate(Val, Info, E)) 2559 return false; 2560 return HandleConversionToBool(Val, Result); 2561 } 2562 2563 template<typename T> 2564 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2565 const T &SrcValue, QualType DestType) { 2566 Info.CCEDiag(E, diag::note_constexpr_overflow) 2567 << SrcValue << DestType; 2568 return Info.noteUndefinedBehavior(); 2569 } 2570 2571 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2572 QualType SrcType, const APFloat &Value, 2573 QualType DestType, APSInt &Result) { 2574 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2575 // Determine whether we are converting to unsigned or signed. 2576 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2577 2578 Result = APSInt(DestWidth, !DestSigned); 2579 bool ignored; 2580 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2581 & APFloat::opInvalidOp) 2582 return HandleOverflow(Info, E, Value, DestType); 2583 return true; 2584 } 2585 2586 /// Get rounding mode to use in evaluation of the specified expression. 2587 /// 2588 /// If rounding mode is unknown at compile time, still try to evaluate the 2589 /// expression. If the result is exact, it does not depend on rounding mode. 2590 /// So return "tonearest" mode instead of "dynamic". 2591 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) { 2592 llvm::RoundingMode RM = 2593 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2594 if (RM == llvm::RoundingMode::Dynamic) 2595 RM = llvm::RoundingMode::NearestTiesToEven; 2596 return RM; 2597 } 2598 2599 /// Check if the given evaluation result is allowed for constant evaluation. 2600 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2601 APFloat::opStatus St) { 2602 // In a constant context, assume that any dynamic rounding mode or FP 2603 // exception state matches the default floating-point environment. 2604 if (Info.InConstantContext) 2605 return true; 2606 2607 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2608 if ((St & APFloat::opInexact) && 2609 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2610 // Inexact result means that it depends on rounding mode. If the requested 2611 // mode is dynamic, the evaluation cannot be made in compile time. 2612 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2613 return false; 2614 } 2615 2616 if ((St != APFloat::opOK) && 2617 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2618 FPO.getExceptionMode() != LangOptions::FPE_Ignore || 2619 FPO.getAllowFEnvAccess())) { 2620 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2621 return false; 2622 } 2623 2624 if ((St & APFloat::opStatus::opInvalidOp) && 2625 FPO.getExceptionMode() != LangOptions::FPE_Ignore) { 2626 // There is no usefully definable result. 2627 Info.FFDiag(E); 2628 return false; 2629 } 2630 2631 // FIXME: if: 2632 // - evaluation triggered other FP exception, and 2633 // - exception mode is not "ignore", and 2634 // - the expression being evaluated is not a part of global variable 2635 // initializer, 2636 // the evaluation probably need to be rejected. 2637 return true; 2638 } 2639 2640 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2641 QualType SrcType, QualType DestType, 2642 APFloat &Result) { 2643 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2644 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 2645 APFloat::opStatus St; 2646 APFloat Value = Result; 2647 bool ignored; 2648 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2649 return checkFloatingPointResult(Info, E, St); 2650 } 2651 2652 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2653 QualType DestType, QualType SrcType, 2654 const APSInt &Value) { 2655 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2656 // Figure out if this is a truncate, extend or noop cast. 2657 // If the input is signed, do a sign extend, noop, or truncate. 2658 APSInt Result = Value.extOrTrunc(DestWidth); 2659 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2660 if (DestType->isBooleanType()) 2661 Result = Value.getBoolValue(); 2662 return Result; 2663 } 2664 2665 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2666 const FPOptions FPO, 2667 QualType SrcType, const APSInt &Value, 2668 QualType DestType, APFloat &Result) { 2669 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2670 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 2671 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM); 2672 return checkFloatingPointResult(Info, E, St); 2673 } 2674 2675 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2676 APValue &Value, const FieldDecl *FD) { 2677 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2678 2679 if (!Value.isInt()) { 2680 // Trying to store a pointer-cast-to-integer into a bitfield. 2681 // FIXME: In this case, we should provide the diagnostic for casting 2682 // a pointer to an integer. 2683 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2684 Info.FFDiag(E); 2685 return false; 2686 } 2687 2688 APSInt &Int = Value.getInt(); 2689 unsigned OldBitWidth = Int.getBitWidth(); 2690 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2691 if (NewBitWidth < OldBitWidth) 2692 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2693 return true; 2694 } 2695 2696 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2697 llvm::APInt &Res) { 2698 APValue SVal; 2699 if (!Evaluate(SVal, Info, E)) 2700 return false; 2701 if (SVal.isInt()) { 2702 Res = SVal.getInt(); 2703 return true; 2704 } 2705 if (SVal.isFloat()) { 2706 Res = SVal.getFloat().bitcastToAPInt(); 2707 return true; 2708 } 2709 if (SVal.isVector()) { 2710 QualType VecTy = E->getType(); 2711 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2712 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2713 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2714 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2715 Res = llvm::APInt::getZero(VecSize); 2716 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2717 APValue &Elt = SVal.getVectorElt(i); 2718 llvm::APInt EltAsInt; 2719 if (Elt.isInt()) { 2720 EltAsInt = Elt.getInt(); 2721 } else if (Elt.isFloat()) { 2722 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2723 } else { 2724 // Don't try to handle vectors of anything other than int or float 2725 // (not sure if it's possible to hit this case). 2726 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2727 return false; 2728 } 2729 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2730 if (BigEndian) 2731 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2732 else 2733 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2734 } 2735 return true; 2736 } 2737 // Give up if the input isn't an int, float, or vector. For example, we 2738 // reject "(v4i16)(intptr_t)&a". 2739 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2740 return false; 2741 } 2742 2743 /// Perform the given integer operation, which is known to need at most BitWidth 2744 /// bits, and check for overflow in the original type (if that type was not an 2745 /// unsigned type). 2746 template<typename Operation> 2747 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2748 const APSInt &LHS, const APSInt &RHS, 2749 unsigned BitWidth, Operation Op, 2750 APSInt &Result) { 2751 if (LHS.isUnsigned()) { 2752 Result = Op(LHS, RHS); 2753 return true; 2754 } 2755 2756 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2757 Result = Value.trunc(LHS.getBitWidth()); 2758 if (Result.extend(BitWidth) != Value) { 2759 if (Info.checkingForUndefinedBehavior()) 2760 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2761 diag::warn_integer_constant_overflow) 2762 << toString(Result, 10) << E->getType(); 2763 return HandleOverflow(Info, E, Value, E->getType()); 2764 } 2765 return true; 2766 } 2767 2768 /// Perform the given binary integer operation. 2769 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2770 BinaryOperatorKind Opcode, APSInt RHS, 2771 APSInt &Result) { 2772 bool HandleOverflowResult = true; 2773 switch (Opcode) { 2774 default: 2775 Info.FFDiag(E); 2776 return false; 2777 case BO_Mul: 2778 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2779 std::multiplies<APSInt>(), Result); 2780 case BO_Add: 2781 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2782 std::plus<APSInt>(), Result); 2783 case BO_Sub: 2784 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2785 std::minus<APSInt>(), Result); 2786 case BO_And: Result = LHS & RHS; return true; 2787 case BO_Xor: Result = LHS ^ RHS; return true; 2788 case BO_Or: Result = LHS | RHS; return true; 2789 case BO_Div: 2790 case BO_Rem: 2791 if (RHS == 0) { 2792 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2793 return false; 2794 } 2795 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2796 // this operation and gives the two's complement result. 2797 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && 2798 LHS.isMinSignedValue()) 2799 HandleOverflowResult = HandleOverflow( 2800 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType()); 2801 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2802 return HandleOverflowResult; 2803 case BO_Shl: { 2804 if (Info.getLangOpts().OpenCL) 2805 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2806 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2807 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2808 RHS.isUnsigned()); 2809 else if (RHS.isSigned() && RHS.isNegative()) { 2810 // During constant-folding, a negative shift is an opposite shift. Such 2811 // a shift is not a constant expression. 2812 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2813 RHS = -RHS; 2814 goto shift_right; 2815 } 2816 shift_left: 2817 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2818 // the shifted type. 2819 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2820 if (SA != RHS) { 2821 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2822 << RHS << E->getType() << LHS.getBitWidth(); 2823 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2824 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2825 // operand, and must not overflow the corresponding unsigned type. 2826 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2827 // E1 x 2^E2 module 2^N. 2828 if (LHS.isNegative()) 2829 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2830 else if (LHS.countl_zero() < SA) 2831 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2832 } 2833 Result = LHS << SA; 2834 return true; 2835 } 2836 case BO_Shr: { 2837 if (Info.getLangOpts().OpenCL) 2838 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2839 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2840 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2841 RHS.isUnsigned()); 2842 else if (RHS.isSigned() && RHS.isNegative()) { 2843 // During constant-folding, a negative shift is an opposite shift. Such a 2844 // shift is not a constant expression. 2845 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2846 RHS = -RHS; 2847 goto shift_left; 2848 } 2849 shift_right: 2850 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2851 // shifted type. 2852 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2853 if (SA != RHS) 2854 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2855 << RHS << E->getType() << LHS.getBitWidth(); 2856 Result = LHS >> SA; 2857 return true; 2858 } 2859 2860 case BO_LT: Result = LHS < RHS; return true; 2861 case BO_GT: Result = LHS > RHS; return true; 2862 case BO_LE: Result = LHS <= RHS; return true; 2863 case BO_GE: Result = LHS >= RHS; return true; 2864 case BO_EQ: Result = LHS == RHS; return true; 2865 case BO_NE: Result = LHS != RHS; return true; 2866 case BO_Cmp: 2867 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2868 } 2869 } 2870 2871 /// Perform the given binary floating-point operation, in-place, on LHS. 2872 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2873 APFloat &LHS, BinaryOperatorKind Opcode, 2874 const APFloat &RHS) { 2875 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 2876 APFloat::opStatus St; 2877 switch (Opcode) { 2878 default: 2879 Info.FFDiag(E); 2880 return false; 2881 case BO_Mul: 2882 St = LHS.multiply(RHS, RM); 2883 break; 2884 case BO_Add: 2885 St = LHS.add(RHS, RM); 2886 break; 2887 case BO_Sub: 2888 St = LHS.subtract(RHS, RM); 2889 break; 2890 case BO_Div: 2891 // [expr.mul]p4: 2892 // If the second operand of / or % is zero the behavior is undefined. 2893 if (RHS.isZero()) 2894 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2895 St = LHS.divide(RHS, RM); 2896 break; 2897 } 2898 2899 // [expr.pre]p4: 2900 // If during the evaluation of an expression, the result is not 2901 // mathematically defined [...], the behavior is undefined. 2902 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2903 if (LHS.isNaN()) { 2904 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2905 return Info.noteUndefinedBehavior(); 2906 } 2907 2908 return checkFloatingPointResult(Info, E, St); 2909 } 2910 2911 static bool handleLogicalOpForVector(const APInt &LHSValue, 2912 BinaryOperatorKind Opcode, 2913 const APInt &RHSValue, APInt &Result) { 2914 bool LHS = (LHSValue != 0); 2915 bool RHS = (RHSValue != 0); 2916 2917 if (Opcode == BO_LAnd) 2918 Result = LHS && RHS; 2919 else 2920 Result = LHS || RHS; 2921 return true; 2922 } 2923 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2924 BinaryOperatorKind Opcode, 2925 const APFloat &RHSValue, APInt &Result) { 2926 bool LHS = !LHSValue.isZero(); 2927 bool RHS = !RHSValue.isZero(); 2928 2929 if (Opcode == BO_LAnd) 2930 Result = LHS && RHS; 2931 else 2932 Result = LHS || RHS; 2933 return true; 2934 } 2935 2936 static bool handleLogicalOpForVector(const APValue &LHSValue, 2937 BinaryOperatorKind Opcode, 2938 const APValue &RHSValue, APInt &Result) { 2939 // The result is always an int type, however operands match the first. 2940 if (LHSValue.getKind() == APValue::Int) 2941 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2942 RHSValue.getInt(), Result); 2943 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2944 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2945 RHSValue.getFloat(), Result); 2946 } 2947 2948 template <typename APTy> 2949 static bool 2950 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2951 const APTy &RHSValue, APInt &Result) { 2952 switch (Opcode) { 2953 default: 2954 llvm_unreachable("unsupported binary operator"); 2955 case BO_EQ: 2956 Result = (LHSValue == RHSValue); 2957 break; 2958 case BO_NE: 2959 Result = (LHSValue != RHSValue); 2960 break; 2961 case BO_LT: 2962 Result = (LHSValue < RHSValue); 2963 break; 2964 case BO_GT: 2965 Result = (LHSValue > RHSValue); 2966 break; 2967 case BO_LE: 2968 Result = (LHSValue <= RHSValue); 2969 break; 2970 case BO_GE: 2971 Result = (LHSValue >= RHSValue); 2972 break; 2973 } 2974 2975 // The boolean operations on these vector types use an instruction that 2976 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 2977 // to -1 to make sure that we produce the correct value. 2978 Result.negate(); 2979 2980 return true; 2981 } 2982 2983 static bool handleCompareOpForVector(const APValue &LHSValue, 2984 BinaryOperatorKind Opcode, 2985 const APValue &RHSValue, APInt &Result) { 2986 // The result is always an int type, however operands match the first. 2987 if (LHSValue.getKind() == APValue::Int) 2988 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2989 RHSValue.getInt(), Result); 2990 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2991 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2992 RHSValue.getFloat(), Result); 2993 } 2994 2995 // Perform binary operations for vector types, in place on the LHS. 2996 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2997 BinaryOperatorKind Opcode, 2998 APValue &LHSValue, 2999 const APValue &RHSValue) { 3000 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 3001 "Operation not supported on vector types"); 3002 3003 const auto *VT = E->getType()->castAs<VectorType>(); 3004 unsigned NumElements = VT->getNumElements(); 3005 QualType EltTy = VT->getElementType(); 3006 3007 // In the cases (typically C as I've observed) where we aren't evaluating 3008 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 3009 // just give up. 3010 if (!LHSValue.isVector()) { 3011 assert(LHSValue.isLValue() && 3012 "A vector result that isn't a vector OR uncalculated LValue"); 3013 Info.FFDiag(E); 3014 return false; 3015 } 3016 3017 assert(LHSValue.getVectorLength() == NumElements && 3018 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 3019 3020 SmallVector<APValue, 4> ResultElements; 3021 3022 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 3023 APValue LHSElt = LHSValue.getVectorElt(EltNum); 3024 APValue RHSElt = RHSValue.getVectorElt(EltNum); 3025 3026 if (EltTy->isIntegerType()) { 3027 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 3028 EltTy->isUnsignedIntegerType()}; 3029 bool Success = true; 3030 3031 if (BinaryOperator::isLogicalOp(Opcode)) 3032 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3033 else if (BinaryOperator::isComparisonOp(Opcode)) 3034 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3035 else 3036 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 3037 RHSElt.getInt(), EltResult); 3038 3039 if (!Success) { 3040 Info.FFDiag(E); 3041 return false; 3042 } 3043 ResultElements.emplace_back(EltResult); 3044 3045 } else if (EltTy->isFloatingType()) { 3046 assert(LHSElt.getKind() == APValue::Float && 3047 RHSElt.getKind() == APValue::Float && 3048 "Mismatched LHS/RHS/Result Type"); 3049 APFloat LHSFloat = LHSElt.getFloat(); 3050 3051 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3052 RHSElt.getFloat())) { 3053 Info.FFDiag(E); 3054 return false; 3055 } 3056 3057 ResultElements.emplace_back(LHSFloat); 3058 } 3059 } 3060 3061 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3062 return true; 3063 } 3064 3065 /// Cast an lvalue referring to a base subobject to a derived class, by 3066 /// truncating the lvalue's path to the given length. 3067 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3068 const RecordDecl *TruncatedType, 3069 unsigned TruncatedElements) { 3070 SubobjectDesignator &D = Result.Designator; 3071 3072 // Check we actually point to a derived class object. 3073 if (TruncatedElements == D.Entries.size()) 3074 return true; 3075 assert(TruncatedElements >= D.MostDerivedPathLength && 3076 "not casting to a derived class"); 3077 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3078 return false; 3079 3080 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3081 const RecordDecl *RD = TruncatedType; 3082 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3083 if (RD->isInvalidDecl()) return false; 3084 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3085 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3086 if (isVirtualBaseClass(D.Entries[I])) 3087 Result.Offset -= Layout.getVBaseClassOffset(Base); 3088 else 3089 Result.Offset -= Layout.getBaseClassOffset(Base); 3090 RD = Base; 3091 } 3092 D.Entries.resize(TruncatedElements); 3093 return true; 3094 } 3095 3096 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3097 const CXXRecordDecl *Derived, 3098 const CXXRecordDecl *Base, 3099 const ASTRecordLayout *RL = nullptr) { 3100 if (!RL) { 3101 if (Derived->isInvalidDecl()) return false; 3102 RL = &Info.Ctx.getASTRecordLayout(Derived); 3103 } 3104 3105 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3106 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3107 return true; 3108 } 3109 3110 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3111 const CXXRecordDecl *DerivedDecl, 3112 const CXXBaseSpecifier *Base) { 3113 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3114 3115 if (!Base->isVirtual()) 3116 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3117 3118 SubobjectDesignator &D = Obj.Designator; 3119 if (D.Invalid) 3120 return false; 3121 3122 // Extract most-derived object and corresponding type. 3123 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3124 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3125 return false; 3126 3127 // Find the virtual base class. 3128 if (DerivedDecl->isInvalidDecl()) return false; 3129 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3130 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3131 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3132 return true; 3133 } 3134 3135 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3136 QualType Type, LValue &Result) { 3137 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3138 PathE = E->path_end(); 3139 PathI != PathE; ++PathI) { 3140 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3141 *PathI)) 3142 return false; 3143 Type = (*PathI)->getType(); 3144 } 3145 return true; 3146 } 3147 3148 /// Cast an lvalue referring to a derived class to a known base subobject. 3149 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3150 const CXXRecordDecl *DerivedRD, 3151 const CXXRecordDecl *BaseRD) { 3152 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3153 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3154 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3155 llvm_unreachable("Class must be derived from the passed in base class!"); 3156 3157 for (CXXBasePathElement &Elem : Paths.front()) 3158 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3159 return false; 3160 return true; 3161 } 3162 3163 /// Update LVal to refer to the given field, which must be a member of the type 3164 /// currently described by LVal. 3165 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3166 const FieldDecl *FD, 3167 const ASTRecordLayout *RL = nullptr) { 3168 if (!RL) { 3169 if (FD->getParent()->isInvalidDecl()) return false; 3170 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3171 } 3172 3173 unsigned I = FD->getFieldIndex(); 3174 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3175 LVal.addDecl(Info, E, FD); 3176 return true; 3177 } 3178 3179 /// Update LVal to refer to the given indirect field. 3180 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3181 LValue &LVal, 3182 const IndirectFieldDecl *IFD) { 3183 for (const auto *C : IFD->chain()) 3184 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3185 return false; 3186 return true; 3187 } 3188 3189 /// Get the size of the given type in char units. 3190 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3191 QualType Type, CharUnits &Size) { 3192 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3193 // extension. 3194 if (Type->isVoidType() || Type->isFunctionType()) { 3195 Size = CharUnits::One(); 3196 return true; 3197 } 3198 3199 if (Type->isDependentType()) { 3200 Info.FFDiag(Loc); 3201 return false; 3202 } 3203 3204 if (!Type->isConstantSizeType()) { 3205 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3206 // FIXME: Better diagnostic. 3207 Info.FFDiag(Loc); 3208 return false; 3209 } 3210 3211 Size = Info.Ctx.getTypeSizeInChars(Type); 3212 return true; 3213 } 3214 3215 /// Update a pointer value to model pointer arithmetic. 3216 /// \param Info - Information about the ongoing evaluation. 3217 /// \param E - The expression being evaluated, for diagnostic purposes. 3218 /// \param LVal - The pointer value to be updated. 3219 /// \param EltTy - The pointee type represented by LVal. 3220 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3221 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3222 LValue &LVal, QualType EltTy, 3223 APSInt Adjustment) { 3224 CharUnits SizeOfPointee; 3225 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3226 return false; 3227 3228 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3229 return true; 3230 } 3231 3232 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3233 LValue &LVal, QualType EltTy, 3234 int64_t Adjustment) { 3235 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3236 APSInt::get(Adjustment)); 3237 } 3238 3239 /// Update an lvalue to refer to a component of a complex number. 3240 /// \param Info - Information about the ongoing evaluation. 3241 /// \param LVal - The lvalue to be updated. 3242 /// \param EltTy - The complex number's component type. 3243 /// \param Imag - False for the real component, true for the imaginary. 3244 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3245 LValue &LVal, QualType EltTy, 3246 bool Imag) { 3247 if (Imag) { 3248 CharUnits SizeOfComponent; 3249 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3250 return false; 3251 LVal.Offset += SizeOfComponent; 3252 } 3253 LVal.addComplex(Info, E, EltTy, Imag); 3254 return true; 3255 } 3256 3257 /// Try to evaluate the initializer for a variable declaration. 3258 /// 3259 /// \param Info Information about the ongoing evaluation. 3260 /// \param E An expression to be used when printing diagnostics. 3261 /// \param VD The variable whose initializer should be obtained. 3262 /// \param Version The version of the variable within the frame. 3263 /// \param Frame The frame in which the variable was created. Must be null 3264 /// if this variable is not local to the evaluation. 3265 /// \param Result Filled in with a pointer to the value of the variable. 3266 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3267 const VarDecl *VD, CallStackFrame *Frame, 3268 unsigned Version, APValue *&Result) { 3269 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3270 3271 // If this is a local variable, dig out its value. 3272 if (Frame) { 3273 Result = Frame->getTemporary(VD, Version); 3274 if (Result) 3275 return true; 3276 3277 if (!isa<ParmVarDecl>(VD)) { 3278 // Assume variables referenced within a lambda's call operator that were 3279 // not declared within the call operator are captures and during checking 3280 // of a potential constant expression, assume they are unknown constant 3281 // expressions. 3282 assert(isLambdaCallOperator(Frame->Callee) && 3283 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3284 "missing value for local variable"); 3285 if (Info.checkingPotentialConstantExpression()) 3286 return false; 3287 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3288 // still reachable at all? 3289 Info.FFDiag(E->getBeginLoc(), 3290 diag::note_unimplemented_constexpr_lambda_feature_ast) 3291 << "captures not currently allowed"; 3292 return false; 3293 } 3294 } 3295 3296 // If we're currently evaluating the initializer of this declaration, use that 3297 // in-flight value. 3298 if (Info.EvaluatingDecl == Base) { 3299 Result = Info.EvaluatingDeclValue; 3300 return true; 3301 } 3302 3303 if (isa<ParmVarDecl>(VD)) { 3304 // Assume parameters of a potential constant expression are usable in 3305 // constant expressions. 3306 if (!Info.checkingPotentialConstantExpression() || 3307 !Info.CurrentCall->Callee || 3308 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3309 if (Info.getLangOpts().CPlusPlus11) { 3310 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3311 << VD; 3312 NoteLValueLocation(Info, Base); 3313 } else { 3314 Info.FFDiag(E); 3315 } 3316 } 3317 return false; 3318 } 3319 3320 // Dig out the initializer, and use the declaration which it's attached to. 3321 // FIXME: We should eventually check whether the variable has a reachable 3322 // initializing declaration. 3323 const Expr *Init = VD->getAnyInitializer(VD); 3324 if (!Init) { 3325 // Don't diagnose during potential constant expression checking; an 3326 // initializer might be added later. 3327 if (!Info.checkingPotentialConstantExpression()) { 3328 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3329 << VD; 3330 NoteLValueLocation(Info, Base); 3331 } 3332 return false; 3333 } 3334 3335 if (Init->isValueDependent()) { 3336 // The DeclRefExpr is not value-dependent, but the variable it refers to 3337 // has a value-dependent initializer. This should only happen in 3338 // constant-folding cases, where the variable is not actually of a suitable 3339 // type for use in a constant expression (otherwise the DeclRefExpr would 3340 // have been value-dependent too), so diagnose that. 3341 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3342 if (!Info.checkingPotentialConstantExpression()) { 3343 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3344 ? diag::note_constexpr_ltor_non_constexpr 3345 : diag::note_constexpr_ltor_non_integral, 1) 3346 << VD << VD->getType(); 3347 NoteLValueLocation(Info, Base); 3348 } 3349 return false; 3350 } 3351 3352 // Check that we can fold the initializer. In C++, we will have already done 3353 // this in the cases where it matters for conformance. 3354 if (!VD->evaluateValue()) { 3355 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3356 NoteLValueLocation(Info, Base); 3357 return false; 3358 } 3359 3360 // Check that the variable is actually usable in constant expressions. For a 3361 // const integral variable or a reference, we might have a non-constant 3362 // initializer that we can nonetheless evaluate the initializer for. Such 3363 // variables are not usable in constant expressions. In C++98, the 3364 // initializer also syntactically needs to be an ICE. 3365 // 3366 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3367 // expressions here; doing so would regress diagnostics for things like 3368 // reading from a volatile constexpr variable. 3369 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3370 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3371 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3372 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3373 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3374 NoteLValueLocation(Info, Base); 3375 } 3376 3377 // Never use the initializer of a weak variable, not even for constant 3378 // folding. We can't be sure that this is the definition that will be used. 3379 if (VD->isWeak()) { 3380 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3381 NoteLValueLocation(Info, Base); 3382 return false; 3383 } 3384 3385 Result = VD->getEvaluatedValue(); 3386 return true; 3387 } 3388 3389 /// Get the base index of the given base class within an APValue representing 3390 /// the given derived class. 3391 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3392 const CXXRecordDecl *Base) { 3393 Base = Base->getCanonicalDecl(); 3394 unsigned Index = 0; 3395 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3396 E = Derived->bases_end(); I != E; ++I, ++Index) { 3397 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3398 return Index; 3399 } 3400 3401 llvm_unreachable("base class missing from derived class's bases list"); 3402 } 3403 3404 /// Extract the value of a character from a string literal. 3405 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3406 uint64_t Index) { 3407 assert(!isa<SourceLocExpr>(Lit) && 3408 "SourceLocExpr should have already been converted to a StringLiteral"); 3409 3410 // FIXME: Support MakeStringConstant 3411 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3412 std::string Str; 3413 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3414 assert(Index <= Str.size() && "Index too large"); 3415 return APSInt::getUnsigned(Str.c_str()[Index]); 3416 } 3417 3418 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3419 Lit = PE->getFunctionName(); 3420 const StringLiteral *S = cast<StringLiteral>(Lit); 3421 const ConstantArrayType *CAT = 3422 Info.Ctx.getAsConstantArrayType(S->getType()); 3423 assert(CAT && "string literal isn't an array"); 3424 QualType CharType = CAT->getElementType(); 3425 assert(CharType->isIntegerType() && "unexpected character type"); 3426 3427 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3428 CharType->isUnsignedIntegerType()); 3429 if (Index < S->getLength()) 3430 Value = S->getCodeUnit(Index); 3431 return Value; 3432 } 3433 3434 // Expand a string literal into an array of characters. 3435 // 3436 // FIXME: This is inefficient; we should probably introduce something similar 3437 // to the LLVM ConstantDataArray to make this cheaper. 3438 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3439 APValue &Result, 3440 QualType AllocType = QualType()) { 3441 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3442 AllocType.isNull() ? S->getType() : AllocType); 3443 assert(CAT && "string literal isn't an array"); 3444 QualType CharType = CAT->getElementType(); 3445 assert(CharType->isIntegerType() && "unexpected character type"); 3446 3447 unsigned Elts = CAT->getSize().getZExtValue(); 3448 Result = APValue(APValue::UninitArray(), 3449 std::min(S->getLength(), Elts), Elts); 3450 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3451 CharType->isUnsignedIntegerType()); 3452 if (Result.hasArrayFiller()) 3453 Result.getArrayFiller() = APValue(Value); 3454 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3455 Value = S->getCodeUnit(I); 3456 Result.getArrayInitializedElt(I) = APValue(Value); 3457 } 3458 } 3459 3460 // Expand an array so that it has more than Index filled elements. 3461 static void expandArray(APValue &Array, unsigned Index) { 3462 unsigned Size = Array.getArraySize(); 3463 assert(Index < Size); 3464 3465 // Always at least double the number of elements for which we store a value. 3466 unsigned OldElts = Array.getArrayInitializedElts(); 3467 unsigned NewElts = std::max(Index+1, OldElts * 2); 3468 NewElts = std::min(Size, std::max(NewElts, 8u)); 3469 3470 // Copy the data across. 3471 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3472 for (unsigned I = 0; I != OldElts; ++I) 3473 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3474 for (unsigned I = OldElts; I != NewElts; ++I) 3475 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3476 if (NewValue.hasArrayFiller()) 3477 NewValue.getArrayFiller() = Array.getArrayFiller(); 3478 Array.swap(NewValue); 3479 } 3480 3481 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3482 /// conversion. If it's of class type, we may assume that the copy operation 3483 /// is trivial. Note that this is never true for a union type with fields 3484 /// (because the copy always "reads" the active member) and always true for 3485 /// a non-class type. 3486 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3487 static bool isReadByLvalueToRvalueConversion(QualType T) { 3488 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3489 return !RD || isReadByLvalueToRvalueConversion(RD); 3490 } 3491 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3492 // FIXME: A trivial copy of a union copies the object representation, even if 3493 // the union is empty. 3494 if (RD->isUnion()) 3495 return !RD->field_empty(); 3496 if (RD->isEmpty()) 3497 return false; 3498 3499 for (auto *Field : RD->fields()) 3500 if (!Field->isUnnamedBitfield() && 3501 isReadByLvalueToRvalueConversion(Field->getType())) 3502 return true; 3503 3504 for (auto &BaseSpec : RD->bases()) 3505 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3506 return true; 3507 3508 return false; 3509 } 3510 3511 /// Diagnose an attempt to read from any unreadable field within the specified 3512 /// type, which might be a class type. 3513 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3514 QualType T) { 3515 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3516 if (!RD) 3517 return false; 3518 3519 if (!RD->hasMutableFields()) 3520 return false; 3521 3522 for (auto *Field : RD->fields()) { 3523 // If we're actually going to read this field in some way, then it can't 3524 // be mutable. If we're in a union, then assigning to a mutable field 3525 // (even an empty one) can change the active member, so that's not OK. 3526 // FIXME: Add core issue number for the union case. 3527 if (Field->isMutable() && 3528 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3529 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3530 Info.Note(Field->getLocation(), diag::note_declared_at); 3531 return true; 3532 } 3533 3534 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3535 return true; 3536 } 3537 3538 for (auto &BaseSpec : RD->bases()) 3539 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3540 return true; 3541 3542 // All mutable fields were empty, and thus not actually read. 3543 return false; 3544 } 3545 3546 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3547 APValue::LValueBase Base, 3548 bool MutableSubobject = false) { 3549 // A temporary or transient heap allocation we created. 3550 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3551 return true; 3552 3553 switch (Info.IsEvaluatingDecl) { 3554 case EvalInfo::EvaluatingDeclKind::None: 3555 return false; 3556 3557 case EvalInfo::EvaluatingDeclKind::Ctor: 3558 // The variable whose initializer we're evaluating. 3559 if (Info.EvaluatingDecl == Base) 3560 return true; 3561 3562 // A temporary lifetime-extended by the variable whose initializer we're 3563 // evaluating. 3564 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3565 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3566 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3567 return false; 3568 3569 case EvalInfo::EvaluatingDeclKind::Dtor: 3570 // C++2a [expr.const]p6: 3571 // [during constant destruction] the lifetime of a and its non-mutable 3572 // subobjects (but not its mutable subobjects) [are] considered to start 3573 // within e. 3574 if (MutableSubobject || Base != Info.EvaluatingDecl) 3575 return false; 3576 // FIXME: We can meaningfully extend this to cover non-const objects, but 3577 // we will need special handling: we should be able to access only 3578 // subobjects of such objects that are themselves declared const. 3579 QualType T = getType(Base); 3580 return T.isConstQualified() || T->isReferenceType(); 3581 } 3582 3583 llvm_unreachable("unknown evaluating decl kind"); 3584 } 3585 3586 namespace { 3587 /// A handle to a complete object (an object that is not a subobject of 3588 /// another object). 3589 struct CompleteObject { 3590 /// The identity of the object. 3591 APValue::LValueBase Base; 3592 /// The value of the complete object. 3593 APValue *Value; 3594 /// The type of the complete object. 3595 QualType Type; 3596 3597 CompleteObject() : Value(nullptr) {} 3598 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3599 : Base(Base), Value(Value), Type(Type) {} 3600 3601 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3602 // If this isn't a "real" access (eg, if it's just accessing the type 3603 // info), allow it. We assume the type doesn't change dynamically for 3604 // subobjects of constexpr objects (even though we'd hit UB here if it 3605 // did). FIXME: Is this right? 3606 if (!isAnyAccess(AK)) 3607 return true; 3608 3609 // In C++14 onwards, it is permitted to read a mutable member whose 3610 // lifetime began within the evaluation. 3611 // FIXME: Should we also allow this in C++11? 3612 if (!Info.getLangOpts().CPlusPlus14) 3613 return false; 3614 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3615 } 3616 3617 explicit operator bool() const { return !Type.isNull(); } 3618 }; 3619 } // end anonymous namespace 3620 3621 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3622 bool IsMutable = false) { 3623 // C++ [basic.type.qualifier]p1: 3624 // - A const object is an object of type const T or a non-mutable subobject 3625 // of a const object. 3626 if (ObjType.isConstQualified() && !IsMutable) 3627 SubobjType.addConst(); 3628 // - A volatile object is an object of type const T or a subobject of a 3629 // volatile object. 3630 if (ObjType.isVolatileQualified()) 3631 SubobjType.addVolatile(); 3632 return SubobjType; 3633 } 3634 3635 /// Find the designated sub-object of an rvalue. 3636 template<typename SubobjectHandler> 3637 typename SubobjectHandler::result_type 3638 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3639 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3640 if (Sub.Invalid) 3641 // A diagnostic will have already been produced. 3642 return handler.failed(); 3643 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3644 if (Info.getLangOpts().CPlusPlus11) 3645 Info.FFDiag(E, Sub.isOnePastTheEnd() 3646 ? diag::note_constexpr_access_past_end 3647 : diag::note_constexpr_access_unsized_array) 3648 << handler.AccessKind; 3649 else 3650 Info.FFDiag(E); 3651 return handler.failed(); 3652 } 3653 3654 APValue *O = Obj.Value; 3655 QualType ObjType = Obj.Type; 3656 const FieldDecl *LastField = nullptr; 3657 const FieldDecl *VolatileField = nullptr; 3658 3659 // Walk the designator's path to find the subobject. 3660 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3661 // Reading an indeterminate value is undefined, but assigning over one is OK. 3662 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3663 (O->isIndeterminate() && 3664 !isValidIndeterminateAccess(handler.AccessKind))) { 3665 if (!Info.checkingPotentialConstantExpression()) 3666 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3667 << handler.AccessKind << O->isIndeterminate(); 3668 return handler.failed(); 3669 } 3670 3671 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3672 // const and volatile semantics are not applied on an object under 3673 // {con,de}struction. 3674 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3675 ObjType->isRecordType() && 3676 Info.isEvaluatingCtorDtor( 3677 Obj.Base, 3678 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) != 3679 ConstructionPhase::None) { 3680 ObjType = Info.Ctx.getCanonicalType(ObjType); 3681 ObjType.removeLocalConst(); 3682 ObjType.removeLocalVolatile(); 3683 } 3684 3685 // If this is our last pass, check that the final object type is OK. 3686 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3687 // Accesses to volatile objects are prohibited. 3688 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3689 if (Info.getLangOpts().CPlusPlus) { 3690 int DiagKind; 3691 SourceLocation Loc; 3692 const NamedDecl *Decl = nullptr; 3693 if (VolatileField) { 3694 DiagKind = 2; 3695 Loc = VolatileField->getLocation(); 3696 Decl = VolatileField; 3697 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3698 DiagKind = 1; 3699 Loc = VD->getLocation(); 3700 Decl = VD; 3701 } else { 3702 DiagKind = 0; 3703 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3704 Loc = E->getExprLoc(); 3705 } 3706 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3707 << handler.AccessKind << DiagKind << Decl; 3708 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3709 } else { 3710 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3711 } 3712 return handler.failed(); 3713 } 3714 3715 // If we are reading an object of class type, there may still be more 3716 // things we need to check: if there are any mutable subobjects, we 3717 // cannot perform this read. (This only happens when performing a trivial 3718 // copy or assignment.) 3719 if (ObjType->isRecordType() && 3720 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3721 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3722 return handler.failed(); 3723 } 3724 3725 if (I == N) { 3726 if (!handler.found(*O, ObjType)) 3727 return false; 3728 3729 // If we modified a bit-field, truncate it to the right width. 3730 if (isModification(handler.AccessKind) && 3731 LastField && LastField->isBitField() && 3732 !truncateBitfieldValue(Info, E, *O, LastField)) 3733 return false; 3734 3735 return true; 3736 } 3737 3738 LastField = nullptr; 3739 if (ObjType->isArrayType()) { 3740 // Next subobject is an array element. 3741 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3742 assert(CAT && "vla in literal type?"); 3743 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3744 if (CAT->getSize().ule(Index)) { 3745 // Note, it should not be possible to form a pointer with a valid 3746 // designator which points more than one past the end of the array. 3747 if (Info.getLangOpts().CPlusPlus11) 3748 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3749 << handler.AccessKind; 3750 else 3751 Info.FFDiag(E); 3752 return handler.failed(); 3753 } 3754 3755 ObjType = CAT->getElementType(); 3756 3757 if (O->getArrayInitializedElts() > Index) 3758 O = &O->getArrayInitializedElt(Index); 3759 else if (!isRead(handler.AccessKind)) { 3760 expandArray(*O, Index); 3761 O = &O->getArrayInitializedElt(Index); 3762 } else 3763 O = &O->getArrayFiller(); 3764 } else if (ObjType->isAnyComplexType()) { 3765 // Next subobject is a complex number. 3766 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3767 if (Index > 1) { 3768 if (Info.getLangOpts().CPlusPlus11) 3769 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3770 << handler.AccessKind; 3771 else 3772 Info.FFDiag(E); 3773 return handler.failed(); 3774 } 3775 3776 ObjType = getSubobjectType( 3777 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3778 3779 assert(I == N - 1 && "extracting subobject of scalar?"); 3780 if (O->isComplexInt()) { 3781 return handler.found(Index ? O->getComplexIntImag() 3782 : O->getComplexIntReal(), ObjType); 3783 } else { 3784 assert(O->isComplexFloat()); 3785 return handler.found(Index ? O->getComplexFloatImag() 3786 : O->getComplexFloatReal(), ObjType); 3787 } 3788 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3789 if (Field->isMutable() && 3790 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3791 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3792 << handler.AccessKind << Field; 3793 Info.Note(Field->getLocation(), diag::note_declared_at); 3794 return handler.failed(); 3795 } 3796 3797 // Next subobject is a class, struct or union field. 3798 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3799 if (RD->isUnion()) { 3800 const FieldDecl *UnionField = O->getUnionField(); 3801 if (!UnionField || 3802 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3803 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3804 // Placement new onto an inactive union member makes it active. 3805 O->setUnion(Field, APValue()); 3806 } else { 3807 // FIXME: If O->getUnionValue() is absent, report that there's no 3808 // active union member rather than reporting the prior active union 3809 // member. We'll need to fix nullptr_t to not use APValue() as its 3810 // representation first. 3811 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3812 << handler.AccessKind << Field << !UnionField << UnionField; 3813 return handler.failed(); 3814 } 3815 } 3816 O = &O->getUnionValue(); 3817 } else 3818 O = &O->getStructField(Field->getFieldIndex()); 3819 3820 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3821 LastField = Field; 3822 if (Field->getType().isVolatileQualified()) 3823 VolatileField = Field; 3824 } else { 3825 // Next subobject is a base class. 3826 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3827 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3828 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3829 3830 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3831 } 3832 } 3833 } 3834 3835 namespace { 3836 struct ExtractSubobjectHandler { 3837 EvalInfo &Info; 3838 const Expr *E; 3839 APValue &Result; 3840 const AccessKinds AccessKind; 3841 3842 typedef bool result_type; 3843 bool failed() { return false; } 3844 bool found(APValue &Subobj, QualType SubobjType) { 3845 Result = Subobj; 3846 if (AccessKind == AK_ReadObjectRepresentation) 3847 return true; 3848 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3849 } 3850 bool found(APSInt &Value, QualType SubobjType) { 3851 Result = APValue(Value); 3852 return true; 3853 } 3854 bool found(APFloat &Value, QualType SubobjType) { 3855 Result = APValue(Value); 3856 return true; 3857 } 3858 }; 3859 } // end anonymous namespace 3860 3861 /// Extract the designated sub-object of an rvalue. 3862 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3863 const CompleteObject &Obj, 3864 const SubobjectDesignator &Sub, APValue &Result, 3865 AccessKinds AK = AK_Read) { 3866 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3867 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3868 return findSubobject(Info, E, Obj, Sub, Handler); 3869 } 3870 3871 namespace { 3872 struct ModifySubobjectHandler { 3873 EvalInfo &Info; 3874 APValue &NewVal; 3875 const Expr *E; 3876 3877 typedef bool result_type; 3878 static const AccessKinds AccessKind = AK_Assign; 3879 3880 bool checkConst(QualType QT) { 3881 // Assigning to a const object has undefined behavior. 3882 if (QT.isConstQualified()) { 3883 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3884 return false; 3885 } 3886 return true; 3887 } 3888 3889 bool failed() { return false; } 3890 bool found(APValue &Subobj, QualType SubobjType) { 3891 if (!checkConst(SubobjType)) 3892 return false; 3893 // We've been given ownership of NewVal, so just swap it in. 3894 Subobj.swap(NewVal); 3895 return true; 3896 } 3897 bool found(APSInt &Value, QualType SubobjType) { 3898 if (!checkConst(SubobjType)) 3899 return false; 3900 if (!NewVal.isInt()) { 3901 // Maybe trying to write a cast pointer value into a complex? 3902 Info.FFDiag(E); 3903 return false; 3904 } 3905 Value = NewVal.getInt(); 3906 return true; 3907 } 3908 bool found(APFloat &Value, QualType SubobjType) { 3909 if (!checkConst(SubobjType)) 3910 return false; 3911 Value = NewVal.getFloat(); 3912 return true; 3913 } 3914 }; 3915 } // end anonymous namespace 3916 3917 const AccessKinds ModifySubobjectHandler::AccessKind; 3918 3919 /// Update the designated sub-object of an rvalue to the given value. 3920 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3921 const CompleteObject &Obj, 3922 const SubobjectDesignator &Sub, 3923 APValue &NewVal) { 3924 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3925 return findSubobject(Info, E, Obj, Sub, Handler); 3926 } 3927 3928 /// Find the position where two subobject designators diverge, or equivalently 3929 /// the length of the common initial subsequence. 3930 static unsigned FindDesignatorMismatch(QualType ObjType, 3931 const SubobjectDesignator &A, 3932 const SubobjectDesignator &B, 3933 bool &WasArrayIndex) { 3934 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3935 for (/**/; I != N; ++I) { 3936 if (!ObjType.isNull() && 3937 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3938 // Next subobject is an array element. 3939 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3940 WasArrayIndex = true; 3941 return I; 3942 } 3943 if (ObjType->isAnyComplexType()) 3944 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3945 else 3946 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3947 } else { 3948 if (A.Entries[I].getAsBaseOrMember() != 3949 B.Entries[I].getAsBaseOrMember()) { 3950 WasArrayIndex = false; 3951 return I; 3952 } 3953 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3954 // Next subobject is a field. 3955 ObjType = FD->getType(); 3956 else 3957 // Next subobject is a base class. 3958 ObjType = QualType(); 3959 } 3960 } 3961 WasArrayIndex = false; 3962 return I; 3963 } 3964 3965 /// Determine whether the given subobject designators refer to elements of the 3966 /// same array object. 3967 static bool AreElementsOfSameArray(QualType ObjType, 3968 const SubobjectDesignator &A, 3969 const SubobjectDesignator &B) { 3970 if (A.Entries.size() != B.Entries.size()) 3971 return false; 3972 3973 bool IsArray = A.MostDerivedIsArrayElement; 3974 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3975 // A is a subobject of the array element. 3976 return false; 3977 3978 // If A (and B) designates an array element, the last entry will be the array 3979 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3980 // of length 1' case, and the entire path must match. 3981 bool WasArrayIndex; 3982 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3983 return CommonLength >= A.Entries.size() - IsArray; 3984 } 3985 3986 /// Find the complete object to which an LValue refers. 3987 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3988 AccessKinds AK, const LValue &LVal, 3989 QualType LValType) { 3990 if (LVal.InvalidBase) { 3991 Info.FFDiag(E); 3992 return CompleteObject(); 3993 } 3994 3995 if (!LVal.Base) { 3996 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3997 return CompleteObject(); 3998 } 3999 4000 CallStackFrame *Frame = nullptr; 4001 unsigned Depth = 0; 4002 if (LVal.getLValueCallIndex()) { 4003 std::tie(Frame, Depth) = 4004 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 4005 if (!Frame) { 4006 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 4007 << AK << LVal.Base.is<const ValueDecl*>(); 4008 NoteLValueLocation(Info, LVal.Base); 4009 return CompleteObject(); 4010 } 4011 } 4012 4013 bool IsAccess = isAnyAccess(AK); 4014 4015 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 4016 // is not a constant expression (even if the object is non-volatile). We also 4017 // apply this rule to C++98, in order to conform to the expected 'volatile' 4018 // semantics. 4019 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 4020 if (Info.getLangOpts().CPlusPlus) 4021 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 4022 << AK << LValType; 4023 else 4024 Info.FFDiag(E); 4025 return CompleteObject(); 4026 } 4027 4028 // Compute value storage location and type of base object. 4029 APValue *BaseVal = nullptr; 4030 QualType BaseType = getType(LVal.Base); 4031 4032 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 4033 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4034 // This is the object whose initializer we're evaluating, so its lifetime 4035 // started in the current evaluation. 4036 BaseVal = Info.EvaluatingDeclValue; 4037 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4038 // Allow reading from a GUID declaration. 4039 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4040 if (isModification(AK)) { 4041 // All the remaining cases do not permit modification of the object. 4042 Info.FFDiag(E, diag::note_constexpr_modify_global); 4043 return CompleteObject(); 4044 } 4045 APValue &V = GD->getAsAPValue(); 4046 if (V.isAbsent()) { 4047 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4048 << GD->getType(); 4049 return CompleteObject(); 4050 } 4051 return CompleteObject(LVal.Base, &V, GD->getType()); 4052 } 4053 4054 // Allow reading the APValue from an UnnamedGlobalConstantDecl. 4055 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) { 4056 if (isModification(AK)) { 4057 Info.FFDiag(E, diag::note_constexpr_modify_global); 4058 return CompleteObject(); 4059 } 4060 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()), 4061 GCD->getType()); 4062 } 4063 4064 // Allow reading from template parameter objects. 4065 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4066 if (isModification(AK)) { 4067 Info.FFDiag(E, diag::note_constexpr_modify_global); 4068 return CompleteObject(); 4069 } 4070 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4071 TPO->getType()); 4072 } 4073 4074 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4075 // In C++11, constexpr, non-volatile variables initialized with constant 4076 // expressions are constant expressions too. Inside constexpr functions, 4077 // parameters are constant expressions even if they're non-const. 4078 // In C++1y, objects local to a constant expression (those with a Frame) are 4079 // both readable and writable inside constant expressions. 4080 // In C, such things can also be folded, although they are not ICEs. 4081 const VarDecl *VD = dyn_cast<VarDecl>(D); 4082 if (VD) { 4083 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4084 VD = VDef; 4085 } 4086 if (!VD || VD->isInvalidDecl()) { 4087 Info.FFDiag(E); 4088 return CompleteObject(); 4089 } 4090 4091 bool IsConstant = BaseType.isConstant(Info.Ctx); 4092 4093 // Unless we're looking at a local variable or argument in a constexpr call, 4094 // the variable we're reading must be const. 4095 if (!Frame) { 4096 if (IsAccess && isa<ParmVarDecl>(VD)) { 4097 // Access of a parameter that's not associated with a frame isn't going 4098 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4099 // suitable diagnostic. 4100 } else if (Info.getLangOpts().CPlusPlus14 && 4101 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4102 // OK, we can read and modify an object if we're in the process of 4103 // evaluating its initializer, because its lifetime began in this 4104 // evaluation. 4105 } else if (isModification(AK)) { 4106 // All the remaining cases do not permit modification of the object. 4107 Info.FFDiag(E, diag::note_constexpr_modify_global); 4108 return CompleteObject(); 4109 } else if (VD->isConstexpr()) { 4110 // OK, we can read this variable. 4111 } else if (BaseType->isIntegralOrEnumerationType()) { 4112 if (!IsConstant) { 4113 if (!IsAccess) 4114 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4115 if (Info.getLangOpts().CPlusPlus) { 4116 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4117 Info.Note(VD->getLocation(), diag::note_declared_at); 4118 } else { 4119 Info.FFDiag(E); 4120 } 4121 return CompleteObject(); 4122 } 4123 } else if (!IsAccess) { 4124 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4125 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4126 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4127 // This variable might end up being constexpr. Don't diagnose it yet. 4128 } else if (IsConstant) { 4129 // Keep evaluating to see what we can do. In particular, we support 4130 // folding of const floating-point types, in order to make static const 4131 // data members of such types (supported as an extension) more useful. 4132 if (Info.getLangOpts().CPlusPlus) { 4133 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4134 ? diag::note_constexpr_ltor_non_constexpr 4135 : diag::note_constexpr_ltor_non_integral, 1) 4136 << VD << BaseType; 4137 Info.Note(VD->getLocation(), diag::note_declared_at); 4138 } else { 4139 Info.CCEDiag(E); 4140 } 4141 } else { 4142 // Never allow reading a non-const value. 4143 if (Info.getLangOpts().CPlusPlus) { 4144 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4145 ? diag::note_constexpr_ltor_non_constexpr 4146 : diag::note_constexpr_ltor_non_integral, 1) 4147 << VD << BaseType; 4148 Info.Note(VD->getLocation(), diag::note_declared_at); 4149 } else { 4150 Info.FFDiag(E); 4151 } 4152 return CompleteObject(); 4153 } 4154 } 4155 4156 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4157 return CompleteObject(); 4158 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4159 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 4160 if (!Alloc) { 4161 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4162 return CompleteObject(); 4163 } 4164 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4165 LVal.Base.getDynamicAllocType()); 4166 } else { 4167 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4168 4169 if (!Frame) { 4170 if (const MaterializeTemporaryExpr *MTE = 4171 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4172 assert(MTE->getStorageDuration() == SD_Static && 4173 "should have a frame for a non-global materialized temporary"); 4174 4175 // C++20 [expr.const]p4: [DR2126] 4176 // An object or reference is usable in constant expressions if it is 4177 // - a temporary object of non-volatile const-qualified literal type 4178 // whose lifetime is extended to that of a variable that is usable 4179 // in constant expressions 4180 // 4181 // C++20 [expr.const]p5: 4182 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4183 // - a non-volatile glvalue that refers to an object that is usable 4184 // in constant expressions, or 4185 // - a non-volatile glvalue of literal type that refers to a 4186 // non-volatile object whose lifetime began within the evaluation 4187 // of E; 4188 // 4189 // C++11 misses the 'began within the evaluation of e' check and 4190 // instead allows all temporaries, including things like: 4191 // int &&r = 1; 4192 // int x = ++r; 4193 // constexpr int k = r; 4194 // Therefore we use the C++14-onwards rules in C++11 too. 4195 // 4196 // Note that temporaries whose lifetimes began while evaluating a 4197 // variable's constructor are not usable while evaluating the 4198 // corresponding destructor, not even if they're of const-qualified 4199 // types. 4200 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4201 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4202 if (!IsAccess) 4203 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4204 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4205 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4206 return CompleteObject(); 4207 } 4208 4209 BaseVal = MTE->getOrCreateValue(false); 4210 assert(BaseVal && "got reference to unevaluated temporary"); 4211 } else { 4212 if (!IsAccess) 4213 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4214 APValue Val; 4215 LVal.moveInto(Val); 4216 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4217 << AK 4218 << Val.getAsString(Info.Ctx, 4219 Info.Ctx.getLValueReferenceType(LValType)); 4220 NoteLValueLocation(Info, LVal.Base); 4221 return CompleteObject(); 4222 } 4223 } else { 4224 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4225 assert(BaseVal && "missing value for temporary"); 4226 } 4227 } 4228 4229 // In C++14, we can't safely access any mutable state when we might be 4230 // evaluating after an unmodeled side effect. Parameters are modeled as state 4231 // in the caller, but aren't visible once the call returns, so they can be 4232 // modified in a speculatively-evaluated call. 4233 // 4234 // FIXME: Not all local state is mutable. Allow local constant subobjects 4235 // to be read here (but take care with 'mutable' fields). 4236 unsigned VisibleDepth = Depth; 4237 if (llvm::isa_and_nonnull<ParmVarDecl>( 4238 LVal.Base.dyn_cast<const ValueDecl *>())) 4239 ++VisibleDepth; 4240 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4241 Info.EvalStatus.HasSideEffects) || 4242 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4243 return CompleteObject(); 4244 4245 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4246 } 4247 4248 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4249 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4250 /// glvalue referred to by an entity of reference type. 4251 /// 4252 /// \param Info - Information about the ongoing evaluation. 4253 /// \param Conv - The expression for which we are performing the conversion. 4254 /// Used for diagnostics. 4255 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4256 /// case of a non-class type). 4257 /// \param LVal - The glvalue on which we are attempting to perform this action. 4258 /// \param RVal - The produced value will be placed here. 4259 /// \param WantObjectRepresentation - If true, we're looking for the object 4260 /// representation rather than the value, and in particular, 4261 /// there is no requirement that the result be fully initialized. 4262 static bool 4263 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4264 const LValue &LVal, APValue &RVal, 4265 bool WantObjectRepresentation = false) { 4266 if (LVal.Designator.Invalid) 4267 return false; 4268 4269 // Check for special cases where there is no existing APValue to look at. 4270 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4271 4272 AccessKinds AK = 4273 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4274 4275 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4276 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4277 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4278 // initializer until now for such expressions. Such an expression can't be 4279 // an ICE in C, so this only matters for fold. 4280 if (Type.isVolatileQualified()) { 4281 Info.FFDiag(Conv); 4282 return false; 4283 } 4284 4285 APValue Lit; 4286 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4287 return false; 4288 4289 // According to GCC info page: 4290 // 4291 // 6.28 Compound Literals 4292 // 4293 // As an optimization, G++ sometimes gives array compound literals longer 4294 // lifetimes: when the array either appears outside a function or has a 4295 // const-qualified type. If foo and its initializer had elements of type 4296 // char *const rather than char *, or if foo were a global variable, the 4297 // array would have static storage duration. But it is probably safest 4298 // just to avoid the use of array compound literals in C++ code. 4299 // 4300 // Obey that rule by checking constness for converted array types. 4301 4302 QualType CLETy = CLE->getType(); 4303 if (CLETy->isArrayType() && !Type->isArrayType()) { 4304 if (!CLETy.isConstant(Info.Ctx)) { 4305 Info.FFDiag(Conv); 4306 Info.Note(CLE->getExprLoc(), diag::note_declared_at); 4307 return false; 4308 } 4309 } 4310 4311 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4312 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4313 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4314 // Special-case character extraction so we don't have to construct an 4315 // APValue for the whole string. 4316 assert(LVal.Designator.Entries.size() <= 1 && 4317 "Can only read characters from string literals"); 4318 if (LVal.Designator.Entries.empty()) { 4319 // Fail for now for LValue to RValue conversion of an array. 4320 // (This shouldn't show up in C/C++, but it could be triggered by a 4321 // weird EvaluateAsRValue call from a tool.) 4322 Info.FFDiag(Conv); 4323 return false; 4324 } 4325 if (LVal.Designator.isOnePastTheEnd()) { 4326 if (Info.getLangOpts().CPlusPlus11) 4327 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4328 else 4329 Info.FFDiag(Conv); 4330 return false; 4331 } 4332 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4333 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4334 return true; 4335 } 4336 } 4337 4338 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4339 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4340 } 4341 4342 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4343 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4344 QualType LValType, APValue &Val) { 4345 if (LVal.Designator.Invalid) 4346 return false; 4347 4348 if (!Info.getLangOpts().CPlusPlus14) { 4349 Info.FFDiag(E); 4350 return false; 4351 } 4352 4353 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4354 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4355 } 4356 4357 namespace { 4358 struct CompoundAssignSubobjectHandler { 4359 EvalInfo &Info; 4360 const CompoundAssignOperator *E; 4361 QualType PromotedLHSType; 4362 BinaryOperatorKind Opcode; 4363 const APValue &RHS; 4364 4365 static const AccessKinds AccessKind = AK_Assign; 4366 4367 typedef bool result_type; 4368 4369 bool checkConst(QualType QT) { 4370 // Assigning to a const object has undefined behavior. 4371 if (QT.isConstQualified()) { 4372 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4373 return false; 4374 } 4375 return true; 4376 } 4377 4378 bool failed() { return false; } 4379 bool found(APValue &Subobj, QualType SubobjType) { 4380 switch (Subobj.getKind()) { 4381 case APValue::Int: 4382 return found(Subobj.getInt(), SubobjType); 4383 case APValue::Float: 4384 return found(Subobj.getFloat(), SubobjType); 4385 case APValue::ComplexInt: 4386 case APValue::ComplexFloat: 4387 // FIXME: Implement complex compound assignment. 4388 Info.FFDiag(E); 4389 return false; 4390 case APValue::LValue: 4391 return foundPointer(Subobj, SubobjType); 4392 case APValue::Vector: 4393 return foundVector(Subobj, SubobjType); 4394 default: 4395 // FIXME: can this happen? 4396 Info.FFDiag(E); 4397 return false; 4398 } 4399 } 4400 4401 bool foundVector(APValue &Value, QualType SubobjType) { 4402 if (!checkConst(SubobjType)) 4403 return false; 4404 4405 if (!SubobjType->isVectorType()) { 4406 Info.FFDiag(E); 4407 return false; 4408 } 4409 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4410 } 4411 4412 bool found(APSInt &Value, QualType SubobjType) { 4413 if (!checkConst(SubobjType)) 4414 return false; 4415 4416 if (!SubobjType->isIntegerType()) { 4417 // We don't support compound assignment on integer-cast-to-pointer 4418 // values. 4419 Info.FFDiag(E); 4420 return false; 4421 } 4422 4423 if (RHS.isInt()) { 4424 APSInt LHS = 4425 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4426 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4427 return false; 4428 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4429 return true; 4430 } else if (RHS.isFloat()) { 4431 const FPOptions FPO = E->getFPFeaturesInEffect( 4432 Info.Ctx.getLangOpts()); 4433 APFloat FValue(0.0); 4434 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4435 PromotedLHSType, FValue) && 4436 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4437 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4438 Value); 4439 } 4440 4441 Info.FFDiag(E); 4442 return false; 4443 } 4444 bool found(APFloat &Value, QualType SubobjType) { 4445 return checkConst(SubobjType) && 4446 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4447 Value) && 4448 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4449 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4450 } 4451 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4452 if (!checkConst(SubobjType)) 4453 return false; 4454 4455 QualType PointeeType; 4456 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4457 PointeeType = PT->getPointeeType(); 4458 4459 if (PointeeType.isNull() || !RHS.isInt() || 4460 (Opcode != BO_Add && Opcode != BO_Sub)) { 4461 Info.FFDiag(E); 4462 return false; 4463 } 4464 4465 APSInt Offset = RHS.getInt(); 4466 if (Opcode == BO_Sub) 4467 negateAsSigned(Offset); 4468 4469 LValue LVal; 4470 LVal.setFrom(Info.Ctx, Subobj); 4471 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4472 return false; 4473 LVal.moveInto(Subobj); 4474 return true; 4475 } 4476 }; 4477 } // end anonymous namespace 4478 4479 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4480 4481 /// Perform a compound assignment of LVal <op>= RVal. 4482 static bool handleCompoundAssignment(EvalInfo &Info, 4483 const CompoundAssignOperator *E, 4484 const LValue &LVal, QualType LValType, 4485 QualType PromotedLValType, 4486 BinaryOperatorKind Opcode, 4487 const APValue &RVal) { 4488 if (LVal.Designator.Invalid) 4489 return false; 4490 4491 if (!Info.getLangOpts().CPlusPlus14) { 4492 Info.FFDiag(E); 4493 return false; 4494 } 4495 4496 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4497 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4498 RVal }; 4499 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4500 } 4501 4502 namespace { 4503 struct IncDecSubobjectHandler { 4504 EvalInfo &Info; 4505 const UnaryOperator *E; 4506 AccessKinds AccessKind; 4507 APValue *Old; 4508 4509 typedef bool result_type; 4510 4511 bool checkConst(QualType QT) { 4512 // Assigning to a const object has undefined behavior. 4513 if (QT.isConstQualified()) { 4514 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4515 return false; 4516 } 4517 return true; 4518 } 4519 4520 bool failed() { return false; } 4521 bool found(APValue &Subobj, QualType SubobjType) { 4522 // Stash the old value. Also clear Old, so we don't clobber it later 4523 // if we're post-incrementing a complex. 4524 if (Old) { 4525 *Old = Subobj; 4526 Old = nullptr; 4527 } 4528 4529 switch (Subobj.getKind()) { 4530 case APValue::Int: 4531 return found(Subobj.getInt(), SubobjType); 4532 case APValue::Float: 4533 return found(Subobj.getFloat(), SubobjType); 4534 case APValue::ComplexInt: 4535 return found(Subobj.getComplexIntReal(), 4536 SubobjType->castAs<ComplexType>()->getElementType() 4537 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4538 case APValue::ComplexFloat: 4539 return found(Subobj.getComplexFloatReal(), 4540 SubobjType->castAs<ComplexType>()->getElementType() 4541 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4542 case APValue::LValue: 4543 return foundPointer(Subobj, SubobjType); 4544 default: 4545 // FIXME: can this happen? 4546 Info.FFDiag(E); 4547 return false; 4548 } 4549 } 4550 bool found(APSInt &Value, QualType SubobjType) { 4551 if (!checkConst(SubobjType)) 4552 return false; 4553 4554 if (!SubobjType->isIntegerType()) { 4555 // We don't support increment / decrement on integer-cast-to-pointer 4556 // values. 4557 Info.FFDiag(E); 4558 return false; 4559 } 4560 4561 if (Old) *Old = APValue(Value); 4562 4563 // bool arithmetic promotes to int, and the conversion back to bool 4564 // doesn't reduce mod 2^n, so special-case it. 4565 if (SubobjType->isBooleanType()) { 4566 if (AccessKind == AK_Increment) 4567 Value = 1; 4568 else 4569 Value = !Value; 4570 return true; 4571 } 4572 4573 bool WasNegative = Value.isNegative(); 4574 if (AccessKind == AK_Increment) { 4575 ++Value; 4576 4577 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4578 APSInt ActualValue(Value, /*IsUnsigned*/true); 4579 return HandleOverflow(Info, E, ActualValue, SubobjType); 4580 } 4581 } else { 4582 --Value; 4583 4584 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4585 unsigned BitWidth = Value.getBitWidth(); 4586 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4587 ActualValue.setBit(BitWidth); 4588 return HandleOverflow(Info, E, ActualValue, SubobjType); 4589 } 4590 } 4591 return true; 4592 } 4593 bool found(APFloat &Value, QualType SubobjType) { 4594 if (!checkConst(SubobjType)) 4595 return false; 4596 4597 if (Old) *Old = APValue(Value); 4598 4599 APFloat One(Value.getSemantics(), 1); 4600 if (AccessKind == AK_Increment) 4601 Value.add(One, APFloat::rmNearestTiesToEven); 4602 else 4603 Value.subtract(One, APFloat::rmNearestTiesToEven); 4604 return true; 4605 } 4606 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4607 if (!checkConst(SubobjType)) 4608 return false; 4609 4610 QualType PointeeType; 4611 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4612 PointeeType = PT->getPointeeType(); 4613 else { 4614 Info.FFDiag(E); 4615 return false; 4616 } 4617 4618 LValue LVal; 4619 LVal.setFrom(Info.Ctx, Subobj); 4620 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4621 AccessKind == AK_Increment ? 1 : -1)) 4622 return false; 4623 LVal.moveInto(Subobj); 4624 return true; 4625 } 4626 }; 4627 } // end anonymous namespace 4628 4629 /// Perform an increment or decrement on LVal. 4630 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4631 QualType LValType, bool IsIncrement, APValue *Old) { 4632 if (LVal.Designator.Invalid) 4633 return false; 4634 4635 if (!Info.getLangOpts().CPlusPlus14) { 4636 Info.FFDiag(E); 4637 return false; 4638 } 4639 4640 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4641 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4642 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4643 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4644 } 4645 4646 /// Build an lvalue for the object argument of a member function call. 4647 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4648 LValue &This) { 4649 if (Object->getType()->isPointerType() && Object->isPRValue()) 4650 return EvaluatePointer(Object, This, Info); 4651 4652 if (Object->isGLValue()) 4653 return EvaluateLValue(Object, This, Info); 4654 4655 if (Object->getType()->isLiteralType(Info.Ctx)) 4656 return EvaluateTemporary(Object, This, Info); 4657 4658 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4659 return false; 4660 } 4661 4662 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4663 /// lvalue referring to the result. 4664 /// 4665 /// \param Info - Information about the ongoing evaluation. 4666 /// \param LV - An lvalue referring to the base of the member pointer. 4667 /// \param RHS - The member pointer expression. 4668 /// \param IncludeMember - Specifies whether the member itself is included in 4669 /// the resulting LValue subobject designator. This is not possible when 4670 /// creating a bound member function. 4671 /// \return The field or method declaration to which the member pointer refers, 4672 /// or 0 if evaluation fails. 4673 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4674 QualType LVType, 4675 LValue &LV, 4676 const Expr *RHS, 4677 bool IncludeMember = true) { 4678 MemberPtr MemPtr; 4679 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4680 return nullptr; 4681 4682 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4683 // member value, the behavior is undefined. 4684 if (!MemPtr.getDecl()) { 4685 // FIXME: Specific diagnostic. 4686 Info.FFDiag(RHS); 4687 return nullptr; 4688 } 4689 4690 if (MemPtr.isDerivedMember()) { 4691 // This is a member of some derived class. Truncate LV appropriately. 4692 // The end of the derived-to-base path for the base object must match the 4693 // derived-to-base path for the member pointer. 4694 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4695 LV.Designator.Entries.size()) { 4696 Info.FFDiag(RHS); 4697 return nullptr; 4698 } 4699 unsigned PathLengthToMember = 4700 LV.Designator.Entries.size() - MemPtr.Path.size(); 4701 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4702 const CXXRecordDecl *LVDecl = getAsBaseClass( 4703 LV.Designator.Entries[PathLengthToMember + I]); 4704 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4705 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4706 Info.FFDiag(RHS); 4707 return nullptr; 4708 } 4709 } 4710 4711 // Truncate the lvalue to the appropriate derived class. 4712 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4713 PathLengthToMember)) 4714 return nullptr; 4715 } else if (!MemPtr.Path.empty()) { 4716 // Extend the LValue path with the member pointer's path. 4717 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4718 MemPtr.Path.size() + IncludeMember); 4719 4720 // Walk down to the appropriate base class. 4721 if (const PointerType *PT = LVType->getAs<PointerType>()) 4722 LVType = PT->getPointeeType(); 4723 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4724 assert(RD && "member pointer access on non-class-type expression"); 4725 // The first class in the path is that of the lvalue. 4726 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4727 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4728 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4729 return nullptr; 4730 RD = Base; 4731 } 4732 // Finally cast to the class containing the member. 4733 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4734 MemPtr.getContainingRecord())) 4735 return nullptr; 4736 } 4737 4738 // Add the member. Note that we cannot build bound member functions here. 4739 if (IncludeMember) { 4740 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4741 if (!HandleLValueMember(Info, RHS, LV, FD)) 4742 return nullptr; 4743 } else if (const IndirectFieldDecl *IFD = 4744 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4745 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4746 return nullptr; 4747 } else { 4748 llvm_unreachable("can't construct reference to bound member function"); 4749 } 4750 } 4751 4752 return MemPtr.getDecl(); 4753 } 4754 4755 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4756 const BinaryOperator *BO, 4757 LValue &LV, 4758 bool IncludeMember = true) { 4759 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4760 4761 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4762 if (Info.noteFailure()) { 4763 MemberPtr MemPtr; 4764 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4765 } 4766 return nullptr; 4767 } 4768 4769 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4770 BO->getRHS(), IncludeMember); 4771 } 4772 4773 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4774 /// the provided lvalue, which currently refers to the base object. 4775 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4776 LValue &Result) { 4777 SubobjectDesignator &D = Result.Designator; 4778 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4779 return false; 4780 4781 QualType TargetQT = E->getType(); 4782 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4783 TargetQT = PT->getPointeeType(); 4784 4785 // Check this cast lands within the final derived-to-base subobject path. 4786 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4787 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4788 << D.MostDerivedType << TargetQT; 4789 return false; 4790 } 4791 4792 // Check the type of the final cast. We don't need to check the path, 4793 // since a cast can only be formed if the path is unique. 4794 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4795 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4796 const CXXRecordDecl *FinalType; 4797 if (NewEntriesSize == D.MostDerivedPathLength) 4798 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4799 else 4800 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4801 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4802 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4803 << D.MostDerivedType << TargetQT; 4804 return false; 4805 } 4806 4807 // Truncate the lvalue to the appropriate derived class. 4808 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4809 } 4810 4811 /// Get the value to use for a default-initialized object of type T. 4812 /// Return false if it encounters something invalid. 4813 static bool getDefaultInitValue(QualType T, APValue &Result) { 4814 bool Success = true; 4815 if (auto *RD = T->getAsCXXRecordDecl()) { 4816 if (RD->isInvalidDecl()) { 4817 Result = APValue(); 4818 return false; 4819 } 4820 if (RD->isUnion()) { 4821 Result = APValue((const FieldDecl *)nullptr); 4822 return true; 4823 } 4824 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4825 std::distance(RD->field_begin(), RD->field_end())); 4826 4827 unsigned Index = 0; 4828 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4829 End = RD->bases_end(); 4830 I != End; ++I, ++Index) 4831 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4832 4833 for (const auto *I : RD->fields()) { 4834 if (I->isUnnamedBitfield()) 4835 continue; 4836 Success &= getDefaultInitValue(I->getType(), 4837 Result.getStructField(I->getFieldIndex())); 4838 } 4839 return Success; 4840 } 4841 4842 if (auto *AT = 4843 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4844 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4845 if (Result.hasArrayFiller()) 4846 Success &= 4847 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4848 4849 return Success; 4850 } 4851 4852 Result = APValue::IndeterminateValue(); 4853 return true; 4854 } 4855 4856 namespace { 4857 enum EvalStmtResult { 4858 /// Evaluation failed. 4859 ESR_Failed, 4860 /// Hit a 'return' statement. 4861 ESR_Returned, 4862 /// Evaluation succeeded. 4863 ESR_Succeeded, 4864 /// Hit a 'continue' statement. 4865 ESR_Continue, 4866 /// Hit a 'break' statement. 4867 ESR_Break, 4868 /// Still scanning for 'case' or 'default' statement. 4869 ESR_CaseNotFound 4870 }; 4871 } 4872 4873 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4874 if (VD->isInvalidDecl()) 4875 return false; 4876 // We don't need to evaluate the initializer for a static local. 4877 if (!VD->hasLocalStorage()) 4878 return true; 4879 4880 LValue Result; 4881 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4882 ScopeKind::Block, Result); 4883 4884 const Expr *InitE = VD->getInit(); 4885 if (!InitE) { 4886 if (VD->getType()->isDependentType()) 4887 return Info.noteSideEffect(); 4888 return getDefaultInitValue(VD->getType(), Val); 4889 } 4890 if (InitE->isValueDependent()) 4891 return false; 4892 4893 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4894 // Wipe out any partially-computed value, to allow tracking that this 4895 // evaluation failed. 4896 Val = APValue(); 4897 return false; 4898 } 4899 4900 return true; 4901 } 4902 4903 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4904 bool OK = true; 4905 4906 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4907 OK &= EvaluateVarDecl(Info, VD); 4908 4909 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4910 for (auto *BD : DD->bindings()) 4911 if (auto *VD = BD->getHoldingVar()) 4912 OK &= EvaluateDecl(Info, VD); 4913 4914 return OK; 4915 } 4916 4917 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4918 assert(E->isValueDependent()); 4919 if (Info.noteSideEffect()) 4920 return true; 4921 assert(E->containsErrors() && "valid value-dependent expression should never " 4922 "reach invalid code path."); 4923 return false; 4924 } 4925 4926 /// Evaluate a condition (either a variable declaration or an expression). 4927 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4928 const Expr *Cond, bool &Result) { 4929 if (Cond->isValueDependent()) 4930 return false; 4931 FullExpressionRAII Scope(Info); 4932 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4933 return false; 4934 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4935 return false; 4936 return Scope.destroy(); 4937 } 4938 4939 namespace { 4940 /// A location where the result (returned value) of evaluating a 4941 /// statement should be stored. 4942 struct StmtResult { 4943 /// The APValue that should be filled in with the returned value. 4944 APValue &Value; 4945 /// The location containing the result, if any (used to support RVO). 4946 const LValue *Slot; 4947 }; 4948 4949 struct TempVersionRAII { 4950 CallStackFrame &Frame; 4951 4952 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4953 Frame.pushTempVersion(); 4954 } 4955 4956 ~TempVersionRAII() { 4957 Frame.popTempVersion(); 4958 } 4959 }; 4960 4961 } 4962 4963 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4964 const Stmt *S, 4965 const SwitchCase *SC = nullptr); 4966 4967 /// Evaluate the body of a loop, and translate the result as appropriate. 4968 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4969 const Stmt *Body, 4970 const SwitchCase *Case = nullptr) { 4971 BlockScopeRAII Scope(Info); 4972 4973 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4974 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4975 ESR = ESR_Failed; 4976 4977 switch (ESR) { 4978 case ESR_Break: 4979 return ESR_Succeeded; 4980 case ESR_Succeeded: 4981 case ESR_Continue: 4982 return ESR_Continue; 4983 case ESR_Failed: 4984 case ESR_Returned: 4985 case ESR_CaseNotFound: 4986 return ESR; 4987 } 4988 llvm_unreachable("Invalid EvalStmtResult!"); 4989 } 4990 4991 /// Evaluate a switch statement. 4992 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4993 const SwitchStmt *SS) { 4994 BlockScopeRAII Scope(Info); 4995 4996 // Evaluate the switch condition. 4997 APSInt Value; 4998 { 4999 if (const Stmt *Init = SS->getInit()) { 5000 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5001 if (ESR != ESR_Succeeded) { 5002 if (ESR != ESR_Failed && !Scope.destroy()) 5003 ESR = ESR_Failed; 5004 return ESR; 5005 } 5006 } 5007 5008 FullExpressionRAII CondScope(Info); 5009 if (SS->getConditionVariable() && 5010 !EvaluateDecl(Info, SS->getConditionVariable())) 5011 return ESR_Failed; 5012 if (SS->getCond()->isValueDependent()) { 5013 // We don't know what the value is, and which branch should jump to. 5014 EvaluateDependentExpr(SS->getCond(), Info); 5015 return ESR_Failed; 5016 } 5017 if (!EvaluateInteger(SS->getCond(), Value, Info)) 5018 return ESR_Failed; 5019 5020 if (!CondScope.destroy()) 5021 return ESR_Failed; 5022 } 5023 5024 // Find the switch case corresponding to the value of the condition. 5025 // FIXME: Cache this lookup. 5026 const SwitchCase *Found = nullptr; 5027 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 5028 SC = SC->getNextSwitchCase()) { 5029 if (isa<DefaultStmt>(SC)) { 5030 Found = SC; 5031 continue; 5032 } 5033 5034 const CaseStmt *CS = cast<CaseStmt>(SC); 5035 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 5036 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 5037 : LHS; 5038 if (LHS <= Value && Value <= RHS) { 5039 Found = SC; 5040 break; 5041 } 5042 } 5043 5044 if (!Found) 5045 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5046 5047 // Search the switch body for the switch case and evaluate it from there. 5048 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 5049 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 5050 return ESR_Failed; 5051 5052 switch (ESR) { 5053 case ESR_Break: 5054 return ESR_Succeeded; 5055 case ESR_Succeeded: 5056 case ESR_Continue: 5057 case ESR_Failed: 5058 case ESR_Returned: 5059 return ESR; 5060 case ESR_CaseNotFound: 5061 // This can only happen if the switch case is nested within a statement 5062 // expression. We have no intention of supporting that. 5063 Info.FFDiag(Found->getBeginLoc(), 5064 diag::note_constexpr_stmt_expr_unsupported); 5065 return ESR_Failed; 5066 } 5067 llvm_unreachable("Invalid EvalStmtResult!"); 5068 } 5069 5070 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) { 5071 // An expression E is a core constant expression unless the evaluation of E 5072 // would evaluate one of the following: [C++23] - a control flow that passes 5073 // through a declaration of a variable with static or thread storage duration 5074 // unless that variable is usable in constant expressions. 5075 if (VD->isLocalVarDecl() && VD->isStaticLocal() && 5076 !VD->isUsableInConstantExpressions(Info.Ctx)) { 5077 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local) 5078 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD; 5079 return false; 5080 } 5081 return true; 5082 } 5083 5084 // Evaluate a statement. 5085 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 5086 const Stmt *S, const SwitchCase *Case) { 5087 if (!Info.nextStep(S)) 5088 return ESR_Failed; 5089 5090 // If we're hunting down a 'case' or 'default' label, recurse through 5091 // substatements until we hit the label. 5092 if (Case) { 5093 switch (S->getStmtClass()) { 5094 case Stmt::CompoundStmtClass: 5095 // FIXME: Precompute which substatement of a compound statement we 5096 // would jump to, and go straight there rather than performing a 5097 // linear scan each time. 5098 case Stmt::LabelStmtClass: 5099 case Stmt::AttributedStmtClass: 5100 case Stmt::DoStmtClass: 5101 break; 5102 5103 case Stmt::CaseStmtClass: 5104 case Stmt::DefaultStmtClass: 5105 if (Case == S) 5106 Case = nullptr; 5107 break; 5108 5109 case Stmt::IfStmtClass: { 5110 // FIXME: Precompute which side of an 'if' we would jump to, and go 5111 // straight there rather than scanning both sides. 5112 const IfStmt *IS = cast<IfStmt>(S); 5113 5114 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5115 // preceded by our switch label. 5116 BlockScopeRAII Scope(Info); 5117 5118 // Step into the init statement in case it brings an (uninitialized) 5119 // variable into scope. 5120 if (const Stmt *Init = IS->getInit()) { 5121 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5122 if (ESR != ESR_CaseNotFound) { 5123 assert(ESR != ESR_Succeeded); 5124 return ESR; 5125 } 5126 } 5127 5128 // Condition variable must be initialized if it exists. 5129 // FIXME: We can skip evaluating the body if there's a condition 5130 // variable, as there can't be any case labels within it. 5131 // (The same is true for 'for' statements.) 5132 5133 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5134 if (ESR == ESR_Failed) 5135 return ESR; 5136 if (ESR != ESR_CaseNotFound) 5137 return Scope.destroy() ? ESR : ESR_Failed; 5138 if (!IS->getElse()) 5139 return ESR_CaseNotFound; 5140 5141 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5142 if (ESR == ESR_Failed) 5143 return ESR; 5144 if (ESR != ESR_CaseNotFound) 5145 return Scope.destroy() ? ESR : ESR_Failed; 5146 return ESR_CaseNotFound; 5147 } 5148 5149 case Stmt::WhileStmtClass: { 5150 EvalStmtResult ESR = 5151 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5152 if (ESR != ESR_Continue) 5153 return ESR; 5154 break; 5155 } 5156 5157 case Stmt::ForStmtClass: { 5158 const ForStmt *FS = cast<ForStmt>(S); 5159 BlockScopeRAII Scope(Info); 5160 5161 // Step into the init statement in case it brings an (uninitialized) 5162 // variable into scope. 5163 if (const Stmt *Init = FS->getInit()) { 5164 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5165 if (ESR != ESR_CaseNotFound) { 5166 assert(ESR != ESR_Succeeded); 5167 return ESR; 5168 } 5169 } 5170 5171 EvalStmtResult ESR = 5172 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5173 if (ESR != ESR_Continue) 5174 return ESR; 5175 if (const auto *Inc = FS->getInc()) { 5176 if (Inc->isValueDependent()) { 5177 if (!EvaluateDependentExpr(Inc, Info)) 5178 return ESR_Failed; 5179 } else { 5180 FullExpressionRAII IncScope(Info); 5181 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5182 return ESR_Failed; 5183 } 5184 } 5185 break; 5186 } 5187 5188 case Stmt::DeclStmtClass: { 5189 // Start the lifetime of any uninitialized variables we encounter. They 5190 // might be used by the selected branch of the switch. 5191 const DeclStmt *DS = cast<DeclStmt>(S); 5192 for (const auto *D : DS->decls()) { 5193 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5194 if (!CheckLocalVariableDeclaration(Info, VD)) 5195 return ESR_Failed; 5196 if (VD->hasLocalStorage() && !VD->getInit()) 5197 if (!EvaluateVarDecl(Info, VD)) 5198 return ESR_Failed; 5199 // FIXME: If the variable has initialization that can't be jumped 5200 // over, bail out of any immediately-surrounding compound-statement 5201 // too. There can't be any case labels here. 5202 } 5203 } 5204 return ESR_CaseNotFound; 5205 } 5206 5207 default: 5208 return ESR_CaseNotFound; 5209 } 5210 } 5211 5212 switch (S->getStmtClass()) { 5213 default: 5214 if (const Expr *E = dyn_cast<Expr>(S)) { 5215 if (E->isValueDependent()) { 5216 if (!EvaluateDependentExpr(E, Info)) 5217 return ESR_Failed; 5218 } else { 5219 // Don't bother evaluating beyond an expression-statement which couldn't 5220 // be evaluated. 5221 // FIXME: Do we need the FullExpressionRAII object here? 5222 // VisitExprWithCleanups should create one when necessary. 5223 FullExpressionRAII Scope(Info); 5224 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5225 return ESR_Failed; 5226 } 5227 return ESR_Succeeded; 5228 } 5229 5230 Info.FFDiag(S->getBeginLoc()); 5231 return ESR_Failed; 5232 5233 case Stmt::NullStmtClass: 5234 return ESR_Succeeded; 5235 5236 case Stmt::DeclStmtClass: { 5237 const DeclStmt *DS = cast<DeclStmt>(S); 5238 for (const auto *D : DS->decls()) { 5239 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 5240 if (VD && !CheckLocalVariableDeclaration(Info, VD)) 5241 return ESR_Failed; 5242 // Each declaration initialization is its own full-expression. 5243 FullExpressionRAII Scope(Info); 5244 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5245 return ESR_Failed; 5246 if (!Scope.destroy()) 5247 return ESR_Failed; 5248 } 5249 return ESR_Succeeded; 5250 } 5251 5252 case Stmt::ReturnStmtClass: { 5253 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5254 FullExpressionRAII Scope(Info); 5255 if (RetExpr && RetExpr->isValueDependent()) { 5256 EvaluateDependentExpr(RetExpr, Info); 5257 // We know we returned, but we don't know what the value is. 5258 return ESR_Failed; 5259 } 5260 if (RetExpr && 5261 !(Result.Slot 5262 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5263 : Evaluate(Result.Value, Info, RetExpr))) 5264 return ESR_Failed; 5265 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5266 } 5267 5268 case Stmt::CompoundStmtClass: { 5269 BlockScopeRAII Scope(Info); 5270 5271 const CompoundStmt *CS = cast<CompoundStmt>(S); 5272 for (const auto *BI : CS->body()) { 5273 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5274 if (ESR == ESR_Succeeded) 5275 Case = nullptr; 5276 else if (ESR != ESR_CaseNotFound) { 5277 if (ESR != ESR_Failed && !Scope.destroy()) 5278 return ESR_Failed; 5279 return ESR; 5280 } 5281 } 5282 if (Case) 5283 return ESR_CaseNotFound; 5284 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5285 } 5286 5287 case Stmt::IfStmtClass: { 5288 const IfStmt *IS = cast<IfStmt>(S); 5289 5290 // Evaluate the condition, as either a var decl or as an expression. 5291 BlockScopeRAII Scope(Info); 5292 if (const Stmt *Init = IS->getInit()) { 5293 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5294 if (ESR != ESR_Succeeded) { 5295 if (ESR != ESR_Failed && !Scope.destroy()) 5296 return ESR_Failed; 5297 return ESR; 5298 } 5299 } 5300 bool Cond; 5301 if (IS->isConsteval()) { 5302 Cond = IS->isNonNegatedConsteval(); 5303 // If we are not in a constant context, if consteval should not evaluate 5304 // to true. 5305 if (!Info.InConstantContext) 5306 Cond = !Cond; 5307 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5308 Cond)) 5309 return ESR_Failed; 5310 5311 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5312 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5313 if (ESR != ESR_Succeeded) { 5314 if (ESR != ESR_Failed && !Scope.destroy()) 5315 return ESR_Failed; 5316 return ESR; 5317 } 5318 } 5319 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5320 } 5321 5322 case Stmt::WhileStmtClass: { 5323 const WhileStmt *WS = cast<WhileStmt>(S); 5324 while (true) { 5325 BlockScopeRAII Scope(Info); 5326 bool Continue; 5327 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5328 Continue)) 5329 return ESR_Failed; 5330 if (!Continue) 5331 break; 5332 5333 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5334 if (ESR != ESR_Continue) { 5335 if (ESR != ESR_Failed && !Scope.destroy()) 5336 return ESR_Failed; 5337 return ESR; 5338 } 5339 if (!Scope.destroy()) 5340 return ESR_Failed; 5341 } 5342 return ESR_Succeeded; 5343 } 5344 5345 case Stmt::DoStmtClass: { 5346 const DoStmt *DS = cast<DoStmt>(S); 5347 bool Continue; 5348 do { 5349 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5350 if (ESR != ESR_Continue) 5351 return ESR; 5352 Case = nullptr; 5353 5354 if (DS->getCond()->isValueDependent()) { 5355 EvaluateDependentExpr(DS->getCond(), Info); 5356 // Bailout as we don't know whether to keep going or terminate the loop. 5357 return ESR_Failed; 5358 } 5359 FullExpressionRAII CondScope(Info); 5360 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5361 !CondScope.destroy()) 5362 return ESR_Failed; 5363 } while (Continue); 5364 return ESR_Succeeded; 5365 } 5366 5367 case Stmt::ForStmtClass: { 5368 const ForStmt *FS = cast<ForStmt>(S); 5369 BlockScopeRAII ForScope(Info); 5370 if (FS->getInit()) { 5371 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5372 if (ESR != ESR_Succeeded) { 5373 if (ESR != ESR_Failed && !ForScope.destroy()) 5374 return ESR_Failed; 5375 return ESR; 5376 } 5377 } 5378 while (true) { 5379 BlockScopeRAII IterScope(Info); 5380 bool Continue = true; 5381 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5382 FS->getCond(), Continue)) 5383 return ESR_Failed; 5384 if (!Continue) 5385 break; 5386 5387 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5388 if (ESR != ESR_Continue) { 5389 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5390 return ESR_Failed; 5391 return ESR; 5392 } 5393 5394 if (const auto *Inc = FS->getInc()) { 5395 if (Inc->isValueDependent()) { 5396 if (!EvaluateDependentExpr(Inc, Info)) 5397 return ESR_Failed; 5398 } else { 5399 FullExpressionRAII IncScope(Info); 5400 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5401 return ESR_Failed; 5402 } 5403 } 5404 5405 if (!IterScope.destroy()) 5406 return ESR_Failed; 5407 } 5408 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5409 } 5410 5411 case Stmt::CXXForRangeStmtClass: { 5412 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5413 BlockScopeRAII Scope(Info); 5414 5415 // Evaluate the init-statement if present. 5416 if (FS->getInit()) { 5417 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5418 if (ESR != ESR_Succeeded) { 5419 if (ESR != ESR_Failed && !Scope.destroy()) 5420 return ESR_Failed; 5421 return ESR; 5422 } 5423 } 5424 5425 // Initialize the __range variable. 5426 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5427 if (ESR != ESR_Succeeded) { 5428 if (ESR != ESR_Failed && !Scope.destroy()) 5429 return ESR_Failed; 5430 return ESR; 5431 } 5432 5433 // In error-recovery cases it's possible to get here even if we failed to 5434 // synthesize the __begin and __end variables. 5435 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5436 return ESR_Failed; 5437 5438 // Create the __begin and __end iterators. 5439 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5440 if (ESR != ESR_Succeeded) { 5441 if (ESR != ESR_Failed && !Scope.destroy()) 5442 return ESR_Failed; 5443 return ESR; 5444 } 5445 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5446 if (ESR != ESR_Succeeded) { 5447 if (ESR != ESR_Failed && !Scope.destroy()) 5448 return ESR_Failed; 5449 return ESR; 5450 } 5451 5452 while (true) { 5453 // Condition: __begin != __end. 5454 { 5455 if (FS->getCond()->isValueDependent()) { 5456 EvaluateDependentExpr(FS->getCond(), Info); 5457 // We don't know whether to keep going or terminate the loop. 5458 return ESR_Failed; 5459 } 5460 bool Continue = true; 5461 FullExpressionRAII CondExpr(Info); 5462 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5463 return ESR_Failed; 5464 if (!Continue) 5465 break; 5466 } 5467 5468 // User's variable declaration, initialized by *__begin. 5469 BlockScopeRAII InnerScope(Info); 5470 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5471 if (ESR != ESR_Succeeded) { 5472 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5473 return ESR_Failed; 5474 return ESR; 5475 } 5476 5477 // Loop body. 5478 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5479 if (ESR != ESR_Continue) { 5480 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5481 return ESR_Failed; 5482 return ESR; 5483 } 5484 if (FS->getInc()->isValueDependent()) { 5485 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5486 return ESR_Failed; 5487 } else { 5488 // Increment: ++__begin 5489 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5490 return ESR_Failed; 5491 } 5492 5493 if (!InnerScope.destroy()) 5494 return ESR_Failed; 5495 } 5496 5497 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5498 } 5499 5500 case Stmt::SwitchStmtClass: 5501 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5502 5503 case Stmt::ContinueStmtClass: 5504 return ESR_Continue; 5505 5506 case Stmt::BreakStmtClass: 5507 return ESR_Break; 5508 5509 case Stmt::LabelStmtClass: 5510 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5511 5512 case Stmt::AttributedStmtClass: 5513 // As a general principle, C++11 attributes can be ignored without 5514 // any semantic impact. 5515 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5516 Case); 5517 5518 case Stmt::CaseStmtClass: 5519 case Stmt::DefaultStmtClass: 5520 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5521 case Stmt::CXXTryStmtClass: 5522 // Evaluate try blocks by evaluating all sub statements. 5523 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5524 } 5525 } 5526 5527 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5528 /// default constructor. If so, we'll fold it whether or not it's marked as 5529 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5530 /// so we need special handling. 5531 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5532 const CXXConstructorDecl *CD, 5533 bool IsValueInitialization) { 5534 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5535 return false; 5536 5537 // Value-initialization does not call a trivial default constructor, so such a 5538 // call is a core constant expression whether or not the constructor is 5539 // constexpr. 5540 if (!CD->isConstexpr() && !IsValueInitialization) { 5541 if (Info.getLangOpts().CPlusPlus11) { 5542 // FIXME: If DiagDecl is an implicitly-declared special member function, 5543 // we should be much more explicit about why it's not constexpr. 5544 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5545 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5546 Info.Note(CD->getLocation(), diag::note_declared_at); 5547 } else { 5548 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5549 } 5550 } 5551 return true; 5552 } 5553 5554 /// CheckConstexprFunction - Check that a function can be called in a constant 5555 /// expression. 5556 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5557 const FunctionDecl *Declaration, 5558 const FunctionDecl *Definition, 5559 const Stmt *Body) { 5560 // Potential constant expressions can contain calls to declared, but not yet 5561 // defined, constexpr functions. 5562 if (Info.checkingPotentialConstantExpression() && !Definition && 5563 Declaration->isConstexpr()) 5564 return false; 5565 5566 // Bail out if the function declaration itself is invalid. We will 5567 // have produced a relevant diagnostic while parsing it, so just 5568 // note the problematic sub-expression. 5569 if (Declaration->isInvalidDecl()) { 5570 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5571 return false; 5572 } 5573 5574 // DR1872: An instantiated virtual constexpr function can't be called in a 5575 // constant expression (prior to C++20). We can still constant-fold such a 5576 // call. 5577 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5578 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5579 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5580 5581 if (Definition && Definition->isInvalidDecl()) { 5582 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5583 return false; 5584 } 5585 5586 // Can we evaluate this function call? 5587 if (Definition && Definition->isConstexpr() && Body) 5588 return true; 5589 5590 if (Info.getLangOpts().CPlusPlus11) { 5591 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5592 5593 // If this function is not constexpr because it is an inherited 5594 // non-constexpr constructor, diagnose that directly. 5595 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5596 if (CD && CD->isInheritingConstructor()) { 5597 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5598 if (!Inherited->isConstexpr()) 5599 DiagDecl = CD = Inherited; 5600 } 5601 5602 // FIXME: If DiagDecl is an implicitly-declared special member function 5603 // or an inheriting constructor, we should be much more explicit about why 5604 // it's not constexpr. 5605 if (CD && CD->isInheritingConstructor()) 5606 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5607 << CD->getInheritedConstructor().getConstructor()->getParent(); 5608 else 5609 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5610 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5611 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5612 } else { 5613 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5614 } 5615 return false; 5616 } 5617 5618 namespace { 5619 struct CheckDynamicTypeHandler { 5620 AccessKinds AccessKind; 5621 typedef bool result_type; 5622 bool failed() { return false; } 5623 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5624 bool found(APSInt &Value, QualType SubobjType) { return true; } 5625 bool found(APFloat &Value, QualType SubobjType) { return true; } 5626 }; 5627 } // end anonymous namespace 5628 5629 /// Check that we can access the notional vptr of an object / determine its 5630 /// dynamic type. 5631 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5632 AccessKinds AK, bool Polymorphic) { 5633 if (This.Designator.Invalid) 5634 return false; 5635 5636 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5637 5638 if (!Obj) 5639 return false; 5640 5641 if (!Obj.Value) { 5642 // The object is not usable in constant expressions, so we can't inspect 5643 // its value to see if it's in-lifetime or what the active union members 5644 // are. We can still check for a one-past-the-end lvalue. 5645 if (This.Designator.isOnePastTheEnd() || 5646 This.Designator.isMostDerivedAnUnsizedArray()) { 5647 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5648 ? diag::note_constexpr_access_past_end 5649 : diag::note_constexpr_access_unsized_array) 5650 << AK; 5651 return false; 5652 } else if (Polymorphic) { 5653 // Conservatively refuse to perform a polymorphic operation if we would 5654 // not be able to read a notional 'vptr' value. 5655 APValue Val; 5656 This.moveInto(Val); 5657 QualType StarThisType = 5658 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5659 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5660 << AK << Val.getAsString(Info.Ctx, StarThisType); 5661 return false; 5662 } 5663 return true; 5664 } 5665 5666 CheckDynamicTypeHandler Handler{AK}; 5667 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5668 } 5669 5670 /// Check that the pointee of the 'this' pointer in a member function call is 5671 /// either within its lifetime or in its period of construction or destruction. 5672 static bool 5673 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5674 const LValue &This, 5675 const CXXMethodDecl *NamedMember) { 5676 return checkDynamicType( 5677 Info, E, This, 5678 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5679 } 5680 5681 struct DynamicType { 5682 /// The dynamic class type of the object. 5683 const CXXRecordDecl *Type; 5684 /// The corresponding path length in the lvalue. 5685 unsigned PathLength; 5686 }; 5687 5688 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5689 unsigned PathLength) { 5690 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5691 Designator.Entries.size() && "invalid path length"); 5692 return (PathLength == Designator.MostDerivedPathLength) 5693 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5694 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5695 } 5696 5697 /// Determine the dynamic type of an object. 5698 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info, 5699 const Expr *E, 5700 LValue &This, 5701 AccessKinds AK) { 5702 // If we don't have an lvalue denoting an object of class type, there is no 5703 // meaningful dynamic type. (We consider objects of non-class type to have no 5704 // dynamic type.) 5705 if (!checkDynamicType(Info, E, This, AK, true)) 5706 return std::nullopt; 5707 5708 // Refuse to compute a dynamic type in the presence of virtual bases. This 5709 // shouldn't happen other than in constant-folding situations, since literal 5710 // types can't have virtual bases. 5711 // 5712 // Note that consumers of DynamicType assume that the type has no virtual 5713 // bases, and will need modifications if this restriction is relaxed. 5714 const CXXRecordDecl *Class = 5715 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5716 if (!Class || Class->getNumVBases()) { 5717 Info.FFDiag(E); 5718 return std::nullopt; 5719 } 5720 5721 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5722 // binary search here instead. But the overwhelmingly common case is that 5723 // we're not in the middle of a constructor, so it probably doesn't matter 5724 // in practice. 5725 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5726 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5727 PathLength <= Path.size(); ++PathLength) { 5728 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5729 Path.slice(0, PathLength))) { 5730 case ConstructionPhase::Bases: 5731 case ConstructionPhase::DestroyingBases: 5732 // We're constructing or destroying a base class. This is not the dynamic 5733 // type. 5734 break; 5735 5736 case ConstructionPhase::None: 5737 case ConstructionPhase::AfterBases: 5738 case ConstructionPhase::AfterFields: 5739 case ConstructionPhase::Destroying: 5740 // We've finished constructing the base classes and not yet started 5741 // destroying them again, so this is the dynamic type. 5742 return DynamicType{getBaseClassType(This.Designator, PathLength), 5743 PathLength}; 5744 } 5745 } 5746 5747 // CWG issue 1517: we're constructing a base class of the object described by 5748 // 'This', so that object has not yet begun its period of construction and 5749 // any polymorphic operation on it results in undefined behavior. 5750 Info.FFDiag(E); 5751 return std::nullopt; 5752 } 5753 5754 /// Perform virtual dispatch. 5755 static const CXXMethodDecl *HandleVirtualDispatch( 5756 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5757 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5758 std::optional<DynamicType> DynType = ComputeDynamicType( 5759 Info, E, This, 5760 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5761 if (!DynType) 5762 return nullptr; 5763 5764 // Find the final overrider. It must be declared in one of the classes on the 5765 // path from the dynamic type to the static type. 5766 // FIXME: If we ever allow literal types to have virtual base classes, that 5767 // won't be true. 5768 const CXXMethodDecl *Callee = Found; 5769 unsigned PathLength = DynType->PathLength; 5770 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5771 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5772 const CXXMethodDecl *Overrider = 5773 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5774 if (Overrider) { 5775 Callee = Overrider; 5776 break; 5777 } 5778 } 5779 5780 // C++2a [class.abstract]p6: 5781 // the effect of making a virtual call to a pure virtual function [...] is 5782 // undefined 5783 if (Callee->isPure()) { 5784 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5785 Info.Note(Callee->getLocation(), diag::note_declared_at); 5786 return nullptr; 5787 } 5788 5789 // If necessary, walk the rest of the path to determine the sequence of 5790 // covariant adjustment steps to apply. 5791 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5792 Found->getReturnType())) { 5793 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5794 for (unsigned CovariantPathLength = PathLength + 1; 5795 CovariantPathLength != This.Designator.Entries.size(); 5796 ++CovariantPathLength) { 5797 const CXXRecordDecl *NextClass = 5798 getBaseClassType(This.Designator, CovariantPathLength); 5799 const CXXMethodDecl *Next = 5800 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5801 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5802 Next->getReturnType(), CovariantAdjustmentPath.back())) 5803 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5804 } 5805 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5806 CovariantAdjustmentPath.back())) 5807 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5808 } 5809 5810 // Perform 'this' adjustment. 5811 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5812 return nullptr; 5813 5814 return Callee; 5815 } 5816 5817 /// Perform the adjustment from a value returned by a virtual function to 5818 /// a value of the statically expected type, which may be a pointer or 5819 /// reference to a base class of the returned type. 5820 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5821 APValue &Result, 5822 ArrayRef<QualType> Path) { 5823 assert(Result.isLValue() && 5824 "unexpected kind of APValue for covariant return"); 5825 if (Result.isNullPointer()) 5826 return true; 5827 5828 LValue LVal; 5829 LVal.setFrom(Info.Ctx, Result); 5830 5831 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5832 for (unsigned I = 1; I != Path.size(); ++I) { 5833 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5834 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5835 if (OldClass != NewClass && 5836 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5837 return false; 5838 OldClass = NewClass; 5839 } 5840 5841 LVal.moveInto(Result); 5842 return true; 5843 } 5844 5845 /// Determine whether \p Base, which is known to be a direct base class of 5846 /// \p Derived, is a public base class. 5847 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5848 const CXXRecordDecl *Base) { 5849 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5850 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5851 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5852 return BaseSpec.getAccessSpecifier() == AS_public; 5853 } 5854 llvm_unreachable("Base is not a direct base of Derived"); 5855 } 5856 5857 /// Apply the given dynamic cast operation on the provided lvalue. 5858 /// 5859 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5860 /// to find a suitable target subobject. 5861 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5862 LValue &Ptr) { 5863 // We can't do anything with a non-symbolic pointer value. 5864 SubobjectDesignator &D = Ptr.Designator; 5865 if (D.Invalid) 5866 return false; 5867 5868 // C++ [expr.dynamic.cast]p6: 5869 // If v is a null pointer value, the result is a null pointer value. 5870 if (Ptr.isNullPointer() && !E->isGLValue()) 5871 return true; 5872 5873 // For all the other cases, we need the pointer to point to an object within 5874 // its lifetime / period of construction / destruction, and we need to know 5875 // its dynamic type. 5876 std::optional<DynamicType> DynType = 5877 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5878 if (!DynType) 5879 return false; 5880 5881 // C++ [expr.dynamic.cast]p7: 5882 // If T is "pointer to cv void", then the result is a pointer to the most 5883 // derived object 5884 if (E->getType()->isVoidPointerType()) 5885 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5886 5887 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5888 assert(C && "dynamic_cast target is not void pointer nor class"); 5889 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5890 5891 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5892 // C++ [expr.dynamic.cast]p9: 5893 if (!E->isGLValue()) { 5894 // The value of a failed cast to pointer type is the null pointer value 5895 // of the required result type. 5896 Ptr.setNull(Info.Ctx, E->getType()); 5897 return true; 5898 } 5899 5900 // A failed cast to reference type throws [...] std::bad_cast. 5901 unsigned DiagKind; 5902 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5903 DynType->Type->isDerivedFrom(C))) 5904 DiagKind = 0; 5905 else if (!Paths || Paths->begin() == Paths->end()) 5906 DiagKind = 1; 5907 else if (Paths->isAmbiguous(CQT)) 5908 DiagKind = 2; 5909 else { 5910 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5911 DiagKind = 3; 5912 } 5913 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5914 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5915 << Info.Ctx.getRecordType(DynType->Type) 5916 << E->getType().getUnqualifiedType(); 5917 return false; 5918 }; 5919 5920 // Runtime check, phase 1: 5921 // Walk from the base subobject towards the derived object looking for the 5922 // target type. 5923 for (int PathLength = Ptr.Designator.Entries.size(); 5924 PathLength >= (int)DynType->PathLength; --PathLength) { 5925 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5926 if (declaresSameEntity(Class, C)) 5927 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5928 // We can only walk across public inheritance edges. 5929 if (PathLength > (int)DynType->PathLength && 5930 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5931 Class)) 5932 return RuntimeCheckFailed(nullptr); 5933 } 5934 5935 // Runtime check, phase 2: 5936 // Search the dynamic type for an unambiguous public base of type C. 5937 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5938 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5939 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5940 Paths.front().Access == AS_public) { 5941 // Downcast to the dynamic type... 5942 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5943 return false; 5944 // ... then upcast to the chosen base class subobject. 5945 for (CXXBasePathElement &Elem : Paths.front()) 5946 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5947 return false; 5948 return true; 5949 } 5950 5951 // Otherwise, the runtime check fails. 5952 return RuntimeCheckFailed(&Paths); 5953 } 5954 5955 namespace { 5956 struct StartLifetimeOfUnionMemberHandler { 5957 EvalInfo &Info; 5958 const Expr *LHSExpr; 5959 const FieldDecl *Field; 5960 bool DuringInit; 5961 bool Failed = false; 5962 static const AccessKinds AccessKind = AK_Assign; 5963 5964 typedef bool result_type; 5965 bool failed() { return Failed; } 5966 bool found(APValue &Subobj, QualType SubobjType) { 5967 // We are supposed to perform no initialization but begin the lifetime of 5968 // the object. We interpret that as meaning to do what default 5969 // initialization of the object would do if all constructors involved were 5970 // trivial: 5971 // * All base, non-variant member, and array element subobjects' lifetimes 5972 // begin 5973 // * No variant members' lifetimes begin 5974 // * All scalar subobjects whose lifetimes begin have indeterminate values 5975 assert(SubobjType->isUnionType()); 5976 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5977 // This union member is already active. If it's also in-lifetime, there's 5978 // nothing to do. 5979 if (Subobj.getUnionValue().hasValue()) 5980 return true; 5981 } else if (DuringInit) { 5982 // We're currently in the process of initializing a different union 5983 // member. If we carried on, that initialization would attempt to 5984 // store to an inactive union member, resulting in undefined behavior. 5985 Info.FFDiag(LHSExpr, 5986 diag::note_constexpr_union_member_change_during_init); 5987 return false; 5988 } 5989 APValue Result; 5990 Failed = !getDefaultInitValue(Field->getType(), Result); 5991 Subobj.setUnion(Field, Result); 5992 return true; 5993 } 5994 bool found(APSInt &Value, QualType SubobjType) { 5995 llvm_unreachable("wrong value kind for union object"); 5996 } 5997 bool found(APFloat &Value, QualType SubobjType) { 5998 llvm_unreachable("wrong value kind for union object"); 5999 } 6000 }; 6001 } // end anonymous namespace 6002 6003 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 6004 6005 /// Handle a builtin simple-assignment or a call to a trivial assignment 6006 /// operator whose left-hand side might involve a union member access. If it 6007 /// does, implicitly start the lifetime of any accessed union elements per 6008 /// C++20 [class.union]5. 6009 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 6010 const LValue &LHS) { 6011 if (LHS.InvalidBase || LHS.Designator.Invalid) 6012 return false; 6013 6014 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 6015 // C++ [class.union]p5: 6016 // define the set S(E) of subexpressions of E as follows: 6017 unsigned PathLength = LHS.Designator.Entries.size(); 6018 for (const Expr *E = LHSExpr; E != nullptr;) { 6019 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 6020 if (auto *ME = dyn_cast<MemberExpr>(E)) { 6021 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 6022 // Note that we can't implicitly start the lifetime of a reference, 6023 // so we don't need to proceed any further if we reach one. 6024 if (!FD || FD->getType()->isReferenceType()) 6025 break; 6026 6027 // ... and also contains A.B if B names a union member ... 6028 if (FD->getParent()->isUnion()) { 6029 // ... of a non-class, non-array type, or of a class type with a 6030 // trivial default constructor that is not deleted, or an array of 6031 // such types. 6032 auto *RD = 6033 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 6034 if (!RD || RD->hasTrivialDefaultConstructor()) 6035 UnionPathLengths.push_back({PathLength - 1, FD}); 6036 } 6037 6038 E = ME->getBase(); 6039 --PathLength; 6040 assert(declaresSameEntity(FD, 6041 LHS.Designator.Entries[PathLength] 6042 .getAsBaseOrMember().getPointer())); 6043 6044 // -- If E is of the form A[B] and is interpreted as a built-in array 6045 // subscripting operator, S(E) is [S(the array operand, if any)]. 6046 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 6047 // Step over an ArrayToPointerDecay implicit cast. 6048 auto *Base = ASE->getBase()->IgnoreImplicit(); 6049 if (!Base->getType()->isArrayType()) 6050 break; 6051 6052 E = Base; 6053 --PathLength; 6054 6055 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6056 // Step over a derived-to-base conversion. 6057 E = ICE->getSubExpr(); 6058 if (ICE->getCastKind() == CK_NoOp) 6059 continue; 6060 if (ICE->getCastKind() != CK_DerivedToBase && 6061 ICE->getCastKind() != CK_UncheckedDerivedToBase) 6062 break; 6063 // Walk path backwards as we walk up from the base to the derived class. 6064 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 6065 --PathLength; 6066 (void)Elt; 6067 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 6068 LHS.Designator.Entries[PathLength] 6069 .getAsBaseOrMember().getPointer())); 6070 } 6071 6072 // -- Otherwise, S(E) is empty. 6073 } else { 6074 break; 6075 } 6076 } 6077 6078 // Common case: no unions' lifetimes are started. 6079 if (UnionPathLengths.empty()) 6080 return true; 6081 6082 // if modification of X [would access an inactive union member], an object 6083 // of the type of X is implicitly created 6084 CompleteObject Obj = 6085 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 6086 if (!Obj) 6087 return false; 6088 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 6089 llvm::reverse(UnionPathLengths)) { 6090 // Form a designator for the union object. 6091 SubobjectDesignator D = LHS.Designator; 6092 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 6093 6094 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 6095 ConstructionPhase::AfterBases; 6096 StartLifetimeOfUnionMemberHandler StartLifetime{ 6097 Info, LHSExpr, LengthAndField.second, DuringInit}; 6098 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 6099 return false; 6100 } 6101 6102 return true; 6103 } 6104 6105 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 6106 CallRef Call, EvalInfo &Info, 6107 bool NonNull = false) { 6108 LValue LV; 6109 // Create the parameter slot and register its destruction. For a vararg 6110 // argument, create a temporary. 6111 // FIXME: For calling conventions that destroy parameters in the callee, 6112 // should we consider performing destruction when the function returns 6113 // instead? 6114 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6115 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6116 ScopeKind::Call, LV); 6117 if (!EvaluateInPlace(V, Info, LV, Arg)) 6118 return false; 6119 6120 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6121 // undefined behavior, so is non-constant. 6122 if (NonNull && V.isLValue() && V.isNullPointer()) { 6123 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6124 return false; 6125 } 6126 6127 return true; 6128 } 6129 6130 /// Evaluate the arguments to a function call. 6131 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6132 EvalInfo &Info, const FunctionDecl *Callee, 6133 bool RightToLeft = false) { 6134 bool Success = true; 6135 llvm::SmallBitVector ForbiddenNullArgs; 6136 if (Callee->hasAttr<NonNullAttr>()) { 6137 ForbiddenNullArgs.resize(Args.size()); 6138 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6139 if (!Attr->args_size()) { 6140 ForbiddenNullArgs.set(); 6141 break; 6142 } else 6143 for (auto Idx : Attr->args()) { 6144 unsigned ASTIdx = Idx.getASTIndex(); 6145 if (ASTIdx >= Args.size()) 6146 continue; 6147 ForbiddenNullArgs[ASTIdx] = true; 6148 } 6149 } 6150 } 6151 for (unsigned I = 0; I < Args.size(); I++) { 6152 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6153 const ParmVarDecl *PVD = 6154 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6155 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6156 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6157 // If we're checking for a potential constant expression, evaluate all 6158 // initializers even if some of them fail. 6159 if (!Info.noteFailure()) 6160 return false; 6161 Success = false; 6162 } 6163 } 6164 return Success; 6165 } 6166 6167 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6168 /// constructor or assignment operator. 6169 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6170 const Expr *E, APValue &Result, 6171 bool CopyObjectRepresentation) { 6172 // Find the reference argument. 6173 CallStackFrame *Frame = Info.CurrentCall; 6174 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6175 if (!RefValue) { 6176 Info.FFDiag(E); 6177 return false; 6178 } 6179 6180 // Copy out the contents of the RHS object. 6181 LValue RefLValue; 6182 RefLValue.setFrom(Info.Ctx, *RefValue); 6183 return handleLValueToRValueConversion( 6184 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6185 CopyObjectRepresentation); 6186 } 6187 6188 /// Evaluate a function call. 6189 static bool HandleFunctionCall(SourceLocation CallLoc, 6190 const FunctionDecl *Callee, const LValue *This, 6191 const Expr *E, ArrayRef<const Expr *> Args, 6192 CallRef Call, const Stmt *Body, EvalInfo &Info, 6193 APValue &Result, const LValue *ResultSlot) { 6194 if (!Info.CheckCallLimit(CallLoc)) 6195 return false; 6196 6197 CallStackFrame Frame(Info, CallLoc, Callee, This, E, Call); 6198 6199 // For a trivial copy or move assignment, perform an APValue copy. This is 6200 // essential for unions, where the operations performed by the assignment 6201 // operator cannot be represented as statements. 6202 // 6203 // Skip this for non-union classes with no fields; in that case, the defaulted 6204 // copy/move does not actually read the object. 6205 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6206 if (MD && MD->isDefaulted() && 6207 (MD->getParent()->isUnion() || 6208 (MD->isTrivial() && 6209 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6210 assert(This && 6211 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6212 APValue RHSValue; 6213 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6214 MD->getParent()->isUnion())) 6215 return false; 6216 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6217 RHSValue)) 6218 return false; 6219 This->moveInto(Result); 6220 return true; 6221 } else if (MD && isLambdaCallOperator(MD)) { 6222 // We're in a lambda; determine the lambda capture field maps unless we're 6223 // just constexpr checking a lambda's call operator. constexpr checking is 6224 // done before the captures have been added to the closure object (unless 6225 // we're inferring constexpr-ness), so we don't have access to them in this 6226 // case. But since we don't need the captures to constexpr check, we can 6227 // just ignore them. 6228 if (!Info.checkingPotentialConstantExpression()) 6229 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6230 Frame.LambdaThisCaptureField); 6231 } 6232 6233 StmtResult Ret = {Result, ResultSlot}; 6234 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6235 if (ESR == ESR_Succeeded) { 6236 if (Callee->getReturnType()->isVoidType()) 6237 return true; 6238 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6239 } 6240 return ESR == ESR_Returned; 6241 } 6242 6243 /// Evaluate a constructor call. 6244 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6245 CallRef Call, 6246 const CXXConstructorDecl *Definition, 6247 EvalInfo &Info, APValue &Result) { 6248 SourceLocation CallLoc = E->getExprLoc(); 6249 if (!Info.CheckCallLimit(CallLoc)) 6250 return false; 6251 6252 const CXXRecordDecl *RD = Definition->getParent(); 6253 if (RD->getNumVBases()) { 6254 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6255 return false; 6256 } 6257 6258 EvalInfo::EvaluatingConstructorRAII EvalObj( 6259 Info, 6260 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6261 RD->getNumBases()); 6262 CallStackFrame Frame(Info, CallLoc, Definition, &This, E, Call); 6263 6264 // FIXME: Creating an APValue just to hold a nonexistent return value is 6265 // wasteful. 6266 APValue RetVal; 6267 StmtResult Ret = {RetVal, nullptr}; 6268 6269 // If it's a delegating constructor, delegate. 6270 if (Definition->isDelegatingConstructor()) { 6271 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6272 if ((*I)->getInit()->isValueDependent()) { 6273 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6274 return false; 6275 } else { 6276 FullExpressionRAII InitScope(Info); 6277 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6278 !InitScope.destroy()) 6279 return false; 6280 } 6281 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6282 } 6283 6284 // For a trivial copy or move constructor, perform an APValue copy. This is 6285 // essential for unions (or classes with anonymous union members), where the 6286 // operations performed by the constructor cannot be represented by 6287 // ctor-initializers. 6288 // 6289 // Skip this for empty non-union classes; we should not perform an 6290 // lvalue-to-rvalue conversion on them because their copy constructor does not 6291 // actually read them. 6292 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6293 (Definition->getParent()->isUnion() || 6294 (Definition->isTrivial() && 6295 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6296 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6297 Definition->getParent()->isUnion()); 6298 } 6299 6300 // Reserve space for the struct members. 6301 if (!Result.hasValue()) { 6302 if (!RD->isUnion()) 6303 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6304 std::distance(RD->field_begin(), RD->field_end())); 6305 else 6306 // A union starts with no active member. 6307 Result = APValue((const FieldDecl*)nullptr); 6308 } 6309 6310 if (RD->isInvalidDecl()) return false; 6311 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6312 6313 // A scope for temporaries lifetime-extended by reference members. 6314 BlockScopeRAII LifetimeExtendedScope(Info); 6315 6316 bool Success = true; 6317 unsigned BasesSeen = 0; 6318 #ifndef NDEBUG 6319 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6320 #endif 6321 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6322 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6323 // We might be initializing the same field again if this is an indirect 6324 // field initialization. 6325 if (FieldIt == RD->field_end() || 6326 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6327 assert(Indirect && "fields out of order?"); 6328 return; 6329 } 6330 6331 // Default-initialize any fields with no explicit initializer. 6332 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6333 assert(FieldIt != RD->field_end() && "missing field?"); 6334 if (!FieldIt->isUnnamedBitfield()) 6335 Success &= getDefaultInitValue( 6336 FieldIt->getType(), 6337 Result.getStructField(FieldIt->getFieldIndex())); 6338 } 6339 ++FieldIt; 6340 }; 6341 for (const auto *I : Definition->inits()) { 6342 LValue Subobject = This; 6343 LValue SubobjectParent = This; 6344 APValue *Value = &Result; 6345 6346 // Determine the subobject to initialize. 6347 FieldDecl *FD = nullptr; 6348 if (I->isBaseInitializer()) { 6349 QualType BaseType(I->getBaseClass(), 0); 6350 #ifndef NDEBUG 6351 // Non-virtual base classes are initialized in the order in the class 6352 // definition. We have already checked for virtual base classes. 6353 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6354 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6355 "base class initializers not in expected order"); 6356 ++BaseIt; 6357 #endif 6358 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6359 BaseType->getAsCXXRecordDecl(), &Layout)) 6360 return false; 6361 Value = &Result.getStructBase(BasesSeen++); 6362 } else if ((FD = I->getMember())) { 6363 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6364 return false; 6365 if (RD->isUnion()) { 6366 Result = APValue(FD); 6367 Value = &Result.getUnionValue(); 6368 } else { 6369 SkipToField(FD, false); 6370 Value = &Result.getStructField(FD->getFieldIndex()); 6371 } 6372 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6373 // Walk the indirect field decl's chain to find the object to initialize, 6374 // and make sure we've initialized every step along it. 6375 auto IndirectFieldChain = IFD->chain(); 6376 for (auto *C : IndirectFieldChain) { 6377 FD = cast<FieldDecl>(C); 6378 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6379 // Switch the union field if it differs. This happens if we had 6380 // preceding zero-initialization, and we're now initializing a union 6381 // subobject other than the first. 6382 // FIXME: In this case, the values of the other subobjects are 6383 // specified, since zero-initialization sets all padding bits to zero. 6384 if (!Value->hasValue() || 6385 (Value->isUnion() && Value->getUnionField() != FD)) { 6386 if (CD->isUnion()) 6387 *Value = APValue(FD); 6388 else 6389 // FIXME: This immediately starts the lifetime of all members of 6390 // an anonymous struct. It would be preferable to strictly start 6391 // member lifetime in initialization order. 6392 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6393 } 6394 // Store Subobject as its parent before updating it for the last element 6395 // in the chain. 6396 if (C == IndirectFieldChain.back()) 6397 SubobjectParent = Subobject; 6398 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6399 return false; 6400 if (CD->isUnion()) 6401 Value = &Value->getUnionValue(); 6402 else { 6403 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6404 SkipToField(FD, true); 6405 Value = &Value->getStructField(FD->getFieldIndex()); 6406 } 6407 } 6408 } else { 6409 llvm_unreachable("unknown base initializer kind"); 6410 } 6411 6412 // Need to override This for implicit field initializers as in this case 6413 // This refers to innermost anonymous struct/union containing initializer, 6414 // not to currently constructed class. 6415 const Expr *Init = I->getInit(); 6416 if (Init->isValueDependent()) { 6417 if (!EvaluateDependentExpr(Init, Info)) 6418 return false; 6419 } else { 6420 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6421 isa<CXXDefaultInitExpr>(Init)); 6422 FullExpressionRAII InitScope(Info); 6423 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6424 (FD && FD->isBitField() && 6425 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6426 // If we're checking for a potential constant expression, evaluate all 6427 // initializers even if some of them fail. 6428 if (!Info.noteFailure()) 6429 return false; 6430 Success = false; 6431 } 6432 } 6433 6434 // This is the point at which the dynamic type of the object becomes this 6435 // class type. 6436 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6437 EvalObj.finishedConstructingBases(); 6438 } 6439 6440 // Default-initialize any remaining fields. 6441 if (!RD->isUnion()) { 6442 for (; FieldIt != RD->field_end(); ++FieldIt) { 6443 if (!FieldIt->isUnnamedBitfield()) 6444 Success &= getDefaultInitValue( 6445 FieldIt->getType(), 6446 Result.getStructField(FieldIt->getFieldIndex())); 6447 } 6448 } 6449 6450 EvalObj.finishedConstructingFields(); 6451 6452 return Success && 6453 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6454 LifetimeExtendedScope.destroy(); 6455 } 6456 6457 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6458 ArrayRef<const Expr*> Args, 6459 const CXXConstructorDecl *Definition, 6460 EvalInfo &Info, APValue &Result) { 6461 CallScopeRAII CallScope(Info); 6462 CallRef Call = Info.CurrentCall->createCall(Definition); 6463 if (!EvaluateArgs(Args, Call, Info, Definition)) 6464 return false; 6465 6466 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6467 CallScope.destroy(); 6468 } 6469 6470 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6471 const LValue &This, APValue &Value, 6472 QualType T) { 6473 // Objects can only be destroyed while they're within their lifetimes. 6474 // FIXME: We have no representation for whether an object of type nullptr_t 6475 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6476 // as indeterminate instead? 6477 if (Value.isAbsent() && !T->isNullPtrType()) { 6478 APValue Printable; 6479 This.moveInto(Printable); 6480 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6481 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6482 return false; 6483 } 6484 6485 // Invent an expression for location purposes. 6486 // FIXME: We shouldn't need to do this. 6487 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6488 6489 // For arrays, destroy elements right-to-left. 6490 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6491 uint64_t Size = CAT->getSize().getZExtValue(); 6492 QualType ElemT = CAT->getElementType(); 6493 6494 LValue ElemLV = This; 6495 ElemLV.addArray(Info, &LocE, CAT); 6496 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6497 return false; 6498 6499 // Ensure that we have actual array elements available to destroy; the 6500 // destructors might mutate the value, so we can't run them on the array 6501 // filler. 6502 if (Size && Size > Value.getArrayInitializedElts()) 6503 expandArray(Value, Value.getArraySize() - 1); 6504 6505 for (; Size != 0; --Size) { 6506 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6507 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6508 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6509 return false; 6510 } 6511 6512 // End the lifetime of this array now. 6513 Value = APValue(); 6514 return true; 6515 } 6516 6517 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6518 if (!RD) { 6519 if (T.isDestructedType()) { 6520 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6521 return false; 6522 } 6523 6524 Value = APValue(); 6525 return true; 6526 } 6527 6528 if (RD->getNumVBases()) { 6529 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6530 return false; 6531 } 6532 6533 const CXXDestructorDecl *DD = RD->getDestructor(); 6534 if (!DD && !RD->hasTrivialDestructor()) { 6535 Info.FFDiag(CallLoc); 6536 return false; 6537 } 6538 6539 if (!DD || DD->isTrivial() || 6540 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6541 // A trivial destructor just ends the lifetime of the object. Check for 6542 // this case before checking for a body, because we might not bother 6543 // building a body for a trivial destructor. Note that it doesn't matter 6544 // whether the destructor is constexpr in this case; all trivial 6545 // destructors are constexpr. 6546 // 6547 // If an anonymous union would be destroyed, some enclosing destructor must 6548 // have been explicitly defined, and the anonymous union destruction should 6549 // have no effect. 6550 Value = APValue(); 6551 return true; 6552 } 6553 6554 if (!Info.CheckCallLimit(CallLoc)) 6555 return false; 6556 6557 const FunctionDecl *Definition = nullptr; 6558 const Stmt *Body = DD->getBody(Definition); 6559 6560 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6561 return false; 6562 6563 CallStackFrame Frame(Info, CallLoc, Definition, &This, /*CallExpr=*/nullptr, 6564 CallRef()); 6565 6566 // We're now in the period of destruction of this object. 6567 unsigned BasesLeft = RD->getNumBases(); 6568 EvalInfo::EvaluatingDestructorRAII EvalObj( 6569 Info, 6570 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6571 if (!EvalObj.DidInsert) { 6572 // C++2a [class.dtor]p19: 6573 // the behavior is undefined if the destructor is invoked for an object 6574 // whose lifetime has ended 6575 // (Note that formally the lifetime ends when the period of destruction 6576 // begins, even though certain uses of the object remain valid until the 6577 // period of destruction ends.) 6578 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6579 return false; 6580 } 6581 6582 // FIXME: Creating an APValue just to hold a nonexistent return value is 6583 // wasteful. 6584 APValue RetVal; 6585 StmtResult Ret = {RetVal, nullptr}; 6586 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6587 return false; 6588 6589 // A union destructor does not implicitly destroy its members. 6590 if (RD->isUnion()) 6591 return true; 6592 6593 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6594 6595 // We don't have a good way to iterate fields in reverse, so collect all the 6596 // fields first and then walk them backwards. 6597 SmallVector<FieldDecl*, 16> Fields(RD->fields()); 6598 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6599 if (FD->isUnnamedBitfield()) 6600 continue; 6601 6602 LValue Subobject = This; 6603 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6604 return false; 6605 6606 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6607 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6608 FD->getType())) 6609 return false; 6610 } 6611 6612 if (BasesLeft != 0) 6613 EvalObj.startedDestroyingBases(); 6614 6615 // Destroy base classes in reverse order. 6616 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6617 --BasesLeft; 6618 6619 QualType BaseType = Base.getType(); 6620 LValue Subobject = This; 6621 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6622 BaseType->getAsCXXRecordDecl(), &Layout)) 6623 return false; 6624 6625 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6626 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6627 BaseType)) 6628 return false; 6629 } 6630 assert(BasesLeft == 0 && "NumBases was wrong?"); 6631 6632 // The period of destruction ends now. The object is gone. 6633 Value = APValue(); 6634 return true; 6635 } 6636 6637 namespace { 6638 struct DestroyObjectHandler { 6639 EvalInfo &Info; 6640 const Expr *E; 6641 const LValue &This; 6642 const AccessKinds AccessKind; 6643 6644 typedef bool result_type; 6645 bool failed() { return false; } 6646 bool found(APValue &Subobj, QualType SubobjType) { 6647 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6648 SubobjType); 6649 } 6650 bool found(APSInt &Value, QualType SubobjType) { 6651 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6652 return false; 6653 } 6654 bool found(APFloat &Value, QualType SubobjType) { 6655 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6656 return false; 6657 } 6658 }; 6659 } 6660 6661 /// Perform a destructor or pseudo-destructor call on the given object, which 6662 /// might in general not be a complete object. 6663 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6664 const LValue &This, QualType ThisType) { 6665 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6666 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6667 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6668 } 6669 6670 /// Destroy and end the lifetime of the given complete object. 6671 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6672 APValue::LValueBase LVBase, APValue &Value, 6673 QualType T) { 6674 // If we've had an unmodeled side-effect, we can't rely on mutable state 6675 // (such as the object we're about to destroy) being correct. 6676 if (Info.EvalStatus.HasSideEffects) 6677 return false; 6678 6679 LValue LV; 6680 LV.set({LVBase}); 6681 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6682 } 6683 6684 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6685 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6686 LValue &Result) { 6687 if (Info.checkingPotentialConstantExpression() || 6688 Info.SpeculativeEvaluationDepth) 6689 return false; 6690 6691 // This is permitted only within a call to std::allocator<T>::allocate. 6692 auto Caller = Info.getStdAllocatorCaller("allocate"); 6693 if (!Caller) { 6694 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6695 ? diag::note_constexpr_new_untyped 6696 : diag::note_constexpr_new); 6697 return false; 6698 } 6699 6700 QualType ElemType = Caller.ElemType; 6701 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6702 Info.FFDiag(E->getExprLoc(), 6703 diag::note_constexpr_new_not_complete_object_type) 6704 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6705 return false; 6706 } 6707 6708 APSInt ByteSize; 6709 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6710 return false; 6711 bool IsNothrow = false; 6712 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6713 EvaluateIgnoredValue(Info, E->getArg(I)); 6714 IsNothrow |= E->getType()->isNothrowT(); 6715 } 6716 6717 CharUnits ElemSize; 6718 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6719 return false; 6720 APInt Size, Remainder; 6721 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6722 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6723 if (Remainder != 0) { 6724 // This likely indicates a bug in the implementation of 'std::allocator'. 6725 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6726 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6727 return false; 6728 } 6729 6730 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6731 if (IsNothrow) { 6732 Result.setNull(Info.Ctx, E->getType()); 6733 return true; 6734 } 6735 6736 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6737 return false; 6738 } 6739 6740 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6741 ArrayType::Normal, 0); 6742 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6743 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6744 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6745 return true; 6746 } 6747 6748 static bool hasVirtualDestructor(QualType T) { 6749 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6750 if (CXXDestructorDecl *DD = RD->getDestructor()) 6751 return DD->isVirtual(); 6752 return false; 6753 } 6754 6755 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6756 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6757 if (CXXDestructorDecl *DD = RD->getDestructor()) 6758 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6759 return nullptr; 6760 } 6761 6762 /// Check that the given object is a suitable pointer to a heap allocation that 6763 /// still exists and is of the right kind for the purpose of a deletion. 6764 /// 6765 /// On success, returns the heap allocation to deallocate. On failure, produces 6766 /// a diagnostic and returns std::nullopt. 6767 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6768 const LValue &Pointer, 6769 DynAlloc::Kind DeallocKind) { 6770 auto PointerAsString = [&] { 6771 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6772 }; 6773 6774 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6775 if (!DA) { 6776 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6777 << PointerAsString(); 6778 if (Pointer.Base) 6779 NoteLValueLocation(Info, Pointer.Base); 6780 return std::nullopt; 6781 } 6782 6783 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6784 if (!Alloc) { 6785 Info.FFDiag(E, diag::note_constexpr_double_delete); 6786 return std::nullopt; 6787 } 6788 6789 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6790 if (DeallocKind != (*Alloc)->getKind()) { 6791 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6792 << DeallocKind << (*Alloc)->getKind() << AllocType; 6793 NoteLValueLocation(Info, Pointer.Base); 6794 return std::nullopt; 6795 } 6796 6797 bool Subobject = false; 6798 if (DeallocKind == DynAlloc::New) { 6799 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6800 Pointer.Designator.isOnePastTheEnd(); 6801 } else { 6802 Subobject = Pointer.Designator.Entries.size() != 1 || 6803 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6804 } 6805 if (Subobject) { 6806 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6807 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6808 return std::nullopt; 6809 } 6810 6811 return Alloc; 6812 } 6813 6814 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6815 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6816 if (Info.checkingPotentialConstantExpression() || 6817 Info.SpeculativeEvaluationDepth) 6818 return false; 6819 6820 // This is permitted only within a call to std::allocator<T>::deallocate. 6821 if (!Info.getStdAllocatorCaller("deallocate")) { 6822 Info.FFDiag(E->getExprLoc()); 6823 return true; 6824 } 6825 6826 LValue Pointer; 6827 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6828 return false; 6829 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6830 EvaluateIgnoredValue(Info, E->getArg(I)); 6831 6832 if (Pointer.Designator.Invalid) 6833 return false; 6834 6835 // Deleting a null pointer would have no effect, but it's not permitted by 6836 // std::allocator<T>::deallocate's contract. 6837 if (Pointer.isNullPointer()) { 6838 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6839 return true; 6840 } 6841 6842 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6843 return false; 6844 6845 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6846 return true; 6847 } 6848 6849 //===----------------------------------------------------------------------===// 6850 // Generic Evaluation 6851 //===----------------------------------------------------------------------===// 6852 namespace { 6853 6854 class BitCastBuffer { 6855 // FIXME: We're going to need bit-level granularity when we support 6856 // bit-fields. 6857 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6858 // we don't support a host or target where that is the case. Still, we should 6859 // use a more generic type in case we ever do. 6860 SmallVector<std::optional<unsigned char>, 32> Bytes; 6861 6862 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6863 "Need at least 8 bit unsigned char"); 6864 6865 bool TargetIsLittleEndian; 6866 6867 public: 6868 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6869 : Bytes(Width.getQuantity()), 6870 TargetIsLittleEndian(TargetIsLittleEndian) {} 6871 6872 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width, 6873 SmallVectorImpl<unsigned char> &Output) const { 6874 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6875 // If a byte of an integer is uninitialized, then the whole integer is 6876 // uninitialized. 6877 if (!Bytes[I.getQuantity()]) 6878 return false; 6879 Output.push_back(*Bytes[I.getQuantity()]); 6880 } 6881 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6882 std::reverse(Output.begin(), Output.end()); 6883 return true; 6884 } 6885 6886 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6887 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6888 std::reverse(Input.begin(), Input.end()); 6889 6890 size_t Index = 0; 6891 for (unsigned char Byte : Input) { 6892 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6893 Bytes[Offset.getQuantity() + Index] = Byte; 6894 ++Index; 6895 } 6896 } 6897 6898 size_t size() { return Bytes.size(); } 6899 }; 6900 6901 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6902 /// target would represent the value at runtime. 6903 class APValueToBufferConverter { 6904 EvalInfo &Info; 6905 BitCastBuffer Buffer; 6906 const CastExpr *BCE; 6907 6908 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6909 const CastExpr *BCE) 6910 : Info(Info), 6911 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6912 BCE(BCE) {} 6913 6914 bool visit(const APValue &Val, QualType Ty) { 6915 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6916 } 6917 6918 // Write out Val with type Ty into Buffer starting at Offset. 6919 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6920 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6921 6922 // As a special case, nullptr_t has an indeterminate value. 6923 if (Ty->isNullPtrType()) 6924 return true; 6925 6926 // Dig through Src to find the byte at SrcOffset. 6927 switch (Val.getKind()) { 6928 case APValue::Indeterminate: 6929 case APValue::None: 6930 return true; 6931 6932 case APValue::Int: 6933 return visitInt(Val.getInt(), Ty, Offset); 6934 case APValue::Float: 6935 return visitFloat(Val.getFloat(), Ty, Offset); 6936 case APValue::Array: 6937 return visitArray(Val, Ty, Offset); 6938 case APValue::Struct: 6939 return visitRecord(Val, Ty, Offset); 6940 6941 case APValue::ComplexInt: 6942 case APValue::ComplexFloat: 6943 case APValue::Vector: 6944 case APValue::FixedPoint: 6945 // FIXME: We should support these. 6946 6947 case APValue::Union: 6948 case APValue::MemberPointer: 6949 case APValue::AddrLabelDiff: { 6950 Info.FFDiag(BCE->getBeginLoc(), 6951 diag::note_constexpr_bit_cast_unsupported_type) 6952 << Ty; 6953 return false; 6954 } 6955 6956 case APValue::LValue: 6957 llvm_unreachable("LValue subobject in bit_cast?"); 6958 } 6959 llvm_unreachable("Unhandled APValue::ValueKind"); 6960 } 6961 6962 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6963 const RecordDecl *RD = Ty->getAsRecordDecl(); 6964 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6965 6966 // Visit the base classes. 6967 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6968 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6969 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6970 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6971 6972 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6973 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6974 return false; 6975 } 6976 } 6977 6978 // Visit the fields. 6979 unsigned FieldIdx = 0; 6980 for (FieldDecl *FD : RD->fields()) { 6981 if (FD->isBitField()) { 6982 Info.FFDiag(BCE->getBeginLoc(), 6983 diag::note_constexpr_bit_cast_unsupported_bitfield); 6984 return false; 6985 } 6986 6987 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6988 6989 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6990 "only bit-fields can have sub-char alignment"); 6991 CharUnits FieldOffset = 6992 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6993 QualType FieldTy = FD->getType(); 6994 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6995 return false; 6996 ++FieldIdx; 6997 } 6998 6999 return true; 7000 } 7001 7002 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 7003 const auto *CAT = 7004 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 7005 if (!CAT) 7006 return false; 7007 7008 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 7009 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 7010 unsigned ArraySize = Val.getArraySize(); 7011 // First, initialize the initialized elements. 7012 for (unsigned I = 0; I != NumInitializedElts; ++I) { 7013 const APValue &SubObj = Val.getArrayInitializedElt(I); 7014 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 7015 return false; 7016 } 7017 7018 // Next, initialize the rest of the array using the filler. 7019 if (Val.hasArrayFiller()) { 7020 const APValue &Filler = Val.getArrayFiller(); 7021 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 7022 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 7023 return false; 7024 } 7025 } 7026 7027 return true; 7028 } 7029 7030 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 7031 APSInt AdjustedVal = Val; 7032 unsigned Width = AdjustedVal.getBitWidth(); 7033 if (Ty->isBooleanType()) { 7034 Width = Info.Ctx.getTypeSize(Ty); 7035 AdjustedVal = AdjustedVal.extend(Width); 7036 } 7037 7038 SmallVector<unsigned char, 8> Bytes(Width / 8); 7039 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 7040 Buffer.writeObject(Offset, Bytes); 7041 return true; 7042 } 7043 7044 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 7045 APSInt AsInt(Val.bitcastToAPInt()); 7046 return visitInt(AsInt, Ty, Offset); 7047 } 7048 7049 public: 7050 static std::optional<BitCastBuffer> 7051 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) { 7052 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 7053 APValueToBufferConverter Converter(Info, DstSize, BCE); 7054 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 7055 return std::nullopt; 7056 return Converter.Buffer; 7057 } 7058 }; 7059 7060 /// Write an BitCastBuffer into an APValue. 7061 class BufferToAPValueConverter { 7062 EvalInfo &Info; 7063 const BitCastBuffer &Buffer; 7064 const CastExpr *BCE; 7065 7066 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 7067 const CastExpr *BCE) 7068 : Info(Info), Buffer(Buffer), BCE(BCE) {} 7069 7070 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 7071 // with an invalid type, so anything left is a deficiency on our part (FIXME). 7072 // Ideally this will be unreachable. 7073 std::nullopt_t unsupportedType(QualType Ty) { 7074 Info.FFDiag(BCE->getBeginLoc(), 7075 diag::note_constexpr_bit_cast_unsupported_type) 7076 << Ty; 7077 return std::nullopt; 7078 } 7079 7080 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) { 7081 Info.FFDiag(BCE->getBeginLoc(), 7082 diag::note_constexpr_bit_cast_unrepresentable_value) 7083 << Ty << toString(Val, /*Radix=*/10); 7084 return std::nullopt; 7085 } 7086 7087 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 7088 const EnumType *EnumSugar = nullptr) { 7089 if (T->isNullPtrType()) { 7090 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 7091 return APValue((Expr *)nullptr, 7092 /*Offset=*/CharUnits::fromQuantity(NullValue), 7093 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 7094 } 7095 7096 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 7097 7098 // Work around floating point types that contain unused padding bytes. This 7099 // is really just `long double` on x86, which is the only fundamental type 7100 // with padding bytes. 7101 if (T->isRealFloatingType()) { 7102 const llvm::fltSemantics &Semantics = 7103 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7104 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 7105 assert(NumBits % 8 == 0); 7106 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 7107 if (NumBytes != SizeOf) 7108 SizeOf = NumBytes; 7109 } 7110 7111 SmallVector<uint8_t, 8> Bytes; 7112 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7113 // If this is std::byte or unsigned char, then its okay to store an 7114 // indeterminate value. 7115 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7116 bool IsUChar = 7117 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7118 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7119 if (!IsStdByte && !IsUChar) { 7120 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7121 Info.FFDiag(BCE->getExprLoc(), 7122 diag::note_constexpr_bit_cast_indet_dest) 7123 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7124 return std::nullopt; 7125 } 7126 7127 return APValue::IndeterminateValue(); 7128 } 7129 7130 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7131 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7132 7133 if (T->isIntegralOrEnumerationType()) { 7134 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7135 7136 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7137 if (IntWidth != Val.getBitWidth()) { 7138 APSInt Truncated = Val.trunc(IntWidth); 7139 if (Truncated.extend(Val.getBitWidth()) != Val) 7140 return unrepresentableValue(QualType(T, 0), Val); 7141 Val = Truncated; 7142 } 7143 7144 return APValue(Val); 7145 } 7146 7147 if (T->isRealFloatingType()) { 7148 const llvm::fltSemantics &Semantics = 7149 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7150 return APValue(APFloat(Semantics, Val)); 7151 } 7152 7153 return unsupportedType(QualType(T, 0)); 7154 } 7155 7156 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7157 const RecordDecl *RD = RTy->getAsRecordDecl(); 7158 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7159 7160 unsigned NumBases = 0; 7161 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7162 NumBases = CXXRD->getNumBases(); 7163 7164 APValue ResultVal(APValue::UninitStruct(), NumBases, 7165 std::distance(RD->field_begin(), RD->field_end())); 7166 7167 // Visit the base classes. 7168 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7169 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7170 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7171 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7172 if (BaseDecl->isEmpty() || 7173 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7174 continue; 7175 7176 std::optional<APValue> SubObj = visitType( 7177 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7178 if (!SubObj) 7179 return std::nullopt; 7180 ResultVal.getStructBase(I) = *SubObj; 7181 } 7182 } 7183 7184 // Visit the fields. 7185 unsigned FieldIdx = 0; 7186 for (FieldDecl *FD : RD->fields()) { 7187 // FIXME: We don't currently support bit-fields. A lot of the logic for 7188 // this is in CodeGen, so we need to factor it around. 7189 if (FD->isBitField()) { 7190 Info.FFDiag(BCE->getBeginLoc(), 7191 diag::note_constexpr_bit_cast_unsupported_bitfield); 7192 return std::nullopt; 7193 } 7194 7195 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7196 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7197 7198 CharUnits FieldOffset = 7199 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7200 Offset; 7201 QualType FieldTy = FD->getType(); 7202 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7203 if (!SubObj) 7204 return std::nullopt; 7205 ResultVal.getStructField(FieldIdx) = *SubObj; 7206 ++FieldIdx; 7207 } 7208 7209 return ResultVal; 7210 } 7211 7212 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7213 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7214 assert(!RepresentationType.isNull() && 7215 "enum forward decl should be caught by Sema"); 7216 const auto *AsBuiltin = 7217 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7218 // Recurse into the underlying type. Treat std::byte transparently as 7219 // unsigned char. 7220 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7221 } 7222 7223 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7224 size_t Size = Ty->getSize().getLimitedValue(); 7225 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7226 7227 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7228 for (size_t I = 0; I != Size; ++I) { 7229 std::optional<APValue> ElementValue = 7230 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7231 if (!ElementValue) 7232 return std::nullopt; 7233 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7234 } 7235 7236 return ArrayValue; 7237 } 7238 7239 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7240 return unsupportedType(QualType(Ty, 0)); 7241 } 7242 7243 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7244 QualType Can = Ty.getCanonicalType(); 7245 7246 switch (Can->getTypeClass()) { 7247 #define TYPE(Class, Base) \ 7248 case Type::Class: \ 7249 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7250 #define ABSTRACT_TYPE(Class, Base) 7251 #define NON_CANONICAL_TYPE(Class, Base) \ 7252 case Type::Class: \ 7253 llvm_unreachable("non-canonical type should be impossible!"); 7254 #define DEPENDENT_TYPE(Class, Base) \ 7255 case Type::Class: \ 7256 llvm_unreachable( \ 7257 "dependent types aren't supported in the constant evaluator!"); 7258 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7259 case Type::Class: \ 7260 llvm_unreachable("either dependent or not canonical!"); 7261 #include "clang/AST/TypeNodes.inc" 7262 } 7263 llvm_unreachable("Unhandled Type::TypeClass"); 7264 } 7265 7266 public: 7267 // Pull out a full value of type DstType. 7268 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7269 const CastExpr *BCE) { 7270 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7271 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7272 } 7273 }; 7274 7275 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7276 QualType Ty, EvalInfo *Info, 7277 const ASTContext &Ctx, 7278 bool CheckingDest) { 7279 Ty = Ty.getCanonicalType(); 7280 7281 auto diag = [&](int Reason) { 7282 if (Info) 7283 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7284 << CheckingDest << (Reason == 4) << Reason; 7285 return false; 7286 }; 7287 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7288 if (Info) 7289 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7290 << NoteTy << Construct << Ty; 7291 return false; 7292 }; 7293 7294 if (Ty->isUnionType()) 7295 return diag(0); 7296 if (Ty->isPointerType()) 7297 return diag(1); 7298 if (Ty->isMemberPointerType()) 7299 return diag(2); 7300 if (Ty.isVolatileQualified()) 7301 return diag(3); 7302 7303 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7304 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7305 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7306 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7307 CheckingDest)) 7308 return note(1, BS.getType(), BS.getBeginLoc()); 7309 } 7310 for (FieldDecl *FD : Record->fields()) { 7311 if (FD->getType()->isReferenceType()) 7312 return diag(4); 7313 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7314 CheckingDest)) 7315 return note(0, FD->getType(), FD->getBeginLoc()); 7316 } 7317 } 7318 7319 if (Ty->isArrayType() && 7320 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7321 Info, Ctx, CheckingDest)) 7322 return false; 7323 7324 return true; 7325 } 7326 7327 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7328 const ASTContext &Ctx, 7329 const CastExpr *BCE) { 7330 bool DestOK = checkBitCastConstexprEligibilityType( 7331 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7332 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7333 BCE->getBeginLoc(), 7334 BCE->getSubExpr()->getType(), Info, Ctx, false); 7335 return SourceOK; 7336 } 7337 7338 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7339 APValue &SourceValue, 7340 const CastExpr *BCE) { 7341 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7342 "no host or target supports non 8-bit chars"); 7343 assert(SourceValue.isLValue() && 7344 "LValueToRValueBitcast requires an lvalue operand!"); 7345 7346 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7347 return false; 7348 7349 LValue SourceLValue; 7350 APValue SourceRValue; 7351 SourceLValue.setFrom(Info.Ctx, SourceValue); 7352 if (!handleLValueToRValueConversion( 7353 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7354 SourceRValue, /*WantObjectRepresentation=*/true)) 7355 return false; 7356 7357 // Read out SourceValue into a char buffer. 7358 std::optional<BitCastBuffer> Buffer = 7359 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7360 if (!Buffer) 7361 return false; 7362 7363 // Write out the buffer into a new APValue. 7364 std::optional<APValue> MaybeDestValue = 7365 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7366 if (!MaybeDestValue) 7367 return false; 7368 7369 DestValue = std::move(*MaybeDestValue); 7370 return true; 7371 } 7372 7373 template <class Derived> 7374 class ExprEvaluatorBase 7375 : public ConstStmtVisitor<Derived, bool> { 7376 private: 7377 Derived &getDerived() { return static_cast<Derived&>(*this); } 7378 bool DerivedSuccess(const APValue &V, const Expr *E) { 7379 return getDerived().Success(V, E); 7380 } 7381 bool DerivedZeroInitialization(const Expr *E) { 7382 return getDerived().ZeroInitialization(E); 7383 } 7384 7385 // Check whether a conditional operator with a non-constant condition is a 7386 // potential constant expression. If neither arm is a potential constant 7387 // expression, then the conditional operator is not either. 7388 template<typename ConditionalOperator> 7389 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7390 assert(Info.checkingPotentialConstantExpression()); 7391 7392 // Speculatively evaluate both arms. 7393 SmallVector<PartialDiagnosticAt, 8> Diag; 7394 { 7395 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7396 StmtVisitorTy::Visit(E->getFalseExpr()); 7397 if (Diag.empty()) 7398 return; 7399 } 7400 7401 { 7402 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7403 Diag.clear(); 7404 StmtVisitorTy::Visit(E->getTrueExpr()); 7405 if (Diag.empty()) 7406 return; 7407 } 7408 7409 Error(E, diag::note_constexpr_conditional_never_const); 7410 } 7411 7412 7413 template<typename ConditionalOperator> 7414 bool HandleConditionalOperator(const ConditionalOperator *E) { 7415 bool BoolResult; 7416 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7417 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7418 CheckPotentialConstantConditional(E); 7419 return false; 7420 } 7421 if (Info.noteFailure()) { 7422 StmtVisitorTy::Visit(E->getTrueExpr()); 7423 StmtVisitorTy::Visit(E->getFalseExpr()); 7424 } 7425 return false; 7426 } 7427 7428 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7429 return StmtVisitorTy::Visit(EvalExpr); 7430 } 7431 7432 protected: 7433 EvalInfo &Info; 7434 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7435 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7436 7437 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7438 return Info.CCEDiag(E, D); 7439 } 7440 7441 bool ZeroInitialization(const Expr *E) { return Error(E); } 7442 7443 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) { 7444 unsigned BuiltinOp = E->getBuiltinCallee(); 7445 return BuiltinOp != 0 && 7446 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp); 7447 } 7448 7449 public: 7450 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7451 7452 EvalInfo &getEvalInfo() { return Info; } 7453 7454 /// Report an evaluation error. This should only be called when an error is 7455 /// first discovered. When propagating an error, just return false. 7456 bool Error(const Expr *E, diag::kind D) { 7457 Info.FFDiag(E, D); 7458 return false; 7459 } 7460 bool Error(const Expr *E) { 7461 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7462 } 7463 7464 bool VisitStmt(const Stmt *) { 7465 llvm_unreachable("Expression evaluator should not be called on stmts"); 7466 } 7467 bool VisitExpr(const Expr *E) { 7468 return Error(E); 7469 } 7470 7471 bool VisitConstantExpr(const ConstantExpr *E) { 7472 if (E->hasAPValueResult()) 7473 return DerivedSuccess(E->getAPValueResult(), E); 7474 7475 return StmtVisitorTy::Visit(E->getSubExpr()); 7476 } 7477 7478 bool VisitParenExpr(const ParenExpr *E) 7479 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7480 bool VisitUnaryExtension(const UnaryOperator *E) 7481 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7482 bool VisitUnaryPlus(const UnaryOperator *E) 7483 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7484 bool VisitChooseExpr(const ChooseExpr *E) 7485 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7486 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7487 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7488 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7489 { return StmtVisitorTy::Visit(E->getReplacement()); } 7490 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7491 TempVersionRAII RAII(*Info.CurrentCall); 7492 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7493 return StmtVisitorTy::Visit(E->getExpr()); 7494 } 7495 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7496 TempVersionRAII RAII(*Info.CurrentCall); 7497 // The initializer may not have been parsed yet, or might be erroneous. 7498 if (!E->getExpr()) 7499 return Error(E); 7500 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7501 return StmtVisitorTy::Visit(E->getExpr()); 7502 } 7503 7504 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7505 FullExpressionRAII Scope(Info); 7506 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7507 } 7508 7509 // Temporaries are registered when created, so we don't care about 7510 // CXXBindTemporaryExpr. 7511 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7512 return StmtVisitorTy::Visit(E->getSubExpr()); 7513 } 7514 7515 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7516 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7517 return static_cast<Derived*>(this)->VisitCastExpr(E); 7518 } 7519 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7520 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7521 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7522 return static_cast<Derived*>(this)->VisitCastExpr(E); 7523 } 7524 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7525 return static_cast<Derived*>(this)->VisitCastExpr(E); 7526 } 7527 7528 bool VisitBinaryOperator(const BinaryOperator *E) { 7529 switch (E->getOpcode()) { 7530 default: 7531 return Error(E); 7532 7533 case BO_Comma: 7534 VisitIgnoredValue(E->getLHS()); 7535 return StmtVisitorTy::Visit(E->getRHS()); 7536 7537 case BO_PtrMemD: 7538 case BO_PtrMemI: { 7539 LValue Obj; 7540 if (!HandleMemberPointerAccess(Info, E, Obj)) 7541 return false; 7542 APValue Result; 7543 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7544 return false; 7545 return DerivedSuccess(Result, E); 7546 } 7547 } 7548 } 7549 7550 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7551 return StmtVisitorTy::Visit(E->getSemanticForm()); 7552 } 7553 7554 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7555 // Evaluate and cache the common expression. We treat it as a temporary, 7556 // even though it's not quite the same thing. 7557 LValue CommonLV; 7558 if (!Evaluate(Info.CurrentCall->createTemporary( 7559 E->getOpaqueValue(), 7560 getStorageType(Info.Ctx, E->getOpaqueValue()), 7561 ScopeKind::FullExpression, CommonLV), 7562 Info, E->getCommon())) 7563 return false; 7564 7565 return HandleConditionalOperator(E); 7566 } 7567 7568 bool VisitConditionalOperator(const ConditionalOperator *E) { 7569 bool IsBcpCall = false; 7570 // If the condition (ignoring parens) is a __builtin_constant_p call, 7571 // the result is a constant expression if it can be folded without 7572 // side-effects. This is an important GNU extension. See GCC PR38377 7573 // for discussion. 7574 if (const CallExpr *CallCE = 7575 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7576 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7577 IsBcpCall = true; 7578 7579 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7580 // constant expression; we can't check whether it's potentially foldable. 7581 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7582 // it would return 'false' in this mode. 7583 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7584 return false; 7585 7586 FoldConstant Fold(Info, IsBcpCall); 7587 if (!HandleConditionalOperator(E)) { 7588 Fold.keepDiagnostics(); 7589 return false; 7590 } 7591 7592 return true; 7593 } 7594 7595 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7596 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7597 return DerivedSuccess(*Value, E); 7598 7599 const Expr *Source = E->getSourceExpr(); 7600 if (!Source) 7601 return Error(E); 7602 if (Source == E) { 7603 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7604 return Error(E); 7605 } 7606 return StmtVisitorTy::Visit(Source); 7607 } 7608 7609 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7610 for (const Expr *SemE : E->semantics()) { 7611 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7612 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7613 // result expression: there could be two different LValues that would 7614 // refer to the same object in that case, and we can't model that. 7615 if (SemE == E->getResultExpr()) 7616 return Error(E); 7617 7618 // Unique OVEs get evaluated if and when we encounter them when 7619 // emitting the rest of the semantic form, rather than eagerly. 7620 if (OVE->isUnique()) 7621 continue; 7622 7623 LValue LV; 7624 if (!Evaluate(Info.CurrentCall->createTemporary( 7625 OVE, getStorageType(Info.Ctx, OVE), 7626 ScopeKind::FullExpression, LV), 7627 Info, OVE->getSourceExpr())) 7628 return false; 7629 } else if (SemE == E->getResultExpr()) { 7630 if (!StmtVisitorTy::Visit(SemE)) 7631 return false; 7632 } else { 7633 if (!EvaluateIgnoredValue(Info, SemE)) 7634 return false; 7635 } 7636 } 7637 return true; 7638 } 7639 7640 bool VisitCallExpr(const CallExpr *E) { 7641 APValue Result; 7642 if (!handleCallExpr(E, Result, nullptr)) 7643 return false; 7644 return DerivedSuccess(Result, E); 7645 } 7646 7647 bool handleCallExpr(const CallExpr *E, APValue &Result, 7648 const LValue *ResultSlot) { 7649 CallScopeRAII CallScope(Info); 7650 7651 const Expr *Callee = E->getCallee()->IgnoreParens(); 7652 QualType CalleeType = Callee->getType(); 7653 7654 const FunctionDecl *FD = nullptr; 7655 LValue *This = nullptr, ThisVal; 7656 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs()); 7657 bool HasQualifier = false; 7658 7659 CallRef Call; 7660 7661 // Extract function decl and 'this' pointer from the callee. 7662 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7663 const CXXMethodDecl *Member = nullptr; 7664 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7665 // Explicit bound member calls, such as x.f() or p->g(); 7666 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7667 return false; 7668 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7669 if (!Member) 7670 return Error(Callee); 7671 This = &ThisVal; 7672 HasQualifier = ME->hasQualifier(); 7673 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7674 // Indirect bound member calls ('.*' or '->*'). 7675 const ValueDecl *D = 7676 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7677 if (!D) 7678 return false; 7679 Member = dyn_cast<CXXMethodDecl>(D); 7680 if (!Member) 7681 return Error(Callee); 7682 This = &ThisVal; 7683 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7684 if (!Info.getLangOpts().CPlusPlus20) 7685 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7686 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7687 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7688 } else 7689 return Error(Callee); 7690 FD = Member; 7691 } else if (CalleeType->isFunctionPointerType()) { 7692 LValue CalleeLV; 7693 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7694 return false; 7695 7696 if (!CalleeLV.getLValueOffset().isZero()) 7697 return Error(Callee); 7698 if (CalleeLV.isNullPointer()) { 7699 Info.FFDiag(Callee, diag::note_constexpr_null_callee) 7700 << const_cast<Expr *>(Callee); 7701 return false; 7702 } 7703 FD = dyn_cast_or_null<FunctionDecl>( 7704 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7705 if (!FD) 7706 return Error(Callee); 7707 // Don't call function pointers which have been cast to some other type. 7708 // Per DR (no number yet), the caller and callee can differ in noexcept. 7709 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7710 CalleeType->getPointeeType(), FD->getType())) { 7711 return Error(E); 7712 } 7713 7714 // For an (overloaded) assignment expression, evaluate the RHS before the 7715 // LHS. 7716 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7717 if (OCE && OCE->isAssignmentOp()) { 7718 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7719 Call = Info.CurrentCall->createCall(FD); 7720 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7721 Info, FD, /*RightToLeft=*/true)) 7722 return false; 7723 } 7724 7725 // Overloaded operator calls to member functions are represented as normal 7726 // calls with '*this' as the first argument. 7727 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7728 if (MD && !MD->isStatic()) { 7729 // FIXME: When selecting an implicit conversion for an overloaded 7730 // operator delete, we sometimes try to evaluate calls to conversion 7731 // operators without a 'this' parameter! 7732 if (Args.empty()) 7733 return Error(E); 7734 7735 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7736 return false; 7737 This = &ThisVal; 7738 7739 // If this is syntactically a simple assignment using a trivial 7740 // assignment operator, start the lifetimes of union members as needed, 7741 // per C++20 [class.union]5. 7742 if (Info.getLangOpts().CPlusPlus20 && OCE && 7743 OCE->getOperator() == OO_Equal && MD->isTrivial() && 7744 !HandleUnionActiveMemberChange(Info, Args[0], ThisVal)) 7745 return false; 7746 7747 Args = Args.slice(1); 7748 } else if (MD && MD->isLambdaStaticInvoker()) { 7749 // Map the static invoker for the lambda back to the call operator. 7750 // Conveniently, we don't have to slice out the 'this' argument (as is 7751 // being done for the non-static case), since a static member function 7752 // doesn't have an implicit argument passed in. 7753 const CXXRecordDecl *ClosureClass = MD->getParent(); 7754 assert( 7755 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7756 "Number of captures must be zero for conversion to function-ptr"); 7757 7758 const CXXMethodDecl *LambdaCallOp = 7759 ClosureClass->getLambdaCallOperator(); 7760 7761 // Set 'FD', the function that will be called below, to the call 7762 // operator. If the closure object represents a generic lambda, find 7763 // the corresponding specialization of the call operator. 7764 7765 if (ClosureClass->isGenericLambda()) { 7766 assert(MD->isFunctionTemplateSpecialization() && 7767 "A generic lambda's static-invoker function must be a " 7768 "template specialization"); 7769 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7770 FunctionTemplateDecl *CallOpTemplate = 7771 LambdaCallOp->getDescribedFunctionTemplate(); 7772 void *InsertPos = nullptr; 7773 FunctionDecl *CorrespondingCallOpSpecialization = 7774 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7775 assert(CorrespondingCallOpSpecialization && 7776 "We must always have a function call operator specialization " 7777 "that corresponds to our static invoker specialization"); 7778 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7779 } else 7780 FD = LambdaCallOp; 7781 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7782 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7783 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7784 LValue Ptr; 7785 if (!HandleOperatorNewCall(Info, E, Ptr)) 7786 return false; 7787 Ptr.moveInto(Result); 7788 return CallScope.destroy(); 7789 } else { 7790 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7791 } 7792 } 7793 } else 7794 return Error(E); 7795 7796 // Evaluate the arguments now if we've not already done so. 7797 if (!Call) { 7798 Call = Info.CurrentCall->createCall(FD); 7799 if (!EvaluateArgs(Args, Call, Info, FD)) 7800 return false; 7801 } 7802 7803 SmallVector<QualType, 4> CovariantAdjustmentPath; 7804 if (This) { 7805 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7806 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7807 // Perform virtual dispatch, if necessary. 7808 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7809 CovariantAdjustmentPath); 7810 if (!FD) 7811 return false; 7812 } else { 7813 // Check that the 'this' pointer points to an object of the right type. 7814 // FIXME: If this is an assignment operator call, we may need to change 7815 // the active union member before we check this. 7816 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7817 return false; 7818 } 7819 } 7820 7821 // Destructor calls are different enough that they have their own codepath. 7822 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7823 assert(This && "no 'this' pointer for destructor call"); 7824 return HandleDestruction(Info, E, *This, 7825 Info.Ctx.getRecordType(DD->getParent())) && 7826 CallScope.destroy(); 7827 } 7828 7829 const FunctionDecl *Definition = nullptr; 7830 Stmt *Body = FD->getBody(Definition); 7831 7832 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7833 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call, 7834 Body, Info, Result, ResultSlot)) 7835 return false; 7836 7837 if (!CovariantAdjustmentPath.empty() && 7838 !HandleCovariantReturnAdjustment(Info, E, Result, 7839 CovariantAdjustmentPath)) 7840 return false; 7841 7842 return CallScope.destroy(); 7843 } 7844 7845 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7846 return StmtVisitorTy::Visit(E->getInitializer()); 7847 } 7848 bool VisitInitListExpr(const InitListExpr *E) { 7849 if (E->getNumInits() == 0) 7850 return DerivedZeroInitialization(E); 7851 if (E->getNumInits() == 1) 7852 return StmtVisitorTy::Visit(E->getInit(0)); 7853 return Error(E); 7854 } 7855 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7856 return DerivedZeroInitialization(E); 7857 } 7858 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7859 return DerivedZeroInitialization(E); 7860 } 7861 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7862 return DerivedZeroInitialization(E); 7863 } 7864 7865 /// A member expression where the object is a prvalue is itself a prvalue. 7866 bool VisitMemberExpr(const MemberExpr *E) { 7867 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7868 "missing temporary materialization conversion"); 7869 assert(!E->isArrow() && "missing call to bound member function?"); 7870 7871 APValue Val; 7872 if (!Evaluate(Val, Info, E->getBase())) 7873 return false; 7874 7875 QualType BaseTy = E->getBase()->getType(); 7876 7877 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7878 if (!FD) return Error(E); 7879 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7880 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7881 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7882 7883 // Note: there is no lvalue base here. But this case should only ever 7884 // happen in C or in C++98, where we cannot be evaluating a constexpr 7885 // constructor, which is the only case the base matters. 7886 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7887 SubobjectDesignator Designator(BaseTy); 7888 Designator.addDeclUnchecked(FD); 7889 7890 APValue Result; 7891 return extractSubobject(Info, E, Obj, Designator, Result) && 7892 DerivedSuccess(Result, E); 7893 } 7894 7895 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7896 APValue Val; 7897 if (!Evaluate(Val, Info, E->getBase())) 7898 return false; 7899 7900 if (Val.isVector()) { 7901 SmallVector<uint32_t, 4> Indices; 7902 E->getEncodedElementAccess(Indices); 7903 if (Indices.size() == 1) { 7904 // Return scalar. 7905 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7906 } else { 7907 // Construct new APValue vector. 7908 SmallVector<APValue, 4> Elts; 7909 for (unsigned I = 0; I < Indices.size(); ++I) { 7910 Elts.push_back(Val.getVectorElt(Indices[I])); 7911 } 7912 APValue VecResult(Elts.data(), Indices.size()); 7913 return DerivedSuccess(VecResult, E); 7914 } 7915 } 7916 7917 return false; 7918 } 7919 7920 bool VisitCastExpr(const CastExpr *E) { 7921 switch (E->getCastKind()) { 7922 default: 7923 break; 7924 7925 case CK_AtomicToNonAtomic: { 7926 APValue AtomicVal; 7927 // This does not need to be done in place even for class/array types: 7928 // atomic-to-non-atomic conversion implies copying the object 7929 // representation. 7930 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7931 return false; 7932 return DerivedSuccess(AtomicVal, E); 7933 } 7934 7935 case CK_NoOp: 7936 case CK_UserDefinedConversion: 7937 return StmtVisitorTy::Visit(E->getSubExpr()); 7938 7939 case CK_LValueToRValue: { 7940 LValue LVal; 7941 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7942 return false; 7943 APValue RVal; 7944 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7945 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7946 LVal, RVal)) 7947 return false; 7948 return DerivedSuccess(RVal, E); 7949 } 7950 case CK_LValueToRValueBitCast: { 7951 APValue DestValue, SourceValue; 7952 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7953 return false; 7954 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7955 return false; 7956 return DerivedSuccess(DestValue, E); 7957 } 7958 7959 case CK_AddressSpaceConversion: { 7960 APValue Value; 7961 if (!Evaluate(Value, Info, E->getSubExpr())) 7962 return false; 7963 return DerivedSuccess(Value, E); 7964 } 7965 } 7966 7967 return Error(E); 7968 } 7969 7970 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7971 return VisitUnaryPostIncDec(UO); 7972 } 7973 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7974 return VisitUnaryPostIncDec(UO); 7975 } 7976 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7977 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7978 return Error(UO); 7979 7980 LValue LVal; 7981 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7982 return false; 7983 APValue RVal; 7984 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7985 UO->isIncrementOp(), &RVal)) 7986 return false; 7987 return DerivedSuccess(RVal, UO); 7988 } 7989 7990 bool VisitStmtExpr(const StmtExpr *E) { 7991 // We will have checked the full-expressions inside the statement expression 7992 // when they were completed, and don't need to check them again now. 7993 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior, 7994 false); 7995 7996 const CompoundStmt *CS = E->getSubStmt(); 7997 if (CS->body_empty()) 7998 return true; 7999 8000 BlockScopeRAII Scope(Info); 8001 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 8002 BE = CS->body_end(); 8003 /**/; ++BI) { 8004 if (BI + 1 == BE) { 8005 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 8006 if (!FinalExpr) { 8007 Info.FFDiag((*BI)->getBeginLoc(), 8008 diag::note_constexpr_stmt_expr_unsupported); 8009 return false; 8010 } 8011 return this->Visit(FinalExpr) && Scope.destroy(); 8012 } 8013 8014 APValue ReturnValue; 8015 StmtResult Result = { ReturnValue, nullptr }; 8016 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 8017 if (ESR != ESR_Succeeded) { 8018 // FIXME: If the statement-expression terminated due to 'return', 8019 // 'break', or 'continue', it would be nice to propagate that to 8020 // the outer statement evaluation rather than bailing out. 8021 if (ESR != ESR_Failed) 8022 Info.FFDiag((*BI)->getBeginLoc(), 8023 diag::note_constexpr_stmt_expr_unsupported); 8024 return false; 8025 } 8026 } 8027 8028 llvm_unreachable("Return from function from the loop above."); 8029 } 8030 8031 /// Visit a value which is evaluated, but whose value is ignored. 8032 void VisitIgnoredValue(const Expr *E) { 8033 EvaluateIgnoredValue(Info, E); 8034 } 8035 8036 /// Potentially visit a MemberExpr's base expression. 8037 void VisitIgnoredBaseExpression(const Expr *E) { 8038 // While MSVC doesn't evaluate the base expression, it does diagnose the 8039 // presence of side-effecting behavior. 8040 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 8041 return; 8042 VisitIgnoredValue(E); 8043 } 8044 }; 8045 8046 } // namespace 8047 8048 //===----------------------------------------------------------------------===// 8049 // Common base class for lvalue and temporary evaluation. 8050 //===----------------------------------------------------------------------===// 8051 namespace { 8052 template<class Derived> 8053 class LValueExprEvaluatorBase 8054 : public ExprEvaluatorBase<Derived> { 8055 protected: 8056 LValue &Result; 8057 bool InvalidBaseOK; 8058 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 8059 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 8060 8061 bool Success(APValue::LValueBase B) { 8062 Result.set(B); 8063 return true; 8064 } 8065 8066 bool evaluatePointer(const Expr *E, LValue &Result) { 8067 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 8068 } 8069 8070 public: 8071 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 8072 : ExprEvaluatorBaseTy(Info), Result(Result), 8073 InvalidBaseOK(InvalidBaseOK) {} 8074 8075 bool Success(const APValue &V, const Expr *E) { 8076 Result.setFrom(this->Info.Ctx, V); 8077 return true; 8078 } 8079 8080 bool VisitMemberExpr(const MemberExpr *E) { 8081 // Handle non-static data members. 8082 QualType BaseTy; 8083 bool EvalOK; 8084 if (E->isArrow()) { 8085 EvalOK = evaluatePointer(E->getBase(), Result); 8086 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 8087 } else if (E->getBase()->isPRValue()) { 8088 assert(E->getBase()->getType()->isRecordType()); 8089 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 8090 BaseTy = E->getBase()->getType(); 8091 } else { 8092 EvalOK = this->Visit(E->getBase()); 8093 BaseTy = E->getBase()->getType(); 8094 } 8095 if (!EvalOK) { 8096 if (!InvalidBaseOK) 8097 return false; 8098 Result.setInvalid(E); 8099 return true; 8100 } 8101 8102 const ValueDecl *MD = E->getMemberDecl(); 8103 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 8104 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 8105 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 8106 (void)BaseTy; 8107 if (!HandleLValueMember(this->Info, E, Result, FD)) 8108 return false; 8109 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 8110 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 8111 return false; 8112 } else 8113 return this->Error(E); 8114 8115 if (MD->getType()->isReferenceType()) { 8116 APValue RefValue; 8117 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 8118 RefValue)) 8119 return false; 8120 return Success(RefValue, E); 8121 } 8122 return true; 8123 } 8124 8125 bool VisitBinaryOperator(const BinaryOperator *E) { 8126 switch (E->getOpcode()) { 8127 default: 8128 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8129 8130 case BO_PtrMemD: 8131 case BO_PtrMemI: 8132 return HandleMemberPointerAccess(this->Info, E, Result); 8133 } 8134 } 8135 8136 bool VisitCastExpr(const CastExpr *E) { 8137 switch (E->getCastKind()) { 8138 default: 8139 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8140 8141 case CK_DerivedToBase: 8142 case CK_UncheckedDerivedToBase: 8143 if (!this->Visit(E->getSubExpr())) 8144 return false; 8145 8146 // Now figure out the necessary offset to add to the base LV to get from 8147 // the derived class to the base class. 8148 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8149 Result); 8150 } 8151 } 8152 }; 8153 } 8154 8155 //===----------------------------------------------------------------------===// 8156 // LValue Evaluation 8157 // 8158 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8159 // function designators (in C), decl references to void objects (in C), and 8160 // temporaries (if building with -Wno-address-of-temporary). 8161 // 8162 // LValue evaluation produces values comprising a base expression of one of the 8163 // following types: 8164 // - Declarations 8165 // * VarDecl 8166 // * FunctionDecl 8167 // - Literals 8168 // * CompoundLiteralExpr in C (and in global scope in C++) 8169 // * StringLiteral 8170 // * PredefinedExpr 8171 // * ObjCStringLiteralExpr 8172 // * ObjCEncodeExpr 8173 // * AddrLabelExpr 8174 // * BlockExpr 8175 // * CallExpr for a MakeStringConstant builtin 8176 // - typeid(T) expressions, as TypeInfoLValues 8177 // - Locals and temporaries 8178 // * MaterializeTemporaryExpr 8179 // * Any Expr, with a CallIndex indicating the function in which the temporary 8180 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8181 // from the AST (FIXME). 8182 // * A MaterializeTemporaryExpr that has static storage duration, with no 8183 // CallIndex, for a lifetime-extended temporary. 8184 // * The ConstantExpr that is currently being evaluated during evaluation of an 8185 // immediate invocation. 8186 // plus an offset in bytes. 8187 //===----------------------------------------------------------------------===// 8188 namespace { 8189 class LValueExprEvaluator 8190 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8191 public: 8192 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8193 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8194 8195 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8196 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8197 8198 bool VisitCallExpr(const CallExpr *E); 8199 bool VisitDeclRefExpr(const DeclRefExpr *E); 8200 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8201 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8202 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8203 bool VisitMemberExpr(const MemberExpr *E); 8204 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8205 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8206 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8207 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8208 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8209 bool VisitUnaryDeref(const UnaryOperator *E); 8210 bool VisitUnaryReal(const UnaryOperator *E); 8211 bool VisitUnaryImag(const UnaryOperator *E); 8212 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8213 return VisitUnaryPreIncDec(UO); 8214 } 8215 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8216 return VisitUnaryPreIncDec(UO); 8217 } 8218 bool VisitBinAssign(const BinaryOperator *BO); 8219 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8220 8221 bool VisitCastExpr(const CastExpr *E) { 8222 switch (E->getCastKind()) { 8223 default: 8224 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8225 8226 case CK_LValueBitCast: 8227 this->CCEDiag(E, diag::note_constexpr_invalid_cast) 8228 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 8229 if (!Visit(E->getSubExpr())) 8230 return false; 8231 Result.Designator.setInvalid(); 8232 return true; 8233 8234 case CK_BaseToDerived: 8235 if (!Visit(E->getSubExpr())) 8236 return false; 8237 return HandleBaseToDerivedCast(Info, E, Result); 8238 8239 case CK_Dynamic: 8240 if (!Visit(E->getSubExpr())) 8241 return false; 8242 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8243 } 8244 } 8245 }; 8246 } // end anonymous namespace 8247 8248 /// Evaluate an expression as an lvalue. This can be legitimately called on 8249 /// expressions which are not glvalues, in three cases: 8250 /// * function designators in C, and 8251 /// * "extern void" objects 8252 /// * @selector() expressions in Objective-C 8253 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8254 bool InvalidBaseOK) { 8255 assert(!E->isValueDependent()); 8256 assert(E->isGLValue() || E->getType()->isFunctionType() || 8257 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens())); 8258 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8259 } 8260 8261 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8262 const NamedDecl *D = E->getDecl(); 8263 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl, 8264 UnnamedGlobalConstantDecl>(D)) 8265 return Success(cast<ValueDecl>(D)); 8266 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8267 return VisitVarDecl(E, VD); 8268 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8269 return Visit(BD->getBinding()); 8270 return Error(E); 8271 } 8272 8273 8274 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8275 8276 // If we are within a lambda's call operator, check whether the 'VD' referred 8277 // to within 'E' actually represents a lambda-capture that maps to a 8278 // data-member/field within the closure object, and if so, evaluate to the 8279 // field or what the field refers to. 8280 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8281 isa<DeclRefExpr>(E) && 8282 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8283 // We don't always have a complete capture-map when checking or inferring if 8284 // the function call operator meets the requirements of a constexpr function 8285 // - but we don't need to evaluate the captures to determine constexprness 8286 // (dcl.constexpr C++17). 8287 if (Info.checkingPotentialConstantExpression()) 8288 return false; 8289 8290 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8291 // Start with 'Result' referring to the complete closure object... 8292 Result = *Info.CurrentCall->This; 8293 // ... then update it to refer to the field of the closure object 8294 // that represents the capture. 8295 if (!HandleLValueMember(Info, E, Result, FD)) 8296 return false; 8297 // And if the field is of reference type, update 'Result' to refer to what 8298 // the field refers to. 8299 if (FD->getType()->isReferenceType()) { 8300 APValue RVal; 8301 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8302 RVal)) 8303 return false; 8304 Result.setFrom(Info.Ctx, RVal); 8305 } 8306 return true; 8307 } 8308 } 8309 8310 CallStackFrame *Frame = nullptr; 8311 unsigned Version = 0; 8312 if (VD->hasLocalStorage()) { 8313 // Only if a local variable was declared in the function currently being 8314 // evaluated, do we expect to be able to find its value in the current 8315 // frame. (Otherwise it was likely declared in an enclosing context and 8316 // could either have a valid evaluatable value (for e.g. a constexpr 8317 // variable) or be ill-formed (and trigger an appropriate evaluation 8318 // diagnostic)). 8319 CallStackFrame *CurrFrame = Info.CurrentCall; 8320 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8321 // Function parameters are stored in some caller's frame. (Usually the 8322 // immediate caller, but for an inherited constructor they may be more 8323 // distant.) 8324 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8325 if (CurrFrame->Arguments) { 8326 VD = CurrFrame->Arguments.getOrigParam(PVD); 8327 Frame = 8328 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8329 Version = CurrFrame->Arguments.Version; 8330 } 8331 } else { 8332 Frame = CurrFrame; 8333 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8334 } 8335 } 8336 } 8337 8338 if (!VD->getType()->isReferenceType()) { 8339 if (Frame) { 8340 Result.set({VD, Frame->Index, Version}); 8341 return true; 8342 } 8343 return Success(VD); 8344 } 8345 8346 if (!Info.getLangOpts().CPlusPlus11) { 8347 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8348 << VD << VD->getType(); 8349 Info.Note(VD->getLocation(), diag::note_declared_at); 8350 } 8351 8352 APValue *V; 8353 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8354 return false; 8355 if (!V->hasValue()) { 8356 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8357 // adjust the diagnostic to say that. 8358 if (!Info.checkingPotentialConstantExpression()) 8359 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8360 return false; 8361 } 8362 return Success(*V, E); 8363 } 8364 8365 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) { 8366 if (!IsConstantEvaluatedBuiltinCall(E)) 8367 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8368 8369 switch (E->getBuiltinCallee()) { 8370 default: 8371 return false; 8372 case Builtin::BIas_const: 8373 case Builtin::BIforward: 8374 case Builtin::BIforward_like: 8375 case Builtin::BImove: 8376 case Builtin::BImove_if_noexcept: 8377 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr()) 8378 return Visit(E->getArg(0)); 8379 break; 8380 } 8381 8382 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8383 } 8384 8385 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8386 const MaterializeTemporaryExpr *E) { 8387 // Walk through the expression to find the materialized temporary itself. 8388 SmallVector<const Expr *, 2> CommaLHSs; 8389 SmallVector<SubobjectAdjustment, 2> Adjustments; 8390 const Expr *Inner = 8391 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8392 8393 // If we passed any comma operators, evaluate their LHSs. 8394 for (const Expr *E : CommaLHSs) 8395 if (!EvaluateIgnoredValue(Info, E)) 8396 return false; 8397 8398 // A materialized temporary with static storage duration can appear within the 8399 // result of a constant expression evaluation, so we need to preserve its 8400 // value for use outside this evaluation. 8401 APValue *Value; 8402 if (E->getStorageDuration() == SD_Static) { 8403 if (Info.EvalMode == EvalInfo::EM_ConstantFold) 8404 return false; 8405 // FIXME: What about SD_Thread? 8406 Value = E->getOrCreateValue(true); 8407 *Value = APValue(); 8408 Result.set(E); 8409 } else { 8410 Value = &Info.CurrentCall->createTemporary( 8411 E, E->getType(), 8412 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8413 : ScopeKind::Block, 8414 Result); 8415 } 8416 8417 QualType Type = Inner->getType(); 8418 8419 // Materialize the temporary itself. 8420 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8421 *Value = APValue(); 8422 return false; 8423 } 8424 8425 // Adjust our lvalue to refer to the desired subobject. 8426 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8427 --I; 8428 switch (Adjustments[I].Kind) { 8429 case SubobjectAdjustment::DerivedToBaseAdjustment: 8430 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8431 Type, Result)) 8432 return false; 8433 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8434 break; 8435 8436 case SubobjectAdjustment::FieldAdjustment: 8437 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8438 return false; 8439 Type = Adjustments[I].Field->getType(); 8440 break; 8441 8442 case SubobjectAdjustment::MemberPointerAdjustment: 8443 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8444 Adjustments[I].Ptr.RHS)) 8445 return false; 8446 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8447 break; 8448 } 8449 } 8450 8451 return true; 8452 } 8453 8454 bool 8455 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8456 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8457 "lvalue compound literal in c++?"); 8458 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8459 // only see this when folding in C, so there's no standard to follow here. 8460 return Success(E); 8461 } 8462 8463 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8464 TypeInfoLValue TypeInfo; 8465 8466 if (!E->isPotentiallyEvaluated()) { 8467 if (E->isTypeOperand()) 8468 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8469 else 8470 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8471 } else { 8472 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8473 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8474 << E->getExprOperand()->getType() 8475 << E->getExprOperand()->getSourceRange(); 8476 } 8477 8478 if (!Visit(E->getExprOperand())) 8479 return false; 8480 8481 std::optional<DynamicType> DynType = 8482 ComputeDynamicType(Info, E, Result, AK_TypeId); 8483 if (!DynType) 8484 return false; 8485 8486 TypeInfo = 8487 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8488 } 8489 8490 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8491 } 8492 8493 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8494 return Success(E->getGuidDecl()); 8495 } 8496 8497 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8498 // Handle static data members. 8499 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8500 VisitIgnoredBaseExpression(E->getBase()); 8501 return VisitVarDecl(E, VD); 8502 } 8503 8504 // Handle static member functions. 8505 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8506 if (MD->isStatic()) { 8507 VisitIgnoredBaseExpression(E->getBase()); 8508 return Success(MD); 8509 } 8510 } 8511 8512 // Handle non-static data members. 8513 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8514 } 8515 8516 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8517 // FIXME: Deal with vectors as array subscript bases. 8518 if (E->getBase()->getType()->isVectorType() || 8519 E->getBase()->getType()->isVLSTBuiltinType()) 8520 return Error(E); 8521 8522 APSInt Index; 8523 bool Success = true; 8524 8525 // C++17's rules require us to evaluate the LHS first, regardless of which 8526 // side is the base. 8527 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8528 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8529 : !EvaluateInteger(SubExpr, Index, Info)) { 8530 if (!Info.noteFailure()) 8531 return false; 8532 Success = false; 8533 } 8534 } 8535 8536 return Success && 8537 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8538 } 8539 8540 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8541 return evaluatePointer(E->getSubExpr(), Result); 8542 } 8543 8544 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8545 if (!Visit(E->getSubExpr())) 8546 return false; 8547 // __real is a no-op on scalar lvalues. 8548 if (E->getSubExpr()->getType()->isAnyComplexType()) 8549 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8550 return true; 8551 } 8552 8553 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8554 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8555 "lvalue __imag__ on scalar?"); 8556 if (!Visit(E->getSubExpr())) 8557 return false; 8558 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8559 return true; 8560 } 8561 8562 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8563 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8564 return Error(UO); 8565 8566 if (!this->Visit(UO->getSubExpr())) 8567 return false; 8568 8569 return handleIncDec( 8570 this->Info, UO, Result, UO->getSubExpr()->getType(), 8571 UO->isIncrementOp(), nullptr); 8572 } 8573 8574 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8575 const CompoundAssignOperator *CAO) { 8576 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8577 return Error(CAO); 8578 8579 bool Success = true; 8580 8581 // C++17 onwards require that we evaluate the RHS first. 8582 APValue RHS; 8583 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8584 if (!Info.noteFailure()) 8585 return false; 8586 Success = false; 8587 } 8588 8589 // The overall lvalue result is the result of evaluating the LHS. 8590 if (!this->Visit(CAO->getLHS()) || !Success) 8591 return false; 8592 8593 return handleCompoundAssignment( 8594 this->Info, CAO, 8595 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8596 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8597 } 8598 8599 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8600 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8601 return Error(E); 8602 8603 bool Success = true; 8604 8605 // C++17 onwards require that we evaluate the RHS first. 8606 APValue NewVal; 8607 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8608 if (!Info.noteFailure()) 8609 return false; 8610 Success = false; 8611 } 8612 8613 if (!this->Visit(E->getLHS()) || !Success) 8614 return false; 8615 8616 if (Info.getLangOpts().CPlusPlus20 && 8617 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8618 return false; 8619 8620 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8621 NewVal); 8622 } 8623 8624 //===----------------------------------------------------------------------===// 8625 // Pointer Evaluation 8626 //===----------------------------------------------------------------------===// 8627 8628 /// Attempts to compute the number of bytes available at the pointer 8629 /// returned by a function with the alloc_size attribute. Returns true if we 8630 /// were successful. Places an unsigned number into `Result`. 8631 /// 8632 /// This expects the given CallExpr to be a call to a function with an 8633 /// alloc_size attribute. 8634 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8635 const CallExpr *Call, 8636 llvm::APInt &Result) { 8637 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8638 8639 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8640 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8641 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8642 if (Call->getNumArgs() <= SizeArgNo) 8643 return false; 8644 8645 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8646 Expr::EvalResult ExprResult; 8647 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8648 return false; 8649 Into = ExprResult.Val.getInt(); 8650 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8651 return false; 8652 Into = Into.zext(BitsInSizeT); 8653 return true; 8654 }; 8655 8656 APSInt SizeOfElem; 8657 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8658 return false; 8659 8660 if (!AllocSize->getNumElemsParam().isValid()) { 8661 Result = std::move(SizeOfElem); 8662 return true; 8663 } 8664 8665 APSInt NumberOfElems; 8666 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8667 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8668 return false; 8669 8670 bool Overflow; 8671 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8672 if (Overflow) 8673 return false; 8674 8675 Result = std::move(BytesAvailable); 8676 return true; 8677 } 8678 8679 /// Convenience function. LVal's base must be a call to an alloc_size 8680 /// function. 8681 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8682 const LValue &LVal, 8683 llvm::APInt &Result) { 8684 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8685 "Can't get the size of a non alloc_size function"); 8686 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8687 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8688 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8689 } 8690 8691 /// Attempts to evaluate the given LValueBase as the result of a call to 8692 /// a function with the alloc_size attribute. If it was possible to do so, this 8693 /// function will return true, make Result's Base point to said function call, 8694 /// and mark Result's Base as invalid. 8695 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8696 LValue &Result) { 8697 if (Base.isNull()) 8698 return false; 8699 8700 // Because we do no form of static analysis, we only support const variables. 8701 // 8702 // Additionally, we can't support parameters, nor can we support static 8703 // variables (in the latter case, use-before-assign isn't UB; in the former, 8704 // we have no clue what they'll be assigned to). 8705 const auto *VD = 8706 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8707 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8708 return false; 8709 8710 const Expr *Init = VD->getAnyInitializer(); 8711 if (!Init || Init->getType().isNull()) 8712 return false; 8713 8714 const Expr *E = Init->IgnoreParens(); 8715 if (!tryUnwrapAllocSizeCall(E)) 8716 return false; 8717 8718 // Store E instead of E unwrapped so that the type of the LValue's base is 8719 // what the user wanted. 8720 Result.setInvalid(E); 8721 8722 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8723 Result.addUnsizedArray(Info, E, Pointee); 8724 return true; 8725 } 8726 8727 namespace { 8728 class PointerExprEvaluator 8729 : public ExprEvaluatorBase<PointerExprEvaluator> { 8730 LValue &Result; 8731 bool InvalidBaseOK; 8732 8733 bool Success(const Expr *E) { 8734 Result.set(E); 8735 return true; 8736 } 8737 8738 bool evaluateLValue(const Expr *E, LValue &Result) { 8739 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8740 } 8741 8742 bool evaluatePointer(const Expr *E, LValue &Result) { 8743 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8744 } 8745 8746 bool visitNonBuiltinCallExpr(const CallExpr *E); 8747 public: 8748 8749 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8750 : ExprEvaluatorBaseTy(info), Result(Result), 8751 InvalidBaseOK(InvalidBaseOK) {} 8752 8753 bool Success(const APValue &V, const Expr *E) { 8754 Result.setFrom(Info.Ctx, V); 8755 return true; 8756 } 8757 bool ZeroInitialization(const Expr *E) { 8758 Result.setNull(Info.Ctx, E->getType()); 8759 return true; 8760 } 8761 8762 bool VisitBinaryOperator(const BinaryOperator *E); 8763 bool VisitCastExpr(const CastExpr* E); 8764 bool VisitUnaryAddrOf(const UnaryOperator *E); 8765 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8766 { return Success(E); } 8767 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8768 if (E->isExpressibleAsConstantInitializer()) 8769 return Success(E); 8770 if (Info.noteFailure()) 8771 EvaluateIgnoredValue(Info, E->getSubExpr()); 8772 return Error(E); 8773 } 8774 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8775 { return Success(E); } 8776 bool VisitCallExpr(const CallExpr *E); 8777 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8778 bool VisitBlockExpr(const BlockExpr *E) { 8779 if (!E->getBlockDecl()->hasCaptures()) 8780 return Success(E); 8781 return Error(E); 8782 } 8783 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8784 // Can't look at 'this' when checking a potential constant expression. 8785 if (Info.checkingPotentialConstantExpression()) 8786 return false; 8787 if (!Info.CurrentCall->This) { 8788 if (Info.getLangOpts().CPlusPlus11) 8789 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8790 else 8791 Info.FFDiag(E); 8792 return false; 8793 } 8794 Result = *Info.CurrentCall->This; 8795 8796 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8797 // Ensure we actually have captured 'this'. If something was wrong with 8798 // 'this' capture, the error would have been previously reported. 8799 // Otherwise we can be inside of a default initialization of an object 8800 // declared by lambda's body, so no need to return false. 8801 if (!Info.CurrentCall->LambdaThisCaptureField) 8802 return true; 8803 8804 // If we have captured 'this', the 'this' expression refers 8805 // to the enclosing '*this' object (either by value or reference) which is 8806 // either copied into the closure object's field that represents the 8807 // '*this' or refers to '*this'. 8808 // Update 'Result' to refer to the data member/field of the closure object 8809 // that represents the '*this' capture. 8810 if (!HandleLValueMember(Info, E, Result, 8811 Info.CurrentCall->LambdaThisCaptureField)) 8812 return false; 8813 // If we captured '*this' by reference, replace the field with its referent. 8814 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8815 ->isPointerType()) { 8816 APValue RVal; 8817 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8818 RVal)) 8819 return false; 8820 8821 Result.setFrom(Info.Ctx, RVal); 8822 } 8823 } 8824 return true; 8825 } 8826 8827 bool VisitCXXNewExpr(const CXXNewExpr *E); 8828 8829 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8830 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?"); 8831 APValue LValResult = E->EvaluateInContext( 8832 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8833 Result.setFrom(Info.Ctx, LValResult); 8834 return true; 8835 } 8836 8837 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8838 std::string ResultStr = E->ComputeName(Info.Ctx); 8839 8840 QualType CharTy = Info.Ctx.CharTy.withConst(); 8841 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8842 ResultStr.size() + 1); 8843 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8844 ArrayType::Normal, 0); 8845 8846 StringLiteral *SL = 8847 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary, 8848 /*Pascal*/ false, ArrayTy, E->getLocation()); 8849 8850 evaluateLValue(SL, Result); 8851 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8852 return true; 8853 } 8854 8855 // FIXME: Missing: @protocol, @selector 8856 }; 8857 } // end anonymous namespace 8858 8859 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8860 bool InvalidBaseOK) { 8861 assert(!E->isValueDependent()); 8862 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8863 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8864 } 8865 8866 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8867 if (E->getOpcode() != BO_Add && 8868 E->getOpcode() != BO_Sub) 8869 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8870 8871 const Expr *PExp = E->getLHS(); 8872 const Expr *IExp = E->getRHS(); 8873 if (IExp->getType()->isPointerType()) 8874 std::swap(PExp, IExp); 8875 8876 bool EvalPtrOK = evaluatePointer(PExp, Result); 8877 if (!EvalPtrOK && !Info.noteFailure()) 8878 return false; 8879 8880 llvm::APSInt Offset; 8881 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8882 return false; 8883 8884 if (E->getOpcode() == BO_Sub) 8885 negateAsSigned(Offset); 8886 8887 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8888 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8889 } 8890 8891 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8892 return evaluateLValue(E->getSubExpr(), Result); 8893 } 8894 8895 // Is the provided decl 'std::source_location::current'? 8896 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) { 8897 if (!FD) 8898 return false; 8899 const IdentifierInfo *FnII = FD->getIdentifier(); 8900 if (!FnII || !FnII->isStr("current")) 8901 return false; 8902 8903 const auto *RD = dyn_cast<RecordDecl>(FD->getParent()); 8904 if (!RD) 8905 return false; 8906 8907 const IdentifierInfo *ClassII = RD->getIdentifier(); 8908 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location"); 8909 } 8910 8911 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8912 const Expr *SubExpr = E->getSubExpr(); 8913 8914 switch (E->getCastKind()) { 8915 default: 8916 break; 8917 case CK_BitCast: 8918 case CK_CPointerToObjCPointerCast: 8919 case CK_BlockPointerToObjCPointerCast: 8920 case CK_AnyPointerToBlockPointerCast: 8921 case CK_AddressSpaceConversion: 8922 if (!Visit(SubExpr)) 8923 return false; 8924 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8925 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8926 // also static_casts, but we disallow them as a resolution to DR1312. 8927 if (!E->getType()->isVoidPointerType()) { 8928 // In some circumstances, we permit casting from void* to cv1 T*, when the 8929 // actual pointee object is actually a cv2 T. 8930 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid && 8931 !Result.IsNullPtr; 8932 bool VoidPtrCastMaybeOK = 8933 HasValidResult && 8934 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8935 E->getType()->getPointeeType()); 8936 // 1. We'll allow it in std::allocator::allocate, and anything which that 8937 // calls. 8938 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s 8939 // <source_location> header. Fixed in GCC 12 and later (2022-04-??). 8940 // We'll allow it in the body of std::source_location::current. GCC's 8941 // implementation had a parameter of type `void*`, and casts from 8942 // that back to `const __impl*` in its body. 8943 if (VoidPtrCastMaybeOK && 8944 (Info.getStdAllocatorCaller("allocate") || 8945 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) || 8946 Info.getLangOpts().CPlusPlus26)) { 8947 // Permitted. 8948 } else { 8949 if (SubExpr->getType()->isVoidPointerType()) { 8950 if (HasValidResult) 8951 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast) 8952 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26 8953 << Result.Designator.getType(Info.Ctx).getCanonicalType() 8954 << E->getType()->getPointeeType(); 8955 else 8956 CCEDiag(E, diag::note_constexpr_invalid_cast) 8957 << 3 << SubExpr->getType(); 8958 } else 8959 CCEDiag(E, diag::note_constexpr_invalid_cast) 8960 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 8961 Result.Designator.setInvalid(); 8962 } 8963 } 8964 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8965 ZeroInitialization(E); 8966 return true; 8967 8968 case CK_DerivedToBase: 8969 case CK_UncheckedDerivedToBase: 8970 if (!evaluatePointer(E->getSubExpr(), Result)) 8971 return false; 8972 if (!Result.Base && Result.Offset.isZero()) 8973 return true; 8974 8975 // Now figure out the necessary offset to add to the base LV to get from 8976 // the derived class to the base class. 8977 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8978 castAs<PointerType>()->getPointeeType(), 8979 Result); 8980 8981 case CK_BaseToDerived: 8982 if (!Visit(E->getSubExpr())) 8983 return false; 8984 if (!Result.Base && Result.Offset.isZero()) 8985 return true; 8986 return HandleBaseToDerivedCast(Info, E, Result); 8987 8988 case CK_Dynamic: 8989 if (!Visit(E->getSubExpr())) 8990 return false; 8991 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8992 8993 case CK_NullToPointer: 8994 VisitIgnoredValue(E->getSubExpr()); 8995 return ZeroInitialization(E); 8996 8997 case CK_IntegralToPointer: { 8998 CCEDiag(E, diag::note_constexpr_invalid_cast) 8999 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 9000 9001 APValue Value; 9002 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 9003 break; 9004 9005 if (Value.isInt()) { 9006 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 9007 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 9008 Result.Base = (Expr*)nullptr; 9009 Result.InvalidBase = false; 9010 Result.Offset = CharUnits::fromQuantity(N); 9011 Result.Designator.setInvalid(); 9012 Result.IsNullPtr = false; 9013 return true; 9014 } else { 9015 // Cast is of an lvalue, no need to change value. 9016 Result.setFrom(Info.Ctx, Value); 9017 return true; 9018 } 9019 } 9020 9021 case CK_ArrayToPointerDecay: { 9022 if (SubExpr->isGLValue()) { 9023 if (!evaluateLValue(SubExpr, Result)) 9024 return false; 9025 } else { 9026 APValue &Value = Info.CurrentCall->createTemporary( 9027 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 9028 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 9029 return false; 9030 } 9031 // The result is a pointer to the first element of the array. 9032 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 9033 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 9034 Result.addArray(Info, E, CAT); 9035 else 9036 Result.addUnsizedArray(Info, E, AT->getElementType()); 9037 return true; 9038 } 9039 9040 case CK_FunctionToPointerDecay: 9041 return evaluateLValue(SubExpr, Result); 9042 9043 case CK_LValueToRValue: { 9044 LValue LVal; 9045 if (!evaluateLValue(E->getSubExpr(), LVal)) 9046 return false; 9047 9048 APValue RVal; 9049 // Note, we use the subexpression's type in order to retain cv-qualifiers. 9050 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 9051 LVal, RVal)) 9052 return InvalidBaseOK && 9053 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 9054 return Success(RVal, E); 9055 } 9056 } 9057 9058 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9059 } 9060 9061 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 9062 UnaryExprOrTypeTrait ExprKind) { 9063 // C++ [expr.alignof]p3: 9064 // When alignof is applied to a reference type, the result is the 9065 // alignment of the referenced type. 9066 T = T.getNonReferenceType(); 9067 9068 if (T.getQualifiers().hasUnaligned()) 9069 return CharUnits::One(); 9070 9071 const bool AlignOfReturnsPreferred = 9072 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 9073 9074 // __alignof is defined to return the preferred alignment. 9075 // Before 8, clang returned the preferred alignment for alignof and _Alignof 9076 // as well. 9077 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 9078 return Info.Ctx.toCharUnitsFromBits( 9079 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 9080 // alignof and _Alignof are defined to return the ABI alignment. 9081 else if (ExprKind == UETT_AlignOf) 9082 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 9083 else 9084 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 9085 } 9086 9087 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 9088 UnaryExprOrTypeTrait ExprKind) { 9089 E = E->IgnoreParens(); 9090 9091 // The kinds of expressions that we have special-case logic here for 9092 // should be kept up to date with the special checks for those 9093 // expressions in Sema. 9094 9095 // alignof decl is always accepted, even if it doesn't make sense: we default 9096 // to 1 in those cases. 9097 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9098 return Info.Ctx.getDeclAlign(DRE->getDecl(), 9099 /*RefAsPointee*/true); 9100 9101 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 9102 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 9103 /*RefAsPointee*/true); 9104 9105 return GetAlignOfType(Info, E->getType(), ExprKind); 9106 } 9107 9108 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 9109 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 9110 return Info.Ctx.getDeclAlign(VD); 9111 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 9112 return GetAlignOfExpr(Info, E, UETT_AlignOf); 9113 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 9114 } 9115 9116 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 9117 /// __builtin_is_aligned and __builtin_assume_aligned. 9118 static bool getAlignmentArgument(const Expr *E, QualType ForType, 9119 EvalInfo &Info, APSInt &Alignment) { 9120 if (!EvaluateInteger(E, Alignment, Info)) 9121 return false; 9122 if (Alignment < 0 || !Alignment.isPowerOf2()) { 9123 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 9124 return false; 9125 } 9126 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 9127 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 9128 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 9129 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 9130 << MaxValue << ForType << Alignment; 9131 return false; 9132 } 9133 // Ensure both alignment and source value have the same bit width so that we 9134 // don't assert when computing the resulting value. 9135 APSInt ExtAlignment = 9136 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 9137 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 9138 "Alignment should not be changed by ext/trunc"); 9139 Alignment = ExtAlignment; 9140 assert(Alignment.getBitWidth() == SrcWidth); 9141 return true; 9142 } 9143 9144 // To be clear: this happily visits unsupported builtins. Better name welcomed. 9145 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 9146 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 9147 return true; 9148 9149 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 9150 return false; 9151 9152 Result.setInvalid(E); 9153 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 9154 Result.addUnsizedArray(Info, E, PointeeTy); 9155 return true; 9156 } 9157 9158 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 9159 if (!IsConstantEvaluatedBuiltinCall(E)) 9160 return visitNonBuiltinCallExpr(E); 9161 return VisitBuiltinCallExpr(E, E->getBuiltinCallee()); 9162 } 9163 9164 // Determine if T is a character type for which we guarantee that 9165 // sizeof(T) == 1. 9166 static bool isOneByteCharacterType(QualType T) { 9167 return T->isCharType() || T->isChar8Type(); 9168 } 9169 9170 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9171 unsigned BuiltinOp) { 9172 if (IsNoOpCall(E)) 9173 return Success(E); 9174 9175 switch (BuiltinOp) { 9176 case Builtin::BIaddressof: 9177 case Builtin::BI__addressof: 9178 case Builtin::BI__builtin_addressof: 9179 return evaluateLValue(E->getArg(0), Result); 9180 case Builtin::BI__builtin_assume_aligned: { 9181 // We need to be very careful here because: if the pointer does not have the 9182 // asserted alignment, then the behavior is undefined, and undefined 9183 // behavior is non-constant. 9184 if (!evaluatePointer(E->getArg(0), Result)) 9185 return false; 9186 9187 LValue OffsetResult(Result); 9188 APSInt Alignment; 9189 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9190 Alignment)) 9191 return false; 9192 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 9193 9194 if (E->getNumArgs() > 2) { 9195 APSInt Offset; 9196 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9197 return false; 9198 9199 int64_t AdditionalOffset = -Offset.getZExtValue(); 9200 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9201 } 9202 9203 // If there is a base object, then it must have the correct alignment. 9204 if (OffsetResult.Base) { 9205 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9206 9207 if (BaseAlignment < Align) { 9208 Result.Designator.setInvalid(); 9209 // FIXME: Add support to Diagnostic for long / long long. 9210 CCEDiag(E->getArg(0), 9211 diag::note_constexpr_baa_insufficient_alignment) << 0 9212 << (unsigned)BaseAlignment.getQuantity() 9213 << (unsigned)Align.getQuantity(); 9214 return false; 9215 } 9216 } 9217 9218 // The offset must also have the correct alignment. 9219 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9220 Result.Designator.setInvalid(); 9221 9222 (OffsetResult.Base 9223 ? CCEDiag(E->getArg(0), 9224 diag::note_constexpr_baa_insufficient_alignment) << 1 9225 : CCEDiag(E->getArg(0), 9226 diag::note_constexpr_baa_value_insufficient_alignment)) 9227 << (int)OffsetResult.Offset.getQuantity() 9228 << (unsigned)Align.getQuantity(); 9229 return false; 9230 } 9231 9232 return true; 9233 } 9234 case Builtin::BI__builtin_align_up: 9235 case Builtin::BI__builtin_align_down: { 9236 if (!evaluatePointer(E->getArg(0), Result)) 9237 return false; 9238 APSInt Alignment; 9239 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9240 Alignment)) 9241 return false; 9242 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9243 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9244 // For align_up/align_down, we can return the same value if the alignment 9245 // is known to be greater or equal to the requested value. 9246 if (PtrAlign.getQuantity() >= Alignment) 9247 return true; 9248 9249 // The alignment could be greater than the minimum at run-time, so we cannot 9250 // infer much about the resulting pointer value. One case is possible: 9251 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9252 // can infer the correct index if the requested alignment is smaller than 9253 // the base alignment so we can perform the computation on the offset. 9254 if (BaseAlignment.getQuantity() >= Alignment) { 9255 assert(Alignment.getBitWidth() <= 64 && 9256 "Cannot handle > 64-bit address-space"); 9257 uint64_t Alignment64 = Alignment.getZExtValue(); 9258 CharUnits NewOffset = CharUnits::fromQuantity( 9259 BuiltinOp == Builtin::BI__builtin_align_down 9260 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9261 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9262 Result.adjustOffset(NewOffset - Result.Offset); 9263 // TODO: diagnose out-of-bounds values/only allow for arrays? 9264 return true; 9265 } 9266 // Otherwise, we cannot constant-evaluate the result. 9267 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9268 << Alignment; 9269 return false; 9270 } 9271 case Builtin::BI__builtin_operator_new: 9272 return HandleOperatorNewCall(Info, E, Result); 9273 case Builtin::BI__builtin_launder: 9274 return evaluatePointer(E->getArg(0), Result); 9275 case Builtin::BIstrchr: 9276 case Builtin::BIwcschr: 9277 case Builtin::BImemchr: 9278 case Builtin::BIwmemchr: 9279 if (Info.getLangOpts().CPlusPlus11) 9280 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9281 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 9282 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 9283 else 9284 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9285 [[fallthrough]]; 9286 case Builtin::BI__builtin_strchr: 9287 case Builtin::BI__builtin_wcschr: 9288 case Builtin::BI__builtin_memchr: 9289 case Builtin::BI__builtin_char_memchr: 9290 case Builtin::BI__builtin_wmemchr: { 9291 if (!Visit(E->getArg(0))) 9292 return false; 9293 APSInt Desired; 9294 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9295 return false; 9296 uint64_t MaxLength = uint64_t(-1); 9297 if (BuiltinOp != Builtin::BIstrchr && 9298 BuiltinOp != Builtin::BIwcschr && 9299 BuiltinOp != Builtin::BI__builtin_strchr && 9300 BuiltinOp != Builtin::BI__builtin_wcschr) { 9301 APSInt N; 9302 if (!EvaluateInteger(E->getArg(2), N, Info)) 9303 return false; 9304 MaxLength = N.getExtValue(); 9305 } 9306 // We cannot find the value if there are no candidates to match against. 9307 if (MaxLength == 0u) 9308 return ZeroInitialization(E); 9309 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9310 Result.Designator.Invalid) 9311 return false; 9312 QualType CharTy = Result.Designator.getType(Info.Ctx); 9313 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9314 BuiltinOp == Builtin::BI__builtin_memchr; 9315 assert(IsRawByte || 9316 Info.Ctx.hasSameUnqualifiedType( 9317 CharTy, E->getArg(0)->getType()->getPointeeType())); 9318 // Pointers to const void may point to objects of incomplete type. 9319 if (IsRawByte && CharTy->isIncompleteType()) { 9320 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9321 return false; 9322 } 9323 // Give up on byte-oriented matching against multibyte elements. 9324 // FIXME: We can compare the bytes in the correct order. 9325 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9326 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9327 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str() 9328 << CharTy; 9329 return false; 9330 } 9331 // Figure out what value we're actually looking for (after converting to 9332 // the corresponding unsigned type if necessary). 9333 uint64_t DesiredVal; 9334 bool StopAtNull = false; 9335 switch (BuiltinOp) { 9336 case Builtin::BIstrchr: 9337 case Builtin::BI__builtin_strchr: 9338 // strchr compares directly to the passed integer, and therefore 9339 // always fails if given an int that is not a char. 9340 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9341 E->getArg(1)->getType(), 9342 Desired), 9343 Desired)) 9344 return ZeroInitialization(E); 9345 StopAtNull = true; 9346 [[fallthrough]]; 9347 case Builtin::BImemchr: 9348 case Builtin::BI__builtin_memchr: 9349 case Builtin::BI__builtin_char_memchr: 9350 // memchr compares by converting both sides to unsigned char. That's also 9351 // correct for strchr if we get this far (to cope with plain char being 9352 // unsigned in the strchr case). 9353 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9354 break; 9355 9356 case Builtin::BIwcschr: 9357 case Builtin::BI__builtin_wcschr: 9358 StopAtNull = true; 9359 [[fallthrough]]; 9360 case Builtin::BIwmemchr: 9361 case Builtin::BI__builtin_wmemchr: 9362 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9363 DesiredVal = Desired.getZExtValue(); 9364 break; 9365 } 9366 9367 for (; MaxLength; --MaxLength) { 9368 APValue Char; 9369 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9370 !Char.isInt()) 9371 return false; 9372 if (Char.getInt().getZExtValue() == DesiredVal) 9373 return true; 9374 if (StopAtNull && !Char.getInt()) 9375 break; 9376 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9377 return false; 9378 } 9379 // Not found: return nullptr. 9380 return ZeroInitialization(E); 9381 } 9382 9383 case Builtin::BImemcpy: 9384 case Builtin::BImemmove: 9385 case Builtin::BIwmemcpy: 9386 case Builtin::BIwmemmove: 9387 if (Info.getLangOpts().CPlusPlus11) 9388 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9389 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 9390 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 9391 else 9392 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9393 [[fallthrough]]; 9394 case Builtin::BI__builtin_memcpy: 9395 case Builtin::BI__builtin_memmove: 9396 case Builtin::BI__builtin_wmemcpy: 9397 case Builtin::BI__builtin_wmemmove: { 9398 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9399 BuiltinOp == Builtin::BIwmemmove || 9400 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9401 BuiltinOp == Builtin::BI__builtin_wmemmove; 9402 bool Move = BuiltinOp == Builtin::BImemmove || 9403 BuiltinOp == Builtin::BIwmemmove || 9404 BuiltinOp == Builtin::BI__builtin_memmove || 9405 BuiltinOp == Builtin::BI__builtin_wmemmove; 9406 9407 // The result of mem* is the first argument. 9408 if (!Visit(E->getArg(0))) 9409 return false; 9410 LValue Dest = Result; 9411 9412 LValue Src; 9413 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9414 return false; 9415 9416 APSInt N; 9417 if (!EvaluateInteger(E->getArg(2), N, Info)) 9418 return false; 9419 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9420 9421 // If the size is zero, we treat this as always being a valid no-op. 9422 // (Even if one of the src and dest pointers is null.) 9423 if (!N) 9424 return true; 9425 9426 // Otherwise, if either of the operands is null, we can't proceed. Don't 9427 // try to determine the type of the copied objects, because there aren't 9428 // any. 9429 if (!Src.Base || !Dest.Base) { 9430 APValue Val; 9431 (!Src.Base ? Src : Dest).moveInto(Val); 9432 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9433 << Move << WChar << !!Src.Base 9434 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9435 return false; 9436 } 9437 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9438 return false; 9439 9440 // We require that Src and Dest are both pointers to arrays of 9441 // trivially-copyable type. (For the wide version, the designator will be 9442 // invalid if the designated object is not a wchar_t.) 9443 QualType T = Dest.Designator.getType(Info.Ctx); 9444 QualType SrcT = Src.Designator.getType(Info.Ctx); 9445 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9446 // FIXME: Consider using our bit_cast implementation to support this. 9447 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9448 return false; 9449 } 9450 if (T->isIncompleteType()) { 9451 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9452 return false; 9453 } 9454 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9455 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9456 return false; 9457 } 9458 9459 // Figure out how many T's we're copying. 9460 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9461 if (!WChar) { 9462 uint64_t Remainder; 9463 llvm::APInt OrigN = N; 9464 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9465 if (Remainder) { 9466 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9467 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9468 << (unsigned)TSize; 9469 return false; 9470 } 9471 } 9472 9473 // Check that the copying will remain within the arrays, just so that we 9474 // can give a more meaningful diagnostic. This implicitly also checks that 9475 // N fits into 64 bits. 9476 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9477 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9478 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9479 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9480 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9481 << toString(N, 10, /*Signed*/false); 9482 return false; 9483 } 9484 uint64_t NElems = N.getZExtValue(); 9485 uint64_t NBytes = NElems * TSize; 9486 9487 // Check for overlap. 9488 int Direction = 1; 9489 if (HasSameBase(Src, Dest)) { 9490 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9491 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9492 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9493 // Dest is inside the source region. 9494 if (!Move) { 9495 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9496 return false; 9497 } 9498 // For memmove and friends, copy backwards. 9499 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9500 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9501 return false; 9502 Direction = -1; 9503 } else if (!Move && SrcOffset >= DestOffset && 9504 SrcOffset - DestOffset < NBytes) { 9505 // Src is inside the destination region for memcpy: invalid. 9506 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9507 return false; 9508 } 9509 } 9510 9511 while (true) { 9512 APValue Val; 9513 // FIXME: Set WantObjectRepresentation to true if we're copying a 9514 // char-like type? 9515 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9516 !handleAssignment(Info, E, Dest, T, Val)) 9517 return false; 9518 // Do not iterate past the last element; if we're copying backwards, that 9519 // might take us off the start of the array. 9520 if (--NElems == 0) 9521 return true; 9522 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9523 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9524 return false; 9525 } 9526 } 9527 9528 default: 9529 return false; 9530 } 9531 } 9532 9533 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9534 APValue &Result, const InitListExpr *ILE, 9535 QualType AllocType); 9536 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9537 APValue &Result, 9538 const CXXConstructExpr *CCE, 9539 QualType AllocType); 9540 9541 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9542 if (!Info.getLangOpts().CPlusPlus20) 9543 Info.CCEDiag(E, diag::note_constexpr_new); 9544 9545 // We cannot speculatively evaluate a delete expression. 9546 if (Info.SpeculativeEvaluationDepth) 9547 return false; 9548 9549 FunctionDecl *OperatorNew = E->getOperatorNew(); 9550 9551 bool IsNothrow = false; 9552 bool IsPlacement = false; 9553 if (OperatorNew->isReservedGlobalPlacementOperator() && 9554 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9555 // FIXME Support array placement new. 9556 assert(E->getNumPlacementArgs() == 1); 9557 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9558 return false; 9559 if (Result.Designator.Invalid) 9560 return false; 9561 IsPlacement = true; 9562 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9563 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9564 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9565 return false; 9566 } else if (E->getNumPlacementArgs()) { 9567 // The only new-placement list we support is of the form (std::nothrow). 9568 // 9569 // FIXME: There is no restriction on this, but it's not clear that any 9570 // other form makes any sense. We get here for cases such as: 9571 // 9572 // new (std::align_val_t{N}) X(int) 9573 // 9574 // (which should presumably be valid only if N is a multiple of 9575 // alignof(int), and in any case can't be deallocated unless N is 9576 // alignof(X) and X has new-extended alignment). 9577 if (E->getNumPlacementArgs() != 1 || 9578 !E->getPlacementArg(0)->getType()->isNothrowT()) 9579 return Error(E, diag::note_constexpr_new_placement); 9580 9581 LValue Nothrow; 9582 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9583 return false; 9584 IsNothrow = true; 9585 } 9586 9587 const Expr *Init = E->getInitializer(); 9588 const InitListExpr *ResizedArrayILE = nullptr; 9589 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9590 bool ValueInit = false; 9591 9592 QualType AllocType = E->getAllocatedType(); 9593 if (std::optional<const Expr *> ArraySize = E->getArraySize()) { 9594 const Expr *Stripped = *ArraySize; 9595 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9596 Stripped = ICE->getSubExpr()) 9597 if (ICE->getCastKind() != CK_NoOp && 9598 ICE->getCastKind() != CK_IntegralCast) 9599 break; 9600 9601 llvm::APSInt ArrayBound; 9602 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9603 return false; 9604 9605 // C++ [expr.new]p9: 9606 // The expression is erroneous if: 9607 // -- [...] its value before converting to size_t [or] applying the 9608 // second standard conversion sequence is less than zero 9609 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9610 if (IsNothrow) 9611 return ZeroInitialization(E); 9612 9613 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9614 << ArrayBound << (*ArraySize)->getSourceRange(); 9615 return false; 9616 } 9617 9618 // -- its value is such that the size of the allocated object would 9619 // exceed the implementation-defined limit 9620 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9621 ArrayBound) > 9622 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9623 if (IsNothrow) 9624 return ZeroInitialization(E); 9625 9626 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9627 << ArrayBound << (*ArraySize)->getSourceRange(); 9628 return false; 9629 } 9630 9631 // -- the new-initializer is a braced-init-list and the number of 9632 // array elements for which initializers are provided [...] 9633 // exceeds the number of elements to initialize 9634 if (!Init) { 9635 // No initialization is performed. 9636 } else if (isa<CXXScalarValueInitExpr>(Init) || 9637 isa<ImplicitValueInitExpr>(Init)) { 9638 ValueInit = true; 9639 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9640 ResizedArrayCCE = CCE; 9641 } else { 9642 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9643 assert(CAT && "unexpected type for array initializer"); 9644 9645 unsigned Bits = 9646 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9647 llvm::APInt InitBound = CAT->getSize().zext(Bits); 9648 llvm::APInt AllocBound = ArrayBound.zext(Bits); 9649 if (InitBound.ugt(AllocBound)) { 9650 if (IsNothrow) 9651 return ZeroInitialization(E); 9652 9653 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9654 << toString(AllocBound, 10, /*Signed=*/false) 9655 << toString(InitBound, 10, /*Signed=*/false) 9656 << (*ArraySize)->getSourceRange(); 9657 return false; 9658 } 9659 9660 // If the sizes differ, we must have an initializer list, and we need 9661 // special handling for this case when we initialize. 9662 if (InitBound != AllocBound) 9663 ResizedArrayILE = cast<InitListExpr>(Init); 9664 } 9665 9666 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9667 ArrayType::Normal, 0); 9668 } else { 9669 assert(!AllocType->isArrayType() && 9670 "array allocation with non-array new"); 9671 } 9672 9673 APValue *Val; 9674 if (IsPlacement) { 9675 AccessKinds AK = AK_Construct; 9676 struct FindObjectHandler { 9677 EvalInfo &Info; 9678 const Expr *E; 9679 QualType AllocType; 9680 const AccessKinds AccessKind; 9681 APValue *Value; 9682 9683 typedef bool result_type; 9684 bool failed() { return false; } 9685 bool found(APValue &Subobj, QualType SubobjType) { 9686 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9687 // old name of the object to be used to name the new object. 9688 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9689 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9690 SubobjType << AllocType; 9691 return false; 9692 } 9693 Value = &Subobj; 9694 return true; 9695 } 9696 bool found(APSInt &Value, QualType SubobjType) { 9697 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9698 return false; 9699 } 9700 bool found(APFloat &Value, QualType SubobjType) { 9701 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9702 return false; 9703 } 9704 } Handler = {Info, E, AllocType, AK, nullptr}; 9705 9706 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9707 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9708 return false; 9709 9710 Val = Handler.Value; 9711 9712 // [basic.life]p1: 9713 // The lifetime of an object o of type T ends when [...] the storage 9714 // which the object occupies is [...] reused by an object that is not 9715 // nested within o (6.6.2). 9716 *Val = APValue(); 9717 } else { 9718 // Perform the allocation and obtain a pointer to the resulting object. 9719 Val = Info.createHeapAlloc(E, AllocType, Result); 9720 if (!Val) 9721 return false; 9722 } 9723 9724 if (ValueInit) { 9725 ImplicitValueInitExpr VIE(AllocType); 9726 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9727 return false; 9728 } else if (ResizedArrayILE) { 9729 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9730 AllocType)) 9731 return false; 9732 } else if (ResizedArrayCCE) { 9733 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9734 AllocType)) 9735 return false; 9736 } else if (Init) { 9737 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9738 return false; 9739 } else if (!getDefaultInitValue(AllocType, *Val)) { 9740 return false; 9741 } 9742 9743 // Array new returns a pointer to the first element, not a pointer to the 9744 // array. 9745 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9746 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9747 9748 return true; 9749 } 9750 //===----------------------------------------------------------------------===// 9751 // Member Pointer Evaluation 9752 //===----------------------------------------------------------------------===// 9753 9754 namespace { 9755 class MemberPointerExprEvaluator 9756 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9757 MemberPtr &Result; 9758 9759 bool Success(const ValueDecl *D) { 9760 Result = MemberPtr(D); 9761 return true; 9762 } 9763 public: 9764 9765 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9766 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9767 9768 bool Success(const APValue &V, const Expr *E) { 9769 Result.setFrom(V); 9770 return true; 9771 } 9772 bool ZeroInitialization(const Expr *E) { 9773 return Success((const ValueDecl*)nullptr); 9774 } 9775 9776 bool VisitCastExpr(const CastExpr *E); 9777 bool VisitUnaryAddrOf(const UnaryOperator *E); 9778 }; 9779 } // end anonymous namespace 9780 9781 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9782 EvalInfo &Info) { 9783 assert(!E->isValueDependent()); 9784 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9785 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9786 } 9787 9788 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9789 switch (E->getCastKind()) { 9790 default: 9791 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9792 9793 case CK_NullToMemberPointer: 9794 VisitIgnoredValue(E->getSubExpr()); 9795 return ZeroInitialization(E); 9796 9797 case CK_BaseToDerivedMemberPointer: { 9798 if (!Visit(E->getSubExpr())) 9799 return false; 9800 if (E->path_empty()) 9801 return true; 9802 // Base-to-derived member pointer casts store the path in derived-to-base 9803 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9804 // the wrong end of the derived->base arc, so stagger the path by one class. 9805 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9806 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9807 PathI != PathE; ++PathI) { 9808 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9809 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9810 if (!Result.castToDerived(Derived)) 9811 return Error(E); 9812 } 9813 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9814 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9815 return Error(E); 9816 return true; 9817 } 9818 9819 case CK_DerivedToBaseMemberPointer: 9820 if (!Visit(E->getSubExpr())) 9821 return false; 9822 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9823 PathE = E->path_end(); PathI != PathE; ++PathI) { 9824 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9825 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9826 if (!Result.castToBase(Base)) 9827 return Error(E); 9828 } 9829 return true; 9830 } 9831 } 9832 9833 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9834 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9835 // member can be formed. 9836 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9837 } 9838 9839 //===----------------------------------------------------------------------===// 9840 // Record Evaluation 9841 //===----------------------------------------------------------------------===// 9842 9843 namespace { 9844 class RecordExprEvaluator 9845 : public ExprEvaluatorBase<RecordExprEvaluator> { 9846 const LValue &This; 9847 APValue &Result; 9848 public: 9849 9850 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9851 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9852 9853 bool Success(const APValue &V, const Expr *E) { 9854 Result = V; 9855 return true; 9856 } 9857 bool ZeroInitialization(const Expr *E) { 9858 return ZeroInitialization(E, E->getType()); 9859 } 9860 bool ZeroInitialization(const Expr *E, QualType T); 9861 9862 bool VisitCallExpr(const CallExpr *E) { 9863 return handleCallExpr(E, Result, &This); 9864 } 9865 bool VisitCastExpr(const CastExpr *E); 9866 bool VisitInitListExpr(const InitListExpr *E); 9867 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9868 return VisitCXXConstructExpr(E, E->getType()); 9869 } 9870 bool VisitLambdaExpr(const LambdaExpr *E); 9871 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9872 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9873 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9874 bool VisitBinCmp(const BinaryOperator *E); 9875 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E); 9876 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit, 9877 ArrayRef<Expr *> Args); 9878 }; 9879 } 9880 9881 /// Perform zero-initialization on an object of non-union class type. 9882 /// C++11 [dcl.init]p5: 9883 /// To zero-initialize an object or reference of type T means: 9884 /// [...] 9885 /// -- if T is a (possibly cv-qualified) non-union class type, 9886 /// each non-static data member and each base-class subobject is 9887 /// zero-initialized 9888 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9889 const RecordDecl *RD, 9890 const LValue &This, APValue &Result) { 9891 assert(!RD->isUnion() && "Expected non-union class type"); 9892 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9893 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9894 std::distance(RD->field_begin(), RD->field_end())); 9895 9896 if (RD->isInvalidDecl()) return false; 9897 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9898 9899 if (CD) { 9900 unsigned Index = 0; 9901 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9902 End = CD->bases_end(); I != End; ++I, ++Index) { 9903 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9904 LValue Subobject = This; 9905 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9906 return false; 9907 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9908 Result.getStructBase(Index))) 9909 return false; 9910 } 9911 } 9912 9913 for (const auto *I : RD->fields()) { 9914 // -- if T is a reference type, no initialization is performed. 9915 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9916 continue; 9917 9918 LValue Subobject = This; 9919 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9920 return false; 9921 9922 ImplicitValueInitExpr VIE(I->getType()); 9923 if (!EvaluateInPlace( 9924 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9925 return false; 9926 } 9927 9928 return true; 9929 } 9930 9931 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9932 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9933 if (RD->isInvalidDecl()) return false; 9934 if (RD->isUnion()) { 9935 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9936 // object's first non-static named data member is zero-initialized 9937 RecordDecl::field_iterator I = RD->field_begin(); 9938 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9939 ++I; 9940 if (I == RD->field_end()) { 9941 Result = APValue((const FieldDecl*)nullptr); 9942 return true; 9943 } 9944 9945 LValue Subobject = This; 9946 if (!HandleLValueMember(Info, E, Subobject, *I)) 9947 return false; 9948 Result = APValue(*I); 9949 ImplicitValueInitExpr VIE(I->getType()); 9950 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9951 } 9952 9953 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9954 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9955 return false; 9956 } 9957 9958 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9959 } 9960 9961 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9962 switch (E->getCastKind()) { 9963 default: 9964 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9965 9966 case CK_ConstructorConversion: 9967 return Visit(E->getSubExpr()); 9968 9969 case CK_DerivedToBase: 9970 case CK_UncheckedDerivedToBase: { 9971 APValue DerivedObject; 9972 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9973 return false; 9974 if (!DerivedObject.isStruct()) 9975 return Error(E->getSubExpr()); 9976 9977 // Derived-to-base rvalue conversion: just slice off the derived part. 9978 APValue *Value = &DerivedObject; 9979 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9980 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9981 PathE = E->path_end(); PathI != PathE; ++PathI) { 9982 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9983 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9984 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9985 RD = Base; 9986 } 9987 Result = *Value; 9988 return true; 9989 } 9990 } 9991 } 9992 9993 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9994 if (E->isTransparent()) 9995 return Visit(E->getInit(0)); 9996 return VisitCXXParenListOrInitListExpr(E, E->inits()); 9997 } 9998 9999 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr( 10000 const Expr *ExprToVisit, ArrayRef<Expr *> Args) { 10001 const RecordDecl *RD = 10002 ExprToVisit->getType()->castAs<RecordType>()->getDecl(); 10003 if (RD->isInvalidDecl()) return false; 10004 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 10005 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 10006 10007 EvalInfo::EvaluatingConstructorRAII EvalObj( 10008 Info, 10009 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 10010 CXXRD && CXXRD->getNumBases()); 10011 10012 if (RD->isUnion()) { 10013 const FieldDecl *Field; 10014 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) { 10015 Field = ILE->getInitializedFieldInUnion(); 10016 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) { 10017 Field = PLIE->getInitializedFieldInUnion(); 10018 } else { 10019 llvm_unreachable( 10020 "Expression is neither an init list nor a C++ paren list"); 10021 } 10022 10023 Result = APValue(Field); 10024 if (!Field) 10025 return true; 10026 10027 // If the initializer list for a union does not contain any elements, the 10028 // first element of the union is value-initialized. 10029 // FIXME: The element should be initialized from an initializer list. 10030 // Is this difference ever observable for initializer lists which 10031 // we don't build? 10032 ImplicitValueInitExpr VIE(Field->getType()); 10033 const Expr *InitExpr = Args.empty() ? &VIE : Args[0]; 10034 10035 LValue Subobject = This; 10036 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 10037 return false; 10038 10039 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 10040 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 10041 isa<CXXDefaultInitExpr>(InitExpr)); 10042 10043 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 10044 if (Field->isBitField()) 10045 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 10046 Field); 10047 return true; 10048 } 10049 10050 return false; 10051 } 10052 10053 if (!Result.hasValue()) 10054 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 10055 std::distance(RD->field_begin(), RD->field_end())); 10056 unsigned ElementNo = 0; 10057 bool Success = true; 10058 10059 // Initialize base classes. 10060 if (CXXRD && CXXRD->getNumBases()) { 10061 for (const auto &Base : CXXRD->bases()) { 10062 assert(ElementNo < Args.size() && "missing init for base class"); 10063 const Expr *Init = Args[ElementNo]; 10064 10065 LValue Subobject = This; 10066 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 10067 return false; 10068 10069 APValue &FieldVal = Result.getStructBase(ElementNo); 10070 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 10071 if (!Info.noteFailure()) 10072 return false; 10073 Success = false; 10074 } 10075 ++ElementNo; 10076 } 10077 10078 EvalObj.finishedConstructingBases(); 10079 } 10080 10081 // Initialize members. 10082 for (const auto *Field : RD->fields()) { 10083 // Anonymous bit-fields are not considered members of the class for 10084 // purposes of aggregate initialization. 10085 if (Field->isUnnamedBitfield()) 10086 continue; 10087 10088 LValue Subobject = This; 10089 10090 bool HaveInit = ElementNo < Args.size(); 10091 10092 // FIXME: Diagnostics here should point to the end of the initializer 10093 // list, not the start. 10094 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit, 10095 Subobject, Field, &Layout)) 10096 return false; 10097 10098 // Perform an implicit value-initialization for members beyond the end of 10099 // the initializer list. 10100 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 10101 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE; 10102 10103 if (Field->getType()->isIncompleteArrayType()) { 10104 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) { 10105 if (!CAT->getSize().isZero()) { 10106 // Bail out for now. This might sort of "work", but the rest of the 10107 // code isn't really prepared to handle it. 10108 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array); 10109 return false; 10110 } 10111 } 10112 } 10113 10114 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 10115 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 10116 isa<CXXDefaultInitExpr>(Init)); 10117 10118 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10119 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 10120 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 10121 FieldVal, Field))) { 10122 if (!Info.noteFailure()) 10123 return false; 10124 Success = false; 10125 } 10126 } 10127 10128 EvalObj.finishedConstructingFields(); 10129 10130 return Success; 10131 } 10132 10133 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10134 QualType T) { 10135 // Note that E's type is not necessarily the type of our class here; we might 10136 // be initializing an array element instead. 10137 const CXXConstructorDecl *FD = E->getConstructor(); 10138 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 10139 10140 bool ZeroInit = E->requiresZeroInitialization(); 10141 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 10142 // If we've already performed zero-initialization, we're already done. 10143 if (Result.hasValue()) 10144 return true; 10145 10146 if (ZeroInit) 10147 return ZeroInitialization(E, T); 10148 10149 return getDefaultInitValue(T, Result); 10150 } 10151 10152 const FunctionDecl *Definition = nullptr; 10153 auto Body = FD->getBody(Definition); 10154 10155 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10156 return false; 10157 10158 // Avoid materializing a temporary for an elidable copy/move constructor. 10159 if (E->isElidable() && !ZeroInit) { 10160 // FIXME: This only handles the simplest case, where the source object 10161 // is passed directly as the first argument to the constructor. 10162 // This should also handle stepping though implicit casts and 10163 // and conversion sequences which involve two steps, with a 10164 // conversion operator followed by a converting constructor. 10165 const Expr *SrcObj = E->getArg(0); 10166 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 10167 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 10168 if (const MaterializeTemporaryExpr *ME = 10169 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 10170 return Visit(ME->getSubExpr()); 10171 } 10172 10173 if (ZeroInit && !ZeroInitialization(E, T)) 10174 return false; 10175 10176 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs()); 10177 return HandleConstructorCall(E, This, Args, 10178 cast<CXXConstructorDecl>(Definition), Info, 10179 Result); 10180 } 10181 10182 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 10183 const CXXInheritedCtorInitExpr *E) { 10184 if (!Info.CurrentCall) { 10185 assert(Info.checkingPotentialConstantExpression()); 10186 return false; 10187 } 10188 10189 const CXXConstructorDecl *FD = E->getConstructor(); 10190 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 10191 return false; 10192 10193 const FunctionDecl *Definition = nullptr; 10194 auto Body = FD->getBody(Definition); 10195 10196 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10197 return false; 10198 10199 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 10200 cast<CXXConstructorDecl>(Definition), Info, 10201 Result); 10202 } 10203 10204 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 10205 const CXXStdInitializerListExpr *E) { 10206 const ConstantArrayType *ArrayType = 10207 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 10208 10209 LValue Array; 10210 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 10211 return false; 10212 10213 assert(ArrayType && "unexpected type for array initializer"); 10214 10215 // Get a pointer to the first element of the array. 10216 Array.addArray(Info, E, ArrayType); 10217 10218 auto InvalidType = [&] { 10219 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 10220 << E->getType(); 10221 return false; 10222 }; 10223 10224 // FIXME: Perform the checks on the field types in SemaInit. 10225 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10226 RecordDecl::field_iterator Field = Record->field_begin(); 10227 if (Field == Record->field_end()) 10228 return InvalidType(); 10229 10230 // Start pointer. 10231 if (!Field->getType()->isPointerType() || 10232 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10233 ArrayType->getElementType())) 10234 return InvalidType(); 10235 10236 // FIXME: What if the initializer_list type has base classes, etc? 10237 Result = APValue(APValue::UninitStruct(), 0, 2); 10238 Array.moveInto(Result.getStructField(0)); 10239 10240 if (++Field == Record->field_end()) 10241 return InvalidType(); 10242 10243 if (Field->getType()->isPointerType() && 10244 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10245 ArrayType->getElementType())) { 10246 // End pointer. 10247 if (!HandleLValueArrayAdjustment(Info, E, Array, 10248 ArrayType->getElementType(), 10249 ArrayType->getSize().getZExtValue())) 10250 return false; 10251 Array.moveInto(Result.getStructField(1)); 10252 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10253 // Length. 10254 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10255 else 10256 return InvalidType(); 10257 10258 if (++Field != Record->field_end()) 10259 return InvalidType(); 10260 10261 return true; 10262 } 10263 10264 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10265 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10266 if (ClosureClass->isInvalidDecl()) 10267 return false; 10268 10269 const size_t NumFields = 10270 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10271 10272 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10273 E->capture_init_end()) && 10274 "The number of lambda capture initializers should equal the number of " 10275 "fields within the closure type"); 10276 10277 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10278 // Iterate through all the lambda's closure object's fields and initialize 10279 // them. 10280 auto *CaptureInitIt = E->capture_init_begin(); 10281 bool Success = true; 10282 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10283 for (const auto *Field : ClosureClass->fields()) { 10284 assert(CaptureInitIt != E->capture_init_end()); 10285 // Get the initializer for this field 10286 Expr *const CurFieldInit = *CaptureInitIt++; 10287 10288 // If there is no initializer, either this is a VLA or an error has 10289 // occurred. 10290 if (!CurFieldInit) 10291 return Error(E); 10292 10293 LValue Subobject = This; 10294 10295 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10296 return false; 10297 10298 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10299 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10300 if (!Info.keepEvaluatingAfterFailure()) 10301 return false; 10302 Success = false; 10303 } 10304 } 10305 return Success; 10306 } 10307 10308 static bool EvaluateRecord(const Expr *E, const LValue &This, 10309 APValue &Result, EvalInfo &Info) { 10310 assert(!E->isValueDependent()); 10311 assert(E->isPRValue() && E->getType()->isRecordType() && 10312 "can't evaluate expression as a record rvalue"); 10313 return RecordExprEvaluator(Info, This, Result).Visit(E); 10314 } 10315 10316 //===----------------------------------------------------------------------===// 10317 // Temporary Evaluation 10318 // 10319 // Temporaries are represented in the AST as rvalues, but generally behave like 10320 // lvalues. The full-object of which the temporary is a subobject is implicitly 10321 // materialized so that a reference can bind to it. 10322 //===----------------------------------------------------------------------===// 10323 namespace { 10324 class TemporaryExprEvaluator 10325 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10326 public: 10327 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10328 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10329 10330 /// Visit an expression which constructs the value of this temporary. 10331 bool VisitConstructExpr(const Expr *E) { 10332 APValue &Value = Info.CurrentCall->createTemporary( 10333 E, E->getType(), ScopeKind::FullExpression, Result); 10334 return EvaluateInPlace(Value, Info, Result, E); 10335 } 10336 10337 bool VisitCastExpr(const CastExpr *E) { 10338 switch (E->getCastKind()) { 10339 default: 10340 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10341 10342 case CK_ConstructorConversion: 10343 return VisitConstructExpr(E->getSubExpr()); 10344 } 10345 } 10346 bool VisitInitListExpr(const InitListExpr *E) { 10347 return VisitConstructExpr(E); 10348 } 10349 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10350 return VisitConstructExpr(E); 10351 } 10352 bool VisitCallExpr(const CallExpr *E) { 10353 return VisitConstructExpr(E); 10354 } 10355 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10356 return VisitConstructExpr(E); 10357 } 10358 bool VisitLambdaExpr(const LambdaExpr *E) { 10359 return VisitConstructExpr(E); 10360 } 10361 }; 10362 } // end anonymous namespace 10363 10364 /// Evaluate an expression of record type as a temporary. 10365 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10366 assert(!E->isValueDependent()); 10367 assert(E->isPRValue() && E->getType()->isRecordType()); 10368 return TemporaryExprEvaluator(Info, Result).Visit(E); 10369 } 10370 10371 //===----------------------------------------------------------------------===// 10372 // Vector Evaluation 10373 //===----------------------------------------------------------------------===// 10374 10375 namespace { 10376 class VectorExprEvaluator 10377 : public ExprEvaluatorBase<VectorExprEvaluator> { 10378 APValue &Result; 10379 public: 10380 10381 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10382 : ExprEvaluatorBaseTy(info), Result(Result) {} 10383 10384 bool Success(ArrayRef<APValue> V, const Expr *E) { 10385 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10386 // FIXME: remove this APValue copy. 10387 Result = APValue(V.data(), V.size()); 10388 return true; 10389 } 10390 bool Success(const APValue &V, const Expr *E) { 10391 assert(V.isVector()); 10392 Result = V; 10393 return true; 10394 } 10395 bool ZeroInitialization(const Expr *E); 10396 10397 bool VisitUnaryReal(const UnaryOperator *E) 10398 { return Visit(E->getSubExpr()); } 10399 bool VisitCastExpr(const CastExpr* E); 10400 bool VisitInitListExpr(const InitListExpr *E); 10401 bool VisitUnaryImag(const UnaryOperator *E); 10402 bool VisitBinaryOperator(const BinaryOperator *E); 10403 bool VisitUnaryOperator(const UnaryOperator *E); 10404 // FIXME: Missing: conditional operator (for GNU 10405 // conditional select), shufflevector, ExtVectorElementExpr 10406 }; 10407 } // end anonymous namespace 10408 10409 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10410 assert(E->isPRValue() && E->getType()->isVectorType() && 10411 "not a vector prvalue"); 10412 return VectorExprEvaluator(Info, Result).Visit(E); 10413 } 10414 10415 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10416 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10417 unsigned NElts = VTy->getNumElements(); 10418 10419 const Expr *SE = E->getSubExpr(); 10420 QualType SETy = SE->getType(); 10421 10422 switch (E->getCastKind()) { 10423 case CK_VectorSplat: { 10424 APValue Val = APValue(); 10425 if (SETy->isIntegerType()) { 10426 APSInt IntResult; 10427 if (!EvaluateInteger(SE, IntResult, Info)) 10428 return false; 10429 Val = APValue(std::move(IntResult)); 10430 } else if (SETy->isRealFloatingType()) { 10431 APFloat FloatResult(0.0); 10432 if (!EvaluateFloat(SE, FloatResult, Info)) 10433 return false; 10434 Val = APValue(std::move(FloatResult)); 10435 } else { 10436 return Error(E); 10437 } 10438 10439 // Splat and create vector APValue. 10440 SmallVector<APValue, 4> Elts(NElts, Val); 10441 return Success(Elts, E); 10442 } 10443 case CK_BitCast: { 10444 // Evaluate the operand into an APInt we can extract from. 10445 llvm::APInt SValInt; 10446 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10447 return false; 10448 // Extract the elements 10449 QualType EltTy = VTy->getElementType(); 10450 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10451 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10452 SmallVector<APValue, 4> Elts; 10453 if (EltTy->isRealFloatingType()) { 10454 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10455 unsigned FloatEltSize = EltSize; 10456 if (&Sem == &APFloat::x87DoubleExtended()) 10457 FloatEltSize = 80; 10458 for (unsigned i = 0; i < NElts; i++) { 10459 llvm::APInt Elt; 10460 if (BigEndian) 10461 Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize); 10462 else 10463 Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize); 10464 Elts.push_back(APValue(APFloat(Sem, Elt))); 10465 } 10466 } else if (EltTy->isIntegerType()) { 10467 for (unsigned i = 0; i < NElts; i++) { 10468 llvm::APInt Elt; 10469 if (BigEndian) 10470 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10471 else 10472 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10473 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10474 } 10475 } else { 10476 return Error(E); 10477 } 10478 return Success(Elts, E); 10479 } 10480 default: 10481 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10482 } 10483 } 10484 10485 bool 10486 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10487 const VectorType *VT = E->getType()->castAs<VectorType>(); 10488 unsigned NumInits = E->getNumInits(); 10489 unsigned NumElements = VT->getNumElements(); 10490 10491 QualType EltTy = VT->getElementType(); 10492 SmallVector<APValue, 4> Elements; 10493 10494 // The number of initializers can be less than the number of 10495 // vector elements. For OpenCL, this can be due to nested vector 10496 // initialization. For GCC compatibility, missing trailing elements 10497 // should be initialized with zeroes. 10498 unsigned CountInits = 0, CountElts = 0; 10499 while (CountElts < NumElements) { 10500 // Handle nested vector initialization. 10501 if (CountInits < NumInits 10502 && E->getInit(CountInits)->getType()->isVectorType()) { 10503 APValue v; 10504 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10505 return Error(E); 10506 unsigned vlen = v.getVectorLength(); 10507 for (unsigned j = 0; j < vlen; j++) 10508 Elements.push_back(v.getVectorElt(j)); 10509 CountElts += vlen; 10510 } else if (EltTy->isIntegerType()) { 10511 llvm::APSInt sInt(32); 10512 if (CountInits < NumInits) { 10513 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10514 return false; 10515 } else // trailing integer zero. 10516 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10517 Elements.push_back(APValue(sInt)); 10518 CountElts++; 10519 } else { 10520 llvm::APFloat f(0.0); 10521 if (CountInits < NumInits) { 10522 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10523 return false; 10524 } else // trailing float zero. 10525 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10526 Elements.push_back(APValue(f)); 10527 CountElts++; 10528 } 10529 CountInits++; 10530 } 10531 return Success(Elements, E); 10532 } 10533 10534 bool 10535 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10536 const auto *VT = E->getType()->castAs<VectorType>(); 10537 QualType EltTy = VT->getElementType(); 10538 APValue ZeroElement; 10539 if (EltTy->isIntegerType()) 10540 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10541 else 10542 ZeroElement = 10543 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10544 10545 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10546 return Success(Elements, E); 10547 } 10548 10549 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10550 VisitIgnoredValue(E->getSubExpr()); 10551 return ZeroInitialization(E); 10552 } 10553 10554 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10555 BinaryOperatorKind Op = E->getOpcode(); 10556 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10557 "Operation not supported on vector types"); 10558 10559 if (Op == BO_Comma) 10560 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10561 10562 Expr *LHS = E->getLHS(); 10563 Expr *RHS = E->getRHS(); 10564 10565 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10566 "Must both be vector types"); 10567 // Checking JUST the types are the same would be fine, except shifts don't 10568 // need to have their types be the same (since you always shift by an int). 10569 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10570 E->getType()->castAs<VectorType>()->getNumElements() && 10571 RHS->getType()->castAs<VectorType>()->getNumElements() == 10572 E->getType()->castAs<VectorType>()->getNumElements() && 10573 "All operands must be the same size."); 10574 10575 APValue LHSValue; 10576 APValue RHSValue; 10577 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10578 if (!LHSOK && !Info.noteFailure()) 10579 return false; 10580 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10581 return false; 10582 10583 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10584 return false; 10585 10586 return Success(LHSValue, E); 10587 } 10588 10589 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, 10590 QualType ResultTy, 10591 UnaryOperatorKind Op, 10592 APValue Elt) { 10593 switch (Op) { 10594 case UO_Plus: 10595 // Nothing to do here. 10596 return Elt; 10597 case UO_Minus: 10598 if (Elt.getKind() == APValue::Int) { 10599 Elt.getInt().negate(); 10600 } else { 10601 assert(Elt.getKind() == APValue::Float && 10602 "Vector can only be int or float type"); 10603 Elt.getFloat().changeSign(); 10604 } 10605 return Elt; 10606 case UO_Not: 10607 // This is only valid for integral types anyway, so we don't have to handle 10608 // float here. 10609 assert(Elt.getKind() == APValue::Int && 10610 "Vector operator ~ can only be int"); 10611 Elt.getInt().flipAllBits(); 10612 return Elt; 10613 case UO_LNot: { 10614 if (Elt.getKind() == APValue::Int) { 10615 Elt.getInt() = !Elt.getInt(); 10616 // operator ! on vectors returns -1 for 'truth', so negate it. 10617 Elt.getInt().negate(); 10618 return Elt; 10619 } 10620 assert(Elt.getKind() == APValue::Float && 10621 "Vector can only be int or float type"); 10622 // Float types result in an int of the same size, but -1 for true, or 0 for 10623 // false. 10624 APSInt EltResult{Ctx.getIntWidth(ResultTy), 10625 ResultTy->isUnsignedIntegerType()}; 10626 if (Elt.getFloat().isZero()) 10627 EltResult.setAllBits(); 10628 else 10629 EltResult.clearAllBits(); 10630 10631 return APValue{EltResult}; 10632 } 10633 default: 10634 // FIXME: Implement the rest of the unary operators. 10635 return std::nullopt; 10636 } 10637 } 10638 10639 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10640 Expr *SubExpr = E->getSubExpr(); 10641 const auto *VD = SubExpr->getType()->castAs<VectorType>(); 10642 // This result element type differs in the case of negating a floating point 10643 // vector, since the result type is the a vector of the equivilant sized 10644 // integer. 10645 const QualType ResultEltTy = VD->getElementType(); 10646 UnaryOperatorKind Op = E->getOpcode(); 10647 10648 APValue SubExprValue; 10649 if (!Evaluate(SubExprValue, Info, SubExpr)) 10650 return false; 10651 10652 // FIXME: This vector evaluator someday needs to be changed to be LValue 10653 // aware/keep LValue information around, rather than dealing with just vector 10654 // types directly. Until then, we cannot handle cases where the operand to 10655 // these unary operators is an LValue. The only case I've been able to see 10656 // cause this is operator++ assigning to a member expression (only valid in 10657 // altivec compilations) in C mode, so this shouldn't limit us too much. 10658 if (SubExprValue.isLValue()) 10659 return false; 10660 10661 assert(SubExprValue.getVectorLength() == VD->getNumElements() && 10662 "Vector length doesn't match type?"); 10663 10664 SmallVector<APValue, 4> ResultElements; 10665 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { 10666 std::optional<APValue> Elt = handleVectorUnaryOperator( 10667 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); 10668 if (!Elt) 10669 return false; 10670 ResultElements.push_back(*Elt); 10671 } 10672 return Success(APValue(ResultElements.data(), ResultElements.size()), E); 10673 } 10674 10675 //===----------------------------------------------------------------------===// 10676 // Array Evaluation 10677 //===----------------------------------------------------------------------===// 10678 10679 namespace { 10680 class ArrayExprEvaluator 10681 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10682 const LValue &This; 10683 APValue &Result; 10684 public: 10685 10686 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10687 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10688 10689 bool Success(const APValue &V, const Expr *E) { 10690 assert(V.isArray() && "expected array"); 10691 Result = V; 10692 return true; 10693 } 10694 10695 bool ZeroInitialization(const Expr *E) { 10696 const ConstantArrayType *CAT = 10697 Info.Ctx.getAsConstantArrayType(E->getType()); 10698 if (!CAT) { 10699 if (E->getType()->isIncompleteArrayType()) { 10700 // We can be asked to zero-initialize a flexible array member; this 10701 // is represented as an ImplicitValueInitExpr of incomplete array 10702 // type. In this case, the array has zero elements. 10703 Result = APValue(APValue::UninitArray(), 0, 0); 10704 return true; 10705 } 10706 // FIXME: We could handle VLAs here. 10707 return Error(E); 10708 } 10709 10710 Result = APValue(APValue::UninitArray(), 0, 10711 CAT->getSize().getZExtValue()); 10712 if (!Result.hasArrayFiller()) 10713 return true; 10714 10715 // Zero-initialize all elements. 10716 LValue Subobject = This; 10717 Subobject.addArray(Info, E, CAT); 10718 ImplicitValueInitExpr VIE(CAT->getElementType()); 10719 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10720 } 10721 10722 bool VisitCallExpr(const CallExpr *E) { 10723 return handleCallExpr(E, Result, &This); 10724 } 10725 bool VisitInitListExpr(const InitListExpr *E, 10726 QualType AllocType = QualType()); 10727 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10728 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10729 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10730 const LValue &Subobject, 10731 APValue *Value, QualType Type); 10732 bool VisitStringLiteral(const StringLiteral *E, 10733 QualType AllocType = QualType()) { 10734 expandStringLiteral(Info, E, Result, AllocType); 10735 return true; 10736 } 10737 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E); 10738 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit, 10739 ArrayRef<Expr *> Args, 10740 const Expr *ArrayFiller, 10741 QualType AllocType = QualType()); 10742 }; 10743 } // end anonymous namespace 10744 10745 static bool EvaluateArray(const Expr *E, const LValue &This, 10746 APValue &Result, EvalInfo &Info) { 10747 assert(!E->isValueDependent()); 10748 assert(E->isPRValue() && E->getType()->isArrayType() && 10749 "not an array prvalue"); 10750 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10751 } 10752 10753 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10754 APValue &Result, const InitListExpr *ILE, 10755 QualType AllocType) { 10756 assert(!ILE->isValueDependent()); 10757 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10758 "not an array prvalue"); 10759 return ArrayExprEvaluator(Info, This, Result) 10760 .VisitInitListExpr(ILE, AllocType); 10761 } 10762 10763 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10764 APValue &Result, 10765 const CXXConstructExpr *CCE, 10766 QualType AllocType) { 10767 assert(!CCE->isValueDependent()); 10768 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10769 "not an array prvalue"); 10770 return ArrayExprEvaluator(Info, This, Result) 10771 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10772 } 10773 10774 // Return true iff the given array filler may depend on the element index. 10775 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10776 // For now, just allow non-class value-initialization and initialization 10777 // lists comprised of them. 10778 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10779 return false; 10780 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10781 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10782 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10783 return true; 10784 } 10785 10786 if (ILE->hasArrayFiller() && 10787 MaybeElementDependentArrayFiller(ILE->getArrayFiller())) 10788 return true; 10789 10790 return false; 10791 } 10792 return true; 10793 } 10794 10795 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10796 QualType AllocType) { 10797 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10798 AllocType.isNull() ? E->getType() : AllocType); 10799 if (!CAT) 10800 return Error(E); 10801 10802 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10803 // an appropriately-typed string literal enclosed in braces. 10804 if (E->isStringLiteralInit()) { 10805 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10806 // FIXME: Support ObjCEncodeExpr here once we support it in 10807 // ArrayExprEvaluator generally. 10808 if (!SL) 10809 return Error(E); 10810 return VisitStringLiteral(SL, AllocType); 10811 } 10812 // Any other transparent list init will need proper handling of the 10813 // AllocType; we can't just recurse to the inner initializer. 10814 assert(!E->isTransparent() && 10815 "transparent array list initialization is not string literal init?"); 10816 10817 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(), 10818 AllocType); 10819 } 10820 10821 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr( 10822 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller, 10823 QualType AllocType) { 10824 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10825 AllocType.isNull() ? ExprToVisit->getType() : AllocType); 10826 10827 bool Success = true; 10828 10829 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10830 "zero-initialized array shouldn't have any initialized elts"); 10831 APValue Filler; 10832 if (Result.isArray() && Result.hasArrayFiller()) 10833 Filler = Result.getArrayFiller(); 10834 10835 unsigned NumEltsToInit = Args.size(); 10836 unsigned NumElts = CAT->getSize().getZExtValue(); 10837 10838 // If the initializer might depend on the array index, run it for each 10839 // array element. 10840 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller)) 10841 NumEltsToInit = NumElts; 10842 10843 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10844 << NumEltsToInit << ".\n"); 10845 10846 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10847 10848 // If the array was previously zero-initialized, preserve the 10849 // zero-initialized values. 10850 if (Filler.hasValue()) { 10851 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10852 Result.getArrayInitializedElt(I) = Filler; 10853 if (Result.hasArrayFiller()) 10854 Result.getArrayFiller() = Filler; 10855 } 10856 10857 LValue Subobject = This; 10858 Subobject.addArray(Info, ExprToVisit, CAT); 10859 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10860 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller; 10861 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10862 Info, Subobject, Init) || 10863 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10864 CAT->getElementType(), 1)) { 10865 if (!Info.noteFailure()) 10866 return false; 10867 Success = false; 10868 } 10869 } 10870 10871 if (!Result.hasArrayFiller()) 10872 return Success; 10873 10874 // If we get here, we have a trivial filler, which we can just evaluate 10875 // once and splat over the rest of the array elements. 10876 assert(ArrayFiller && "no array filler for incomplete init list"); 10877 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10878 ArrayFiller) && 10879 Success; 10880 } 10881 10882 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10883 LValue CommonLV; 10884 if (E->getCommonExpr() && 10885 !Evaluate(Info.CurrentCall->createTemporary( 10886 E->getCommonExpr(), 10887 getStorageType(Info.Ctx, E->getCommonExpr()), 10888 ScopeKind::FullExpression, CommonLV), 10889 Info, E->getCommonExpr()->getSourceExpr())) 10890 return false; 10891 10892 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10893 10894 uint64_t Elements = CAT->getSize().getZExtValue(); 10895 Result = APValue(APValue::UninitArray(), Elements, Elements); 10896 10897 LValue Subobject = This; 10898 Subobject.addArray(Info, E, CAT); 10899 10900 bool Success = true; 10901 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10902 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10903 Info, Subobject, E->getSubExpr()) || 10904 !HandleLValueArrayAdjustment(Info, E, Subobject, 10905 CAT->getElementType(), 1)) { 10906 if (!Info.noteFailure()) 10907 return false; 10908 Success = false; 10909 } 10910 } 10911 10912 return Success; 10913 } 10914 10915 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10916 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10917 } 10918 10919 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10920 const LValue &Subobject, 10921 APValue *Value, 10922 QualType Type) { 10923 bool HadZeroInit = Value->hasValue(); 10924 10925 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10926 unsigned FinalSize = CAT->getSize().getZExtValue(); 10927 10928 // Preserve the array filler if we had prior zero-initialization. 10929 APValue Filler = 10930 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10931 : APValue(); 10932 10933 *Value = APValue(APValue::UninitArray(), 0, FinalSize); 10934 if (FinalSize == 0) 10935 return true; 10936 10937 bool HasTrivialConstructor = CheckTrivialDefaultConstructor( 10938 Info, E->getExprLoc(), E->getConstructor(), 10939 E->requiresZeroInitialization()); 10940 LValue ArrayElt = Subobject; 10941 ArrayElt.addArray(Info, E, CAT); 10942 // We do the whole initialization in two passes, first for just one element, 10943 // then for the whole array. It's possible we may find out we can't do const 10944 // init in the first pass, in which case we avoid allocating a potentially 10945 // large array. We don't do more passes because expanding array requires 10946 // copying the data, which is wasteful. 10947 for (const unsigned N : {1u, FinalSize}) { 10948 unsigned OldElts = Value->getArrayInitializedElts(); 10949 if (OldElts == N) 10950 break; 10951 10952 // Expand the array to appropriate size. 10953 APValue NewValue(APValue::UninitArray(), N, FinalSize); 10954 for (unsigned I = 0; I < OldElts; ++I) 10955 NewValue.getArrayInitializedElt(I).swap( 10956 Value->getArrayInitializedElt(I)); 10957 Value->swap(NewValue); 10958 10959 if (HadZeroInit) 10960 for (unsigned I = OldElts; I < N; ++I) 10961 Value->getArrayInitializedElt(I) = Filler; 10962 10963 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) { 10964 // If we have a trivial constructor, only evaluate it once and copy 10965 // the result into all the array elements. 10966 APValue &FirstResult = Value->getArrayInitializedElt(0); 10967 for (unsigned I = OldElts; I < FinalSize; ++I) 10968 Value->getArrayInitializedElt(I) = FirstResult; 10969 } else { 10970 for (unsigned I = OldElts; I < N; ++I) { 10971 if (!VisitCXXConstructExpr(E, ArrayElt, 10972 &Value->getArrayInitializedElt(I), 10973 CAT->getElementType()) || 10974 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10975 CAT->getElementType(), 1)) 10976 return false; 10977 // When checking for const initilization any diagnostic is considered 10978 // an error. 10979 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && 10980 !Info.keepEvaluatingAfterFailure()) 10981 return false; 10982 } 10983 } 10984 } 10985 10986 return true; 10987 } 10988 10989 if (!Type->isRecordType()) 10990 return Error(E); 10991 10992 return RecordExprEvaluator(Info, Subobject, *Value) 10993 .VisitCXXConstructExpr(E, Type); 10994 } 10995 10996 bool ArrayExprEvaluator::VisitCXXParenListInitExpr( 10997 const CXXParenListInitExpr *E) { 10998 assert(dyn_cast<ConstantArrayType>(E->getType()) && 10999 "Expression result is not a constant array type"); 11000 11001 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(), 11002 E->getArrayFiller()); 11003 } 11004 11005 //===----------------------------------------------------------------------===// 11006 // Integer Evaluation 11007 // 11008 // As a GNU extension, we support casting pointers to sufficiently-wide integer 11009 // types and back in constant folding. Integer values are thus represented 11010 // either as an integer-valued APValue, or as an lvalue-valued APValue. 11011 //===----------------------------------------------------------------------===// 11012 11013 namespace { 11014 class IntExprEvaluator 11015 : public ExprEvaluatorBase<IntExprEvaluator> { 11016 APValue &Result; 11017 public: 11018 IntExprEvaluator(EvalInfo &info, APValue &result) 11019 : ExprEvaluatorBaseTy(info), Result(result) {} 11020 11021 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 11022 assert(E->getType()->isIntegralOrEnumerationType() && 11023 "Invalid evaluation result."); 11024 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 11025 "Invalid evaluation result."); 11026 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 11027 "Invalid evaluation result."); 11028 Result = APValue(SI); 11029 return true; 11030 } 11031 bool Success(const llvm::APSInt &SI, const Expr *E) { 11032 return Success(SI, E, Result); 11033 } 11034 11035 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 11036 assert(E->getType()->isIntegralOrEnumerationType() && 11037 "Invalid evaluation result."); 11038 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 11039 "Invalid evaluation result."); 11040 Result = APValue(APSInt(I)); 11041 Result.getInt().setIsUnsigned( 11042 E->getType()->isUnsignedIntegerOrEnumerationType()); 11043 return true; 11044 } 11045 bool Success(const llvm::APInt &I, const Expr *E) { 11046 return Success(I, E, Result); 11047 } 11048 11049 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11050 assert(E->getType()->isIntegralOrEnumerationType() && 11051 "Invalid evaluation result."); 11052 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 11053 return true; 11054 } 11055 bool Success(uint64_t Value, const Expr *E) { 11056 return Success(Value, E, Result); 11057 } 11058 11059 bool Success(CharUnits Size, const Expr *E) { 11060 return Success(Size.getQuantity(), E); 11061 } 11062 11063 bool Success(const APValue &V, const Expr *E) { 11064 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 11065 Result = V; 11066 return true; 11067 } 11068 return Success(V.getInt(), E); 11069 } 11070 11071 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 11072 11073 //===--------------------------------------------------------------------===// 11074 // Visitor Methods 11075 //===--------------------------------------------------------------------===// 11076 11077 bool VisitIntegerLiteral(const IntegerLiteral *E) { 11078 return Success(E->getValue(), E); 11079 } 11080 bool VisitCharacterLiteral(const CharacterLiteral *E) { 11081 return Success(E->getValue(), E); 11082 } 11083 11084 bool CheckReferencedDecl(const Expr *E, const Decl *D); 11085 bool VisitDeclRefExpr(const DeclRefExpr *E) { 11086 if (CheckReferencedDecl(E, E->getDecl())) 11087 return true; 11088 11089 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 11090 } 11091 bool VisitMemberExpr(const MemberExpr *E) { 11092 if (CheckReferencedDecl(E, E->getMemberDecl())) { 11093 VisitIgnoredBaseExpression(E->getBase()); 11094 return true; 11095 } 11096 11097 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 11098 } 11099 11100 bool VisitCallExpr(const CallExpr *E); 11101 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 11102 bool VisitBinaryOperator(const BinaryOperator *E); 11103 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 11104 bool VisitUnaryOperator(const UnaryOperator *E); 11105 11106 bool VisitCastExpr(const CastExpr* E); 11107 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 11108 11109 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 11110 return Success(E->getValue(), E); 11111 } 11112 11113 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 11114 return Success(E->getValue(), E); 11115 } 11116 11117 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 11118 if (Info.ArrayInitIndex == uint64_t(-1)) { 11119 // We were asked to evaluate this subexpression independent of the 11120 // enclosing ArrayInitLoopExpr. We can't do that. 11121 Info.FFDiag(E); 11122 return false; 11123 } 11124 return Success(Info.ArrayInitIndex, E); 11125 } 11126 11127 // Note, GNU defines __null as an integer, not a pointer. 11128 bool VisitGNUNullExpr(const GNUNullExpr *E) { 11129 return ZeroInitialization(E); 11130 } 11131 11132 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 11133 return Success(E->getValue(), E); 11134 } 11135 11136 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 11137 return Success(E->getValue(), E); 11138 } 11139 11140 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 11141 return Success(E->getValue(), E); 11142 } 11143 11144 bool VisitUnaryReal(const UnaryOperator *E); 11145 bool VisitUnaryImag(const UnaryOperator *E); 11146 11147 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 11148 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 11149 bool VisitSourceLocExpr(const SourceLocExpr *E); 11150 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 11151 bool VisitRequiresExpr(const RequiresExpr *E); 11152 // FIXME: Missing: array subscript of vector, member of vector 11153 }; 11154 11155 class FixedPointExprEvaluator 11156 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 11157 APValue &Result; 11158 11159 public: 11160 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 11161 : ExprEvaluatorBaseTy(info), Result(result) {} 11162 11163 bool Success(const llvm::APInt &I, const Expr *E) { 11164 return Success( 11165 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11166 } 11167 11168 bool Success(uint64_t Value, const Expr *E) { 11169 return Success( 11170 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11171 } 11172 11173 bool Success(const APValue &V, const Expr *E) { 11174 return Success(V.getFixedPoint(), E); 11175 } 11176 11177 bool Success(const APFixedPoint &V, const Expr *E) { 11178 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 11179 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 11180 "Invalid evaluation result."); 11181 Result = APValue(V); 11182 return true; 11183 } 11184 11185 //===--------------------------------------------------------------------===// 11186 // Visitor Methods 11187 //===--------------------------------------------------------------------===// 11188 11189 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 11190 return Success(E->getValue(), E); 11191 } 11192 11193 bool VisitCastExpr(const CastExpr *E); 11194 bool VisitUnaryOperator(const UnaryOperator *E); 11195 bool VisitBinaryOperator(const BinaryOperator *E); 11196 }; 11197 } // end anonymous namespace 11198 11199 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 11200 /// produce either the integer value or a pointer. 11201 /// 11202 /// GCC has a heinous extension which folds casts between pointer types and 11203 /// pointer-sized integral types. We support this by allowing the evaluation of 11204 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 11205 /// Some simple arithmetic on such values is supported (they are treated much 11206 /// like char*). 11207 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 11208 EvalInfo &Info) { 11209 assert(!E->isValueDependent()); 11210 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 11211 return IntExprEvaluator(Info, Result).Visit(E); 11212 } 11213 11214 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 11215 assert(!E->isValueDependent()); 11216 APValue Val; 11217 if (!EvaluateIntegerOrLValue(E, Val, Info)) 11218 return false; 11219 if (!Val.isInt()) { 11220 // FIXME: It would be better to produce the diagnostic for casting 11221 // a pointer to an integer. 11222 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11223 return false; 11224 } 11225 Result = Val.getInt(); 11226 return true; 11227 } 11228 11229 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 11230 APValue Evaluated = E->EvaluateInContext( 11231 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 11232 return Success(Evaluated, E); 11233 } 11234 11235 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 11236 EvalInfo &Info) { 11237 assert(!E->isValueDependent()); 11238 if (E->getType()->isFixedPointType()) { 11239 APValue Val; 11240 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 11241 return false; 11242 if (!Val.isFixedPoint()) 11243 return false; 11244 11245 Result = Val.getFixedPoint(); 11246 return true; 11247 } 11248 return false; 11249 } 11250 11251 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 11252 EvalInfo &Info) { 11253 assert(!E->isValueDependent()); 11254 if (E->getType()->isIntegerType()) { 11255 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 11256 APSInt Val; 11257 if (!EvaluateInteger(E, Val, Info)) 11258 return false; 11259 Result = APFixedPoint(Val, FXSema); 11260 return true; 11261 } else if (E->getType()->isFixedPointType()) { 11262 return EvaluateFixedPoint(E, Result, Info); 11263 } 11264 return false; 11265 } 11266 11267 /// Check whether the given declaration can be directly converted to an integral 11268 /// rvalue. If not, no diagnostic is produced; there are other things we can 11269 /// try. 11270 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 11271 // Enums are integer constant exprs. 11272 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 11273 // Check for signedness/width mismatches between E type and ECD value. 11274 bool SameSign = (ECD->getInitVal().isSigned() 11275 == E->getType()->isSignedIntegerOrEnumerationType()); 11276 bool SameWidth = (ECD->getInitVal().getBitWidth() 11277 == Info.Ctx.getIntWidth(E->getType())); 11278 if (SameSign && SameWidth) 11279 return Success(ECD->getInitVal(), E); 11280 else { 11281 // Get rid of mismatch (otherwise Success assertions will fail) 11282 // by computing a new value matching the type of E. 11283 llvm::APSInt Val = ECD->getInitVal(); 11284 if (!SameSign) 11285 Val.setIsSigned(!ECD->getInitVal().isSigned()); 11286 if (!SameWidth) 11287 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 11288 return Success(Val, E); 11289 } 11290 } 11291 return false; 11292 } 11293 11294 /// Values returned by __builtin_classify_type, chosen to match the values 11295 /// produced by GCC's builtin. 11296 enum class GCCTypeClass { 11297 None = -1, 11298 Void = 0, 11299 Integer = 1, 11300 // GCC reserves 2 for character types, but instead classifies them as 11301 // integers. 11302 Enum = 3, 11303 Bool = 4, 11304 Pointer = 5, 11305 // GCC reserves 6 for references, but appears to never use it (because 11306 // expressions never have reference type, presumably). 11307 PointerToDataMember = 7, 11308 RealFloat = 8, 11309 Complex = 9, 11310 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 11311 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 11312 // GCC claims to reserve 11 for pointers to member functions, but *actually* 11313 // uses 12 for that purpose, same as for a class or struct. Maybe it 11314 // internally implements a pointer to member as a struct? Who knows. 11315 PointerToMemberFunction = 12, // Not a bug, see above. 11316 ClassOrStruct = 12, 11317 Union = 13, 11318 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 11319 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 11320 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 11321 // literals. 11322 }; 11323 11324 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11325 /// as GCC. 11326 static GCCTypeClass 11327 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 11328 assert(!T->isDependentType() && "unexpected dependent type"); 11329 11330 QualType CanTy = T.getCanonicalType(); 11331 11332 switch (CanTy->getTypeClass()) { 11333 #define TYPE(ID, BASE) 11334 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 11335 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 11336 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 11337 #include "clang/AST/TypeNodes.inc" 11338 case Type::Auto: 11339 case Type::DeducedTemplateSpecialization: 11340 llvm_unreachable("unexpected non-canonical or dependent type"); 11341 11342 case Type::Builtin: 11343 switch (cast<BuiltinType>(CanTy)->getKind()) { 11344 #define BUILTIN_TYPE(ID, SINGLETON_ID) 11345 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 11346 case BuiltinType::ID: return GCCTypeClass::Integer; 11347 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 11348 case BuiltinType::ID: return GCCTypeClass::RealFloat; 11349 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 11350 case BuiltinType::ID: break; 11351 #include "clang/AST/BuiltinTypes.def" 11352 case BuiltinType::Void: 11353 return GCCTypeClass::Void; 11354 11355 case BuiltinType::Bool: 11356 return GCCTypeClass::Bool; 11357 11358 case BuiltinType::Char_U: 11359 case BuiltinType::UChar: 11360 case BuiltinType::WChar_U: 11361 case BuiltinType::Char8: 11362 case BuiltinType::Char16: 11363 case BuiltinType::Char32: 11364 case BuiltinType::UShort: 11365 case BuiltinType::UInt: 11366 case BuiltinType::ULong: 11367 case BuiltinType::ULongLong: 11368 case BuiltinType::UInt128: 11369 return GCCTypeClass::Integer; 11370 11371 case BuiltinType::UShortAccum: 11372 case BuiltinType::UAccum: 11373 case BuiltinType::ULongAccum: 11374 case BuiltinType::UShortFract: 11375 case BuiltinType::UFract: 11376 case BuiltinType::ULongFract: 11377 case BuiltinType::SatUShortAccum: 11378 case BuiltinType::SatUAccum: 11379 case BuiltinType::SatULongAccum: 11380 case BuiltinType::SatUShortFract: 11381 case BuiltinType::SatUFract: 11382 case BuiltinType::SatULongFract: 11383 return GCCTypeClass::None; 11384 11385 case BuiltinType::NullPtr: 11386 11387 case BuiltinType::ObjCId: 11388 case BuiltinType::ObjCClass: 11389 case BuiltinType::ObjCSel: 11390 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11391 case BuiltinType::Id: 11392 #include "clang/Basic/OpenCLImageTypes.def" 11393 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11394 case BuiltinType::Id: 11395 #include "clang/Basic/OpenCLExtensionTypes.def" 11396 case BuiltinType::OCLSampler: 11397 case BuiltinType::OCLEvent: 11398 case BuiltinType::OCLClkEvent: 11399 case BuiltinType::OCLQueue: 11400 case BuiltinType::OCLReserveID: 11401 #define SVE_TYPE(Name, Id, SingletonId) \ 11402 case BuiltinType::Id: 11403 #include "clang/Basic/AArch64SVEACLETypes.def" 11404 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11405 case BuiltinType::Id: 11406 #include "clang/Basic/PPCTypes.def" 11407 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11408 #include "clang/Basic/RISCVVTypes.def" 11409 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11410 #include "clang/Basic/WebAssemblyReferenceTypes.def" 11411 return GCCTypeClass::None; 11412 11413 case BuiltinType::Dependent: 11414 llvm_unreachable("unexpected dependent type"); 11415 }; 11416 llvm_unreachable("unexpected placeholder type"); 11417 11418 case Type::Enum: 11419 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11420 11421 case Type::Pointer: 11422 case Type::ConstantArray: 11423 case Type::VariableArray: 11424 case Type::IncompleteArray: 11425 case Type::FunctionNoProto: 11426 case Type::FunctionProto: 11427 return GCCTypeClass::Pointer; 11428 11429 case Type::MemberPointer: 11430 return CanTy->isMemberDataPointerType() 11431 ? GCCTypeClass::PointerToDataMember 11432 : GCCTypeClass::PointerToMemberFunction; 11433 11434 case Type::Complex: 11435 return GCCTypeClass::Complex; 11436 11437 case Type::Record: 11438 return CanTy->isUnionType() ? GCCTypeClass::Union 11439 : GCCTypeClass::ClassOrStruct; 11440 11441 case Type::Atomic: 11442 // GCC classifies _Atomic T the same as T. 11443 return EvaluateBuiltinClassifyType( 11444 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11445 11446 case Type::BlockPointer: 11447 case Type::Vector: 11448 case Type::ExtVector: 11449 case Type::ConstantMatrix: 11450 case Type::ObjCObject: 11451 case Type::ObjCInterface: 11452 case Type::ObjCObjectPointer: 11453 case Type::Pipe: 11454 case Type::BitInt: 11455 // GCC classifies vectors as None. We follow its lead and classify all 11456 // other types that don't fit into the regular classification the same way. 11457 return GCCTypeClass::None; 11458 11459 case Type::LValueReference: 11460 case Type::RValueReference: 11461 llvm_unreachable("invalid type for expression"); 11462 } 11463 11464 llvm_unreachable("unexpected type class"); 11465 } 11466 11467 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11468 /// as GCC. 11469 static GCCTypeClass 11470 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11471 // If no argument was supplied, default to None. This isn't 11472 // ideal, however it is what gcc does. 11473 if (E->getNumArgs() == 0) 11474 return GCCTypeClass::None; 11475 11476 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11477 // being an ICE, but still folds it to a constant using the type of the first 11478 // argument. 11479 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11480 } 11481 11482 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11483 /// __builtin_constant_p when applied to the given pointer. 11484 /// 11485 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11486 /// or it points to the first character of a string literal. 11487 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11488 APValue::LValueBase Base = LV.getLValueBase(); 11489 if (Base.isNull()) { 11490 // A null base is acceptable. 11491 return true; 11492 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11493 if (!isa<StringLiteral>(E)) 11494 return false; 11495 return LV.getLValueOffset().isZero(); 11496 } else if (Base.is<TypeInfoLValue>()) { 11497 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11498 // evaluate to true. 11499 return true; 11500 } else { 11501 // Any other base is not constant enough for GCC. 11502 return false; 11503 } 11504 } 11505 11506 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11507 /// GCC as we can manage. 11508 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11509 // This evaluation is not permitted to have side-effects, so evaluate it in 11510 // a speculative evaluation context. 11511 SpeculativeEvaluationRAII SpeculativeEval(Info); 11512 11513 // Constant-folding is always enabled for the operand of __builtin_constant_p 11514 // (even when the enclosing evaluation context otherwise requires a strict 11515 // language-specific constant expression). 11516 FoldConstant Fold(Info, true); 11517 11518 QualType ArgType = Arg->getType(); 11519 11520 // __builtin_constant_p always has one operand. The rules which gcc follows 11521 // are not precisely documented, but are as follows: 11522 // 11523 // - If the operand is of integral, floating, complex or enumeration type, 11524 // and can be folded to a known value of that type, it returns 1. 11525 // - If the operand can be folded to a pointer to the first character 11526 // of a string literal (or such a pointer cast to an integral type) 11527 // or to a null pointer or an integer cast to a pointer, it returns 1. 11528 // 11529 // Otherwise, it returns 0. 11530 // 11531 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11532 // its support for this did not work prior to GCC 9 and is not yet well 11533 // understood. 11534 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11535 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11536 ArgType->isNullPtrType()) { 11537 APValue V; 11538 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11539 Fold.keepDiagnostics(); 11540 return false; 11541 } 11542 11543 // For a pointer (possibly cast to integer), there are special rules. 11544 if (V.getKind() == APValue::LValue) 11545 return EvaluateBuiltinConstantPForLValue(V); 11546 11547 // Otherwise, any constant value is good enough. 11548 return V.hasValue(); 11549 } 11550 11551 // Anything else isn't considered to be sufficiently constant. 11552 return false; 11553 } 11554 11555 /// Retrieves the "underlying object type" of the given expression, 11556 /// as used by __builtin_object_size. 11557 static QualType getObjectType(APValue::LValueBase B) { 11558 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11559 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11560 return VD->getType(); 11561 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11562 if (isa<CompoundLiteralExpr>(E)) 11563 return E->getType(); 11564 } else if (B.is<TypeInfoLValue>()) { 11565 return B.getTypeInfoType(); 11566 } else if (B.is<DynamicAllocLValue>()) { 11567 return B.getDynamicAllocType(); 11568 } 11569 11570 return QualType(); 11571 } 11572 11573 /// A more selective version of E->IgnoreParenCasts for 11574 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11575 /// to change the type of E. 11576 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11577 /// 11578 /// Always returns an RValue with a pointer representation. 11579 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11580 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11581 11582 auto *NoParens = E->IgnoreParens(); 11583 auto *Cast = dyn_cast<CastExpr>(NoParens); 11584 if (Cast == nullptr) 11585 return NoParens; 11586 11587 // We only conservatively allow a few kinds of casts, because this code is 11588 // inherently a simple solution that seeks to support the common case. 11589 auto CastKind = Cast->getCastKind(); 11590 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11591 CastKind != CK_AddressSpaceConversion) 11592 return NoParens; 11593 11594 auto *SubExpr = Cast->getSubExpr(); 11595 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11596 return NoParens; 11597 return ignorePointerCastsAndParens(SubExpr); 11598 } 11599 11600 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11601 /// record layout. e.g. 11602 /// struct { struct { int a, b; } fst, snd; } obj; 11603 /// obj.fst // no 11604 /// obj.snd // yes 11605 /// obj.fst.a // no 11606 /// obj.fst.b // no 11607 /// obj.snd.a // no 11608 /// obj.snd.b // yes 11609 /// 11610 /// Please note: this function is specialized for how __builtin_object_size 11611 /// views "objects". 11612 /// 11613 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11614 /// correct result, it will always return true. 11615 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11616 assert(!LVal.Designator.Invalid); 11617 11618 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11619 const RecordDecl *Parent = FD->getParent(); 11620 Invalid = Parent->isInvalidDecl(); 11621 if (Invalid || Parent->isUnion()) 11622 return true; 11623 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11624 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11625 }; 11626 11627 auto &Base = LVal.getLValueBase(); 11628 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11629 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11630 bool Invalid; 11631 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11632 return Invalid; 11633 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11634 for (auto *FD : IFD->chain()) { 11635 bool Invalid; 11636 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11637 return Invalid; 11638 } 11639 } 11640 } 11641 11642 unsigned I = 0; 11643 QualType BaseType = getType(Base); 11644 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11645 // If we don't know the array bound, conservatively assume we're looking at 11646 // the final array element. 11647 ++I; 11648 if (BaseType->isIncompleteArrayType()) 11649 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11650 else 11651 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11652 } 11653 11654 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11655 const auto &Entry = LVal.Designator.Entries[I]; 11656 if (BaseType->isArrayType()) { 11657 // Because __builtin_object_size treats arrays as objects, we can ignore 11658 // the index iff this is the last array in the Designator. 11659 if (I + 1 == E) 11660 return true; 11661 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11662 uint64_t Index = Entry.getAsArrayIndex(); 11663 if (Index + 1 != CAT->getSize()) 11664 return false; 11665 BaseType = CAT->getElementType(); 11666 } else if (BaseType->isAnyComplexType()) { 11667 const auto *CT = BaseType->castAs<ComplexType>(); 11668 uint64_t Index = Entry.getAsArrayIndex(); 11669 if (Index != 1) 11670 return false; 11671 BaseType = CT->getElementType(); 11672 } else if (auto *FD = getAsField(Entry)) { 11673 bool Invalid; 11674 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11675 return Invalid; 11676 BaseType = FD->getType(); 11677 } else { 11678 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11679 return false; 11680 } 11681 } 11682 return true; 11683 } 11684 11685 /// Tests to see if the LValue has a user-specified designator (that isn't 11686 /// necessarily valid). Note that this always returns 'true' if the LValue has 11687 /// an unsized array as its first designator entry, because there's currently no 11688 /// way to tell if the user typed *foo or foo[0]. 11689 static bool refersToCompleteObject(const LValue &LVal) { 11690 if (LVal.Designator.Invalid) 11691 return false; 11692 11693 if (!LVal.Designator.Entries.empty()) 11694 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11695 11696 if (!LVal.InvalidBase) 11697 return true; 11698 11699 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11700 // the LValueBase. 11701 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11702 return !E || !isa<MemberExpr>(E); 11703 } 11704 11705 /// Attempts to detect a user writing into a piece of memory that's impossible 11706 /// to figure out the size of by just using types. 11707 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11708 const SubobjectDesignator &Designator = LVal.Designator; 11709 // Notes: 11710 // - Users can only write off of the end when we have an invalid base. Invalid 11711 // bases imply we don't know where the memory came from. 11712 // - We used to be a bit more aggressive here; we'd only be conservative if 11713 // the array at the end was flexible, or if it had 0 or 1 elements. This 11714 // broke some common standard library extensions (PR30346), but was 11715 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11716 // with some sort of list. OTOH, it seems that GCC is always 11717 // conservative with the last element in structs (if it's an array), so our 11718 // current behavior is more compatible than an explicit list approach would 11719 // be. 11720 auto isFlexibleArrayMember = [&] { 11721 using FAMKind = LangOptions::StrictFlexArraysLevelKind; 11722 FAMKind StrictFlexArraysLevel = 11723 Ctx.getLangOpts().getStrictFlexArraysLevel(); 11724 11725 if (Designator.isMostDerivedAnUnsizedArray()) 11726 return true; 11727 11728 if (StrictFlexArraysLevel == FAMKind::Default) 11729 return true; 11730 11731 if (Designator.getMostDerivedArraySize() == 0 && 11732 StrictFlexArraysLevel != FAMKind::IncompleteOnly) 11733 return true; 11734 11735 if (Designator.getMostDerivedArraySize() == 1 && 11736 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete) 11737 return true; 11738 11739 return false; 11740 }; 11741 11742 return LVal.InvalidBase && 11743 Designator.Entries.size() == Designator.MostDerivedPathLength && 11744 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() && 11745 isDesignatorAtObjectEnd(Ctx, LVal); 11746 } 11747 11748 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11749 /// Fails if the conversion would cause loss of precision. 11750 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11751 CharUnits &Result) { 11752 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11753 if (Int.ugt(CharUnitsMax)) 11754 return false; 11755 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11756 return true; 11757 } 11758 11759 /// If we're evaluating the object size of an instance of a struct that 11760 /// contains a flexible array member, add the size of the initializer. 11761 static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, 11762 const LValue &LV, CharUnits &Size) { 11763 if (!T.isNull() && T->isStructureType() && 11764 T->getAsStructureType()->getDecl()->hasFlexibleArrayMember()) 11765 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>()) 11766 if (const auto *VD = dyn_cast<VarDecl>(V)) 11767 if (VD->hasInit()) 11768 Size += VD->getFlexibleArrayInitChars(Info.Ctx); 11769 } 11770 11771 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11772 /// determine how many bytes exist from the beginning of the object to either 11773 /// the end of the current subobject, or the end of the object itself, depending 11774 /// on what the LValue looks like + the value of Type. 11775 /// 11776 /// If this returns false, the value of Result is undefined. 11777 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11778 unsigned Type, const LValue &LVal, 11779 CharUnits &EndOffset) { 11780 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11781 11782 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11783 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11784 return false; 11785 return HandleSizeof(Info, ExprLoc, Ty, Result); 11786 }; 11787 11788 // We want to evaluate the size of the entire object. This is a valid fallback 11789 // for when Type=1 and the designator is invalid, because we're asked for an 11790 // upper-bound. 11791 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11792 // Type=3 wants a lower bound, so we can't fall back to this. 11793 if (Type == 3 && !DetermineForCompleteObject) 11794 return false; 11795 11796 llvm::APInt APEndOffset; 11797 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11798 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11799 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11800 11801 if (LVal.InvalidBase) 11802 return false; 11803 11804 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11805 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset); 11806 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset); 11807 return Ret; 11808 } 11809 11810 // We want to evaluate the size of a subobject. 11811 const SubobjectDesignator &Designator = LVal.Designator; 11812 11813 // The following is a moderately common idiom in C: 11814 // 11815 // struct Foo { int a; char c[1]; }; 11816 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11817 // strcpy(&F->c[0], Bar); 11818 // 11819 // In order to not break too much legacy code, we need to support it. 11820 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11821 // If we can resolve this to an alloc_size call, we can hand that back, 11822 // because we know for certain how many bytes there are to write to. 11823 llvm::APInt APEndOffset; 11824 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11825 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11826 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11827 11828 // If we cannot determine the size of the initial allocation, then we can't 11829 // given an accurate upper-bound. However, we are still able to give 11830 // conservative lower-bounds for Type=3. 11831 if (Type == 1) 11832 return false; 11833 } 11834 11835 CharUnits BytesPerElem; 11836 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11837 return false; 11838 11839 // According to the GCC documentation, we want the size of the subobject 11840 // denoted by the pointer. But that's not quite right -- what we actually 11841 // want is the size of the immediately-enclosing array, if there is one. 11842 int64_t ElemsRemaining; 11843 if (Designator.MostDerivedIsArrayElement && 11844 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11845 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11846 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11847 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11848 } else { 11849 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11850 } 11851 11852 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11853 return true; 11854 } 11855 11856 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11857 /// returns true and stores the result in @p Size. 11858 /// 11859 /// If @p WasError is non-null, this will report whether the failure to evaluate 11860 /// is to be treated as an Error in IntExprEvaluator. 11861 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11862 EvalInfo &Info, uint64_t &Size) { 11863 // Determine the denoted object. 11864 LValue LVal; 11865 { 11866 // The operand of __builtin_object_size is never evaluated for side-effects. 11867 // If there are any, but we can determine the pointed-to object anyway, then 11868 // ignore the side-effects. 11869 SpeculativeEvaluationRAII SpeculativeEval(Info); 11870 IgnoreSideEffectsRAII Fold(Info); 11871 11872 if (E->isGLValue()) { 11873 // It's possible for us to be given GLValues if we're called via 11874 // Expr::tryEvaluateObjectSize. 11875 APValue RVal; 11876 if (!EvaluateAsRValue(Info, E, RVal)) 11877 return false; 11878 LVal.setFrom(Info.Ctx, RVal); 11879 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11880 /*InvalidBaseOK=*/true)) 11881 return false; 11882 } 11883 11884 // If we point to before the start of the object, there are no accessible 11885 // bytes. 11886 if (LVal.getLValueOffset().isNegative()) { 11887 Size = 0; 11888 return true; 11889 } 11890 11891 CharUnits EndOffset; 11892 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11893 return false; 11894 11895 // If we've fallen outside of the end offset, just pretend there's nothing to 11896 // write to/read from. 11897 if (EndOffset <= LVal.getLValueOffset()) 11898 Size = 0; 11899 else 11900 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11901 return true; 11902 } 11903 11904 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11905 if (!IsConstantEvaluatedBuiltinCall(E)) 11906 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11907 return VisitBuiltinCallExpr(E, E->getBuiltinCallee()); 11908 } 11909 11910 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11911 APValue &Val, APSInt &Alignment) { 11912 QualType SrcTy = E->getArg(0)->getType(); 11913 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11914 return false; 11915 // Even though we are evaluating integer expressions we could get a pointer 11916 // argument for the __builtin_is_aligned() case. 11917 if (SrcTy->isPointerType()) { 11918 LValue Ptr; 11919 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11920 return false; 11921 Ptr.moveInto(Val); 11922 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11923 Info.FFDiag(E->getArg(0)); 11924 return false; 11925 } else { 11926 APSInt SrcInt; 11927 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11928 return false; 11929 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11930 "Bit widths must be the same"); 11931 Val = APValue(SrcInt); 11932 } 11933 assert(Val.hasValue()); 11934 return true; 11935 } 11936 11937 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11938 unsigned BuiltinOp) { 11939 switch (BuiltinOp) { 11940 default: 11941 return false; 11942 11943 case Builtin::BI__builtin_dynamic_object_size: 11944 case Builtin::BI__builtin_object_size: { 11945 // The type was checked when we built the expression. 11946 unsigned Type = 11947 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11948 assert(Type <= 3 && "unexpected type"); 11949 11950 uint64_t Size; 11951 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11952 return Success(Size, E); 11953 11954 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11955 return Success((Type & 2) ? 0 : -1, E); 11956 11957 // Expression had no side effects, but we couldn't statically determine the 11958 // size of the referenced object. 11959 switch (Info.EvalMode) { 11960 case EvalInfo::EM_ConstantExpression: 11961 case EvalInfo::EM_ConstantFold: 11962 case EvalInfo::EM_IgnoreSideEffects: 11963 // Leave it to IR generation. 11964 return Error(E); 11965 case EvalInfo::EM_ConstantExpressionUnevaluated: 11966 // Reduce it to a constant now. 11967 return Success((Type & 2) ? 0 : -1, E); 11968 } 11969 11970 llvm_unreachable("unexpected EvalMode"); 11971 } 11972 11973 case Builtin::BI__builtin_os_log_format_buffer_size: { 11974 analyze_os_log::OSLogBufferLayout Layout; 11975 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11976 return Success(Layout.size().getQuantity(), E); 11977 } 11978 11979 case Builtin::BI__builtin_is_aligned: { 11980 APValue Src; 11981 APSInt Alignment; 11982 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11983 return false; 11984 if (Src.isLValue()) { 11985 // If we evaluated a pointer, check the minimum known alignment. 11986 LValue Ptr; 11987 Ptr.setFrom(Info.Ctx, Src); 11988 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11989 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11990 // We can return true if the known alignment at the computed offset is 11991 // greater than the requested alignment. 11992 assert(PtrAlign.isPowerOfTwo()); 11993 assert(Alignment.isPowerOf2()); 11994 if (PtrAlign.getQuantity() >= Alignment) 11995 return Success(1, E); 11996 // If the alignment is not known to be sufficient, some cases could still 11997 // be aligned at run time. However, if the requested alignment is less or 11998 // equal to the base alignment and the offset is not aligned, we know that 11999 // the run-time value can never be aligned. 12000 if (BaseAlignment.getQuantity() >= Alignment && 12001 PtrAlign.getQuantity() < Alignment) 12002 return Success(0, E); 12003 // Otherwise we can't infer whether the value is sufficiently aligned. 12004 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 12005 // in cases where we can't fully evaluate the pointer. 12006 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 12007 << Alignment; 12008 return false; 12009 } 12010 assert(Src.isInt()); 12011 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 12012 } 12013 case Builtin::BI__builtin_align_up: { 12014 APValue Src; 12015 APSInt Alignment; 12016 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 12017 return false; 12018 if (!Src.isInt()) 12019 return Error(E); 12020 APSInt AlignedVal = 12021 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 12022 Src.getInt().isUnsigned()); 12023 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 12024 return Success(AlignedVal, E); 12025 } 12026 case Builtin::BI__builtin_align_down: { 12027 APValue Src; 12028 APSInt Alignment; 12029 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 12030 return false; 12031 if (!Src.isInt()) 12032 return Error(E); 12033 APSInt AlignedVal = 12034 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 12035 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 12036 return Success(AlignedVal, E); 12037 } 12038 12039 case Builtin::BI__builtin_bitreverse8: 12040 case Builtin::BI__builtin_bitreverse16: 12041 case Builtin::BI__builtin_bitreverse32: 12042 case Builtin::BI__builtin_bitreverse64: { 12043 APSInt Val; 12044 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12045 return false; 12046 12047 return Success(Val.reverseBits(), E); 12048 } 12049 12050 case Builtin::BI__builtin_bswap16: 12051 case Builtin::BI__builtin_bswap32: 12052 case Builtin::BI__builtin_bswap64: { 12053 APSInt Val; 12054 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12055 return false; 12056 12057 return Success(Val.byteSwap(), E); 12058 } 12059 12060 case Builtin::BI__builtin_classify_type: 12061 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 12062 12063 case Builtin::BI__builtin_clrsb: 12064 case Builtin::BI__builtin_clrsbl: 12065 case Builtin::BI__builtin_clrsbll: { 12066 APSInt Val; 12067 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12068 return false; 12069 12070 return Success(Val.getBitWidth() - Val.getSignificantBits(), E); 12071 } 12072 12073 case Builtin::BI__builtin_clz: 12074 case Builtin::BI__builtin_clzl: 12075 case Builtin::BI__builtin_clzll: 12076 case Builtin::BI__builtin_clzs: { 12077 APSInt Val; 12078 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12079 return false; 12080 if (!Val) 12081 return Error(E); 12082 12083 return Success(Val.countl_zero(), E); 12084 } 12085 12086 case Builtin::BI__builtin_constant_p: { 12087 const Expr *Arg = E->getArg(0); 12088 if (EvaluateBuiltinConstantP(Info, Arg)) 12089 return Success(true, E); 12090 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 12091 // Outside a constant context, eagerly evaluate to false in the presence 12092 // of side-effects in order to avoid -Wunsequenced false-positives in 12093 // a branch on __builtin_constant_p(expr). 12094 return Success(false, E); 12095 } 12096 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12097 return false; 12098 } 12099 12100 case Builtin::BI__builtin_is_constant_evaluated: { 12101 const auto *Callee = Info.CurrentCall->getCallee(); 12102 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 12103 (Info.CallStackDepth == 1 || 12104 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 12105 Callee->getIdentifier() && 12106 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 12107 // FIXME: Find a better way to avoid duplicated diagnostics. 12108 if (Info.EvalStatus.Diag) 12109 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 12110 : Info.CurrentCall->CallLoc, 12111 diag::warn_is_constant_evaluated_always_true_constexpr) 12112 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 12113 : "std::is_constant_evaluated"); 12114 } 12115 12116 return Success(Info.InConstantContext, E); 12117 } 12118 12119 case Builtin::BI__builtin_ctz: 12120 case Builtin::BI__builtin_ctzl: 12121 case Builtin::BI__builtin_ctzll: 12122 case Builtin::BI__builtin_ctzs: { 12123 APSInt Val; 12124 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12125 return false; 12126 if (!Val) 12127 return Error(E); 12128 12129 return Success(Val.countr_zero(), E); 12130 } 12131 12132 case Builtin::BI__builtin_eh_return_data_regno: { 12133 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 12134 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 12135 return Success(Operand, E); 12136 } 12137 12138 case Builtin::BI__builtin_expect: 12139 case Builtin::BI__builtin_expect_with_probability: 12140 return Visit(E->getArg(0)); 12141 12142 case Builtin::BI__builtin_ffs: 12143 case Builtin::BI__builtin_ffsl: 12144 case Builtin::BI__builtin_ffsll: { 12145 APSInt Val; 12146 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12147 return false; 12148 12149 unsigned N = Val.countr_zero(); 12150 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 12151 } 12152 12153 case Builtin::BI__builtin_fpclassify: { 12154 APFloat Val(0.0); 12155 if (!EvaluateFloat(E->getArg(5), Val, Info)) 12156 return false; 12157 unsigned Arg; 12158 switch (Val.getCategory()) { 12159 case APFloat::fcNaN: Arg = 0; break; 12160 case APFloat::fcInfinity: Arg = 1; break; 12161 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 12162 case APFloat::fcZero: Arg = 4; break; 12163 } 12164 return Visit(E->getArg(Arg)); 12165 } 12166 12167 case Builtin::BI__builtin_isinf_sign: { 12168 APFloat Val(0.0); 12169 return EvaluateFloat(E->getArg(0), Val, Info) && 12170 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 12171 } 12172 12173 case Builtin::BI__builtin_isinf: { 12174 APFloat Val(0.0); 12175 return EvaluateFloat(E->getArg(0), Val, Info) && 12176 Success(Val.isInfinity() ? 1 : 0, E); 12177 } 12178 12179 case Builtin::BI__builtin_isfinite: { 12180 APFloat Val(0.0); 12181 return EvaluateFloat(E->getArg(0), Val, Info) && 12182 Success(Val.isFinite() ? 1 : 0, E); 12183 } 12184 12185 case Builtin::BI__builtin_isnan: { 12186 APFloat Val(0.0); 12187 return EvaluateFloat(E->getArg(0), Val, Info) && 12188 Success(Val.isNaN() ? 1 : 0, E); 12189 } 12190 12191 case Builtin::BI__builtin_isnormal: { 12192 APFloat Val(0.0); 12193 return EvaluateFloat(E->getArg(0), Val, Info) && 12194 Success(Val.isNormal() ? 1 : 0, E); 12195 } 12196 12197 case Builtin::BI__builtin_isfpclass: { 12198 APSInt MaskVal; 12199 if (!EvaluateInteger(E->getArg(1), MaskVal, Info)) 12200 return false; 12201 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue()); 12202 APFloat Val(0.0); 12203 return EvaluateFloat(E->getArg(0), Val, Info) && 12204 Success((Val.classify() & Test) ? 1 : 0, E); 12205 } 12206 12207 case Builtin::BI__builtin_parity: 12208 case Builtin::BI__builtin_parityl: 12209 case Builtin::BI__builtin_parityll: { 12210 APSInt Val; 12211 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12212 return false; 12213 12214 return Success(Val.popcount() % 2, E); 12215 } 12216 12217 case Builtin::BI__builtin_popcount: 12218 case Builtin::BI__builtin_popcountl: 12219 case Builtin::BI__builtin_popcountll: { 12220 APSInt Val; 12221 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12222 return false; 12223 12224 return Success(Val.popcount(), E); 12225 } 12226 12227 case Builtin::BI__builtin_rotateleft8: 12228 case Builtin::BI__builtin_rotateleft16: 12229 case Builtin::BI__builtin_rotateleft32: 12230 case Builtin::BI__builtin_rotateleft64: 12231 case Builtin::BI_rotl8: // Microsoft variants of rotate right 12232 case Builtin::BI_rotl16: 12233 case Builtin::BI_rotl: 12234 case Builtin::BI_lrotl: 12235 case Builtin::BI_rotl64: { 12236 APSInt Val, Amt; 12237 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12238 !EvaluateInteger(E->getArg(1), Amt, Info)) 12239 return false; 12240 12241 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 12242 } 12243 12244 case Builtin::BI__builtin_rotateright8: 12245 case Builtin::BI__builtin_rotateright16: 12246 case Builtin::BI__builtin_rotateright32: 12247 case Builtin::BI__builtin_rotateright64: 12248 case Builtin::BI_rotr8: // Microsoft variants of rotate right 12249 case Builtin::BI_rotr16: 12250 case Builtin::BI_rotr: 12251 case Builtin::BI_lrotr: 12252 case Builtin::BI_rotr64: { 12253 APSInt Val, Amt; 12254 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12255 !EvaluateInteger(E->getArg(1), Amt, Info)) 12256 return false; 12257 12258 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 12259 } 12260 12261 case Builtin::BIstrlen: 12262 case Builtin::BIwcslen: 12263 // A call to strlen is not a constant expression. 12264 if (Info.getLangOpts().CPlusPlus11) 12265 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12266 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 12267 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 12268 else 12269 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12270 [[fallthrough]]; 12271 case Builtin::BI__builtin_strlen: 12272 case Builtin::BI__builtin_wcslen: { 12273 // As an extension, we support __builtin_strlen() as a constant expression, 12274 // and support folding strlen() to a constant. 12275 uint64_t StrLen; 12276 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 12277 return Success(StrLen, E); 12278 return false; 12279 } 12280 12281 case Builtin::BIstrcmp: 12282 case Builtin::BIwcscmp: 12283 case Builtin::BIstrncmp: 12284 case Builtin::BIwcsncmp: 12285 case Builtin::BImemcmp: 12286 case Builtin::BIbcmp: 12287 case Builtin::BIwmemcmp: 12288 // A call to strlen is not a constant expression. 12289 if (Info.getLangOpts().CPlusPlus11) 12290 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12291 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 12292 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 12293 else 12294 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12295 [[fallthrough]]; 12296 case Builtin::BI__builtin_strcmp: 12297 case Builtin::BI__builtin_wcscmp: 12298 case Builtin::BI__builtin_strncmp: 12299 case Builtin::BI__builtin_wcsncmp: 12300 case Builtin::BI__builtin_memcmp: 12301 case Builtin::BI__builtin_bcmp: 12302 case Builtin::BI__builtin_wmemcmp: { 12303 LValue String1, String2; 12304 if (!EvaluatePointer(E->getArg(0), String1, Info) || 12305 !EvaluatePointer(E->getArg(1), String2, Info)) 12306 return false; 12307 12308 uint64_t MaxLength = uint64_t(-1); 12309 if (BuiltinOp != Builtin::BIstrcmp && 12310 BuiltinOp != Builtin::BIwcscmp && 12311 BuiltinOp != Builtin::BI__builtin_strcmp && 12312 BuiltinOp != Builtin::BI__builtin_wcscmp) { 12313 APSInt N; 12314 if (!EvaluateInteger(E->getArg(2), N, Info)) 12315 return false; 12316 MaxLength = N.getExtValue(); 12317 } 12318 12319 // Empty substrings compare equal by definition. 12320 if (MaxLength == 0u) 12321 return Success(0, E); 12322 12323 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12324 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12325 String1.Designator.Invalid || String2.Designator.Invalid) 12326 return false; 12327 12328 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 12329 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 12330 12331 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 12332 BuiltinOp == Builtin::BIbcmp || 12333 BuiltinOp == Builtin::BI__builtin_memcmp || 12334 BuiltinOp == Builtin::BI__builtin_bcmp; 12335 12336 assert(IsRawByte || 12337 (Info.Ctx.hasSameUnqualifiedType( 12338 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 12339 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 12340 12341 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 12342 // 'char8_t', but no other types. 12343 if (IsRawByte && 12344 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 12345 // FIXME: Consider using our bit_cast implementation to support this. 12346 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 12347 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str() 12348 << CharTy1 << CharTy2; 12349 return false; 12350 } 12351 12352 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 12353 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 12354 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 12355 Char1.isInt() && Char2.isInt(); 12356 }; 12357 const auto &AdvanceElems = [&] { 12358 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 12359 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 12360 }; 12361 12362 bool StopAtNull = 12363 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 12364 BuiltinOp != Builtin::BIwmemcmp && 12365 BuiltinOp != Builtin::BI__builtin_memcmp && 12366 BuiltinOp != Builtin::BI__builtin_bcmp && 12367 BuiltinOp != Builtin::BI__builtin_wmemcmp); 12368 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 12369 BuiltinOp == Builtin::BIwcsncmp || 12370 BuiltinOp == Builtin::BIwmemcmp || 12371 BuiltinOp == Builtin::BI__builtin_wcscmp || 12372 BuiltinOp == Builtin::BI__builtin_wcsncmp || 12373 BuiltinOp == Builtin::BI__builtin_wmemcmp; 12374 12375 for (; MaxLength; --MaxLength) { 12376 APValue Char1, Char2; 12377 if (!ReadCurElems(Char1, Char2)) 12378 return false; 12379 if (Char1.getInt().ne(Char2.getInt())) { 12380 if (IsWide) // wmemcmp compares with wchar_t signedness. 12381 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 12382 // memcmp always compares unsigned chars. 12383 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 12384 } 12385 if (StopAtNull && !Char1.getInt()) 12386 return Success(0, E); 12387 assert(!(StopAtNull && !Char2.getInt())); 12388 if (!AdvanceElems()) 12389 return false; 12390 } 12391 // We hit the strncmp / memcmp limit. 12392 return Success(0, E); 12393 } 12394 12395 case Builtin::BI__atomic_always_lock_free: 12396 case Builtin::BI__atomic_is_lock_free: 12397 case Builtin::BI__c11_atomic_is_lock_free: { 12398 APSInt SizeVal; 12399 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 12400 return false; 12401 12402 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12403 // of two less than or equal to the maximum inline atomic width, we know it 12404 // is lock-free. If the size isn't a power of two, or greater than the 12405 // maximum alignment where we promote atomics, we know it is not lock-free 12406 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12407 // the answer can only be determined at runtime; for example, 16-byte 12408 // atomics have lock-free implementations on some, but not all, 12409 // x86-64 processors. 12410 12411 // Check power-of-two. 12412 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12413 if (Size.isPowerOfTwo()) { 12414 // Check against inlining width. 12415 unsigned InlineWidthBits = 12416 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12417 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12418 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12419 Size == CharUnits::One() || 12420 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12421 Expr::NPC_NeverValueDependent)) 12422 // OK, we will inline appropriately-aligned operations of this size, 12423 // and _Atomic(T) is appropriately-aligned. 12424 return Success(1, E); 12425 12426 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12427 castAs<PointerType>()->getPointeeType(); 12428 if (!PointeeType->isIncompleteType() && 12429 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12430 // OK, we will inline operations on this object. 12431 return Success(1, E); 12432 } 12433 } 12434 } 12435 12436 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12437 Success(0, E) : Error(E); 12438 } 12439 case Builtin::BI__builtin_add_overflow: 12440 case Builtin::BI__builtin_sub_overflow: 12441 case Builtin::BI__builtin_mul_overflow: 12442 case Builtin::BI__builtin_sadd_overflow: 12443 case Builtin::BI__builtin_uadd_overflow: 12444 case Builtin::BI__builtin_uaddl_overflow: 12445 case Builtin::BI__builtin_uaddll_overflow: 12446 case Builtin::BI__builtin_usub_overflow: 12447 case Builtin::BI__builtin_usubl_overflow: 12448 case Builtin::BI__builtin_usubll_overflow: 12449 case Builtin::BI__builtin_umul_overflow: 12450 case Builtin::BI__builtin_umull_overflow: 12451 case Builtin::BI__builtin_umulll_overflow: 12452 case Builtin::BI__builtin_saddl_overflow: 12453 case Builtin::BI__builtin_saddll_overflow: 12454 case Builtin::BI__builtin_ssub_overflow: 12455 case Builtin::BI__builtin_ssubl_overflow: 12456 case Builtin::BI__builtin_ssubll_overflow: 12457 case Builtin::BI__builtin_smul_overflow: 12458 case Builtin::BI__builtin_smull_overflow: 12459 case Builtin::BI__builtin_smulll_overflow: { 12460 LValue ResultLValue; 12461 APSInt LHS, RHS; 12462 12463 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12464 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12465 !EvaluateInteger(E->getArg(1), RHS, Info) || 12466 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12467 return false; 12468 12469 APSInt Result; 12470 bool DidOverflow = false; 12471 12472 // If the types don't have to match, enlarge all 3 to the largest of them. 12473 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12474 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12475 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12476 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12477 ResultType->isSignedIntegerOrEnumerationType(); 12478 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12479 ResultType->isSignedIntegerOrEnumerationType(); 12480 uint64_t LHSSize = LHS.getBitWidth(); 12481 uint64_t RHSSize = RHS.getBitWidth(); 12482 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12483 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12484 12485 // Add an additional bit if the signedness isn't uniformly agreed to. We 12486 // could do this ONLY if there is a signed and an unsigned that both have 12487 // MaxBits, but the code to check that is pretty nasty. The issue will be 12488 // caught in the shrink-to-result later anyway. 12489 if (IsSigned && !AllSigned) 12490 ++MaxBits; 12491 12492 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12493 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12494 Result = APSInt(MaxBits, !IsSigned); 12495 } 12496 12497 // Find largest int. 12498 switch (BuiltinOp) { 12499 default: 12500 llvm_unreachable("Invalid value for BuiltinOp"); 12501 case Builtin::BI__builtin_add_overflow: 12502 case Builtin::BI__builtin_sadd_overflow: 12503 case Builtin::BI__builtin_saddl_overflow: 12504 case Builtin::BI__builtin_saddll_overflow: 12505 case Builtin::BI__builtin_uadd_overflow: 12506 case Builtin::BI__builtin_uaddl_overflow: 12507 case Builtin::BI__builtin_uaddll_overflow: 12508 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12509 : LHS.uadd_ov(RHS, DidOverflow); 12510 break; 12511 case Builtin::BI__builtin_sub_overflow: 12512 case Builtin::BI__builtin_ssub_overflow: 12513 case Builtin::BI__builtin_ssubl_overflow: 12514 case Builtin::BI__builtin_ssubll_overflow: 12515 case Builtin::BI__builtin_usub_overflow: 12516 case Builtin::BI__builtin_usubl_overflow: 12517 case Builtin::BI__builtin_usubll_overflow: 12518 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12519 : LHS.usub_ov(RHS, DidOverflow); 12520 break; 12521 case Builtin::BI__builtin_mul_overflow: 12522 case Builtin::BI__builtin_smul_overflow: 12523 case Builtin::BI__builtin_smull_overflow: 12524 case Builtin::BI__builtin_smulll_overflow: 12525 case Builtin::BI__builtin_umul_overflow: 12526 case Builtin::BI__builtin_umull_overflow: 12527 case Builtin::BI__builtin_umulll_overflow: 12528 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12529 : LHS.umul_ov(RHS, DidOverflow); 12530 break; 12531 } 12532 12533 // In the case where multiple sizes are allowed, truncate and see if 12534 // the values are the same. 12535 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12536 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12537 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12538 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12539 // since it will give us the behavior of a TruncOrSelf in the case where 12540 // its parameter <= its size. We previously set Result to be at least the 12541 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12542 // will work exactly like TruncOrSelf. 12543 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12544 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12545 12546 if (!APSInt::isSameValue(Temp, Result)) 12547 DidOverflow = true; 12548 Result = Temp; 12549 } 12550 12551 APValue APV{Result}; 12552 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12553 return false; 12554 return Success(DidOverflow, E); 12555 } 12556 } 12557 } 12558 12559 /// Determine whether this is a pointer past the end of the complete 12560 /// object referred to by the lvalue. 12561 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12562 const LValue &LV) { 12563 // A null pointer can be viewed as being "past the end" but we don't 12564 // choose to look at it that way here. 12565 if (!LV.getLValueBase()) 12566 return false; 12567 12568 // If the designator is valid and refers to a subobject, we're not pointing 12569 // past the end. 12570 if (!LV.getLValueDesignator().Invalid && 12571 !LV.getLValueDesignator().isOnePastTheEnd()) 12572 return false; 12573 12574 // A pointer to an incomplete type might be past-the-end if the type's size is 12575 // zero. We cannot tell because the type is incomplete. 12576 QualType Ty = getType(LV.getLValueBase()); 12577 if (Ty->isIncompleteType()) 12578 return true; 12579 12580 // We're a past-the-end pointer if we point to the byte after the object, 12581 // no matter what our type or path is. 12582 auto Size = Ctx.getTypeSizeInChars(Ty); 12583 return LV.getLValueOffset() == Size; 12584 } 12585 12586 namespace { 12587 12588 /// Data recursive integer evaluator of certain binary operators. 12589 /// 12590 /// We use a data recursive algorithm for binary operators so that we are able 12591 /// to handle extreme cases of chained binary operators without causing stack 12592 /// overflow. 12593 class DataRecursiveIntBinOpEvaluator { 12594 struct EvalResult { 12595 APValue Val; 12596 bool Failed; 12597 12598 EvalResult() : Failed(false) { } 12599 12600 void swap(EvalResult &RHS) { 12601 Val.swap(RHS.Val); 12602 Failed = RHS.Failed; 12603 RHS.Failed = false; 12604 } 12605 }; 12606 12607 struct Job { 12608 const Expr *E; 12609 EvalResult LHSResult; // meaningful only for binary operator expression. 12610 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12611 12612 Job() = default; 12613 Job(Job &&) = default; 12614 12615 void startSpeculativeEval(EvalInfo &Info) { 12616 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12617 } 12618 12619 private: 12620 SpeculativeEvaluationRAII SpecEvalRAII; 12621 }; 12622 12623 SmallVector<Job, 16> Queue; 12624 12625 IntExprEvaluator &IntEval; 12626 EvalInfo &Info; 12627 APValue &FinalResult; 12628 12629 public: 12630 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12631 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12632 12633 /// True if \param E is a binary operator that we are going to handle 12634 /// data recursively. 12635 /// We handle binary operators that are comma, logical, or that have operands 12636 /// with integral or enumeration type. 12637 static bool shouldEnqueue(const BinaryOperator *E) { 12638 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12639 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12640 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12641 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12642 } 12643 12644 bool Traverse(const BinaryOperator *E) { 12645 enqueue(E); 12646 EvalResult PrevResult; 12647 while (!Queue.empty()) 12648 process(PrevResult); 12649 12650 if (PrevResult.Failed) return false; 12651 12652 FinalResult.swap(PrevResult.Val); 12653 return true; 12654 } 12655 12656 private: 12657 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12658 return IntEval.Success(Value, E, Result); 12659 } 12660 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12661 return IntEval.Success(Value, E, Result); 12662 } 12663 bool Error(const Expr *E) { 12664 return IntEval.Error(E); 12665 } 12666 bool Error(const Expr *E, diag::kind D) { 12667 return IntEval.Error(E, D); 12668 } 12669 12670 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12671 return Info.CCEDiag(E, D); 12672 } 12673 12674 // Returns true if visiting the RHS is necessary, false otherwise. 12675 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12676 bool &SuppressRHSDiags); 12677 12678 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12679 const BinaryOperator *E, APValue &Result); 12680 12681 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12682 Result.Failed = !Evaluate(Result.Val, Info, E); 12683 if (Result.Failed) 12684 Result.Val = APValue(); 12685 } 12686 12687 void process(EvalResult &Result); 12688 12689 void enqueue(const Expr *E) { 12690 E = E->IgnoreParens(); 12691 Queue.resize(Queue.size()+1); 12692 Queue.back().E = E; 12693 Queue.back().Kind = Job::AnyExprKind; 12694 } 12695 }; 12696 12697 } 12698 12699 bool DataRecursiveIntBinOpEvaluator:: 12700 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12701 bool &SuppressRHSDiags) { 12702 if (E->getOpcode() == BO_Comma) { 12703 // Ignore LHS but note if we could not evaluate it. 12704 if (LHSResult.Failed) 12705 return Info.noteSideEffect(); 12706 return true; 12707 } 12708 12709 if (E->isLogicalOp()) { 12710 bool LHSAsBool; 12711 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12712 // We were able to evaluate the LHS, see if we can get away with not 12713 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12714 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12715 Success(LHSAsBool, E, LHSResult.Val); 12716 return false; // Ignore RHS 12717 } 12718 } else { 12719 LHSResult.Failed = true; 12720 12721 // Since we weren't able to evaluate the left hand side, it 12722 // might have had side effects. 12723 if (!Info.noteSideEffect()) 12724 return false; 12725 12726 // We can't evaluate the LHS; however, sometimes the result 12727 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12728 // Don't ignore RHS and suppress diagnostics from this arm. 12729 SuppressRHSDiags = true; 12730 } 12731 12732 return true; 12733 } 12734 12735 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12736 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12737 12738 if (LHSResult.Failed && !Info.noteFailure()) 12739 return false; // Ignore RHS; 12740 12741 return true; 12742 } 12743 12744 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12745 bool IsSub) { 12746 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12747 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12748 // offsets. 12749 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12750 CharUnits &Offset = LVal.getLValueOffset(); 12751 uint64_t Offset64 = Offset.getQuantity(); 12752 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12753 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12754 : Offset64 + Index64); 12755 } 12756 12757 bool DataRecursiveIntBinOpEvaluator:: 12758 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12759 const BinaryOperator *E, APValue &Result) { 12760 if (E->getOpcode() == BO_Comma) { 12761 if (RHSResult.Failed) 12762 return false; 12763 Result = RHSResult.Val; 12764 return true; 12765 } 12766 12767 if (E->isLogicalOp()) { 12768 bool lhsResult, rhsResult; 12769 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12770 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12771 12772 if (LHSIsOK) { 12773 if (RHSIsOK) { 12774 if (E->getOpcode() == BO_LOr) 12775 return Success(lhsResult || rhsResult, E, Result); 12776 else 12777 return Success(lhsResult && rhsResult, E, Result); 12778 } 12779 } else { 12780 if (RHSIsOK) { 12781 // We can't evaluate the LHS; however, sometimes the result 12782 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12783 if (rhsResult == (E->getOpcode() == BO_LOr)) 12784 return Success(rhsResult, E, Result); 12785 } 12786 } 12787 12788 return false; 12789 } 12790 12791 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12792 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12793 12794 if (LHSResult.Failed || RHSResult.Failed) 12795 return false; 12796 12797 const APValue &LHSVal = LHSResult.Val; 12798 const APValue &RHSVal = RHSResult.Val; 12799 12800 // Handle cases like (unsigned long)&a + 4. 12801 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12802 Result = LHSVal; 12803 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12804 return true; 12805 } 12806 12807 // Handle cases like 4 + (unsigned long)&a 12808 if (E->getOpcode() == BO_Add && 12809 RHSVal.isLValue() && LHSVal.isInt()) { 12810 Result = RHSVal; 12811 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12812 return true; 12813 } 12814 12815 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12816 // Handle (intptr_t)&&A - (intptr_t)&&B. 12817 if (!LHSVal.getLValueOffset().isZero() || 12818 !RHSVal.getLValueOffset().isZero()) 12819 return false; 12820 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12821 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12822 if (!LHSExpr || !RHSExpr) 12823 return false; 12824 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12825 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12826 if (!LHSAddrExpr || !RHSAddrExpr) 12827 return false; 12828 // Make sure both labels come from the same function. 12829 if (LHSAddrExpr->getLabel()->getDeclContext() != 12830 RHSAddrExpr->getLabel()->getDeclContext()) 12831 return false; 12832 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12833 return true; 12834 } 12835 12836 // All the remaining cases expect both operands to be an integer 12837 if (!LHSVal.isInt() || !RHSVal.isInt()) 12838 return Error(E); 12839 12840 // Set up the width and signedness manually, in case it can't be deduced 12841 // from the operation we're performing. 12842 // FIXME: Don't do this in the cases where we can deduce it. 12843 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12844 E->getType()->isUnsignedIntegerOrEnumerationType()); 12845 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12846 RHSVal.getInt(), Value)) 12847 return false; 12848 return Success(Value, E, Result); 12849 } 12850 12851 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12852 Job &job = Queue.back(); 12853 12854 switch (job.Kind) { 12855 case Job::AnyExprKind: { 12856 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12857 if (shouldEnqueue(Bop)) { 12858 job.Kind = Job::BinOpKind; 12859 enqueue(Bop->getLHS()); 12860 return; 12861 } 12862 } 12863 12864 EvaluateExpr(job.E, Result); 12865 Queue.pop_back(); 12866 return; 12867 } 12868 12869 case Job::BinOpKind: { 12870 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12871 bool SuppressRHSDiags = false; 12872 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12873 Queue.pop_back(); 12874 return; 12875 } 12876 if (SuppressRHSDiags) 12877 job.startSpeculativeEval(Info); 12878 job.LHSResult.swap(Result); 12879 job.Kind = Job::BinOpVisitedLHSKind; 12880 enqueue(Bop->getRHS()); 12881 return; 12882 } 12883 12884 case Job::BinOpVisitedLHSKind: { 12885 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12886 EvalResult RHS; 12887 RHS.swap(Result); 12888 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12889 Queue.pop_back(); 12890 return; 12891 } 12892 } 12893 12894 llvm_unreachable("Invalid Job::Kind!"); 12895 } 12896 12897 namespace { 12898 enum class CmpResult { 12899 Unequal, 12900 Less, 12901 Equal, 12902 Greater, 12903 Unordered, 12904 }; 12905 } 12906 12907 template <class SuccessCB, class AfterCB> 12908 static bool 12909 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12910 SuccessCB &&Success, AfterCB &&DoAfter) { 12911 assert(!E->isValueDependent()); 12912 assert(E->isComparisonOp() && "expected comparison operator"); 12913 assert((E->getOpcode() == BO_Cmp || 12914 E->getType()->isIntegralOrEnumerationType()) && 12915 "unsupported binary expression evaluation"); 12916 auto Error = [&](const Expr *E) { 12917 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12918 return false; 12919 }; 12920 12921 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12922 bool IsEquality = E->isEqualityOp(); 12923 12924 QualType LHSTy = E->getLHS()->getType(); 12925 QualType RHSTy = E->getRHS()->getType(); 12926 12927 if (LHSTy->isIntegralOrEnumerationType() && 12928 RHSTy->isIntegralOrEnumerationType()) { 12929 APSInt LHS, RHS; 12930 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12931 if (!LHSOK && !Info.noteFailure()) 12932 return false; 12933 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12934 return false; 12935 if (LHS < RHS) 12936 return Success(CmpResult::Less, E); 12937 if (LHS > RHS) 12938 return Success(CmpResult::Greater, E); 12939 return Success(CmpResult::Equal, E); 12940 } 12941 12942 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12943 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12944 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12945 12946 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12947 if (!LHSOK && !Info.noteFailure()) 12948 return false; 12949 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12950 return false; 12951 if (LHSFX < RHSFX) 12952 return Success(CmpResult::Less, E); 12953 if (LHSFX > RHSFX) 12954 return Success(CmpResult::Greater, E); 12955 return Success(CmpResult::Equal, E); 12956 } 12957 12958 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12959 ComplexValue LHS, RHS; 12960 bool LHSOK; 12961 if (E->isAssignmentOp()) { 12962 LValue LV; 12963 EvaluateLValue(E->getLHS(), LV, Info); 12964 LHSOK = false; 12965 } else if (LHSTy->isRealFloatingType()) { 12966 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12967 if (LHSOK) { 12968 LHS.makeComplexFloat(); 12969 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12970 } 12971 } else { 12972 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12973 } 12974 if (!LHSOK && !Info.noteFailure()) 12975 return false; 12976 12977 if (E->getRHS()->getType()->isRealFloatingType()) { 12978 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12979 return false; 12980 RHS.makeComplexFloat(); 12981 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12982 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12983 return false; 12984 12985 if (LHS.isComplexFloat()) { 12986 APFloat::cmpResult CR_r = 12987 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12988 APFloat::cmpResult CR_i = 12989 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12990 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12991 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12992 } else { 12993 assert(IsEquality && "invalid complex comparison"); 12994 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12995 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12996 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12997 } 12998 } 12999 13000 if (LHSTy->isRealFloatingType() && 13001 RHSTy->isRealFloatingType()) { 13002 APFloat RHS(0.0), LHS(0.0); 13003 13004 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 13005 if (!LHSOK && !Info.noteFailure()) 13006 return false; 13007 13008 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 13009 return false; 13010 13011 assert(E->isComparisonOp() && "Invalid binary operator!"); 13012 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 13013 if (!Info.InConstantContext && 13014 APFloatCmpResult == APFloat::cmpUnordered && 13015 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 13016 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 13017 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 13018 return false; 13019 } 13020 auto GetCmpRes = [&]() { 13021 switch (APFloatCmpResult) { 13022 case APFloat::cmpEqual: 13023 return CmpResult::Equal; 13024 case APFloat::cmpLessThan: 13025 return CmpResult::Less; 13026 case APFloat::cmpGreaterThan: 13027 return CmpResult::Greater; 13028 case APFloat::cmpUnordered: 13029 return CmpResult::Unordered; 13030 } 13031 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 13032 }; 13033 return Success(GetCmpRes(), E); 13034 } 13035 13036 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 13037 LValue LHSValue, RHSValue; 13038 13039 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13040 if (!LHSOK && !Info.noteFailure()) 13041 return false; 13042 13043 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13044 return false; 13045 13046 // Reject differing bases from the normal codepath; we special-case 13047 // comparisons to null. 13048 if (!HasSameBase(LHSValue, RHSValue)) { 13049 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) { 13050 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType()); 13051 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType()); 13052 Info.FFDiag(E, DiagID) 13053 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS); 13054 return false; 13055 }; 13056 // Inequalities and subtractions between unrelated pointers have 13057 // unspecified or undefined behavior. 13058 if (!IsEquality) 13059 return DiagComparison( 13060 diag::note_constexpr_pointer_comparison_unspecified); 13061 // A constant address may compare equal to the address of a symbol. 13062 // The one exception is that address of an object cannot compare equal 13063 // to a null pointer constant. 13064 // TODO: Should we restrict this to actual null pointers, and exclude the 13065 // case of zero cast to pointer type? 13066 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 13067 (!RHSValue.Base && !RHSValue.Offset.isZero())) 13068 return DiagComparison(diag::note_constexpr_pointer_constant_comparison, 13069 !RHSValue.Base); 13070 // It's implementation-defined whether distinct literals will have 13071 // distinct addresses. In clang, the result of such a comparison is 13072 // unspecified, so it is not a constant expression. However, we do know 13073 // that the address of a literal will be non-null. 13074 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 13075 LHSValue.Base && RHSValue.Base) 13076 return DiagComparison(diag::note_constexpr_literal_comparison); 13077 // We can't tell whether weak symbols will end up pointing to the same 13078 // object. 13079 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 13080 return DiagComparison(diag::note_constexpr_pointer_weak_comparison, 13081 !IsWeakLValue(LHSValue)); 13082 // We can't compare the address of the start of one object with the 13083 // past-the-end address of another object, per C++ DR1652. 13084 if (LHSValue.Base && LHSValue.Offset.isZero() && 13085 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) 13086 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end, 13087 true); 13088 if (RHSValue.Base && RHSValue.Offset.isZero() && 13089 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)) 13090 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end, 13091 false); 13092 // We can't tell whether an object is at the same address as another 13093 // zero sized object. 13094 if ((RHSValue.Base && isZeroSized(LHSValue)) || 13095 (LHSValue.Base && isZeroSized(RHSValue))) 13096 return DiagComparison( 13097 diag::note_constexpr_pointer_comparison_zero_sized); 13098 return Success(CmpResult::Unequal, E); 13099 } 13100 13101 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13102 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13103 13104 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13105 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13106 13107 // C++11 [expr.rel]p3: 13108 // Pointers to void (after pointer conversions) can be compared, with a 13109 // result defined as follows: If both pointers represent the same 13110 // address or are both the null pointer value, the result is true if the 13111 // operator is <= or >= and false otherwise; otherwise the result is 13112 // unspecified. 13113 // We interpret this as applying to pointers to *cv* void. 13114 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 13115 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 13116 13117 // C++11 [expr.rel]p2: 13118 // - If two pointers point to non-static data members of the same object, 13119 // or to subobjects or array elements fo such members, recursively, the 13120 // pointer to the later declared member compares greater provided the 13121 // two members have the same access control and provided their class is 13122 // not a union. 13123 // [...] 13124 // - Otherwise pointer comparisons are unspecified. 13125 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 13126 bool WasArrayIndex; 13127 unsigned Mismatch = FindDesignatorMismatch( 13128 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 13129 // At the point where the designators diverge, the comparison has a 13130 // specified value if: 13131 // - we are comparing array indices 13132 // - we are comparing fields of a union, or fields with the same access 13133 // Otherwise, the result is unspecified and thus the comparison is not a 13134 // constant expression. 13135 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 13136 Mismatch < RHSDesignator.Entries.size()) { 13137 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 13138 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 13139 if (!LF && !RF) 13140 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 13141 else if (!LF) 13142 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 13143 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 13144 << RF->getParent() << RF; 13145 else if (!RF) 13146 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 13147 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 13148 << LF->getParent() << LF; 13149 else if (!LF->getParent()->isUnion() && 13150 LF->getAccess() != RF->getAccess()) 13151 Info.CCEDiag(E, 13152 diag::note_constexpr_pointer_comparison_differing_access) 13153 << LF << LF->getAccess() << RF << RF->getAccess() 13154 << LF->getParent(); 13155 } 13156 } 13157 13158 // The comparison here must be unsigned, and performed with the same 13159 // width as the pointer. 13160 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 13161 uint64_t CompareLHS = LHSOffset.getQuantity(); 13162 uint64_t CompareRHS = RHSOffset.getQuantity(); 13163 assert(PtrSize <= 64 && "Unexpected pointer width"); 13164 uint64_t Mask = ~0ULL >> (64 - PtrSize); 13165 CompareLHS &= Mask; 13166 CompareRHS &= Mask; 13167 13168 // If there is a base and this is a relational operator, we can only 13169 // compare pointers within the object in question; otherwise, the result 13170 // depends on where the object is located in memory. 13171 if (!LHSValue.Base.isNull() && IsRelational) { 13172 QualType BaseTy = getType(LHSValue.Base); 13173 if (BaseTy->isIncompleteType()) 13174 return Error(E); 13175 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 13176 uint64_t OffsetLimit = Size.getQuantity(); 13177 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 13178 return Error(E); 13179 } 13180 13181 if (CompareLHS < CompareRHS) 13182 return Success(CmpResult::Less, E); 13183 if (CompareLHS > CompareRHS) 13184 return Success(CmpResult::Greater, E); 13185 return Success(CmpResult::Equal, E); 13186 } 13187 13188 if (LHSTy->isMemberPointerType()) { 13189 assert(IsEquality && "unexpected member pointer operation"); 13190 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 13191 13192 MemberPtr LHSValue, RHSValue; 13193 13194 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 13195 if (!LHSOK && !Info.noteFailure()) 13196 return false; 13197 13198 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13199 return false; 13200 13201 // If either operand is a pointer to a weak function, the comparison is not 13202 // constant. 13203 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) { 13204 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison) 13205 << LHSValue.getDecl(); 13206 return false; 13207 } 13208 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) { 13209 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison) 13210 << RHSValue.getDecl(); 13211 return false; 13212 } 13213 13214 // C++11 [expr.eq]p2: 13215 // If both operands are null, they compare equal. Otherwise if only one is 13216 // null, they compare unequal. 13217 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 13218 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 13219 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 13220 } 13221 13222 // Otherwise if either is a pointer to a virtual member function, the 13223 // result is unspecified. 13224 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 13225 if (MD->isVirtual()) 13226 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 13227 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 13228 if (MD->isVirtual()) 13229 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 13230 13231 // Otherwise they compare equal if and only if they would refer to the 13232 // same member of the same most derived object or the same subobject if 13233 // they were dereferenced with a hypothetical object of the associated 13234 // class type. 13235 bool Equal = LHSValue == RHSValue; 13236 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 13237 } 13238 13239 if (LHSTy->isNullPtrType()) { 13240 assert(E->isComparisonOp() && "unexpected nullptr operation"); 13241 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 13242 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 13243 // are compared, the result is true of the operator is <=, >= or ==, and 13244 // false otherwise. 13245 return Success(CmpResult::Equal, E); 13246 } 13247 13248 return DoAfter(); 13249 } 13250 13251 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 13252 if (!CheckLiteralType(Info, E)) 13253 return false; 13254 13255 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13256 ComparisonCategoryResult CCR; 13257 switch (CR) { 13258 case CmpResult::Unequal: 13259 llvm_unreachable("should never produce Unequal for three-way comparison"); 13260 case CmpResult::Less: 13261 CCR = ComparisonCategoryResult::Less; 13262 break; 13263 case CmpResult::Equal: 13264 CCR = ComparisonCategoryResult::Equal; 13265 break; 13266 case CmpResult::Greater: 13267 CCR = ComparisonCategoryResult::Greater; 13268 break; 13269 case CmpResult::Unordered: 13270 CCR = ComparisonCategoryResult::Unordered; 13271 break; 13272 } 13273 // Evaluation succeeded. Lookup the information for the comparison category 13274 // type and fetch the VarDecl for the result. 13275 const ComparisonCategoryInfo &CmpInfo = 13276 Info.Ctx.CompCategories.getInfoForType(E->getType()); 13277 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 13278 // Check and evaluate the result as a constant expression. 13279 LValue LV; 13280 LV.set(VD); 13281 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 13282 return false; 13283 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 13284 ConstantExprKind::Normal); 13285 }; 13286 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13287 return ExprEvaluatorBaseTy::VisitBinCmp(E); 13288 }); 13289 } 13290 13291 bool RecordExprEvaluator::VisitCXXParenListInitExpr( 13292 const CXXParenListInitExpr *E) { 13293 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs()); 13294 } 13295 13296 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13297 // We don't support assignment in C. C++ assignments don't get here because 13298 // assignment is an lvalue in C++. 13299 if (E->isAssignmentOp()) { 13300 Error(E); 13301 if (!Info.noteFailure()) 13302 return false; 13303 } 13304 13305 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 13306 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 13307 13308 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 13309 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 13310 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 13311 13312 if (E->isComparisonOp()) { 13313 // Evaluate builtin binary comparisons by evaluating them as three-way 13314 // comparisons and then translating the result. 13315 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13316 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 13317 "should only produce Unequal for equality comparisons"); 13318 bool IsEqual = CR == CmpResult::Equal, 13319 IsLess = CR == CmpResult::Less, 13320 IsGreater = CR == CmpResult::Greater; 13321 auto Op = E->getOpcode(); 13322 switch (Op) { 13323 default: 13324 llvm_unreachable("unsupported binary operator"); 13325 case BO_EQ: 13326 case BO_NE: 13327 return Success(IsEqual == (Op == BO_EQ), E); 13328 case BO_LT: 13329 return Success(IsLess, E); 13330 case BO_GT: 13331 return Success(IsGreater, E); 13332 case BO_LE: 13333 return Success(IsEqual || IsLess, E); 13334 case BO_GE: 13335 return Success(IsEqual || IsGreater, E); 13336 } 13337 }; 13338 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13339 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13340 }); 13341 } 13342 13343 QualType LHSTy = E->getLHS()->getType(); 13344 QualType RHSTy = E->getRHS()->getType(); 13345 13346 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 13347 E->getOpcode() == BO_Sub) { 13348 LValue LHSValue, RHSValue; 13349 13350 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13351 if (!LHSOK && !Info.noteFailure()) 13352 return false; 13353 13354 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13355 return false; 13356 13357 // Reject differing bases from the normal codepath; we special-case 13358 // comparisons to null. 13359 if (!HasSameBase(LHSValue, RHSValue)) { 13360 // Handle &&A - &&B. 13361 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 13362 return Error(E); 13363 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 13364 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 13365 if (!LHSExpr || !RHSExpr) 13366 return Error(E); 13367 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13368 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13369 if (!LHSAddrExpr || !RHSAddrExpr) 13370 return Error(E); 13371 // Make sure both labels come from the same function. 13372 if (LHSAddrExpr->getLabel()->getDeclContext() != 13373 RHSAddrExpr->getLabel()->getDeclContext()) 13374 return Error(E); 13375 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 13376 } 13377 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13378 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13379 13380 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13381 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13382 13383 // C++11 [expr.add]p6: 13384 // Unless both pointers point to elements of the same array object, or 13385 // one past the last element of the array object, the behavior is 13386 // undefined. 13387 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 13388 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 13389 RHSDesignator)) 13390 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 13391 13392 QualType Type = E->getLHS()->getType(); 13393 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 13394 13395 CharUnits ElementSize; 13396 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 13397 return false; 13398 13399 // As an extension, a type may have zero size (empty struct or union in 13400 // C, array of zero length). Pointer subtraction in such cases has 13401 // undefined behavior, so is not constant. 13402 if (ElementSize.isZero()) { 13403 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 13404 << ElementType; 13405 return false; 13406 } 13407 13408 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 13409 // and produce incorrect results when it overflows. Such behavior 13410 // appears to be non-conforming, but is common, so perhaps we should 13411 // assume the standard intended for such cases to be undefined behavior 13412 // and check for them. 13413 13414 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 13415 // overflow in the final conversion to ptrdiff_t. 13416 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 13417 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 13418 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 13419 false); 13420 APSInt TrueResult = (LHS - RHS) / ElemSize; 13421 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 13422 13423 if (Result.extend(65) != TrueResult && 13424 !HandleOverflow(Info, E, TrueResult, E->getType())) 13425 return false; 13426 return Success(Result, E); 13427 } 13428 13429 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13430 } 13431 13432 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 13433 /// a result as the expression's type. 13434 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13435 const UnaryExprOrTypeTraitExpr *E) { 13436 switch(E->getKind()) { 13437 case UETT_PreferredAlignOf: 13438 case UETT_AlignOf: { 13439 if (E->isArgumentType()) 13440 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13441 E); 13442 else 13443 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13444 E); 13445 } 13446 13447 case UETT_VecStep: { 13448 QualType Ty = E->getTypeOfArgument(); 13449 13450 if (Ty->isVectorType()) { 13451 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13452 13453 // The vec_step built-in functions that take a 3-component 13454 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13455 if (n == 3) 13456 n = 4; 13457 13458 return Success(n, E); 13459 } else 13460 return Success(1, E); 13461 } 13462 13463 case UETT_SizeOf: { 13464 QualType SrcTy = E->getTypeOfArgument(); 13465 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13466 // the result is the size of the referenced type." 13467 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13468 SrcTy = Ref->getPointeeType(); 13469 13470 CharUnits Sizeof; 13471 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13472 return false; 13473 return Success(Sizeof, E); 13474 } 13475 case UETT_OpenMPRequiredSimdAlign: 13476 assert(E->isArgumentType()); 13477 return Success( 13478 Info.Ctx.toCharUnitsFromBits( 13479 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13480 .getQuantity(), 13481 E); 13482 } 13483 13484 llvm_unreachable("unknown expr/type trait"); 13485 } 13486 13487 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13488 CharUnits Result; 13489 unsigned n = OOE->getNumComponents(); 13490 if (n == 0) 13491 return Error(OOE); 13492 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13493 for (unsigned i = 0; i != n; ++i) { 13494 OffsetOfNode ON = OOE->getComponent(i); 13495 switch (ON.getKind()) { 13496 case OffsetOfNode::Array: { 13497 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13498 APSInt IdxResult; 13499 if (!EvaluateInteger(Idx, IdxResult, Info)) 13500 return false; 13501 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13502 if (!AT) 13503 return Error(OOE); 13504 CurrentType = AT->getElementType(); 13505 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13506 Result += IdxResult.getSExtValue() * ElementSize; 13507 break; 13508 } 13509 13510 case OffsetOfNode::Field: { 13511 FieldDecl *MemberDecl = ON.getField(); 13512 const RecordType *RT = CurrentType->getAs<RecordType>(); 13513 if (!RT) 13514 return Error(OOE); 13515 RecordDecl *RD = RT->getDecl(); 13516 if (RD->isInvalidDecl()) return false; 13517 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13518 unsigned i = MemberDecl->getFieldIndex(); 13519 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13520 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13521 CurrentType = MemberDecl->getType().getNonReferenceType(); 13522 break; 13523 } 13524 13525 case OffsetOfNode::Identifier: 13526 llvm_unreachable("dependent __builtin_offsetof"); 13527 13528 case OffsetOfNode::Base: { 13529 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13530 if (BaseSpec->isVirtual()) 13531 return Error(OOE); 13532 13533 // Find the layout of the class whose base we are looking into. 13534 const RecordType *RT = CurrentType->getAs<RecordType>(); 13535 if (!RT) 13536 return Error(OOE); 13537 RecordDecl *RD = RT->getDecl(); 13538 if (RD->isInvalidDecl()) return false; 13539 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13540 13541 // Find the base class itself. 13542 CurrentType = BaseSpec->getType(); 13543 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13544 if (!BaseRT) 13545 return Error(OOE); 13546 13547 // Add the offset to the base. 13548 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13549 break; 13550 } 13551 } 13552 } 13553 return Success(Result, OOE); 13554 } 13555 13556 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13557 switch (E->getOpcode()) { 13558 default: 13559 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13560 // See C99 6.6p3. 13561 return Error(E); 13562 case UO_Extension: 13563 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13564 // If so, we could clear the diagnostic ID. 13565 return Visit(E->getSubExpr()); 13566 case UO_Plus: 13567 // The result is just the value. 13568 return Visit(E->getSubExpr()); 13569 case UO_Minus: { 13570 if (!Visit(E->getSubExpr())) 13571 return false; 13572 if (!Result.isInt()) return Error(E); 13573 const APSInt &Value = Result.getInt(); 13574 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) { 13575 if (Info.checkingForUndefinedBehavior()) 13576 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13577 diag::warn_integer_constant_overflow) 13578 << toString(Value, 10) << E->getType(); 13579 13580 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13581 E->getType())) 13582 return false; 13583 } 13584 return Success(-Value, E); 13585 } 13586 case UO_Not: { 13587 if (!Visit(E->getSubExpr())) 13588 return false; 13589 if (!Result.isInt()) return Error(E); 13590 return Success(~Result.getInt(), E); 13591 } 13592 case UO_LNot: { 13593 bool bres; 13594 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13595 return false; 13596 return Success(!bres, E); 13597 } 13598 } 13599 } 13600 13601 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13602 /// result type is integer. 13603 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13604 const Expr *SubExpr = E->getSubExpr(); 13605 QualType DestType = E->getType(); 13606 QualType SrcType = SubExpr->getType(); 13607 13608 switch (E->getCastKind()) { 13609 case CK_BaseToDerived: 13610 case CK_DerivedToBase: 13611 case CK_UncheckedDerivedToBase: 13612 case CK_Dynamic: 13613 case CK_ToUnion: 13614 case CK_ArrayToPointerDecay: 13615 case CK_FunctionToPointerDecay: 13616 case CK_NullToPointer: 13617 case CK_NullToMemberPointer: 13618 case CK_BaseToDerivedMemberPointer: 13619 case CK_DerivedToBaseMemberPointer: 13620 case CK_ReinterpretMemberPointer: 13621 case CK_ConstructorConversion: 13622 case CK_IntegralToPointer: 13623 case CK_ToVoid: 13624 case CK_VectorSplat: 13625 case CK_IntegralToFloating: 13626 case CK_FloatingCast: 13627 case CK_CPointerToObjCPointerCast: 13628 case CK_BlockPointerToObjCPointerCast: 13629 case CK_AnyPointerToBlockPointerCast: 13630 case CK_ObjCObjectLValueCast: 13631 case CK_FloatingRealToComplex: 13632 case CK_FloatingComplexToReal: 13633 case CK_FloatingComplexCast: 13634 case CK_FloatingComplexToIntegralComplex: 13635 case CK_IntegralRealToComplex: 13636 case CK_IntegralComplexCast: 13637 case CK_IntegralComplexToFloatingComplex: 13638 case CK_BuiltinFnToFnPtr: 13639 case CK_ZeroToOCLOpaqueType: 13640 case CK_NonAtomicToAtomic: 13641 case CK_AddressSpaceConversion: 13642 case CK_IntToOCLSampler: 13643 case CK_FloatingToFixedPoint: 13644 case CK_FixedPointToFloating: 13645 case CK_FixedPointCast: 13646 case CK_IntegralToFixedPoint: 13647 case CK_MatrixCast: 13648 llvm_unreachable("invalid cast kind for integral value"); 13649 13650 case CK_BitCast: 13651 case CK_Dependent: 13652 case CK_LValueBitCast: 13653 case CK_ARCProduceObject: 13654 case CK_ARCConsumeObject: 13655 case CK_ARCReclaimReturnedObject: 13656 case CK_ARCExtendBlockObject: 13657 case CK_CopyAndAutoreleaseBlockObject: 13658 return Error(E); 13659 13660 case CK_UserDefinedConversion: 13661 case CK_LValueToRValue: 13662 case CK_AtomicToNonAtomic: 13663 case CK_NoOp: 13664 case CK_LValueToRValueBitCast: 13665 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13666 13667 case CK_MemberPointerToBoolean: 13668 case CK_PointerToBoolean: 13669 case CK_IntegralToBoolean: 13670 case CK_FloatingToBoolean: 13671 case CK_BooleanToSignedIntegral: 13672 case CK_FloatingComplexToBoolean: 13673 case CK_IntegralComplexToBoolean: { 13674 bool BoolResult; 13675 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13676 return false; 13677 uint64_t IntResult = BoolResult; 13678 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13679 IntResult = (uint64_t)-1; 13680 return Success(IntResult, E); 13681 } 13682 13683 case CK_FixedPointToIntegral: { 13684 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13685 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13686 return false; 13687 bool Overflowed; 13688 llvm::APSInt Result = Src.convertToInt( 13689 Info.Ctx.getIntWidth(DestType), 13690 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13691 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13692 return false; 13693 return Success(Result, E); 13694 } 13695 13696 case CK_FixedPointToBoolean: { 13697 // Unsigned padding does not affect this. 13698 APValue Val; 13699 if (!Evaluate(Val, Info, SubExpr)) 13700 return false; 13701 return Success(Val.getFixedPoint().getBoolValue(), E); 13702 } 13703 13704 case CK_IntegralCast: { 13705 if (!Visit(SubExpr)) 13706 return false; 13707 13708 if (!Result.isInt()) { 13709 // Allow casts of address-of-label differences if they are no-ops 13710 // or narrowing. (The narrowing case isn't actually guaranteed to 13711 // be constant-evaluatable except in some narrow cases which are hard 13712 // to detect here. We let it through on the assumption the user knows 13713 // what they are doing.) 13714 if (Result.isAddrLabelDiff()) 13715 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13716 // Only allow casts of lvalues if they are lossless. 13717 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13718 } 13719 13720 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext && 13721 Info.EvalMode == EvalInfo::EM_ConstantExpression && 13722 DestType->isEnumeralType()) { 13723 13724 bool ConstexprVar = true; 13725 13726 // We know if we are here that we are in a context that we might require 13727 // a constant expression or a context that requires a constant 13728 // value. But if we are initializing a value we don't know if it is a 13729 // constexpr variable or not. We can check the EvaluatingDecl to determine 13730 // if it constexpr or not. If not then we don't want to emit a diagnostic. 13731 if (const auto *VD = dyn_cast_or_null<VarDecl>( 13732 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) 13733 ConstexprVar = VD->isConstexpr(); 13734 13735 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType()); 13736 const EnumDecl *ED = ET->getDecl(); 13737 // Check that the value is within the range of the enumeration values. 13738 // 13739 // This corressponds to [expr.static.cast]p10 which says: 13740 // A value of integral or enumeration type can be explicitly converted 13741 // to a complete enumeration type ... If the enumeration type does not 13742 // have a fixed underlying type, the value is unchanged if the original 13743 // value is within the range of the enumeration values ([dcl.enum]), and 13744 // otherwise, the behavior is undefined. 13745 // 13746 // This was resolved as part of DR2338 which has CD5 status. 13747 if (!ED->isFixed()) { 13748 llvm::APInt Min; 13749 llvm::APInt Max; 13750 13751 ED->getValueRange(Max, Min); 13752 --Max; 13753 13754 if (ED->getNumNegativeBits() && ConstexprVar && 13755 (Max.slt(Result.getInt().getSExtValue()) || 13756 Min.sgt(Result.getInt().getSExtValue()))) 13757 Info.Ctx.getDiagnostics().Report( 13758 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range) 13759 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue() 13760 << Max.getSExtValue() << ED; 13761 else if (!ED->getNumNegativeBits() && ConstexprVar && 13762 Max.ult(Result.getInt().getZExtValue())) 13763 Info.Ctx.getDiagnostics().Report( 13764 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range) 13765 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue() 13766 << Max.getZExtValue() << ED; 13767 } 13768 } 13769 13770 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13771 Result.getInt()), E); 13772 } 13773 13774 case CK_PointerToIntegral: { 13775 CCEDiag(E, diag::note_constexpr_invalid_cast) 13776 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 13777 13778 LValue LV; 13779 if (!EvaluatePointer(SubExpr, LV, Info)) 13780 return false; 13781 13782 if (LV.getLValueBase()) { 13783 // Only allow based lvalue casts if they are lossless. 13784 // FIXME: Allow a larger integer size than the pointer size, and allow 13785 // narrowing back down to pointer width in subsequent integral casts. 13786 // FIXME: Check integer type's active bits, not its type size. 13787 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13788 return Error(E); 13789 13790 LV.Designator.setInvalid(); 13791 LV.moveInto(Result); 13792 return true; 13793 } 13794 13795 APSInt AsInt; 13796 APValue V; 13797 LV.moveInto(V); 13798 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13799 llvm_unreachable("Can't cast this!"); 13800 13801 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13802 } 13803 13804 case CK_IntegralComplexToReal: { 13805 ComplexValue C; 13806 if (!EvaluateComplex(SubExpr, C, Info)) 13807 return false; 13808 return Success(C.getComplexIntReal(), E); 13809 } 13810 13811 case CK_FloatingToIntegral: { 13812 APFloat F(0.0); 13813 if (!EvaluateFloat(SubExpr, F, Info)) 13814 return false; 13815 13816 APSInt Value; 13817 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13818 return false; 13819 return Success(Value, E); 13820 } 13821 } 13822 13823 llvm_unreachable("unknown cast resulting in integral value"); 13824 } 13825 13826 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13827 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13828 ComplexValue LV; 13829 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13830 return false; 13831 if (!LV.isComplexInt()) 13832 return Error(E); 13833 return Success(LV.getComplexIntReal(), E); 13834 } 13835 13836 return Visit(E->getSubExpr()); 13837 } 13838 13839 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13840 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13841 ComplexValue LV; 13842 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13843 return false; 13844 if (!LV.isComplexInt()) 13845 return Error(E); 13846 return Success(LV.getComplexIntImag(), E); 13847 } 13848 13849 VisitIgnoredValue(E->getSubExpr()); 13850 return Success(0, E); 13851 } 13852 13853 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13854 return Success(E->getPackLength(), E); 13855 } 13856 13857 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13858 return Success(E->getValue(), E); 13859 } 13860 13861 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13862 const ConceptSpecializationExpr *E) { 13863 return Success(E->isSatisfied(), E); 13864 } 13865 13866 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13867 return Success(E->isSatisfied(), E); 13868 } 13869 13870 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13871 switch (E->getOpcode()) { 13872 default: 13873 // Invalid unary operators 13874 return Error(E); 13875 case UO_Plus: 13876 // The result is just the value. 13877 return Visit(E->getSubExpr()); 13878 case UO_Minus: { 13879 if (!Visit(E->getSubExpr())) return false; 13880 if (!Result.isFixedPoint()) 13881 return Error(E); 13882 bool Overflowed; 13883 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13884 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13885 return false; 13886 return Success(Negated, E); 13887 } 13888 case UO_LNot: { 13889 bool bres; 13890 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13891 return false; 13892 return Success(!bres, E); 13893 } 13894 } 13895 } 13896 13897 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13898 const Expr *SubExpr = E->getSubExpr(); 13899 QualType DestType = E->getType(); 13900 assert(DestType->isFixedPointType() && 13901 "Expected destination type to be a fixed point type"); 13902 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13903 13904 switch (E->getCastKind()) { 13905 case CK_FixedPointCast: { 13906 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13907 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13908 return false; 13909 bool Overflowed; 13910 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13911 if (Overflowed) { 13912 if (Info.checkingForUndefinedBehavior()) 13913 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13914 diag::warn_fixedpoint_constant_overflow) 13915 << Result.toString() << E->getType(); 13916 if (!HandleOverflow(Info, E, Result, E->getType())) 13917 return false; 13918 } 13919 return Success(Result, E); 13920 } 13921 case CK_IntegralToFixedPoint: { 13922 APSInt Src; 13923 if (!EvaluateInteger(SubExpr, Src, Info)) 13924 return false; 13925 13926 bool Overflowed; 13927 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13928 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13929 13930 if (Overflowed) { 13931 if (Info.checkingForUndefinedBehavior()) 13932 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13933 diag::warn_fixedpoint_constant_overflow) 13934 << IntResult.toString() << E->getType(); 13935 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13936 return false; 13937 } 13938 13939 return Success(IntResult, E); 13940 } 13941 case CK_FloatingToFixedPoint: { 13942 APFloat Src(0.0); 13943 if (!EvaluateFloat(SubExpr, Src, Info)) 13944 return false; 13945 13946 bool Overflowed; 13947 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13948 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13949 13950 if (Overflowed) { 13951 if (Info.checkingForUndefinedBehavior()) 13952 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13953 diag::warn_fixedpoint_constant_overflow) 13954 << Result.toString() << E->getType(); 13955 if (!HandleOverflow(Info, E, Result, E->getType())) 13956 return false; 13957 } 13958 13959 return Success(Result, E); 13960 } 13961 case CK_NoOp: 13962 case CK_LValueToRValue: 13963 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13964 default: 13965 return Error(E); 13966 } 13967 } 13968 13969 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13970 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13971 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13972 13973 const Expr *LHS = E->getLHS(); 13974 const Expr *RHS = E->getRHS(); 13975 FixedPointSemantics ResultFXSema = 13976 Info.Ctx.getFixedPointSemantics(E->getType()); 13977 13978 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13979 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13980 return false; 13981 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13982 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13983 return false; 13984 13985 bool OpOverflow = false, ConversionOverflow = false; 13986 APFixedPoint Result(LHSFX.getSemantics()); 13987 switch (E->getOpcode()) { 13988 case BO_Add: { 13989 Result = LHSFX.add(RHSFX, &OpOverflow) 13990 .convert(ResultFXSema, &ConversionOverflow); 13991 break; 13992 } 13993 case BO_Sub: { 13994 Result = LHSFX.sub(RHSFX, &OpOverflow) 13995 .convert(ResultFXSema, &ConversionOverflow); 13996 break; 13997 } 13998 case BO_Mul: { 13999 Result = LHSFX.mul(RHSFX, &OpOverflow) 14000 .convert(ResultFXSema, &ConversionOverflow); 14001 break; 14002 } 14003 case BO_Div: { 14004 if (RHSFX.getValue() == 0) { 14005 Info.FFDiag(E, diag::note_expr_divide_by_zero); 14006 return false; 14007 } 14008 Result = LHSFX.div(RHSFX, &OpOverflow) 14009 .convert(ResultFXSema, &ConversionOverflow); 14010 break; 14011 } 14012 case BO_Shl: 14013 case BO_Shr: { 14014 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 14015 llvm::APSInt RHSVal = RHSFX.getValue(); 14016 14017 unsigned ShiftBW = 14018 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 14019 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 14020 // Embedded-C 4.1.6.2.2: 14021 // The right operand must be nonnegative and less than the total number 14022 // of (nonpadding) bits of the fixed-point operand ... 14023 if (RHSVal.isNegative()) 14024 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 14025 else if (Amt != RHSVal) 14026 Info.CCEDiag(E, diag::note_constexpr_large_shift) 14027 << RHSVal << E->getType() << ShiftBW; 14028 14029 if (E->getOpcode() == BO_Shl) 14030 Result = LHSFX.shl(Amt, &OpOverflow); 14031 else 14032 Result = LHSFX.shr(Amt, &OpOverflow); 14033 break; 14034 } 14035 default: 14036 return false; 14037 } 14038 if (OpOverflow || ConversionOverflow) { 14039 if (Info.checkingForUndefinedBehavior()) 14040 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 14041 diag::warn_fixedpoint_constant_overflow) 14042 << Result.toString() << E->getType(); 14043 if (!HandleOverflow(Info, E, Result, E->getType())) 14044 return false; 14045 } 14046 return Success(Result, E); 14047 } 14048 14049 //===----------------------------------------------------------------------===// 14050 // Float Evaluation 14051 //===----------------------------------------------------------------------===// 14052 14053 namespace { 14054 class FloatExprEvaluator 14055 : public ExprEvaluatorBase<FloatExprEvaluator> { 14056 APFloat &Result; 14057 public: 14058 FloatExprEvaluator(EvalInfo &info, APFloat &result) 14059 : ExprEvaluatorBaseTy(info), Result(result) {} 14060 14061 bool Success(const APValue &V, const Expr *e) { 14062 Result = V.getFloat(); 14063 return true; 14064 } 14065 14066 bool ZeroInitialization(const Expr *E) { 14067 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 14068 return true; 14069 } 14070 14071 bool VisitCallExpr(const CallExpr *E); 14072 14073 bool VisitUnaryOperator(const UnaryOperator *E); 14074 bool VisitBinaryOperator(const BinaryOperator *E); 14075 bool VisitFloatingLiteral(const FloatingLiteral *E); 14076 bool VisitCastExpr(const CastExpr *E); 14077 14078 bool VisitUnaryReal(const UnaryOperator *E); 14079 bool VisitUnaryImag(const UnaryOperator *E); 14080 14081 // FIXME: Missing: array subscript of vector, member of vector 14082 }; 14083 } // end anonymous namespace 14084 14085 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 14086 assert(!E->isValueDependent()); 14087 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 14088 return FloatExprEvaluator(Info, Result).Visit(E); 14089 } 14090 14091 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 14092 QualType ResultTy, 14093 const Expr *Arg, 14094 bool SNaN, 14095 llvm::APFloat &Result) { 14096 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 14097 if (!S) return false; 14098 14099 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 14100 14101 llvm::APInt fill; 14102 14103 // Treat empty strings as if they were zero. 14104 if (S->getString().empty()) 14105 fill = llvm::APInt(32, 0); 14106 else if (S->getString().getAsInteger(0, fill)) 14107 return false; 14108 14109 if (Context.getTargetInfo().isNan2008()) { 14110 if (SNaN) 14111 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 14112 else 14113 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 14114 } else { 14115 // Prior to IEEE 754-2008, architectures were allowed to choose whether 14116 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 14117 // a different encoding to what became a standard in 2008, and for pre- 14118 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 14119 // sNaN. This is now known as "legacy NaN" encoding. 14120 if (SNaN) 14121 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 14122 else 14123 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 14124 } 14125 14126 return true; 14127 } 14128 14129 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 14130 if (!IsConstantEvaluatedBuiltinCall(E)) 14131 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14132 14133 switch (E->getBuiltinCallee()) { 14134 default: 14135 return false; 14136 14137 case Builtin::BI__builtin_huge_val: 14138 case Builtin::BI__builtin_huge_valf: 14139 case Builtin::BI__builtin_huge_vall: 14140 case Builtin::BI__builtin_huge_valf16: 14141 case Builtin::BI__builtin_huge_valf128: 14142 case Builtin::BI__builtin_inf: 14143 case Builtin::BI__builtin_inff: 14144 case Builtin::BI__builtin_infl: 14145 case Builtin::BI__builtin_inff16: 14146 case Builtin::BI__builtin_inff128: { 14147 const llvm::fltSemantics &Sem = 14148 Info.Ctx.getFloatTypeSemantics(E->getType()); 14149 Result = llvm::APFloat::getInf(Sem); 14150 return true; 14151 } 14152 14153 case Builtin::BI__builtin_nans: 14154 case Builtin::BI__builtin_nansf: 14155 case Builtin::BI__builtin_nansl: 14156 case Builtin::BI__builtin_nansf16: 14157 case Builtin::BI__builtin_nansf128: 14158 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 14159 true, Result)) 14160 return Error(E); 14161 return true; 14162 14163 case Builtin::BI__builtin_nan: 14164 case Builtin::BI__builtin_nanf: 14165 case Builtin::BI__builtin_nanl: 14166 case Builtin::BI__builtin_nanf16: 14167 case Builtin::BI__builtin_nanf128: 14168 // If this is __builtin_nan() turn this into a nan, otherwise we 14169 // can't constant fold it. 14170 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 14171 false, Result)) 14172 return Error(E); 14173 return true; 14174 14175 case Builtin::BI__builtin_fabs: 14176 case Builtin::BI__builtin_fabsf: 14177 case Builtin::BI__builtin_fabsl: 14178 case Builtin::BI__builtin_fabsf128: 14179 // The C standard says "fabs raises no floating-point exceptions, 14180 // even if x is a signaling NaN. The returned value is independent of 14181 // the current rounding direction mode." Therefore constant folding can 14182 // proceed without regard to the floating point settings. 14183 // Reference, WG14 N2478 F.10.4.3 14184 if (!EvaluateFloat(E->getArg(0), Result, Info)) 14185 return false; 14186 14187 if (Result.isNegative()) 14188 Result.changeSign(); 14189 return true; 14190 14191 case Builtin::BI__arithmetic_fence: 14192 return EvaluateFloat(E->getArg(0), Result, Info); 14193 14194 // FIXME: Builtin::BI__builtin_powi 14195 // FIXME: Builtin::BI__builtin_powif 14196 // FIXME: Builtin::BI__builtin_powil 14197 14198 case Builtin::BI__builtin_copysign: 14199 case Builtin::BI__builtin_copysignf: 14200 case Builtin::BI__builtin_copysignl: 14201 case Builtin::BI__builtin_copysignf128: { 14202 APFloat RHS(0.); 14203 if (!EvaluateFloat(E->getArg(0), Result, Info) || 14204 !EvaluateFloat(E->getArg(1), RHS, Info)) 14205 return false; 14206 Result.copySign(RHS); 14207 return true; 14208 } 14209 14210 case Builtin::BI__builtin_fmax: 14211 case Builtin::BI__builtin_fmaxf: 14212 case Builtin::BI__builtin_fmaxl: 14213 case Builtin::BI__builtin_fmaxf16: 14214 case Builtin::BI__builtin_fmaxf128: { 14215 // TODO: Handle sNaN. 14216 APFloat RHS(0.); 14217 if (!EvaluateFloat(E->getArg(0), Result, Info) || 14218 !EvaluateFloat(E->getArg(1), RHS, Info)) 14219 return false; 14220 // When comparing zeroes, return +0.0 if one of the zeroes is positive. 14221 if (Result.isZero() && RHS.isZero() && Result.isNegative()) 14222 Result = RHS; 14223 else if (Result.isNaN() || RHS > Result) 14224 Result = RHS; 14225 return true; 14226 } 14227 14228 case Builtin::BI__builtin_fmin: 14229 case Builtin::BI__builtin_fminf: 14230 case Builtin::BI__builtin_fminl: 14231 case Builtin::BI__builtin_fminf16: 14232 case Builtin::BI__builtin_fminf128: { 14233 // TODO: Handle sNaN. 14234 APFloat RHS(0.); 14235 if (!EvaluateFloat(E->getArg(0), Result, Info) || 14236 !EvaluateFloat(E->getArg(1), RHS, Info)) 14237 return false; 14238 // When comparing zeroes, return -0.0 if one of the zeroes is negative. 14239 if (Result.isZero() && RHS.isZero() && RHS.isNegative()) 14240 Result = RHS; 14241 else if (Result.isNaN() || RHS < Result) 14242 Result = RHS; 14243 return true; 14244 } 14245 } 14246 } 14247 14248 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 14249 if (E->getSubExpr()->getType()->isAnyComplexType()) { 14250 ComplexValue CV; 14251 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 14252 return false; 14253 Result = CV.FloatReal; 14254 return true; 14255 } 14256 14257 return Visit(E->getSubExpr()); 14258 } 14259 14260 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 14261 if (E->getSubExpr()->getType()->isAnyComplexType()) { 14262 ComplexValue CV; 14263 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 14264 return false; 14265 Result = CV.FloatImag; 14266 return true; 14267 } 14268 14269 VisitIgnoredValue(E->getSubExpr()); 14270 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 14271 Result = llvm::APFloat::getZero(Sem); 14272 return true; 14273 } 14274 14275 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14276 switch (E->getOpcode()) { 14277 default: return Error(E); 14278 case UO_Plus: 14279 return EvaluateFloat(E->getSubExpr(), Result, Info); 14280 case UO_Minus: 14281 // In C standard, WG14 N2478 F.3 p4 14282 // "the unary - raises no floating point exceptions, 14283 // even if the operand is signalling." 14284 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 14285 return false; 14286 Result.changeSign(); 14287 return true; 14288 } 14289 } 14290 14291 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14292 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14293 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14294 14295 APFloat RHS(0.0); 14296 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 14297 if (!LHSOK && !Info.noteFailure()) 14298 return false; 14299 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 14300 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 14301 } 14302 14303 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 14304 Result = E->getValue(); 14305 return true; 14306 } 14307 14308 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 14309 const Expr* SubExpr = E->getSubExpr(); 14310 14311 switch (E->getCastKind()) { 14312 default: 14313 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14314 14315 case CK_IntegralToFloating: { 14316 APSInt IntResult; 14317 const FPOptions FPO = E->getFPFeaturesInEffect( 14318 Info.Ctx.getLangOpts()); 14319 return EvaluateInteger(SubExpr, IntResult, Info) && 14320 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 14321 IntResult, E->getType(), Result); 14322 } 14323 14324 case CK_FixedPointToFloating: { 14325 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 14326 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 14327 return false; 14328 Result = 14329 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 14330 return true; 14331 } 14332 14333 case CK_FloatingCast: { 14334 if (!Visit(SubExpr)) 14335 return false; 14336 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 14337 Result); 14338 } 14339 14340 case CK_FloatingComplexToReal: { 14341 ComplexValue V; 14342 if (!EvaluateComplex(SubExpr, V, Info)) 14343 return false; 14344 Result = V.getComplexFloatReal(); 14345 return true; 14346 } 14347 } 14348 } 14349 14350 //===----------------------------------------------------------------------===// 14351 // Complex Evaluation (for float and integer) 14352 //===----------------------------------------------------------------------===// 14353 14354 namespace { 14355 class ComplexExprEvaluator 14356 : public ExprEvaluatorBase<ComplexExprEvaluator> { 14357 ComplexValue &Result; 14358 14359 public: 14360 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 14361 : ExprEvaluatorBaseTy(info), Result(Result) {} 14362 14363 bool Success(const APValue &V, const Expr *e) { 14364 Result.setFrom(V); 14365 return true; 14366 } 14367 14368 bool ZeroInitialization(const Expr *E); 14369 14370 //===--------------------------------------------------------------------===// 14371 // Visitor Methods 14372 //===--------------------------------------------------------------------===// 14373 14374 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 14375 bool VisitCastExpr(const CastExpr *E); 14376 bool VisitBinaryOperator(const BinaryOperator *E); 14377 bool VisitUnaryOperator(const UnaryOperator *E); 14378 bool VisitInitListExpr(const InitListExpr *E); 14379 bool VisitCallExpr(const CallExpr *E); 14380 }; 14381 } // end anonymous namespace 14382 14383 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 14384 EvalInfo &Info) { 14385 assert(!E->isValueDependent()); 14386 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 14387 return ComplexExprEvaluator(Info, Result).Visit(E); 14388 } 14389 14390 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 14391 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 14392 if (ElemTy->isRealFloatingType()) { 14393 Result.makeComplexFloat(); 14394 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 14395 Result.FloatReal = Zero; 14396 Result.FloatImag = Zero; 14397 } else { 14398 Result.makeComplexInt(); 14399 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 14400 Result.IntReal = Zero; 14401 Result.IntImag = Zero; 14402 } 14403 return true; 14404 } 14405 14406 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 14407 const Expr* SubExpr = E->getSubExpr(); 14408 14409 if (SubExpr->getType()->isRealFloatingType()) { 14410 Result.makeComplexFloat(); 14411 APFloat &Imag = Result.FloatImag; 14412 if (!EvaluateFloat(SubExpr, Imag, Info)) 14413 return false; 14414 14415 Result.FloatReal = APFloat(Imag.getSemantics()); 14416 return true; 14417 } else { 14418 assert(SubExpr->getType()->isIntegerType() && 14419 "Unexpected imaginary literal."); 14420 14421 Result.makeComplexInt(); 14422 APSInt &Imag = Result.IntImag; 14423 if (!EvaluateInteger(SubExpr, Imag, Info)) 14424 return false; 14425 14426 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 14427 return true; 14428 } 14429 } 14430 14431 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 14432 14433 switch (E->getCastKind()) { 14434 case CK_BitCast: 14435 case CK_BaseToDerived: 14436 case CK_DerivedToBase: 14437 case CK_UncheckedDerivedToBase: 14438 case CK_Dynamic: 14439 case CK_ToUnion: 14440 case CK_ArrayToPointerDecay: 14441 case CK_FunctionToPointerDecay: 14442 case CK_NullToPointer: 14443 case CK_NullToMemberPointer: 14444 case CK_BaseToDerivedMemberPointer: 14445 case CK_DerivedToBaseMemberPointer: 14446 case CK_MemberPointerToBoolean: 14447 case CK_ReinterpretMemberPointer: 14448 case CK_ConstructorConversion: 14449 case CK_IntegralToPointer: 14450 case CK_PointerToIntegral: 14451 case CK_PointerToBoolean: 14452 case CK_ToVoid: 14453 case CK_VectorSplat: 14454 case CK_IntegralCast: 14455 case CK_BooleanToSignedIntegral: 14456 case CK_IntegralToBoolean: 14457 case CK_IntegralToFloating: 14458 case CK_FloatingToIntegral: 14459 case CK_FloatingToBoolean: 14460 case CK_FloatingCast: 14461 case CK_CPointerToObjCPointerCast: 14462 case CK_BlockPointerToObjCPointerCast: 14463 case CK_AnyPointerToBlockPointerCast: 14464 case CK_ObjCObjectLValueCast: 14465 case CK_FloatingComplexToReal: 14466 case CK_FloatingComplexToBoolean: 14467 case CK_IntegralComplexToReal: 14468 case CK_IntegralComplexToBoolean: 14469 case CK_ARCProduceObject: 14470 case CK_ARCConsumeObject: 14471 case CK_ARCReclaimReturnedObject: 14472 case CK_ARCExtendBlockObject: 14473 case CK_CopyAndAutoreleaseBlockObject: 14474 case CK_BuiltinFnToFnPtr: 14475 case CK_ZeroToOCLOpaqueType: 14476 case CK_NonAtomicToAtomic: 14477 case CK_AddressSpaceConversion: 14478 case CK_IntToOCLSampler: 14479 case CK_FloatingToFixedPoint: 14480 case CK_FixedPointToFloating: 14481 case CK_FixedPointCast: 14482 case CK_FixedPointToBoolean: 14483 case CK_FixedPointToIntegral: 14484 case CK_IntegralToFixedPoint: 14485 case CK_MatrixCast: 14486 llvm_unreachable("invalid cast kind for complex value"); 14487 14488 case CK_LValueToRValue: 14489 case CK_AtomicToNonAtomic: 14490 case CK_NoOp: 14491 case CK_LValueToRValueBitCast: 14492 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14493 14494 case CK_Dependent: 14495 case CK_LValueBitCast: 14496 case CK_UserDefinedConversion: 14497 return Error(E); 14498 14499 case CK_FloatingRealToComplex: { 14500 APFloat &Real = Result.FloatReal; 14501 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 14502 return false; 14503 14504 Result.makeComplexFloat(); 14505 Result.FloatImag = APFloat(Real.getSemantics()); 14506 return true; 14507 } 14508 14509 case CK_FloatingComplexCast: { 14510 if (!Visit(E->getSubExpr())) 14511 return false; 14512 14513 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14514 QualType From 14515 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14516 14517 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 14518 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 14519 } 14520 14521 case CK_FloatingComplexToIntegralComplex: { 14522 if (!Visit(E->getSubExpr())) 14523 return false; 14524 14525 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14526 QualType From 14527 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14528 Result.makeComplexInt(); 14529 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 14530 To, Result.IntReal) && 14531 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 14532 To, Result.IntImag); 14533 } 14534 14535 case CK_IntegralRealToComplex: { 14536 APSInt &Real = Result.IntReal; 14537 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14538 return false; 14539 14540 Result.makeComplexInt(); 14541 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14542 return true; 14543 } 14544 14545 case CK_IntegralComplexCast: { 14546 if (!Visit(E->getSubExpr())) 14547 return false; 14548 14549 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14550 QualType From 14551 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14552 14553 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14554 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14555 return true; 14556 } 14557 14558 case CK_IntegralComplexToFloatingComplex: { 14559 if (!Visit(E->getSubExpr())) 14560 return false; 14561 14562 const FPOptions FPO = E->getFPFeaturesInEffect( 14563 Info.Ctx.getLangOpts()); 14564 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14565 QualType From 14566 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14567 Result.makeComplexFloat(); 14568 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14569 To, Result.FloatReal) && 14570 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14571 To, Result.FloatImag); 14572 } 14573 } 14574 14575 llvm_unreachable("unknown cast resulting in complex value"); 14576 } 14577 14578 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14579 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14580 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14581 14582 // Track whether the LHS or RHS is real at the type system level. When this is 14583 // the case we can simplify our evaluation strategy. 14584 bool LHSReal = false, RHSReal = false; 14585 14586 bool LHSOK; 14587 if (E->getLHS()->getType()->isRealFloatingType()) { 14588 LHSReal = true; 14589 APFloat &Real = Result.FloatReal; 14590 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14591 if (LHSOK) { 14592 Result.makeComplexFloat(); 14593 Result.FloatImag = APFloat(Real.getSemantics()); 14594 } 14595 } else { 14596 LHSOK = Visit(E->getLHS()); 14597 } 14598 if (!LHSOK && !Info.noteFailure()) 14599 return false; 14600 14601 ComplexValue RHS; 14602 if (E->getRHS()->getType()->isRealFloatingType()) { 14603 RHSReal = true; 14604 APFloat &Real = RHS.FloatReal; 14605 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14606 return false; 14607 RHS.makeComplexFloat(); 14608 RHS.FloatImag = APFloat(Real.getSemantics()); 14609 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14610 return false; 14611 14612 assert(!(LHSReal && RHSReal) && 14613 "Cannot have both operands of a complex operation be real."); 14614 switch (E->getOpcode()) { 14615 default: return Error(E); 14616 case BO_Add: 14617 if (Result.isComplexFloat()) { 14618 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14619 APFloat::rmNearestTiesToEven); 14620 if (LHSReal) 14621 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14622 else if (!RHSReal) 14623 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14624 APFloat::rmNearestTiesToEven); 14625 } else { 14626 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14627 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14628 } 14629 break; 14630 case BO_Sub: 14631 if (Result.isComplexFloat()) { 14632 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14633 APFloat::rmNearestTiesToEven); 14634 if (LHSReal) { 14635 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14636 Result.getComplexFloatImag().changeSign(); 14637 } else if (!RHSReal) { 14638 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14639 APFloat::rmNearestTiesToEven); 14640 } 14641 } else { 14642 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14643 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14644 } 14645 break; 14646 case BO_Mul: 14647 if (Result.isComplexFloat()) { 14648 // This is an implementation of complex multiplication according to the 14649 // constraints laid out in C11 Annex G. The implementation uses the 14650 // following naming scheme: 14651 // (a + ib) * (c + id) 14652 ComplexValue LHS = Result; 14653 APFloat &A = LHS.getComplexFloatReal(); 14654 APFloat &B = LHS.getComplexFloatImag(); 14655 APFloat &C = RHS.getComplexFloatReal(); 14656 APFloat &D = RHS.getComplexFloatImag(); 14657 APFloat &ResR = Result.getComplexFloatReal(); 14658 APFloat &ResI = Result.getComplexFloatImag(); 14659 if (LHSReal) { 14660 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14661 ResR = A * C; 14662 ResI = A * D; 14663 } else if (RHSReal) { 14664 ResR = C * A; 14665 ResI = C * B; 14666 } else { 14667 // In the fully general case, we need to handle NaNs and infinities 14668 // robustly. 14669 APFloat AC = A * C; 14670 APFloat BD = B * D; 14671 APFloat AD = A * D; 14672 APFloat BC = B * C; 14673 ResR = AC - BD; 14674 ResI = AD + BC; 14675 if (ResR.isNaN() && ResI.isNaN()) { 14676 bool Recalc = false; 14677 if (A.isInfinity() || B.isInfinity()) { 14678 A = APFloat::copySign( 14679 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14680 B = APFloat::copySign( 14681 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14682 if (C.isNaN()) 14683 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14684 if (D.isNaN()) 14685 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14686 Recalc = true; 14687 } 14688 if (C.isInfinity() || D.isInfinity()) { 14689 C = APFloat::copySign( 14690 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14691 D = APFloat::copySign( 14692 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14693 if (A.isNaN()) 14694 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14695 if (B.isNaN()) 14696 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14697 Recalc = true; 14698 } 14699 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14700 AD.isInfinity() || BC.isInfinity())) { 14701 if (A.isNaN()) 14702 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14703 if (B.isNaN()) 14704 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14705 if (C.isNaN()) 14706 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14707 if (D.isNaN()) 14708 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14709 Recalc = true; 14710 } 14711 if (Recalc) { 14712 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14713 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14714 } 14715 } 14716 } 14717 } else { 14718 ComplexValue LHS = Result; 14719 Result.getComplexIntReal() = 14720 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14721 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14722 Result.getComplexIntImag() = 14723 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14724 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14725 } 14726 break; 14727 case BO_Div: 14728 if (Result.isComplexFloat()) { 14729 // This is an implementation of complex division according to the 14730 // constraints laid out in C11 Annex G. The implementation uses the 14731 // following naming scheme: 14732 // (a + ib) / (c + id) 14733 ComplexValue LHS = Result; 14734 APFloat &A = LHS.getComplexFloatReal(); 14735 APFloat &B = LHS.getComplexFloatImag(); 14736 APFloat &C = RHS.getComplexFloatReal(); 14737 APFloat &D = RHS.getComplexFloatImag(); 14738 APFloat &ResR = Result.getComplexFloatReal(); 14739 APFloat &ResI = Result.getComplexFloatImag(); 14740 if (RHSReal) { 14741 ResR = A / C; 14742 ResI = B / C; 14743 } else { 14744 if (LHSReal) { 14745 // No real optimizations we can do here, stub out with zero. 14746 B = APFloat::getZero(A.getSemantics()); 14747 } 14748 int DenomLogB = 0; 14749 APFloat MaxCD = maxnum(abs(C), abs(D)); 14750 if (MaxCD.isFinite()) { 14751 DenomLogB = ilogb(MaxCD); 14752 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14753 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14754 } 14755 APFloat Denom = C * C + D * D; 14756 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14757 APFloat::rmNearestTiesToEven); 14758 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14759 APFloat::rmNearestTiesToEven); 14760 if (ResR.isNaN() && ResI.isNaN()) { 14761 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14762 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14763 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14764 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14765 D.isFinite()) { 14766 A = APFloat::copySign( 14767 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14768 B = APFloat::copySign( 14769 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14770 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14771 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14772 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14773 C = APFloat::copySign( 14774 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14775 D = APFloat::copySign( 14776 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14777 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14778 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14779 } 14780 } 14781 } 14782 } else { 14783 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14784 return Error(E, diag::note_expr_divide_by_zero); 14785 14786 ComplexValue LHS = Result; 14787 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14788 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14789 Result.getComplexIntReal() = 14790 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14791 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14792 Result.getComplexIntImag() = 14793 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14794 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14795 } 14796 break; 14797 } 14798 14799 return true; 14800 } 14801 14802 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14803 // Get the operand value into 'Result'. 14804 if (!Visit(E->getSubExpr())) 14805 return false; 14806 14807 switch (E->getOpcode()) { 14808 default: 14809 return Error(E); 14810 case UO_Extension: 14811 return true; 14812 case UO_Plus: 14813 // The result is always just the subexpr. 14814 return true; 14815 case UO_Minus: 14816 if (Result.isComplexFloat()) { 14817 Result.getComplexFloatReal().changeSign(); 14818 Result.getComplexFloatImag().changeSign(); 14819 } 14820 else { 14821 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14822 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14823 } 14824 return true; 14825 case UO_Not: 14826 if (Result.isComplexFloat()) 14827 Result.getComplexFloatImag().changeSign(); 14828 else 14829 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14830 return true; 14831 } 14832 } 14833 14834 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14835 if (E->getNumInits() == 2) { 14836 if (E->getType()->isComplexType()) { 14837 Result.makeComplexFloat(); 14838 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14839 return false; 14840 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14841 return false; 14842 } else { 14843 Result.makeComplexInt(); 14844 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14845 return false; 14846 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14847 return false; 14848 } 14849 return true; 14850 } 14851 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14852 } 14853 14854 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14855 if (!IsConstantEvaluatedBuiltinCall(E)) 14856 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14857 14858 switch (E->getBuiltinCallee()) { 14859 case Builtin::BI__builtin_complex: 14860 Result.makeComplexFloat(); 14861 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14862 return false; 14863 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14864 return false; 14865 return true; 14866 14867 default: 14868 return false; 14869 } 14870 } 14871 14872 //===----------------------------------------------------------------------===// 14873 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14874 // implicit conversion. 14875 //===----------------------------------------------------------------------===// 14876 14877 namespace { 14878 class AtomicExprEvaluator : 14879 public ExprEvaluatorBase<AtomicExprEvaluator> { 14880 const LValue *This; 14881 APValue &Result; 14882 public: 14883 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14884 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14885 14886 bool Success(const APValue &V, const Expr *E) { 14887 Result = V; 14888 return true; 14889 } 14890 14891 bool ZeroInitialization(const Expr *E) { 14892 ImplicitValueInitExpr VIE( 14893 E->getType()->castAs<AtomicType>()->getValueType()); 14894 // For atomic-qualified class (and array) types in C++, initialize the 14895 // _Atomic-wrapped subobject directly, in-place. 14896 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14897 : Evaluate(Result, Info, &VIE); 14898 } 14899 14900 bool VisitCastExpr(const CastExpr *E) { 14901 switch (E->getCastKind()) { 14902 default: 14903 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14904 case CK_NullToPointer: 14905 VisitIgnoredValue(E->getSubExpr()); 14906 return ZeroInitialization(E); 14907 case CK_NonAtomicToAtomic: 14908 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14909 : Evaluate(Result, Info, E->getSubExpr()); 14910 } 14911 } 14912 }; 14913 } // end anonymous namespace 14914 14915 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14916 EvalInfo &Info) { 14917 assert(!E->isValueDependent()); 14918 assert(E->isPRValue() && E->getType()->isAtomicType()); 14919 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14920 } 14921 14922 //===----------------------------------------------------------------------===// 14923 // Void expression evaluation, primarily for a cast to void on the LHS of a 14924 // comma operator 14925 //===----------------------------------------------------------------------===// 14926 14927 namespace { 14928 class VoidExprEvaluator 14929 : public ExprEvaluatorBase<VoidExprEvaluator> { 14930 public: 14931 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14932 14933 bool Success(const APValue &V, const Expr *e) { return true; } 14934 14935 bool ZeroInitialization(const Expr *E) { return true; } 14936 14937 bool VisitCastExpr(const CastExpr *E) { 14938 switch (E->getCastKind()) { 14939 default: 14940 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14941 case CK_ToVoid: 14942 VisitIgnoredValue(E->getSubExpr()); 14943 return true; 14944 } 14945 } 14946 14947 bool VisitCallExpr(const CallExpr *E) { 14948 if (!IsConstantEvaluatedBuiltinCall(E)) 14949 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14950 14951 switch (E->getBuiltinCallee()) { 14952 case Builtin::BI__assume: 14953 case Builtin::BI__builtin_assume: 14954 // The argument is not evaluated! 14955 return true; 14956 14957 case Builtin::BI__builtin_operator_delete: 14958 return HandleOperatorDeleteCall(Info, E); 14959 14960 default: 14961 return false; 14962 } 14963 } 14964 14965 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14966 }; 14967 } // end anonymous namespace 14968 14969 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14970 // We cannot speculatively evaluate a delete expression. 14971 if (Info.SpeculativeEvaluationDepth) 14972 return false; 14973 14974 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14975 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14976 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14977 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14978 return false; 14979 } 14980 14981 const Expr *Arg = E->getArgument(); 14982 14983 LValue Pointer; 14984 if (!EvaluatePointer(Arg, Pointer, Info)) 14985 return false; 14986 if (Pointer.Designator.Invalid) 14987 return false; 14988 14989 // Deleting a null pointer has no effect. 14990 if (Pointer.isNullPointer()) { 14991 // This is the only case where we need to produce an extension warning: 14992 // the only other way we can succeed is if we find a dynamic allocation, 14993 // and we will have warned when we allocated it in that case. 14994 if (!Info.getLangOpts().CPlusPlus20) 14995 Info.CCEDiag(E, diag::note_constexpr_new); 14996 return true; 14997 } 14998 14999 std::optional<DynAlloc *> Alloc = CheckDeleteKind( 15000 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 15001 if (!Alloc) 15002 return false; 15003 QualType AllocType = Pointer.Base.getDynamicAllocType(); 15004 15005 // For the non-array case, the designator must be empty if the static type 15006 // does not have a virtual destructor. 15007 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 15008 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 15009 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 15010 << Arg->getType()->getPointeeType() << AllocType; 15011 return false; 15012 } 15013 15014 // For a class type with a virtual destructor, the selected operator delete 15015 // is the one looked up when building the destructor. 15016 if (!E->isArrayForm() && !E->isGlobalDelete()) { 15017 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 15018 if (VirtualDelete && 15019 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 15020 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 15021 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 15022 return false; 15023 } 15024 } 15025 15026 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 15027 (*Alloc)->Value, AllocType)) 15028 return false; 15029 15030 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 15031 // The element was already erased. This means the destructor call also 15032 // deleted the object. 15033 // FIXME: This probably results in undefined behavior before we get this 15034 // far, and should be diagnosed elsewhere first. 15035 Info.FFDiag(E, diag::note_constexpr_double_delete); 15036 return false; 15037 } 15038 15039 return true; 15040 } 15041 15042 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 15043 assert(!E->isValueDependent()); 15044 assert(E->isPRValue() && E->getType()->isVoidType()); 15045 return VoidExprEvaluator(Info).Visit(E); 15046 } 15047 15048 //===----------------------------------------------------------------------===// 15049 // Top level Expr::EvaluateAsRValue method. 15050 //===----------------------------------------------------------------------===// 15051 15052 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 15053 assert(!E->isValueDependent()); 15054 // In C, function designators are not lvalues, but we evaluate them as if they 15055 // are. 15056 QualType T = E->getType(); 15057 if (E->isGLValue() || T->isFunctionType()) { 15058 LValue LV; 15059 if (!EvaluateLValue(E, LV, Info)) 15060 return false; 15061 LV.moveInto(Result); 15062 } else if (T->isVectorType()) { 15063 if (!EvaluateVector(E, Result, Info)) 15064 return false; 15065 } else if (T->isIntegralOrEnumerationType()) { 15066 if (!IntExprEvaluator(Info, Result).Visit(E)) 15067 return false; 15068 } else if (T->hasPointerRepresentation()) { 15069 LValue LV; 15070 if (!EvaluatePointer(E, LV, Info)) 15071 return false; 15072 LV.moveInto(Result); 15073 } else if (T->isRealFloatingType()) { 15074 llvm::APFloat F(0.0); 15075 if (!EvaluateFloat(E, F, Info)) 15076 return false; 15077 Result = APValue(F); 15078 } else if (T->isAnyComplexType()) { 15079 ComplexValue C; 15080 if (!EvaluateComplex(E, C, Info)) 15081 return false; 15082 C.moveInto(Result); 15083 } else if (T->isFixedPointType()) { 15084 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 15085 } else if (T->isMemberPointerType()) { 15086 MemberPtr P; 15087 if (!EvaluateMemberPointer(E, P, Info)) 15088 return false; 15089 P.moveInto(Result); 15090 return true; 15091 } else if (T->isArrayType()) { 15092 LValue LV; 15093 APValue &Value = 15094 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 15095 if (!EvaluateArray(E, LV, Value, Info)) 15096 return false; 15097 Result = Value; 15098 } else if (T->isRecordType()) { 15099 LValue LV; 15100 APValue &Value = 15101 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 15102 if (!EvaluateRecord(E, LV, Value, Info)) 15103 return false; 15104 Result = Value; 15105 } else if (T->isVoidType()) { 15106 if (!Info.getLangOpts().CPlusPlus11) 15107 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 15108 << E->getType(); 15109 if (!EvaluateVoid(E, Info)) 15110 return false; 15111 } else if (T->isAtomicType()) { 15112 QualType Unqual = T.getAtomicUnqualifiedType(); 15113 if (Unqual->isArrayType() || Unqual->isRecordType()) { 15114 LValue LV; 15115 APValue &Value = Info.CurrentCall->createTemporary( 15116 E, Unqual, ScopeKind::FullExpression, LV); 15117 if (!EvaluateAtomic(E, &LV, Value, Info)) 15118 return false; 15119 Result = Value; 15120 } else { 15121 if (!EvaluateAtomic(E, nullptr, Result, Info)) 15122 return false; 15123 } 15124 } else if (Info.getLangOpts().CPlusPlus11) { 15125 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 15126 return false; 15127 } else { 15128 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 15129 return false; 15130 } 15131 15132 return true; 15133 } 15134 15135 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 15136 /// cases, the in-place evaluation is essential, since later initializers for 15137 /// an object can indirectly refer to subobjects which were initialized earlier. 15138 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 15139 const Expr *E, bool AllowNonLiteralTypes) { 15140 assert(!E->isValueDependent()); 15141 15142 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 15143 return false; 15144 15145 if (E->isPRValue()) { 15146 // Evaluate arrays and record types in-place, so that later initializers can 15147 // refer to earlier-initialized members of the object. 15148 QualType T = E->getType(); 15149 if (T->isArrayType()) 15150 return EvaluateArray(E, This, Result, Info); 15151 else if (T->isRecordType()) 15152 return EvaluateRecord(E, This, Result, Info); 15153 else if (T->isAtomicType()) { 15154 QualType Unqual = T.getAtomicUnqualifiedType(); 15155 if (Unqual->isArrayType() || Unqual->isRecordType()) 15156 return EvaluateAtomic(E, &This, Result, Info); 15157 } 15158 } 15159 15160 // For any other type, in-place evaluation is unimportant. 15161 return Evaluate(Result, Info, E); 15162 } 15163 15164 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 15165 /// lvalue-to-rvalue cast if it is an lvalue. 15166 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 15167 assert(!E->isValueDependent()); 15168 15169 if (E->getType().isNull()) 15170 return false; 15171 15172 if (!CheckLiteralType(Info, E)) 15173 return false; 15174 15175 if (Info.EnableNewConstInterp) { 15176 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 15177 return false; 15178 } else { 15179 if (!::Evaluate(Result, Info, E)) 15180 return false; 15181 } 15182 15183 // Implicit lvalue-to-rvalue cast. 15184 if (E->isGLValue()) { 15185 LValue LV; 15186 LV.setFrom(Info.Ctx, Result); 15187 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 15188 return false; 15189 } 15190 15191 // Check this core constant expression is a constant expression. 15192 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 15193 ConstantExprKind::Normal) && 15194 CheckMemoryLeaks(Info); 15195 } 15196 15197 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 15198 const ASTContext &Ctx, bool &IsConst) { 15199 // Fast-path evaluations of integer literals, since we sometimes see files 15200 // containing vast quantities of these. 15201 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 15202 Result.Val = APValue(APSInt(L->getValue(), 15203 L->getType()->isUnsignedIntegerType())); 15204 IsConst = true; 15205 return true; 15206 } 15207 15208 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) { 15209 Result.Val = APValue(APSInt(APInt(1, L->getValue()))); 15210 IsConst = true; 15211 return true; 15212 } 15213 15214 // This case should be rare, but we need to check it before we check on 15215 // the type below. 15216 if (Exp->getType().isNull()) { 15217 IsConst = false; 15218 return true; 15219 } 15220 15221 // FIXME: Evaluating values of large array and record types can cause 15222 // performance problems. Only do so in C++11 for now. 15223 if (Exp->isPRValue() && 15224 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && 15225 !Ctx.getLangOpts().CPlusPlus11) { 15226 IsConst = false; 15227 return true; 15228 } 15229 return false; 15230 } 15231 15232 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 15233 Expr::SideEffectsKind SEK) { 15234 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 15235 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 15236 } 15237 15238 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 15239 const ASTContext &Ctx, EvalInfo &Info) { 15240 assert(!E->isValueDependent()); 15241 bool IsConst; 15242 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 15243 return IsConst; 15244 15245 return EvaluateAsRValue(Info, E, Result.Val); 15246 } 15247 15248 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 15249 const ASTContext &Ctx, 15250 Expr::SideEffectsKind AllowSideEffects, 15251 EvalInfo &Info) { 15252 assert(!E->isValueDependent()); 15253 if (!E->getType()->isIntegralOrEnumerationType()) 15254 return false; 15255 15256 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 15257 !ExprResult.Val.isInt() || 15258 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15259 return false; 15260 15261 return true; 15262 } 15263 15264 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 15265 const ASTContext &Ctx, 15266 Expr::SideEffectsKind AllowSideEffects, 15267 EvalInfo &Info) { 15268 assert(!E->isValueDependent()); 15269 if (!E->getType()->isFixedPointType()) 15270 return false; 15271 15272 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 15273 return false; 15274 15275 if (!ExprResult.Val.isFixedPoint() || 15276 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15277 return false; 15278 15279 return true; 15280 } 15281 15282 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 15283 /// any crazy technique (that has nothing to do with language standards) that 15284 /// we want to. If this function returns true, it returns the folded constant 15285 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 15286 /// will be applied to the result. 15287 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 15288 bool InConstantContext) const { 15289 assert(!isValueDependent() && 15290 "Expression evaluator can't be called on a dependent expression."); 15291 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue"); 15292 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15293 Info.InConstantContext = InConstantContext; 15294 return ::EvaluateAsRValue(this, Result, Ctx, Info); 15295 } 15296 15297 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 15298 bool InConstantContext) const { 15299 assert(!isValueDependent() && 15300 "Expression evaluator can't be called on a dependent expression."); 15301 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition"); 15302 EvalResult Scratch; 15303 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 15304 HandleConversionToBool(Scratch.Val, Result); 15305 } 15306 15307 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 15308 SideEffectsKind AllowSideEffects, 15309 bool InConstantContext) const { 15310 assert(!isValueDependent() && 15311 "Expression evaluator can't be called on a dependent expression."); 15312 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt"); 15313 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15314 Info.InConstantContext = InConstantContext; 15315 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 15316 } 15317 15318 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 15319 SideEffectsKind AllowSideEffects, 15320 bool InConstantContext) const { 15321 assert(!isValueDependent() && 15322 "Expression evaluator can't be called on a dependent expression."); 15323 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint"); 15324 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15325 Info.InConstantContext = InConstantContext; 15326 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 15327 } 15328 15329 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 15330 SideEffectsKind AllowSideEffects, 15331 bool InConstantContext) const { 15332 assert(!isValueDependent() && 15333 "Expression evaluator can't be called on a dependent expression."); 15334 15335 if (!getType()->isRealFloatingType()) 15336 return false; 15337 15338 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat"); 15339 EvalResult ExprResult; 15340 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 15341 !ExprResult.Val.isFloat() || 15342 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15343 return false; 15344 15345 Result = ExprResult.Val.getFloat(); 15346 return true; 15347 } 15348 15349 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 15350 bool InConstantContext) const { 15351 assert(!isValueDependent() && 15352 "Expression evaluator can't be called on a dependent expression."); 15353 15354 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue"); 15355 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 15356 Info.InConstantContext = InConstantContext; 15357 LValue LV; 15358 CheckedTemporaries CheckedTemps; 15359 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 15360 Result.HasSideEffects || 15361 !CheckLValueConstantExpression(Info, getExprLoc(), 15362 Ctx.getLValueReferenceType(getType()), LV, 15363 ConstantExprKind::Normal, CheckedTemps)) 15364 return false; 15365 15366 LV.moveInto(Result.Val); 15367 return true; 15368 } 15369 15370 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 15371 APValue DestroyedValue, QualType Type, 15372 SourceLocation Loc, Expr::EvalStatus &EStatus, 15373 bool IsConstantDestruction) { 15374 EvalInfo Info(Ctx, EStatus, 15375 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 15376 : EvalInfo::EM_ConstantFold); 15377 Info.setEvaluatingDecl(Base, DestroyedValue, 15378 EvalInfo::EvaluatingDeclKind::Dtor); 15379 Info.InConstantContext = IsConstantDestruction; 15380 15381 LValue LVal; 15382 LVal.set(Base); 15383 15384 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 15385 EStatus.HasSideEffects) 15386 return false; 15387 15388 if (!Info.discardCleanups()) 15389 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15390 15391 return true; 15392 } 15393 15394 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 15395 ConstantExprKind Kind) const { 15396 assert(!isValueDependent() && 15397 "Expression evaluator can't be called on a dependent expression."); 15398 bool IsConst; 15399 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue()) 15400 return true; 15401 15402 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr"); 15403 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 15404 EvalInfo Info(Ctx, Result, EM); 15405 Info.InConstantContext = true; 15406 15407 // The type of the object we're initializing is 'const T' for a class NTTP. 15408 QualType T = getType(); 15409 if (Kind == ConstantExprKind::ClassTemplateArgument) 15410 T.addConst(); 15411 15412 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 15413 // represent the result of the evaluation. CheckConstantExpression ensures 15414 // this doesn't escape. 15415 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 15416 APValue::LValueBase Base(&BaseMTE); 15417 15418 Info.setEvaluatingDecl(Base, Result.Val); 15419 LValue LVal; 15420 LVal.set(Base); 15421 15422 { 15423 // C++23 [intro.execution]/p5 15424 // A full-expression is [...] a constant-expression 15425 // So we need to make sure temporary objects are destroyed after having 15426 // evaluating the expression (per C++23 [class.temporary]/p4). 15427 FullExpressionRAII Scope(Info); 15428 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 15429 Result.HasSideEffects || !Scope.destroy()) 15430 return false; 15431 } 15432 15433 if (!Info.discardCleanups()) 15434 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15435 15436 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 15437 Result.Val, Kind)) 15438 return false; 15439 if (!CheckMemoryLeaks(Info)) 15440 return false; 15441 15442 // If this is a class template argument, it's required to have constant 15443 // destruction too. 15444 if (Kind == ConstantExprKind::ClassTemplateArgument && 15445 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 15446 true) || 15447 Result.HasSideEffects)) { 15448 // FIXME: Prefix a note to indicate that the problem is lack of constant 15449 // destruction. 15450 return false; 15451 } 15452 15453 return true; 15454 } 15455 15456 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 15457 const VarDecl *VD, 15458 SmallVectorImpl<PartialDiagnosticAt> &Notes, 15459 bool IsConstantInitialization) const { 15460 assert(!isValueDependent() && 15461 "Expression evaluator can't be called on a dependent expression."); 15462 15463 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] { 15464 std::string Name; 15465 llvm::raw_string_ostream OS(Name); 15466 VD->printQualifiedName(OS); 15467 return Name; 15468 }); 15469 15470 // FIXME: Evaluating initializers for large array and record types can cause 15471 // performance problems. Only do so in C++11 for now. 15472 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 15473 !Ctx.getLangOpts().CPlusPlus11) 15474 return false; 15475 15476 Expr::EvalStatus EStatus; 15477 EStatus.Diag = &Notes; 15478 15479 EvalInfo Info(Ctx, EStatus, 15480 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus) 15481 ? EvalInfo::EM_ConstantExpression 15482 : EvalInfo::EM_ConstantFold); 15483 Info.setEvaluatingDecl(VD, Value); 15484 Info.InConstantContext = IsConstantInitialization; 15485 15486 if (Info.EnableNewConstInterp) { 15487 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 15488 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 15489 return false; 15490 } else { 15491 LValue LVal; 15492 LVal.set(VD); 15493 15494 if (!EvaluateInPlace(Value, Info, LVal, this, 15495 /*AllowNonLiteralTypes=*/true) || 15496 EStatus.HasSideEffects) 15497 return false; 15498 15499 // At this point, any lifetime-extended temporaries are completely 15500 // initialized. 15501 Info.performLifetimeExtension(); 15502 15503 if (!Info.discardCleanups()) 15504 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15505 } 15506 15507 SourceLocation DeclLoc = VD->getLocation(); 15508 QualType DeclTy = VD->getType(); 15509 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 15510 ConstantExprKind::Normal) && 15511 CheckMemoryLeaks(Info); 15512 } 15513 15514 bool VarDecl::evaluateDestruction( 15515 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15516 Expr::EvalStatus EStatus; 15517 EStatus.Diag = &Notes; 15518 15519 // Only treat the destruction as constant destruction if we formally have 15520 // constant initialization (or are usable in a constant expression). 15521 bool IsConstantDestruction = hasConstantInitialization(); 15522 15523 // Make a copy of the value for the destructor to mutate, if we know it. 15524 // Otherwise, treat the value as default-initialized; if the destructor works 15525 // anyway, then the destruction is constant (and must be essentially empty). 15526 APValue DestroyedValue; 15527 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 15528 DestroyedValue = *getEvaluatedValue(); 15529 else if (!getDefaultInitValue(getType(), DestroyedValue)) 15530 return false; 15531 15532 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 15533 getType(), getLocation(), EStatus, 15534 IsConstantDestruction) || 15535 EStatus.HasSideEffects) 15536 return false; 15537 15538 ensureEvaluatedStmt()->HasConstantDestruction = true; 15539 return true; 15540 } 15541 15542 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 15543 /// constant folded, but discard the result. 15544 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 15545 assert(!isValueDependent() && 15546 "Expression evaluator can't be called on a dependent expression."); 15547 15548 EvalResult Result; 15549 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 15550 !hasUnacceptableSideEffect(Result, SEK); 15551 } 15552 15553 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 15554 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15555 assert(!isValueDependent() && 15556 "Expression evaluator can't be called on a dependent expression."); 15557 15558 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt"); 15559 EvalResult EVResult; 15560 EVResult.Diag = Diag; 15561 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15562 Info.InConstantContext = true; 15563 15564 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 15565 (void)Result; 15566 assert(Result && "Could not evaluate expression"); 15567 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15568 15569 return EVResult.Val.getInt(); 15570 } 15571 15572 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 15573 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15574 assert(!isValueDependent() && 15575 "Expression evaluator can't be called on a dependent expression."); 15576 15577 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow"); 15578 EvalResult EVResult; 15579 EVResult.Diag = Diag; 15580 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15581 Info.InConstantContext = true; 15582 Info.CheckingForUndefinedBehavior = true; 15583 15584 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15585 (void)Result; 15586 assert(Result && "Could not evaluate expression"); 15587 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15588 15589 return EVResult.Val.getInt(); 15590 } 15591 15592 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15593 assert(!isValueDependent() && 15594 "Expression evaluator can't be called on a dependent expression."); 15595 15596 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow"); 15597 bool IsConst; 15598 EvalResult EVResult; 15599 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15600 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15601 Info.CheckingForUndefinedBehavior = true; 15602 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15603 } 15604 } 15605 15606 bool Expr::EvalResult::isGlobalLValue() const { 15607 assert(Val.isLValue()); 15608 return IsGlobalLValue(Val.getLValueBase()); 15609 } 15610 15611 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15612 /// an integer constant expression. 15613 15614 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15615 /// comma, etc 15616 15617 // CheckICE - This function does the fundamental ICE checking: the returned 15618 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15619 // and a (possibly null) SourceLocation indicating the location of the problem. 15620 // 15621 // Note that to reduce code duplication, this helper does no evaluation 15622 // itself; the caller checks whether the expression is evaluatable, and 15623 // in the rare cases where CheckICE actually cares about the evaluated 15624 // value, it calls into Evaluate. 15625 15626 namespace { 15627 15628 enum ICEKind { 15629 /// This expression is an ICE. 15630 IK_ICE, 15631 /// This expression is not an ICE, but if it isn't evaluated, it's 15632 /// a legal subexpression for an ICE. This return value is used to handle 15633 /// the comma operator in C99 mode, and non-constant subexpressions. 15634 IK_ICEIfUnevaluated, 15635 /// This expression is not an ICE, and is not a legal subexpression for one. 15636 IK_NotICE 15637 }; 15638 15639 struct ICEDiag { 15640 ICEKind Kind; 15641 SourceLocation Loc; 15642 15643 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15644 }; 15645 15646 } 15647 15648 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15649 15650 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15651 15652 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15653 Expr::EvalResult EVResult; 15654 Expr::EvalStatus Status; 15655 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15656 15657 Info.InConstantContext = true; 15658 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15659 !EVResult.Val.isInt()) 15660 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15661 15662 return NoDiag(); 15663 } 15664 15665 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15666 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15667 if (!E->getType()->isIntegralOrEnumerationType()) 15668 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15669 15670 switch (E->getStmtClass()) { 15671 #define ABSTRACT_STMT(Node) 15672 #define STMT(Node, Base) case Expr::Node##Class: 15673 #define EXPR(Node, Base) 15674 #include "clang/AST/StmtNodes.inc" 15675 case Expr::PredefinedExprClass: 15676 case Expr::FloatingLiteralClass: 15677 case Expr::ImaginaryLiteralClass: 15678 case Expr::StringLiteralClass: 15679 case Expr::ArraySubscriptExprClass: 15680 case Expr::MatrixSubscriptExprClass: 15681 case Expr::OMPArraySectionExprClass: 15682 case Expr::OMPArrayShapingExprClass: 15683 case Expr::OMPIteratorExprClass: 15684 case Expr::MemberExprClass: 15685 case Expr::CompoundAssignOperatorClass: 15686 case Expr::CompoundLiteralExprClass: 15687 case Expr::ExtVectorElementExprClass: 15688 case Expr::DesignatedInitExprClass: 15689 case Expr::ArrayInitLoopExprClass: 15690 case Expr::ArrayInitIndexExprClass: 15691 case Expr::NoInitExprClass: 15692 case Expr::DesignatedInitUpdateExprClass: 15693 case Expr::ImplicitValueInitExprClass: 15694 case Expr::ParenListExprClass: 15695 case Expr::VAArgExprClass: 15696 case Expr::AddrLabelExprClass: 15697 case Expr::StmtExprClass: 15698 case Expr::CXXMemberCallExprClass: 15699 case Expr::CUDAKernelCallExprClass: 15700 case Expr::CXXAddrspaceCastExprClass: 15701 case Expr::CXXDynamicCastExprClass: 15702 case Expr::CXXTypeidExprClass: 15703 case Expr::CXXUuidofExprClass: 15704 case Expr::MSPropertyRefExprClass: 15705 case Expr::MSPropertySubscriptExprClass: 15706 case Expr::CXXNullPtrLiteralExprClass: 15707 case Expr::UserDefinedLiteralClass: 15708 case Expr::CXXThisExprClass: 15709 case Expr::CXXThrowExprClass: 15710 case Expr::CXXNewExprClass: 15711 case Expr::CXXDeleteExprClass: 15712 case Expr::CXXPseudoDestructorExprClass: 15713 case Expr::UnresolvedLookupExprClass: 15714 case Expr::TypoExprClass: 15715 case Expr::RecoveryExprClass: 15716 case Expr::DependentScopeDeclRefExprClass: 15717 case Expr::CXXConstructExprClass: 15718 case Expr::CXXInheritedCtorInitExprClass: 15719 case Expr::CXXStdInitializerListExprClass: 15720 case Expr::CXXBindTemporaryExprClass: 15721 case Expr::ExprWithCleanupsClass: 15722 case Expr::CXXTemporaryObjectExprClass: 15723 case Expr::CXXUnresolvedConstructExprClass: 15724 case Expr::CXXDependentScopeMemberExprClass: 15725 case Expr::UnresolvedMemberExprClass: 15726 case Expr::ObjCStringLiteralClass: 15727 case Expr::ObjCBoxedExprClass: 15728 case Expr::ObjCArrayLiteralClass: 15729 case Expr::ObjCDictionaryLiteralClass: 15730 case Expr::ObjCEncodeExprClass: 15731 case Expr::ObjCMessageExprClass: 15732 case Expr::ObjCSelectorExprClass: 15733 case Expr::ObjCProtocolExprClass: 15734 case Expr::ObjCIvarRefExprClass: 15735 case Expr::ObjCPropertyRefExprClass: 15736 case Expr::ObjCSubscriptRefExprClass: 15737 case Expr::ObjCIsaExprClass: 15738 case Expr::ObjCAvailabilityCheckExprClass: 15739 case Expr::ShuffleVectorExprClass: 15740 case Expr::ConvertVectorExprClass: 15741 case Expr::BlockExprClass: 15742 case Expr::NoStmtClass: 15743 case Expr::OpaqueValueExprClass: 15744 case Expr::PackExpansionExprClass: 15745 case Expr::SubstNonTypeTemplateParmPackExprClass: 15746 case Expr::FunctionParmPackExprClass: 15747 case Expr::AsTypeExprClass: 15748 case Expr::ObjCIndirectCopyRestoreExprClass: 15749 case Expr::MaterializeTemporaryExprClass: 15750 case Expr::PseudoObjectExprClass: 15751 case Expr::AtomicExprClass: 15752 case Expr::LambdaExprClass: 15753 case Expr::CXXFoldExprClass: 15754 case Expr::CoawaitExprClass: 15755 case Expr::DependentCoawaitExprClass: 15756 case Expr::CoyieldExprClass: 15757 case Expr::SYCLUniqueStableNameExprClass: 15758 case Expr::CXXParenListInitExprClass: 15759 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15760 15761 case Expr::InitListExprClass: { 15762 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15763 // form "T x = { a };" is equivalent to "T x = a;". 15764 // Unless we're initializing a reference, T is a scalar as it is known to be 15765 // of integral or enumeration type. 15766 if (E->isPRValue()) 15767 if (cast<InitListExpr>(E)->getNumInits() == 1) 15768 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15769 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15770 } 15771 15772 case Expr::SizeOfPackExprClass: 15773 case Expr::GNUNullExprClass: 15774 case Expr::SourceLocExprClass: 15775 return NoDiag(); 15776 15777 case Expr::SubstNonTypeTemplateParmExprClass: 15778 return 15779 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15780 15781 case Expr::ConstantExprClass: 15782 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15783 15784 case Expr::ParenExprClass: 15785 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15786 case Expr::GenericSelectionExprClass: 15787 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15788 case Expr::IntegerLiteralClass: 15789 case Expr::FixedPointLiteralClass: 15790 case Expr::CharacterLiteralClass: 15791 case Expr::ObjCBoolLiteralExprClass: 15792 case Expr::CXXBoolLiteralExprClass: 15793 case Expr::CXXScalarValueInitExprClass: 15794 case Expr::TypeTraitExprClass: 15795 case Expr::ConceptSpecializationExprClass: 15796 case Expr::RequiresExprClass: 15797 case Expr::ArrayTypeTraitExprClass: 15798 case Expr::ExpressionTraitExprClass: 15799 case Expr::CXXNoexceptExprClass: 15800 return NoDiag(); 15801 case Expr::CallExprClass: 15802 case Expr::CXXOperatorCallExprClass: { 15803 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15804 // constant expressions, but they can never be ICEs because an ICE cannot 15805 // contain an operand of (pointer to) function type. 15806 const CallExpr *CE = cast<CallExpr>(E); 15807 if (CE->getBuiltinCallee()) 15808 return CheckEvalInICE(E, Ctx); 15809 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15810 } 15811 case Expr::CXXRewrittenBinaryOperatorClass: 15812 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15813 Ctx); 15814 case Expr::DeclRefExprClass: { 15815 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15816 if (isa<EnumConstantDecl>(D)) 15817 return NoDiag(); 15818 15819 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15820 // integer variables in constant expressions: 15821 // 15822 // C++ 7.1.5.1p2 15823 // A variable of non-volatile const-qualified integral or enumeration 15824 // type initialized by an ICE can be used in ICEs. 15825 // 15826 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15827 // that mode, use of reference variables should not be allowed. 15828 const VarDecl *VD = dyn_cast<VarDecl>(D); 15829 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15830 !VD->getType()->isReferenceType()) 15831 return NoDiag(); 15832 15833 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15834 } 15835 case Expr::UnaryOperatorClass: { 15836 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15837 switch (Exp->getOpcode()) { 15838 case UO_PostInc: 15839 case UO_PostDec: 15840 case UO_PreInc: 15841 case UO_PreDec: 15842 case UO_AddrOf: 15843 case UO_Deref: 15844 case UO_Coawait: 15845 // C99 6.6/3 allows increment and decrement within unevaluated 15846 // subexpressions of constant expressions, but they can never be ICEs 15847 // because an ICE cannot contain an lvalue operand. 15848 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15849 case UO_Extension: 15850 case UO_LNot: 15851 case UO_Plus: 15852 case UO_Minus: 15853 case UO_Not: 15854 case UO_Real: 15855 case UO_Imag: 15856 return CheckICE(Exp->getSubExpr(), Ctx); 15857 } 15858 llvm_unreachable("invalid unary operator class"); 15859 } 15860 case Expr::OffsetOfExprClass: { 15861 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15862 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15863 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15864 // compliance: we should warn earlier for offsetof expressions with 15865 // array subscripts that aren't ICEs, and if the array subscripts 15866 // are ICEs, the value of the offsetof must be an integer constant. 15867 return CheckEvalInICE(E, Ctx); 15868 } 15869 case Expr::UnaryExprOrTypeTraitExprClass: { 15870 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15871 if ((Exp->getKind() == UETT_SizeOf) && 15872 Exp->getTypeOfArgument()->isVariableArrayType()) 15873 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15874 return NoDiag(); 15875 } 15876 case Expr::BinaryOperatorClass: { 15877 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15878 switch (Exp->getOpcode()) { 15879 case BO_PtrMemD: 15880 case BO_PtrMemI: 15881 case BO_Assign: 15882 case BO_MulAssign: 15883 case BO_DivAssign: 15884 case BO_RemAssign: 15885 case BO_AddAssign: 15886 case BO_SubAssign: 15887 case BO_ShlAssign: 15888 case BO_ShrAssign: 15889 case BO_AndAssign: 15890 case BO_XorAssign: 15891 case BO_OrAssign: 15892 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15893 // constant expressions, but they can never be ICEs because an ICE cannot 15894 // contain an lvalue operand. 15895 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15896 15897 case BO_Mul: 15898 case BO_Div: 15899 case BO_Rem: 15900 case BO_Add: 15901 case BO_Sub: 15902 case BO_Shl: 15903 case BO_Shr: 15904 case BO_LT: 15905 case BO_GT: 15906 case BO_LE: 15907 case BO_GE: 15908 case BO_EQ: 15909 case BO_NE: 15910 case BO_And: 15911 case BO_Xor: 15912 case BO_Or: 15913 case BO_Comma: 15914 case BO_Cmp: { 15915 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15916 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15917 if (Exp->getOpcode() == BO_Div || 15918 Exp->getOpcode() == BO_Rem) { 15919 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15920 // we don't evaluate one. 15921 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15922 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15923 if (REval == 0) 15924 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15925 if (REval.isSigned() && REval.isAllOnes()) { 15926 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15927 if (LEval.isMinSignedValue()) 15928 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15929 } 15930 } 15931 } 15932 if (Exp->getOpcode() == BO_Comma) { 15933 if (Ctx.getLangOpts().C99) { 15934 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15935 // if it isn't evaluated. 15936 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15937 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15938 } else { 15939 // In both C89 and C++, commas in ICEs are illegal. 15940 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15941 } 15942 } 15943 return Worst(LHSResult, RHSResult); 15944 } 15945 case BO_LAnd: 15946 case BO_LOr: { 15947 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15948 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15949 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15950 // Rare case where the RHS has a comma "side-effect"; we need 15951 // to actually check the condition to see whether the side 15952 // with the comma is evaluated. 15953 if ((Exp->getOpcode() == BO_LAnd) != 15954 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15955 return RHSResult; 15956 return NoDiag(); 15957 } 15958 15959 return Worst(LHSResult, RHSResult); 15960 } 15961 } 15962 llvm_unreachable("invalid binary operator kind"); 15963 } 15964 case Expr::ImplicitCastExprClass: 15965 case Expr::CStyleCastExprClass: 15966 case Expr::CXXFunctionalCastExprClass: 15967 case Expr::CXXStaticCastExprClass: 15968 case Expr::CXXReinterpretCastExprClass: 15969 case Expr::CXXConstCastExprClass: 15970 case Expr::ObjCBridgedCastExprClass: { 15971 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15972 if (isa<ExplicitCastExpr>(E)) { 15973 if (const FloatingLiteral *FL 15974 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15975 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15976 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15977 APSInt IgnoredVal(DestWidth, !DestSigned); 15978 bool Ignored; 15979 // If the value does not fit in the destination type, the behavior is 15980 // undefined, so we are not required to treat it as a constant 15981 // expression. 15982 if (FL->getValue().convertToInteger(IgnoredVal, 15983 llvm::APFloat::rmTowardZero, 15984 &Ignored) & APFloat::opInvalidOp) 15985 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15986 return NoDiag(); 15987 } 15988 } 15989 switch (cast<CastExpr>(E)->getCastKind()) { 15990 case CK_LValueToRValue: 15991 case CK_AtomicToNonAtomic: 15992 case CK_NonAtomicToAtomic: 15993 case CK_NoOp: 15994 case CK_IntegralToBoolean: 15995 case CK_IntegralCast: 15996 return CheckICE(SubExpr, Ctx); 15997 default: 15998 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15999 } 16000 } 16001 case Expr::BinaryConditionalOperatorClass: { 16002 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 16003 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 16004 if (CommonResult.Kind == IK_NotICE) return CommonResult; 16005 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 16006 if (FalseResult.Kind == IK_NotICE) return FalseResult; 16007 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 16008 if (FalseResult.Kind == IK_ICEIfUnevaluated && 16009 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 16010 return FalseResult; 16011 } 16012 case Expr::ConditionalOperatorClass: { 16013 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 16014 // If the condition (ignoring parens) is a __builtin_constant_p call, 16015 // then only the true side is actually considered in an integer constant 16016 // expression, and it is fully evaluated. This is an important GNU 16017 // extension. See GCC PR38377 for discussion. 16018 if (const CallExpr *CallCE 16019 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 16020 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 16021 return CheckEvalInICE(E, Ctx); 16022 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 16023 if (CondResult.Kind == IK_NotICE) 16024 return CondResult; 16025 16026 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 16027 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 16028 16029 if (TrueResult.Kind == IK_NotICE) 16030 return TrueResult; 16031 if (FalseResult.Kind == IK_NotICE) 16032 return FalseResult; 16033 if (CondResult.Kind == IK_ICEIfUnevaluated) 16034 return CondResult; 16035 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 16036 return NoDiag(); 16037 // Rare case where the diagnostics depend on which side is evaluated 16038 // Note that if we get here, CondResult is 0, and at least one of 16039 // TrueResult and FalseResult is non-zero. 16040 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 16041 return FalseResult; 16042 return TrueResult; 16043 } 16044 case Expr::CXXDefaultArgExprClass: 16045 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 16046 case Expr::CXXDefaultInitExprClass: 16047 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 16048 case Expr::ChooseExprClass: { 16049 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 16050 } 16051 case Expr::BuiltinBitCastExprClass: { 16052 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 16053 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16054 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 16055 } 16056 } 16057 16058 llvm_unreachable("Invalid StmtClass!"); 16059 } 16060 16061 /// Evaluate an expression as a C++11 integral constant expression. 16062 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 16063 const Expr *E, 16064 llvm::APSInt *Value, 16065 SourceLocation *Loc) { 16066 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16067 if (Loc) *Loc = E->getExprLoc(); 16068 return false; 16069 } 16070 16071 APValue Result; 16072 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 16073 return false; 16074 16075 if (!Result.isInt()) { 16076 if (Loc) *Loc = E->getExprLoc(); 16077 return false; 16078 } 16079 16080 if (Value) *Value = Result.getInt(); 16081 return true; 16082 } 16083 16084 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 16085 SourceLocation *Loc) const { 16086 assert(!isValueDependent() && 16087 "Expression evaluator can't be called on a dependent expression."); 16088 16089 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr"); 16090 16091 if (Ctx.getLangOpts().CPlusPlus11) 16092 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 16093 16094 ICEDiag D = CheckICE(this, Ctx); 16095 if (D.Kind != IK_ICE) { 16096 if (Loc) *Loc = D.Loc; 16097 return false; 16098 } 16099 return true; 16100 } 16101 16102 std::optional<llvm::APSInt> 16103 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc, 16104 bool isEvaluated) const { 16105 if (isValueDependent()) { 16106 // Expression evaluator can't succeed on a dependent expression. 16107 return std::nullopt; 16108 } 16109 16110 APSInt Value; 16111 16112 if (Ctx.getLangOpts().CPlusPlus11) { 16113 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 16114 return Value; 16115 return std::nullopt; 16116 } 16117 16118 if (!isIntegerConstantExpr(Ctx, Loc)) 16119 return std::nullopt; 16120 16121 // The only possible side-effects here are due to UB discovered in the 16122 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 16123 // required to treat the expression as an ICE, so we produce the folded 16124 // value. 16125 EvalResult ExprResult; 16126 Expr::EvalStatus Status; 16127 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 16128 Info.InConstantContext = true; 16129 16130 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 16131 llvm_unreachable("ICE cannot be evaluated!"); 16132 16133 return ExprResult.Val.getInt(); 16134 } 16135 16136 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 16137 assert(!isValueDependent() && 16138 "Expression evaluator can't be called on a dependent expression."); 16139 16140 return CheckICE(this, Ctx).Kind == IK_ICE; 16141 } 16142 16143 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 16144 SourceLocation *Loc) const { 16145 assert(!isValueDependent() && 16146 "Expression evaluator can't be called on a dependent expression."); 16147 16148 // We support this checking in C++98 mode in order to diagnose compatibility 16149 // issues. 16150 assert(Ctx.getLangOpts().CPlusPlus); 16151 16152 // Build evaluation settings. 16153 Expr::EvalStatus Status; 16154 SmallVector<PartialDiagnosticAt, 8> Diags; 16155 Status.Diag = &Diags; 16156 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 16157 16158 APValue Scratch; 16159 bool IsConstExpr = 16160 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 16161 // FIXME: We don't produce a diagnostic for this, but the callers that 16162 // call us on arbitrary full-expressions should generally not care. 16163 Info.discardCleanups() && !Status.HasSideEffects; 16164 16165 if (!Diags.empty()) { 16166 IsConstExpr = false; 16167 if (Loc) *Loc = Diags[0].first; 16168 } else if (!IsConstExpr) { 16169 // FIXME: This shouldn't happen. 16170 if (Loc) *Loc = getExprLoc(); 16171 } 16172 16173 return IsConstExpr; 16174 } 16175 16176 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 16177 const FunctionDecl *Callee, 16178 ArrayRef<const Expr*> Args, 16179 const Expr *This) const { 16180 assert(!isValueDependent() && 16181 "Expression evaluator can't be called on a dependent expression."); 16182 16183 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] { 16184 std::string Name; 16185 llvm::raw_string_ostream OS(Name); 16186 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(), 16187 /*Qualified=*/true); 16188 return Name; 16189 }); 16190 16191 Expr::EvalStatus Status; 16192 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 16193 Info.InConstantContext = true; 16194 16195 LValue ThisVal; 16196 const LValue *ThisPtr = nullptr; 16197 if (This) { 16198 #ifndef NDEBUG 16199 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 16200 assert(MD && "Don't provide `this` for non-methods."); 16201 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 16202 #endif 16203 if (!This->isValueDependent() && 16204 EvaluateObjectArgument(Info, This, ThisVal) && 16205 !Info.EvalStatus.HasSideEffects) 16206 ThisPtr = &ThisVal; 16207 16208 // Ignore any side-effects from a failed evaluation. This is safe because 16209 // they can't interfere with any other argument evaluation. 16210 Info.EvalStatus.HasSideEffects = false; 16211 } 16212 16213 CallRef Call = Info.CurrentCall->createCall(Callee); 16214 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 16215 I != E; ++I) { 16216 unsigned Idx = I - Args.begin(); 16217 if (Idx >= Callee->getNumParams()) 16218 break; 16219 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 16220 if ((*I)->isValueDependent() || 16221 !EvaluateCallArg(PVD, *I, Call, Info) || 16222 Info.EvalStatus.HasSideEffects) { 16223 // If evaluation fails, throw away the argument entirely. 16224 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 16225 *Slot = APValue(); 16226 } 16227 16228 // Ignore any side-effects from a failed evaluation. This is safe because 16229 // they can't interfere with any other argument evaluation. 16230 Info.EvalStatus.HasSideEffects = false; 16231 } 16232 16233 // Parameter cleanups happen in the caller and are not part of this 16234 // evaluation. 16235 Info.discardCleanups(); 16236 Info.EvalStatus.HasSideEffects = false; 16237 16238 // Build fake call to Callee. 16239 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This, 16240 Call); 16241 // FIXME: Missing ExprWithCleanups in enable_if conditions? 16242 FullExpressionRAII Scope(Info); 16243 return Evaluate(Value, Info, this) && Scope.destroy() && 16244 !Info.EvalStatus.HasSideEffects; 16245 } 16246 16247 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 16248 SmallVectorImpl< 16249 PartialDiagnosticAt> &Diags) { 16250 // FIXME: It would be useful to check constexpr function templates, but at the 16251 // moment the constant expression evaluator cannot cope with the non-rigorous 16252 // ASTs which we build for dependent expressions. 16253 if (FD->isDependentContext()) 16254 return true; 16255 16256 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] { 16257 std::string Name; 16258 llvm::raw_string_ostream OS(Name); 16259 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(), 16260 /*Qualified=*/true); 16261 return Name; 16262 }); 16263 16264 Expr::EvalStatus Status; 16265 Status.Diag = &Diags; 16266 16267 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 16268 Info.InConstantContext = true; 16269 Info.CheckingPotentialConstantExpression = true; 16270 16271 // The constexpr VM attempts to compile all methods to bytecode here. 16272 if (Info.EnableNewConstInterp) { 16273 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 16274 return Diags.empty(); 16275 } 16276 16277 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 16278 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 16279 16280 // Fabricate an arbitrary expression on the stack and pretend that it 16281 // is a temporary being used as the 'this' pointer. 16282 LValue This; 16283 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 16284 This.set({&VIE, Info.CurrentCall->Index}); 16285 16286 ArrayRef<const Expr*> Args; 16287 16288 APValue Scratch; 16289 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 16290 // Evaluate the call as a constant initializer, to allow the construction 16291 // of objects of non-literal types. 16292 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 16293 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 16294 } else { 16295 SourceLocation Loc = FD->getLocation(); 16296 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 16297 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch, 16298 /*ResultSlot=*/nullptr); 16299 } 16300 16301 return Diags.empty(); 16302 } 16303 16304 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 16305 const FunctionDecl *FD, 16306 SmallVectorImpl< 16307 PartialDiagnosticAt> &Diags) { 16308 assert(!E->isValueDependent() && 16309 "Expression evaluator can't be called on a dependent expression."); 16310 16311 Expr::EvalStatus Status; 16312 Status.Diag = &Diags; 16313 16314 EvalInfo Info(FD->getASTContext(), Status, 16315 EvalInfo::EM_ConstantExpressionUnevaluated); 16316 Info.InConstantContext = true; 16317 Info.CheckingPotentialConstantExpression = true; 16318 16319 // Fabricate a call stack frame to give the arguments a plausible cover story. 16320 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr, 16321 /*CallExpr=*/nullptr, CallRef()); 16322 16323 APValue ResultScratch; 16324 Evaluate(ResultScratch, Info, E); 16325 return Diags.empty(); 16326 } 16327 16328 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 16329 unsigned Type) const { 16330 if (!getType()->isPointerType()) 16331 return false; 16332 16333 Expr::EvalStatus Status; 16334 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 16335 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 16336 } 16337 16338 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 16339 EvalInfo &Info) { 16340 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 16341 return false; 16342 16343 LValue String; 16344 16345 if (!EvaluatePointer(E, String, Info)) 16346 return false; 16347 16348 QualType CharTy = E->getType()->getPointeeType(); 16349 16350 // Fast path: if it's a string literal, search the string value. 16351 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 16352 String.getLValueBase().dyn_cast<const Expr *>())) { 16353 StringRef Str = S->getBytes(); 16354 int64_t Off = String.Offset.getQuantity(); 16355 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 16356 S->getCharByteWidth() == 1 && 16357 // FIXME: Add fast-path for wchar_t too. 16358 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 16359 Str = Str.substr(Off); 16360 16361 StringRef::size_type Pos = Str.find(0); 16362 if (Pos != StringRef::npos) 16363 Str = Str.substr(0, Pos); 16364 16365 Result = Str.size(); 16366 return true; 16367 } 16368 16369 // Fall through to slow path. 16370 } 16371 16372 // Slow path: scan the bytes of the string looking for the terminating 0. 16373 for (uint64_t Strlen = 0; /**/; ++Strlen) { 16374 APValue Char; 16375 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 16376 !Char.isInt()) 16377 return false; 16378 if (!Char.getInt()) { 16379 Result = Strlen; 16380 return true; 16381 } 16382 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 16383 return false; 16384 } 16385 } 16386 16387 bool Expr::EvaluateCharRangeAsString(std::string &Result, 16388 const Expr *SizeExpression, 16389 const Expr *PtrExpression, ASTContext &Ctx, 16390 EvalResult &Status) const { 16391 LValue String; 16392 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 16393 Info.InConstantContext = true; 16394 16395 FullExpressionRAII Scope(Info); 16396 APSInt SizeValue; 16397 if (!::EvaluateInteger(SizeExpression, SizeValue, Info)) 16398 return false; 16399 16400 int64_t Size = SizeValue.getExtValue(); 16401 16402 if (!::EvaluatePointer(PtrExpression, String, Info)) 16403 return false; 16404 16405 QualType CharTy = PtrExpression->getType()->getPointeeType(); 16406 for (int64_t I = 0; I < Size; ++I) { 16407 APValue Char; 16408 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String, 16409 Char)) 16410 return false; 16411 16412 APSInt C = Char.getInt(); 16413 Result.push_back(static_cast<char>(C.getExtValue())); 16414 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1)) 16415 return false; 16416 } 16417 if (!Scope.destroy()) 16418 return false; 16419 16420 if (!CheckMemoryLeaks(Info)) 16421 return false; 16422 16423 return true; 16424 } 16425 16426 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 16427 Expr::EvalStatus Status; 16428 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 16429 return EvaluateBuiltinStrLen(this, Result, Info); 16430 } 16431