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/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 return B.getType(); 83 } 84 85 /// Get an LValue path entry, which is known to not be an array index, as a 86 /// field declaration. 87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 89 } 90 /// Get an LValue path entry, which is known to not be an array index, as a 91 /// base class declaration. 92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 94 } 95 /// Determine whether this LValue path entry for a base class names a virtual 96 /// base class. 97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 98 return E.getAsBaseOrMember().getInt(); 99 } 100 101 /// Given an expression, determine the type used to store the result of 102 /// evaluating that expression. 103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 104 if (E->isPRValue()) 105 return E->getType(); 106 return Ctx.getLValueReferenceType(E->getType()); 107 } 108 109 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 111 if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) 112 return DirectCallee->getAttr<AllocSizeAttr>(); 113 if (const Decl *IndirectCallee = CE->getCalleeDecl()) 114 return IndirectCallee->getAttr<AllocSizeAttr>(); 115 return nullptr; 116 } 117 118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 119 /// This will look through a single cast. 120 /// 121 /// Returns null if we couldn't unwrap a function with alloc_size. 122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 123 if (!E->getType()->isPointerType()) 124 return nullptr; 125 126 E = E->IgnoreParens(); 127 // If we're doing a variable assignment from e.g. malloc(N), there will 128 // probably be a cast of some kind. In exotic cases, we might also see a 129 // top-level ExprWithCleanups. Ignore them either way. 130 if (const auto *FE = dyn_cast<FullExpr>(E)) 131 E = FE->getSubExpr()->IgnoreParens(); 132 133 if (const auto *Cast = dyn_cast<CastExpr>(E)) 134 E = Cast->getSubExpr()->IgnoreParens(); 135 136 if (const auto *CE = dyn_cast<CallExpr>(E)) 137 return getAllocSizeAttr(CE) ? CE : nullptr; 138 return nullptr; 139 } 140 141 /// Determines whether or not the given Base contains a call to a function 142 /// with the alloc_size attribute. 143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 144 const auto *E = Base.dyn_cast<const Expr *>(); 145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 146 } 147 148 /// Determines whether the given kind of constant expression is only ever 149 /// used for name mangling. If so, it's permitted to reference things that we 150 /// can't generate code for (in particular, dllimported functions). 151 static bool isForManglingOnly(ConstantExprKind Kind) { 152 switch (Kind) { 153 case ConstantExprKind::Normal: 154 case ConstantExprKind::ClassTemplateArgument: 155 case ConstantExprKind::ImmediateInvocation: 156 // Note that non-type template arguments of class type are emitted as 157 // template parameter objects. 158 return false; 159 160 case ConstantExprKind::NonClassTemplateArgument: 161 return true; 162 } 163 llvm_unreachable("unknown ConstantExprKind"); 164 } 165 166 static bool isTemplateArgument(ConstantExprKind Kind) { 167 switch (Kind) { 168 case ConstantExprKind::Normal: 169 case ConstantExprKind::ImmediateInvocation: 170 return false; 171 172 case ConstantExprKind::ClassTemplateArgument: 173 case ConstantExprKind::NonClassTemplateArgument: 174 return true; 175 } 176 llvm_unreachable("unknown ConstantExprKind"); 177 } 178 179 /// The bound to claim that an array of unknown bound has. 180 /// The value in MostDerivedArraySize is undefined in this case. So, set it 181 /// to an arbitrary value that's likely to loudly break things if it's used. 182 static const uint64_t AssumedSizeForUnsizedArray = 183 std::numeric_limits<uint64_t>::max() / 2; 184 185 /// Determines if an LValue with the given LValueBase will have an unsized 186 /// array in its designator. 187 /// Find the path length and type of the most-derived subobject in the given 188 /// path, and find the size of the containing array, if any. 189 static unsigned 190 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 191 ArrayRef<APValue::LValuePathEntry> Path, 192 uint64_t &ArraySize, QualType &Type, bool &IsArray, 193 bool &FirstEntryIsUnsizedArray) { 194 // This only accepts LValueBases from APValues, and APValues don't support 195 // arrays that lack size info. 196 assert(!isBaseAnAllocSizeCall(Base) && 197 "Unsized arrays shouldn't appear here"); 198 unsigned MostDerivedLength = 0; 199 Type = getType(Base); 200 201 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 202 if (Type->isArrayType()) { 203 const ArrayType *AT = Ctx.getAsArrayType(Type); 204 Type = AT->getElementType(); 205 MostDerivedLength = I + 1; 206 IsArray = true; 207 208 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 209 ArraySize = CAT->getSize().getZExtValue(); 210 } else { 211 assert(I == 0 && "unexpected unsized array designator"); 212 FirstEntryIsUnsizedArray = true; 213 ArraySize = AssumedSizeForUnsizedArray; 214 } 215 } else if (Type->isAnyComplexType()) { 216 const ComplexType *CT = Type->castAs<ComplexType>(); 217 Type = CT->getElementType(); 218 ArraySize = 2; 219 MostDerivedLength = I + 1; 220 IsArray = true; 221 } else if (const FieldDecl *FD = getAsField(Path[I])) { 222 Type = FD->getType(); 223 ArraySize = 0; 224 MostDerivedLength = I + 1; 225 IsArray = false; 226 } else { 227 // Path[I] describes a base class. 228 ArraySize = 0; 229 IsArray = false; 230 } 231 } 232 return MostDerivedLength; 233 } 234 235 /// A path from a glvalue to a subobject of that glvalue. 236 struct SubobjectDesignator { 237 /// True if the subobject was named in a manner not supported by C++11. Such 238 /// lvalues can still be folded, but they are not core constant expressions 239 /// and we cannot perform lvalue-to-rvalue conversions on them. 240 unsigned Invalid : 1; 241 242 /// Is this a pointer one past the end of an object? 243 unsigned IsOnePastTheEnd : 1; 244 245 /// Indicator of whether the first entry is an unsized array. 246 unsigned FirstEntryIsAnUnsizedArray : 1; 247 248 /// Indicator of whether the most-derived object is an array element. 249 unsigned MostDerivedIsArrayElement : 1; 250 251 /// The length of the path to the most-derived object of which this is a 252 /// subobject. 253 unsigned MostDerivedPathLength : 28; 254 255 /// The size of the array of which the most-derived object is an element. 256 /// This will always be 0 if the most-derived object is not an array 257 /// element. 0 is not an indicator of whether or not the most-derived object 258 /// is an array, however, because 0-length arrays are allowed. 259 /// 260 /// If the current array is an unsized array, the value of this is 261 /// undefined. 262 uint64_t MostDerivedArraySize; 263 264 /// The type of the most derived object referred to by this address. 265 QualType MostDerivedType; 266 267 typedef APValue::LValuePathEntry PathEntry; 268 269 /// The entries on the path from the glvalue to the designated subobject. 270 SmallVector<PathEntry, 8> Entries; 271 272 SubobjectDesignator() : Invalid(true) {} 273 274 explicit SubobjectDesignator(QualType T) 275 : Invalid(false), IsOnePastTheEnd(false), 276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 277 MostDerivedPathLength(0), MostDerivedArraySize(0), 278 MostDerivedType(T) {} 279 280 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 281 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 282 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 283 MostDerivedPathLength(0), MostDerivedArraySize(0) { 284 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 285 if (!Invalid) { 286 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 287 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 288 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 289 if (V.getLValueBase()) { 290 bool IsArray = false; 291 bool FirstIsUnsizedArray = false; 292 MostDerivedPathLength = findMostDerivedSubobject( 293 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 294 MostDerivedType, IsArray, FirstIsUnsizedArray); 295 MostDerivedIsArrayElement = IsArray; 296 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 297 } 298 } 299 } 300 301 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 302 unsigned NewLength) { 303 if (Invalid) 304 return; 305 306 assert(Base && "cannot truncate path for null pointer"); 307 assert(NewLength <= Entries.size() && "not a truncation"); 308 309 if (NewLength == Entries.size()) 310 return; 311 Entries.resize(NewLength); 312 313 bool IsArray = false; 314 bool FirstIsUnsizedArray = false; 315 MostDerivedPathLength = findMostDerivedSubobject( 316 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 317 FirstIsUnsizedArray); 318 MostDerivedIsArrayElement = IsArray; 319 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 320 } 321 322 void setInvalid() { 323 Invalid = true; 324 Entries.clear(); 325 } 326 327 /// Determine whether the most derived subobject is an array without a 328 /// known bound. 329 bool isMostDerivedAnUnsizedArray() const { 330 assert(!Invalid && "Calling this makes no sense on invalid designators"); 331 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 332 } 333 334 /// Determine what the most derived array's size is. Results in an assertion 335 /// failure if the most derived array lacks a size. 336 uint64_t getMostDerivedArraySize() const { 337 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 338 return MostDerivedArraySize; 339 } 340 341 /// Determine whether this is a one-past-the-end pointer. 342 bool isOnePastTheEnd() const { 343 assert(!Invalid); 344 if (IsOnePastTheEnd) 345 return true; 346 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 347 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 348 MostDerivedArraySize) 349 return true; 350 return false; 351 } 352 353 /// Get the range of valid index adjustments in the form 354 /// {maximum value that can be subtracted from this pointer, 355 /// maximum value that can be added to this pointer} 356 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 357 if (Invalid || isMostDerivedAnUnsizedArray()) 358 return {0, 0}; 359 360 // [expr.add]p4: For the purposes of these operators, a pointer to a 361 // nonarray object behaves the same as a pointer to the first element of 362 // an array of length one with the type of the object as its element type. 363 bool IsArray = MostDerivedPathLength == Entries.size() && 364 MostDerivedIsArrayElement; 365 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 366 : (uint64_t)IsOnePastTheEnd; 367 uint64_t ArraySize = 368 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 369 return {ArrayIndex, ArraySize - ArrayIndex}; 370 } 371 372 /// Check that this refers to a valid subobject. 373 bool isValidSubobject() const { 374 if (Invalid) 375 return false; 376 return !isOnePastTheEnd(); 377 } 378 /// Check that this refers to a valid subobject, and if not, produce a 379 /// relevant diagnostic and set the designator as invalid. 380 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 381 382 /// Get the type of the designated object. 383 QualType getType(ASTContext &Ctx) const { 384 assert(!Invalid && "invalid designator has no subobject type"); 385 return MostDerivedPathLength == Entries.size() 386 ? MostDerivedType 387 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 388 } 389 390 /// Update this designator to refer to the first element within this array. 391 void addArrayUnchecked(const ConstantArrayType *CAT) { 392 Entries.push_back(PathEntry::ArrayIndex(0)); 393 394 // This is a most-derived object. 395 MostDerivedType = CAT->getElementType(); 396 MostDerivedIsArrayElement = true; 397 MostDerivedArraySize = CAT->getSize().getZExtValue(); 398 MostDerivedPathLength = Entries.size(); 399 } 400 /// Update this designator to refer to the first element within the array of 401 /// elements of type T. This is an array of unknown size. 402 void addUnsizedArrayUnchecked(QualType ElemTy) { 403 Entries.push_back(PathEntry::ArrayIndex(0)); 404 405 MostDerivedType = ElemTy; 406 MostDerivedIsArrayElement = true; 407 // The value in MostDerivedArraySize is undefined in this case. So, set it 408 // to an arbitrary value that's likely to loudly break things if it's 409 // used. 410 MostDerivedArraySize = AssumedSizeForUnsizedArray; 411 MostDerivedPathLength = Entries.size(); 412 } 413 /// Update this designator to refer to the given base or member of this 414 /// object. 415 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 416 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 417 418 // If this isn't a base class, it's a new most-derived object. 419 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 420 MostDerivedType = FD->getType(); 421 MostDerivedIsArrayElement = false; 422 MostDerivedArraySize = 0; 423 MostDerivedPathLength = Entries.size(); 424 } 425 } 426 /// Update this designator to refer to the given complex component. 427 void addComplexUnchecked(QualType EltTy, bool Imag) { 428 Entries.push_back(PathEntry::ArrayIndex(Imag)); 429 430 // This is technically a most-derived object, though in practice this 431 // is unlikely to matter. 432 MostDerivedType = EltTy; 433 MostDerivedIsArrayElement = true; 434 MostDerivedArraySize = 2; 435 MostDerivedPathLength = Entries.size(); 436 } 437 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 438 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 439 const APSInt &N); 440 /// Add N to the address of this subobject. 441 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 442 if (Invalid || !N) return; 443 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 444 if (isMostDerivedAnUnsizedArray()) { 445 diagnoseUnsizedArrayPointerArithmetic(Info, E); 446 // Can't verify -- trust that the user is doing the right thing (or if 447 // not, trust that the caller will catch the bad behavior). 448 // FIXME: Should we reject if this overflows, at least? 449 Entries.back() = PathEntry::ArrayIndex( 450 Entries.back().getAsArrayIndex() + TruncatedN); 451 return; 452 } 453 454 // [expr.add]p4: For the purposes of these operators, a pointer to a 455 // nonarray object behaves the same as a pointer to the first element of 456 // an array of length one with the type of the object as its element type. 457 bool IsArray = MostDerivedPathLength == Entries.size() && 458 MostDerivedIsArrayElement; 459 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 460 : (uint64_t)IsOnePastTheEnd; 461 uint64_t ArraySize = 462 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 463 464 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 465 // Calculate the actual index in a wide enough type, so we can include 466 // it in the note. 467 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 468 (llvm::APInt&)N += ArrayIndex; 469 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 470 diagnosePointerArithmetic(Info, E, N); 471 setInvalid(); 472 return; 473 } 474 475 ArrayIndex += TruncatedN; 476 assert(ArrayIndex <= ArraySize && 477 "bounds check succeeded for out-of-bounds index"); 478 479 if (IsArray) 480 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 481 else 482 IsOnePastTheEnd = (ArrayIndex != 0); 483 } 484 }; 485 486 /// A scope at the end of which an object can need to be destroyed. 487 enum class ScopeKind { 488 Block, 489 FullExpression, 490 Call 491 }; 492 493 /// A reference to a particular call and its arguments. 494 struct CallRef { 495 CallRef() : OrigCallee(), CallIndex(0), Version() {} 496 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 497 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 498 499 explicit operator bool() const { return OrigCallee; } 500 501 /// Get the parameter that the caller initialized, corresponding to the 502 /// given parameter in the callee. 503 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 504 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 505 : PVD; 506 } 507 508 /// The callee at the point where the arguments were evaluated. This might 509 /// be different from the actual callee (a different redeclaration, or a 510 /// virtual override), but this function's parameters are the ones that 511 /// appear in the parameter map. 512 const FunctionDecl *OrigCallee; 513 /// The call index of the frame that holds the argument values. 514 unsigned CallIndex; 515 /// The version of the parameters corresponding to this call. 516 unsigned Version; 517 }; 518 519 /// A stack frame in the constexpr call stack. 520 class CallStackFrame : public interp::Frame { 521 public: 522 EvalInfo &Info; 523 524 /// Parent - The caller of this stack frame. 525 CallStackFrame *Caller; 526 527 /// Callee - The function which was called. 528 const FunctionDecl *Callee; 529 530 /// This - The binding for the this pointer in this call, if any. 531 const LValue *This; 532 533 /// Information on how to find the arguments to this call. Our arguments 534 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 535 /// key and this value as the version. 536 CallRef Arguments; 537 538 /// Source location information about the default argument or default 539 /// initializer expression we're evaluating, if any. 540 CurrentSourceLocExprScope CurSourceLocExprScope; 541 542 // Note that we intentionally use std::map here so that references to 543 // values are stable. 544 typedef std::pair<const void *, unsigned> MapKeyTy; 545 typedef std::map<MapKeyTy, APValue> MapTy; 546 /// Temporaries - Temporary lvalues materialized within this stack frame. 547 MapTy Temporaries; 548 549 /// CallLoc - The location of the call expression for this call. 550 SourceLocation CallLoc; 551 552 /// Index - The call index of this call. 553 unsigned Index; 554 555 /// The stack of integers for tracking version numbers for temporaries. 556 SmallVector<unsigned, 2> TempVersionStack = {1}; 557 unsigned CurTempVersion = TempVersionStack.back(); 558 559 unsigned getTempVersion() const { return TempVersionStack.back(); } 560 561 void pushTempVersion() { 562 TempVersionStack.push_back(++CurTempVersion); 563 } 564 565 void popTempVersion() { 566 TempVersionStack.pop_back(); 567 } 568 569 CallRef createCall(const FunctionDecl *Callee) { 570 return {Callee, Index, ++CurTempVersion}; 571 } 572 573 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 574 // on the overall stack usage of deeply-recursing constexpr evaluations. 575 // (We should cache this map rather than recomputing it repeatedly.) 576 // But let's try this and see how it goes; we can look into caching the map 577 // as a later change. 578 579 /// LambdaCaptureFields - Mapping from captured variables/this to 580 /// corresponding data members in the closure class. 581 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 582 FieldDecl *LambdaThisCaptureField; 583 584 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 585 const FunctionDecl *Callee, const LValue *This, 586 CallRef Arguments); 587 ~CallStackFrame(); 588 589 // Return the temporary for Key whose version number is Version. 590 APValue *getTemporary(const void *Key, unsigned Version) { 591 MapKeyTy KV(Key, Version); 592 auto LB = Temporaries.lower_bound(KV); 593 if (LB != Temporaries.end() && LB->first == KV) 594 return &LB->second; 595 // Pair (Key,Version) wasn't found in the map. Check that no elements 596 // in the map have 'Key' as their key. 597 assert((LB == Temporaries.end() || LB->first.first != Key) && 598 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 599 "Element with key 'Key' found in map"); 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) 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 665 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 666 const LValue &This, QualType ThisType); 667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 668 APValue::LValueBase LVBase, APValue &Value, 669 QualType T); 670 671 namespace { 672 /// A cleanup, and a flag indicating whether it is lifetime-extended. 673 class Cleanup { 674 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 675 APValue::LValueBase Base; 676 QualType T; 677 678 public: 679 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 680 ScopeKind Scope) 681 : Value(Val, Scope), Base(Base), T(T) {} 682 683 /// Determine whether this cleanup should be performed at the end of the 684 /// given kind of scope. 685 bool isDestroyedAtEndOf(ScopeKind K) const { 686 return (int)Value.getInt() >= (int)K; 687 } 688 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 689 if (RunDestructors) { 690 SourceLocation Loc; 691 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 692 Loc = VD->getLocation(); 693 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 694 Loc = E->getExprLoc(); 695 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 696 } 697 *Value.getPointer() = APValue(); 698 return true; 699 } 700 701 bool hasSideEffect() { 702 return T.isDestructedType(); 703 } 704 }; 705 706 /// A reference to an object whose construction we are currently evaluating. 707 struct ObjectUnderConstruction { 708 APValue::LValueBase Base; 709 ArrayRef<APValue::LValuePathEntry> Path; 710 friend bool operator==(const ObjectUnderConstruction &LHS, 711 const ObjectUnderConstruction &RHS) { 712 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 713 } 714 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 715 return llvm::hash_combine(Obj.Base, Obj.Path); 716 } 717 }; 718 enum class ConstructionPhase { 719 None, 720 Bases, 721 AfterBases, 722 AfterFields, 723 Destroying, 724 DestroyingBases 725 }; 726 } 727 728 namespace llvm { 729 template<> struct DenseMapInfo<ObjectUnderConstruction> { 730 using Base = DenseMapInfo<APValue::LValueBase>; 731 static ObjectUnderConstruction getEmptyKey() { 732 return {Base::getEmptyKey(), {}}; } 733 static ObjectUnderConstruction getTombstoneKey() { 734 return {Base::getTombstoneKey(), {}}; 735 } 736 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 737 return hash_value(Object); 738 } 739 static bool isEqual(const ObjectUnderConstruction &LHS, 740 const ObjectUnderConstruction &RHS) { 741 return LHS == RHS; 742 } 743 }; 744 } 745 746 namespace { 747 /// A dynamically-allocated heap object. 748 struct DynAlloc { 749 /// The value of this heap-allocated object. 750 APValue Value; 751 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 752 /// or a CallExpr (the latter is for direct calls to operator new inside 753 /// std::allocator<T>::allocate). 754 const Expr *AllocExpr = nullptr; 755 756 enum Kind { 757 New, 758 ArrayNew, 759 StdAllocator 760 }; 761 762 /// Get the kind of the allocation. This must match between allocation 763 /// and deallocation. 764 Kind getKind() const { 765 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 766 return NE->isArray() ? ArrayNew : New; 767 assert(isa<CallExpr>(AllocExpr)); 768 return StdAllocator; 769 } 770 }; 771 772 struct DynAllocOrder { 773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 774 return L.getIndex() < R.getIndex(); 775 } 776 }; 777 778 /// EvalInfo - This is a private struct used by the evaluator to capture 779 /// information about a subexpression as it is folded. It retains information 780 /// about the AST context, but also maintains information about the folded 781 /// expression. 782 /// 783 /// If an expression could be evaluated, it is still possible it is not a C 784 /// "integer constant expression" or constant expression. If not, this struct 785 /// captures information about how and why not. 786 /// 787 /// One bit of information passed *into* the request for constant folding 788 /// indicates whether the subexpression is "evaluated" or not according to C 789 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 790 /// evaluate the expression regardless of what the RHS is, but C only allows 791 /// certain things in certain situations. 792 class EvalInfo : public interp::State { 793 public: 794 ASTContext &Ctx; 795 796 /// EvalStatus - Contains information about the evaluation. 797 Expr::EvalStatus &EvalStatus; 798 799 /// CurrentCall - The top of the constexpr call stack. 800 CallStackFrame *CurrentCall; 801 802 /// CallStackDepth - The number of calls in the call stack right now. 803 unsigned CallStackDepth; 804 805 /// NextCallIndex - The next call index to assign. 806 unsigned NextCallIndex; 807 808 /// StepsLeft - The remaining number of evaluation steps we're permitted 809 /// to perform. This is essentially a limit for the number of statements 810 /// we will evaluate. 811 unsigned StepsLeft; 812 813 /// Enable the experimental new constant interpreter. If an expression is 814 /// not supported by the interpreter, an error is triggered. 815 bool EnableNewConstInterp; 816 817 /// BottomFrame - The frame in which evaluation started. This must be 818 /// initialized after CurrentCall and CallStackDepth. 819 CallStackFrame BottomFrame; 820 821 /// A stack of values whose lifetimes end at the end of some surrounding 822 /// evaluation frame. 823 llvm::SmallVector<Cleanup, 16> CleanupStack; 824 825 /// EvaluatingDecl - This is the declaration whose initializer is being 826 /// evaluated, if any. 827 APValue::LValueBase EvaluatingDecl; 828 829 enum class EvaluatingDeclKind { 830 None, 831 /// We're evaluating the construction of EvaluatingDecl. 832 Ctor, 833 /// We're evaluating the destruction of EvaluatingDecl. 834 Dtor, 835 }; 836 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 837 838 /// EvaluatingDeclValue - This is the value being constructed for the 839 /// declaration whose initializer is being evaluated, if any. 840 APValue *EvaluatingDeclValue; 841 842 /// Set of objects that are currently being constructed. 843 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 844 ObjectsUnderConstruction; 845 846 /// Current heap allocations, along with the location where each was 847 /// allocated. We use std::map here because we need stable addresses 848 /// for the stored APValues. 849 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 850 851 /// The number of heap allocations performed so far in this evaluation. 852 unsigned NumHeapAllocs = 0; 853 854 struct EvaluatingConstructorRAII { 855 EvalInfo &EI; 856 ObjectUnderConstruction Object; 857 bool DidInsert; 858 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 859 bool HasBases) 860 : EI(EI), Object(Object) { 861 DidInsert = 862 EI.ObjectsUnderConstruction 863 .insert({Object, HasBases ? ConstructionPhase::Bases 864 : ConstructionPhase::AfterBases}) 865 .second; 866 } 867 void finishedConstructingBases() { 868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 869 } 870 void finishedConstructingFields() { 871 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 872 } 873 ~EvaluatingConstructorRAII() { 874 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 875 } 876 }; 877 878 struct EvaluatingDestructorRAII { 879 EvalInfo &EI; 880 ObjectUnderConstruction Object; 881 bool DidInsert; 882 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 883 : EI(EI), Object(Object) { 884 DidInsert = EI.ObjectsUnderConstruction 885 .insert({Object, ConstructionPhase::Destroying}) 886 .second; 887 } 888 void startedDestroyingBases() { 889 EI.ObjectsUnderConstruction[Object] = 890 ConstructionPhase::DestroyingBases; 891 } 892 ~EvaluatingDestructorRAII() { 893 if (DidInsert) 894 EI.ObjectsUnderConstruction.erase(Object); 895 } 896 }; 897 898 ConstructionPhase 899 isEvaluatingCtorDtor(APValue::LValueBase Base, 900 ArrayRef<APValue::LValuePathEntry> Path) { 901 return ObjectsUnderConstruction.lookup({Base, Path}); 902 } 903 904 /// If we're currently speculatively evaluating, the outermost call stack 905 /// depth at which we can mutate state, otherwise 0. 906 unsigned SpeculativeEvaluationDepth = 0; 907 908 /// The current array initialization index, if we're performing array 909 /// initialization. 910 uint64_t ArrayInitIndex = -1; 911 912 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 913 /// notes attached to it will also be stored, otherwise they will not be. 914 bool HasActiveDiagnostic; 915 916 /// Have we emitted a diagnostic explaining why we couldn't constant 917 /// fold (not just why it's not strictly a constant expression)? 918 bool HasFoldFailureDiagnostic; 919 920 /// Whether or not we're in a context where the front end requires a 921 /// constant value. 922 bool InConstantContext; 923 924 /// Whether we're checking that an expression is a potential constant 925 /// expression. If so, do not fail on constructs that could become constant 926 /// later on (such as a use of an undefined global). 927 bool CheckingPotentialConstantExpression = false; 928 929 /// Whether we're checking for an expression that has undefined behavior. 930 /// If so, we will produce warnings if we encounter an operation that is 931 /// always undefined. 932 /// 933 /// Note that we still need to evaluate the expression normally when this 934 /// is set; this is used when evaluating ICEs in C. 935 bool CheckingForUndefinedBehavior = false; 936 937 enum EvaluationMode { 938 /// Evaluate as a constant expression. Stop if we find that the expression 939 /// is not a constant expression. 940 EM_ConstantExpression, 941 942 /// Evaluate as a constant expression. Stop if we find that the expression 943 /// is not a constant expression. Some expressions can be retried in the 944 /// optimizer if we don't constant fold them here, but in an unevaluated 945 /// context we try to fold them immediately since the optimizer never 946 /// gets a chance to look at it. 947 EM_ConstantExpressionUnevaluated, 948 949 /// Fold the expression to a constant. Stop if we hit a side-effect that 950 /// we can't model. 951 EM_ConstantFold, 952 953 /// Evaluate in any way we know how. Don't worry about side-effects that 954 /// can't be modeled. 955 EM_IgnoreSideEffects, 956 } EvalMode; 957 958 /// Are we checking whether the expression is a potential constant 959 /// expression? 960 bool checkingPotentialConstantExpression() const override { 961 return CheckingPotentialConstantExpression; 962 } 963 964 /// Are we checking an expression for overflow? 965 // FIXME: We should check for any kind of undefined or suspicious behavior 966 // in such constructs, not just overflow. 967 bool checkingForUndefinedBehavior() const override { 968 return CheckingForUndefinedBehavior; 969 } 970 971 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 972 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 973 CallStackDepth(0), NextCallIndex(1), 974 StepsLeft(C.getLangOpts().ConstexprStepLimit), 975 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 976 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 977 EvaluatingDecl((const ValueDecl *)nullptr), 978 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 979 HasFoldFailureDiagnostic(false), InConstantContext(false), 980 EvalMode(Mode) {} 981 982 ~EvalInfo() { 983 discardCleanups(); 984 } 985 986 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 987 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 988 EvaluatingDecl = Base; 989 IsEvaluatingDecl = EDK; 990 EvaluatingDeclValue = &Value; 991 } 992 993 bool CheckCallLimit(SourceLocation Loc) { 994 // Don't perform any constexpr calls (other than the call we're checking) 995 // when checking a potential constant expression. 996 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 997 return false; 998 if (NextCallIndex == 0) { 999 // NextCallIndex has wrapped around. 1000 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1001 return false; 1002 } 1003 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1004 return true; 1005 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1006 << getLangOpts().ConstexprCallDepth; 1007 return false; 1008 } 1009 1010 std::pair<CallStackFrame *, unsigned> 1011 getCallFrameAndDepth(unsigned CallIndex) { 1012 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1013 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1014 // be null in this loop. 1015 unsigned Depth = CallStackDepth; 1016 CallStackFrame *Frame = CurrentCall; 1017 while (Frame->Index > CallIndex) { 1018 Frame = Frame->Caller; 1019 --Depth; 1020 } 1021 if (Frame->Index == CallIndex) 1022 return {Frame, Depth}; 1023 return {nullptr, 0}; 1024 } 1025 1026 bool nextStep(const Stmt *S) { 1027 if (!StepsLeft) { 1028 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1029 return false; 1030 } 1031 --StepsLeft; 1032 return true; 1033 } 1034 1035 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1036 1037 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1038 Optional<DynAlloc*> Result; 1039 auto It = HeapAllocs.find(DA); 1040 if (It != HeapAllocs.end()) 1041 Result = &It->second; 1042 return Result; 1043 } 1044 1045 /// Get the allocated storage for the given parameter of the given call. 1046 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1047 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1048 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1049 : nullptr; 1050 } 1051 1052 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1053 struct StdAllocatorCaller { 1054 unsigned FrameIndex; 1055 QualType ElemType; 1056 explicit operator bool() const { return FrameIndex != 0; }; 1057 }; 1058 1059 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1060 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1061 Call = Call->Caller) { 1062 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1063 if (!MD) 1064 continue; 1065 const IdentifierInfo *FnII = MD->getIdentifier(); 1066 if (!FnII || !FnII->isStr(FnName)) 1067 continue; 1068 1069 const auto *CTSD = 1070 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1071 if (!CTSD) 1072 continue; 1073 1074 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1075 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1076 if (CTSD->isInStdNamespace() && ClassII && 1077 ClassII->isStr("allocator") && TAL.size() >= 1 && 1078 TAL[0].getKind() == TemplateArgument::Type) 1079 return {Call->Index, TAL[0].getAsType()}; 1080 } 1081 1082 return {}; 1083 } 1084 1085 void performLifetimeExtension() { 1086 // Disable the cleanups for lifetime-extended temporaries. 1087 CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1088 CleanupStack.end(), 1089 [](Cleanup &C) { 1090 return !C.isDestroyedAtEndOf( 1091 ScopeKind::FullExpression); 1092 }), 1093 CleanupStack.end()); 1094 } 1095 1096 /// Throw away any remaining cleanups at the end of evaluation. If any 1097 /// cleanups would have had a side-effect, note that as an unmodeled 1098 /// side-effect and return false. Otherwise, return true. 1099 bool discardCleanups() { 1100 for (Cleanup &C : CleanupStack) { 1101 if (C.hasSideEffect() && !noteSideEffect()) { 1102 CleanupStack.clear(); 1103 return false; 1104 } 1105 } 1106 CleanupStack.clear(); 1107 return true; 1108 } 1109 1110 private: 1111 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1112 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1113 1114 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1115 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1116 1117 void setFoldFailureDiagnostic(bool Flag) override { 1118 HasFoldFailureDiagnostic = Flag; 1119 } 1120 1121 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1122 1123 ASTContext &getCtx() const override { return Ctx; } 1124 1125 // If we have a prior diagnostic, it will be noting that the expression 1126 // isn't a constant expression. This diagnostic is more important, 1127 // unless we require this evaluation to produce a constant expression. 1128 // 1129 // FIXME: We might want to show both diagnostics to the user in 1130 // EM_ConstantFold mode. 1131 bool hasPriorDiagnostic() override { 1132 if (!EvalStatus.Diag->empty()) { 1133 switch (EvalMode) { 1134 case EM_ConstantFold: 1135 case EM_IgnoreSideEffects: 1136 if (!HasFoldFailureDiagnostic) 1137 break; 1138 // We've already failed to fold something. Keep that diagnostic. 1139 LLVM_FALLTHROUGH; 1140 case EM_ConstantExpression: 1141 case EM_ConstantExpressionUnevaluated: 1142 setActiveDiagnostic(false); 1143 return true; 1144 } 1145 } 1146 return false; 1147 } 1148 1149 unsigned getCallStackDepth() override { return CallStackDepth; } 1150 1151 public: 1152 /// Should we continue evaluation after encountering a side-effect that we 1153 /// couldn't model? 1154 bool keepEvaluatingAfterSideEffect() { 1155 switch (EvalMode) { 1156 case EM_IgnoreSideEffects: 1157 return true; 1158 1159 case EM_ConstantExpression: 1160 case EM_ConstantExpressionUnevaluated: 1161 case EM_ConstantFold: 1162 // By default, assume any side effect might be valid in some other 1163 // evaluation of this expression from a different context. 1164 return checkingPotentialConstantExpression() || 1165 checkingForUndefinedBehavior(); 1166 } 1167 llvm_unreachable("Missed EvalMode case"); 1168 } 1169 1170 /// Note that we have had a side-effect, and determine whether we should 1171 /// keep evaluating. 1172 bool noteSideEffect() { 1173 EvalStatus.HasSideEffects = true; 1174 return keepEvaluatingAfterSideEffect(); 1175 } 1176 1177 /// Should we continue evaluation after encountering undefined behavior? 1178 bool keepEvaluatingAfterUndefinedBehavior() { 1179 switch (EvalMode) { 1180 case EM_IgnoreSideEffects: 1181 case EM_ConstantFold: 1182 return true; 1183 1184 case EM_ConstantExpression: 1185 case EM_ConstantExpressionUnevaluated: 1186 return checkingForUndefinedBehavior(); 1187 } 1188 llvm_unreachable("Missed EvalMode case"); 1189 } 1190 1191 /// Note that we hit something that was technically undefined behavior, but 1192 /// that we can evaluate past it (such as signed overflow or floating-point 1193 /// division by zero.) 1194 bool noteUndefinedBehavior() override { 1195 EvalStatus.HasUndefinedBehavior = true; 1196 return keepEvaluatingAfterUndefinedBehavior(); 1197 } 1198 1199 /// Should we continue evaluation as much as possible after encountering a 1200 /// construct which can't be reduced to a value? 1201 bool keepEvaluatingAfterFailure() const override { 1202 if (!StepsLeft) 1203 return false; 1204 1205 switch (EvalMode) { 1206 case EM_ConstantExpression: 1207 case EM_ConstantExpressionUnevaluated: 1208 case EM_ConstantFold: 1209 case EM_IgnoreSideEffects: 1210 return checkingPotentialConstantExpression() || 1211 checkingForUndefinedBehavior(); 1212 } 1213 llvm_unreachable("Missed EvalMode case"); 1214 } 1215 1216 /// Notes that we failed to evaluate an expression that other expressions 1217 /// directly depend on, and determine if we should keep evaluating. This 1218 /// should only be called if we actually intend to keep evaluating. 1219 /// 1220 /// Call noteSideEffect() instead if we may be able to ignore the value that 1221 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1222 /// 1223 /// (Foo(), 1) // use noteSideEffect 1224 /// (Foo() || true) // use noteSideEffect 1225 /// Foo() + 1 // use noteFailure 1226 LLVM_NODISCARD bool noteFailure() { 1227 // Failure when evaluating some expression often means there is some 1228 // subexpression whose evaluation was skipped. Therefore, (because we 1229 // don't track whether we skipped an expression when unwinding after an 1230 // evaluation failure) every evaluation failure that bubbles up from a 1231 // subexpression implies that a side-effect has potentially happened. We 1232 // skip setting the HasSideEffects flag to true until we decide to 1233 // continue evaluating after that point, which happens here. 1234 bool KeepGoing = keepEvaluatingAfterFailure(); 1235 EvalStatus.HasSideEffects |= KeepGoing; 1236 return KeepGoing; 1237 } 1238 1239 class ArrayInitLoopIndex { 1240 EvalInfo &Info; 1241 uint64_t OuterIndex; 1242 1243 public: 1244 ArrayInitLoopIndex(EvalInfo &Info) 1245 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1246 Info.ArrayInitIndex = 0; 1247 } 1248 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1249 1250 operator uint64_t&() { return Info.ArrayInitIndex; } 1251 }; 1252 }; 1253 1254 /// Object used to treat all foldable expressions as constant expressions. 1255 struct FoldConstant { 1256 EvalInfo &Info; 1257 bool Enabled; 1258 bool HadNoPriorDiags; 1259 EvalInfo::EvaluationMode OldMode; 1260 1261 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1262 : Info(Info), 1263 Enabled(Enabled), 1264 HadNoPriorDiags(Info.EvalStatus.Diag && 1265 Info.EvalStatus.Diag->empty() && 1266 !Info.EvalStatus.HasSideEffects), 1267 OldMode(Info.EvalMode) { 1268 if (Enabled) 1269 Info.EvalMode = EvalInfo::EM_ConstantFold; 1270 } 1271 void keepDiagnostics() { Enabled = false; } 1272 ~FoldConstant() { 1273 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1274 !Info.EvalStatus.HasSideEffects) 1275 Info.EvalStatus.Diag->clear(); 1276 Info.EvalMode = OldMode; 1277 } 1278 }; 1279 1280 /// RAII object used to set the current evaluation mode to ignore 1281 /// side-effects. 1282 struct IgnoreSideEffectsRAII { 1283 EvalInfo &Info; 1284 EvalInfo::EvaluationMode OldMode; 1285 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1286 : Info(Info), OldMode(Info.EvalMode) { 1287 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1288 } 1289 1290 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1291 }; 1292 1293 /// RAII object used to optionally suppress diagnostics and side-effects from 1294 /// a speculative evaluation. 1295 class SpeculativeEvaluationRAII { 1296 EvalInfo *Info = nullptr; 1297 Expr::EvalStatus OldStatus; 1298 unsigned OldSpeculativeEvaluationDepth; 1299 1300 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1301 Info = Other.Info; 1302 OldStatus = Other.OldStatus; 1303 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1304 Other.Info = nullptr; 1305 } 1306 1307 void maybeRestoreState() { 1308 if (!Info) 1309 return; 1310 1311 Info->EvalStatus = OldStatus; 1312 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1313 } 1314 1315 public: 1316 SpeculativeEvaluationRAII() = default; 1317 1318 SpeculativeEvaluationRAII( 1319 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1320 : Info(&Info), OldStatus(Info.EvalStatus), 1321 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1322 Info.EvalStatus.Diag = NewDiag; 1323 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1324 } 1325 1326 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1327 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1328 moveFromAndCancel(std::move(Other)); 1329 } 1330 1331 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1332 maybeRestoreState(); 1333 moveFromAndCancel(std::move(Other)); 1334 return *this; 1335 } 1336 1337 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1338 }; 1339 1340 /// RAII object wrapping a full-expression or block scope, and handling 1341 /// the ending of the lifetime of temporaries created within it. 1342 template<ScopeKind Kind> 1343 class ScopeRAII { 1344 EvalInfo &Info; 1345 unsigned OldStackSize; 1346 public: 1347 ScopeRAII(EvalInfo &Info) 1348 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1349 // Push a new temporary version. This is needed to distinguish between 1350 // temporaries created in different iterations of a loop. 1351 Info.CurrentCall->pushTempVersion(); 1352 } 1353 bool destroy(bool RunDestructors = true) { 1354 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1355 OldStackSize = -1U; 1356 return OK; 1357 } 1358 ~ScopeRAII() { 1359 if (OldStackSize != -1U) 1360 destroy(false); 1361 // Body moved to a static method to encourage the compiler to inline away 1362 // instances of this class. 1363 Info.CurrentCall->popTempVersion(); 1364 } 1365 private: 1366 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1367 unsigned OldStackSize) { 1368 assert(OldStackSize <= Info.CleanupStack.size() && 1369 "running cleanups out of order?"); 1370 1371 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1372 // for a full-expression scope. 1373 bool Success = true; 1374 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1375 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1376 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1377 Success = false; 1378 break; 1379 } 1380 } 1381 } 1382 1383 // Compact any retained cleanups. 1384 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1385 if (Kind != ScopeKind::Block) 1386 NewEnd = 1387 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1388 return C.isDestroyedAtEndOf(Kind); 1389 }); 1390 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1391 return Success; 1392 } 1393 }; 1394 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1395 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1396 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1397 } 1398 1399 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1400 CheckSubobjectKind CSK) { 1401 if (Invalid) 1402 return false; 1403 if (isOnePastTheEnd()) { 1404 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1405 << CSK; 1406 setInvalid(); 1407 return false; 1408 } 1409 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1410 // must actually be at least one array element; even a VLA cannot have a 1411 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1412 return true; 1413 } 1414 1415 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1416 const Expr *E) { 1417 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1418 // Do not set the designator as invalid: we can represent this situation, 1419 // and correct handling of __builtin_object_size requires us to do so. 1420 } 1421 1422 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1423 const Expr *E, 1424 const APSInt &N) { 1425 // If we're complaining, we must be able to statically determine the size of 1426 // the most derived array. 1427 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1428 Info.CCEDiag(E, diag::note_constexpr_array_index) 1429 << N << /*array*/ 0 1430 << static_cast<unsigned>(getMostDerivedArraySize()); 1431 else 1432 Info.CCEDiag(E, diag::note_constexpr_array_index) 1433 << N << /*non-array*/ 1; 1434 setInvalid(); 1435 } 1436 1437 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1438 const FunctionDecl *Callee, const LValue *This, 1439 CallRef Call) 1440 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1441 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1442 Info.CurrentCall = this; 1443 ++Info.CallStackDepth; 1444 } 1445 1446 CallStackFrame::~CallStackFrame() { 1447 assert(Info.CurrentCall == this && "calls retired out of order"); 1448 --Info.CallStackDepth; 1449 Info.CurrentCall = Caller; 1450 } 1451 1452 static bool isRead(AccessKinds AK) { 1453 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1454 } 1455 1456 static bool isModification(AccessKinds AK) { 1457 switch (AK) { 1458 case AK_Read: 1459 case AK_ReadObjectRepresentation: 1460 case AK_MemberCall: 1461 case AK_DynamicCast: 1462 case AK_TypeId: 1463 return false; 1464 case AK_Assign: 1465 case AK_Increment: 1466 case AK_Decrement: 1467 case AK_Construct: 1468 case AK_Destroy: 1469 return true; 1470 } 1471 llvm_unreachable("unknown access kind"); 1472 } 1473 1474 static bool isAnyAccess(AccessKinds AK) { 1475 return isRead(AK) || isModification(AK); 1476 } 1477 1478 /// Is this an access per the C++ definition? 1479 static bool isFormalAccess(AccessKinds AK) { 1480 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1481 } 1482 1483 /// Is this kind of axcess valid on an indeterminate object value? 1484 static bool isValidIndeterminateAccess(AccessKinds AK) { 1485 switch (AK) { 1486 case AK_Read: 1487 case AK_Increment: 1488 case AK_Decrement: 1489 // These need the object's value. 1490 return false; 1491 1492 case AK_ReadObjectRepresentation: 1493 case AK_Assign: 1494 case AK_Construct: 1495 case AK_Destroy: 1496 // Construction and destruction don't need the value. 1497 return true; 1498 1499 case AK_MemberCall: 1500 case AK_DynamicCast: 1501 case AK_TypeId: 1502 // These aren't really meaningful on scalars. 1503 return true; 1504 } 1505 llvm_unreachable("unknown access kind"); 1506 } 1507 1508 namespace { 1509 struct ComplexValue { 1510 private: 1511 bool IsInt; 1512 1513 public: 1514 APSInt IntReal, IntImag; 1515 APFloat FloatReal, FloatImag; 1516 1517 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1518 1519 void makeComplexFloat() { IsInt = false; } 1520 bool isComplexFloat() const { return !IsInt; } 1521 APFloat &getComplexFloatReal() { return FloatReal; } 1522 APFloat &getComplexFloatImag() { return FloatImag; } 1523 1524 void makeComplexInt() { IsInt = true; } 1525 bool isComplexInt() const { return IsInt; } 1526 APSInt &getComplexIntReal() { return IntReal; } 1527 APSInt &getComplexIntImag() { return IntImag; } 1528 1529 void moveInto(APValue &v) const { 1530 if (isComplexFloat()) 1531 v = APValue(FloatReal, FloatImag); 1532 else 1533 v = APValue(IntReal, IntImag); 1534 } 1535 void setFrom(const APValue &v) { 1536 assert(v.isComplexFloat() || v.isComplexInt()); 1537 if (v.isComplexFloat()) { 1538 makeComplexFloat(); 1539 FloatReal = v.getComplexFloatReal(); 1540 FloatImag = v.getComplexFloatImag(); 1541 } else { 1542 makeComplexInt(); 1543 IntReal = v.getComplexIntReal(); 1544 IntImag = v.getComplexIntImag(); 1545 } 1546 } 1547 }; 1548 1549 struct LValue { 1550 APValue::LValueBase Base; 1551 CharUnits Offset; 1552 SubobjectDesignator Designator; 1553 bool IsNullPtr : 1; 1554 bool InvalidBase : 1; 1555 1556 const APValue::LValueBase getLValueBase() const { return Base; } 1557 CharUnits &getLValueOffset() { return Offset; } 1558 const CharUnits &getLValueOffset() const { return Offset; } 1559 SubobjectDesignator &getLValueDesignator() { return Designator; } 1560 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1561 bool isNullPointer() const { return IsNullPtr;} 1562 1563 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1564 unsigned getLValueVersion() const { return Base.getVersion(); } 1565 1566 void moveInto(APValue &V) const { 1567 if (Designator.Invalid) 1568 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1569 else { 1570 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1571 V = APValue(Base, Offset, Designator.Entries, 1572 Designator.IsOnePastTheEnd, IsNullPtr); 1573 } 1574 } 1575 void setFrom(ASTContext &Ctx, const APValue &V) { 1576 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1577 Base = V.getLValueBase(); 1578 Offset = V.getLValueOffset(); 1579 InvalidBase = false; 1580 Designator = SubobjectDesignator(Ctx, V); 1581 IsNullPtr = V.isNullPointer(); 1582 } 1583 1584 void set(APValue::LValueBase B, bool BInvalid = false) { 1585 #ifndef NDEBUG 1586 // We only allow a few types of invalid bases. Enforce that here. 1587 if (BInvalid) { 1588 const auto *E = B.get<const Expr *>(); 1589 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1590 "Unexpected type of invalid base"); 1591 } 1592 #endif 1593 1594 Base = B; 1595 Offset = CharUnits::fromQuantity(0); 1596 InvalidBase = BInvalid; 1597 Designator = SubobjectDesignator(getType(B)); 1598 IsNullPtr = false; 1599 } 1600 1601 void setNull(ASTContext &Ctx, QualType PointerTy) { 1602 Base = (const ValueDecl *)nullptr; 1603 Offset = 1604 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1605 InvalidBase = false; 1606 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1607 IsNullPtr = true; 1608 } 1609 1610 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1611 set(B, true); 1612 } 1613 1614 std::string toString(ASTContext &Ctx, QualType T) const { 1615 APValue Printable; 1616 moveInto(Printable); 1617 return Printable.getAsString(Ctx, T); 1618 } 1619 1620 private: 1621 // Check that this LValue is not based on a null pointer. If it is, produce 1622 // a diagnostic and mark the designator as invalid. 1623 template <typename GenDiagType> 1624 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1625 if (Designator.Invalid) 1626 return false; 1627 if (IsNullPtr) { 1628 GenDiag(); 1629 Designator.setInvalid(); 1630 return false; 1631 } 1632 return true; 1633 } 1634 1635 public: 1636 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1637 CheckSubobjectKind CSK) { 1638 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1639 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1640 }); 1641 } 1642 1643 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1644 AccessKinds AK) { 1645 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1646 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1647 }); 1648 } 1649 1650 // Check this LValue refers to an object. If not, set the designator to be 1651 // invalid and emit a diagnostic. 1652 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1653 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1654 Designator.checkSubobject(Info, E, CSK); 1655 } 1656 1657 void addDecl(EvalInfo &Info, const Expr *E, 1658 const Decl *D, bool Virtual = false) { 1659 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1660 Designator.addDeclUnchecked(D, Virtual); 1661 } 1662 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1663 if (!Designator.Entries.empty()) { 1664 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1665 Designator.setInvalid(); 1666 return; 1667 } 1668 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1669 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1670 Designator.FirstEntryIsAnUnsizedArray = true; 1671 Designator.addUnsizedArrayUnchecked(ElemTy); 1672 } 1673 } 1674 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1675 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1676 Designator.addArrayUnchecked(CAT); 1677 } 1678 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1679 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1680 Designator.addComplexUnchecked(EltTy, Imag); 1681 } 1682 void clearIsNullPointer() { 1683 IsNullPtr = false; 1684 } 1685 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1686 const APSInt &Index, CharUnits ElementSize) { 1687 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1688 // but we're not required to diagnose it and it's valid in C++.) 1689 if (!Index) 1690 return; 1691 1692 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1693 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1694 // offsets. 1695 uint64_t Offset64 = Offset.getQuantity(); 1696 uint64_t ElemSize64 = ElementSize.getQuantity(); 1697 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1698 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1699 1700 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1701 Designator.adjustIndex(Info, E, Index); 1702 clearIsNullPointer(); 1703 } 1704 void adjustOffset(CharUnits N) { 1705 Offset += N; 1706 if (N.getQuantity()) 1707 clearIsNullPointer(); 1708 } 1709 }; 1710 1711 struct MemberPtr { 1712 MemberPtr() {} 1713 explicit MemberPtr(const ValueDecl *Decl) : 1714 DeclAndIsDerivedMember(Decl, false), Path() {} 1715 1716 /// The member or (direct or indirect) field referred to by this member 1717 /// pointer, or 0 if this is a null member pointer. 1718 const ValueDecl *getDecl() const { 1719 return DeclAndIsDerivedMember.getPointer(); 1720 } 1721 /// Is this actually a member of some type derived from the relevant class? 1722 bool isDerivedMember() const { 1723 return DeclAndIsDerivedMember.getInt(); 1724 } 1725 /// Get the class which the declaration actually lives in. 1726 const CXXRecordDecl *getContainingRecord() const { 1727 return cast<CXXRecordDecl>( 1728 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1729 } 1730 1731 void moveInto(APValue &V) const { 1732 V = APValue(getDecl(), isDerivedMember(), Path); 1733 } 1734 void setFrom(const APValue &V) { 1735 assert(V.isMemberPointer()); 1736 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1737 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1738 Path.clear(); 1739 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1740 Path.insert(Path.end(), P.begin(), P.end()); 1741 } 1742 1743 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1744 /// whether the member is a member of some class derived from the class type 1745 /// of the member pointer. 1746 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1747 /// Path - The path of base/derived classes from the member declaration's 1748 /// class (exclusive) to the class type of the member pointer (inclusive). 1749 SmallVector<const CXXRecordDecl*, 4> Path; 1750 1751 /// Perform a cast towards the class of the Decl (either up or down the 1752 /// hierarchy). 1753 bool castBack(const CXXRecordDecl *Class) { 1754 assert(!Path.empty()); 1755 const CXXRecordDecl *Expected; 1756 if (Path.size() >= 2) 1757 Expected = Path[Path.size() - 2]; 1758 else 1759 Expected = getContainingRecord(); 1760 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1761 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1762 // if B does not contain the original member and is not a base or 1763 // derived class of the class containing the original member, the result 1764 // of the cast is undefined. 1765 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1766 // (D::*). We consider that to be a language defect. 1767 return false; 1768 } 1769 Path.pop_back(); 1770 return true; 1771 } 1772 /// Perform a base-to-derived member pointer cast. 1773 bool castToDerived(const CXXRecordDecl *Derived) { 1774 if (!getDecl()) 1775 return true; 1776 if (!isDerivedMember()) { 1777 Path.push_back(Derived); 1778 return true; 1779 } 1780 if (!castBack(Derived)) 1781 return false; 1782 if (Path.empty()) 1783 DeclAndIsDerivedMember.setInt(false); 1784 return true; 1785 } 1786 /// Perform a derived-to-base member pointer cast. 1787 bool castToBase(const CXXRecordDecl *Base) { 1788 if (!getDecl()) 1789 return true; 1790 if (Path.empty()) 1791 DeclAndIsDerivedMember.setInt(true); 1792 if (isDerivedMember()) { 1793 Path.push_back(Base); 1794 return true; 1795 } 1796 return castBack(Base); 1797 } 1798 }; 1799 1800 /// Compare two member pointers, which are assumed to be of the same type. 1801 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1802 if (!LHS.getDecl() || !RHS.getDecl()) 1803 return !LHS.getDecl() && !RHS.getDecl(); 1804 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1805 return false; 1806 return LHS.Path == RHS.Path; 1807 } 1808 } 1809 1810 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1811 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1812 const LValue &This, const Expr *E, 1813 bool AllowNonLiteralTypes = false); 1814 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1815 bool InvalidBaseOK = false); 1816 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1817 bool InvalidBaseOK = false); 1818 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1819 EvalInfo &Info); 1820 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1821 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1822 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1823 EvalInfo &Info); 1824 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1825 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1826 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1827 EvalInfo &Info); 1828 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1829 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 1830 EvalInfo &Info); 1831 1832 /// Evaluate an integer or fixed point expression into an APResult. 1833 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1834 EvalInfo &Info); 1835 1836 /// Evaluate only a fixed point expression into an APResult. 1837 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1838 EvalInfo &Info); 1839 1840 //===----------------------------------------------------------------------===// 1841 // Misc utilities 1842 //===----------------------------------------------------------------------===// 1843 1844 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1845 /// preserving its value (by extending by up to one bit as needed). 1846 static void negateAsSigned(APSInt &Int) { 1847 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1848 Int = Int.extend(Int.getBitWidth() + 1); 1849 Int.setIsSigned(true); 1850 } 1851 Int = -Int; 1852 } 1853 1854 template<typename KeyT> 1855 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1856 ScopeKind Scope, LValue &LV) { 1857 unsigned Version = getTempVersion(); 1858 APValue::LValueBase Base(Key, Index, Version); 1859 LV.set(Base); 1860 return createLocal(Base, Key, T, Scope); 1861 } 1862 1863 /// Allocate storage for a parameter of a function call made in this frame. 1864 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1865 LValue &LV) { 1866 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1867 APValue::LValueBase Base(PVD, Index, Args.Version); 1868 LV.set(Base); 1869 // We always destroy parameters at the end of the call, even if we'd allow 1870 // them to live to the end of the full-expression at runtime, in order to 1871 // give portable results and match other compilers. 1872 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1873 } 1874 1875 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1876 QualType T, ScopeKind Scope) { 1877 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1878 unsigned Version = Base.getVersion(); 1879 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1880 assert(Result.isAbsent() && "local created multiple times"); 1881 1882 // If we're creating a local immediately in the operand of a speculative 1883 // evaluation, don't register a cleanup to be run outside the speculative 1884 // evaluation context, since we won't actually be able to initialize this 1885 // object. 1886 if (Index <= Info.SpeculativeEvaluationDepth) { 1887 if (T.isDestructedType()) 1888 Info.noteSideEffect(); 1889 } else { 1890 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1891 } 1892 return Result; 1893 } 1894 1895 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1896 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1897 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1898 return nullptr; 1899 } 1900 1901 DynamicAllocLValue DA(NumHeapAllocs++); 1902 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1903 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1904 std::forward_as_tuple(DA), std::tuple<>()); 1905 assert(Result.second && "reused a heap alloc index?"); 1906 Result.first->second.AllocExpr = E; 1907 return &Result.first->second.Value; 1908 } 1909 1910 /// Produce a string describing the given constexpr call. 1911 void CallStackFrame::describe(raw_ostream &Out) { 1912 unsigned ArgIndex = 0; 1913 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1914 !isa<CXXConstructorDecl>(Callee) && 1915 cast<CXXMethodDecl>(Callee)->isInstance(); 1916 1917 if (!IsMemberCall) 1918 Out << *Callee << '('; 1919 1920 if (This && IsMemberCall) { 1921 APValue Val; 1922 This->moveInto(Val); 1923 Val.printPretty(Out, Info.Ctx, 1924 This->Designator.MostDerivedType); 1925 // FIXME: Add parens around Val if needed. 1926 Out << "->" << *Callee << '('; 1927 IsMemberCall = false; 1928 } 1929 1930 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1931 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1932 if (ArgIndex > (unsigned)IsMemberCall) 1933 Out << ", "; 1934 1935 const ParmVarDecl *Param = *I; 1936 APValue *V = Info.getParamSlot(Arguments, Param); 1937 if (V) 1938 V->printPretty(Out, Info.Ctx, Param->getType()); 1939 else 1940 Out << "<...>"; 1941 1942 if (ArgIndex == 0 && IsMemberCall) 1943 Out << "->" << *Callee << '('; 1944 } 1945 1946 Out << ')'; 1947 } 1948 1949 /// Evaluate an expression to see if it had side-effects, and discard its 1950 /// result. 1951 /// \return \c true if the caller should keep evaluating. 1952 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1953 assert(!E->isValueDependent()); 1954 APValue Scratch; 1955 if (!Evaluate(Scratch, Info, E)) 1956 // We don't need the value, but we might have skipped a side effect here. 1957 return Info.noteSideEffect(); 1958 return true; 1959 } 1960 1961 /// Should this call expression be treated as a string literal? 1962 static bool IsStringLiteralCall(const CallExpr *E) { 1963 unsigned Builtin = E->getBuiltinCallee(); 1964 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1965 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1966 } 1967 1968 static bool IsGlobalLValue(APValue::LValueBase B) { 1969 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1970 // constant expression of pointer type that evaluates to... 1971 1972 // ... a null pointer value, or a prvalue core constant expression of type 1973 // std::nullptr_t. 1974 if (!B) return true; 1975 1976 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1977 // ... the address of an object with static storage duration, 1978 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1979 return VD->hasGlobalStorage(); 1980 if (isa<TemplateParamObjectDecl>(D)) 1981 return true; 1982 // ... the address of a function, 1983 // ... the address of a GUID [MS extension], 1984 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1985 } 1986 1987 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1988 return true; 1989 1990 const Expr *E = B.get<const Expr*>(); 1991 switch (E->getStmtClass()) { 1992 default: 1993 return false; 1994 case Expr::CompoundLiteralExprClass: { 1995 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1996 return CLE->isFileScope() && CLE->isLValue(); 1997 } 1998 case Expr::MaterializeTemporaryExprClass: 1999 // A materialized temporary might have been lifetime-extended to static 2000 // storage duration. 2001 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 2002 // A string literal has static storage duration. 2003 case Expr::StringLiteralClass: 2004 case Expr::PredefinedExprClass: 2005 case Expr::ObjCStringLiteralClass: 2006 case Expr::ObjCEncodeExprClass: 2007 return true; 2008 case Expr::ObjCBoxedExprClass: 2009 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2010 case Expr::CallExprClass: 2011 return IsStringLiteralCall(cast<CallExpr>(E)); 2012 // For GCC compatibility, &&label has static storage duration. 2013 case Expr::AddrLabelExprClass: 2014 return true; 2015 // A Block literal expression may be used as the initialization value for 2016 // Block variables at global or local static scope. 2017 case Expr::BlockExprClass: 2018 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2019 case Expr::ImplicitValueInitExprClass: 2020 // FIXME: 2021 // We can never form an lvalue with an implicit value initialization as its 2022 // base through expression evaluation, so these only appear in one case: the 2023 // implicit variable declaration we invent when checking whether a constexpr 2024 // constructor can produce a constant expression. We must assume that such 2025 // an expression might be a global lvalue. 2026 return true; 2027 } 2028 } 2029 2030 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2031 return LVal.Base.dyn_cast<const ValueDecl*>(); 2032 } 2033 2034 static bool IsLiteralLValue(const LValue &Value) { 2035 if (Value.getLValueCallIndex()) 2036 return false; 2037 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2038 return E && !isa<MaterializeTemporaryExpr>(E); 2039 } 2040 2041 static bool IsWeakLValue(const LValue &Value) { 2042 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2043 return Decl && Decl->isWeak(); 2044 } 2045 2046 static bool isZeroSized(const LValue &Value) { 2047 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2048 if (Decl && isa<VarDecl>(Decl)) { 2049 QualType Ty = Decl->getType(); 2050 if (Ty->isArrayType()) 2051 return Ty->isIncompleteType() || 2052 Decl->getASTContext().getTypeSize(Ty) == 0; 2053 } 2054 return false; 2055 } 2056 2057 static bool HasSameBase(const LValue &A, const LValue &B) { 2058 if (!A.getLValueBase()) 2059 return !B.getLValueBase(); 2060 if (!B.getLValueBase()) 2061 return false; 2062 2063 if (A.getLValueBase().getOpaqueValue() != 2064 B.getLValueBase().getOpaqueValue()) 2065 return false; 2066 2067 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2068 A.getLValueVersion() == B.getLValueVersion(); 2069 } 2070 2071 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2072 assert(Base && "no location for a null lvalue"); 2073 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2074 2075 // For a parameter, find the corresponding call stack frame (if it still 2076 // exists), and point at the parameter of the function definition we actually 2077 // invoked. 2078 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2079 unsigned Idx = PVD->getFunctionScopeIndex(); 2080 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2081 if (F->Arguments.CallIndex == Base.getCallIndex() && 2082 F->Arguments.Version == Base.getVersion() && F->Callee && 2083 Idx < F->Callee->getNumParams()) { 2084 VD = F->Callee->getParamDecl(Idx); 2085 break; 2086 } 2087 } 2088 } 2089 2090 if (VD) 2091 Info.Note(VD->getLocation(), diag::note_declared_at); 2092 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2093 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2094 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2095 // FIXME: Produce a note for dangling pointers too. 2096 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2097 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2098 diag::note_constexpr_dynamic_alloc_here); 2099 } 2100 // We have no information to show for a typeid(T) object. 2101 } 2102 2103 enum class CheckEvaluationResultKind { 2104 ConstantExpression, 2105 FullyInitialized, 2106 }; 2107 2108 /// Materialized temporaries that we've already checked to determine if they're 2109 /// initializsed by a constant expression. 2110 using CheckedTemporaries = 2111 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2112 2113 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2114 EvalInfo &Info, SourceLocation DiagLoc, 2115 QualType Type, const APValue &Value, 2116 ConstantExprKind Kind, 2117 SourceLocation SubobjectLoc, 2118 CheckedTemporaries &CheckedTemps); 2119 2120 /// Check that this reference or pointer core constant expression is a valid 2121 /// value for an address or reference constant expression. Return true if we 2122 /// can fold this expression, whether or not it's a constant expression. 2123 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2124 QualType Type, const LValue &LVal, 2125 ConstantExprKind Kind, 2126 CheckedTemporaries &CheckedTemps) { 2127 bool IsReferenceType = Type->isReferenceType(); 2128 2129 APValue::LValueBase Base = LVal.getLValueBase(); 2130 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2131 2132 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2133 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2134 2135 // Additional restrictions apply in a template argument. We only enforce the 2136 // C++20 restrictions here; additional syntactic and semantic restrictions 2137 // are applied elsewhere. 2138 if (isTemplateArgument(Kind)) { 2139 int InvalidBaseKind = -1; 2140 StringRef Ident; 2141 if (Base.is<TypeInfoLValue>()) 2142 InvalidBaseKind = 0; 2143 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2144 InvalidBaseKind = 1; 2145 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2146 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2147 InvalidBaseKind = 2; 2148 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2149 InvalidBaseKind = 3; 2150 Ident = PE->getIdentKindName(); 2151 } 2152 2153 if (InvalidBaseKind != -1) { 2154 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2155 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2156 << Ident; 2157 return false; 2158 } 2159 } 2160 2161 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2162 if (FD->isConsteval()) { 2163 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2164 << !Type->isAnyPointerType(); 2165 Info.Note(FD->getLocation(), diag::note_declared_at); 2166 return false; 2167 } 2168 } 2169 2170 // Check that the object is a global. Note that the fake 'this' object we 2171 // manufacture when checking potential constant expressions is conservatively 2172 // assumed to be global here. 2173 if (!IsGlobalLValue(Base)) { 2174 if (Info.getLangOpts().CPlusPlus11) { 2175 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2176 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2177 << IsReferenceType << !Designator.Entries.empty() 2178 << !!VD << VD; 2179 2180 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2181 if (VarD && VarD->isConstexpr()) { 2182 // Non-static local constexpr variables have unintuitive semantics: 2183 // constexpr int a = 1; 2184 // constexpr const int *p = &a; 2185 // ... is invalid because the address of 'a' is not constant. Suggest 2186 // adding a 'static' in this case. 2187 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2188 << VarD 2189 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2190 } else { 2191 NoteLValueLocation(Info, Base); 2192 } 2193 } else { 2194 Info.FFDiag(Loc); 2195 } 2196 // Don't allow references to temporaries to escape. 2197 return false; 2198 } 2199 assert((Info.checkingPotentialConstantExpression() || 2200 LVal.getLValueCallIndex() == 0) && 2201 "have call index for global lvalue"); 2202 2203 if (Base.is<DynamicAllocLValue>()) { 2204 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2205 << IsReferenceType << !Designator.Entries.empty(); 2206 NoteLValueLocation(Info, Base); 2207 return false; 2208 } 2209 2210 if (BaseVD) { 2211 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2212 // Check if this is a thread-local variable. 2213 if (Var->getTLSKind()) 2214 // FIXME: Diagnostic! 2215 return false; 2216 2217 // A dllimport variable never acts like a constant, unless we're 2218 // evaluating a value for use only in name mangling. 2219 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2220 // FIXME: Diagnostic! 2221 return false; 2222 } 2223 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2224 // __declspec(dllimport) must be handled very carefully: 2225 // We must never initialize an expression with the thunk in C++. 2226 // Doing otherwise would allow the same id-expression to yield 2227 // different addresses for the same function in different translation 2228 // units. However, this means that we must dynamically initialize the 2229 // expression with the contents of the import address table at runtime. 2230 // 2231 // The C language has no notion of ODR; furthermore, it has no notion of 2232 // dynamic initialization. This means that we are permitted to 2233 // perform initialization with the address of the thunk. 2234 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2235 FD->hasAttr<DLLImportAttr>()) 2236 // FIXME: Diagnostic! 2237 return false; 2238 } 2239 } else if (const auto *MTE = 2240 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2241 if (CheckedTemps.insert(MTE).second) { 2242 QualType TempType = getType(Base); 2243 if (TempType.isDestructedType()) { 2244 Info.FFDiag(MTE->getExprLoc(), 2245 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2246 << TempType; 2247 return false; 2248 } 2249 2250 APValue *V = MTE->getOrCreateValue(false); 2251 assert(V && "evasluation result refers to uninitialised temporary"); 2252 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2253 Info, MTE->getExprLoc(), TempType, *V, 2254 Kind, SourceLocation(), CheckedTemps)) 2255 return false; 2256 } 2257 } 2258 2259 // Allow address constant expressions to be past-the-end pointers. This is 2260 // an extension: the standard requires them to point to an object. 2261 if (!IsReferenceType) 2262 return true; 2263 2264 // A reference constant expression must refer to an object. 2265 if (!Base) { 2266 // FIXME: diagnostic 2267 Info.CCEDiag(Loc); 2268 return true; 2269 } 2270 2271 // Does this refer one past the end of some object? 2272 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2273 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2274 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2275 NoteLValueLocation(Info, Base); 2276 } 2277 2278 return true; 2279 } 2280 2281 /// Member pointers are constant expressions unless they point to a 2282 /// non-virtual dllimport member function. 2283 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2284 SourceLocation Loc, 2285 QualType Type, 2286 const APValue &Value, 2287 ConstantExprKind Kind) { 2288 const ValueDecl *Member = Value.getMemberPointerDecl(); 2289 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2290 if (!FD) 2291 return true; 2292 if (FD->isConsteval()) { 2293 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2294 Info.Note(FD->getLocation(), diag::note_declared_at); 2295 return false; 2296 } 2297 return isForManglingOnly(Kind) || FD->isVirtual() || 2298 !FD->hasAttr<DLLImportAttr>(); 2299 } 2300 2301 /// Check that this core constant expression is of literal type, and if not, 2302 /// produce an appropriate diagnostic. 2303 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2304 const LValue *This = nullptr) { 2305 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2306 return true; 2307 2308 // C++1y: A constant initializer for an object o [...] may also invoke 2309 // constexpr constructors for o and its subobjects even if those objects 2310 // are of non-literal class types. 2311 // 2312 // C++11 missed this detail for aggregates, so classes like this: 2313 // struct foo_t { union { int i; volatile int j; } u; }; 2314 // are not (obviously) initializable like so: 2315 // __attribute__((__require_constant_initialization__)) 2316 // static const foo_t x = {{0}}; 2317 // because "i" is a subobject with non-literal initialization (due to the 2318 // volatile member of the union). See: 2319 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2320 // Therefore, we use the C++1y behavior. 2321 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2322 return true; 2323 2324 // Prvalue constant expressions must be of literal types. 2325 if (Info.getLangOpts().CPlusPlus11) 2326 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2327 << E->getType(); 2328 else 2329 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2330 return false; 2331 } 2332 2333 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2334 EvalInfo &Info, SourceLocation DiagLoc, 2335 QualType Type, const APValue &Value, 2336 ConstantExprKind Kind, 2337 SourceLocation SubobjectLoc, 2338 CheckedTemporaries &CheckedTemps) { 2339 if (!Value.hasValue()) { 2340 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2341 << true << Type; 2342 if (SubobjectLoc.isValid()) 2343 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2344 return false; 2345 } 2346 2347 // We allow _Atomic(T) to be initialized from anything that T can be 2348 // initialized from. 2349 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2350 Type = AT->getValueType(); 2351 2352 // Core issue 1454: For a literal constant expression of array or class type, 2353 // each subobject of its value shall have been initialized by a constant 2354 // expression. 2355 if (Value.isArray()) { 2356 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2357 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2358 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2359 Value.getArrayInitializedElt(I), Kind, 2360 SubobjectLoc, CheckedTemps)) 2361 return false; 2362 } 2363 if (!Value.hasArrayFiller()) 2364 return true; 2365 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2366 Value.getArrayFiller(), Kind, SubobjectLoc, 2367 CheckedTemps); 2368 } 2369 if (Value.isUnion() && Value.getUnionField()) { 2370 return CheckEvaluationResult( 2371 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2372 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2373 CheckedTemps); 2374 } 2375 if (Value.isStruct()) { 2376 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2377 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2378 unsigned BaseIndex = 0; 2379 for (const CXXBaseSpecifier &BS : CD->bases()) { 2380 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2381 Value.getStructBase(BaseIndex), Kind, 2382 BS.getBeginLoc(), CheckedTemps)) 2383 return false; 2384 ++BaseIndex; 2385 } 2386 } 2387 for (const auto *I : RD->fields()) { 2388 if (I->isUnnamedBitfield()) 2389 continue; 2390 2391 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2392 Value.getStructField(I->getFieldIndex()), 2393 Kind, I->getLocation(), CheckedTemps)) 2394 return false; 2395 } 2396 } 2397 2398 if (Value.isLValue() && 2399 CERK == CheckEvaluationResultKind::ConstantExpression) { 2400 LValue LVal; 2401 LVal.setFrom(Info.Ctx, Value); 2402 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2403 CheckedTemps); 2404 } 2405 2406 if (Value.isMemberPointer() && 2407 CERK == CheckEvaluationResultKind::ConstantExpression) 2408 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2409 2410 // Everything else is fine. 2411 return true; 2412 } 2413 2414 /// Check that this core constant expression value is a valid value for a 2415 /// constant expression. If not, report an appropriate diagnostic. Does not 2416 /// check that the expression is of literal type. 2417 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2418 QualType Type, const APValue &Value, 2419 ConstantExprKind Kind) { 2420 // Nothing to check for a constant expression of type 'cv void'. 2421 if (Type->isVoidType()) 2422 return true; 2423 2424 CheckedTemporaries CheckedTemps; 2425 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2426 Info, DiagLoc, Type, Value, Kind, 2427 SourceLocation(), CheckedTemps); 2428 } 2429 2430 /// Check that this evaluated value is fully-initialized and can be loaded by 2431 /// an lvalue-to-rvalue conversion. 2432 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2433 QualType Type, const APValue &Value) { 2434 CheckedTemporaries CheckedTemps; 2435 return CheckEvaluationResult( 2436 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2437 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2438 } 2439 2440 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2441 /// "the allocated storage is deallocated within the evaluation". 2442 static bool CheckMemoryLeaks(EvalInfo &Info) { 2443 if (!Info.HeapAllocs.empty()) { 2444 // We can still fold to a constant despite a compile-time memory leak, 2445 // so long as the heap allocation isn't referenced in the result (we check 2446 // that in CheckConstantExpression). 2447 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2448 diag::note_constexpr_memory_leak) 2449 << unsigned(Info.HeapAllocs.size() - 1); 2450 } 2451 return true; 2452 } 2453 2454 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2455 // A null base expression indicates a null pointer. These are always 2456 // evaluatable, and they are false unless the offset is zero. 2457 if (!Value.getLValueBase()) { 2458 Result = !Value.getLValueOffset().isZero(); 2459 return true; 2460 } 2461 2462 // We have a non-null base. These are generally known to be true, but if it's 2463 // a weak declaration it can be null at runtime. 2464 Result = true; 2465 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2466 return !Decl || !Decl->isWeak(); 2467 } 2468 2469 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2470 switch (Val.getKind()) { 2471 case APValue::None: 2472 case APValue::Indeterminate: 2473 return false; 2474 case APValue::Int: 2475 Result = Val.getInt().getBoolValue(); 2476 return true; 2477 case APValue::FixedPoint: 2478 Result = Val.getFixedPoint().getBoolValue(); 2479 return true; 2480 case APValue::Float: 2481 Result = !Val.getFloat().isZero(); 2482 return true; 2483 case APValue::ComplexInt: 2484 Result = Val.getComplexIntReal().getBoolValue() || 2485 Val.getComplexIntImag().getBoolValue(); 2486 return true; 2487 case APValue::ComplexFloat: 2488 Result = !Val.getComplexFloatReal().isZero() || 2489 !Val.getComplexFloatImag().isZero(); 2490 return true; 2491 case APValue::LValue: 2492 return EvalPointerValueAsBool(Val, Result); 2493 case APValue::MemberPointer: 2494 Result = Val.getMemberPointerDecl(); 2495 return true; 2496 case APValue::Vector: 2497 case APValue::Array: 2498 case APValue::Struct: 2499 case APValue::Union: 2500 case APValue::AddrLabelDiff: 2501 return false; 2502 } 2503 2504 llvm_unreachable("unknown APValue kind"); 2505 } 2506 2507 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2508 EvalInfo &Info) { 2509 assert(!E->isValueDependent()); 2510 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2511 APValue Val; 2512 if (!Evaluate(Val, Info, E)) 2513 return false; 2514 return HandleConversionToBool(Val, Result); 2515 } 2516 2517 template<typename T> 2518 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2519 const T &SrcValue, QualType DestType) { 2520 Info.CCEDiag(E, diag::note_constexpr_overflow) 2521 << SrcValue << DestType; 2522 return Info.noteUndefinedBehavior(); 2523 } 2524 2525 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2526 QualType SrcType, const APFloat &Value, 2527 QualType DestType, APSInt &Result) { 2528 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2529 // Determine whether we are converting to unsigned or signed. 2530 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2531 2532 Result = APSInt(DestWidth, !DestSigned); 2533 bool ignored; 2534 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2535 & APFloat::opInvalidOp) 2536 return HandleOverflow(Info, E, Value, DestType); 2537 return true; 2538 } 2539 2540 /// Get rounding mode used for evaluation of the specified expression. 2541 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2542 /// dynamic. 2543 /// If rounding mode is unknown at compile time, still try to evaluate the 2544 /// expression. If the result is exact, it does not depend on rounding mode. 2545 /// So return "tonearest" mode instead of "dynamic". 2546 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2547 bool &DynamicRM) { 2548 llvm::RoundingMode RM = 2549 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2550 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2551 if (DynamicRM) 2552 RM = llvm::RoundingMode::NearestTiesToEven; 2553 return RM; 2554 } 2555 2556 /// Check if the given evaluation result is allowed for constant evaluation. 2557 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2558 APFloat::opStatus St) { 2559 // In a constant context, assume that any dynamic rounding mode or FP 2560 // exception state matches the default floating-point environment. 2561 if (Info.InConstantContext) 2562 return true; 2563 2564 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2565 if ((St & APFloat::opInexact) && 2566 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2567 // Inexact result means that it depends on rounding mode. If the requested 2568 // mode is dynamic, the evaluation cannot be made in compile time. 2569 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2570 return false; 2571 } 2572 2573 if ((St != APFloat::opOK) && 2574 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2575 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2576 FPO.getAllowFEnvAccess())) { 2577 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2578 return false; 2579 } 2580 2581 if ((St & APFloat::opStatus::opInvalidOp) && 2582 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2583 // There is no usefully definable result. 2584 Info.FFDiag(E); 2585 return false; 2586 } 2587 2588 // FIXME: if: 2589 // - evaluation triggered other FP exception, and 2590 // - exception mode is not "ignore", and 2591 // - the expression being evaluated is not a part of global variable 2592 // initializer, 2593 // the evaluation probably need to be rejected. 2594 return true; 2595 } 2596 2597 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2598 QualType SrcType, QualType DestType, 2599 APFloat &Result) { 2600 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2601 bool DynamicRM; 2602 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2603 APFloat::opStatus St; 2604 APFloat Value = Result; 2605 bool ignored; 2606 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2607 return checkFloatingPointResult(Info, E, St); 2608 } 2609 2610 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2611 QualType DestType, QualType SrcType, 2612 const APSInt &Value) { 2613 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2614 // Figure out if this is a truncate, extend or noop cast. 2615 // If the input is signed, do a sign extend, noop, or truncate. 2616 APSInt Result = Value.extOrTrunc(DestWidth); 2617 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2618 if (DestType->isBooleanType()) 2619 Result = Value.getBoolValue(); 2620 return Result; 2621 } 2622 2623 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2624 const FPOptions FPO, 2625 QualType SrcType, const APSInt &Value, 2626 QualType DestType, APFloat &Result) { 2627 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2628 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2629 APFloat::rmNearestTiesToEven); 2630 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2631 FPO.isFPConstrained()) { 2632 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2633 return false; 2634 } 2635 return true; 2636 } 2637 2638 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2639 APValue &Value, const FieldDecl *FD) { 2640 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2641 2642 if (!Value.isInt()) { 2643 // Trying to store a pointer-cast-to-integer into a bitfield. 2644 // FIXME: In this case, we should provide the diagnostic for casting 2645 // a pointer to an integer. 2646 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2647 Info.FFDiag(E); 2648 return false; 2649 } 2650 2651 APSInt &Int = Value.getInt(); 2652 unsigned OldBitWidth = Int.getBitWidth(); 2653 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2654 if (NewBitWidth < OldBitWidth) 2655 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2656 return true; 2657 } 2658 2659 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2660 llvm::APInt &Res) { 2661 APValue SVal; 2662 if (!Evaluate(SVal, Info, E)) 2663 return false; 2664 if (SVal.isInt()) { 2665 Res = SVal.getInt(); 2666 return true; 2667 } 2668 if (SVal.isFloat()) { 2669 Res = SVal.getFloat().bitcastToAPInt(); 2670 return true; 2671 } 2672 if (SVal.isVector()) { 2673 QualType VecTy = E->getType(); 2674 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2675 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2676 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2677 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2678 Res = llvm::APInt::getZero(VecSize); 2679 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2680 APValue &Elt = SVal.getVectorElt(i); 2681 llvm::APInt EltAsInt; 2682 if (Elt.isInt()) { 2683 EltAsInt = Elt.getInt(); 2684 } else if (Elt.isFloat()) { 2685 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2686 } else { 2687 // Don't try to handle vectors of anything other than int or float 2688 // (not sure if it's possible to hit this case). 2689 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2690 return false; 2691 } 2692 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2693 if (BigEndian) 2694 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2695 else 2696 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2697 } 2698 return true; 2699 } 2700 // Give up if the input isn't an int, float, or vector. For example, we 2701 // reject "(v4i16)(intptr_t)&a". 2702 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2703 return false; 2704 } 2705 2706 /// Perform the given integer operation, which is known to need at most BitWidth 2707 /// bits, and check for overflow in the original type (if that type was not an 2708 /// unsigned type). 2709 template<typename Operation> 2710 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2711 const APSInt &LHS, const APSInt &RHS, 2712 unsigned BitWidth, Operation Op, 2713 APSInt &Result) { 2714 if (LHS.isUnsigned()) { 2715 Result = Op(LHS, RHS); 2716 return true; 2717 } 2718 2719 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2720 Result = Value.trunc(LHS.getBitWidth()); 2721 if (Result.extend(BitWidth) != Value) { 2722 if (Info.checkingForUndefinedBehavior()) 2723 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2724 diag::warn_integer_constant_overflow) 2725 << toString(Result, 10) << E->getType(); 2726 return HandleOverflow(Info, E, Value, E->getType()); 2727 } 2728 return true; 2729 } 2730 2731 /// Perform the given binary integer operation. 2732 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2733 BinaryOperatorKind Opcode, APSInt RHS, 2734 APSInt &Result) { 2735 switch (Opcode) { 2736 default: 2737 Info.FFDiag(E); 2738 return false; 2739 case BO_Mul: 2740 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2741 std::multiplies<APSInt>(), Result); 2742 case BO_Add: 2743 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2744 std::plus<APSInt>(), Result); 2745 case BO_Sub: 2746 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2747 std::minus<APSInt>(), Result); 2748 case BO_And: Result = LHS & RHS; return true; 2749 case BO_Xor: Result = LHS ^ RHS; return true; 2750 case BO_Or: Result = LHS | RHS; return true; 2751 case BO_Div: 2752 case BO_Rem: 2753 if (RHS == 0) { 2754 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2755 return false; 2756 } 2757 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2758 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2759 // this operation and gives the two's complement result. 2760 if (RHS.isNegative() && RHS.isAllOnesValue() && 2761 LHS.isSigned() && LHS.isMinSignedValue()) 2762 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2763 E->getType()); 2764 return true; 2765 case BO_Shl: { 2766 if (Info.getLangOpts().OpenCL) 2767 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2768 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2769 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2770 RHS.isUnsigned()); 2771 else if (RHS.isSigned() && RHS.isNegative()) { 2772 // During constant-folding, a negative shift is an opposite shift. Such 2773 // a shift is not a constant expression. 2774 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2775 RHS = -RHS; 2776 goto shift_right; 2777 } 2778 shift_left: 2779 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2780 // the shifted type. 2781 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2782 if (SA != RHS) { 2783 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2784 << RHS << E->getType() << LHS.getBitWidth(); 2785 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2786 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2787 // operand, and must not overflow the corresponding unsigned type. 2788 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2789 // E1 x 2^E2 module 2^N. 2790 if (LHS.isNegative()) 2791 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2792 else if (LHS.countLeadingZeros() < SA) 2793 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2794 } 2795 Result = LHS << SA; 2796 return true; 2797 } 2798 case BO_Shr: { 2799 if (Info.getLangOpts().OpenCL) 2800 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2801 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2802 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2803 RHS.isUnsigned()); 2804 else if (RHS.isSigned() && RHS.isNegative()) { 2805 // During constant-folding, a negative shift is an opposite shift. Such a 2806 // shift is not a constant expression. 2807 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2808 RHS = -RHS; 2809 goto shift_left; 2810 } 2811 shift_right: 2812 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2813 // shifted type. 2814 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2815 if (SA != RHS) 2816 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2817 << RHS << E->getType() << LHS.getBitWidth(); 2818 Result = LHS >> SA; 2819 return true; 2820 } 2821 2822 case BO_LT: Result = LHS < RHS; return true; 2823 case BO_GT: Result = LHS > RHS; return true; 2824 case BO_LE: Result = LHS <= RHS; return true; 2825 case BO_GE: Result = LHS >= RHS; return true; 2826 case BO_EQ: Result = LHS == RHS; return true; 2827 case BO_NE: Result = LHS != RHS; return true; 2828 case BO_Cmp: 2829 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2830 } 2831 } 2832 2833 /// Perform the given binary floating-point operation, in-place, on LHS. 2834 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2835 APFloat &LHS, BinaryOperatorKind Opcode, 2836 const APFloat &RHS) { 2837 bool DynamicRM; 2838 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2839 APFloat::opStatus St; 2840 switch (Opcode) { 2841 default: 2842 Info.FFDiag(E); 2843 return false; 2844 case BO_Mul: 2845 St = LHS.multiply(RHS, RM); 2846 break; 2847 case BO_Add: 2848 St = LHS.add(RHS, RM); 2849 break; 2850 case BO_Sub: 2851 St = LHS.subtract(RHS, RM); 2852 break; 2853 case BO_Div: 2854 // [expr.mul]p4: 2855 // If the second operand of / or % is zero the behavior is undefined. 2856 if (RHS.isZero()) 2857 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2858 St = LHS.divide(RHS, RM); 2859 break; 2860 } 2861 2862 // [expr.pre]p4: 2863 // If during the evaluation of an expression, the result is not 2864 // mathematically defined [...], the behavior is undefined. 2865 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2866 if (LHS.isNaN()) { 2867 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2868 return Info.noteUndefinedBehavior(); 2869 } 2870 2871 return checkFloatingPointResult(Info, E, St); 2872 } 2873 2874 static bool handleLogicalOpForVector(const APInt &LHSValue, 2875 BinaryOperatorKind Opcode, 2876 const APInt &RHSValue, APInt &Result) { 2877 bool LHS = (LHSValue != 0); 2878 bool RHS = (RHSValue != 0); 2879 2880 if (Opcode == BO_LAnd) 2881 Result = LHS && RHS; 2882 else 2883 Result = LHS || RHS; 2884 return true; 2885 } 2886 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2887 BinaryOperatorKind Opcode, 2888 const APFloat &RHSValue, APInt &Result) { 2889 bool LHS = !LHSValue.isZero(); 2890 bool RHS = !RHSValue.isZero(); 2891 2892 if (Opcode == BO_LAnd) 2893 Result = LHS && RHS; 2894 else 2895 Result = LHS || RHS; 2896 return true; 2897 } 2898 2899 static bool handleLogicalOpForVector(const APValue &LHSValue, 2900 BinaryOperatorKind Opcode, 2901 const APValue &RHSValue, APInt &Result) { 2902 // The result is always an int type, however operands match the first. 2903 if (LHSValue.getKind() == APValue::Int) 2904 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2905 RHSValue.getInt(), Result); 2906 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2907 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2908 RHSValue.getFloat(), Result); 2909 } 2910 2911 template <typename APTy> 2912 static bool 2913 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2914 const APTy &RHSValue, APInt &Result) { 2915 switch (Opcode) { 2916 default: 2917 llvm_unreachable("unsupported binary operator"); 2918 case BO_EQ: 2919 Result = (LHSValue == RHSValue); 2920 break; 2921 case BO_NE: 2922 Result = (LHSValue != RHSValue); 2923 break; 2924 case BO_LT: 2925 Result = (LHSValue < RHSValue); 2926 break; 2927 case BO_GT: 2928 Result = (LHSValue > RHSValue); 2929 break; 2930 case BO_LE: 2931 Result = (LHSValue <= RHSValue); 2932 break; 2933 case BO_GE: 2934 Result = (LHSValue >= RHSValue); 2935 break; 2936 } 2937 2938 return true; 2939 } 2940 2941 static bool handleCompareOpForVector(const APValue &LHSValue, 2942 BinaryOperatorKind Opcode, 2943 const APValue &RHSValue, APInt &Result) { 2944 // The result is always an int type, however operands match the first. 2945 if (LHSValue.getKind() == APValue::Int) 2946 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2947 RHSValue.getInt(), Result); 2948 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2949 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2950 RHSValue.getFloat(), Result); 2951 } 2952 2953 // Perform binary operations for vector types, in place on the LHS. 2954 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2955 BinaryOperatorKind Opcode, 2956 APValue &LHSValue, 2957 const APValue &RHSValue) { 2958 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2959 "Operation not supported on vector types"); 2960 2961 const auto *VT = E->getType()->castAs<VectorType>(); 2962 unsigned NumElements = VT->getNumElements(); 2963 QualType EltTy = VT->getElementType(); 2964 2965 // In the cases (typically C as I've observed) where we aren't evaluating 2966 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2967 // just give up. 2968 if (!LHSValue.isVector()) { 2969 assert(LHSValue.isLValue() && 2970 "A vector result that isn't a vector OR uncalculated LValue"); 2971 Info.FFDiag(E); 2972 return false; 2973 } 2974 2975 assert(LHSValue.getVectorLength() == NumElements && 2976 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2977 2978 SmallVector<APValue, 4> ResultElements; 2979 2980 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2981 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2982 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2983 2984 if (EltTy->isIntegerType()) { 2985 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2986 EltTy->isUnsignedIntegerType()}; 2987 bool Success = true; 2988 2989 if (BinaryOperator::isLogicalOp(Opcode)) 2990 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2991 else if (BinaryOperator::isComparisonOp(Opcode)) 2992 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2993 else 2994 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2995 RHSElt.getInt(), EltResult); 2996 2997 if (!Success) { 2998 Info.FFDiag(E); 2999 return false; 3000 } 3001 ResultElements.emplace_back(EltResult); 3002 3003 } else if (EltTy->isFloatingType()) { 3004 assert(LHSElt.getKind() == APValue::Float && 3005 RHSElt.getKind() == APValue::Float && 3006 "Mismatched LHS/RHS/Result Type"); 3007 APFloat LHSFloat = LHSElt.getFloat(); 3008 3009 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3010 RHSElt.getFloat())) { 3011 Info.FFDiag(E); 3012 return false; 3013 } 3014 3015 ResultElements.emplace_back(LHSFloat); 3016 } 3017 } 3018 3019 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3020 return true; 3021 } 3022 3023 /// Cast an lvalue referring to a base subobject to a derived class, by 3024 /// truncating the lvalue's path to the given length. 3025 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3026 const RecordDecl *TruncatedType, 3027 unsigned TruncatedElements) { 3028 SubobjectDesignator &D = Result.Designator; 3029 3030 // Check we actually point to a derived class object. 3031 if (TruncatedElements == D.Entries.size()) 3032 return true; 3033 assert(TruncatedElements >= D.MostDerivedPathLength && 3034 "not casting to a derived class"); 3035 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3036 return false; 3037 3038 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3039 const RecordDecl *RD = TruncatedType; 3040 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3041 if (RD->isInvalidDecl()) return false; 3042 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3043 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3044 if (isVirtualBaseClass(D.Entries[I])) 3045 Result.Offset -= Layout.getVBaseClassOffset(Base); 3046 else 3047 Result.Offset -= Layout.getBaseClassOffset(Base); 3048 RD = Base; 3049 } 3050 D.Entries.resize(TruncatedElements); 3051 return true; 3052 } 3053 3054 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3055 const CXXRecordDecl *Derived, 3056 const CXXRecordDecl *Base, 3057 const ASTRecordLayout *RL = nullptr) { 3058 if (!RL) { 3059 if (Derived->isInvalidDecl()) return false; 3060 RL = &Info.Ctx.getASTRecordLayout(Derived); 3061 } 3062 3063 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3064 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3065 return true; 3066 } 3067 3068 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3069 const CXXRecordDecl *DerivedDecl, 3070 const CXXBaseSpecifier *Base) { 3071 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3072 3073 if (!Base->isVirtual()) 3074 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3075 3076 SubobjectDesignator &D = Obj.Designator; 3077 if (D.Invalid) 3078 return false; 3079 3080 // Extract most-derived object and corresponding type. 3081 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3082 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3083 return false; 3084 3085 // Find the virtual base class. 3086 if (DerivedDecl->isInvalidDecl()) return false; 3087 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3088 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3089 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3090 return true; 3091 } 3092 3093 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3094 QualType Type, LValue &Result) { 3095 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3096 PathE = E->path_end(); 3097 PathI != PathE; ++PathI) { 3098 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3099 *PathI)) 3100 return false; 3101 Type = (*PathI)->getType(); 3102 } 3103 return true; 3104 } 3105 3106 /// Cast an lvalue referring to a derived class to a known base subobject. 3107 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3108 const CXXRecordDecl *DerivedRD, 3109 const CXXRecordDecl *BaseRD) { 3110 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3111 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3112 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3113 llvm_unreachable("Class must be derived from the passed in base class!"); 3114 3115 for (CXXBasePathElement &Elem : Paths.front()) 3116 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3117 return false; 3118 return true; 3119 } 3120 3121 /// Update LVal to refer to the given field, which must be a member of the type 3122 /// currently described by LVal. 3123 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3124 const FieldDecl *FD, 3125 const ASTRecordLayout *RL = nullptr) { 3126 if (!RL) { 3127 if (FD->getParent()->isInvalidDecl()) return false; 3128 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3129 } 3130 3131 unsigned I = FD->getFieldIndex(); 3132 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3133 LVal.addDecl(Info, E, FD); 3134 return true; 3135 } 3136 3137 /// Update LVal to refer to the given indirect field. 3138 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3139 LValue &LVal, 3140 const IndirectFieldDecl *IFD) { 3141 for (const auto *C : IFD->chain()) 3142 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3143 return false; 3144 return true; 3145 } 3146 3147 /// Get the size of the given type in char units. 3148 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3149 QualType Type, CharUnits &Size) { 3150 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3151 // extension. 3152 if (Type->isVoidType() || Type->isFunctionType()) { 3153 Size = CharUnits::One(); 3154 return true; 3155 } 3156 3157 if (Type->isDependentType()) { 3158 Info.FFDiag(Loc); 3159 return false; 3160 } 3161 3162 if (!Type->isConstantSizeType()) { 3163 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3164 // FIXME: Better diagnostic. 3165 Info.FFDiag(Loc); 3166 return false; 3167 } 3168 3169 Size = Info.Ctx.getTypeSizeInChars(Type); 3170 return true; 3171 } 3172 3173 /// Update a pointer value to model pointer arithmetic. 3174 /// \param Info - Information about the ongoing evaluation. 3175 /// \param E - The expression being evaluated, for diagnostic purposes. 3176 /// \param LVal - The pointer value to be updated. 3177 /// \param EltTy - The pointee type represented by LVal. 3178 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3179 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3180 LValue &LVal, QualType EltTy, 3181 APSInt Adjustment) { 3182 CharUnits SizeOfPointee; 3183 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3184 return false; 3185 3186 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3187 return true; 3188 } 3189 3190 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3191 LValue &LVal, QualType EltTy, 3192 int64_t Adjustment) { 3193 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3194 APSInt::get(Adjustment)); 3195 } 3196 3197 /// Update an lvalue to refer to a component of a complex number. 3198 /// \param Info - Information about the ongoing evaluation. 3199 /// \param LVal - The lvalue to be updated. 3200 /// \param EltTy - The complex number's component type. 3201 /// \param Imag - False for the real component, true for the imaginary. 3202 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3203 LValue &LVal, QualType EltTy, 3204 bool Imag) { 3205 if (Imag) { 3206 CharUnits SizeOfComponent; 3207 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3208 return false; 3209 LVal.Offset += SizeOfComponent; 3210 } 3211 LVal.addComplex(Info, E, EltTy, Imag); 3212 return true; 3213 } 3214 3215 /// Try to evaluate the initializer for a variable declaration. 3216 /// 3217 /// \param Info Information about the ongoing evaluation. 3218 /// \param E An expression to be used when printing diagnostics. 3219 /// \param VD The variable whose initializer should be obtained. 3220 /// \param Version The version of the variable within the frame. 3221 /// \param Frame The frame in which the variable was created. Must be null 3222 /// if this variable is not local to the evaluation. 3223 /// \param Result Filled in with a pointer to the value of the variable. 3224 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3225 const VarDecl *VD, CallStackFrame *Frame, 3226 unsigned Version, APValue *&Result) { 3227 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3228 3229 // If this is a local variable, dig out its value. 3230 if (Frame) { 3231 Result = Frame->getTemporary(VD, Version); 3232 if (Result) 3233 return true; 3234 3235 if (!isa<ParmVarDecl>(VD)) { 3236 // Assume variables referenced within a lambda's call operator that were 3237 // not declared within the call operator are captures and during checking 3238 // of a potential constant expression, assume they are unknown constant 3239 // expressions. 3240 assert(isLambdaCallOperator(Frame->Callee) && 3241 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3242 "missing value for local variable"); 3243 if (Info.checkingPotentialConstantExpression()) 3244 return false; 3245 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3246 // still reachable at all? 3247 Info.FFDiag(E->getBeginLoc(), 3248 diag::note_unimplemented_constexpr_lambda_feature_ast) 3249 << "captures not currently allowed"; 3250 return false; 3251 } 3252 } 3253 3254 // If we're currently evaluating the initializer of this declaration, use that 3255 // in-flight value. 3256 if (Info.EvaluatingDecl == Base) { 3257 Result = Info.EvaluatingDeclValue; 3258 return true; 3259 } 3260 3261 if (isa<ParmVarDecl>(VD)) { 3262 // Assume parameters of a potential constant expression are usable in 3263 // constant expressions. 3264 if (!Info.checkingPotentialConstantExpression() || 3265 !Info.CurrentCall->Callee || 3266 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3267 if (Info.getLangOpts().CPlusPlus11) { 3268 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3269 << VD; 3270 NoteLValueLocation(Info, Base); 3271 } else { 3272 Info.FFDiag(E); 3273 } 3274 } 3275 return false; 3276 } 3277 3278 // Dig out the initializer, and use the declaration which it's attached to. 3279 // FIXME: We should eventually check whether the variable has a reachable 3280 // initializing declaration. 3281 const Expr *Init = VD->getAnyInitializer(VD); 3282 if (!Init) { 3283 // Don't diagnose during potential constant expression checking; an 3284 // initializer might be added later. 3285 if (!Info.checkingPotentialConstantExpression()) { 3286 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3287 << VD; 3288 NoteLValueLocation(Info, Base); 3289 } 3290 return false; 3291 } 3292 3293 if (Init->isValueDependent()) { 3294 // The DeclRefExpr is not value-dependent, but the variable it refers to 3295 // has a value-dependent initializer. This should only happen in 3296 // constant-folding cases, where the variable is not actually of a suitable 3297 // type for use in a constant expression (otherwise the DeclRefExpr would 3298 // have been value-dependent too), so diagnose that. 3299 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3300 if (!Info.checkingPotentialConstantExpression()) { 3301 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3302 ? diag::note_constexpr_ltor_non_constexpr 3303 : diag::note_constexpr_ltor_non_integral, 1) 3304 << VD << VD->getType(); 3305 NoteLValueLocation(Info, Base); 3306 } 3307 return false; 3308 } 3309 3310 // Check that we can fold the initializer. In C++, we will have already done 3311 // this in the cases where it matters for conformance. 3312 if (!VD->evaluateValue()) { 3313 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3314 NoteLValueLocation(Info, Base); 3315 return false; 3316 } 3317 3318 // Check that the variable is actually usable in constant expressions. For a 3319 // const integral variable or a reference, we might have a non-constant 3320 // initializer that we can nonetheless evaluate the initializer for. Such 3321 // variables are not usable in constant expressions. In C++98, the 3322 // initializer also syntactically needs to be an ICE. 3323 // 3324 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3325 // expressions here; doing so would regress diagnostics for things like 3326 // reading from a volatile constexpr variable. 3327 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3328 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3329 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3330 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3331 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3332 NoteLValueLocation(Info, Base); 3333 } 3334 3335 // Never use the initializer of a weak variable, not even for constant 3336 // folding. We can't be sure that this is the definition that will be used. 3337 if (VD->isWeak()) { 3338 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3339 NoteLValueLocation(Info, Base); 3340 return false; 3341 } 3342 3343 Result = VD->getEvaluatedValue(); 3344 return true; 3345 } 3346 3347 /// Get the base index of the given base class within an APValue representing 3348 /// the given derived class. 3349 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3350 const CXXRecordDecl *Base) { 3351 Base = Base->getCanonicalDecl(); 3352 unsigned Index = 0; 3353 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3354 E = Derived->bases_end(); I != E; ++I, ++Index) { 3355 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3356 return Index; 3357 } 3358 3359 llvm_unreachable("base class missing from derived class's bases list"); 3360 } 3361 3362 /// Extract the value of a character from a string literal. 3363 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3364 uint64_t Index) { 3365 assert(!isa<SourceLocExpr>(Lit) && 3366 "SourceLocExpr should have already been converted to a StringLiteral"); 3367 3368 // FIXME: Support MakeStringConstant 3369 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3370 std::string Str; 3371 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3372 assert(Index <= Str.size() && "Index too large"); 3373 return APSInt::getUnsigned(Str.c_str()[Index]); 3374 } 3375 3376 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3377 Lit = PE->getFunctionName(); 3378 const StringLiteral *S = cast<StringLiteral>(Lit); 3379 const ConstantArrayType *CAT = 3380 Info.Ctx.getAsConstantArrayType(S->getType()); 3381 assert(CAT && "string literal isn't an array"); 3382 QualType CharType = CAT->getElementType(); 3383 assert(CharType->isIntegerType() && "unexpected character type"); 3384 3385 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3386 CharType->isUnsignedIntegerType()); 3387 if (Index < S->getLength()) 3388 Value = S->getCodeUnit(Index); 3389 return Value; 3390 } 3391 3392 // Expand a string literal into an array of characters. 3393 // 3394 // FIXME: This is inefficient; we should probably introduce something similar 3395 // to the LLVM ConstantDataArray to make this cheaper. 3396 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3397 APValue &Result, 3398 QualType AllocType = QualType()) { 3399 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3400 AllocType.isNull() ? S->getType() : AllocType); 3401 assert(CAT && "string literal isn't an array"); 3402 QualType CharType = CAT->getElementType(); 3403 assert(CharType->isIntegerType() && "unexpected character type"); 3404 3405 unsigned Elts = CAT->getSize().getZExtValue(); 3406 Result = APValue(APValue::UninitArray(), 3407 std::min(S->getLength(), Elts), Elts); 3408 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3409 CharType->isUnsignedIntegerType()); 3410 if (Result.hasArrayFiller()) 3411 Result.getArrayFiller() = APValue(Value); 3412 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3413 Value = S->getCodeUnit(I); 3414 Result.getArrayInitializedElt(I) = APValue(Value); 3415 } 3416 } 3417 3418 // Expand an array so that it has more than Index filled elements. 3419 static void expandArray(APValue &Array, unsigned Index) { 3420 unsigned Size = Array.getArraySize(); 3421 assert(Index < Size); 3422 3423 // Always at least double the number of elements for which we store a value. 3424 unsigned OldElts = Array.getArrayInitializedElts(); 3425 unsigned NewElts = std::max(Index+1, OldElts * 2); 3426 NewElts = std::min(Size, std::max(NewElts, 8u)); 3427 3428 // Copy the data across. 3429 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3430 for (unsigned I = 0; I != OldElts; ++I) 3431 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3432 for (unsigned I = OldElts; I != NewElts; ++I) 3433 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3434 if (NewValue.hasArrayFiller()) 3435 NewValue.getArrayFiller() = Array.getArrayFiller(); 3436 Array.swap(NewValue); 3437 } 3438 3439 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3440 /// conversion. If it's of class type, we may assume that the copy operation 3441 /// is trivial. Note that this is never true for a union type with fields 3442 /// (because the copy always "reads" the active member) and always true for 3443 /// a non-class type. 3444 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3445 static bool isReadByLvalueToRvalueConversion(QualType T) { 3446 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3447 return !RD || isReadByLvalueToRvalueConversion(RD); 3448 } 3449 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3450 // FIXME: A trivial copy of a union copies the object representation, even if 3451 // the union is empty. 3452 if (RD->isUnion()) 3453 return !RD->field_empty(); 3454 if (RD->isEmpty()) 3455 return false; 3456 3457 for (auto *Field : RD->fields()) 3458 if (!Field->isUnnamedBitfield() && 3459 isReadByLvalueToRvalueConversion(Field->getType())) 3460 return true; 3461 3462 for (auto &BaseSpec : RD->bases()) 3463 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3464 return true; 3465 3466 return false; 3467 } 3468 3469 /// Diagnose an attempt to read from any unreadable field within the specified 3470 /// type, which might be a class type. 3471 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3472 QualType T) { 3473 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3474 if (!RD) 3475 return false; 3476 3477 if (!RD->hasMutableFields()) 3478 return false; 3479 3480 for (auto *Field : RD->fields()) { 3481 // If we're actually going to read this field in some way, then it can't 3482 // be mutable. If we're in a union, then assigning to a mutable field 3483 // (even an empty one) can change the active member, so that's not OK. 3484 // FIXME: Add core issue number for the union case. 3485 if (Field->isMutable() && 3486 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3487 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3488 Info.Note(Field->getLocation(), diag::note_declared_at); 3489 return true; 3490 } 3491 3492 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3493 return true; 3494 } 3495 3496 for (auto &BaseSpec : RD->bases()) 3497 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3498 return true; 3499 3500 // All mutable fields were empty, and thus not actually read. 3501 return false; 3502 } 3503 3504 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3505 APValue::LValueBase Base, 3506 bool MutableSubobject = false) { 3507 // A temporary or transient heap allocation we created. 3508 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3509 return true; 3510 3511 switch (Info.IsEvaluatingDecl) { 3512 case EvalInfo::EvaluatingDeclKind::None: 3513 return false; 3514 3515 case EvalInfo::EvaluatingDeclKind::Ctor: 3516 // The variable whose initializer we're evaluating. 3517 if (Info.EvaluatingDecl == Base) 3518 return true; 3519 3520 // A temporary lifetime-extended by the variable whose initializer we're 3521 // evaluating. 3522 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3523 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3524 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3525 return false; 3526 3527 case EvalInfo::EvaluatingDeclKind::Dtor: 3528 // C++2a [expr.const]p6: 3529 // [during constant destruction] the lifetime of a and its non-mutable 3530 // subobjects (but not its mutable subobjects) [are] considered to start 3531 // within e. 3532 if (MutableSubobject || Base != Info.EvaluatingDecl) 3533 return false; 3534 // FIXME: We can meaningfully extend this to cover non-const objects, but 3535 // we will need special handling: we should be able to access only 3536 // subobjects of such objects that are themselves declared const. 3537 QualType T = getType(Base); 3538 return T.isConstQualified() || T->isReferenceType(); 3539 } 3540 3541 llvm_unreachable("unknown evaluating decl kind"); 3542 } 3543 3544 namespace { 3545 /// A handle to a complete object (an object that is not a subobject of 3546 /// another object). 3547 struct CompleteObject { 3548 /// The identity of the object. 3549 APValue::LValueBase Base; 3550 /// The value of the complete object. 3551 APValue *Value; 3552 /// The type of the complete object. 3553 QualType Type; 3554 3555 CompleteObject() : Value(nullptr) {} 3556 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3557 : Base(Base), Value(Value), Type(Type) {} 3558 3559 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3560 // If this isn't a "real" access (eg, if it's just accessing the type 3561 // info), allow it. We assume the type doesn't change dynamically for 3562 // subobjects of constexpr objects (even though we'd hit UB here if it 3563 // did). FIXME: Is this right? 3564 if (!isAnyAccess(AK)) 3565 return true; 3566 3567 // In C++14 onwards, it is permitted to read a mutable member whose 3568 // lifetime began within the evaluation. 3569 // FIXME: Should we also allow this in C++11? 3570 if (!Info.getLangOpts().CPlusPlus14) 3571 return false; 3572 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3573 } 3574 3575 explicit operator bool() const { return !Type.isNull(); } 3576 }; 3577 } // end anonymous namespace 3578 3579 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3580 bool IsMutable = false) { 3581 // C++ [basic.type.qualifier]p1: 3582 // - A const object is an object of type const T or a non-mutable subobject 3583 // of a const object. 3584 if (ObjType.isConstQualified() && !IsMutable) 3585 SubobjType.addConst(); 3586 // - A volatile object is an object of type const T or a subobject of a 3587 // volatile object. 3588 if (ObjType.isVolatileQualified()) 3589 SubobjType.addVolatile(); 3590 return SubobjType; 3591 } 3592 3593 /// Find the designated sub-object of an rvalue. 3594 template<typename SubobjectHandler> 3595 typename SubobjectHandler::result_type 3596 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3597 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3598 if (Sub.Invalid) 3599 // A diagnostic will have already been produced. 3600 return handler.failed(); 3601 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3602 if (Info.getLangOpts().CPlusPlus11) 3603 Info.FFDiag(E, Sub.isOnePastTheEnd() 3604 ? diag::note_constexpr_access_past_end 3605 : diag::note_constexpr_access_unsized_array) 3606 << handler.AccessKind; 3607 else 3608 Info.FFDiag(E); 3609 return handler.failed(); 3610 } 3611 3612 APValue *O = Obj.Value; 3613 QualType ObjType = Obj.Type; 3614 const FieldDecl *LastField = nullptr; 3615 const FieldDecl *VolatileField = nullptr; 3616 3617 // Walk the designator's path to find the subobject. 3618 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3619 // Reading an indeterminate value is undefined, but assigning over one is OK. 3620 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3621 (O->isIndeterminate() && 3622 !isValidIndeterminateAccess(handler.AccessKind))) { 3623 if (!Info.checkingPotentialConstantExpression()) 3624 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3625 << handler.AccessKind << O->isIndeterminate(); 3626 return handler.failed(); 3627 } 3628 3629 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3630 // const and volatile semantics are not applied on an object under 3631 // {con,de}struction. 3632 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3633 ObjType->isRecordType() && 3634 Info.isEvaluatingCtorDtor( 3635 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3636 Sub.Entries.begin() + I)) != 3637 ConstructionPhase::None) { 3638 ObjType = Info.Ctx.getCanonicalType(ObjType); 3639 ObjType.removeLocalConst(); 3640 ObjType.removeLocalVolatile(); 3641 } 3642 3643 // If this is our last pass, check that the final object type is OK. 3644 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3645 // Accesses to volatile objects are prohibited. 3646 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3647 if (Info.getLangOpts().CPlusPlus) { 3648 int DiagKind; 3649 SourceLocation Loc; 3650 const NamedDecl *Decl = nullptr; 3651 if (VolatileField) { 3652 DiagKind = 2; 3653 Loc = VolatileField->getLocation(); 3654 Decl = VolatileField; 3655 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3656 DiagKind = 1; 3657 Loc = VD->getLocation(); 3658 Decl = VD; 3659 } else { 3660 DiagKind = 0; 3661 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3662 Loc = E->getExprLoc(); 3663 } 3664 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3665 << handler.AccessKind << DiagKind << Decl; 3666 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3667 } else { 3668 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3669 } 3670 return handler.failed(); 3671 } 3672 3673 // If we are reading an object of class type, there may still be more 3674 // things we need to check: if there are any mutable subobjects, we 3675 // cannot perform this read. (This only happens when performing a trivial 3676 // copy or assignment.) 3677 if (ObjType->isRecordType() && 3678 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3679 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3680 return handler.failed(); 3681 } 3682 3683 if (I == N) { 3684 if (!handler.found(*O, ObjType)) 3685 return false; 3686 3687 // If we modified a bit-field, truncate it to the right width. 3688 if (isModification(handler.AccessKind) && 3689 LastField && LastField->isBitField() && 3690 !truncateBitfieldValue(Info, E, *O, LastField)) 3691 return false; 3692 3693 return true; 3694 } 3695 3696 LastField = nullptr; 3697 if (ObjType->isArrayType()) { 3698 // Next subobject is an array element. 3699 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3700 assert(CAT && "vla in literal type?"); 3701 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3702 if (CAT->getSize().ule(Index)) { 3703 // Note, it should not be possible to form a pointer with a valid 3704 // designator which points more than one past the end of the array. 3705 if (Info.getLangOpts().CPlusPlus11) 3706 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3707 << handler.AccessKind; 3708 else 3709 Info.FFDiag(E); 3710 return handler.failed(); 3711 } 3712 3713 ObjType = CAT->getElementType(); 3714 3715 if (O->getArrayInitializedElts() > Index) 3716 O = &O->getArrayInitializedElt(Index); 3717 else if (!isRead(handler.AccessKind)) { 3718 expandArray(*O, Index); 3719 O = &O->getArrayInitializedElt(Index); 3720 } else 3721 O = &O->getArrayFiller(); 3722 } else if (ObjType->isAnyComplexType()) { 3723 // Next subobject is a complex number. 3724 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3725 if (Index > 1) { 3726 if (Info.getLangOpts().CPlusPlus11) 3727 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3728 << handler.AccessKind; 3729 else 3730 Info.FFDiag(E); 3731 return handler.failed(); 3732 } 3733 3734 ObjType = getSubobjectType( 3735 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3736 3737 assert(I == N - 1 && "extracting subobject of scalar?"); 3738 if (O->isComplexInt()) { 3739 return handler.found(Index ? O->getComplexIntImag() 3740 : O->getComplexIntReal(), ObjType); 3741 } else { 3742 assert(O->isComplexFloat()); 3743 return handler.found(Index ? O->getComplexFloatImag() 3744 : O->getComplexFloatReal(), ObjType); 3745 } 3746 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3747 if (Field->isMutable() && 3748 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3749 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3750 << handler.AccessKind << Field; 3751 Info.Note(Field->getLocation(), diag::note_declared_at); 3752 return handler.failed(); 3753 } 3754 3755 // Next subobject is a class, struct or union field. 3756 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3757 if (RD->isUnion()) { 3758 const FieldDecl *UnionField = O->getUnionField(); 3759 if (!UnionField || 3760 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3761 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3762 // Placement new onto an inactive union member makes it active. 3763 O->setUnion(Field, APValue()); 3764 } else { 3765 // FIXME: If O->getUnionValue() is absent, report that there's no 3766 // active union member rather than reporting the prior active union 3767 // member. We'll need to fix nullptr_t to not use APValue() as its 3768 // representation first. 3769 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3770 << handler.AccessKind << Field << !UnionField << UnionField; 3771 return handler.failed(); 3772 } 3773 } 3774 O = &O->getUnionValue(); 3775 } else 3776 O = &O->getStructField(Field->getFieldIndex()); 3777 3778 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3779 LastField = Field; 3780 if (Field->getType().isVolatileQualified()) 3781 VolatileField = Field; 3782 } else { 3783 // Next subobject is a base class. 3784 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3785 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3786 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3787 3788 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3789 } 3790 } 3791 } 3792 3793 namespace { 3794 struct ExtractSubobjectHandler { 3795 EvalInfo &Info; 3796 const Expr *E; 3797 APValue &Result; 3798 const AccessKinds AccessKind; 3799 3800 typedef bool result_type; 3801 bool failed() { return false; } 3802 bool found(APValue &Subobj, QualType SubobjType) { 3803 Result = Subobj; 3804 if (AccessKind == AK_ReadObjectRepresentation) 3805 return true; 3806 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3807 } 3808 bool found(APSInt &Value, QualType SubobjType) { 3809 Result = APValue(Value); 3810 return true; 3811 } 3812 bool found(APFloat &Value, QualType SubobjType) { 3813 Result = APValue(Value); 3814 return true; 3815 } 3816 }; 3817 } // end anonymous namespace 3818 3819 /// Extract the designated sub-object of an rvalue. 3820 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3821 const CompleteObject &Obj, 3822 const SubobjectDesignator &Sub, APValue &Result, 3823 AccessKinds AK = AK_Read) { 3824 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3825 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3826 return findSubobject(Info, E, Obj, Sub, Handler); 3827 } 3828 3829 namespace { 3830 struct ModifySubobjectHandler { 3831 EvalInfo &Info; 3832 APValue &NewVal; 3833 const Expr *E; 3834 3835 typedef bool result_type; 3836 static const AccessKinds AccessKind = AK_Assign; 3837 3838 bool checkConst(QualType QT) { 3839 // Assigning to a const object has undefined behavior. 3840 if (QT.isConstQualified()) { 3841 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3842 return false; 3843 } 3844 return true; 3845 } 3846 3847 bool failed() { return false; } 3848 bool found(APValue &Subobj, QualType SubobjType) { 3849 if (!checkConst(SubobjType)) 3850 return false; 3851 // We've been given ownership of NewVal, so just swap it in. 3852 Subobj.swap(NewVal); 3853 return true; 3854 } 3855 bool found(APSInt &Value, QualType SubobjType) { 3856 if (!checkConst(SubobjType)) 3857 return false; 3858 if (!NewVal.isInt()) { 3859 // Maybe trying to write a cast pointer value into a complex? 3860 Info.FFDiag(E); 3861 return false; 3862 } 3863 Value = NewVal.getInt(); 3864 return true; 3865 } 3866 bool found(APFloat &Value, QualType SubobjType) { 3867 if (!checkConst(SubobjType)) 3868 return false; 3869 Value = NewVal.getFloat(); 3870 return true; 3871 } 3872 }; 3873 } // end anonymous namespace 3874 3875 const AccessKinds ModifySubobjectHandler::AccessKind; 3876 3877 /// Update the designated sub-object of an rvalue to the given value. 3878 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3879 const CompleteObject &Obj, 3880 const SubobjectDesignator &Sub, 3881 APValue &NewVal) { 3882 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3883 return findSubobject(Info, E, Obj, Sub, Handler); 3884 } 3885 3886 /// Find the position where two subobject designators diverge, or equivalently 3887 /// the length of the common initial subsequence. 3888 static unsigned FindDesignatorMismatch(QualType ObjType, 3889 const SubobjectDesignator &A, 3890 const SubobjectDesignator &B, 3891 bool &WasArrayIndex) { 3892 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3893 for (/**/; I != N; ++I) { 3894 if (!ObjType.isNull() && 3895 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3896 // Next subobject is an array element. 3897 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3898 WasArrayIndex = true; 3899 return I; 3900 } 3901 if (ObjType->isAnyComplexType()) 3902 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3903 else 3904 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3905 } else { 3906 if (A.Entries[I].getAsBaseOrMember() != 3907 B.Entries[I].getAsBaseOrMember()) { 3908 WasArrayIndex = false; 3909 return I; 3910 } 3911 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3912 // Next subobject is a field. 3913 ObjType = FD->getType(); 3914 else 3915 // Next subobject is a base class. 3916 ObjType = QualType(); 3917 } 3918 } 3919 WasArrayIndex = false; 3920 return I; 3921 } 3922 3923 /// Determine whether the given subobject designators refer to elements of the 3924 /// same array object. 3925 static bool AreElementsOfSameArray(QualType ObjType, 3926 const SubobjectDesignator &A, 3927 const SubobjectDesignator &B) { 3928 if (A.Entries.size() != B.Entries.size()) 3929 return false; 3930 3931 bool IsArray = A.MostDerivedIsArrayElement; 3932 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3933 // A is a subobject of the array element. 3934 return false; 3935 3936 // If A (and B) designates an array element, the last entry will be the array 3937 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3938 // of length 1' case, and the entire path must match. 3939 bool WasArrayIndex; 3940 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3941 return CommonLength >= A.Entries.size() - IsArray; 3942 } 3943 3944 /// Find the complete object to which an LValue refers. 3945 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3946 AccessKinds AK, const LValue &LVal, 3947 QualType LValType) { 3948 if (LVal.InvalidBase) { 3949 Info.FFDiag(E); 3950 return CompleteObject(); 3951 } 3952 3953 if (!LVal.Base) { 3954 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3955 return CompleteObject(); 3956 } 3957 3958 CallStackFrame *Frame = nullptr; 3959 unsigned Depth = 0; 3960 if (LVal.getLValueCallIndex()) { 3961 std::tie(Frame, Depth) = 3962 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3963 if (!Frame) { 3964 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3965 << AK << LVal.Base.is<const ValueDecl*>(); 3966 NoteLValueLocation(Info, LVal.Base); 3967 return CompleteObject(); 3968 } 3969 } 3970 3971 bool IsAccess = isAnyAccess(AK); 3972 3973 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3974 // is not a constant expression (even if the object is non-volatile). We also 3975 // apply this rule to C++98, in order to conform to the expected 'volatile' 3976 // semantics. 3977 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3978 if (Info.getLangOpts().CPlusPlus) 3979 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3980 << AK << LValType; 3981 else 3982 Info.FFDiag(E); 3983 return CompleteObject(); 3984 } 3985 3986 // Compute value storage location and type of base object. 3987 APValue *BaseVal = nullptr; 3988 QualType BaseType = getType(LVal.Base); 3989 3990 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3991 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3992 // This is the object whose initializer we're evaluating, so its lifetime 3993 // started in the current evaluation. 3994 BaseVal = Info.EvaluatingDeclValue; 3995 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3996 // Allow reading from a GUID declaration. 3997 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3998 if (isModification(AK)) { 3999 // All the remaining cases do not permit modification of the object. 4000 Info.FFDiag(E, diag::note_constexpr_modify_global); 4001 return CompleteObject(); 4002 } 4003 APValue &V = GD->getAsAPValue(); 4004 if (V.isAbsent()) { 4005 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4006 << GD->getType(); 4007 return CompleteObject(); 4008 } 4009 return CompleteObject(LVal.Base, &V, GD->getType()); 4010 } 4011 4012 // Allow reading from template parameter objects. 4013 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4014 if (isModification(AK)) { 4015 Info.FFDiag(E, diag::note_constexpr_modify_global); 4016 return CompleteObject(); 4017 } 4018 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4019 TPO->getType()); 4020 } 4021 4022 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4023 // In C++11, constexpr, non-volatile variables initialized with constant 4024 // expressions are constant expressions too. Inside constexpr functions, 4025 // parameters are constant expressions even if they're non-const. 4026 // In C++1y, objects local to a constant expression (those with a Frame) are 4027 // both readable and writable inside constant expressions. 4028 // In C, such things can also be folded, although they are not ICEs. 4029 const VarDecl *VD = dyn_cast<VarDecl>(D); 4030 if (VD) { 4031 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4032 VD = VDef; 4033 } 4034 if (!VD || VD->isInvalidDecl()) { 4035 Info.FFDiag(E); 4036 return CompleteObject(); 4037 } 4038 4039 bool IsConstant = BaseType.isConstant(Info.Ctx); 4040 4041 // Unless we're looking at a local variable or argument in a constexpr call, 4042 // the variable we're reading must be const. 4043 if (!Frame) { 4044 if (IsAccess && isa<ParmVarDecl>(VD)) { 4045 // Access of a parameter that's not associated with a frame isn't going 4046 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4047 // suitable diagnostic. 4048 } else if (Info.getLangOpts().CPlusPlus14 && 4049 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4050 // OK, we can read and modify an object if we're in the process of 4051 // evaluating its initializer, because its lifetime began in this 4052 // evaluation. 4053 } else if (isModification(AK)) { 4054 // All the remaining cases do not permit modification of the object. 4055 Info.FFDiag(E, diag::note_constexpr_modify_global); 4056 return CompleteObject(); 4057 } else if (VD->isConstexpr()) { 4058 // OK, we can read this variable. 4059 } else if (BaseType->isIntegralOrEnumerationType()) { 4060 if (!IsConstant) { 4061 if (!IsAccess) 4062 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4063 if (Info.getLangOpts().CPlusPlus) { 4064 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4065 Info.Note(VD->getLocation(), diag::note_declared_at); 4066 } else { 4067 Info.FFDiag(E); 4068 } 4069 return CompleteObject(); 4070 } 4071 } else if (!IsAccess) { 4072 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4073 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4074 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4075 // This variable might end up being constexpr. Don't diagnose it yet. 4076 } else if (IsConstant) { 4077 // Keep evaluating to see what we can do. In particular, we support 4078 // folding of const floating-point types, in order to make static const 4079 // data members of such types (supported as an extension) more useful. 4080 if (Info.getLangOpts().CPlusPlus) { 4081 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4082 ? diag::note_constexpr_ltor_non_constexpr 4083 : diag::note_constexpr_ltor_non_integral, 1) 4084 << VD << BaseType; 4085 Info.Note(VD->getLocation(), diag::note_declared_at); 4086 } else { 4087 Info.CCEDiag(E); 4088 } 4089 } else { 4090 // Never allow reading a non-const value. 4091 if (Info.getLangOpts().CPlusPlus) { 4092 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4093 ? diag::note_constexpr_ltor_non_constexpr 4094 : diag::note_constexpr_ltor_non_integral, 1) 4095 << VD << BaseType; 4096 Info.Note(VD->getLocation(), diag::note_declared_at); 4097 } else { 4098 Info.FFDiag(E); 4099 } 4100 return CompleteObject(); 4101 } 4102 } 4103 4104 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4105 return CompleteObject(); 4106 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4107 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4108 if (!Alloc) { 4109 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4110 return CompleteObject(); 4111 } 4112 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4113 LVal.Base.getDynamicAllocType()); 4114 } else { 4115 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4116 4117 if (!Frame) { 4118 if (const MaterializeTemporaryExpr *MTE = 4119 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4120 assert(MTE->getStorageDuration() == SD_Static && 4121 "should have a frame for a non-global materialized temporary"); 4122 4123 // C++20 [expr.const]p4: [DR2126] 4124 // An object or reference is usable in constant expressions if it is 4125 // - a temporary object of non-volatile const-qualified literal type 4126 // whose lifetime is extended to that of a variable that is usable 4127 // in constant expressions 4128 // 4129 // C++20 [expr.const]p5: 4130 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4131 // - a non-volatile glvalue that refers to an object that is usable 4132 // in constant expressions, or 4133 // - a non-volatile glvalue of literal type that refers to a 4134 // non-volatile object whose lifetime began within the evaluation 4135 // of E; 4136 // 4137 // C++11 misses the 'began within the evaluation of e' check and 4138 // instead allows all temporaries, including things like: 4139 // int &&r = 1; 4140 // int x = ++r; 4141 // constexpr int k = r; 4142 // Therefore we use the C++14-onwards rules in C++11 too. 4143 // 4144 // Note that temporaries whose lifetimes began while evaluating a 4145 // variable's constructor are not usable while evaluating the 4146 // corresponding destructor, not even if they're of const-qualified 4147 // types. 4148 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4149 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4150 if (!IsAccess) 4151 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4152 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4153 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4154 return CompleteObject(); 4155 } 4156 4157 BaseVal = MTE->getOrCreateValue(false); 4158 assert(BaseVal && "got reference to unevaluated temporary"); 4159 } else { 4160 if (!IsAccess) 4161 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4162 APValue Val; 4163 LVal.moveInto(Val); 4164 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4165 << AK 4166 << Val.getAsString(Info.Ctx, 4167 Info.Ctx.getLValueReferenceType(LValType)); 4168 NoteLValueLocation(Info, LVal.Base); 4169 return CompleteObject(); 4170 } 4171 } else { 4172 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4173 assert(BaseVal && "missing value for temporary"); 4174 } 4175 } 4176 4177 // In C++14, we can't safely access any mutable state when we might be 4178 // evaluating after an unmodeled side effect. Parameters are modeled as state 4179 // in the caller, but aren't visible once the call returns, so they can be 4180 // modified in a speculatively-evaluated call. 4181 // 4182 // FIXME: Not all local state is mutable. Allow local constant subobjects 4183 // to be read here (but take care with 'mutable' fields). 4184 unsigned VisibleDepth = Depth; 4185 if (llvm::isa_and_nonnull<ParmVarDecl>( 4186 LVal.Base.dyn_cast<const ValueDecl *>())) 4187 ++VisibleDepth; 4188 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4189 Info.EvalStatus.HasSideEffects) || 4190 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4191 return CompleteObject(); 4192 4193 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4194 } 4195 4196 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4197 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4198 /// glvalue referred to by an entity of reference type. 4199 /// 4200 /// \param Info - Information about the ongoing evaluation. 4201 /// \param Conv - The expression for which we are performing the conversion. 4202 /// Used for diagnostics. 4203 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4204 /// case of a non-class type). 4205 /// \param LVal - The glvalue on which we are attempting to perform this action. 4206 /// \param RVal - The produced value will be placed here. 4207 /// \param WantObjectRepresentation - If true, we're looking for the object 4208 /// representation rather than the value, and in particular, 4209 /// there is no requirement that the result be fully initialized. 4210 static bool 4211 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4212 const LValue &LVal, APValue &RVal, 4213 bool WantObjectRepresentation = false) { 4214 if (LVal.Designator.Invalid) 4215 return false; 4216 4217 // Check for special cases where there is no existing APValue to look at. 4218 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4219 4220 AccessKinds AK = 4221 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4222 4223 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4224 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4225 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4226 // initializer until now for such expressions. Such an expression can't be 4227 // an ICE in C, so this only matters for fold. 4228 if (Type.isVolatileQualified()) { 4229 Info.FFDiag(Conv); 4230 return false; 4231 } 4232 APValue Lit; 4233 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4234 return false; 4235 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4236 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4237 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4238 // Special-case character extraction so we don't have to construct an 4239 // APValue for the whole string. 4240 assert(LVal.Designator.Entries.size() <= 1 && 4241 "Can only read characters from string literals"); 4242 if (LVal.Designator.Entries.empty()) { 4243 // Fail for now for LValue to RValue conversion of an array. 4244 // (This shouldn't show up in C/C++, but it could be triggered by a 4245 // weird EvaluateAsRValue call from a tool.) 4246 Info.FFDiag(Conv); 4247 return false; 4248 } 4249 if (LVal.Designator.isOnePastTheEnd()) { 4250 if (Info.getLangOpts().CPlusPlus11) 4251 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4252 else 4253 Info.FFDiag(Conv); 4254 return false; 4255 } 4256 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4257 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4258 return true; 4259 } 4260 } 4261 4262 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4263 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4264 } 4265 4266 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4267 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4268 QualType LValType, APValue &Val) { 4269 if (LVal.Designator.Invalid) 4270 return false; 4271 4272 if (!Info.getLangOpts().CPlusPlus14) { 4273 Info.FFDiag(E); 4274 return false; 4275 } 4276 4277 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4278 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4279 } 4280 4281 namespace { 4282 struct CompoundAssignSubobjectHandler { 4283 EvalInfo &Info; 4284 const CompoundAssignOperator *E; 4285 QualType PromotedLHSType; 4286 BinaryOperatorKind Opcode; 4287 const APValue &RHS; 4288 4289 static const AccessKinds AccessKind = AK_Assign; 4290 4291 typedef bool result_type; 4292 4293 bool checkConst(QualType QT) { 4294 // Assigning to a const object has undefined behavior. 4295 if (QT.isConstQualified()) { 4296 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4297 return false; 4298 } 4299 return true; 4300 } 4301 4302 bool failed() { return false; } 4303 bool found(APValue &Subobj, QualType SubobjType) { 4304 switch (Subobj.getKind()) { 4305 case APValue::Int: 4306 return found(Subobj.getInt(), SubobjType); 4307 case APValue::Float: 4308 return found(Subobj.getFloat(), SubobjType); 4309 case APValue::ComplexInt: 4310 case APValue::ComplexFloat: 4311 // FIXME: Implement complex compound assignment. 4312 Info.FFDiag(E); 4313 return false; 4314 case APValue::LValue: 4315 return foundPointer(Subobj, SubobjType); 4316 case APValue::Vector: 4317 return foundVector(Subobj, SubobjType); 4318 default: 4319 // FIXME: can this happen? 4320 Info.FFDiag(E); 4321 return false; 4322 } 4323 } 4324 4325 bool foundVector(APValue &Value, QualType SubobjType) { 4326 if (!checkConst(SubobjType)) 4327 return false; 4328 4329 if (!SubobjType->isVectorType()) { 4330 Info.FFDiag(E); 4331 return false; 4332 } 4333 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4334 } 4335 4336 bool found(APSInt &Value, QualType SubobjType) { 4337 if (!checkConst(SubobjType)) 4338 return false; 4339 4340 if (!SubobjType->isIntegerType()) { 4341 // We don't support compound assignment on integer-cast-to-pointer 4342 // values. 4343 Info.FFDiag(E); 4344 return false; 4345 } 4346 4347 if (RHS.isInt()) { 4348 APSInt LHS = 4349 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4350 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4351 return false; 4352 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4353 return true; 4354 } else if (RHS.isFloat()) { 4355 const FPOptions FPO = E->getFPFeaturesInEffect( 4356 Info.Ctx.getLangOpts()); 4357 APFloat FValue(0.0); 4358 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4359 PromotedLHSType, FValue) && 4360 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4361 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4362 Value); 4363 } 4364 4365 Info.FFDiag(E); 4366 return false; 4367 } 4368 bool found(APFloat &Value, QualType SubobjType) { 4369 return checkConst(SubobjType) && 4370 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4371 Value) && 4372 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4373 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4374 } 4375 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4376 if (!checkConst(SubobjType)) 4377 return false; 4378 4379 QualType PointeeType; 4380 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4381 PointeeType = PT->getPointeeType(); 4382 4383 if (PointeeType.isNull() || !RHS.isInt() || 4384 (Opcode != BO_Add && Opcode != BO_Sub)) { 4385 Info.FFDiag(E); 4386 return false; 4387 } 4388 4389 APSInt Offset = RHS.getInt(); 4390 if (Opcode == BO_Sub) 4391 negateAsSigned(Offset); 4392 4393 LValue LVal; 4394 LVal.setFrom(Info.Ctx, Subobj); 4395 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4396 return false; 4397 LVal.moveInto(Subobj); 4398 return true; 4399 } 4400 }; 4401 } // end anonymous namespace 4402 4403 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4404 4405 /// Perform a compound assignment of LVal <op>= RVal. 4406 static bool handleCompoundAssignment(EvalInfo &Info, 4407 const CompoundAssignOperator *E, 4408 const LValue &LVal, QualType LValType, 4409 QualType PromotedLValType, 4410 BinaryOperatorKind Opcode, 4411 const APValue &RVal) { 4412 if (LVal.Designator.Invalid) 4413 return false; 4414 4415 if (!Info.getLangOpts().CPlusPlus14) { 4416 Info.FFDiag(E); 4417 return false; 4418 } 4419 4420 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4421 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4422 RVal }; 4423 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4424 } 4425 4426 namespace { 4427 struct IncDecSubobjectHandler { 4428 EvalInfo &Info; 4429 const UnaryOperator *E; 4430 AccessKinds AccessKind; 4431 APValue *Old; 4432 4433 typedef bool result_type; 4434 4435 bool checkConst(QualType QT) { 4436 // Assigning to a const object has undefined behavior. 4437 if (QT.isConstQualified()) { 4438 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4439 return false; 4440 } 4441 return true; 4442 } 4443 4444 bool failed() { return false; } 4445 bool found(APValue &Subobj, QualType SubobjType) { 4446 // Stash the old value. Also clear Old, so we don't clobber it later 4447 // if we're post-incrementing a complex. 4448 if (Old) { 4449 *Old = Subobj; 4450 Old = nullptr; 4451 } 4452 4453 switch (Subobj.getKind()) { 4454 case APValue::Int: 4455 return found(Subobj.getInt(), SubobjType); 4456 case APValue::Float: 4457 return found(Subobj.getFloat(), SubobjType); 4458 case APValue::ComplexInt: 4459 return found(Subobj.getComplexIntReal(), 4460 SubobjType->castAs<ComplexType>()->getElementType() 4461 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4462 case APValue::ComplexFloat: 4463 return found(Subobj.getComplexFloatReal(), 4464 SubobjType->castAs<ComplexType>()->getElementType() 4465 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4466 case APValue::LValue: 4467 return foundPointer(Subobj, SubobjType); 4468 default: 4469 // FIXME: can this happen? 4470 Info.FFDiag(E); 4471 return false; 4472 } 4473 } 4474 bool found(APSInt &Value, QualType SubobjType) { 4475 if (!checkConst(SubobjType)) 4476 return false; 4477 4478 if (!SubobjType->isIntegerType()) { 4479 // We don't support increment / decrement on integer-cast-to-pointer 4480 // values. 4481 Info.FFDiag(E); 4482 return false; 4483 } 4484 4485 if (Old) *Old = APValue(Value); 4486 4487 // bool arithmetic promotes to int, and the conversion back to bool 4488 // doesn't reduce mod 2^n, so special-case it. 4489 if (SubobjType->isBooleanType()) { 4490 if (AccessKind == AK_Increment) 4491 Value = 1; 4492 else 4493 Value = !Value; 4494 return true; 4495 } 4496 4497 bool WasNegative = Value.isNegative(); 4498 if (AccessKind == AK_Increment) { 4499 ++Value; 4500 4501 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4502 APSInt ActualValue(Value, /*IsUnsigned*/true); 4503 return HandleOverflow(Info, E, ActualValue, SubobjType); 4504 } 4505 } else { 4506 --Value; 4507 4508 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4509 unsigned BitWidth = Value.getBitWidth(); 4510 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4511 ActualValue.setBit(BitWidth); 4512 return HandleOverflow(Info, E, ActualValue, SubobjType); 4513 } 4514 } 4515 return true; 4516 } 4517 bool found(APFloat &Value, QualType SubobjType) { 4518 if (!checkConst(SubobjType)) 4519 return false; 4520 4521 if (Old) *Old = APValue(Value); 4522 4523 APFloat One(Value.getSemantics(), 1); 4524 if (AccessKind == AK_Increment) 4525 Value.add(One, APFloat::rmNearestTiesToEven); 4526 else 4527 Value.subtract(One, APFloat::rmNearestTiesToEven); 4528 return true; 4529 } 4530 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4531 if (!checkConst(SubobjType)) 4532 return false; 4533 4534 QualType PointeeType; 4535 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4536 PointeeType = PT->getPointeeType(); 4537 else { 4538 Info.FFDiag(E); 4539 return false; 4540 } 4541 4542 LValue LVal; 4543 LVal.setFrom(Info.Ctx, Subobj); 4544 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4545 AccessKind == AK_Increment ? 1 : -1)) 4546 return false; 4547 LVal.moveInto(Subobj); 4548 return true; 4549 } 4550 }; 4551 } // end anonymous namespace 4552 4553 /// Perform an increment or decrement on LVal. 4554 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4555 QualType LValType, bool IsIncrement, APValue *Old) { 4556 if (LVal.Designator.Invalid) 4557 return false; 4558 4559 if (!Info.getLangOpts().CPlusPlus14) { 4560 Info.FFDiag(E); 4561 return false; 4562 } 4563 4564 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4565 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4566 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4567 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4568 } 4569 4570 /// Build an lvalue for the object argument of a member function call. 4571 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4572 LValue &This) { 4573 if (Object->getType()->isPointerType() && Object->isPRValue()) 4574 return EvaluatePointer(Object, This, Info); 4575 4576 if (Object->isGLValue()) 4577 return EvaluateLValue(Object, This, Info); 4578 4579 if (Object->getType()->isLiteralType(Info.Ctx)) 4580 return EvaluateTemporary(Object, This, Info); 4581 4582 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4583 return false; 4584 } 4585 4586 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4587 /// lvalue referring to the result. 4588 /// 4589 /// \param Info - Information about the ongoing evaluation. 4590 /// \param LV - An lvalue referring to the base of the member pointer. 4591 /// \param RHS - The member pointer expression. 4592 /// \param IncludeMember - Specifies whether the member itself is included in 4593 /// the resulting LValue subobject designator. This is not possible when 4594 /// creating a bound member function. 4595 /// \return The field or method declaration to which the member pointer refers, 4596 /// or 0 if evaluation fails. 4597 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4598 QualType LVType, 4599 LValue &LV, 4600 const Expr *RHS, 4601 bool IncludeMember = true) { 4602 MemberPtr MemPtr; 4603 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4604 return nullptr; 4605 4606 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4607 // member value, the behavior is undefined. 4608 if (!MemPtr.getDecl()) { 4609 // FIXME: Specific diagnostic. 4610 Info.FFDiag(RHS); 4611 return nullptr; 4612 } 4613 4614 if (MemPtr.isDerivedMember()) { 4615 // This is a member of some derived class. Truncate LV appropriately. 4616 // The end of the derived-to-base path for the base object must match the 4617 // derived-to-base path for the member pointer. 4618 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4619 LV.Designator.Entries.size()) { 4620 Info.FFDiag(RHS); 4621 return nullptr; 4622 } 4623 unsigned PathLengthToMember = 4624 LV.Designator.Entries.size() - MemPtr.Path.size(); 4625 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4626 const CXXRecordDecl *LVDecl = getAsBaseClass( 4627 LV.Designator.Entries[PathLengthToMember + I]); 4628 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4629 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4630 Info.FFDiag(RHS); 4631 return nullptr; 4632 } 4633 } 4634 4635 // Truncate the lvalue to the appropriate derived class. 4636 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4637 PathLengthToMember)) 4638 return nullptr; 4639 } else if (!MemPtr.Path.empty()) { 4640 // Extend the LValue path with the member pointer's path. 4641 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4642 MemPtr.Path.size() + IncludeMember); 4643 4644 // Walk down to the appropriate base class. 4645 if (const PointerType *PT = LVType->getAs<PointerType>()) 4646 LVType = PT->getPointeeType(); 4647 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4648 assert(RD && "member pointer access on non-class-type expression"); 4649 // The first class in the path is that of the lvalue. 4650 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4651 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4652 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4653 return nullptr; 4654 RD = Base; 4655 } 4656 // Finally cast to the class containing the member. 4657 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4658 MemPtr.getContainingRecord())) 4659 return nullptr; 4660 } 4661 4662 // Add the member. Note that we cannot build bound member functions here. 4663 if (IncludeMember) { 4664 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4665 if (!HandleLValueMember(Info, RHS, LV, FD)) 4666 return nullptr; 4667 } else if (const IndirectFieldDecl *IFD = 4668 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4669 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4670 return nullptr; 4671 } else { 4672 llvm_unreachable("can't construct reference to bound member function"); 4673 } 4674 } 4675 4676 return MemPtr.getDecl(); 4677 } 4678 4679 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4680 const BinaryOperator *BO, 4681 LValue &LV, 4682 bool IncludeMember = true) { 4683 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4684 4685 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4686 if (Info.noteFailure()) { 4687 MemberPtr MemPtr; 4688 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4689 } 4690 return nullptr; 4691 } 4692 4693 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4694 BO->getRHS(), IncludeMember); 4695 } 4696 4697 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4698 /// the provided lvalue, which currently refers to the base object. 4699 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4700 LValue &Result) { 4701 SubobjectDesignator &D = Result.Designator; 4702 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4703 return false; 4704 4705 QualType TargetQT = E->getType(); 4706 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4707 TargetQT = PT->getPointeeType(); 4708 4709 // Check this cast lands within the final derived-to-base subobject path. 4710 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4711 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4712 << D.MostDerivedType << TargetQT; 4713 return false; 4714 } 4715 4716 // Check the type of the final cast. We don't need to check the path, 4717 // since a cast can only be formed if the path is unique. 4718 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4719 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4720 const CXXRecordDecl *FinalType; 4721 if (NewEntriesSize == D.MostDerivedPathLength) 4722 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4723 else 4724 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4725 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4726 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4727 << D.MostDerivedType << TargetQT; 4728 return false; 4729 } 4730 4731 // Truncate the lvalue to the appropriate derived class. 4732 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4733 } 4734 4735 /// Get the value to use for a default-initialized object of type T. 4736 /// Return false if it encounters something invalid. 4737 static bool getDefaultInitValue(QualType T, APValue &Result) { 4738 bool Success = true; 4739 if (auto *RD = T->getAsCXXRecordDecl()) { 4740 if (RD->isInvalidDecl()) { 4741 Result = APValue(); 4742 return false; 4743 } 4744 if (RD->isUnion()) { 4745 Result = APValue((const FieldDecl *)nullptr); 4746 return true; 4747 } 4748 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4749 std::distance(RD->field_begin(), RD->field_end())); 4750 4751 unsigned Index = 0; 4752 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4753 End = RD->bases_end(); 4754 I != End; ++I, ++Index) 4755 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4756 4757 for (const auto *I : RD->fields()) { 4758 if (I->isUnnamedBitfield()) 4759 continue; 4760 Success &= getDefaultInitValue(I->getType(), 4761 Result.getStructField(I->getFieldIndex())); 4762 } 4763 return Success; 4764 } 4765 4766 if (auto *AT = 4767 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4768 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4769 if (Result.hasArrayFiller()) 4770 Success &= 4771 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4772 4773 return Success; 4774 } 4775 4776 Result = APValue::IndeterminateValue(); 4777 return true; 4778 } 4779 4780 namespace { 4781 enum EvalStmtResult { 4782 /// Evaluation failed. 4783 ESR_Failed, 4784 /// Hit a 'return' statement. 4785 ESR_Returned, 4786 /// Evaluation succeeded. 4787 ESR_Succeeded, 4788 /// Hit a 'continue' statement. 4789 ESR_Continue, 4790 /// Hit a 'break' statement. 4791 ESR_Break, 4792 /// Still scanning for 'case' or 'default' statement. 4793 ESR_CaseNotFound 4794 }; 4795 } 4796 4797 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4798 // We don't need to evaluate the initializer for a static local. 4799 if (!VD->hasLocalStorage()) 4800 return true; 4801 4802 LValue Result; 4803 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4804 ScopeKind::Block, Result); 4805 4806 const Expr *InitE = VD->getInit(); 4807 if (!InitE) { 4808 if (VD->getType()->isDependentType()) 4809 return Info.noteSideEffect(); 4810 return getDefaultInitValue(VD->getType(), Val); 4811 } 4812 if (InitE->isValueDependent()) 4813 return false; 4814 4815 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4816 // Wipe out any partially-computed value, to allow tracking that this 4817 // evaluation failed. 4818 Val = APValue(); 4819 return false; 4820 } 4821 4822 return true; 4823 } 4824 4825 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4826 bool OK = true; 4827 4828 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4829 OK &= EvaluateVarDecl(Info, VD); 4830 4831 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4832 for (auto *BD : DD->bindings()) 4833 if (auto *VD = BD->getHoldingVar()) 4834 OK &= EvaluateDecl(Info, VD); 4835 4836 return OK; 4837 } 4838 4839 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4840 assert(E->isValueDependent()); 4841 if (Info.noteSideEffect()) 4842 return true; 4843 assert(E->containsErrors() && "valid value-dependent expression should never " 4844 "reach invalid code path."); 4845 return false; 4846 } 4847 4848 /// Evaluate a condition (either a variable declaration or an expression). 4849 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4850 const Expr *Cond, bool &Result) { 4851 if (Cond->isValueDependent()) 4852 return false; 4853 FullExpressionRAII Scope(Info); 4854 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4855 return false; 4856 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4857 return false; 4858 return Scope.destroy(); 4859 } 4860 4861 namespace { 4862 /// A location where the result (returned value) of evaluating a 4863 /// statement should be stored. 4864 struct StmtResult { 4865 /// The APValue that should be filled in with the returned value. 4866 APValue &Value; 4867 /// The location containing the result, if any (used to support RVO). 4868 const LValue *Slot; 4869 }; 4870 4871 struct TempVersionRAII { 4872 CallStackFrame &Frame; 4873 4874 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4875 Frame.pushTempVersion(); 4876 } 4877 4878 ~TempVersionRAII() { 4879 Frame.popTempVersion(); 4880 } 4881 }; 4882 4883 } 4884 4885 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4886 const Stmt *S, 4887 const SwitchCase *SC = nullptr); 4888 4889 /// Evaluate the body of a loop, and translate the result as appropriate. 4890 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4891 const Stmt *Body, 4892 const SwitchCase *Case = nullptr) { 4893 BlockScopeRAII Scope(Info); 4894 4895 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4896 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4897 ESR = ESR_Failed; 4898 4899 switch (ESR) { 4900 case ESR_Break: 4901 return ESR_Succeeded; 4902 case ESR_Succeeded: 4903 case ESR_Continue: 4904 return ESR_Continue; 4905 case ESR_Failed: 4906 case ESR_Returned: 4907 case ESR_CaseNotFound: 4908 return ESR; 4909 } 4910 llvm_unreachable("Invalid EvalStmtResult!"); 4911 } 4912 4913 /// Evaluate a switch statement. 4914 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4915 const SwitchStmt *SS) { 4916 BlockScopeRAII Scope(Info); 4917 4918 // Evaluate the switch condition. 4919 APSInt Value; 4920 { 4921 if (const Stmt *Init = SS->getInit()) { 4922 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4923 if (ESR != ESR_Succeeded) { 4924 if (ESR != ESR_Failed && !Scope.destroy()) 4925 ESR = ESR_Failed; 4926 return ESR; 4927 } 4928 } 4929 4930 FullExpressionRAII CondScope(Info); 4931 if (SS->getConditionVariable() && 4932 !EvaluateDecl(Info, SS->getConditionVariable())) 4933 return ESR_Failed; 4934 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4935 return ESR_Failed; 4936 if (!CondScope.destroy()) 4937 return ESR_Failed; 4938 } 4939 4940 // Find the switch case corresponding to the value of the condition. 4941 // FIXME: Cache this lookup. 4942 const SwitchCase *Found = nullptr; 4943 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4944 SC = SC->getNextSwitchCase()) { 4945 if (isa<DefaultStmt>(SC)) { 4946 Found = SC; 4947 continue; 4948 } 4949 4950 const CaseStmt *CS = cast<CaseStmt>(SC); 4951 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4952 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4953 : LHS; 4954 if (LHS <= Value && Value <= RHS) { 4955 Found = SC; 4956 break; 4957 } 4958 } 4959 4960 if (!Found) 4961 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4962 4963 // Search the switch body for the switch case and evaluate it from there. 4964 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4965 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4966 return ESR_Failed; 4967 4968 switch (ESR) { 4969 case ESR_Break: 4970 return ESR_Succeeded; 4971 case ESR_Succeeded: 4972 case ESR_Continue: 4973 case ESR_Failed: 4974 case ESR_Returned: 4975 return ESR; 4976 case ESR_CaseNotFound: 4977 // This can only happen if the switch case is nested within a statement 4978 // expression. We have no intention of supporting that. 4979 Info.FFDiag(Found->getBeginLoc(), 4980 diag::note_constexpr_stmt_expr_unsupported); 4981 return ESR_Failed; 4982 } 4983 llvm_unreachable("Invalid EvalStmtResult!"); 4984 } 4985 4986 // Evaluate a statement. 4987 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4988 const Stmt *S, const SwitchCase *Case) { 4989 if (!Info.nextStep(S)) 4990 return ESR_Failed; 4991 4992 // If we're hunting down a 'case' or 'default' label, recurse through 4993 // substatements until we hit the label. 4994 if (Case) { 4995 switch (S->getStmtClass()) { 4996 case Stmt::CompoundStmtClass: 4997 // FIXME: Precompute which substatement of a compound statement we 4998 // would jump to, and go straight there rather than performing a 4999 // linear scan each time. 5000 case Stmt::LabelStmtClass: 5001 case Stmt::AttributedStmtClass: 5002 case Stmt::DoStmtClass: 5003 break; 5004 5005 case Stmt::CaseStmtClass: 5006 case Stmt::DefaultStmtClass: 5007 if (Case == S) 5008 Case = nullptr; 5009 break; 5010 5011 case Stmt::IfStmtClass: { 5012 // FIXME: Precompute which side of an 'if' we would jump to, and go 5013 // straight there rather than scanning both sides. 5014 const IfStmt *IS = cast<IfStmt>(S); 5015 5016 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5017 // preceded by our switch label. 5018 BlockScopeRAII Scope(Info); 5019 5020 // Step into the init statement in case it brings an (uninitialized) 5021 // variable into scope. 5022 if (const Stmt *Init = IS->getInit()) { 5023 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5024 if (ESR != ESR_CaseNotFound) { 5025 assert(ESR != ESR_Succeeded); 5026 return ESR; 5027 } 5028 } 5029 5030 // Condition variable must be initialized if it exists. 5031 // FIXME: We can skip evaluating the body if there's a condition 5032 // variable, as there can't be any case labels within it. 5033 // (The same is true for 'for' statements.) 5034 5035 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5036 if (ESR == ESR_Failed) 5037 return ESR; 5038 if (ESR != ESR_CaseNotFound) 5039 return Scope.destroy() ? ESR : ESR_Failed; 5040 if (!IS->getElse()) 5041 return ESR_CaseNotFound; 5042 5043 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5044 if (ESR == ESR_Failed) 5045 return ESR; 5046 if (ESR != ESR_CaseNotFound) 5047 return Scope.destroy() ? ESR : ESR_Failed; 5048 return ESR_CaseNotFound; 5049 } 5050 5051 case Stmt::WhileStmtClass: { 5052 EvalStmtResult ESR = 5053 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5054 if (ESR != ESR_Continue) 5055 return ESR; 5056 break; 5057 } 5058 5059 case Stmt::ForStmtClass: { 5060 const ForStmt *FS = cast<ForStmt>(S); 5061 BlockScopeRAII Scope(Info); 5062 5063 // Step into the init statement in case it brings an (uninitialized) 5064 // variable into scope. 5065 if (const Stmt *Init = FS->getInit()) { 5066 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5067 if (ESR != ESR_CaseNotFound) { 5068 assert(ESR != ESR_Succeeded); 5069 return ESR; 5070 } 5071 } 5072 5073 EvalStmtResult ESR = 5074 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5075 if (ESR != ESR_Continue) 5076 return ESR; 5077 if (const auto *Inc = FS->getInc()) { 5078 if (Inc->isValueDependent()) { 5079 if (!EvaluateDependentExpr(Inc, Info)) 5080 return ESR_Failed; 5081 } else { 5082 FullExpressionRAII IncScope(Info); 5083 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5084 return ESR_Failed; 5085 } 5086 } 5087 break; 5088 } 5089 5090 case Stmt::DeclStmtClass: { 5091 // Start the lifetime of any uninitialized variables we encounter. They 5092 // might be used by the selected branch of the switch. 5093 const DeclStmt *DS = cast<DeclStmt>(S); 5094 for (const auto *D : DS->decls()) { 5095 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5096 if (VD->hasLocalStorage() && !VD->getInit()) 5097 if (!EvaluateVarDecl(Info, VD)) 5098 return ESR_Failed; 5099 // FIXME: If the variable has initialization that can't be jumped 5100 // over, bail out of any immediately-surrounding compound-statement 5101 // too. There can't be any case labels here. 5102 } 5103 } 5104 return ESR_CaseNotFound; 5105 } 5106 5107 default: 5108 return ESR_CaseNotFound; 5109 } 5110 } 5111 5112 switch (S->getStmtClass()) { 5113 default: 5114 if (const Expr *E = dyn_cast<Expr>(S)) { 5115 if (E->isValueDependent()) { 5116 if (!EvaluateDependentExpr(E, Info)) 5117 return ESR_Failed; 5118 } else { 5119 // Don't bother evaluating beyond an expression-statement which couldn't 5120 // be evaluated. 5121 // FIXME: Do we need the FullExpressionRAII object here? 5122 // VisitExprWithCleanups should create one when necessary. 5123 FullExpressionRAII Scope(Info); 5124 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5125 return ESR_Failed; 5126 } 5127 return ESR_Succeeded; 5128 } 5129 5130 Info.FFDiag(S->getBeginLoc()); 5131 return ESR_Failed; 5132 5133 case Stmt::NullStmtClass: 5134 return ESR_Succeeded; 5135 5136 case Stmt::DeclStmtClass: { 5137 const DeclStmt *DS = cast<DeclStmt>(S); 5138 for (const auto *D : DS->decls()) { 5139 // Each declaration initialization is its own full-expression. 5140 FullExpressionRAII Scope(Info); 5141 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5142 return ESR_Failed; 5143 if (!Scope.destroy()) 5144 return ESR_Failed; 5145 } 5146 return ESR_Succeeded; 5147 } 5148 5149 case Stmt::ReturnStmtClass: { 5150 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5151 FullExpressionRAII Scope(Info); 5152 if (RetExpr && RetExpr->isValueDependent()) { 5153 EvaluateDependentExpr(RetExpr, Info); 5154 // We know we returned, but we don't know what the value is. 5155 return ESR_Failed; 5156 } 5157 if (RetExpr && 5158 !(Result.Slot 5159 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5160 : Evaluate(Result.Value, Info, RetExpr))) 5161 return ESR_Failed; 5162 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5163 } 5164 5165 case Stmt::CompoundStmtClass: { 5166 BlockScopeRAII Scope(Info); 5167 5168 const CompoundStmt *CS = cast<CompoundStmt>(S); 5169 for (const auto *BI : CS->body()) { 5170 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5171 if (ESR == ESR_Succeeded) 5172 Case = nullptr; 5173 else if (ESR != ESR_CaseNotFound) { 5174 if (ESR != ESR_Failed && !Scope.destroy()) 5175 return ESR_Failed; 5176 return ESR; 5177 } 5178 } 5179 if (Case) 5180 return ESR_CaseNotFound; 5181 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5182 } 5183 5184 case Stmt::IfStmtClass: { 5185 const IfStmt *IS = cast<IfStmt>(S); 5186 5187 // Evaluate the condition, as either a var decl or as an expression. 5188 BlockScopeRAII Scope(Info); 5189 if (const Stmt *Init = IS->getInit()) { 5190 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5191 if (ESR != ESR_Succeeded) { 5192 if (ESR != ESR_Failed && !Scope.destroy()) 5193 return ESR_Failed; 5194 return ESR; 5195 } 5196 } 5197 bool Cond; 5198 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5199 return ESR_Failed; 5200 5201 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5202 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5203 if (ESR != ESR_Succeeded) { 5204 if (ESR != ESR_Failed && !Scope.destroy()) 5205 return ESR_Failed; 5206 return ESR; 5207 } 5208 } 5209 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5210 } 5211 5212 case Stmt::WhileStmtClass: { 5213 const WhileStmt *WS = cast<WhileStmt>(S); 5214 while (true) { 5215 BlockScopeRAII Scope(Info); 5216 bool Continue; 5217 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5218 Continue)) 5219 return ESR_Failed; 5220 if (!Continue) 5221 break; 5222 5223 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5224 if (ESR != ESR_Continue) { 5225 if (ESR != ESR_Failed && !Scope.destroy()) 5226 return ESR_Failed; 5227 return ESR; 5228 } 5229 if (!Scope.destroy()) 5230 return ESR_Failed; 5231 } 5232 return ESR_Succeeded; 5233 } 5234 5235 case Stmt::DoStmtClass: { 5236 const DoStmt *DS = cast<DoStmt>(S); 5237 bool Continue; 5238 do { 5239 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5240 if (ESR != ESR_Continue) 5241 return ESR; 5242 Case = nullptr; 5243 5244 if (DS->getCond()->isValueDependent()) { 5245 EvaluateDependentExpr(DS->getCond(), Info); 5246 // Bailout as we don't know whether to keep going or terminate the loop. 5247 return ESR_Failed; 5248 } 5249 FullExpressionRAII CondScope(Info); 5250 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5251 !CondScope.destroy()) 5252 return ESR_Failed; 5253 } while (Continue); 5254 return ESR_Succeeded; 5255 } 5256 5257 case Stmt::ForStmtClass: { 5258 const ForStmt *FS = cast<ForStmt>(S); 5259 BlockScopeRAII ForScope(Info); 5260 if (FS->getInit()) { 5261 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5262 if (ESR != ESR_Succeeded) { 5263 if (ESR != ESR_Failed && !ForScope.destroy()) 5264 return ESR_Failed; 5265 return ESR; 5266 } 5267 } 5268 while (true) { 5269 BlockScopeRAII IterScope(Info); 5270 bool Continue = true; 5271 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5272 FS->getCond(), Continue)) 5273 return ESR_Failed; 5274 if (!Continue) 5275 break; 5276 5277 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5278 if (ESR != ESR_Continue) { 5279 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5280 return ESR_Failed; 5281 return ESR; 5282 } 5283 5284 if (const auto *Inc = FS->getInc()) { 5285 if (Inc->isValueDependent()) { 5286 if (!EvaluateDependentExpr(Inc, Info)) 5287 return ESR_Failed; 5288 } else { 5289 FullExpressionRAII IncScope(Info); 5290 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5291 return ESR_Failed; 5292 } 5293 } 5294 5295 if (!IterScope.destroy()) 5296 return ESR_Failed; 5297 } 5298 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5299 } 5300 5301 case Stmt::CXXForRangeStmtClass: { 5302 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5303 BlockScopeRAII Scope(Info); 5304 5305 // Evaluate the init-statement if present. 5306 if (FS->getInit()) { 5307 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5308 if (ESR != ESR_Succeeded) { 5309 if (ESR != ESR_Failed && !Scope.destroy()) 5310 return ESR_Failed; 5311 return ESR; 5312 } 5313 } 5314 5315 // Initialize the __range variable. 5316 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5317 if (ESR != ESR_Succeeded) { 5318 if (ESR != ESR_Failed && !Scope.destroy()) 5319 return ESR_Failed; 5320 return ESR; 5321 } 5322 5323 // Create the __begin and __end iterators. 5324 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5325 if (ESR != ESR_Succeeded) { 5326 if (ESR != ESR_Failed && !Scope.destroy()) 5327 return ESR_Failed; 5328 return ESR; 5329 } 5330 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5331 if (ESR != ESR_Succeeded) { 5332 if (ESR != ESR_Failed && !Scope.destroy()) 5333 return ESR_Failed; 5334 return ESR; 5335 } 5336 5337 while (true) { 5338 // Condition: __begin != __end. 5339 { 5340 if (FS->getCond()->isValueDependent()) { 5341 EvaluateDependentExpr(FS->getCond(), Info); 5342 // We don't know whether to keep going or terminate the loop. 5343 return ESR_Failed; 5344 } 5345 bool Continue = true; 5346 FullExpressionRAII CondExpr(Info); 5347 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5348 return ESR_Failed; 5349 if (!Continue) 5350 break; 5351 } 5352 5353 // User's variable declaration, initialized by *__begin. 5354 BlockScopeRAII InnerScope(Info); 5355 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5356 if (ESR != ESR_Succeeded) { 5357 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5358 return ESR_Failed; 5359 return ESR; 5360 } 5361 5362 // Loop body. 5363 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5364 if (ESR != ESR_Continue) { 5365 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5366 return ESR_Failed; 5367 return ESR; 5368 } 5369 if (FS->getInc()->isValueDependent()) { 5370 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5371 return ESR_Failed; 5372 } else { 5373 // Increment: ++__begin 5374 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5375 return ESR_Failed; 5376 } 5377 5378 if (!InnerScope.destroy()) 5379 return ESR_Failed; 5380 } 5381 5382 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5383 } 5384 5385 case Stmt::SwitchStmtClass: 5386 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5387 5388 case Stmt::ContinueStmtClass: 5389 return ESR_Continue; 5390 5391 case Stmt::BreakStmtClass: 5392 return ESR_Break; 5393 5394 case Stmt::LabelStmtClass: 5395 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5396 5397 case Stmt::AttributedStmtClass: 5398 // As a general principle, C++11 attributes can be ignored without 5399 // any semantic impact. 5400 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5401 Case); 5402 5403 case Stmt::CaseStmtClass: 5404 case Stmt::DefaultStmtClass: 5405 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5406 case Stmt::CXXTryStmtClass: 5407 // Evaluate try blocks by evaluating all sub statements. 5408 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5409 } 5410 } 5411 5412 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5413 /// default constructor. If so, we'll fold it whether or not it's marked as 5414 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5415 /// so we need special handling. 5416 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5417 const CXXConstructorDecl *CD, 5418 bool IsValueInitialization) { 5419 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5420 return false; 5421 5422 // Value-initialization does not call a trivial default constructor, so such a 5423 // call is a core constant expression whether or not the constructor is 5424 // constexpr. 5425 if (!CD->isConstexpr() && !IsValueInitialization) { 5426 if (Info.getLangOpts().CPlusPlus11) { 5427 // FIXME: If DiagDecl is an implicitly-declared special member function, 5428 // we should be much more explicit about why it's not constexpr. 5429 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5430 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5431 Info.Note(CD->getLocation(), diag::note_declared_at); 5432 } else { 5433 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5434 } 5435 } 5436 return true; 5437 } 5438 5439 /// CheckConstexprFunction - Check that a function can be called in a constant 5440 /// expression. 5441 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5442 const FunctionDecl *Declaration, 5443 const FunctionDecl *Definition, 5444 const Stmt *Body) { 5445 // Potential constant expressions can contain calls to declared, but not yet 5446 // defined, constexpr functions. 5447 if (Info.checkingPotentialConstantExpression() && !Definition && 5448 Declaration->isConstexpr()) 5449 return false; 5450 5451 // Bail out if the function declaration itself is invalid. We will 5452 // have produced a relevant diagnostic while parsing it, so just 5453 // note the problematic sub-expression. 5454 if (Declaration->isInvalidDecl()) { 5455 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5456 return false; 5457 } 5458 5459 // DR1872: An instantiated virtual constexpr function can't be called in a 5460 // constant expression (prior to C++20). We can still constant-fold such a 5461 // call. 5462 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5463 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5464 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5465 5466 if (Definition && Definition->isInvalidDecl()) { 5467 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5468 return false; 5469 } 5470 5471 // Can we evaluate this function call? 5472 if (Definition && Definition->isConstexpr() && Body) 5473 return true; 5474 5475 if (Info.getLangOpts().CPlusPlus11) { 5476 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5477 5478 // If this function is not constexpr because it is an inherited 5479 // non-constexpr constructor, diagnose that directly. 5480 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5481 if (CD && CD->isInheritingConstructor()) { 5482 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5483 if (!Inherited->isConstexpr()) 5484 DiagDecl = CD = Inherited; 5485 } 5486 5487 // FIXME: If DiagDecl is an implicitly-declared special member function 5488 // or an inheriting constructor, we should be much more explicit about why 5489 // it's not constexpr. 5490 if (CD && CD->isInheritingConstructor()) 5491 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5492 << CD->getInheritedConstructor().getConstructor()->getParent(); 5493 else 5494 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5495 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5496 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5497 } else { 5498 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5499 } 5500 return false; 5501 } 5502 5503 namespace { 5504 struct CheckDynamicTypeHandler { 5505 AccessKinds AccessKind; 5506 typedef bool result_type; 5507 bool failed() { return false; } 5508 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5509 bool found(APSInt &Value, QualType SubobjType) { return true; } 5510 bool found(APFloat &Value, QualType SubobjType) { return true; } 5511 }; 5512 } // end anonymous namespace 5513 5514 /// Check that we can access the notional vptr of an object / determine its 5515 /// dynamic type. 5516 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5517 AccessKinds AK, bool Polymorphic) { 5518 if (This.Designator.Invalid) 5519 return false; 5520 5521 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5522 5523 if (!Obj) 5524 return false; 5525 5526 if (!Obj.Value) { 5527 // The object is not usable in constant expressions, so we can't inspect 5528 // its value to see if it's in-lifetime or what the active union members 5529 // are. We can still check for a one-past-the-end lvalue. 5530 if (This.Designator.isOnePastTheEnd() || 5531 This.Designator.isMostDerivedAnUnsizedArray()) { 5532 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5533 ? diag::note_constexpr_access_past_end 5534 : diag::note_constexpr_access_unsized_array) 5535 << AK; 5536 return false; 5537 } else if (Polymorphic) { 5538 // Conservatively refuse to perform a polymorphic operation if we would 5539 // not be able to read a notional 'vptr' value. 5540 APValue Val; 5541 This.moveInto(Val); 5542 QualType StarThisType = 5543 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5544 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5545 << AK << Val.getAsString(Info.Ctx, StarThisType); 5546 return false; 5547 } 5548 return true; 5549 } 5550 5551 CheckDynamicTypeHandler Handler{AK}; 5552 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5553 } 5554 5555 /// Check that the pointee of the 'this' pointer in a member function call is 5556 /// either within its lifetime or in its period of construction or destruction. 5557 static bool 5558 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5559 const LValue &This, 5560 const CXXMethodDecl *NamedMember) { 5561 return checkDynamicType( 5562 Info, E, This, 5563 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5564 } 5565 5566 struct DynamicType { 5567 /// The dynamic class type of the object. 5568 const CXXRecordDecl *Type; 5569 /// The corresponding path length in the lvalue. 5570 unsigned PathLength; 5571 }; 5572 5573 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5574 unsigned PathLength) { 5575 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5576 Designator.Entries.size() && "invalid path length"); 5577 return (PathLength == Designator.MostDerivedPathLength) 5578 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5579 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5580 } 5581 5582 /// Determine the dynamic type of an object. 5583 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5584 LValue &This, AccessKinds AK) { 5585 // If we don't have an lvalue denoting an object of class type, there is no 5586 // meaningful dynamic type. (We consider objects of non-class type to have no 5587 // dynamic type.) 5588 if (!checkDynamicType(Info, E, This, AK, true)) 5589 return None; 5590 5591 // Refuse to compute a dynamic type in the presence of virtual bases. This 5592 // shouldn't happen other than in constant-folding situations, since literal 5593 // types can't have virtual bases. 5594 // 5595 // Note that consumers of DynamicType assume that the type has no virtual 5596 // bases, and will need modifications if this restriction is relaxed. 5597 const CXXRecordDecl *Class = 5598 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5599 if (!Class || Class->getNumVBases()) { 5600 Info.FFDiag(E); 5601 return None; 5602 } 5603 5604 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5605 // binary search here instead. But the overwhelmingly common case is that 5606 // we're not in the middle of a constructor, so it probably doesn't matter 5607 // in practice. 5608 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5609 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5610 PathLength <= Path.size(); ++PathLength) { 5611 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5612 Path.slice(0, PathLength))) { 5613 case ConstructionPhase::Bases: 5614 case ConstructionPhase::DestroyingBases: 5615 // We're constructing or destroying a base class. This is not the dynamic 5616 // type. 5617 break; 5618 5619 case ConstructionPhase::None: 5620 case ConstructionPhase::AfterBases: 5621 case ConstructionPhase::AfterFields: 5622 case ConstructionPhase::Destroying: 5623 // We've finished constructing the base classes and not yet started 5624 // destroying them again, so this is the dynamic type. 5625 return DynamicType{getBaseClassType(This.Designator, PathLength), 5626 PathLength}; 5627 } 5628 } 5629 5630 // CWG issue 1517: we're constructing a base class of the object described by 5631 // 'This', so that object has not yet begun its period of construction and 5632 // any polymorphic operation on it results in undefined behavior. 5633 Info.FFDiag(E); 5634 return None; 5635 } 5636 5637 /// Perform virtual dispatch. 5638 static const CXXMethodDecl *HandleVirtualDispatch( 5639 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5640 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5641 Optional<DynamicType> DynType = ComputeDynamicType( 5642 Info, E, This, 5643 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5644 if (!DynType) 5645 return nullptr; 5646 5647 // Find the final overrider. It must be declared in one of the classes on the 5648 // path from the dynamic type to the static type. 5649 // FIXME: If we ever allow literal types to have virtual base classes, that 5650 // won't be true. 5651 const CXXMethodDecl *Callee = Found; 5652 unsigned PathLength = DynType->PathLength; 5653 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5654 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5655 const CXXMethodDecl *Overrider = 5656 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5657 if (Overrider) { 5658 Callee = Overrider; 5659 break; 5660 } 5661 } 5662 5663 // C++2a [class.abstract]p6: 5664 // the effect of making a virtual call to a pure virtual function [...] is 5665 // undefined 5666 if (Callee->isPure()) { 5667 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5668 Info.Note(Callee->getLocation(), diag::note_declared_at); 5669 return nullptr; 5670 } 5671 5672 // If necessary, walk the rest of the path to determine the sequence of 5673 // covariant adjustment steps to apply. 5674 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5675 Found->getReturnType())) { 5676 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5677 for (unsigned CovariantPathLength = PathLength + 1; 5678 CovariantPathLength != This.Designator.Entries.size(); 5679 ++CovariantPathLength) { 5680 const CXXRecordDecl *NextClass = 5681 getBaseClassType(This.Designator, CovariantPathLength); 5682 const CXXMethodDecl *Next = 5683 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5684 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5685 Next->getReturnType(), CovariantAdjustmentPath.back())) 5686 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5687 } 5688 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5689 CovariantAdjustmentPath.back())) 5690 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5691 } 5692 5693 // Perform 'this' adjustment. 5694 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5695 return nullptr; 5696 5697 return Callee; 5698 } 5699 5700 /// Perform the adjustment from a value returned by a virtual function to 5701 /// a value of the statically expected type, which may be a pointer or 5702 /// reference to a base class of the returned type. 5703 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5704 APValue &Result, 5705 ArrayRef<QualType> Path) { 5706 assert(Result.isLValue() && 5707 "unexpected kind of APValue for covariant return"); 5708 if (Result.isNullPointer()) 5709 return true; 5710 5711 LValue LVal; 5712 LVal.setFrom(Info.Ctx, Result); 5713 5714 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5715 for (unsigned I = 1; I != Path.size(); ++I) { 5716 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5717 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5718 if (OldClass != NewClass && 5719 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5720 return false; 5721 OldClass = NewClass; 5722 } 5723 5724 LVal.moveInto(Result); 5725 return true; 5726 } 5727 5728 /// Determine whether \p Base, which is known to be a direct base class of 5729 /// \p Derived, is a public base class. 5730 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5731 const CXXRecordDecl *Base) { 5732 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5733 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5734 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5735 return BaseSpec.getAccessSpecifier() == AS_public; 5736 } 5737 llvm_unreachable("Base is not a direct base of Derived"); 5738 } 5739 5740 /// Apply the given dynamic cast operation on the provided lvalue. 5741 /// 5742 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5743 /// to find a suitable target subobject. 5744 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5745 LValue &Ptr) { 5746 // We can't do anything with a non-symbolic pointer value. 5747 SubobjectDesignator &D = Ptr.Designator; 5748 if (D.Invalid) 5749 return false; 5750 5751 // C++ [expr.dynamic.cast]p6: 5752 // If v is a null pointer value, the result is a null pointer value. 5753 if (Ptr.isNullPointer() && !E->isGLValue()) 5754 return true; 5755 5756 // For all the other cases, we need the pointer to point to an object within 5757 // its lifetime / period of construction / destruction, and we need to know 5758 // its dynamic type. 5759 Optional<DynamicType> DynType = 5760 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5761 if (!DynType) 5762 return false; 5763 5764 // C++ [expr.dynamic.cast]p7: 5765 // If T is "pointer to cv void", then the result is a pointer to the most 5766 // derived object 5767 if (E->getType()->isVoidPointerType()) 5768 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5769 5770 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5771 assert(C && "dynamic_cast target is not void pointer nor class"); 5772 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5773 5774 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5775 // C++ [expr.dynamic.cast]p9: 5776 if (!E->isGLValue()) { 5777 // The value of a failed cast to pointer type is the null pointer value 5778 // of the required result type. 5779 Ptr.setNull(Info.Ctx, E->getType()); 5780 return true; 5781 } 5782 5783 // A failed cast to reference type throws [...] std::bad_cast. 5784 unsigned DiagKind; 5785 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5786 DynType->Type->isDerivedFrom(C))) 5787 DiagKind = 0; 5788 else if (!Paths || Paths->begin() == Paths->end()) 5789 DiagKind = 1; 5790 else if (Paths->isAmbiguous(CQT)) 5791 DiagKind = 2; 5792 else { 5793 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5794 DiagKind = 3; 5795 } 5796 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5797 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5798 << Info.Ctx.getRecordType(DynType->Type) 5799 << E->getType().getUnqualifiedType(); 5800 return false; 5801 }; 5802 5803 // Runtime check, phase 1: 5804 // Walk from the base subobject towards the derived object looking for the 5805 // target type. 5806 for (int PathLength = Ptr.Designator.Entries.size(); 5807 PathLength >= (int)DynType->PathLength; --PathLength) { 5808 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5809 if (declaresSameEntity(Class, C)) 5810 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5811 // We can only walk across public inheritance edges. 5812 if (PathLength > (int)DynType->PathLength && 5813 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5814 Class)) 5815 return RuntimeCheckFailed(nullptr); 5816 } 5817 5818 // Runtime check, phase 2: 5819 // Search the dynamic type for an unambiguous public base of type C. 5820 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5821 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5822 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5823 Paths.front().Access == AS_public) { 5824 // Downcast to the dynamic type... 5825 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5826 return false; 5827 // ... then upcast to the chosen base class subobject. 5828 for (CXXBasePathElement &Elem : Paths.front()) 5829 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5830 return false; 5831 return true; 5832 } 5833 5834 // Otherwise, the runtime check fails. 5835 return RuntimeCheckFailed(&Paths); 5836 } 5837 5838 namespace { 5839 struct StartLifetimeOfUnionMemberHandler { 5840 EvalInfo &Info; 5841 const Expr *LHSExpr; 5842 const FieldDecl *Field; 5843 bool DuringInit; 5844 bool Failed = false; 5845 static const AccessKinds AccessKind = AK_Assign; 5846 5847 typedef bool result_type; 5848 bool failed() { return Failed; } 5849 bool found(APValue &Subobj, QualType SubobjType) { 5850 // We are supposed to perform no initialization but begin the lifetime of 5851 // the object. We interpret that as meaning to do what default 5852 // initialization of the object would do if all constructors involved were 5853 // trivial: 5854 // * All base, non-variant member, and array element subobjects' lifetimes 5855 // begin 5856 // * No variant members' lifetimes begin 5857 // * All scalar subobjects whose lifetimes begin have indeterminate values 5858 assert(SubobjType->isUnionType()); 5859 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5860 // This union member is already active. If it's also in-lifetime, there's 5861 // nothing to do. 5862 if (Subobj.getUnionValue().hasValue()) 5863 return true; 5864 } else if (DuringInit) { 5865 // We're currently in the process of initializing a different union 5866 // member. If we carried on, that initialization would attempt to 5867 // store to an inactive union member, resulting in undefined behavior. 5868 Info.FFDiag(LHSExpr, 5869 diag::note_constexpr_union_member_change_during_init); 5870 return false; 5871 } 5872 APValue Result; 5873 Failed = !getDefaultInitValue(Field->getType(), Result); 5874 Subobj.setUnion(Field, Result); 5875 return true; 5876 } 5877 bool found(APSInt &Value, QualType SubobjType) { 5878 llvm_unreachable("wrong value kind for union object"); 5879 } 5880 bool found(APFloat &Value, QualType SubobjType) { 5881 llvm_unreachable("wrong value kind for union object"); 5882 } 5883 }; 5884 } // end anonymous namespace 5885 5886 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5887 5888 /// Handle a builtin simple-assignment or a call to a trivial assignment 5889 /// operator whose left-hand side might involve a union member access. If it 5890 /// does, implicitly start the lifetime of any accessed union elements per 5891 /// C++20 [class.union]5. 5892 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5893 const LValue &LHS) { 5894 if (LHS.InvalidBase || LHS.Designator.Invalid) 5895 return false; 5896 5897 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5898 // C++ [class.union]p5: 5899 // define the set S(E) of subexpressions of E as follows: 5900 unsigned PathLength = LHS.Designator.Entries.size(); 5901 for (const Expr *E = LHSExpr; E != nullptr;) { 5902 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5903 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5904 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5905 // Note that we can't implicitly start the lifetime of a reference, 5906 // so we don't need to proceed any further if we reach one. 5907 if (!FD || FD->getType()->isReferenceType()) 5908 break; 5909 5910 // ... and also contains A.B if B names a union member ... 5911 if (FD->getParent()->isUnion()) { 5912 // ... of a non-class, non-array type, or of a class type with a 5913 // trivial default constructor that is not deleted, or an array of 5914 // such types. 5915 auto *RD = 5916 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5917 if (!RD || RD->hasTrivialDefaultConstructor()) 5918 UnionPathLengths.push_back({PathLength - 1, FD}); 5919 } 5920 5921 E = ME->getBase(); 5922 --PathLength; 5923 assert(declaresSameEntity(FD, 5924 LHS.Designator.Entries[PathLength] 5925 .getAsBaseOrMember().getPointer())); 5926 5927 // -- If E is of the form A[B] and is interpreted as a built-in array 5928 // subscripting operator, S(E) is [S(the array operand, if any)]. 5929 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5930 // Step over an ArrayToPointerDecay implicit cast. 5931 auto *Base = ASE->getBase()->IgnoreImplicit(); 5932 if (!Base->getType()->isArrayType()) 5933 break; 5934 5935 E = Base; 5936 --PathLength; 5937 5938 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5939 // Step over a derived-to-base conversion. 5940 E = ICE->getSubExpr(); 5941 if (ICE->getCastKind() == CK_NoOp) 5942 continue; 5943 if (ICE->getCastKind() != CK_DerivedToBase && 5944 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5945 break; 5946 // Walk path backwards as we walk up from the base to the derived class. 5947 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5948 --PathLength; 5949 (void)Elt; 5950 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5951 LHS.Designator.Entries[PathLength] 5952 .getAsBaseOrMember().getPointer())); 5953 } 5954 5955 // -- Otherwise, S(E) is empty. 5956 } else { 5957 break; 5958 } 5959 } 5960 5961 // Common case: no unions' lifetimes are started. 5962 if (UnionPathLengths.empty()) 5963 return true; 5964 5965 // if modification of X [would access an inactive union member], an object 5966 // of the type of X is implicitly created 5967 CompleteObject Obj = 5968 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5969 if (!Obj) 5970 return false; 5971 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5972 llvm::reverse(UnionPathLengths)) { 5973 // Form a designator for the union object. 5974 SubobjectDesignator D = LHS.Designator; 5975 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5976 5977 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5978 ConstructionPhase::AfterBases; 5979 StartLifetimeOfUnionMemberHandler StartLifetime{ 5980 Info, LHSExpr, LengthAndField.second, DuringInit}; 5981 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5982 return false; 5983 } 5984 5985 return true; 5986 } 5987 5988 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5989 CallRef Call, EvalInfo &Info, 5990 bool NonNull = false) { 5991 LValue LV; 5992 // Create the parameter slot and register its destruction. For a vararg 5993 // argument, create a temporary. 5994 // FIXME: For calling conventions that destroy parameters in the callee, 5995 // should we consider performing destruction when the function returns 5996 // instead? 5997 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 5998 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 5999 ScopeKind::Call, LV); 6000 if (!EvaluateInPlace(V, Info, LV, Arg)) 6001 return false; 6002 6003 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6004 // undefined behavior, so is non-constant. 6005 if (NonNull && V.isLValue() && V.isNullPointer()) { 6006 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6007 return false; 6008 } 6009 6010 return true; 6011 } 6012 6013 /// Evaluate the arguments to a function call. 6014 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6015 EvalInfo &Info, const FunctionDecl *Callee, 6016 bool RightToLeft = false) { 6017 bool Success = true; 6018 llvm::SmallBitVector ForbiddenNullArgs; 6019 if (Callee->hasAttr<NonNullAttr>()) { 6020 ForbiddenNullArgs.resize(Args.size()); 6021 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6022 if (!Attr->args_size()) { 6023 ForbiddenNullArgs.set(); 6024 break; 6025 } else 6026 for (auto Idx : Attr->args()) { 6027 unsigned ASTIdx = Idx.getASTIndex(); 6028 if (ASTIdx >= Args.size()) 6029 continue; 6030 ForbiddenNullArgs[ASTIdx] = 1; 6031 } 6032 } 6033 } 6034 for (unsigned I = 0; I < Args.size(); I++) { 6035 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6036 const ParmVarDecl *PVD = 6037 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6038 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6039 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6040 // If we're checking for a potential constant expression, evaluate all 6041 // initializers even if some of them fail. 6042 if (!Info.noteFailure()) 6043 return false; 6044 Success = false; 6045 } 6046 } 6047 return Success; 6048 } 6049 6050 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6051 /// constructor or assignment operator. 6052 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6053 const Expr *E, APValue &Result, 6054 bool CopyObjectRepresentation) { 6055 // Find the reference argument. 6056 CallStackFrame *Frame = Info.CurrentCall; 6057 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6058 if (!RefValue) { 6059 Info.FFDiag(E); 6060 return false; 6061 } 6062 6063 // Copy out the contents of the RHS object. 6064 LValue RefLValue; 6065 RefLValue.setFrom(Info.Ctx, *RefValue); 6066 return handleLValueToRValueConversion( 6067 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6068 CopyObjectRepresentation); 6069 } 6070 6071 /// Evaluate a function call. 6072 static bool HandleFunctionCall(SourceLocation CallLoc, 6073 const FunctionDecl *Callee, const LValue *This, 6074 ArrayRef<const Expr *> Args, CallRef Call, 6075 const Stmt *Body, EvalInfo &Info, 6076 APValue &Result, const LValue *ResultSlot) { 6077 if (!Info.CheckCallLimit(CallLoc)) 6078 return false; 6079 6080 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6081 6082 // For a trivial copy or move assignment, perform an APValue copy. This is 6083 // essential for unions, where the operations performed by the assignment 6084 // operator cannot be represented as statements. 6085 // 6086 // Skip this for non-union classes with no fields; in that case, the defaulted 6087 // copy/move does not actually read the object. 6088 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6089 if (MD && MD->isDefaulted() && 6090 (MD->getParent()->isUnion() || 6091 (MD->isTrivial() && 6092 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6093 assert(This && 6094 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6095 APValue RHSValue; 6096 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6097 MD->getParent()->isUnion())) 6098 return false; 6099 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6100 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6101 return false; 6102 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6103 RHSValue)) 6104 return false; 6105 This->moveInto(Result); 6106 return true; 6107 } else if (MD && isLambdaCallOperator(MD)) { 6108 // We're in a lambda; determine the lambda capture field maps unless we're 6109 // just constexpr checking a lambda's call operator. constexpr checking is 6110 // done before the captures have been added to the closure object (unless 6111 // we're inferring constexpr-ness), so we don't have access to them in this 6112 // case. But since we don't need the captures to constexpr check, we can 6113 // just ignore them. 6114 if (!Info.checkingPotentialConstantExpression()) 6115 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6116 Frame.LambdaThisCaptureField); 6117 } 6118 6119 StmtResult Ret = {Result, ResultSlot}; 6120 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6121 if (ESR == ESR_Succeeded) { 6122 if (Callee->getReturnType()->isVoidType()) 6123 return true; 6124 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6125 } 6126 return ESR == ESR_Returned; 6127 } 6128 6129 /// Evaluate a constructor call. 6130 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6131 CallRef Call, 6132 const CXXConstructorDecl *Definition, 6133 EvalInfo &Info, APValue &Result) { 6134 SourceLocation CallLoc = E->getExprLoc(); 6135 if (!Info.CheckCallLimit(CallLoc)) 6136 return false; 6137 6138 const CXXRecordDecl *RD = Definition->getParent(); 6139 if (RD->getNumVBases()) { 6140 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6141 return false; 6142 } 6143 6144 EvalInfo::EvaluatingConstructorRAII EvalObj( 6145 Info, 6146 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6147 RD->getNumBases()); 6148 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6149 6150 // FIXME: Creating an APValue just to hold a nonexistent return value is 6151 // wasteful. 6152 APValue RetVal; 6153 StmtResult Ret = {RetVal, nullptr}; 6154 6155 // If it's a delegating constructor, delegate. 6156 if (Definition->isDelegatingConstructor()) { 6157 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6158 if ((*I)->getInit()->isValueDependent()) { 6159 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6160 return false; 6161 } else { 6162 FullExpressionRAII InitScope(Info); 6163 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6164 !InitScope.destroy()) 6165 return false; 6166 } 6167 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6168 } 6169 6170 // For a trivial copy or move constructor, perform an APValue copy. This is 6171 // essential for unions (or classes with anonymous union members), where the 6172 // operations performed by the constructor cannot be represented by 6173 // ctor-initializers. 6174 // 6175 // Skip this for empty non-union classes; we should not perform an 6176 // lvalue-to-rvalue conversion on them because their copy constructor does not 6177 // actually read them. 6178 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6179 (Definition->getParent()->isUnion() || 6180 (Definition->isTrivial() && 6181 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6182 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6183 Definition->getParent()->isUnion()); 6184 } 6185 6186 // Reserve space for the struct members. 6187 if (!Result.hasValue()) { 6188 if (!RD->isUnion()) 6189 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6190 std::distance(RD->field_begin(), RD->field_end())); 6191 else 6192 // A union starts with no active member. 6193 Result = APValue((const FieldDecl*)nullptr); 6194 } 6195 6196 if (RD->isInvalidDecl()) return false; 6197 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6198 6199 // A scope for temporaries lifetime-extended by reference members. 6200 BlockScopeRAII LifetimeExtendedScope(Info); 6201 6202 bool Success = true; 6203 unsigned BasesSeen = 0; 6204 #ifndef NDEBUG 6205 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6206 #endif 6207 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6208 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6209 // We might be initializing the same field again if this is an indirect 6210 // field initialization. 6211 if (FieldIt == RD->field_end() || 6212 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6213 assert(Indirect && "fields out of order?"); 6214 return; 6215 } 6216 6217 // Default-initialize any fields with no explicit initializer. 6218 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6219 assert(FieldIt != RD->field_end() && "missing field?"); 6220 if (!FieldIt->isUnnamedBitfield()) 6221 Success &= getDefaultInitValue( 6222 FieldIt->getType(), 6223 Result.getStructField(FieldIt->getFieldIndex())); 6224 } 6225 ++FieldIt; 6226 }; 6227 for (const auto *I : Definition->inits()) { 6228 LValue Subobject = This; 6229 LValue SubobjectParent = This; 6230 APValue *Value = &Result; 6231 6232 // Determine the subobject to initialize. 6233 FieldDecl *FD = nullptr; 6234 if (I->isBaseInitializer()) { 6235 QualType BaseType(I->getBaseClass(), 0); 6236 #ifndef NDEBUG 6237 // Non-virtual base classes are initialized in the order in the class 6238 // definition. We have already checked for virtual base classes. 6239 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6240 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6241 "base class initializers not in expected order"); 6242 ++BaseIt; 6243 #endif 6244 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6245 BaseType->getAsCXXRecordDecl(), &Layout)) 6246 return false; 6247 Value = &Result.getStructBase(BasesSeen++); 6248 } else if ((FD = I->getMember())) { 6249 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6250 return false; 6251 if (RD->isUnion()) { 6252 Result = APValue(FD); 6253 Value = &Result.getUnionValue(); 6254 } else { 6255 SkipToField(FD, false); 6256 Value = &Result.getStructField(FD->getFieldIndex()); 6257 } 6258 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6259 // Walk the indirect field decl's chain to find the object to initialize, 6260 // and make sure we've initialized every step along it. 6261 auto IndirectFieldChain = IFD->chain(); 6262 for (auto *C : IndirectFieldChain) { 6263 FD = cast<FieldDecl>(C); 6264 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6265 // Switch the union field if it differs. This happens if we had 6266 // preceding zero-initialization, and we're now initializing a union 6267 // subobject other than the first. 6268 // FIXME: In this case, the values of the other subobjects are 6269 // specified, since zero-initialization sets all padding bits to zero. 6270 if (!Value->hasValue() || 6271 (Value->isUnion() && Value->getUnionField() != FD)) { 6272 if (CD->isUnion()) 6273 *Value = APValue(FD); 6274 else 6275 // FIXME: This immediately starts the lifetime of all members of 6276 // an anonymous struct. It would be preferable to strictly start 6277 // member lifetime in initialization order. 6278 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6279 } 6280 // Store Subobject as its parent before updating it for the last element 6281 // in the chain. 6282 if (C == IndirectFieldChain.back()) 6283 SubobjectParent = Subobject; 6284 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6285 return false; 6286 if (CD->isUnion()) 6287 Value = &Value->getUnionValue(); 6288 else { 6289 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6290 SkipToField(FD, true); 6291 Value = &Value->getStructField(FD->getFieldIndex()); 6292 } 6293 } 6294 } else { 6295 llvm_unreachable("unknown base initializer kind"); 6296 } 6297 6298 // Need to override This for implicit field initializers as in this case 6299 // This refers to innermost anonymous struct/union containing initializer, 6300 // not to currently constructed class. 6301 const Expr *Init = I->getInit(); 6302 if (Init->isValueDependent()) { 6303 if (!EvaluateDependentExpr(Init, Info)) 6304 return false; 6305 } else { 6306 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6307 isa<CXXDefaultInitExpr>(Init)); 6308 FullExpressionRAII InitScope(Info); 6309 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6310 (FD && FD->isBitField() && 6311 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6312 // If we're checking for a potential constant expression, evaluate all 6313 // initializers even if some of them fail. 6314 if (!Info.noteFailure()) 6315 return false; 6316 Success = false; 6317 } 6318 } 6319 6320 // This is the point at which the dynamic type of the object becomes this 6321 // class type. 6322 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6323 EvalObj.finishedConstructingBases(); 6324 } 6325 6326 // Default-initialize any remaining fields. 6327 if (!RD->isUnion()) { 6328 for (; FieldIt != RD->field_end(); ++FieldIt) { 6329 if (!FieldIt->isUnnamedBitfield()) 6330 Success &= getDefaultInitValue( 6331 FieldIt->getType(), 6332 Result.getStructField(FieldIt->getFieldIndex())); 6333 } 6334 } 6335 6336 EvalObj.finishedConstructingFields(); 6337 6338 return Success && 6339 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6340 LifetimeExtendedScope.destroy(); 6341 } 6342 6343 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6344 ArrayRef<const Expr*> Args, 6345 const CXXConstructorDecl *Definition, 6346 EvalInfo &Info, APValue &Result) { 6347 CallScopeRAII CallScope(Info); 6348 CallRef Call = Info.CurrentCall->createCall(Definition); 6349 if (!EvaluateArgs(Args, Call, Info, Definition)) 6350 return false; 6351 6352 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6353 CallScope.destroy(); 6354 } 6355 6356 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6357 const LValue &This, APValue &Value, 6358 QualType T) { 6359 // Objects can only be destroyed while they're within their lifetimes. 6360 // FIXME: We have no representation for whether an object of type nullptr_t 6361 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6362 // as indeterminate instead? 6363 if (Value.isAbsent() && !T->isNullPtrType()) { 6364 APValue Printable; 6365 This.moveInto(Printable); 6366 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6367 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6368 return false; 6369 } 6370 6371 // Invent an expression for location purposes. 6372 // FIXME: We shouldn't need to do this. 6373 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6374 6375 // For arrays, destroy elements right-to-left. 6376 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6377 uint64_t Size = CAT->getSize().getZExtValue(); 6378 QualType ElemT = CAT->getElementType(); 6379 6380 LValue ElemLV = This; 6381 ElemLV.addArray(Info, &LocE, CAT); 6382 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6383 return false; 6384 6385 // Ensure that we have actual array elements available to destroy; the 6386 // destructors might mutate the value, so we can't run them on the array 6387 // filler. 6388 if (Size && Size > Value.getArrayInitializedElts()) 6389 expandArray(Value, Value.getArraySize() - 1); 6390 6391 for (; Size != 0; --Size) { 6392 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6393 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6394 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6395 return false; 6396 } 6397 6398 // End the lifetime of this array now. 6399 Value = APValue(); 6400 return true; 6401 } 6402 6403 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6404 if (!RD) { 6405 if (T.isDestructedType()) { 6406 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6407 return false; 6408 } 6409 6410 Value = APValue(); 6411 return true; 6412 } 6413 6414 if (RD->getNumVBases()) { 6415 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6416 return false; 6417 } 6418 6419 const CXXDestructorDecl *DD = RD->getDestructor(); 6420 if (!DD && !RD->hasTrivialDestructor()) { 6421 Info.FFDiag(CallLoc); 6422 return false; 6423 } 6424 6425 if (!DD || DD->isTrivial() || 6426 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6427 // A trivial destructor just ends the lifetime of the object. Check for 6428 // this case before checking for a body, because we might not bother 6429 // building a body for a trivial destructor. Note that it doesn't matter 6430 // whether the destructor is constexpr in this case; all trivial 6431 // destructors are constexpr. 6432 // 6433 // If an anonymous union would be destroyed, some enclosing destructor must 6434 // have been explicitly defined, and the anonymous union destruction should 6435 // have no effect. 6436 Value = APValue(); 6437 return true; 6438 } 6439 6440 if (!Info.CheckCallLimit(CallLoc)) 6441 return false; 6442 6443 const FunctionDecl *Definition = nullptr; 6444 const Stmt *Body = DD->getBody(Definition); 6445 6446 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6447 return false; 6448 6449 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6450 6451 // We're now in the period of destruction of this object. 6452 unsigned BasesLeft = RD->getNumBases(); 6453 EvalInfo::EvaluatingDestructorRAII EvalObj( 6454 Info, 6455 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6456 if (!EvalObj.DidInsert) { 6457 // C++2a [class.dtor]p19: 6458 // the behavior is undefined if the destructor is invoked for an object 6459 // whose lifetime has ended 6460 // (Note that formally the lifetime ends when the period of destruction 6461 // begins, even though certain uses of the object remain valid until the 6462 // period of destruction ends.) 6463 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6464 return false; 6465 } 6466 6467 // FIXME: Creating an APValue just to hold a nonexistent return value is 6468 // wasteful. 6469 APValue RetVal; 6470 StmtResult Ret = {RetVal, nullptr}; 6471 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6472 return false; 6473 6474 // A union destructor does not implicitly destroy its members. 6475 if (RD->isUnion()) 6476 return true; 6477 6478 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6479 6480 // We don't have a good way to iterate fields in reverse, so collect all the 6481 // fields first and then walk them backwards. 6482 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6483 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6484 if (FD->isUnnamedBitfield()) 6485 continue; 6486 6487 LValue Subobject = This; 6488 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6489 return false; 6490 6491 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6492 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6493 FD->getType())) 6494 return false; 6495 } 6496 6497 if (BasesLeft != 0) 6498 EvalObj.startedDestroyingBases(); 6499 6500 // Destroy base classes in reverse order. 6501 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6502 --BasesLeft; 6503 6504 QualType BaseType = Base.getType(); 6505 LValue Subobject = This; 6506 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6507 BaseType->getAsCXXRecordDecl(), &Layout)) 6508 return false; 6509 6510 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6511 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6512 BaseType)) 6513 return false; 6514 } 6515 assert(BasesLeft == 0 && "NumBases was wrong?"); 6516 6517 // The period of destruction ends now. The object is gone. 6518 Value = APValue(); 6519 return true; 6520 } 6521 6522 namespace { 6523 struct DestroyObjectHandler { 6524 EvalInfo &Info; 6525 const Expr *E; 6526 const LValue &This; 6527 const AccessKinds AccessKind; 6528 6529 typedef bool result_type; 6530 bool failed() { return false; } 6531 bool found(APValue &Subobj, QualType SubobjType) { 6532 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6533 SubobjType); 6534 } 6535 bool found(APSInt &Value, QualType SubobjType) { 6536 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6537 return false; 6538 } 6539 bool found(APFloat &Value, QualType SubobjType) { 6540 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6541 return false; 6542 } 6543 }; 6544 } 6545 6546 /// Perform a destructor or pseudo-destructor call on the given object, which 6547 /// might in general not be a complete object. 6548 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6549 const LValue &This, QualType ThisType) { 6550 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6551 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6552 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6553 } 6554 6555 /// Destroy and end the lifetime of the given complete object. 6556 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6557 APValue::LValueBase LVBase, APValue &Value, 6558 QualType T) { 6559 // If we've had an unmodeled side-effect, we can't rely on mutable state 6560 // (such as the object we're about to destroy) being correct. 6561 if (Info.EvalStatus.HasSideEffects) 6562 return false; 6563 6564 LValue LV; 6565 LV.set({LVBase}); 6566 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6567 } 6568 6569 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6570 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6571 LValue &Result) { 6572 if (Info.checkingPotentialConstantExpression() || 6573 Info.SpeculativeEvaluationDepth) 6574 return false; 6575 6576 // This is permitted only within a call to std::allocator<T>::allocate. 6577 auto Caller = Info.getStdAllocatorCaller("allocate"); 6578 if (!Caller) { 6579 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6580 ? diag::note_constexpr_new_untyped 6581 : diag::note_constexpr_new); 6582 return false; 6583 } 6584 6585 QualType ElemType = Caller.ElemType; 6586 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6587 Info.FFDiag(E->getExprLoc(), 6588 diag::note_constexpr_new_not_complete_object_type) 6589 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6590 return false; 6591 } 6592 6593 APSInt ByteSize; 6594 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6595 return false; 6596 bool IsNothrow = false; 6597 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6598 EvaluateIgnoredValue(Info, E->getArg(I)); 6599 IsNothrow |= E->getType()->isNothrowT(); 6600 } 6601 6602 CharUnits ElemSize; 6603 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6604 return false; 6605 APInt Size, Remainder; 6606 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6607 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6608 if (Remainder != 0) { 6609 // This likely indicates a bug in the implementation of 'std::allocator'. 6610 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6611 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6612 return false; 6613 } 6614 6615 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6616 if (IsNothrow) { 6617 Result.setNull(Info.Ctx, E->getType()); 6618 return true; 6619 } 6620 6621 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6622 return false; 6623 } 6624 6625 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6626 ArrayType::Normal, 0); 6627 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6628 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6629 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6630 return true; 6631 } 6632 6633 static bool hasVirtualDestructor(QualType T) { 6634 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6635 if (CXXDestructorDecl *DD = RD->getDestructor()) 6636 return DD->isVirtual(); 6637 return false; 6638 } 6639 6640 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6641 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6642 if (CXXDestructorDecl *DD = RD->getDestructor()) 6643 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6644 return nullptr; 6645 } 6646 6647 /// Check that the given object is a suitable pointer to a heap allocation that 6648 /// still exists and is of the right kind for the purpose of a deletion. 6649 /// 6650 /// On success, returns the heap allocation to deallocate. On failure, produces 6651 /// a diagnostic and returns None. 6652 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6653 const LValue &Pointer, 6654 DynAlloc::Kind DeallocKind) { 6655 auto PointerAsString = [&] { 6656 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6657 }; 6658 6659 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6660 if (!DA) { 6661 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6662 << PointerAsString(); 6663 if (Pointer.Base) 6664 NoteLValueLocation(Info, Pointer.Base); 6665 return None; 6666 } 6667 6668 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6669 if (!Alloc) { 6670 Info.FFDiag(E, diag::note_constexpr_double_delete); 6671 return None; 6672 } 6673 6674 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6675 if (DeallocKind != (*Alloc)->getKind()) { 6676 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6677 << DeallocKind << (*Alloc)->getKind() << AllocType; 6678 NoteLValueLocation(Info, Pointer.Base); 6679 return None; 6680 } 6681 6682 bool Subobject = false; 6683 if (DeallocKind == DynAlloc::New) { 6684 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6685 Pointer.Designator.isOnePastTheEnd(); 6686 } else { 6687 Subobject = Pointer.Designator.Entries.size() != 1 || 6688 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6689 } 6690 if (Subobject) { 6691 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6692 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6693 return None; 6694 } 6695 6696 return Alloc; 6697 } 6698 6699 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6700 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6701 if (Info.checkingPotentialConstantExpression() || 6702 Info.SpeculativeEvaluationDepth) 6703 return false; 6704 6705 // This is permitted only within a call to std::allocator<T>::deallocate. 6706 if (!Info.getStdAllocatorCaller("deallocate")) { 6707 Info.FFDiag(E->getExprLoc()); 6708 return true; 6709 } 6710 6711 LValue Pointer; 6712 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6713 return false; 6714 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6715 EvaluateIgnoredValue(Info, E->getArg(I)); 6716 6717 if (Pointer.Designator.Invalid) 6718 return false; 6719 6720 // Deleting a null pointer would have no effect, but it's not permitted by 6721 // std::allocator<T>::deallocate's contract. 6722 if (Pointer.isNullPointer()) { 6723 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6724 return true; 6725 } 6726 6727 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6728 return false; 6729 6730 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6731 return true; 6732 } 6733 6734 //===----------------------------------------------------------------------===// 6735 // Generic Evaluation 6736 //===----------------------------------------------------------------------===// 6737 namespace { 6738 6739 class BitCastBuffer { 6740 // FIXME: We're going to need bit-level granularity when we support 6741 // bit-fields. 6742 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6743 // we don't support a host or target where that is the case. Still, we should 6744 // use a more generic type in case we ever do. 6745 SmallVector<Optional<unsigned char>, 32> Bytes; 6746 6747 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6748 "Need at least 8 bit unsigned char"); 6749 6750 bool TargetIsLittleEndian; 6751 6752 public: 6753 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6754 : Bytes(Width.getQuantity()), 6755 TargetIsLittleEndian(TargetIsLittleEndian) {} 6756 6757 LLVM_NODISCARD 6758 bool readObject(CharUnits Offset, CharUnits Width, 6759 SmallVectorImpl<unsigned char> &Output) const { 6760 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6761 // If a byte of an integer is uninitialized, then the whole integer is 6762 // uninitalized. 6763 if (!Bytes[I.getQuantity()]) 6764 return false; 6765 Output.push_back(*Bytes[I.getQuantity()]); 6766 } 6767 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6768 std::reverse(Output.begin(), Output.end()); 6769 return true; 6770 } 6771 6772 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6773 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6774 std::reverse(Input.begin(), Input.end()); 6775 6776 size_t Index = 0; 6777 for (unsigned char Byte : Input) { 6778 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6779 Bytes[Offset.getQuantity() + Index] = Byte; 6780 ++Index; 6781 } 6782 } 6783 6784 size_t size() { return Bytes.size(); } 6785 }; 6786 6787 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6788 /// target would represent the value at runtime. 6789 class APValueToBufferConverter { 6790 EvalInfo &Info; 6791 BitCastBuffer Buffer; 6792 const CastExpr *BCE; 6793 6794 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6795 const CastExpr *BCE) 6796 : Info(Info), 6797 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6798 BCE(BCE) {} 6799 6800 bool visit(const APValue &Val, QualType Ty) { 6801 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6802 } 6803 6804 // Write out Val with type Ty into Buffer starting at Offset. 6805 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6806 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6807 6808 // As a special case, nullptr_t has an indeterminate value. 6809 if (Ty->isNullPtrType()) 6810 return true; 6811 6812 // Dig through Src to find the byte at SrcOffset. 6813 switch (Val.getKind()) { 6814 case APValue::Indeterminate: 6815 case APValue::None: 6816 return true; 6817 6818 case APValue::Int: 6819 return visitInt(Val.getInt(), Ty, Offset); 6820 case APValue::Float: 6821 return visitFloat(Val.getFloat(), Ty, Offset); 6822 case APValue::Array: 6823 return visitArray(Val, Ty, Offset); 6824 case APValue::Struct: 6825 return visitRecord(Val, Ty, Offset); 6826 6827 case APValue::ComplexInt: 6828 case APValue::ComplexFloat: 6829 case APValue::Vector: 6830 case APValue::FixedPoint: 6831 // FIXME: We should support these. 6832 6833 case APValue::Union: 6834 case APValue::MemberPointer: 6835 case APValue::AddrLabelDiff: { 6836 Info.FFDiag(BCE->getBeginLoc(), 6837 diag::note_constexpr_bit_cast_unsupported_type) 6838 << Ty; 6839 return false; 6840 } 6841 6842 case APValue::LValue: 6843 llvm_unreachable("LValue subobject in bit_cast?"); 6844 } 6845 llvm_unreachable("Unhandled APValue::ValueKind"); 6846 } 6847 6848 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6849 const RecordDecl *RD = Ty->getAsRecordDecl(); 6850 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6851 6852 // Visit the base classes. 6853 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6854 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6855 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6856 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6857 6858 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6859 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6860 return false; 6861 } 6862 } 6863 6864 // Visit the fields. 6865 unsigned FieldIdx = 0; 6866 for (FieldDecl *FD : RD->fields()) { 6867 if (FD->isBitField()) { 6868 Info.FFDiag(BCE->getBeginLoc(), 6869 diag::note_constexpr_bit_cast_unsupported_bitfield); 6870 return false; 6871 } 6872 6873 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6874 6875 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6876 "only bit-fields can have sub-char alignment"); 6877 CharUnits FieldOffset = 6878 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6879 QualType FieldTy = FD->getType(); 6880 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6881 return false; 6882 ++FieldIdx; 6883 } 6884 6885 return true; 6886 } 6887 6888 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6889 const auto *CAT = 6890 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6891 if (!CAT) 6892 return false; 6893 6894 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6895 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6896 unsigned ArraySize = Val.getArraySize(); 6897 // First, initialize the initialized elements. 6898 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6899 const APValue &SubObj = Val.getArrayInitializedElt(I); 6900 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6901 return false; 6902 } 6903 6904 // Next, initialize the rest of the array using the filler. 6905 if (Val.hasArrayFiller()) { 6906 const APValue &Filler = Val.getArrayFiller(); 6907 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6908 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6909 return false; 6910 } 6911 } 6912 6913 return true; 6914 } 6915 6916 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6917 APSInt AdjustedVal = Val; 6918 unsigned Width = AdjustedVal.getBitWidth(); 6919 if (Ty->isBooleanType()) { 6920 Width = Info.Ctx.getTypeSize(Ty); 6921 AdjustedVal = AdjustedVal.extend(Width); 6922 } 6923 6924 SmallVector<unsigned char, 8> Bytes(Width / 8); 6925 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6926 Buffer.writeObject(Offset, Bytes); 6927 return true; 6928 } 6929 6930 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6931 APSInt AsInt(Val.bitcastToAPInt()); 6932 return visitInt(AsInt, Ty, Offset); 6933 } 6934 6935 public: 6936 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6937 const CastExpr *BCE) { 6938 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6939 APValueToBufferConverter Converter(Info, DstSize, BCE); 6940 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6941 return None; 6942 return Converter.Buffer; 6943 } 6944 }; 6945 6946 /// Write an BitCastBuffer into an APValue. 6947 class BufferToAPValueConverter { 6948 EvalInfo &Info; 6949 const BitCastBuffer &Buffer; 6950 const CastExpr *BCE; 6951 6952 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6953 const CastExpr *BCE) 6954 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6955 6956 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6957 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6958 // Ideally this will be unreachable. 6959 llvm::NoneType unsupportedType(QualType Ty) { 6960 Info.FFDiag(BCE->getBeginLoc(), 6961 diag::note_constexpr_bit_cast_unsupported_type) 6962 << Ty; 6963 return None; 6964 } 6965 6966 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6967 Info.FFDiag(BCE->getBeginLoc(), 6968 diag::note_constexpr_bit_cast_unrepresentable_value) 6969 << Ty << toString(Val, /*Radix=*/10); 6970 return None; 6971 } 6972 6973 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6974 const EnumType *EnumSugar = nullptr) { 6975 if (T->isNullPtrType()) { 6976 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6977 return APValue((Expr *)nullptr, 6978 /*Offset=*/CharUnits::fromQuantity(NullValue), 6979 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6980 } 6981 6982 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6983 6984 // Work around floating point types that contain unused padding bytes. This 6985 // is really just `long double` on x86, which is the only fundamental type 6986 // with padding bytes. 6987 if (T->isRealFloatingType()) { 6988 const llvm::fltSemantics &Semantics = 6989 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6990 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6991 assert(NumBits % 8 == 0); 6992 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6993 if (NumBytes != SizeOf) 6994 SizeOf = NumBytes; 6995 } 6996 6997 SmallVector<uint8_t, 8> Bytes; 6998 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6999 // If this is std::byte or unsigned char, then its okay to store an 7000 // indeterminate value. 7001 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7002 bool IsUChar = 7003 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7004 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7005 if (!IsStdByte && !IsUChar) { 7006 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7007 Info.FFDiag(BCE->getExprLoc(), 7008 diag::note_constexpr_bit_cast_indet_dest) 7009 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7010 return None; 7011 } 7012 7013 return APValue::IndeterminateValue(); 7014 } 7015 7016 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7017 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7018 7019 if (T->isIntegralOrEnumerationType()) { 7020 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7021 7022 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7023 if (IntWidth != Val.getBitWidth()) { 7024 APSInt Truncated = Val.trunc(IntWidth); 7025 if (Truncated.extend(Val.getBitWidth()) != Val) 7026 return unrepresentableValue(QualType(T, 0), Val); 7027 Val = Truncated; 7028 } 7029 7030 return APValue(Val); 7031 } 7032 7033 if (T->isRealFloatingType()) { 7034 const llvm::fltSemantics &Semantics = 7035 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7036 return APValue(APFloat(Semantics, Val)); 7037 } 7038 7039 return unsupportedType(QualType(T, 0)); 7040 } 7041 7042 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7043 const RecordDecl *RD = RTy->getAsRecordDecl(); 7044 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7045 7046 unsigned NumBases = 0; 7047 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7048 NumBases = CXXRD->getNumBases(); 7049 7050 APValue ResultVal(APValue::UninitStruct(), NumBases, 7051 std::distance(RD->field_begin(), RD->field_end())); 7052 7053 // Visit the base classes. 7054 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7055 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7056 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7057 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7058 if (BaseDecl->isEmpty() || 7059 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7060 continue; 7061 7062 Optional<APValue> SubObj = visitType( 7063 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7064 if (!SubObj) 7065 return None; 7066 ResultVal.getStructBase(I) = *SubObj; 7067 } 7068 } 7069 7070 // Visit the fields. 7071 unsigned FieldIdx = 0; 7072 for (FieldDecl *FD : RD->fields()) { 7073 // FIXME: We don't currently support bit-fields. A lot of the logic for 7074 // this is in CodeGen, so we need to factor it around. 7075 if (FD->isBitField()) { 7076 Info.FFDiag(BCE->getBeginLoc(), 7077 diag::note_constexpr_bit_cast_unsupported_bitfield); 7078 return None; 7079 } 7080 7081 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7082 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7083 7084 CharUnits FieldOffset = 7085 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7086 Offset; 7087 QualType FieldTy = FD->getType(); 7088 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7089 if (!SubObj) 7090 return None; 7091 ResultVal.getStructField(FieldIdx) = *SubObj; 7092 ++FieldIdx; 7093 } 7094 7095 return ResultVal; 7096 } 7097 7098 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7099 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7100 assert(!RepresentationType.isNull() && 7101 "enum forward decl should be caught by Sema"); 7102 const auto *AsBuiltin = 7103 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7104 // Recurse into the underlying type. Treat std::byte transparently as 7105 // unsigned char. 7106 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7107 } 7108 7109 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7110 size_t Size = Ty->getSize().getLimitedValue(); 7111 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7112 7113 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7114 for (size_t I = 0; I != Size; ++I) { 7115 Optional<APValue> ElementValue = 7116 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7117 if (!ElementValue) 7118 return None; 7119 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7120 } 7121 7122 return ArrayValue; 7123 } 7124 7125 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7126 return unsupportedType(QualType(Ty, 0)); 7127 } 7128 7129 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7130 QualType Can = Ty.getCanonicalType(); 7131 7132 switch (Can->getTypeClass()) { 7133 #define TYPE(Class, Base) \ 7134 case Type::Class: \ 7135 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7136 #define ABSTRACT_TYPE(Class, Base) 7137 #define NON_CANONICAL_TYPE(Class, Base) \ 7138 case Type::Class: \ 7139 llvm_unreachable("non-canonical type should be impossible!"); 7140 #define DEPENDENT_TYPE(Class, Base) \ 7141 case Type::Class: \ 7142 llvm_unreachable( \ 7143 "dependent types aren't supported in the constant evaluator!"); 7144 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7145 case Type::Class: \ 7146 llvm_unreachable("either dependent or not canonical!"); 7147 #include "clang/AST/TypeNodes.inc" 7148 } 7149 llvm_unreachable("Unhandled Type::TypeClass"); 7150 } 7151 7152 public: 7153 // Pull out a full value of type DstType. 7154 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7155 const CastExpr *BCE) { 7156 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7157 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7158 } 7159 }; 7160 7161 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7162 QualType Ty, EvalInfo *Info, 7163 const ASTContext &Ctx, 7164 bool CheckingDest) { 7165 Ty = Ty.getCanonicalType(); 7166 7167 auto diag = [&](int Reason) { 7168 if (Info) 7169 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7170 << CheckingDest << (Reason == 4) << Reason; 7171 return false; 7172 }; 7173 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7174 if (Info) 7175 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7176 << NoteTy << Construct << Ty; 7177 return false; 7178 }; 7179 7180 if (Ty->isUnionType()) 7181 return diag(0); 7182 if (Ty->isPointerType()) 7183 return diag(1); 7184 if (Ty->isMemberPointerType()) 7185 return diag(2); 7186 if (Ty.isVolatileQualified()) 7187 return diag(3); 7188 7189 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7190 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7191 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7192 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7193 CheckingDest)) 7194 return note(1, BS.getType(), BS.getBeginLoc()); 7195 } 7196 for (FieldDecl *FD : Record->fields()) { 7197 if (FD->getType()->isReferenceType()) 7198 return diag(4); 7199 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7200 CheckingDest)) 7201 return note(0, FD->getType(), FD->getBeginLoc()); 7202 } 7203 } 7204 7205 if (Ty->isArrayType() && 7206 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7207 Info, Ctx, CheckingDest)) 7208 return false; 7209 7210 return true; 7211 } 7212 7213 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7214 const ASTContext &Ctx, 7215 const CastExpr *BCE) { 7216 bool DestOK = checkBitCastConstexprEligibilityType( 7217 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7218 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7219 BCE->getBeginLoc(), 7220 BCE->getSubExpr()->getType(), Info, Ctx, false); 7221 return SourceOK; 7222 } 7223 7224 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7225 APValue &SourceValue, 7226 const CastExpr *BCE) { 7227 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7228 "no host or target supports non 8-bit chars"); 7229 assert(SourceValue.isLValue() && 7230 "LValueToRValueBitcast requires an lvalue operand!"); 7231 7232 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7233 return false; 7234 7235 LValue SourceLValue; 7236 APValue SourceRValue; 7237 SourceLValue.setFrom(Info.Ctx, SourceValue); 7238 if (!handleLValueToRValueConversion( 7239 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7240 SourceRValue, /*WantObjectRepresentation=*/true)) 7241 return false; 7242 7243 // Read out SourceValue into a char buffer. 7244 Optional<BitCastBuffer> Buffer = 7245 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7246 if (!Buffer) 7247 return false; 7248 7249 // Write out the buffer into a new APValue. 7250 Optional<APValue> MaybeDestValue = 7251 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7252 if (!MaybeDestValue) 7253 return false; 7254 7255 DestValue = std::move(*MaybeDestValue); 7256 return true; 7257 } 7258 7259 template <class Derived> 7260 class ExprEvaluatorBase 7261 : public ConstStmtVisitor<Derived, bool> { 7262 private: 7263 Derived &getDerived() { return static_cast<Derived&>(*this); } 7264 bool DerivedSuccess(const APValue &V, const Expr *E) { 7265 return getDerived().Success(V, E); 7266 } 7267 bool DerivedZeroInitialization(const Expr *E) { 7268 return getDerived().ZeroInitialization(E); 7269 } 7270 7271 // Check whether a conditional operator with a non-constant condition is a 7272 // potential constant expression. If neither arm is a potential constant 7273 // expression, then the conditional operator is not either. 7274 template<typename ConditionalOperator> 7275 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7276 assert(Info.checkingPotentialConstantExpression()); 7277 7278 // Speculatively evaluate both arms. 7279 SmallVector<PartialDiagnosticAt, 8> Diag; 7280 { 7281 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7282 StmtVisitorTy::Visit(E->getFalseExpr()); 7283 if (Diag.empty()) 7284 return; 7285 } 7286 7287 { 7288 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7289 Diag.clear(); 7290 StmtVisitorTy::Visit(E->getTrueExpr()); 7291 if (Diag.empty()) 7292 return; 7293 } 7294 7295 Error(E, diag::note_constexpr_conditional_never_const); 7296 } 7297 7298 7299 template<typename ConditionalOperator> 7300 bool HandleConditionalOperator(const ConditionalOperator *E) { 7301 bool BoolResult; 7302 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7303 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7304 CheckPotentialConstantConditional(E); 7305 return false; 7306 } 7307 if (Info.noteFailure()) { 7308 StmtVisitorTy::Visit(E->getTrueExpr()); 7309 StmtVisitorTy::Visit(E->getFalseExpr()); 7310 } 7311 return false; 7312 } 7313 7314 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7315 return StmtVisitorTy::Visit(EvalExpr); 7316 } 7317 7318 protected: 7319 EvalInfo &Info; 7320 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7321 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7322 7323 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7324 return Info.CCEDiag(E, D); 7325 } 7326 7327 bool ZeroInitialization(const Expr *E) { return Error(E); } 7328 7329 public: 7330 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7331 7332 EvalInfo &getEvalInfo() { return Info; } 7333 7334 /// Report an evaluation error. This should only be called when an error is 7335 /// first discovered. When propagating an error, just return false. 7336 bool Error(const Expr *E, diag::kind D) { 7337 Info.FFDiag(E, D); 7338 return false; 7339 } 7340 bool Error(const Expr *E) { 7341 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7342 } 7343 7344 bool VisitStmt(const Stmt *) { 7345 llvm_unreachable("Expression evaluator should not be called on stmts"); 7346 } 7347 bool VisitExpr(const Expr *E) { 7348 return Error(E); 7349 } 7350 7351 bool VisitConstantExpr(const ConstantExpr *E) { 7352 if (E->hasAPValueResult()) 7353 return DerivedSuccess(E->getAPValueResult(), E); 7354 7355 return StmtVisitorTy::Visit(E->getSubExpr()); 7356 } 7357 7358 bool VisitParenExpr(const ParenExpr *E) 7359 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7360 bool VisitUnaryExtension(const UnaryOperator *E) 7361 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7362 bool VisitUnaryPlus(const UnaryOperator *E) 7363 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7364 bool VisitChooseExpr(const ChooseExpr *E) 7365 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7366 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7367 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7368 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7369 { return StmtVisitorTy::Visit(E->getReplacement()); } 7370 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7371 TempVersionRAII RAII(*Info.CurrentCall); 7372 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7373 return StmtVisitorTy::Visit(E->getExpr()); 7374 } 7375 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7376 TempVersionRAII RAII(*Info.CurrentCall); 7377 // The initializer may not have been parsed yet, or might be erroneous. 7378 if (!E->getExpr()) 7379 return Error(E); 7380 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7381 return StmtVisitorTy::Visit(E->getExpr()); 7382 } 7383 7384 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7385 FullExpressionRAII Scope(Info); 7386 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7387 } 7388 7389 // Temporaries are registered when created, so we don't care about 7390 // CXXBindTemporaryExpr. 7391 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7392 return StmtVisitorTy::Visit(E->getSubExpr()); 7393 } 7394 7395 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7396 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7397 return static_cast<Derived*>(this)->VisitCastExpr(E); 7398 } 7399 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7400 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7401 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7402 return static_cast<Derived*>(this)->VisitCastExpr(E); 7403 } 7404 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7405 return static_cast<Derived*>(this)->VisitCastExpr(E); 7406 } 7407 7408 bool VisitBinaryOperator(const BinaryOperator *E) { 7409 switch (E->getOpcode()) { 7410 default: 7411 return Error(E); 7412 7413 case BO_Comma: 7414 VisitIgnoredValue(E->getLHS()); 7415 return StmtVisitorTy::Visit(E->getRHS()); 7416 7417 case BO_PtrMemD: 7418 case BO_PtrMemI: { 7419 LValue Obj; 7420 if (!HandleMemberPointerAccess(Info, E, Obj)) 7421 return false; 7422 APValue Result; 7423 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7424 return false; 7425 return DerivedSuccess(Result, E); 7426 } 7427 } 7428 } 7429 7430 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7431 return StmtVisitorTy::Visit(E->getSemanticForm()); 7432 } 7433 7434 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7435 // Evaluate and cache the common expression. We treat it as a temporary, 7436 // even though it's not quite the same thing. 7437 LValue CommonLV; 7438 if (!Evaluate(Info.CurrentCall->createTemporary( 7439 E->getOpaqueValue(), 7440 getStorageType(Info.Ctx, E->getOpaqueValue()), 7441 ScopeKind::FullExpression, CommonLV), 7442 Info, E->getCommon())) 7443 return false; 7444 7445 return HandleConditionalOperator(E); 7446 } 7447 7448 bool VisitConditionalOperator(const ConditionalOperator *E) { 7449 bool IsBcpCall = false; 7450 // If the condition (ignoring parens) is a __builtin_constant_p call, 7451 // the result is a constant expression if it can be folded without 7452 // side-effects. This is an important GNU extension. See GCC PR38377 7453 // for discussion. 7454 if (const CallExpr *CallCE = 7455 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7456 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7457 IsBcpCall = true; 7458 7459 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7460 // constant expression; we can't check whether it's potentially foldable. 7461 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7462 // it would return 'false' in this mode. 7463 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7464 return false; 7465 7466 FoldConstant Fold(Info, IsBcpCall); 7467 if (!HandleConditionalOperator(E)) { 7468 Fold.keepDiagnostics(); 7469 return false; 7470 } 7471 7472 return true; 7473 } 7474 7475 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7476 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7477 return DerivedSuccess(*Value, E); 7478 7479 const Expr *Source = E->getSourceExpr(); 7480 if (!Source) 7481 return Error(E); 7482 if (Source == E) { // sanity checking. 7483 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7484 return Error(E); 7485 } 7486 return StmtVisitorTy::Visit(Source); 7487 } 7488 7489 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7490 for (const Expr *SemE : E->semantics()) { 7491 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7492 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7493 // result expression: there could be two different LValues that would 7494 // refer to the same object in that case, and we can't model that. 7495 if (SemE == E->getResultExpr()) 7496 return Error(E); 7497 7498 // Unique OVEs get evaluated if and when we encounter them when 7499 // emitting the rest of the semantic form, rather than eagerly. 7500 if (OVE->isUnique()) 7501 continue; 7502 7503 LValue LV; 7504 if (!Evaluate(Info.CurrentCall->createTemporary( 7505 OVE, getStorageType(Info.Ctx, OVE), 7506 ScopeKind::FullExpression, LV), 7507 Info, OVE->getSourceExpr())) 7508 return false; 7509 } else if (SemE == E->getResultExpr()) { 7510 if (!StmtVisitorTy::Visit(SemE)) 7511 return false; 7512 } else { 7513 if (!EvaluateIgnoredValue(Info, SemE)) 7514 return false; 7515 } 7516 } 7517 return true; 7518 } 7519 7520 bool VisitCallExpr(const CallExpr *E) { 7521 APValue Result; 7522 if (!handleCallExpr(E, Result, nullptr)) 7523 return false; 7524 return DerivedSuccess(Result, E); 7525 } 7526 7527 bool handleCallExpr(const CallExpr *E, APValue &Result, 7528 const LValue *ResultSlot) { 7529 CallScopeRAII CallScope(Info); 7530 7531 const Expr *Callee = E->getCallee()->IgnoreParens(); 7532 QualType CalleeType = Callee->getType(); 7533 7534 const FunctionDecl *FD = nullptr; 7535 LValue *This = nullptr, ThisVal; 7536 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7537 bool HasQualifier = false; 7538 7539 CallRef Call; 7540 7541 // Extract function decl and 'this' pointer from the callee. 7542 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7543 const CXXMethodDecl *Member = nullptr; 7544 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7545 // Explicit bound member calls, such as x.f() or p->g(); 7546 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7547 return false; 7548 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7549 if (!Member) 7550 return Error(Callee); 7551 This = &ThisVal; 7552 HasQualifier = ME->hasQualifier(); 7553 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7554 // Indirect bound member calls ('.*' or '->*'). 7555 const ValueDecl *D = 7556 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7557 if (!D) 7558 return false; 7559 Member = dyn_cast<CXXMethodDecl>(D); 7560 if (!Member) 7561 return Error(Callee); 7562 This = &ThisVal; 7563 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7564 if (!Info.getLangOpts().CPlusPlus20) 7565 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7566 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7567 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7568 } else 7569 return Error(Callee); 7570 FD = Member; 7571 } else if (CalleeType->isFunctionPointerType()) { 7572 LValue CalleeLV; 7573 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7574 return false; 7575 7576 if (!CalleeLV.getLValueOffset().isZero()) 7577 return Error(Callee); 7578 FD = dyn_cast_or_null<FunctionDecl>( 7579 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7580 if (!FD) 7581 return Error(Callee); 7582 // Don't call function pointers which have been cast to some other type. 7583 // Per DR (no number yet), the caller and callee can differ in noexcept. 7584 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7585 CalleeType->getPointeeType(), FD->getType())) { 7586 return Error(E); 7587 } 7588 7589 // For an (overloaded) assignment expression, evaluate the RHS before the 7590 // LHS. 7591 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7592 if (OCE && OCE->isAssignmentOp()) { 7593 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7594 Call = Info.CurrentCall->createCall(FD); 7595 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7596 Info, FD, /*RightToLeft=*/true)) 7597 return false; 7598 } 7599 7600 // Overloaded operator calls to member functions are represented as normal 7601 // calls with '*this' as the first argument. 7602 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7603 if (MD && !MD->isStatic()) { 7604 // FIXME: When selecting an implicit conversion for an overloaded 7605 // operator delete, we sometimes try to evaluate calls to conversion 7606 // operators without a 'this' parameter! 7607 if (Args.empty()) 7608 return Error(E); 7609 7610 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7611 return false; 7612 This = &ThisVal; 7613 Args = Args.slice(1); 7614 } else if (MD && MD->isLambdaStaticInvoker()) { 7615 // Map the static invoker for the lambda back to the call operator. 7616 // Conveniently, we don't have to slice out the 'this' argument (as is 7617 // being done for the non-static case), since a static member function 7618 // doesn't have an implicit argument passed in. 7619 const CXXRecordDecl *ClosureClass = MD->getParent(); 7620 assert( 7621 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7622 "Number of captures must be zero for conversion to function-ptr"); 7623 7624 const CXXMethodDecl *LambdaCallOp = 7625 ClosureClass->getLambdaCallOperator(); 7626 7627 // Set 'FD', the function that will be called below, to the call 7628 // operator. If the closure object represents a generic lambda, find 7629 // the corresponding specialization of the call operator. 7630 7631 if (ClosureClass->isGenericLambda()) { 7632 assert(MD->isFunctionTemplateSpecialization() && 7633 "A generic lambda's static-invoker function must be a " 7634 "template specialization"); 7635 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7636 FunctionTemplateDecl *CallOpTemplate = 7637 LambdaCallOp->getDescribedFunctionTemplate(); 7638 void *InsertPos = nullptr; 7639 FunctionDecl *CorrespondingCallOpSpecialization = 7640 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7641 assert(CorrespondingCallOpSpecialization && 7642 "We must always have a function call operator specialization " 7643 "that corresponds to our static invoker specialization"); 7644 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7645 } else 7646 FD = LambdaCallOp; 7647 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7648 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7649 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7650 LValue Ptr; 7651 if (!HandleOperatorNewCall(Info, E, Ptr)) 7652 return false; 7653 Ptr.moveInto(Result); 7654 return CallScope.destroy(); 7655 } else { 7656 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7657 } 7658 } 7659 } else 7660 return Error(E); 7661 7662 // Evaluate the arguments now if we've not already done so. 7663 if (!Call) { 7664 Call = Info.CurrentCall->createCall(FD); 7665 if (!EvaluateArgs(Args, Call, Info, FD)) 7666 return false; 7667 } 7668 7669 SmallVector<QualType, 4> CovariantAdjustmentPath; 7670 if (This) { 7671 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7672 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7673 // Perform virtual dispatch, if necessary. 7674 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7675 CovariantAdjustmentPath); 7676 if (!FD) 7677 return false; 7678 } else { 7679 // Check that the 'this' pointer points to an object of the right type. 7680 // FIXME: If this is an assignment operator call, we may need to change 7681 // the active union member before we check this. 7682 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7683 return false; 7684 } 7685 } 7686 7687 // Destructor calls are different enough that they have their own codepath. 7688 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7689 assert(This && "no 'this' pointer for destructor call"); 7690 return HandleDestruction(Info, E, *This, 7691 Info.Ctx.getRecordType(DD->getParent())) && 7692 CallScope.destroy(); 7693 } 7694 7695 const FunctionDecl *Definition = nullptr; 7696 Stmt *Body = FD->getBody(Definition); 7697 7698 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7699 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7700 Body, Info, Result, ResultSlot)) 7701 return false; 7702 7703 if (!CovariantAdjustmentPath.empty() && 7704 !HandleCovariantReturnAdjustment(Info, E, Result, 7705 CovariantAdjustmentPath)) 7706 return false; 7707 7708 return CallScope.destroy(); 7709 } 7710 7711 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7712 return StmtVisitorTy::Visit(E->getInitializer()); 7713 } 7714 bool VisitInitListExpr(const InitListExpr *E) { 7715 if (E->getNumInits() == 0) 7716 return DerivedZeroInitialization(E); 7717 if (E->getNumInits() == 1) 7718 return StmtVisitorTy::Visit(E->getInit(0)); 7719 return Error(E); 7720 } 7721 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7722 return DerivedZeroInitialization(E); 7723 } 7724 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7725 return DerivedZeroInitialization(E); 7726 } 7727 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7728 return DerivedZeroInitialization(E); 7729 } 7730 7731 /// A member expression where the object is a prvalue is itself a prvalue. 7732 bool VisitMemberExpr(const MemberExpr *E) { 7733 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7734 "missing temporary materialization conversion"); 7735 assert(!E->isArrow() && "missing call to bound member function?"); 7736 7737 APValue Val; 7738 if (!Evaluate(Val, Info, E->getBase())) 7739 return false; 7740 7741 QualType BaseTy = E->getBase()->getType(); 7742 7743 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7744 if (!FD) return Error(E); 7745 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7746 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7747 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7748 7749 // Note: there is no lvalue base here. But this case should only ever 7750 // happen in C or in C++98, where we cannot be evaluating a constexpr 7751 // constructor, which is the only case the base matters. 7752 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7753 SubobjectDesignator Designator(BaseTy); 7754 Designator.addDeclUnchecked(FD); 7755 7756 APValue Result; 7757 return extractSubobject(Info, E, Obj, Designator, Result) && 7758 DerivedSuccess(Result, E); 7759 } 7760 7761 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7762 APValue Val; 7763 if (!Evaluate(Val, Info, E->getBase())) 7764 return false; 7765 7766 if (Val.isVector()) { 7767 SmallVector<uint32_t, 4> Indices; 7768 E->getEncodedElementAccess(Indices); 7769 if (Indices.size() == 1) { 7770 // Return scalar. 7771 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7772 } else { 7773 // Construct new APValue vector. 7774 SmallVector<APValue, 4> Elts; 7775 for (unsigned I = 0; I < Indices.size(); ++I) { 7776 Elts.push_back(Val.getVectorElt(Indices[I])); 7777 } 7778 APValue VecResult(Elts.data(), Indices.size()); 7779 return DerivedSuccess(VecResult, E); 7780 } 7781 } 7782 7783 return false; 7784 } 7785 7786 bool VisitCastExpr(const CastExpr *E) { 7787 switch (E->getCastKind()) { 7788 default: 7789 break; 7790 7791 case CK_AtomicToNonAtomic: { 7792 APValue AtomicVal; 7793 // This does not need to be done in place even for class/array types: 7794 // atomic-to-non-atomic conversion implies copying the object 7795 // representation. 7796 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7797 return false; 7798 return DerivedSuccess(AtomicVal, E); 7799 } 7800 7801 case CK_NoOp: 7802 case CK_UserDefinedConversion: 7803 return StmtVisitorTy::Visit(E->getSubExpr()); 7804 7805 case CK_LValueToRValue: { 7806 LValue LVal; 7807 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7808 return false; 7809 APValue RVal; 7810 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7811 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7812 LVal, RVal)) 7813 return false; 7814 return DerivedSuccess(RVal, E); 7815 } 7816 case CK_LValueToRValueBitCast: { 7817 APValue DestValue, SourceValue; 7818 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7819 return false; 7820 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7821 return false; 7822 return DerivedSuccess(DestValue, E); 7823 } 7824 7825 case CK_AddressSpaceConversion: { 7826 APValue Value; 7827 if (!Evaluate(Value, Info, E->getSubExpr())) 7828 return false; 7829 return DerivedSuccess(Value, E); 7830 } 7831 } 7832 7833 return Error(E); 7834 } 7835 7836 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7837 return VisitUnaryPostIncDec(UO); 7838 } 7839 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7840 return VisitUnaryPostIncDec(UO); 7841 } 7842 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7843 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7844 return Error(UO); 7845 7846 LValue LVal; 7847 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7848 return false; 7849 APValue RVal; 7850 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7851 UO->isIncrementOp(), &RVal)) 7852 return false; 7853 return DerivedSuccess(RVal, UO); 7854 } 7855 7856 bool VisitStmtExpr(const StmtExpr *E) { 7857 // We will have checked the full-expressions inside the statement expression 7858 // when they were completed, and don't need to check them again now. 7859 llvm::SaveAndRestore<bool> NotCheckingForUB( 7860 Info.CheckingForUndefinedBehavior, false); 7861 7862 const CompoundStmt *CS = E->getSubStmt(); 7863 if (CS->body_empty()) 7864 return true; 7865 7866 BlockScopeRAII Scope(Info); 7867 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7868 BE = CS->body_end(); 7869 /**/; ++BI) { 7870 if (BI + 1 == BE) { 7871 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7872 if (!FinalExpr) { 7873 Info.FFDiag((*BI)->getBeginLoc(), 7874 diag::note_constexpr_stmt_expr_unsupported); 7875 return false; 7876 } 7877 return this->Visit(FinalExpr) && Scope.destroy(); 7878 } 7879 7880 APValue ReturnValue; 7881 StmtResult Result = { ReturnValue, nullptr }; 7882 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7883 if (ESR != ESR_Succeeded) { 7884 // FIXME: If the statement-expression terminated due to 'return', 7885 // 'break', or 'continue', it would be nice to propagate that to 7886 // the outer statement evaluation rather than bailing out. 7887 if (ESR != ESR_Failed) 7888 Info.FFDiag((*BI)->getBeginLoc(), 7889 diag::note_constexpr_stmt_expr_unsupported); 7890 return false; 7891 } 7892 } 7893 7894 llvm_unreachable("Return from function from the loop above."); 7895 } 7896 7897 /// Visit a value which is evaluated, but whose value is ignored. 7898 void VisitIgnoredValue(const Expr *E) { 7899 EvaluateIgnoredValue(Info, E); 7900 } 7901 7902 /// Potentially visit a MemberExpr's base expression. 7903 void VisitIgnoredBaseExpression(const Expr *E) { 7904 // While MSVC doesn't evaluate the base expression, it does diagnose the 7905 // presence of side-effecting behavior. 7906 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7907 return; 7908 VisitIgnoredValue(E); 7909 } 7910 }; 7911 7912 } // namespace 7913 7914 //===----------------------------------------------------------------------===// 7915 // Common base class for lvalue and temporary evaluation. 7916 //===----------------------------------------------------------------------===// 7917 namespace { 7918 template<class Derived> 7919 class LValueExprEvaluatorBase 7920 : public ExprEvaluatorBase<Derived> { 7921 protected: 7922 LValue &Result; 7923 bool InvalidBaseOK; 7924 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7925 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7926 7927 bool Success(APValue::LValueBase B) { 7928 Result.set(B); 7929 return true; 7930 } 7931 7932 bool evaluatePointer(const Expr *E, LValue &Result) { 7933 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7934 } 7935 7936 public: 7937 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7938 : ExprEvaluatorBaseTy(Info), Result(Result), 7939 InvalidBaseOK(InvalidBaseOK) {} 7940 7941 bool Success(const APValue &V, const Expr *E) { 7942 Result.setFrom(this->Info.Ctx, V); 7943 return true; 7944 } 7945 7946 bool VisitMemberExpr(const MemberExpr *E) { 7947 // Handle non-static data members. 7948 QualType BaseTy; 7949 bool EvalOK; 7950 if (E->isArrow()) { 7951 EvalOK = evaluatePointer(E->getBase(), Result); 7952 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7953 } else if (E->getBase()->isPRValue()) { 7954 assert(E->getBase()->getType()->isRecordType()); 7955 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7956 BaseTy = E->getBase()->getType(); 7957 } else { 7958 EvalOK = this->Visit(E->getBase()); 7959 BaseTy = E->getBase()->getType(); 7960 } 7961 if (!EvalOK) { 7962 if (!InvalidBaseOK) 7963 return false; 7964 Result.setInvalid(E); 7965 return true; 7966 } 7967 7968 const ValueDecl *MD = E->getMemberDecl(); 7969 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7970 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7971 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7972 (void)BaseTy; 7973 if (!HandleLValueMember(this->Info, E, Result, FD)) 7974 return false; 7975 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7976 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7977 return false; 7978 } else 7979 return this->Error(E); 7980 7981 if (MD->getType()->isReferenceType()) { 7982 APValue RefValue; 7983 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7984 RefValue)) 7985 return false; 7986 return Success(RefValue, E); 7987 } 7988 return true; 7989 } 7990 7991 bool VisitBinaryOperator(const BinaryOperator *E) { 7992 switch (E->getOpcode()) { 7993 default: 7994 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7995 7996 case BO_PtrMemD: 7997 case BO_PtrMemI: 7998 return HandleMemberPointerAccess(this->Info, E, Result); 7999 } 8000 } 8001 8002 bool VisitCastExpr(const CastExpr *E) { 8003 switch (E->getCastKind()) { 8004 default: 8005 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8006 8007 case CK_DerivedToBase: 8008 case CK_UncheckedDerivedToBase: 8009 if (!this->Visit(E->getSubExpr())) 8010 return false; 8011 8012 // Now figure out the necessary offset to add to the base LV to get from 8013 // the derived class to the base class. 8014 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8015 Result); 8016 } 8017 } 8018 }; 8019 } 8020 8021 //===----------------------------------------------------------------------===// 8022 // LValue Evaluation 8023 // 8024 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8025 // function designators (in C), decl references to void objects (in C), and 8026 // temporaries (if building with -Wno-address-of-temporary). 8027 // 8028 // LValue evaluation produces values comprising a base expression of one of the 8029 // following types: 8030 // - Declarations 8031 // * VarDecl 8032 // * FunctionDecl 8033 // - Literals 8034 // * CompoundLiteralExpr in C (and in global scope in C++) 8035 // * StringLiteral 8036 // * PredefinedExpr 8037 // * ObjCStringLiteralExpr 8038 // * ObjCEncodeExpr 8039 // * AddrLabelExpr 8040 // * BlockExpr 8041 // * CallExpr for a MakeStringConstant builtin 8042 // - typeid(T) expressions, as TypeInfoLValues 8043 // - Locals and temporaries 8044 // * MaterializeTemporaryExpr 8045 // * Any Expr, with a CallIndex indicating the function in which the temporary 8046 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8047 // from the AST (FIXME). 8048 // * A MaterializeTemporaryExpr that has static storage duration, with no 8049 // CallIndex, for a lifetime-extended temporary. 8050 // * The ConstantExpr that is currently being evaluated during evaluation of an 8051 // immediate invocation. 8052 // plus an offset in bytes. 8053 //===----------------------------------------------------------------------===// 8054 namespace { 8055 class LValueExprEvaluator 8056 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8057 public: 8058 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8059 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8060 8061 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8062 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8063 8064 bool VisitDeclRefExpr(const DeclRefExpr *E); 8065 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8066 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8067 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8068 bool VisitMemberExpr(const MemberExpr *E); 8069 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8070 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8071 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8072 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8073 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8074 bool VisitUnaryDeref(const UnaryOperator *E); 8075 bool VisitUnaryReal(const UnaryOperator *E); 8076 bool VisitUnaryImag(const UnaryOperator *E); 8077 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8078 return VisitUnaryPreIncDec(UO); 8079 } 8080 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8081 return VisitUnaryPreIncDec(UO); 8082 } 8083 bool VisitBinAssign(const BinaryOperator *BO); 8084 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8085 8086 bool VisitCastExpr(const CastExpr *E) { 8087 switch (E->getCastKind()) { 8088 default: 8089 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8090 8091 case CK_LValueBitCast: 8092 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8093 if (!Visit(E->getSubExpr())) 8094 return false; 8095 Result.Designator.setInvalid(); 8096 return true; 8097 8098 case CK_BaseToDerived: 8099 if (!Visit(E->getSubExpr())) 8100 return false; 8101 return HandleBaseToDerivedCast(Info, E, Result); 8102 8103 case CK_Dynamic: 8104 if (!Visit(E->getSubExpr())) 8105 return false; 8106 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8107 } 8108 } 8109 }; 8110 } // end anonymous namespace 8111 8112 /// Evaluate an expression as an lvalue. This can be legitimately called on 8113 /// expressions which are not glvalues, in three cases: 8114 /// * function designators in C, and 8115 /// * "extern void" objects 8116 /// * @selector() expressions in Objective-C 8117 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8118 bool InvalidBaseOK) { 8119 assert(!E->isValueDependent()); 8120 assert(E->isGLValue() || E->getType()->isFunctionType() || 8121 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8122 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8123 } 8124 8125 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8126 const NamedDecl *D = E->getDecl(); 8127 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8128 return Success(cast<ValueDecl>(D)); 8129 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8130 return VisitVarDecl(E, VD); 8131 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8132 return Visit(BD->getBinding()); 8133 return Error(E); 8134 } 8135 8136 8137 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8138 8139 // If we are within a lambda's call operator, check whether the 'VD' referred 8140 // to within 'E' actually represents a lambda-capture that maps to a 8141 // data-member/field within the closure object, and if so, evaluate to the 8142 // field or what the field refers to. 8143 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8144 isa<DeclRefExpr>(E) && 8145 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8146 // We don't always have a complete capture-map when checking or inferring if 8147 // the function call operator meets the requirements of a constexpr function 8148 // - but we don't need to evaluate the captures to determine constexprness 8149 // (dcl.constexpr C++17). 8150 if (Info.checkingPotentialConstantExpression()) 8151 return false; 8152 8153 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8154 // Start with 'Result' referring to the complete closure object... 8155 Result = *Info.CurrentCall->This; 8156 // ... then update it to refer to the field of the closure object 8157 // that represents the capture. 8158 if (!HandleLValueMember(Info, E, Result, FD)) 8159 return false; 8160 // And if the field is of reference type, update 'Result' to refer to what 8161 // the field refers to. 8162 if (FD->getType()->isReferenceType()) { 8163 APValue RVal; 8164 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8165 RVal)) 8166 return false; 8167 Result.setFrom(Info.Ctx, RVal); 8168 } 8169 return true; 8170 } 8171 } 8172 8173 CallStackFrame *Frame = nullptr; 8174 unsigned Version = 0; 8175 if (VD->hasLocalStorage()) { 8176 // Only if a local variable was declared in the function currently being 8177 // evaluated, do we expect to be able to find its value in the current 8178 // frame. (Otherwise it was likely declared in an enclosing context and 8179 // could either have a valid evaluatable value (for e.g. a constexpr 8180 // variable) or be ill-formed (and trigger an appropriate evaluation 8181 // diagnostic)). 8182 CallStackFrame *CurrFrame = Info.CurrentCall; 8183 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8184 // Function parameters are stored in some caller's frame. (Usually the 8185 // immediate caller, but for an inherited constructor they may be more 8186 // distant.) 8187 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8188 if (CurrFrame->Arguments) { 8189 VD = CurrFrame->Arguments.getOrigParam(PVD); 8190 Frame = 8191 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8192 Version = CurrFrame->Arguments.Version; 8193 } 8194 } else { 8195 Frame = CurrFrame; 8196 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8197 } 8198 } 8199 } 8200 8201 if (!VD->getType()->isReferenceType()) { 8202 if (Frame) { 8203 Result.set({VD, Frame->Index, Version}); 8204 return true; 8205 } 8206 return Success(VD); 8207 } 8208 8209 if (!Info.getLangOpts().CPlusPlus11) { 8210 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8211 << VD << VD->getType(); 8212 Info.Note(VD->getLocation(), diag::note_declared_at); 8213 } 8214 8215 APValue *V; 8216 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8217 return false; 8218 if (!V->hasValue()) { 8219 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8220 // adjust the diagnostic to say that. 8221 if (!Info.checkingPotentialConstantExpression()) 8222 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8223 return false; 8224 } 8225 return Success(*V, E); 8226 } 8227 8228 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8229 const MaterializeTemporaryExpr *E) { 8230 // Walk through the expression to find the materialized temporary itself. 8231 SmallVector<const Expr *, 2> CommaLHSs; 8232 SmallVector<SubobjectAdjustment, 2> Adjustments; 8233 const Expr *Inner = 8234 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8235 8236 // If we passed any comma operators, evaluate their LHSs. 8237 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8238 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8239 return false; 8240 8241 // A materialized temporary with static storage duration can appear within the 8242 // result of a constant expression evaluation, so we need to preserve its 8243 // value for use outside this evaluation. 8244 APValue *Value; 8245 if (E->getStorageDuration() == SD_Static) { 8246 // FIXME: What about SD_Thread? 8247 Value = E->getOrCreateValue(true); 8248 *Value = APValue(); 8249 Result.set(E); 8250 } else { 8251 Value = &Info.CurrentCall->createTemporary( 8252 E, E->getType(), 8253 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8254 : ScopeKind::Block, 8255 Result); 8256 } 8257 8258 QualType Type = Inner->getType(); 8259 8260 // Materialize the temporary itself. 8261 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8262 *Value = APValue(); 8263 return false; 8264 } 8265 8266 // Adjust our lvalue to refer to the desired subobject. 8267 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8268 --I; 8269 switch (Adjustments[I].Kind) { 8270 case SubobjectAdjustment::DerivedToBaseAdjustment: 8271 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8272 Type, Result)) 8273 return false; 8274 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8275 break; 8276 8277 case SubobjectAdjustment::FieldAdjustment: 8278 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8279 return false; 8280 Type = Adjustments[I].Field->getType(); 8281 break; 8282 8283 case SubobjectAdjustment::MemberPointerAdjustment: 8284 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8285 Adjustments[I].Ptr.RHS)) 8286 return false; 8287 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8288 break; 8289 } 8290 } 8291 8292 return true; 8293 } 8294 8295 bool 8296 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8297 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8298 "lvalue compound literal in c++?"); 8299 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8300 // only see this when folding in C, so there's no standard to follow here. 8301 return Success(E); 8302 } 8303 8304 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8305 TypeInfoLValue TypeInfo; 8306 8307 if (!E->isPotentiallyEvaluated()) { 8308 if (E->isTypeOperand()) 8309 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8310 else 8311 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8312 } else { 8313 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8314 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8315 << E->getExprOperand()->getType() 8316 << E->getExprOperand()->getSourceRange(); 8317 } 8318 8319 if (!Visit(E->getExprOperand())) 8320 return false; 8321 8322 Optional<DynamicType> DynType = 8323 ComputeDynamicType(Info, E, Result, AK_TypeId); 8324 if (!DynType) 8325 return false; 8326 8327 TypeInfo = 8328 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8329 } 8330 8331 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8332 } 8333 8334 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8335 return Success(E->getGuidDecl()); 8336 } 8337 8338 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8339 // Handle static data members. 8340 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8341 VisitIgnoredBaseExpression(E->getBase()); 8342 return VisitVarDecl(E, VD); 8343 } 8344 8345 // Handle static member functions. 8346 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8347 if (MD->isStatic()) { 8348 VisitIgnoredBaseExpression(E->getBase()); 8349 return Success(MD); 8350 } 8351 } 8352 8353 // Handle non-static data members. 8354 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8355 } 8356 8357 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8358 // FIXME: Deal with vectors as array subscript bases. 8359 if (E->getBase()->getType()->isVectorType()) 8360 return Error(E); 8361 8362 APSInt Index; 8363 bool Success = true; 8364 8365 // C++17's rules require us to evaluate the LHS first, regardless of which 8366 // side is the base. 8367 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8368 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8369 : !EvaluateInteger(SubExpr, Index, Info)) { 8370 if (!Info.noteFailure()) 8371 return false; 8372 Success = false; 8373 } 8374 } 8375 8376 return Success && 8377 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8378 } 8379 8380 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8381 return evaluatePointer(E->getSubExpr(), Result); 8382 } 8383 8384 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8385 if (!Visit(E->getSubExpr())) 8386 return false; 8387 // __real is a no-op on scalar lvalues. 8388 if (E->getSubExpr()->getType()->isAnyComplexType()) 8389 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8390 return true; 8391 } 8392 8393 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8394 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8395 "lvalue __imag__ on scalar?"); 8396 if (!Visit(E->getSubExpr())) 8397 return false; 8398 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8399 return true; 8400 } 8401 8402 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8403 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8404 return Error(UO); 8405 8406 if (!this->Visit(UO->getSubExpr())) 8407 return false; 8408 8409 return handleIncDec( 8410 this->Info, UO, Result, UO->getSubExpr()->getType(), 8411 UO->isIncrementOp(), nullptr); 8412 } 8413 8414 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8415 const CompoundAssignOperator *CAO) { 8416 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8417 return Error(CAO); 8418 8419 bool Success = true; 8420 8421 // C++17 onwards require that we evaluate the RHS first. 8422 APValue RHS; 8423 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8424 if (!Info.noteFailure()) 8425 return false; 8426 Success = false; 8427 } 8428 8429 // The overall lvalue result is the result of evaluating the LHS. 8430 if (!this->Visit(CAO->getLHS()) || !Success) 8431 return false; 8432 8433 return handleCompoundAssignment( 8434 this->Info, CAO, 8435 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8436 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8437 } 8438 8439 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8440 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8441 return Error(E); 8442 8443 bool Success = true; 8444 8445 // C++17 onwards require that we evaluate the RHS first. 8446 APValue NewVal; 8447 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8448 if (!Info.noteFailure()) 8449 return false; 8450 Success = false; 8451 } 8452 8453 if (!this->Visit(E->getLHS()) || !Success) 8454 return false; 8455 8456 if (Info.getLangOpts().CPlusPlus20 && 8457 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8458 return false; 8459 8460 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8461 NewVal); 8462 } 8463 8464 //===----------------------------------------------------------------------===// 8465 // Pointer Evaluation 8466 //===----------------------------------------------------------------------===// 8467 8468 /// Attempts to compute the number of bytes available at the pointer 8469 /// returned by a function with the alloc_size attribute. Returns true if we 8470 /// were successful. Places an unsigned number into `Result`. 8471 /// 8472 /// This expects the given CallExpr to be a call to a function with an 8473 /// alloc_size attribute. 8474 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8475 const CallExpr *Call, 8476 llvm::APInt &Result) { 8477 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8478 8479 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8480 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8481 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8482 if (Call->getNumArgs() <= SizeArgNo) 8483 return false; 8484 8485 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8486 Expr::EvalResult ExprResult; 8487 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8488 return false; 8489 Into = ExprResult.Val.getInt(); 8490 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8491 return false; 8492 Into = Into.zextOrSelf(BitsInSizeT); 8493 return true; 8494 }; 8495 8496 APSInt SizeOfElem; 8497 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8498 return false; 8499 8500 if (!AllocSize->getNumElemsParam().isValid()) { 8501 Result = std::move(SizeOfElem); 8502 return true; 8503 } 8504 8505 APSInt NumberOfElems; 8506 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8507 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8508 return false; 8509 8510 bool Overflow; 8511 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8512 if (Overflow) 8513 return false; 8514 8515 Result = std::move(BytesAvailable); 8516 return true; 8517 } 8518 8519 /// Convenience function. LVal's base must be a call to an alloc_size 8520 /// function. 8521 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8522 const LValue &LVal, 8523 llvm::APInt &Result) { 8524 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8525 "Can't get the size of a non alloc_size function"); 8526 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8527 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8528 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8529 } 8530 8531 /// Attempts to evaluate the given LValueBase as the result of a call to 8532 /// a function with the alloc_size attribute. If it was possible to do so, this 8533 /// function will return true, make Result's Base point to said function call, 8534 /// and mark Result's Base as invalid. 8535 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8536 LValue &Result) { 8537 if (Base.isNull()) 8538 return false; 8539 8540 // Because we do no form of static analysis, we only support const variables. 8541 // 8542 // Additionally, we can't support parameters, nor can we support static 8543 // variables (in the latter case, use-before-assign isn't UB; in the former, 8544 // we have no clue what they'll be assigned to). 8545 const auto *VD = 8546 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8547 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8548 return false; 8549 8550 const Expr *Init = VD->getAnyInitializer(); 8551 if (!Init) 8552 return false; 8553 8554 const Expr *E = Init->IgnoreParens(); 8555 if (!tryUnwrapAllocSizeCall(E)) 8556 return false; 8557 8558 // Store E instead of E unwrapped so that the type of the LValue's base is 8559 // what the user wanted. 8560 Result.setInvalid(E); 8561 8562 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8563 Result.addUnsizedArray(Info, E, Pointee); 8564 return true; 8565 } 8566 8567 namespace { 8568 class PointerExprEvaluator 8569 : public ExprEvaluatorBase<PointerExprEvaluator> { 8570 LValue &Result; 8571 bool InvalidBaseOK; 8572 8573 bool Success(const Expr *E) { 8574 Result.set(E); 8575 return true; 8576 } 8577 8578 bool evaluateLValue(const Expr *E, LValue &Result) { 8579 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8580 } 8581 8582 bool evaluatePointer(const Expr *E, LValue &Result) { 8583 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8584 } 8585 8586 bool visitNonBuiltinCallExpr(const CallExpr *E); 8587 public: 8588 8589 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8590 : ExprEvaluatorBaseTy(info), Result(Result), 8591 InvalidBaseOK(InvalidBaseOK) {} 8592 8593 bool Success(const APValue &V, const Expr *E) { 8594 Result.setFrom(Info.Ctx, V); 8595 return true; 8596 } 8597 bool ZeroInitialization(const Expr *E) { 8598 Result.setNull(Info.Ctx, E->getType()); 8599 return true; 8600 } 8601 8602 bool VisitBinaryOperator(const BinaryOperator *E); 8603 bool VisitCastExpr(const CastExpr* E); 8604 bool VisitUnaryAddrOf(const UnaryOperator *E); 8605 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8606 { return Success(E); } 8607 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8608 if (E->isExpressibleAsConstantInitializer()) 8609 return Success(E); 8610 if (Info.noteFailure()) 8611 EvaluateIgnoredValue(Info, E->getSubExpr()); 8612 return Error(E); 8613 } 8614 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8615 { return Success(E); } 8616 bool VisitCallExpr(const CallExpr *E); 8617 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8618 bool VisitBlockExpr(const BlockExpr *E) { 8619 if (!E->getBlockDecl()->hasCaptures()) 8620 return Success(E); 8621 return Error(E); 8622 } 8623 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8624 // Can't look at 'this' when checking a potential constant expression. 8625 if (Info.checkingPotentialConstantExpression()) 8626 return false; 8627 if (!Info.CurrentCall->This) { 8628 if (Info.getLangOpts().CPlusPlus11) 8629 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8630 else 8631 Info.FFDiag(E); 8632 return false; 8633 } 8634 Result = *Info.CurrentCall->This; 8635 // If we are inside a lambda's call operator, the 'this' expression refers 8636 // to the enclosing '*this' object (either by value or reference) which is 8637 // either copied into the closure object's field that represents the '*this' 8638 // or refers to '*this'. 8639 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8640 // Ensure we actually have captured 'this'. (an error will have 8641 // been previously reported if not). 8642 if (!Info.CurrentCall->LambdaThisCaptureField) 8643 return false; 8644 8645 // Update 'Result' to refer to the data member/field of the closure object 8646 // that represents the '*this' capture. 8647 if (!HandleLValueMember(Info, E, Result, 8648 Info.CurrentCall->LambdaThisCaptureField)) 8649 return false; 8650 // If we captured '*this' by reference, replace the field with its referent. 8651 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8652 ->isPointerType()) { 8653 APValue RVal; 8654 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8655 RVal)) 8656 return false; 8657 8658 Result.setFrom(Info.Ctx, RVal); 8659 } 8660 } 8661 return true; 8662 } 8663 8664 bool VisitCXXNewExpr(const CXXNewExpr *E); 8665 8666 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8667 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8668 APValue LValResult = E->EvaluateInContext( 8669 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8670 Result.setFrom(Info.Ctx, LValResult); 8671 return true; 8672 } 8673 8674 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8675 std::string ResultStr = E->ComputeName(Info.Ctx); 8676 8677 Info.Ctx.SYCLUniqueStableNameEvaluatedValues[E] = ResultStr; 8678 8679 QualType CharTy = Info.Ctx.CharTy.withConst(); 8680 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8681 ResultStr.size() + 1); 8682 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8683 ArrayType::Normal, 0); 8684 8685 StringLiteral *SL = 8686 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, 8687 /*Pascal*/ false, ArrayTy, E->getLocation()); 8688 8689 evaluateLValue(SL, Result); 8690 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8691 return true; 8692 } 8693 8694 // FIXME: Missing: @protocol, @selector 8695 }; 8696 } // end anonymous namespace 8697 8698 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8699 bool InvalidBaseOK) { 8700 assert(!E->isValueDependent()); 8701 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8702 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8703 } 8704 8705 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8706 if (E->getOpcode() != BO_Add && 8707 E->getOpcode() != BO_Sub) 8708 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8709 8710 const Expr *PExp = E->getLHS(); 8711 const Expr *IExp = E->getRHS(); 8712 if (IExp->getType()->isPointerType()) 8713 std::swap(PExp, IExp); 8714 8715 bool EvalPtrOK = evaluatePointer(PExp, Result); 8716 if (!EvalPtrOK && !Info.noteFailure()) 8717 return false; 8718 8719 llvm::APSInt Offset; 8720 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8721 return false; 8722 8723 if (E->getOpcode() == BO_Sub) 8724 negateAsSigned(Offset); 8725 8726 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8727 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8728 } 8729 8730 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8731 return evaluateLValue(E->getSubExpr(), Result); 8732 } 8733 8734 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8735 const Expr *SubExpr = E->getSubExpr(); 8736 8737 switch (E->getCastKind()) { 8738 default: 8739 break; 8740 case CK_BitCast: 8741 case CK_CPointerToObjCPointerCast: 8742 case CK_BlockPointerToObjCPointerCast: 8743 case CK_AnyPointerToBlockPointerCast: 8744 case CK_AddressSpaceConversion: 8745 if (!Visit(SubExpr)) 8746 return false; 8747 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8748 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8749 // also static_casts, but we disallow them as a resolution to DR1312. 8750 if (!E->getType()->isVoidPointerType()) { 8751 if (!Result.InvalidBase && !Result.Designator.Invalid && 8752 !Result.IsNullPtr && 8753 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8754 E->getType()->getPointeeType()) && 8755 Info.getStdAllocatorCaller("allocate")) { 8756 // Inside a call to std::allocator::allocate and friends, we permit 8757 // casting from void* back to cv1 T* for a pointer that points to a 8758 // cv2 T. 8759 } else { 8760 Result.Designator.setInvalid(); 8761 if (SubExpr->getType()->isVoidPointerType()) 8762 CCEDiag(E, diag::note_constexpr_invalid_cast) 8763 << 3 << SubExpr->getType(); 8764 else 8765 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8766 } 8767 } 8768 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8769 ZeroInitialization(E); 8770 return true; 8771 8772 case CK_DerivedToBase: 8773 case CK_UncheckedDerivedToBase: 8774 if (!evaluatePointer(E->getSubExpr(), Result)) 8775 return false; 8776 if (!Result.Base && Result.Offset.isZero()) 8777 return true; 8778 8779 // Now figure out the necessary offset to add to the base LV to get from 8780 // the derived class to the base class. 8781 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8782 castAs<PointerType>()->getPointeeType(), 8783 Result); 8784 8785 case CK_BaseToDerived: 8786 if (!Visit(E->getSubExpr())) 8787 return false; 8788 if (!Result.Base && Result.Offset.isZero()) 8789 return true; 8790 return HandleBaseToDerivedCast(Info, E, Result); 8791 8792 case CK_Dynamic: 8793 if (!Visit(E->getSubExpr())) 8794 return false; 8795 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8796 8797 case CK_NullToPointer: 8798 VisitIgnoredValue(E->getSubExpr()); 8799 return ZeroInitialization(E); 8800 8801 case CK_IntegralToPointer: { 8802 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8803 8804 APValue Value; 8805 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8806 break; 8807 8808 if (Value.isInt()) { 8809 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8810 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8811 Result.Base = (Expr*)nullptr; 8812 Result.InvalidBase = false; 8813 Result.Offset = CharUnits::fromQuantity(N); 8814 Result.Designator.setInvalid(); 8815 Result.IsNullPtr = false; 8816 return true; 8817 } else { 8818 // Cast is of an lvalue, no need to change value. 8819 Result.setFrom(Info.Ctx, Value); 8820 return true; 8821 } 8822 } 8823 8824 case CK_ArrayToPointerDecay: { 8825 if (SubExpr->isGLValue()) { 8826 if (!evaluateLValue(SubExpr, Result)) 8827 return false; 8828 } else { 8829 APValue &Value = Info.CurrentCall->createTemporary( 8830 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8831 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8832 return false; 8833 } 8834 // The result is a pointer to the first element of the array. 8835 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8836 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8837 Result.addArray(Info, E, CAT); 8838 else 8839 Result.addUnsizedArray(Info, E, AT->getElementType()); 8840 return true; 8841 } 8842 8843 case CK_FunctionToPointerDecay: 8844 return evaluateLValue(SubExpr, Result); 8845 8846 case CK_LValueToRValue: { 8847 LValue LVal; 8848 if (!evaluateLValue(E->getSubExpr(), LVal)) 8849 return false; 8850 8851 APValue RVal; 8852 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8853 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8854 LVal, RVal)) 8855 return InvalidBaseOK && 8856 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8857 return Success(RVal, E); 8858 } 8859 } 8860 8861 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8862 } 8863 8864 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8865 UnaryExprOrTypeTrait ExprKind) { 8866 // C++ [expr.alignof]p3: 8867 // When alignof is applied to a reference type, the result is the 8868 // alignment of the referenced type. 8869 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8870 T = Ref->getPointeeType(); 8871 8872 if (T.getQualifiers().hasUnaligned()) 8873 return CharUnits::One(); 8874 8875 const bool AlignOfReturnsPreferred = 8876 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8877 8878 // __alignof is defined to return the preferred alignment. 8879 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8880 // as well. 8881 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8882 return Info.Ctx.toCharUnitsFromBits( 8883 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8884 // alignof and _Alignof are defined to return the ABI alignment. 8885 else if (ExprKind == UETT_AlignOf) 8886 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8887 else 8888 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8889 } 8890 8891 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8892 UnaryExprOrTypeTrait ExprKind) { 8893 E = E->IgnoreParens(); 8894 8895 // The kinds of expressions that we have special-case logic here for 8896 // should be kept up to date with the special checks for those 8897 // expressions in Sema. 8898 8899 // alignof decl is always accepted, even if it doesn't make sense: we default 8900 // to 1 in those cases. 8901 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8902 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8903 /*RefAsPointee*/true); 8904 8905 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8906 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8907 /*RefAsPointee*/true); 8908 8909 return GetAlignOfType(Info, E->getType(), ExprKind); 8910 } 8911 8912 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8913 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8914 return Info.Ctx.getDeclAlign(VD); 8915 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8916 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8917 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8918 } 8919 8920 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8921 /// __builtin_is_aligned and __builtin_assume_aligned. 8922 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8923 EvalInfo &Info, APSInt &Alignment) { 8924 if (!EvaluateInteger(E, Alignment, Info)) 8925 return false; 8926 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8927 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8928 return false; 8929 } 8930 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8931 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8932 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8933 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8934 << MaxValue << ForType << Alignment; 8935 return false; 8936 } 8937 // Ensure both alignment and source value have the same bit width so that we 8938 // don't assert when computing the resulting value. 8939 APSInt ExtAlignment = 8940 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8941 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8942 "Alignment should not be changed by ext/trunc"); 8943 Alignment = ExtAlignment; 8944 assert(Alignment.getBitWidth() == SrcWidth); 8945 return true; 8946 } 8947 8948 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8949 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8950 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8951 return true; 8952 8953 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8954 return false; 8955 8956 Result.setInvalid(E); 8957 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8958 Result.addUnsizedArray(Info, E, PointeeTy); 8959 return true; 8960 } 8961 8962 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8963 if (IsStringLiteralCall(E)) 8964 return Success(E); 8965 8966 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8967 return VisitBuiltinCallExpr(E, BuiltinOp); 8968 8969 return visitNonBuiltinCallExpr(E); 8970 } 8971 8972 // Determine if T is a character type for which we guarantee that 8973 // sizeof(T) == 1. 8974 static bool isOneByteCharacterType(QualType T) { 8975 return T->isCharType() || T->isChar8Type(); 8976 } 8977 8978 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8979 unsigned BuiltinOp) { 8980 switch (BuiltinOp) { 8981 case Builtin::BI__builtin_addressof: 8982 return evaluateLValue(E->getArg(0), Result); 8983 case Builtin::BI__builtin_assume_aligned: { 8984 // We need to be very careful here because: if the pointer does not have the 8985 // asserted alignment, then the behavior is undefined, and undefined 8986 // behavior is non-constant. 8987 if (!evaluatePointer(E->getArg(0), Result)) 8988 return false; 8989 8990 LValue OffsetResult(Result); 8991 APSInt Alignment; 8992 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8993 Alignment)) 8994 return false; 8995 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8996 8997 if (E->getNumArgs() > 2) { 8998 APSInt Offset; 8999 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9000 return false; 9001 9002 int64_t AdditionalOffset = -Offset.getZExtValue(); 9003 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9004 } 9005 9006 // If there is a base object, then it must have the correct alignment. 9007 if (OffsetResult.Base) { 9008 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9009 9010 if (BaseAlignment < Align) { 9011 Result.Designator.setInvalid(); 9012 // FIXME: Add support to Diagnostic for long / long long. 9013 CCEDiag(E->getArg(0), 9014 diag::note_constexpr_baa_insufficient_alignment) << 0 9015 << (unsigned)BaseAlignment.getQuantity() 9016 << (unsigned)Align.getQuantity(); 9017 return false; 9018 } 9019 } 9020 9021 // The offset must also have the correct alignment. 9022 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9023 Result.Designator.setInvalid(); 9024 9025 (OffsetResult.Base 9026 ? CCEDiag(E->getArg(0), 9027 diag::note_constexpr_baa_insufficient_alignment) << 1 9028 : CCEDiag(E->getArg(0), 9029 diag::note_constexpr_baa_value_insufficient_alignment)) 9030 << (int)OffsetResult.Offset.getQuantity() 9031 << (unsigned)Align.getQuantity(); 9032 return false; 9033 } 9034 9035 return true; 9036 } 9037 case Builtin::BI__builtin_align_up: 9038 case Builtin::BI__builtin_align_down: { 9039 if (!evaluatePointer(E->getArg(0), Result)) 9040 return false; 9041 APSInt Alignment; 9042 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9043 Alignment)) 9044 return false; 9045 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9046 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9047 // For align_up/align_down, we can return the same value if the alignment 9048 // is known to be greater or equal to the requested value. 9049 if (PtrAlign.getQuantity() >= Alignment) 9050 return true; 9051 9052 // The alignment could be greater than the minimum at run-time, so we cannot 9053 // infer much about the resulting pointer value. One case is possible: 9054 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9055 // can infer the correct index if the requested alignment is smaller than 9056 // the base alignment so we can perform the computation on the offset. 9057 if (BaseAlignment.getQuantity() >= Alignment) { 9058 assert(Alignment.getBitWidth() <= 64 && 9059 "Cannot handle > 64-bit address-space"); 9060 uint64_t Alignment64 = Alignment.getZExtValue(); 9061 CharUnits NewOffset = CharUnits::fromQuantity( 9062 BuiltinOp == Builtin::BI__builtin_align_down 9063 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9064 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9065 Result.adjustOffset(NewOffset - Result.Offset); 9066 // TODO: diagnose out-of-bounds values/only allow for arrays? 9067 return true; 9068 } 9069 // Otherwise, we cannot constant-evaluate the result. 9070 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9071 << Alignment; 9072 return false; 9073 } 9074 case Builtin::BI__builtin_operator_new: 9075 return HandleOperatorNewCall(Info, E, Result); 9076 case Builtin::BI__builtin_launder: 9077 return evaluatePointer(E->getArg(0), Result); 9078 case Builtin::BIstrchr: 9079 case Builtin::BIwcschr: 9080 case Builtin::BImemchr: 9081 case Builtin::BIwmemchr: 9082 if (Info.getLangOpts().CPlusPlus11) 9083 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9084 << /*isConstexpr*/0 << /*isConstructor*/0 9085 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9086 else 9087 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9088 LLVM_FALLTHROUGH; 9089 case Builtin::BI__builtin_strchr: 9090 case Builtin::BI__builtin_wcschr: 9091 case Builtin::BI__builtin_memchr: 9092 case Builtin::BI__builtin_char_memchr: 9093 case Builtin::BI__builtin_wmemchr: { 9094 if (!Visit(E->getArg(0))) 9095 return false; 9096 APSInt Desired; 9097 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9098 return false; 9099 uint64_t MaxLength = uint64_t(-1); 9100 if (BuiltinOp != Builtin::BIstrchr && 9101 BuiltinOp != Builtin::BIwcschr && 9102 BuiltinOp != Builtin::BI__builtin_strchr && 9103 BuiltinOp != Builtin::BI__builtin_wcschr) { 9104 APSInt N; 9105 if (!EvaluateInteger(E->getArg(2), N, Info)) 9106 return false; 9107 MaxLength = N.getExtValue(); 9108 } 9109 // We cannot find the value if there are no candidates to match against. 9110 if (MaxLength == 0u) 9111 return ZeroInitialization(E); 9112 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9113 Result.Designator.Invalid) 9114 return false; 9115 QualType CharTy = Result.Designator.getType(Info.Ctx); 9116 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9117 BuiltinOp == Builtin::BI__builtin_memchr; 9118 assert(IsRawByte || 9119 Info.Ctx.hasSameUnqualifiedType( 9120 CharTy, E->getArg(0)->getType()->getPointeeType())); 9121 // Pointers to const void may point to objects of incomplete type. 9122 if (IsRawByte && CharTy->isIncompleteType()) { 9123 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9124 return false; 9125 } 9126 // Give up on byte-oriented matching against multibyte elements. 9127 // FIXME: We can compare the bytes in the correct order. 9128 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9129 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9130 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9131 << CharTy; 9132 return false; 9133 } 9134 // Figure out what value we're actually looking for (after converting to 9135 // the corresponding unsigned type if necessary). 9136 uint64_t DesiredVal; 9137 bool StopAtNull = false; 9138 switch (BuiltinOp) { 9139 case Builtin::BIstrchr: 9140 case Builtin::BI__builtin_strchr: 9141 // strchr compares directly to the passed integer, and therefore 9142 // always fails if given an int that is not a char. 9143 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9144 E->getArg(1)->getType(), 9145 Desired), 9146 Desired)) 9147 return ZeroInitialization(E); 9148 StopAtNull = true; 9149 LLVM_FALLTHROUGH; 9150 case Builtin::BImemchr: 9151 case Builtin::BI__builtin_memchr: 9152 case Builtin::BI__builtin_char_memchr: 9153 // memchr compares by converting both sides to unsigned char. That's also 9154 // correct for strchr if we get this far (to cope with plain char being 9155 // unsigned in the strchr case). 9156 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9157 break; 9158 9159 case Builtin::BIwcschr: 9160 case Builtin::BI__builtin_wcschr: 9161 StopAtNull = true; 9162 LLVM_FALLTHROUGH; 9163 case Builtin::BIwmemchr: 9164 case Builtin::BI__builtin_wmemchr: 9165 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9166 DesiredVal = Desired.getZExtValue(); 9167 break; 9168 } 9169 9170 for (; MaxLength; --MaxLength) { 9171 APValue Char; 9172 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9173 !Char.isInt()) 9174 return false; 9175 if (Char.getInt().getZExtValue() == DesiredVal) 9176 return true; 9177 if (StopAtNull && !Char.getInt()) 9178 break; 9179 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9180 return false; 9181 } 9182 // Not found: return nullptr. 9183 return ZeroInitialization(E); 9184 } 9185 9186 case Builtin::BImemcpy: 9187 case Builtin::BImemmove: 9188 case Builtin::BIwmemcpy: 9189 case Builtin::BIwmemmove: 9190 if (Info.getLangOpts().CPlusPlus11) 9191 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9192 << /*isConstexpr*/0 << /*isConstructor*/0 9193 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9194 else 9195 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9196 LLVM_FALLTHROUGH; 9197 case Builtin::BI__builtin_memcpy: 9198 case Builtin::BI__builtin_memmove: 9199 case Builtin::BI__builtin_wmemcpy: 9200 case Builtin::BI__builtin_wmemmove: { 9201 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9202 BuiltinOp == Builtin::BIwmemmove || 9203 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9204 BuiltinOp == Builtin::BI__builtin_wmemmove; 9205 bool Move = BuiltinOp == Builtin::BImemmove || 9206 BuiltinOp == Builtin::BIwmemmove || 9207 BuiltinOp == Builtin::BI__builtin_memmove || 9208 BuiltinOp == Builtin::BI__builtin_wmemmove; 9209 9210 // The result of mem* is the first argument. 9211 if (!Visit(E->getArg(0))) 9212 return false; 9213 LValue Dest = Result; 9214 9215 LValue Src; 9216 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9217 return false; 9218 9219 APSInt N; 9220 if (!EvaluateInteger(E->getArg(2), N, Info)) 9221 return false; 9222 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9223 9224 // If the size is zero, we treat this as always being a valid no-op. 9225 // (Even if one of the src and dest pointers is null.) 9226 if (!N) 9227 return true; 9228 9229 // Otherwise, if either of the operands is null, we can't proceed. Don't 9230 // try to determine the type of the copied objects, because there aren't 9231 // any. 9232 if (!Src.Base || !Dest.Base) { 9233 APValue Val; 9234 (!Src.Base ? Src : Dest).moveInto(Val); 9235 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9236 << Move << WChar << !!Src.Base 9237 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9238 return false; 9239 } 9240 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9241 return false; 9242 9243 // We require that Src and Dest are both pointers to arrays of 9244 // trivially-copyable type. (For the wide version, the designator will be 9245 // invalid if the designated object is not a wchar_t.) 9246 QualType T = Dest.Designator.getType(Info.Ctx); 9247 QualType SrcT = Src.Designator.getType(Info.Ctx); 9248 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9249 // FIXME: Consider using our bit_cast implementation to support this. 9250 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9251 return false; 9252 } 9253 if (T->isIncompleteType()) { 9254 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9255 return false; 9256 } 9257 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9258 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9259 return false; 9260 } 9261 9262 // Figure out how many T's we're copying. 9263 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9264 if (!WChar) { 9265 uint64_t Remainder; 9266 llvm::APInt OrigN = N; 9267 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9268 if (Remainder) { 9269 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9270 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9271 << (unsigned)TSize; 9272 return false; 9273 } 9274 } 9275 9276 // Check that the copying will remain within the arrays, just so that we 9277 // can give a more meaningful diagnostic. This implicitly also checks that 9278 // N fits into 64 bits. 9279 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9280 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9281 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9282 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9283 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9284 << toString(N, 10, /*Signed*/false); 9285 return false; 9286 } 9287 uint64_t NElems = N.getZExtValue(); 9288 uint64_t NBytes = NElems * TSize; 9289 9290 // Check for overlap. 9291 int Direction = 1; 9292 if (HasSameBase(Src, Dest)) { 9293 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9294 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9295 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9296 // Dest is inside the source region. 9297 if (!Move) { 9298 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9299 return false; 9300 } 9301 // For memmove and friends, copy backwards. 9302 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9303 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9304 return false; 9305 Direction = -1; 9306 } else if (!Move && SrcOffset >= DestOffset && 9307 SrcOffset - DestOffset < NBytes) { 9308 // Src is inside the destination region for memcpy: invalid. 9309 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9310 return false; 9311 } 9312 } 9313 9314 while (true) { 9315 APValue Val; 9316 // FIXME: Set WantObjectRepresentation to true if we're copying a 9317 // char-like type? 9318 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9319 !handleAssignment(Info, E, Dest, T, Val)) 9320 return false; 9321 // Do not iterate past the last element; if we're copying backwards, that 9322 // might take us off the start of the array. 9323 if (--NElems == 0) 9324 return true; 9325 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9326 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9327 return false; 9328 } 9329 } 9330 9331 default: 9332 break; 9333 } 9334 9335 return visitNonBuiltinCallExpr(E); 9336 } 9337 9338 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9339 APValue &Result, const InitListExpr *ILE, 9340 QualType AllocType); 9341 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9342 APValue &Result, 9343 const CXXConstructExpr *CCE, 9344 QualType AllocType); 9345 9346 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9347 if (!Info.getLangOpts().CPlusPlus20) 9348 Info.CCEDiag(E, diag::note_constexpr_new); 9349 9350 // We cannot speculatively evaluate a delete expression. 9351 if (Info.SpeculativeEvaluationDepth) 9352 return false; 9353 9354 FunctionDecl *OperatorNew = E->getOperatorNew(); 9355 9356 bool IsNothrow = false; 9357 bool IsPlacement = false; 9358 if (OperatorNew->isReservedGlobalPlacementOperator() && 9359 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9360 // FIXME Support array placement new. 9361 assert(E->getNumPlacementArgs() == 1); 9362 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9363 return false; 9364 if (Result.Designator.Invalid) 9365 return false; 9366 IsPlacement = true; 9367 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9368 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9369 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9370 return false; 9371 } else if (E->getNumPlacementArgs()) { 9372 // The only new-placement list we support is of the form (std::nothrow). 9373 // 9374 // FIXME: There is no restriction on this, but it's not clear that any 9375 // other form makes any sense. We get here for cases such as: 9376 // 9377 // new (std::align_val_t{N}) X(int) 9378 // 9379 // (which should presumably be valid only if N is a multiple of 9380 // alignof(int), and in any case can't be deallocated unless N is 9381 // alignof(X) and X has new-extended alignment). 9382 if (E->getNumPlacementArgs() != 1 || 9383 !E->getPlacementArg(0)->getType()->isNothrowT()) 9384 return Error(E, diag::note_constexpr_new_placement); 9385 9386 LValue Nothrow; 9387 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9388 return false; 9389 IsNothrow = true; 9390 } 9391 9392 const Expr *Init = E->getInitializer(); 9393 const InitListExpr *ResizedArrayILE = nullptr; 9394 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9395 bool ValueInit = false; 9396 9397 QualType AllocType = E->getAllocatedType(); 9398 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9399 const Expr *Stripped = *ArraySize; 9400 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9401 Stripped = ICE->getSubExpr()) 9402 if (ICE->getCastKind() != CK_NoOp && 9403 ICE->getCastKind() != CK_IntegralCast) 9404 break; 9405 9406 llvm::APSInt ArrayBound; 9407 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9408 return false; 9409 9410 // C++ [expr.new]p9: 9411 // The expression is erroneous if: 9412 // -- [...] its value before converting to size_t [or] applying the 9413 // second standard conversion sequence is less than zero 9414 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9415 if (IsNothrow) 9416 return ZeroInitialization(E); 9417 9418 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9419 << ArrayBound << (*ArraySize)->getSourceRange(); 9420 return false; 9421 } 9422 9423 // -- its value is such that the size of the allocated object would 9424 // exceed the implementation-defined limit 9425 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9426 ArrayBound) > 9427 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9428 if (IsNothrow) 9429 return ZeroInitialization(E); 9430 9431 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9432 << ArrayBound << (*ArraySize)->getSourceRange(); 9433 return false; 9434 } 9435 9436 // -- the new-initializer is a braced-init-list and the number of 9437 // array elements for which initializers are provided [...] 9438 // exceeds the number of elements to initialize 9439 if (!Init) { 9440 // No initialization is performed. 9441 } else if (isa<CXXScalarValueInitExpr>(Init) || 9442 isa<ImplicitValueInitExpr>(Init)) { 9443 ValueInit = true; 9444 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9445 ResizedArrayCCE = CCE; 9446 } else { 9447 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9448 assert(CAT && "unexpected type for array initializer"); 9449 9450 unsigned Bits = 9451 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9452 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9453 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9454 if (InitBound.ugt(AllocBound)) { 9455 if (IsNothrow) 9456 return ZeroInitialization(E); 9457 9458 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9459 << toString(AllocBound, 10, /*Signed=*/false) 9460 << toString(InitBound, 10, /*Signed=*/false) 9461 << (*ArraySize)->getSourceRange(); 9462 return false; 9463 } 9464 9465 // If the sizes differ, we must have an initializer list, and we need 9466 // special handling for this case when we initialize. 9467 if (InitBound != AllocBound) 9468 ResizedArrayILE = cast<InitListExpr>(Init); 9469 } 9470 9471 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9472 ArrayType::Normal, 0); 9473 } else { 9474 assert(!AllocType->isArrayType() && 9475 "array allocation with non-array new"); 9476 } 9477 9478 APValue *Val; 9479 if (IsPlacement) { 9480 AccessKinds AK = AK_Construct; 9481 struct FindObjectHandler { 9482 EvalInfo &Info; 9483 const Expr *E; 9484 QualType AllocType; 9485 const AccessKinds AccessKind; 9486 APValue *Value; 9487 9488 typedef bool result_type; 9489 bool failed() { return false; } 9490 bool found(APValue &Subobj, QualType SubobjType) { 9491 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9492 // old name of the object to be used to name the new object. 9493 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9494 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9495 SubobjType << AllocType; 9496 return false; 9497 } 9498 Value = &Subobj; 9499 return true; 9500 } 9501 bool found(APSInt &Value, QualType SubobjType) { 9502 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9503 return false; 9504 } 9505 bool found(APFloat &Value, QualType SubobjType) { 9506 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9507 return false; 9508 } 9509 } Handler = {Info, E, AllocType, AK, nullptr}; 9510 9511 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9512 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9513 return false; 9514 9515 Val = Handler.Value; 9516 9517 // [basic.life]p1: 9518 // The lifetime of an object o of type T ends when [...] the storage 9519 // which the object occupies is [...] reused by an object that is not 9520 // nested within o (6.6.2). 9521 *Val = APValue(); 9522 } else { 9523 // Perform the allocation and obtain a pointer to the resulting object. 9524 Val = Info.createHeapAlloc(E, AllocType, Result); 9525 if (!Val) 9526 return false; 9527 } 9528 9529 if (ValueInit) { 9530 ImplicitValueInitExpr VIE(AllocType); 9531 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9532 return false; 9533 } else if (ResizedArrayILE) { 9534 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9535 AllocType)) 9536 return false; 9537 } else if (ResizedArrayCCE) { 9538 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9539 AllocType)) 9540 return false; 9541 } else if (Init) { 9542 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9543 return false; 9544 } else if (!getDefaultInitValue(AllocType, *Val)) { 9545 return false; 9546 } 9547 9548 // Array new returns a pointer to the first element, not a pointer to the 9549 // array. 9550 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9551 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9552 9553 return true; 9554 } 9555 //===----------------------------------------------------------------------===// 9556 // Member Pointer Evaluation 9557 //===----------------------------------------------------------------------===// 9558 9559 namespace { 9560 class MemberPointerExprEvaluator 9561 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9562 MemberPtr &Result; 9563 9564 bool Success(const ValueDecl *D) { 9565 Result = MemberPtr(D); 9566 return true; 9567 } 9568 public: 9569 9570 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9571 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9572 9573 bool Success(const APValue &V, const Expr *E) { 9574 Result.setFrom(V); 9575 return true; 9576 } 9577 bool ZeroInitialization(const Expr *E) { 9578 return Success((const ValueDecl*)nullptr); 9579 } 9580 9581 bool VisitCastExpr(const CastExpr *E); 9582 bool VisitUnaryAddrOf(const UnaryOperator *E); 9583 }; 9584 } // end anonymous namespace 9585 9586 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9587 EvalInfo &Info) { 9588 assert(!E->isValueDependent()); 9589 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9590 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9591 } 9592 9593 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9594 switch (E->getCastKind()) { 9595 default: 9596 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9597 9598 case CK_NullToMemberPointer: 9599 VisitIgnoredValue(E->getSubExpr()); 9600 return ZeroInitialization(E); 9601 9602 case CK_BaseToDerivedMemberPointer: { 9603 if (!Visit(E->getSubExpr())) 9604 return false; 9605 if (E->path_empty()) 9606 return true; 9607 // Base-to-derived member pointer casts store the path in derived-to-base 9608 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9609 // the wrong end of the derived->base arc, so stagger the path by one class. 9610 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9611 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9612 PathI != PathE; ++PathI) { 9613 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9614 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9615 if (!Result.castToDerived(Derived)) 9616 return Error(E); 9617 } 9618 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9619 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9620 return Error(E); 9621 return true; 9622 } 9623 9624 case CK_DerivedToBaseMemberPointer: 9625 if (!Visit(E->getSubExpr())) 9626 return false; 9627 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9628 PathE = E->path_end(); PathI != PathE; ++PathI) { 9629 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9630 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9631 if (!Result.castToBase(Base)) 9632 return Error(E); 9633 } 9634 return true; 9635 } 9636 } 9637 9638 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9639 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9640 // member can be formed. 9641 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9642 } 9643 9644 //===----------------------------------------------------------------------===// 9645 // Record Evaluation 9646 //===----------------------------------------------------------------------===// 9647 9648 namespace { 9649 class RecordExprEvaluator 9650 : public ExprEvaluatorBase<RecordExprEvaluator> { 9651 const LValue &This; 9652 APValue &Result; 9653 public: 9654 9655 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9656 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9657 9658 bool Success(const APValue &V, const Expr *E) { 9659 Result = V; 9660 return true; 9661 } 9662 bool ZeroInitialization(const Expr *E) { 9663 return ZeroInitialization(E, E->getType()); 9664 } 9665 bool ZeroInitialization(const Expr *E, QualType T); 9666 9667 bool VisitCallExpr(const CallExpr *E) { 9668 return handleCallExpr(E, Result, &This); 9669 } 9670 bool VisitCastExpr(const CastExpr *E); 9671 bool VisitInitListExpr(const InitListExpr *E); 9672 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9673 return VisitCXXConstructExpr(E, E->getType()); 9674 } 9675 bool VisitLambdaExpr(const LambdaExpr *E); 9676 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9677 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9678 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9679 bool VisitBinCmp(const BinaryOperator *E); 9680 }; 9681 } 9682 9683 /// Perform zero-initialization on an object of non-union class type. 9684 /// C++11 [dcl.init]p5: 9685 /// To zero-initialize an object or reference of type T means: 9686 /// [...] 9687 /// -- if T is a (possibly cv-qualified) non-union class type, 9688 /// each non-static data member and each base-class subobject is 9689 /// zero-initialized 9690 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9691 const RecordDecl *RD, 9692 const LValue &This, APValue &Result) { 9693 assert(!RD->isUnion() && "Expected non-union class type"); 9694 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9695 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9696 std::distance(RD->field_begin(), RD->field_end())); 9697 9698 if (RD->isInvalidDecl()) return false; 9699 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9700 9701 if (CD) { 9702 unsigned Index = 0; 9703 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9704 End = CD->bases_end(); I != End; ++I, ++Index) { 9705 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9706 LValue Subobject = This; 9707 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9708 return false; 9709 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9710 Result.getStructBase(Index))) 9711 return false; 9712 } 9713 } 9714 9715 for (const auto *I : RD->fields()) { 9716 // -- if T is a reference type, no initialization is performed. 9717 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9718 continue; 9719 9720 LValue Subobject = This; 9721 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9722 return false; 9723 9724 ImplicitValueInitExpr VIE(I->getType()); 9725 if (!EvaluateInPlace( 9726 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9727 return false; 9728 } 9729 9730 return true; 9731 } 9732 9733 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9734 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9735 if (RD->isInvalidDecl()) return false; 9736 if (RD->isUnion()) { 9737 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9738 // object's first non-static named data member is zero-initialized 9739 RecordDecl::field_iterator I = RD->field_begin(); 9740 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9741 ++I; 9742 if (I == RD->field_end()) { 9743 Result = APValue((const FieldDecl*)nullptr); 9744 return true; 9745 } 9746 9747 LValue Subobject = This; 9748 if (!HandleLValueMember(Info, E, Subobject, *I)) 9749 return false; 9750 Result = APValue(*I); 9751 ImplicitValueInitExpr VIE(I->getType()); 9752 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9753 } 9754 9755 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9756 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9757 return false; 9758 } 9759 9760 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9761 } 9762 9763 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9764 switch (E->getCastKind()) { 9765 default: 9766 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9767 9768 case CK_ConstructorConversion: 9769 return Visit(E->getSubExpr()); 9770 9771 case CK_DerivedToBase: 9772 case CK_UncheckedDerivedToBase: { 9773 APValue DerivedObject; 9774 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9775 return false; 9776 if (!DerivedObject.isStruct()) 9777 return Error(E->getSubExpr()); 9778 9779 // Derived-to-base rvalue conversion: just slice off the derived part. 9780 APValue *Value = &DerivedObject; 9781 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9782 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9783 PathE = E->path_end(); PathI != PathE; ++PathI) { 9784 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9785 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9786 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9787 RD = Base; 9788 } 9789 Result = *Value; 9790 return true; 9791 } 9792 } 9793 } 9794 9795 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9796 if (E->isTransparent()) 9797 return Visit(E->getInit(0)); 9798 9799 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9800 if (RD->isInvalidDecl()) return false; 9801 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9802 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9803 9804 EvalInfo::EvaluatingConstructorRAII EvalObj( 9805 Info, 9806 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9807 CXXRD && CXXRD->getNumBases()); 9808 9809 if (RD->isUnion()) { 9810 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9811 Result = APValue(Field); 9812 if (!Field) 9813 return true; 9814 9815 // If the initializer list for a union does not contain any elements, the 9816 // first element of the union is value-initialized. 9817 // FIXME: The element should be initialized from an initializer list. 9818 // Is this difference ever observable for initializer lists which 9819 // we don't build? 9820 ImplicitValueInitExpr VIE(Field->getType()); 9821 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9822 9823 LValue Subobject = This; 9824 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9825 return false; 9826 9827 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9828 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9829 isa<CXXDefaultInitExpr>(InitExpr)); 9830 9831 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9832 if (Field->isBitField()) 9833 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9834 Field); 9835 return true; 9836 } 9837 9838 return false; 9839 } 9840 9841 if (!Result.hasValue()) 9842 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9843 std::distance(RD->field_begin(), RD->field_end())); 9844 unsigned ElementNo = 0; 9845 bool Success = true; 9846 9847 // Initialize base classes. 9848 if (CXXRD && CXXRD->getNumBases()) { 9849 for (const auto &Base : CXXRD->bases()) { 9850 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9851 const Expr *Init = E->getInit(ElementNo); 9852 9853 LValue Subobject = This; 9854 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9855 return false; 9856 9857 APValue &FieldVal = Result.getStructBase(ElementNo); 9858 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9859 if (!Info.noteFailure()) 9860 return false; 9861 Success = false; 9862 } 9863 ++ElementNo; 9864 } 9865 9866 EvalObj.finishedConstructingBases(); 9867 } 9868 9869 // Initialize members. 9870 for (const auto *Field : RD->fields()) { 9871 // Anonymous bit-fields are not considered members of the class for 9872 // purposes of aggregate initialization. 9873 if (Field->isUnnamedBitfield()) 9874 continue; 9875 9876 LValue Subobject = This; 9877 9878 bool HaveInit = ElementNo < E->getNumInits(); 9879 9880 // FIXME: Diagnostics here should point to the end of the initializer 9881 // list, not the start. 9882 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9883 Subobject, Field, &Layout)) 9884 return false; 9885 9886 // Perform an implicit value-initialization for members beyond the end of 9887 // the initializer list. 9888 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9889 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9890 9891 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9892 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9893 isa<CXXDefaultInitExpr>(Init)); 9894 9895 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9896 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9897 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9898 FieldVal, Field))) { 9899 if (!Info.noteFailure()) 9900 return false; 9901 Success = false; 9902 } 9903 } 9904 9905 EvalObj.finishedConstructingFields(); 9906 9907 return Success; 9908 } 9909 9910 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9911 QualType T) { 9912 // Note that E's type is not necessarily the type of our class here; we might 9913 // be initializing an array element instead. 9914 const CXXConstructorDecl *FD = E->getConstructor(); 9915 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9916 9917 bool ZeroInit = E->requiresZeroInitialization(); 9918 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9919 // If we've already performed zero-initialization, we're already done. 9920 if (Result.hasValue()) 9921 return true; 9922 9923 if (ZeroInit) 9924 return ZeroInitialization(E, T); 9925 9926 return getDefaultInitValue(T, Result); 9927 } 9928 9929 const FunctionDecl *Definition = nullptr; 9930 auto Body = FD->getBody(Definition); 9931 9932 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9933 return false; 9934 9935 // Avoid materializing a temporary for an elidable copy/move constructor. 9936 if (E->isElidable() && !ZeroInit) 9937 if (const MaterializeTemporaryExpr *ME 9938 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9939 return Visit(ME->getSubExpr()); 9940 9941 if (ZeroInit && !ZeroInitialization(E, T)) 9942 return false; 9943 9944 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9945 return HandleConstructorCall(E, This, Args, 9946 cast<CXXConstructorDecl>(Definition), Info, 9947 Result); 9948 } 9949 9950 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9951 const CXXInheritedCtorInitExpr *E) { 9952 if (!Info.CurrentCall) { 9953 assert(Info.checkingPotentialConstantExpression()); 9954 return false; 9955 } 9956 9957 const CXXConstructorDecl *FD = E->getConstructor(); 9958 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9959 return false; 9960 9961 const FunctionDecl *Definition = nullptr; 9962 auto Body = FD->getBody(Definition); 9963 9964 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9965 return false; 9966 9967 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9968 cast<CXXConstructorDecl>(Definition), Info, 9969 Result); 9970 } 9971 9972 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9973 const CXXStdInitializerListExpr *E) { 9974 const ConstantArrayType *ArrayType = 9975 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9976 9977 LValue Array; 9978 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9979 return false; 9980 9981 // Get a pointer to the first element of the array. 9982 Array.addArray(Info, E, ArrayType); 9983 9984 auto InvalidType = [&] { 9985 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9986 << E->getType(); 9987 return false; 9988 }; 9989 9990 // FIXME: Perform the checks on the field types in SemaInit. 9991 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9992 RecordDecl::field_iterator Field = Record->field_begin(); 9993 if (Field == Record->field_end()) 9994 return InvalidType(); 9995 9996 // Start pointer. 9997 if (!Field->getType()->isPointerType() || 9998 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9999 ArrayType->getElementType())) 10000 return InvalidType(); 10001 10002 // FIXME: What if the initializer_list type has base classes, etc? 10003 Result = APValue(APValue::UninitStruct(), 0, 2); 10004 Array.moveInto(Result.getStructField(0)); 10005 10006 if (++Field == Record->field_end()) 10007 return InvalidType(); 10008 10009 if (Field->getType()->isPointerType() && 10010 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10011 ArrayType->getElementType())) { 10012 // End pointer. 10013 if (!HandleLValueArrayAdjustment(Info, E, Array, 10014 ArrayType->getElementType(), 10015 ArrayType->getSize().getZExtValue())) 10016 return false; 10017 Array.moveInto(Result.getStructField(1)); 10018 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10019 // Length. 10020 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10021 else 10022 return InvalidType(); 10023 10024 if (++Field != Record->field_end()) 10025 return InvalidType(); 10026 10027 return true; 10028 } 10029 10030 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10031 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10032 if (ClosureClass->isInvalidDecl()) 10033 return false; 10034 10035 const size_t NumFields = 10036 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10037 10038 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10039 E->capture_init_end()) && 10040 "The number of lambda capture initializers should equal the number of " 10041 "fields within the closure type"); 10042 10043 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10044 // Iterate through all the lambda's closure object's fields and initialize 10045 // them. 10046 auto *CaptureInitIt = E->capture_init_begin(); 10047 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10048 bool Success = true; 10049 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10050 for (const auto *Field : ClosureClass->fields()) { 10051 assert(CaptureInitIt != E->capture_init_end()); 10052 // Get the initializer for this field 10053 Expr *const CurFieldInit = *CaptureInitIt++; 10054 10055 // If there is no initializer, either this is a VLA or an error has 10056 // occurred. 10057 if (!CurFieldInit) 10058 return Error(E); 10059 10060 LValue Subobject = This; 10061 10062 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10063 return false; 10064 10065 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10066 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10067 if (!Info.keepEvaluatingAfterFailure()) 10068 return false; 10069 Success = false; 10070 } 10071 ++CaptureIt; 10072 } 10073 return Success; 10074 } 10075 10076 static bool EvaluateRecord(const Expr *E, const LValue &This, 10077 APValue &Result, EvalInfo &Info) { 10078 assert(!E->isValueDependent()); 10079 assert(E->isPRValue() && E->getType()->isRecordType() && 10080 "can't evaluate expression as a record rvalue"); 10081 return RecordExprEvaluator(Info, This, Result).Visit(E); 10082 } 10083 10084 //===----------------------------------------------------------------------===// 10085 // Temporary Evaluation 10086 // 10087 // Temporaries are represented in the AST as rvalues, but generally behave like 10088 // lvalues. The full-object of which the temporary is a subobject is implicitly 10089 // materialized so that a reference can bind to it. 10090 //===----------------------------------------------------------------------===// 10091 namespace { 10092 class TemporaryExprEvaluator 10093 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10094 public: 10095 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10096 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10097 10098 /// Visit an expression which constructs the value of this temporary. 10099 bool VisitConstructExpr(const Expr *E) { 10100 APValue &Value = Info.CurrentCall->createTemporary( 10101 E, E->getType(), ScopeKind::FullExpression, Result); 10102 return EvaluateInPlace(Value, Info, Result, E); 10103 } 10104 10105 bool VisitCastExpr(const CastExpr *E) { 10106 switch (E->getCastKind()) { 10107 default: 10108 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10109 10110 case CK_ConstructorConversion: 10111 return VisitConstructExpr(E->getSubExpr()); 10112 } 10113 } 10114 bool VisitInitListExpr(const InitListExpr *E) { 10115 return VisitConstructExpr(E); 10116 } 10117 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10118 return VisitConstructExpr(E); 10119 } 10120 bool VisitCallExpr(const CallExpr *E) { 10121 return VisitConstructExpr(E); 10122 } 10123 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10124 return VisitConstructExpr(E); 10125 } 10126 bool VisitLambdaExpr(const LambdaExpr *E) { 10127 return VisitConstructExpr(E); 10128 } 10129 }; 10130 } // end anonymous namespace 10131 10132 /// Evaluate an expression of record type as a temporary. 10133 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10134 assert(!E->isValueDependent()); 10135 assert(E->isPRValue() && E->getType()->isRecordType()); 10136 return TemporaryExprEvaluator(Info, Result).Visit(E); 10137 } 10138 10139 //===----------------------------------------------------------------------===// 10140 // Vector Evaluation 10141 //===----------------------------------------------------------------------===// 10142 10143 namespace { 10144 class VectorExprEvaluator 10145 : public ExprEvaluatorBase<VectorExprEvaluator> { 10146 APValue &Result; 10147 public: 10148 10149 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10150 : ExprEvaluatorBaseTy(info), Result(Result) {} 10151 10152 bool Success(ArrayRef<APValue> V, const Expr *E) { 10153 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10154 // FIXME: remove this APValue copy. 10155 Result = APValue(V.data(), V.size()); 10156 return true; 10157 } 10158 bool Success(const APValue &V, const Expr *E) { 10159 assert(V.isVector()); 10160 Result = V; 10161 return true; 10162 } 10163 bool ZeroInitialization(const Expr *E); 10164 10165 bool VisitUnaryReal(const UnaryOperator *E) 10166 { return Visit(E->getSubExpr()); } 10167 bool VisitCastExpr(const CastExpr* E); 10168 bool VisitInitListExpr(const InitListExpr *E); 10169 bool VisitUnaryImag(const UnaryOperator *E); 10170 bool VisitBinaryOperator(const BinaryOperator *E); 10171 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10172 // conditional select), shufflevector, ExtVectorElementExpr 10173 }; 10174 } // end anonymous namespace 10175 10176 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10177 assert(E->isPRValue() && E->getType()->isVectorType() && 10178 "not a vector prvalue"); 10179 return VectorExprEvaluator(Info, Result).Visit(E); 10180 } 10181 10182 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10183 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10184 unsigned NElts = VTy->getNumElements(); 10185 10186 const Expr *SE = E->getSubExpr(); 10187 QualType SETy = SE->getType(); 10188 10189 switch (E->getCastKind()) { 10190 case CK_VectorSplat: { 10191 APValue Val = APValue(); 10192 if (SETy->isIntegerType()) { 10193 APSInt IntResult; 10194 if (!EvaluateInteger(SE, IntResult, Info)) 10195 return false; 10196 Val = APValue(std::move(IntResult)); 10197 } else if (SETy->isRealFloatingType()) { 10198 APFloat FloatResult(0.0); 10199 if (!EvaluateFloat(SE, FloatResult, Info)) 10200 return false; 10201 Val = APValue(std::move(FloatResult)); 10202 } else { 10203 return Error(E); 10204 } 10205 10206 // Splat and create vector APValue. 10207 SmallVector<APValue, 4> Elts(NElts, Val); 10208 return Success(Elts, E); 10209 } 10210 case CK_BitCast: { 10211 // Evaluate the operand into an APInt we can extract from. 10212 llvm::APInt SValInt; 10213 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10214 return false; 10215 // Extract the elements 10216 QualType EltTy = VTy->getElementType(); 10217 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10218 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10219 SmallVector<APValue, 4> Elts; 10220 if (EltTy->isRealFloatingType()) { 10221 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10222 unsigned FloatEltSize = EltSize; 10223 if (&Sem == &APFloat::x87DoubleExtended()) 10224 FloatEltSize = 80; 10225 for (unsigned i = 0; i < NElts; i++) { 10226 llvm::APInt Elt; 10227 if (BigEndian) 10228 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10229 else 10230 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10231 Elts.push_back(APValue(APFloat(Sem, Elt))); 10232 } 10233 } else if (EltTy->isIntegerType()) { 10234 for (unsigned i = 0; i < NElts; i++) { 10235 llvm::APInt Elt; 10236 if (BigEndian) 10237 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10238 else 10239 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10240 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10241 } 10242 } else { 10243 return Error(E); 10244 } 10245 return Success(Elts, E); 10246 } 10247 default: 10248 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10249 } 10250 } 10251 10252 bool 10253 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10254 const VectorType *VT = E->getType()->castAs<VectorType>(); 10255 unsigned NumInits = E->getNumInits(); 10256 unsigned NumElements = VT->getNumElements(); 10257 10258 QualType EltTy = VT->getElementType(); 10259 SmallVector<APValue, 4> Elements; 10260 10261 // The number of initializers can be less than the number of 10262 // vector elements. For OpenCL, this can be due to nested vector 10263 // initialization. For GCC compatibility, missing trailing elements 10264 // should be initialized with zeroes. 10265 unsigned CountInits = 0, CountElts = 0; 10266 while (CountElts < NumElements) { 10267 // Handle nested vector initialization. 10268 if (CountInits < NumInits 10269 && E->getInit(CountInits)->getType()->isVectorType()) { 10270 APValue v; 10271 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10272 return Error(E); 10273 unsigned vlen = v.getVectorLength(); 10274 for (unsigned j = 0; j < vlen; j++) 10275 Elements.push_back(v.getVectorElt(j)); 10276 CountElts += vlen; 10277 } else if (EltTy->isIntegerType()) { 10278 llvm::APSInt sInt(32); 10279 if (CountInits < NumInits) { 10280 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10281 return false; 10282 } else // trailing integer zero. 10283 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10284 Elements.push_back(APValue(sInt)); 10285 CountElts++; 10286 } else { 10287 llvm::APFloat f(0.0); 10288 if (CountInits < NumInits) { 10289 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10290 return false; 10291 } else // trailing float zero. 10292 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10293 Elements.push_back(APValue(f)); 10294 CountElts++; 10295 } 10296 CountInits++; 10297 } 10298 return Success(Elements, E); 10299 } 10300 10301 bool 10302 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10303 const auto *VT = E->getType()->castAs<VectorType>(); 10304 QualType EltTy = VT->getElementType(); 10305 APValue ZeroElement; 10306 if (EltTy->isIntegerType()) 10307 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10308 else 10309 ZeroElement = 10310 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10311 10312 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10313 return Success(Elements, E); 10314 } 10315 10316 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10317 VisitIgnoredValue(E->getSubExpr()); 10318 return ZeroInitialization(E); 10319 } 10320 10321 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10322 BinaryOperatorKind Op = E->getOpcode(); 10323 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10324 "Operation not supported on vector types"); 10325 10326 if (Op == BO_Comma) 10327 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10328 10329 Expr *LHS = E->getLHS(); 10330 Expr *RHS = E->getRHS(); 10331 10332 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10333 "Must both be vector types"); 10334 // Checking JUST the types are the same would be fine, except shifts don't 10335 // need to have their types be the same (since you always shift by an int). 10336 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10337 E->getType()->castAs<VectorType>()->getNumElements() && 10338 RHS->getType()->castAs<VectorType>()->getNumElements() == 10339 E->getType()->castAs<VectorType>()->getNumElements() && 10340 "All operands must be the same size."); 10341 10342 APValue LHSValue; 10343 APValue RHSValue; 10344 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10345 if (!LHSOK && !Info.noteFailure()) 10346 return false; 10347 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10348 return false; 10349 10350 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10351 return false; 10352 10353 return Success(LHSValue, E); 10354 } 10355 10356 //===----------------------------------------------------------------------===// 10357 // Array Evaluation 10358 //===----------------------------------------------------------------------===// 10359 10360 namespace { 10361 class ArrayExprEvaluator 10362 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10363 const LValue &This; 10364 APValue &Result; 10365 public: 10366 10367 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10368 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10369 10370 bool Success(const APValue &V, const Expr *E) { 10371 assert(V.isArray() && "expected array"); 10372 Result = V; 10373 return true; 10374 } 10375 10376 bool ZeroInitialization(const Expr *E) { 10377 const ConstantArrayType *CAT = 10378 Info.Ctx.getAsConstantArrayType(E->getType()); 10379 if (!CAT) { 10380 if (E->getType()->isIncompleteArrayType()) { 10381 // We can be asked to zero-initialize a flexible array member; this 10382 // is represented as an ImplicitValueInitExpr of incomplete array 10383 // type. In this case, the array has zero elements. 10384 Result = APValue(APValue::UninitArray(), 0, 0); 10385 return true; 10386 } 10387 // FIXME: We could handle VLAs here. 10388 return Error(E); 10389 } 10390 10391 Result = APValue(APValue::UninitArray(), 0, 10392 CAT->getSize().getZExtValue()); 10393 if (!Result.hasArrayFiller()) 10394 return true; 10395 10396 // Zero-initialize all elements. 10397 LValue Subobject = This; 10398 Subobject.addArray(Info, E, CAT); 10399 ImplicitValueInitExpr VIE(CAT->getElementType()); 10400 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10401 } 10402 10403 bool VisitCallExpr(const CallExpr *E) { 10404 return handleCallExpr(E, Result, &This); 10405 } 10406 bool VisitInitListExpr(const InitListExpr *E, 10407 QualType AllocType = QualType()); 10408 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10409 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10410 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10411 const LValue &Subobject, 10412 APValue *Value, QualType Type); 10413 bool VisitStringLiteral(const StringLiteral *E, 10414 QualType AllocType = QualType()) { 10415 expandStringLiteral(Info, E, Result, AllocType); 10416 return true; 10417 } 10418 }; 10419 } // end anonymous namespace 10420 10421 static bool EvaluateArray(const Expr *E, const LValue &This, 10422 APValue &Result, EvalInfo &Info) { 10423 assert(!E->isValueDependent()); 10424 assert(E->isPRValue() && E->getType()->isArrayType() && 10425 "not an array prvalue"); 10426 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10427 } 10428 10429 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10430 APValue &Result, const InitListExpr *ILE, 10431 QualType AllocType) { 10432 assert(!ILE->isValueDependent()); 10433 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10434 "not an array prvalue"); 10435 return ArrayExprEvaluator(Info, This, Result) 10436 .VisitInitListExpr(ILE, AllocType); 10437 } 10438 10439 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10440 APValue &Result, 10441 const CXXConstructExpr *CCE, 10442 QualType AllocType) { 10443 assert(!CCE->isValueDependent()); 10444 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10445 "not an array prvalue"); 10446 return ArrayExprEvaluator(Info, This, Result) 10447 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10448 } 10449 10450 // Return true iff the given array filler may depend on the element index. 10451 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10452 // For now, just allow non-class value-initialization and initialization 10453 // lists comprised of them. 10454 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10455 return false; 10456 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10457 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10458 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10459 return true; 10460 } 10461 return false; 10462 } 10463 return true; 10464 } 10465 10466 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10467 QualType AllocType) { 10468 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10469 AllocType.isNull() ? E->getType() : AllocType); 10470 if (!CAT) 10471 return Error(E); 10472 10473 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10474 // an appropriately-typed string literal enclosed in braces. 10475 if (E->isStringLiteralInit()) { 10476 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10477 // FIXME: Support ObjCEncodeExpr here once we support it in 10478 // ArrayExprEvaluator generally. 10479 if (!SL) 10480 return Error(E); 10481 return VisitStringLiteral(SL, AllocType); 10482 } 10483 // Any other transparent list init will need proper handling of the 10484 // AllocType; we can't just recurse to the inner initializer. 10485 assert(!E->isTransparent() && 10486 "transparent array list initialization is not string literal init?"); 10487 10488 bool Success = true; 10489 10490 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10491 "zero-initialized array shouldn't have any initialized elts"); 10492 APValue Filler; 10493 if (Result.isArray() && Result.hasArrayFiller()) 10494 Filler = Result.getArrayFiller(); 10495 10496 unsigned NumEltsToInit = E->getNumInits(); 10497 unsigned NumElts = CAT->getSize().getZExtValue(); 10498 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10499 10500 // If the initializer might depend on the array index, run it for each 10501 // array element. 10502 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10503 NumEltsToInit = NumElts; 10504 10505 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10506 << NumEltsToInit << ".\n"); 10507 10508 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10509 10510 // If the array was previously zero-initialized, preserve the 10511 // zero-initialized values. 10512 if (Filler.hasValue()) { 10513 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10514 Result.getArrayInitializedElt(I) = Filler; 10515 if (Result.hasArrayFiller()) 10516 Result.getArrayFiller() = Filler; 10517 } 10518 10519 LValue Subobject = This; 10520 Subobject.addArray(Info, E, CAT); 10521 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10522 const Expr *Init = 10523 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10524 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10525 Info, Subobject, Init) || 10526 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10527 CAT->getElementType(), 1)) { 10528 if (!Info.noteFailure()) 10529 return false; 10530 Success = false; 10531 } 10532 } 10533 10534 if (!Result.hasArrayFiller()) 10535 return Success; 10536 10537 // If we get here, we have a trivial filler, which we can just evaluate 10538 // once and splat over the rest of the array elements. 10539 assert(FillerExpr && "no array filler for incomplete init list"); 10540 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10541 FillerExpr) && Success; 10542 } 10543 10544 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10545 LValue CommonLV; 10546 if (E->getCommonExpr() && 10547 !Evaluate(Info.CurrentCall->createTemporary( 10548 E->getCommonExpr(), 10549 getStorageType(Info.Ctx, E->getCommonExpr()), 10550 ScopeKind::FullExpression, CommonLV), 10551 Info, E->getCommonExpr()->getSourceExpr())) 10552 return false; 10553 10554 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10555 10556 uint64_t Elements = CAT->getSize().getZExtValue(); 10557 Result = APValue(APValue::UninitArray(), Elements, Elements); 10558 10559 LValue Subobject = This; 10560 Subobject.addArray(Info, E, CAT); 10561 10562 bool Success = true; 10563 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10564 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10565 Info, Subobject, E->getSubExpr()) || 10566 !HandleLValueArrayAdjustment(Info, E, Subobject, 10567 CAT->getElementType(), 1)) { 10568 if (!Info.noteFailure()) 10569 return false; 10570 Success = false; 10571 } 10572 } 10573 10574 return Success; 10575 } 10576 10577 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10578 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10579 } 10580 10581 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10582 const LValue &Subobject, 10583 APValue *Value, 10584 QualType Type) { 10585 bool HadZeroInit = Value->hasValue(); 10586 10587 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10588 unsigned N = CAT->getSize().getZExtValue(); 10589 10590 // Preserve the array filler if we had prior zero-initialization. 10591 APValue Filler = 10592 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10593 : APValue(); 10594 10595 *Value = APValue(APValue::UninitArray(), N, N); 10596 10597 if (HadZeroInit) 10598 for (unsigned I = 0; I != N; ++I) 10599 Value->getArrayInitializedElt(I) = Filler; 10600 10601 // Initialize the elements. 10602 LValue ArrayElt = Subobject; 10603 ArrayElt.addArray(Info, E, CAT); 10604 for (unsigned I = 0; I != N; ++I) 10605 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10606 CAT->getElementType()) || 10607 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10608 CAT->getElementType(), 1)) 10609 return false; 10610 10611 return true; 10612 } 10613 10614 if (!Type->isRecordType()) 10615 return Error(E); 10616 10617 return RecordExprEvaluator(Info, Subobject, *Value) 10618 .VisitCXXConstructExpr(E, Type); 10619 } 10620 10621 //===----------------------------------------------------------------------===// 10622 // Integer Evaluation 10623 // 10624 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10625 // types and back in constant folding. Integer values are thus represented 10626 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10627 //===----------------------------------------------------------------------===// 10628 10629 namespace { 10630 class IntExprEvaluator 10631 : public ExprEvaluatorBase<IntExprEvaluator> { 10632 APValue &Result; 10633 public: 10634 IntExprEvaluator(EvalInfo &info, APValue &result) 10635 : ExprEvaluatorBaseTy(info), Result(result) {} 10636 10637 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10638 assert(E->getType()->isIntegralOrEnumerationType() && 10639 "Invalid evaluation result."); 10640 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10641 "Invalid evaluation result."); 10642 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10643 "Invalid evaluation result."); 10644 Result = APValue(SI); 10645 return true; 10646 } 10647 bool Success(const llvm::APSInt &SI, const Expr *E) { 10648 return Success(SI, E, Result); 10649 } 10650 10651 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10652 assert(E->getType()->isIntegralOrEnumerationType() && 10653 "Invalid evaluation result."); 10654 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10655 "Invalid evaluation result."); 10656 Result = APValue(APSInt(I)); 10657 Result.getInt().setIsUnsigned( 10658 E->getType()->isUnsignedIntegerOrEnumerationType()); 10659 return true; 10660 } 10661 bool Success(const llvm::APInt &I, const Expr *E) { 10662 return Success(I, E, Result); 10663 } 10664 10665 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10666 assert(E->getType()->isIntegralOrEnumerationType() && 10667 "Invalid evaluation result."); 10668 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10669 return true; 10670 } 10671 bool Success(uint64_t Value, const Expr *E) { 10672 return Success(Value, E, Result); 10673 } 10674 10675 bool Success(CharUnits Size, const Expr *E) { 10676 return Success(Size.getQuantity(), E); 10677 } 10678 10679 bool Success(const APValue &V, const Expr *E) { 10680 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10681 Result = V; 10682 return true; 10683 } 10684 return Success(V.getInt(), E); 10685 } 10686 10687 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10688 10689 //===--------------------------------------------------------------------===// 10690 // Visitor Methods 10691 //===--------------------------------------------------------------------===// 10692 10693 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10694 return Success(E->getValue(), E); 10695 } 10696 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10697 return Success(E->getValue(), E); 10698 } 10699 10700 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10701 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10702 if (CheckReferencedDecl(E, E->getDecl())) 10703 return true; 10704 10705 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10706 } 10707 bool VisitMemberExpr(const MemberExpr *E) { 10708 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10709 VisitIgnoredBaseExpression(E->getBase()); 10710 return true; 10711 } 10712 10713 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10714 } 10715 10716 bool VisitCallExpr(const CallExpr *E); 10717 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10718 bool VisitBinaryOperator(const BinaryOperator *E); 10719 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10720 bool VisitUnaryOperator(const UnaryOperator *E); 10721 10722 bool VisitCastExpr(const CastExpr* E); 10723 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10724 10725 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10726 return Success(E->getValue(), E); 10727 } 10728 10729 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10730 return Success(E->getValue(), E); 10731 } 10732 10733 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10734 if (Info.ArrayInitIndex == uint64_t(-1)) { 10735 // We were asked to evaluate this subexpression independent of the 10736 // enclosing ArrayInitLoopExpr. We can't do that. 10737 Info.FFDiag(E); 10738 return false; 10739 } 10740 return Success(Info.ArrayInitIndex, E); 10741 } 10742 10743 // Note, GNU defines __null as an integer, not a pointer. 10744 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10745 return ZeroInitialization(E); 10746 } 10747 10748 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10749 return Success(E->getValue(), E); 10750 } 10751 10752 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10753 return Success(E->getValue(), E); 10754 } 10755 10756 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10757 return Success(E->getValue(), E); 10758 } 10759 10760 bool VisitUnaryReal(const UnaryOperator *E); 10761 bool VisitUnaryImag(const UnaryOperator *E); 10762 10763 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10764 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10765 bool VisitSourceLocExpr(const SourceLocExpr *E); 10766 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10767 bool VisitRequiresExpr(const RequiresExpr *E); 10768 // FIXME: Missing: array subscript of vector, member of vector 10769 }; 10770 10771 class FixedPointExprEvaluator 10772 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10773 APValue &Result; 10774 10775 public: 10776 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10777 : ExprEvaluatorBaseTy(info), Result(result) {} 10778 10779 bool Success(const llvm::APInt &I, const Expr *E) { 10780 return Success( 10781 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10782 } 10783 10784 bool Success(uint64_t Value, const Expr *E) { 10785 return Success( 10786 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10787 } 10788 10789 bool Success(const APValue &V, const Expr *E) { 10790 return Success(V.getFixedPoint(), E); 10791 } 10792 10793 bool Success(const APFixedPoint &V, const Expr *E) { 10794 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10795 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10796 "Invalid evaluation result."); 10797 Result = APValue(V); 10798 return true; 10799 } 10800 10801 //===--------------------------------------------------------------------===// 10802 // Visitor Methods 10803 //===--------------------------------------------------------------------===// 10804 10805 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10806 return Success(E->getValue(), E); 10807 } 10808 10809 bool VisitCastExpr(const CastExpr *E); 10810 bool VisitUnaryOperator(const UnaryOperator *E); 10811 bool VisitBinaryOperator(const BinaryOperator *E); 10812 }; 10813 } // end anonymous namespace 10814 10815 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10816 /// produce either the integer value or a pointer. 10817 /// 10818 /// GCC has a heinous extension which folds casts between pointer types and 10819 /// pointer-sized integral types. We support this by allowing the evaluation of 10820 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10821 /// Some simple arithmetic on such values is supported (they are treated much 10822 /// like char*). 10823 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10824 EvalInfo &Info) { 10825 assert(!E->isValueDependent()); 10826 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 10827 return IntExprEvaluator(Info, Result).Visit(E); 10828 } 10829 10830 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10831 assert(!E->isValueDependent()); 10832 APValue Val; 10833 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10834 return false; 10835 if (!Val.isInt()) { 10836 // FIXME: It would be better to produce the diagnostic for casting 10837 // a pointer to an integer. 10838 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10839 return false; 10840 } 10841 Result = Val.getInt(); 10842 return true; 10843 } 10844 10845 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10846 APValue Evaluated = E->EvaluateInContext( 10847 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10848 return Success(Evaluated, E); 10849 } 10850 10851 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10852 EvalInfo &Info) { 10853 assert(!E->isValueDependent()); 10854 if (E->getType()->isFixedPointType()) { 10855 APValue Val; 10856 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10857 return false; 10858 if (!Val.isFixedPoint()) 10859 return false; 10860 10861 Result = Val.getFixedPoint(); 10862 return true; 10863 } 10864 return false; 10865 } 10866 10867 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10868 EvalInfo &Info) { 10869 assert(!E->isValueDependent()); 10870 if (E->getType()->isIntegerType()) { 10871 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10872 APSInt Val; 10873 if (!EvaluateInteger(E, Val, Info)) 10874 return false; 10875 Result = APFixedPoint(Val, FXSema); 10876 return true; 10877 } else if (E->getType()->isFixedPointType()) { 10878 return EvaluateFixedPoint(E, Result, Info); 10879 } 10880 return false; 10881 } 10882 10883 /// Check whether the given declaration can be directly converted to an integral 10884 /// rvalue. If not, no diagnostic is produced; there are other things we can 10885 /// try. 10886 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10887 // Enums are integer constant exprs. 10888 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10889 // Check for signedness/width mismatches between E type and ECD value. 10890 bool SameSign = (ECD->getInitVal().isSigned() 10891 == E->getType()->isSignedIntegerOrEnumerationType()); 10892 bool SameWidth = (ECD->getInitVal().getBitWidth() 10893 == Info.Ctx.getIntWidth(E->getType())); 10894 if (SameSign && SameWidth) 10895 return Success(ECD->getInitVal(), E); 10896 else { 10897 // Get rid of mismatch (otherwise Success assertions will fail) 10898 // by computing a new value matching the type of E. 10899 llvm::APSInt Val = ECD->getInitVal(); 10900 if (!SameSign) 10901 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10902 if (!SameWidth) 10903 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10904 return Success(Val, E); 10905 } 10906 } 10907 return false; 10908 } 10909 10910 /// Values returned by __builtin_classify_type, chosen to match the values 10911 /// produced by GCC's builtin. 10912 enum class GCCTypeClass { 10913 None = -1, 10914 Void = 0, 10915 Integer = 1, 10916 // GCC reserves 2 for character types, but instead classifies them as 10917 // integers. 10918 Enum = 3, 10919 Bool = 4, 10920 Pointer = 5, 10921 // GCC reserves 6 for references, but appears to never use it (because 10922 // expressions never have reference type, presumably). 10923 PointerToDataMember = 7, 10924 RealFloat = 8, 10925 Complex = 9, 10926 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10927 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10928 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10929 // uses 12 for that purpose, same as for a class or struct. Maybe it 10930 // internally implements a pointer to member as a struct? Who knows. 10931 PointerToMemberFunction = 12, // Not a bug, see above. 10932 ClassOrStruct = 12, 10933 Union = 13, 10934 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10935 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10936 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10937 // literals. 10938 }; 10939 10940 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10941 /// as GCC. 10942 static GCCTypeClass 10943 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10944 assert(!T->isDependentType() && "unexpected dependent type"); 10945 10946 QualType CanTy = T.getCanonicalType(); 10947 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10948 10949 switch (CanTy->getTypeClass()) { 10950 #define TYPE(ID, BASE) 10951 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10952 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10953 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10954 #include "clang/AST/TypeNodes.inc" 10955 case Type::Auto: 10956 case Type::DeducedTemplateSpecialization: 10957 llvm_unreachable("unexpected non-canonical or dependent type"); 10958 10959 case Type::Builtin: 10960 switch (BT->getKind()) { 10961 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10962 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10963 case BuiltinType::ID: return GCCTypeClass::Integer; 10964 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10965 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10966 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10967 case BuiltinType::ID: break; 10968 #include "clang/AST/BuiltinTypes.def" 10969 case BuiltinType::Void: 10970 return GCCTypeClass::Void; 10971 10972 case BuiltinType::Bool: 10973 return GCCTypeClass::Bool; 10974 10975 case BuiltinType::Char_U: 10976 case BuiltinType::UChar: 10977 case BuiltinType::WChar_U: 10978 case BuiltinType::Char8: 10979 case BuiltinType::Char16: 10980 case BuiltinType::Char32: 10981 case BuiltinType::UShort: 10982 case BuiltinType::UInt: 10983 case BuiltinType::ULong: 10984 case BuiltinType::ULongLong: 10985 case BuiltinType::UInt128: 10986 return GCCTypeClass::Integer; 10987 10988 case BuiltinType::UShortAccum: 10989 case BuiltinType::UAccum: 10990 case BuiltinType::ULongAccum: 10991 case BuiltinType::UShortFract: 10992 case BuiltinType::UFract: 10993 case BuiltinType::ULongFract: 10994 case BuiltinType::SatUShortAccum: 10995 case BuiltinType::SatUAccum: 10996 case BuiltinType::SatULongAccum: 10997 case BuiltinType::SatUShortFract: 10998 case BuiltinType::SatUFract: 10999 case BuiltinType::SatULongFract: 11000 return GCCTypeClass::None; 11001 11002 case BuiltinType::NullPtr: 11003 11004 case BuiltinType::ObjCId: 11005 case BuiltinType::ObjCClass: 11006 case BuiltinType::ObjCSel: 11007 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11008 case BuiltinType::Id: 11009 #include "clang/Basic/OpenCLImageTypes.def" 11010 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11011 case BuiltinType::Id: 11012 #include "clang/Basic/OpenCLExtensionTypes.def" 11013 case BuiltinType::OCLSampler: 11014 case BuiltinType::OCLEvent: 11015 case BuiltinType::OCLClkEvent: 11016 case BuiltinType::OCLQueue: 11017 case BuiltinType::OCLReserveID: 11018 #define SVE_TYPE(Name, Id, SingletonId) \ 11019 case BuiltinType::Id: 11020 #include "clang/Basic/AArch64SVEACLETypes.def" 11021 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11022 case BuiltinType::Id: 11023 #include "clang/Basic/PPCTypes.def" 11024 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11025 #include "clang/Basic/RISCVVTypes.def" 11026 return GCCTypeClass::None; 11027 11028 case BuiltinType::Dependent: 11029 llvm_unreachable("unexpected dependent type"); 11030 }; 11031 llvm_unreachable("unexpected placeholder type"); 11032 11033 case Type::Enum: 11034 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11035 11036 case Type::Pointer: 11037 case Type::ConstantArray: 11038 case Type::VariableArray: 11039 case Type::IncompleteArray: 11040 case Type::FunctionNoProto: 11041 case Type::FunctionProto: 11042 return GCCTypeClass::Pointer; 11043 11044 case Type::MemberPointer: 11045 return CanTy->isMemberDataPointerType() 11046 ? GCCTypeClass::PointerToDataMember 11047 : GCCTypeClass::PointerToMemberFunction; 11048 11049 case Type::Complex: 11050 return GCCTypeClass::Complex; 11051 11052 case Type::Record: 11053 return CanTy->isUnionType() ? GCCTypeClass::Union 11054 : GCCTypeClass::ClassOrStruct; 11055 11056 case Type::Atomic: 11057 // GCC classifies _Atomic T the same as T. 11058 return EvaluateBuiltinClassifyType( 11059 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11060 11061 case Type::BlockPointer: 11062 case Type::Vector: 11063 case Type::ExtVector: 11064 case Type::ConstantMatrix: 11065 case Type::ObjCObject: 11066 case Type::ObjCInterface: 11067 case Type::ObjCObjectPointer: 11068 case Type::Pipe: 11069 case Type::ExtInt: 11070 // GCC classifies vectors as None. We follow its lead and classify all 11071 // other types that don't fit into the regular classification the same way. 11072 return GCCTypeClass::None; 11073 11074 case Type::LValueReference: 11075 case Type::RValueReference: 11076 llvm_unreachable("invalid type for expression"); 11077 } 11078 11079 llvm_unreachable("unexpected type class"); 11080 } 11081 11082 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11083 /// as GCC. 11084 static GCCTypeClass 11085 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11086 // If no argument was supplied, default to None. This isn't 11087 // ideal, however it is what gcc does. 11088 if (E->getNumArgs() == 0) 11089 return GCCTypeClass::None; 11090 11091 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11092 // being an ICE, but still folds it to a constant using the type of the first 11093 // argument. 11094 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11095 } 11096 11097 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11098 /// __builtin_constant_p when applied to the given pointer. 11099 /// 11100 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11101 /// or it points to the first character of a string literal. 11102 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11103 APValue::LValueBase Base = LV.getLValueBase(); 11104 if (Base.isNull()) { 11105 // A null base is acceptable. 11106 return true; 11107 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11108 if (!isa<StringLiteral>(E)) 11109 return false; 11110 return LV.getLValueOffset().isZero(); 11111 } else if (Base.is<TypeInfoLValue>()) { 11112 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11113 // evaluate to true. 11114 return true; 11115 } else { 11116 // Any other base is not constant enough for GCC. 11117 return false; 11118 } 11119 } 11120 11121 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11122 /// GCC as we can manage. 11123 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11124 // This evaluation is not permitted to have side-effects, so evaluate it in 11125 // a speculative evaluation context. 11126 SpeculativeEvaluationRAII SpeculativeEval(Info); 11127 11128 // Constant-folding is always enabled for the operand of __builtin_constant_p 11129 // (even when the enclosing evaluation context otherwise requires a strict 11130 // language-specific constant expression). 11131 FoldConstant Fold(Info, true); 11132 11133 QualType ArgType = Arg->getType(); 11134 11135 // __builtin_constant_p always has one operand. The rules which gcc follows 11136 // are not precisely documented, but are as follows: 11137 // 11138 // - If the operand is of integral, floating, complex or enumeration type, 11139 // and can be folded to a known value of that type, it returns 1. 11140 // - If the operand can be folded to a pointer to the first character 11141 // of a string literal (or such a pointer cast to an integral type) 11142 // or to a null pointer or an integer cast to a pointer, it returns 1. 11143 // 11144 // Otherwise, it returns 0. 11145 // 11146 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11147 // its support for this did not work prior to GCC 9 and is not yet well 11148 // understood. 11149 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11150 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11151 ArgType->isNullPtrType()) { 11152 APValue V; 11153 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11154 Fold.keepDiagnostics(); 11155 return false; 11156 } 11157 11158 // For a pointer (possibly cast to integer), there are special rules. 11159 if (V.getKind() == APValue::LValue) 11160 return EvaluateBuiltinConstantPForLValue(V); 11161 11162 // Otherwise, any constant value is good enough. 11163 return V.hasValue(); 11164 } 11165 11166 // Anything else isn't considered to be sufficiently constant. 11167 return false; 11168 } 11169 11170 /// Retrieves the "underlying object type" of the given expression, 11171 /// as used by __builtin_object_size. 11172 static QualType getObjectType(APValue::LValueBase B) { 11173 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11174 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11175 return VD->getType(); 11176 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11177 if (isa<CompoundLiteralExpr>(E)) 11178 return E->getType(); 11179 } else if (B.is<TypeInfoLValue>()) { 11180 return B.getTypeInfoType(); 11181 } else if (B.is<DynamicAllocLValue>()) { 11182 return B.getDynamicAllocType(); 11183 } 11184 11185 return QualType(); 11186 } 11187 11188 /// A more selective version of E->IgnoreParenCasts for 11189 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11190 /// to change the type of E. 11191 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11192 /// 11193 /// Always returns an RValue with a pointer representation. 11194 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11195 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11196 11197 auto *NoParens = E->IgnoreParens(); 11198 auto *Cast = dyn_cast<CastExpr>(NoParens); 11199 if (Cast == nullptr) 11200 return NoParens; 11201 11202 // We only conservatively allow a few kinds of casts, because this code is 11203 // inherently a simple solution that seeks to support the common case. 11204 auto CastKind = Cast->getCastKind(); 11205 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11206 CastKind != CK_AddressSpaceConversion) 11207 return NoParens; 11208 11209 auto *SubExpr = Cast->getSubExpr(); 11210 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11211 return NoParens; 11212 return ignorePointerCastsAndParens(SubExpr); 11213 } 11214 11215 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11216 /// record layout. e.g. 11217 /// struct { struct { int a, b; } fst, snd; } obj; 11218 /// obj.fst // no 11219 /// obj.snd // yes 11220 /// obj.fst.a // no 11221 /// obj.fst.b // no 11222 /// obj.snd.a // no 11223 /// obj.snd.b // yes 11224 /// 11225 /// Please note: this function is specialized for how __builtin_object_size 11226 /// views "objects". 11227 /// 11228 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11229 /// correct result, it will always return true. 11230 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11231 assert(!LVal.Designator.Invalid); 11232 11233 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11234 const RecordDecl *Parent = FD->getParent(); 11235 Invalid = Parent->isInvalidDecl(); 11236 if (Invalid || Parent->isUnion()) 11237 return true; 11238 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11239 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11240 }; 11241 11242 auto &Base = LVal.getLValueBase(); 11243 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11244 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11245 bool Invalid; 11246 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11247 return Invalid; 11248 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11249 for (auto *FD : IFD->chain()) { 11250 bool Invalid; 11251 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11252 return Invalid; 11253 } 11254 } 11255 } 11256 11257 unsigned I = 0; 11258 QualType BaseType = getType(Base); 11259 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11260 // If we don't know the array bound, conservatively assume we're looking at 11261 // the final array element. 11262 ++I; 11263 if (BaseType->isIncompleteArrayType()) 11264 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11265 else 11266 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11267 } 11268 11269 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11270 const auto &Entry = LVal.Designator.Entries[I]; 11271 if (BaseType->isArrayType()) { 11272 // Because __builtin_object_size treats arrays as objects, we can ignore 11273 // the index iff this is the last array in the Designator. 11274 if (I + 1 == E) 11275 return true; 11276 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11277 uint64_t Index = Entry.getAsArrayIndex(); 11278 if (Index + 1 != CAT->getSize()) 11279 return false; 11280 BaseType = CAT->getElementType(); 11281 } else if (BaseType->isAnyComplexType()) { 11282 const auto *CT = BaseType->castAs<ComplexType>(); 11283 uint64_t Index = Entry.getAsArrayIndex(); 11284 if (Index != 1) 11285 return false; 11286 BaseType = CT->getElementType(); 11287 } else if (auto *FD = getAsField(Entry)) { 11288 bool Invalid; 11289 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11290 return Invalid; 11291 BaseType = FD->getType(); 11292 } else { 11293 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11294 return false; 11295 } 11296 } 11297 return true; 11298 } 11299 11300 /// Tests to see if the LValue has a user-specified designator (that isn't 11301 /// necessarily valid). Note that this always returns 'true' if the LValue has 11302 /// an unsized array as its first designator entry, because there's currently no 11303 /// way to tell if the user typed *foo or foo[0]. 11304 static bool refersToCompleteObject(const LValue &LVal) { 11305 if (LVal.Designator.Invalid) 11306 return false; 11307 11308 if (!LVal.Designator.Entries.empty()) 11309 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11310 11311 if (!LVal.InvalidBase) 11312 return true; 11313 11314 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11315 // the LValueBase. 11316 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11317 return !E || !isa<MemberExpr>(E); 11318 } 11319 11320 /// Attempts to detect a user writing into a piece of memory that's impossible 11321 /// to figure out the size of by just using types. 11322 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11323 const SubobjectDesignator &Designator = LVal.Designator; 11324 // Notes: 11325 // - Users can only write off of the end when we have an invalid base. Invalid 11326 // bases imply we don't know where the memory came from. 11327 // - We used to be a bit more aggressive here; we'd only be conservative if 11328 // the array at the end was flexible, or if it had 0 or 1 elements. This 11329 // broke some common standard library extensions (PR30346), but was 11330 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11331 // with some sort of list. OTOH, it seems that GCC is always 11332 // conservative with the last element in structs (if it's an array), so our 11333 // current behavior is more compatible than an explicit list approach would 11334 // be. 11335 return LVal.InvalidBase && 11336 Designator.Entries.size() == Designator.MostDerivedPathLength && 11337 Designator.MostDerivedIsArrayElement && 11338 isDesignatorAtObjectEnd(Ctx, LVal); 11339 } 11340 11341 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11342 /// Fails if the conversion would cause loss of precision. 11343 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11344 CharUnits &Result) { 11345 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11346 if (Int.ugt(CharUnitsMax)) 11347 return false; 11348 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11349 return true; 11350 } 11351 11352 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11353 /// determine how many bytes exist from the beginning of the object to either 11354 /// the end of the current subobject, or the end of the object itself, depending 11355 /// on what the LValue looks like + the value of Type. 11356 /// 11357 /// If this returns false, the value of Result is undefined. 11358 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11359 unsigned Type, const LValue &LVal, 11360 CharUnits &EndOffset) { 11361 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11362 11363 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11364 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11365 return false; 11366 return HandleSizeof(Info, ExprLoc, Ty, Result); 11367 }; 11368 11369 // We want to evaluate the size of the entire object. This is a valid fallback 11370 // for when Type=1 and the designator is invalid, because we're asked for an 11371 // upper-bound. 11372 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11373 // Type=3 wants a lower bound, so we can't fall back to this. 11374 if (Type == 3 && !DetermineForCompleteObject) 11375 return false; 11376 11377 llvm::APInt APEndOffset; 11378 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11379 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11380 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11381 11382 if (LVal.InvalidBase) 11383 return false; 11384 11385 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11386 return CheckedHandleSizeof(BaseTy, EndOffset); 11387 } 11388 11389 // We want to evaluate the size of a subobject. 11390 const SubobjectDesignator &Designator = LVal.Designator; 11391 11392 // The following is a moderately common idiom in C: 11393 // 11394 // struct Foo { int a; char c[1]; }; 11395 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11396 // strcpy(&F->c[0], Bar); 11397 // 11398 // In order to not break too much legacy code, we need to support it. 11399 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11400 // If we can resolve this to an alloc_size call, we can hand that back, 11401 // because we know for certain how many bytes there are to write to. 11402 llvm::APInt APEndOffset; 11403 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11404 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11405 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11406 11407 // If we cannot determine the size of the initial allocation, then we can't 11408 // given an accurate upper-bound. However, we are still able to give 11409 // conservative lower-bounds for Type=3. 11410 if (Type == 1) 11411 return false; 11412 } 11413 11414 CharUnits BytesPerElem; 11415 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11416 return false; 11417 11418 // According to the GCC documentation, we want the size of the subobject 11419 // denoted by the pointer. But that's not quite right -- what we actually 11420 // want is the size of the immediately-enclosing array, if there is one. 11421 int64_t ElemsRemaining; 11422 if (Designator.MostDerivedIsArrayElement && 11423 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11424 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11425 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11426 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11427 } else { 11428 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11429 } 11430 11431 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11432 return true; 11433 } 11434 11435 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11436 /// returns true and stores the result in @p Size. 11437 /// 11438 /// If @p WasError is non-null, this will report whether the failure to evaluate 11439 /// is to be treated as an Error in IntExprEvaluator. 11440 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11441 EvalInfo &Info, uint64_t &Size) { 11442 // Determine the denoted object. 11443 LValue LVal; 11444 { 11445 // The operand of __builtin_object_size is never evaluated for side-effects. 11446 // If there are any, but we can determine the pointed-to object anyway, then 11447 // ignore the side-effects. 11448 SpeculativeEvaluationRAII SpeculativeEval(Info); 11449 IgnoreSideEffectsRAII Fold(Info); 11450 11451 if (E->isGLValue()) { 11452 // It's possible for us to be given GLValues if we're called via 11453 // Expr::tryEvaluateObjectSize. 11454 APValue RVal; 11455 if (!EvaluateAsRValue(Info, E, RVal)) 11456 return false; 11457 LVal.setFrom(Info.Ctx, RVal); 11458 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11459 /*InvalidBaseOK=*/true)) 11460 return false; 11461 } 11462 11463 // If we point to before the start of the object, there are no accessible 11464 // bytes. 11465 if (LVal.getLValueOffset().isNegative()) { 11466 Size = 0; 11467 return true; 11468 } 11469 11470 CharUnits EndOffset; 11471 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11472 return false; 11473 11474 // If we've fallen outside of the end offset, just pretend there's nothing to 11475 // write to/read from. 11476 if (EndOffset <= LVal.getLValueOffset()) 11477 Size = 0; 11478 else 11479 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11480 return true; 11481 } 11482 11483 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11484 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11485 return VisitBuiltinCallExpr(E, BuiltinOp); 11486 11487 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11488 } 11489 11490 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11491 APValue &Val, APSInt &Alignment) { 11492 QualType SrcTy = E->getArg(0)->getType(); 11493 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11494 return false; 11495 // Even though we are evaluating integer expressions we could get a pointer 11496 // argument for the __builtin_is_aligned() case. 11497 if (SrcTy->isPointerType()) { 11498 LValue Ptr; 11499 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11500 return false; 11501 Ptr.moveInto(Val); 11502 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11503 Info.FFDiag(E->getArg(0)); 11504 return false; 11505 } else { 11506 APSInt SrcInt; 11507 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11508 return false; 11509 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11510 "Bit widths must be the same"); 11511 Val = APValue(SrcInt); 11512 } 11513 assert(Val.hasValue()); 11514 return true; 11515 } 11516 11517 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11518 unsigned BuiltinOp) { 11519 switch (BuiltinOp) { 11520 default: 11521 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11522 11523 case Builtin::BI__builtin_dynamic_object_size: 11524 case Builtin::BI__builtin_object_size: { 11525 // The type was checked when we built the expression. 11526 unsigned Type = 11527 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11528 assert(Type <= 3 && "unexpected type"); 11529 11530 uint64_t Size; 11531 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11532 return Success(Size, E); 11533 11534 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11535 return Success((Type & 2) ? 0 : -1, E); 11536 11537 // Expression had no side effects, but we couldn't statically determine the 11538 // size of the referenced object. 11539 switch (Info.EvalMode) { 11540 case EvalInfo::EM_ConstantExpression: 11541 case EvalInfo::EM_ConstantFold: 11542 case EvalInfo::EM_IgnoreSideEffects: 11543 // Leave it to IR generation. 11544 return Error(E); 11545 case EvalInfo::EM_ConstantExpressionUnevaluated: 11546 // Reduce it to a constant now. 11547 return Success((Type & 2) ? 0 : -1, E); 11548 } 11549 11550 llvm_unreachable("unexpected EvalMode"); 11551 } 11552 11553 case Builtin::BI__builtin_os_log_format_buffer_size: { 11554 analyze_os_log::OSLogBufferLayout Layout; 11555 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11556 return Success(Layout.size().getQuantity(), E); 11557 } 11558 11559 case Builtin::BI__builtin_is_aligned: { 11560 APValue Src; 11561 APSInt Alignment; 11562 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11563 return false; 11564 if (Src.isLValue()) { 11565 // If we evaluated a pointer, check the minimum known alignment. 11566 LValue Ptr; 11567 Ptr.setFrom(Info.Ctx, Src); 11568 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11569 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11570 // We can return true if the known alignment at the computed offset is 11571 // greater than the requested alignment. 11572 assert(PtrAlign.isPowerOfTwo()); 11573 assert(Alignment.isPowerOf2()); 11574 if (PtrAlign.getQuantity() >= Alignment) 11575 return Success(1, E); 11576 // If the alignment is not known to be sufficient, some cases could still 11577 // be aligned at run time. However, if the requested alignment is less or 11578 // equal to the base alignment and the offset is not aligned, we know that 11579 // the run-time value can never be aligned. 11580 if (BaseAlignment.getQuantity() >= Alignment && 11581 PtrAlign.getQuantity() < Alignment) 11582 return Success(0, E); 11583 // Otherwise we can't infer whether the value is sufficiently aligned. 11584 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11585 // in cases where we can't fully evaluate the pointer. 11586 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11587 << Alignment; 11588 return false; 11589 } 11590 assert(Src.isInt()); 11591 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11592 } 11593 case Builtin::BI__builtin_align_up: { 11594 APValue Src; 11595 APSInt Alignment; 11596 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11597 return false; 11598 if (!Src.isInt()) 11599 return Error(E); 11600 APSInt AlignedVal = 11601 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11602 Src.getInt().isUnsigned()); 11603 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11604 return Success(AlignedVal, E); 11605 } 11606 case Builtin::BI__builtin_align_down: { 11607 APValue Src; 11608 APSInt Alignment; 11609 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11610 return false; 11611 if (!Src.isInt()) 11612 return Error(E); 11613 APSInt AlignedVal = 11614 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11615 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11616 return Success(AlignedVal, E); 11617 } 11618 11619 case Builtin::BI__builtin_bitreverse8: 11620 case Builtin::BI__builtin_bitreverse16: 11621 case Builtin::BI__builtin_bitreverse32: 11622 case Builtin::BI__builtin_bitreverse64: { 11623 APSInt Val; 11624 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11625 return false; 11626 11627 return Success(Val.reverseBits(), E); 11628 } 11629 11630 case Builtin::BI__builtin_bswap16: 11631 case Builtin::BI__builtin_bswap32: 11632 case Builtin::BI__builtin_bswap64: { 11633 APSInt Val; 11634 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11635 return false; 11636 11637 return Success(Val.byteSwap(), E); 11638 } 11639 11640 case Builtin::BI__builtin_classify_type: 11641 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11642 11643 case Builtin::BI__builtin_clrsb: 11644 case Builtin::BI__builtin_clrsbl: 11645 case Builtin::BI__builtin_clrsbll: { 11646 APSInt Val; 11647 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11648 return false; 11649 11650 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11651 } 11652 11653 case Builtin::BI__builtin_clz: 11654 case Builtin::BI__builtin_clzl: 11655 case Builtin::BI__builtin_clzll: 11656 case Builtin::BI__builtin_clzs: { 11657 APSInt Val; 11658 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11659 return false; 11660 if (!Val) 11661 return Error(E); 11662 11663 return Success(Val.countLeadingZeros(), E); 11664 } 11665 11666 case Builtin::BI__builtin_constant_p: { 11667 const Expr *Arg = E->getArg(0); 11668 if (EvaluateBuiltinConstantP(Info, Arg)) 11669 return Success(true, E); 11670 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11671 // Outside a constant context, eagerly evaluate to false in the presence 11672 // of side-effects in order to avoid -Wunsequenced false-positives in 11673 // a branch on __builtin_constant_p(expr). 11674 return Success(false, E); 11675 } 11676 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11677 return false; 11678 } 11679 11680 case Builtin::BI__builtin_is_constant_evaluated: { 11681 const auto *Callee = Info.CurrentCall->getCallee(); 11682 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11683 (Info.CallStackDepth == 1 || 11684 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11685 Callee->getIdentifier() && 11686 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11687 // FIXME: Find a better way to avoid duplicated diagnostics. 11688 if (Info.EvalStatus.Diag) 11689 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11690 : Info.CurrentCall->CallLoc, 11691 diag::warn_is_constant_evaluated_always_true_constexpr) 11692 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11693 : "std::is_constant_evaluated"); 11694 } 11695 11696 return Success(Info.InConstantContext, E); 11697 } 11698 11699 case Builtin::BI__builtin_ctz: 11700 case Builtin::BI__builtin_ctzl: 11701 case Builtin::BI__builtin_ctzll: 11702 case Builtin::BI__builtin_ctzs: { 11703 APSInt Val; 11704 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11705 return false; 11706 if (!Val) 11707 return Error(E); 11708 11709 return Success(Val.countTrailingZeros(), E); 11710 } 11711 11712 case Builtin::BI__builtin_eh_return_data_regno: { 11713 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11714 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11715 return Success(Operand, E); 11716 } 11717 11718 case Builtin::BI__builtin_expect: 11719 case Builtin::BI__builtin_expect_with_probability: 11720 return Visit(E->getArg(0)); 11721 11722 case Builtin::BI__builtin_ffs: 11723 case Builtin::BI__builtin_ffsl: 11724 case Builtin::BI__builtin_ffsll: { 11725 APSInt Val; 11726 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11727 return false; 11728 11729 unsigned N = Val.countTrailingZeros(); 11730 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11731 } 11732 11733 case Builtin::BI__builtin_fpclassify: { 11734 APFloat Val(0.0); 11735 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11736 return false; 11737 unsigned Arg; 11738 switch (Val.getCategory()) { 11739 case APFloat::fcNaN: Arg = 0; break; 11740 case APFloat::fcInfinity: Arg = 1; break; 11741 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11742 case APFloat::fcZero: Arg = 4; break; 11743 } 11744 return Visit(E->getArg(Arg)); 11745 } 11746 11747 case Builtin::BI__builtin_isinf_sign: { 11748 APFloat Val(0.0); 11749 return EvaluateFloat(E->getArg(0), Val, Info) && 11750 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11751 } 11752 11753 case Builtin::BI__builtin_isinf: { 11754 APFloat Val(0.0); 11755 return EvaluateFloat(E->getArg(0), Val, Info) && 11756 Success(Val.isInfinity() ? 1 : 0, E); 11757 } 11758 11759 case Builtin::BI__builtin_isfinite: { 11760 APFloat Val(0.0); 11761 return EvaluateFloat(E->getArg(0), Val, Info) && 11762 Success(Val.isFinite() ? 1 : 0, E); 11763 } 11764 11765 case Builtin::BI__builtin_isnan: { 11766 APFloat Val(0.0); 11767 return EvaluateFloat(E->getArg(0), Val, Info) && 11768 Success(Val.isNaN() ? 1 : 0, E); 11769 } 11770 11771 case Builtin::BI__builtin_isnormal: { 11772 APFloat Val(0.0); 11773 return EvaluateFloat(E->getArg(0), Val, Info) && 11774 Success(Val.isNormal() ? 1 : 0, E); 11775 } 11776 11777 case Builtin::BI__builtin_parity: 11778 case Builtin::BI__builtin_parityl: 11779 case Builtin::BI__builtin_parityll: { 11780 APSInt Val; 11781 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11782 return false; 11783 11784 return Success(Val.countPopulation() % 2, E); 11785 } 11786 11787 case Builtin::BI__builtin_popcount: 11788 case Builtin::BI__builtin_popcountl: 11789 case Builtin::BI__builtin_popcountll: { 11790 APSInt Val; 11791 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11792 return false; 11793 11794 return Success(Val.countPopulation(), E); 11795 } 11796 11797 case Builtin::BI__builtin_rotateleft8: 11798 case Builtin::BI__builtin_rotateleft16: 11799 case Builtin::BI__builtin_rotateleft32: 11800 case Builtin::BI__builtin_rotateleft64: 11801 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11802 case Builtin::BI_rotl16: 11803 case Builtin::BI_rotl: 11804 case Builtin::BI_lrotl: 11805 case Builtin::BI_rotl64: { 11806 APSInt Val, Amt; 11807 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11808 !EvaluateInteger(E->getArg(1), Amt, Info)) 11809 return false; 11810 11811 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11812 } 11813 11814 case Builtin::BI__builtin_rotateright8: 11815 case Builtin::BI__builtin_rotateright16: 11816 case Builtin::BI__builtin_rotateright32: 11817 case Builtin::BI__builtin_rotateright64: 11818 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11819 case Builtin::BI_rotr16: 11820 case Builtin::BI_rotr: 11821 case Builtin::BI_lrotr: 11822 case Builtin::BI_rotr64: { 11823 APSInt Val, Amt; 11824 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11825 !EvaluateInteger(E->getArg(1), Amt, Info)) 11826 return false; 11827 11828 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11829 } 11830 11831 case Builtin::BIstrlen: 11832 case Builtin::BIwcslen: 11833 // A call to strlen is not a constant expression. 11834 if (Info.getLangOpts().CPlusPlus11) 11835 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11836 << /*isConstexpr*/0 << /*isConstructor*/0 11837 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11838 else 11839 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11840 LLVM_FALLTHROUGH; 11841 case Builtin::BI__builtin_strlen: 11842 case Builtin::BI__builtin_wcslen: { 11843 // As an extension, we support __builtin_strlen() as a constant expression, 11844 // and support folding strlen() to a constant. 11845 uint64_t StrLen; 11846 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 11847 return Success(StrLen, E); 11848 return false; 11849 } 11850 11851 case Builtin::BIstrcmp: 11852 case Builtin::BIwcscmp: 11853 case Builtin::BIstrncmp: 11854 case Builtin::BIwcsncmp: 11855 case Builtin::BImemcmp: 11856 case Builtin::BIbcmp: 11857 case Builtin::BIwmemcmp: 11858 // A call to strlen is not a constant expression. 11859 if (Info.getLangOpts().CPlusPlus11) 11860 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11861 << /*isConstexpr*/0 << /*isConstructor*/0 11862 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11863 else 11864 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11865 LLVM_FALLTHROUGH; 11866 case Builtin::BI__builtin_strcmp: 11867 case Builtin::BI__builtin_wcscmp: 11868 case Builtin::BI__builtin_strncmp: 11869 case Builtin::BI__builtin_wcsncmp: 11870 case Builtin::BI__builtin_memcmp: 11871 case Builtin::BI__builtin_bcmp: 11872 case Builtin::BI__builtin_wmemcmp: { 11873 LValue String1, String2; 11874 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11875 !EvaluatePointer(E->getArg(1), String2, Info)) 11876 return false; 11877 11878 uint64_t MaxLength = uint64_t(-1); 11879 if (BuiltinOp != Builtin::BIstrcmp && 11880 BuiltinOp != Builtin::BIwcscmp && 11881 BuiltinOp != Builtin::BI__builtin_strcmp && 11882 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11883 APSInt N; 11884 if (!EvaluateInteger(E->getArg(2), N, Info)) 11885 return false; 11886 MaxLength = N.getExtValue(); 11887 } 11888 11889 // Empty substrings compare equal by definition. 11890 if (MaxLength == 0u) 11891 return Success(0, E); 11892 11893 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11894 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11895 String1.Designator.Invalid || String2.Designator.Invalid) 11896 return false; 11897 11898 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11899 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11900 11901 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11902 BuiltinOp == Builtin::BIbcmp || 11903 BuiltinOp == Builtin::BI__builtin_memcmp || 11904 BuiltinOp == Builtin::BI__builtin_bcmp; 11905 11906 assert(IsRawByte || 11907 (Info.Ctx.hasSameUnqualifiedType( 11908 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11909 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11910 11911 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11912 // 'char8_t', but no other types. 11913 if (IsRawByte && 11914 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11915 // FIXME: Consider using our bit_cast implementation to support this. 11916 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11917 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11918 << CharTy1 << CharTy2; 11919 return false; 11920 } 11921 11922 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11923 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11924 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11925 Char1.isInt() && Char2.isInt(); 11926 }; 11927 const auto &AdvanceElems = [&] { 11928 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11929 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11930 }; 11931 11932 bool StopAtNull = 11933 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11934 BuiltinOp != Builtin::BIwmemcmp && 11935 BuiltinOp != Builtin::BI__builtin_memcmp && 11936 BuiltinOp != Builtin::BI__builtin_bcmp && 11937 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11938 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11939 BuiltinOp == Builtin::BIwcsncmp || 11940 BuiltinOp == Builtin::BIwmemcmp || 11941 BuiltinOp == Builtin::BI__builtin_wcscmp || 11942 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11943 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11944 11945 for (; MaxLength; --MaxLength) { 11946 APValue Char1, Char2; 11947 if (!ReadCurElems(Char1, Char2)) 11948 return false; 11949 if (Char1.getInt().ne(Char2.getInt())) { 11950 if (IsWide) // wmemcmp compares with wchar_t signedness. 11951 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11952 // memcmp always compares unsigned chars. 11953 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11954 } 11955 if (StopAtNull && !Char1.getInt()) 11956 return Success(0, E); 11957 assert(!(StopAtNull && !Char2.getInt())); 11958 if (!AdvanceElems()) 11959 return false; 11960 } 11961 // We hit the strncmp / memcmp limit. 11962 return Success(0, E); 11963 } 11964 11965 case Builtin::BI__atomic_always_lock_free: 11966 case Builtin::BI__atomic_is_lock_free: 11967 case Builtin::BI__c11_atomic_is_lock_free: { 11968 APSInt SizeVal; 11969 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11970 return false; 11971 11972 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11973 // of two less than or equal to the maximum inline atomic width, we know it 11974 // is lock-free. If the size isn't a power of two, or greater than the 11975 // maximum alignment where we promote atomics, we know it is not lock-free 11976 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11977 // the answer can only be determined at runtime; for example, 16-byte 11978 // atomics have lock-free implementations on some, but not all, 11979 // x86-64 processors. 11980 11981 // Check power-of-two. 11982 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11983 if (Size.isPowerOfTwo()) { 11984 // Check against inlining width. 11985 unsigned InlineWidthBits = 11986 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11987 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11988 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11989 Size == CharUnits::One() || 11990 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11991 Expr::NPC_NeverValueDependent)) 11992 // OK, we will inline appropriately-aligned operations of this size, 11993 // and _Atomic(T) is appropriately-aligned. 11994 return Success(1, E); 11995 11996 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11997 castAs<PointerType>()->getPointeeType(); 11998 if (!PointeeType->isIncompleteType() && 11999 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12000 // OK, we will inline operations on this object. 12001 return Success(1, E); 12002 } 12003 } 12004 } 12005 12006 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12007 Success(0, E) : Error(E); 12008 } 12009 case Builtin::BI__builtin_add_overflow: 12010 case Builtin::BI__builtin_sub_overflow: 12011 case Builtin::BI__builtin_mul_overflow: 12012 case Builtin::BI__builtin_sadd_overflow: 12013 case Builtin::BI__builtin_uadd_overflow: 12014 case Builtin::BI__builtin_uaddl_overflow: 12015 case Builtin::BI__builtin_uaddll_overflow: 12016 case Builtin::BI__builtin_usub_overflow: 12017 case Builtin::BI__builtin_usubl_overflow: 12018 case Builtin::BI__builtin_usubll_overflow: 12019 case Builtin::BI__builtin_umul_overflow: 12020 case Builtin::BI__builtin_umull_overflow: 12021 case Builtin::BI__builtin_umulll_overflow: 12022 case Builtin::BI__builtin_saddl_overflow: 12023 case Builtin::BI__builtin_saddll_overflow: 12024 case Builtin::BI__builtin_ssub_overflow: 12025 case Builtin::BI__builtin_ssubl_overflow: 12026 case Builtin::BI__builtin_ssubll_overflow: 12027 case Builtin::BI__builtin_smul_overflow: 12028 case Builtin::BI__builtin_smull_overflow: 12029 case Builtin::BI__builtin_smulll_overflow: { 12030 LValue ResultLValue; 12031 APSInt LHS, RHS; 12032 12033 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12034 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12035 !EvaluateInteger(E->getArg(1), RHS, Info) || 12036 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12037 return false; 12038 12039 APSInt Result; 12040 bool DidOverflow = false; 12041 12042 // If the types don't have to match, enlarge all 3 to the largest of them. 12043 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12044 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12045 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12046 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12047 ResultType->isSignedIntegerOrEnumerationType(); 12048 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12049 ResultType->isSignedIntegerOrEnumerationType(); 12050 uint64_t LHSSize = LHS.getBitWidth(); 12051 uint64_t RHSSize = RHS.getBitWidth(); 12052 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12053 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12054 12055 // Add an additional bit if the signedness isn't uniformly agreed to. We 12056 // could do this ONLY if there is a signed and an unsigned that both have 12057 // MaxBits, but the code to check that is pretty nasty. The issue will be 12058 // caught in the shrink-to-result later anyway. 12059 if (IsSigned && !AllSigned) 12060 ++MaxBits; 12061 12062 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12063 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12064 Result = APSInt(MaxBits, !IsSigned); 12065 } 12066 12067 // Find largest int. 12068 switch (BuiltinOp) { 12069 default: 12070 llvm_unreachable("Invalid value for BuiltinOp"); 12071 case Builtin::BI__builtin_add_overflow: 12072 case Builtin::BI__builtin_sadd_overflow: 12073 case Builtin::BI__builtin_saddl_overflow: 12074 case Builtin::BI__builtin_saddll_overflow: 12075 case Builtin::BI__builtin_uadd_overflow: 12076 case Builtin::BI__builtin_uaddl_overflow: 12077 case Builtin::BI__builtin_uaddll_overflow: 12078 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12079 : LHS.uadd_ov(RHS, DidOverflow); 12080 break; 12081 case Builtin::BI__builtin_sub_overflow: 12082 case Builtin::BI__builtin_ssub_overflow: 12083 case Builtin::BI__builtin_ssubl_overflow: 12084 case Builtin::BI__builtin_ssubll_overflow: 12085 case Builtin::BI__builtin_usub_overflow: 12086 case Builtin::BI__builtin_usubl_overflow: 12087 case Builtin::BI__builtin_usubll_overflow: 12088 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12089 : LHS.usub_ov(RHS, DidOverflow); 12090 break; 12091 case Builtin::BI__builtin_mul_overflow: 12092 case Builtin::BI__builtin_smul_overflow: 12093 case Builtin::BI__builtin_smull_overflow: 12094 case Builtin::BI__builtin_smulll_overflow: 12095 case Builtin::BI__builtin_umul_overflow: 12096 case Builtin::BI__builtin_umull_overflow: 12097 case Builtin::BI__builtin_umulll_overflow: 12098 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12099 : LHS.umul_ov(RHS, DidOverflow); 12100 break; 12101 } 12102 12103 // In the case where multiple sizes are allowed, truncate and see if 12104 // the values are the same. 12105 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12106 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12107 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12108 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12109 // since it will give us the behavior of a TruncOrSelf in the case where 12110 // its parameter <= its size. We previously set Result to be at least the 12111 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12112 // will work exactly like TruncOrSelf. 12113 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12114 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12115 12116 if (!APSInt::isSameValue(Temp, Result)) 12117 DidOverflow = true; 12118 Result = Temp; 12119 } 12120 12121 APValue APV{Result}; 12122 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12123 return false; 12124 return Success(DidOverflow, E); 12125 } 12126 } 12127 } 12128 12129 /// Determine whether this is a pointer past the end of the complete 12130 /// object referred to by the lvalue. 12131 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12132 const LValue &LV) { 12133 // A null pointer can be viewed as being "past the end" but we don't 12134 // choose to look at it that way here. 12135 if (!LV.getLValueBase()) 12136 return false; 12137 12138 // If the designator is valid and refers to a subobject, we're not pointing 12139 // past the end. 12140 if (!LV.getLValueDesignator().Invalid && 12141 !LV.getLValueDesignator().isOnePastTheEnd()) 12142 return false; 12143 12144 // A pointer to an incomplete type might be past-the-end if the type's size is 12145 // zero. We cannot tell because the type is incomplete. 12146 QualType Ty = getType(LV.getLValueBase()); 12147 if (Ty->isIncompleteType()) 12148 return true; 12149 12150 // We're a past-the-end pointer if we point to the byte after the object, 12151 // no matter what our type or path is. 12152 auto Size = Ctx.getTypeSizeInChars(Ty); 12153 return LV.getLValueOffset() == Size; 12154 } 12155 12156 namespace { 12157 12158 /// Data recursive integer evaluator of certain binary operators. 12159 /// 12160 /// We use a data recursive algorithm for binary operators so that we are able 12161 /// to handle extreme cases of chained binary operators without causing stack 12162 /// overflow. 12163 class DataRecursiveIntBinOpEvaluator { 12164 struct EvalResult { 12165 APValue Val; 12166 bool Failed; 12167 12168 EvalResult() : Failed(false) { } 12169 12170 void swap(EvalResult &RHS) { 12171 Val.swap(RHS.Val); 12172 Failed = RHS.Failed; 12173 RHS.Failed = false; 12174 } 12175 }; 12176 12177 struct Job { 12178 const Expr *E; 12179 EvalResult LHSResult; // meaningful only for binary operator expression. 12180 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12181 12182 Job() = default; 12183 Job(Job &&) = default; 12184 12185 void startSpeculativeEval(EvalInfo &Info) { 12186 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12187 } 12188 12189 private: 12190 SpeculativeEvaluationRAII SpecEvalRAII; 12191 }; 12192 12193 SmallVector<Job, 16> Queue; 12194 12195 IntExprEvaluator &IntEval; 12196 EvalInfo &Info; 12197 APValue &FinalResult; 12198 12199 public: 12200 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12201 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12202 12203 /// True if \param E is a binary operator that we are going to handle 12204 /// data recursively. 12205 /// We handle binary operators that are comma, logical, or that have operands 12206 /// with integral or enumeration type. 12207 static bool shouldEnqueue(const BinaryOperator *E) { 12208 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12209 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12210 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12211 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12212 } 12213 12214 bool Traverse(const BinaryOperator *E) { 12215 enqueue(E); 12216 EvalResult PrevResult; 12217 while (!Queue.empty()) 12218 process(PrevResult); 12219 12220 if (PrevResult.Failed) return false; 12221 12222 FinalResult.swap(PrevResult.Val); 12223 return true; 12224 } 12225 12226 private: 12227 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12228 return IntEval.Success(Value, E, Result); 12229 } 12230 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12231 return IntEval.Success(Value, E, Result); 12232 } 12233 bool Error(const Expr *E) { 12234 return IntEval.Error(E); 12235 } 12236 bool Error(const Expr *E, diag::kind D) { 12237 return IntEval.Error(E, D); 12238 } 12239 12240 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12241 return Info.CCEDiag(E, D); 12242 } 12243 12244 // Returns true if visiting the RHS is necessary, false otherwise. 12245 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12246 bool &SuppressRHSDiags); 12247 12248 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12249 const BinaryOperator *E, APValue &Result); 12250 12251 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12252 Result.Failed = !Evaluate(Result.Val, Info, E); 12253 if (Result.Failed) 12254 Result.Val = APValue(); 12255 } 12256 12257 void process(EvalResult &Result); 12258 12259 void enqueue(const Expr *E) { 12260 E = E->IgnoreParens(); 12261 Queue.resize(Queue.size()+1); 12262 Queue.back().E = E; 12263 Queue.back().Kind = Job::AnyExprKind; 12264 } 12265 }; 12266 12267 } 12268 12269 bool DataRecursiveIntBinOpEvaluator:: 12270 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12271 bool &SuppressRHSDiags) { 12272 if (E->getOpcode() == BO_Comma) { 12273 // Ignore LHS but note if we could not evaluate it. 12274 if (LHSResult.Failed) 12275 return Info.noteSideEffect(); 12276 return true; 12277 } 12278 12279 if (E->isLogicalOp()) { 12280 bool LHSAsBool; 12281 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12282 // We were able to evaluate the LHS, see if we can get away with not 12283 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12284 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12285 Success(LHSAsBool, E, LHSResult.Val); 12286 return false; // Ignore RHS 12287 } 12288 } else { 12289 LHSResult.Failed = true; 12290 12291 // Since we weren't able to evaluate the left hand side, it 12292 // might have had side effects. 12293 if (!Info.noteSideEffect()) 12294 return false; 12295 12296 // We can't evaluate the LHS; however, sometimes the result 12297 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12298 // Don't ignore RHS and suppress diagnostics from this arm. 12299 SuppressRHSDiags = true; 12300 } 12301 12302 return true; 12303 } 12304 12305 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12306 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12307 12308 if (LHSResult.Failed && !Info.noteFailure()) 12309 return false; // Ignore RHS; 12310 12311 return true; 12312 } 12313 12314 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12315 bool IsSub) { 12316 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12317 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12318 // offsets. 12319 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12320 CharUnits &Offset = LVal.getLValueOffset(); 12321 uint64_t Offset64 = Offset.getQuantity(); 12322 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12323 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12324 : Offset64 + Index64); 12325 } 12326 12327 bool DataRecursiveIntBinOpEvaluator:: 12328 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12329 const BinaryOperator *E, APValue &Result) { 12330 if (E->getOpcode() == BO_Comma) { 12331 if (RHSResult.Failed) 12332 return false; 12333 Result = RHSResult.Val; 12334 return true; 12335 } 12336 12337 if (E->isLogicalOp()) { 12338 bool lhsResult, rhsResult; 12339 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12340 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12341 12342 if (LHSIsOK) { 12343 if (RHSIsOK) { 12344 if (E->getOpcode() == BO_LOr) 12345 return Success(lhsResult || rhsResult, E, Result); 12346 else 12347 return Success(lhsResult && rhsResult, E, Result); 12348 } 12349 } else { 12350 if (RHSIsOK) { 12351 // We can't evaluate the LHS; however, sometimes the result 12352 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12353 if (rhsResult == (E->getOpcode() == BO_LOr)) 12354 return Success(rhsResult, E, Result); 12355 } 12356 } 12357 12358 return false; 12359 } 12360 12361 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12362 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12363 12364 if (LHSResult.Failed || RHSResult.Failed) 12365 return false; 12366 12367 const APValue &LHSVal = LHSResult.Val; 12368 const APValue &RHSVal = RHSResult.Val; 12369 12370 // Handle cases like (unsigned long)&a + 4. 12371 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12372 Result = LHSVal; 12373 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12374 return true; 12375 } 12376 12377 // Handle cases like 4 + (unsigned long)&a 12378 if (E->getOpcode() == BO_Add && 12379 RHSVal.isLValue() && LHSVal.isInt()) { 12380 Result = RHSVal; 12381 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12382 return true; 12383 } 12384 12385 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12386 // Handle (intptr_t)&&A - (intptr_t)&&B. 12387 if (!LHSVal.getLValueOffset().isZero() || 12388 !RHSVal.getLValueOffset().isZero()) 12389 return false; 12390 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12391 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12392 if (!LHSExpr || !RHSExpr) 12393 return false; 12394 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12395 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12396 if (!LHSAddrExpr || !RHSAddrExpr) 12397 return false; 12398 // Make sure both labels come from the same function. 12399 if (LHSAddrExpr->getLabel()->getDeclContext() != 12400 RHSAddrExpr->getLabel()->getDeclContext()) 12401 return false; 12402 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12403 return true; 12404 } 12405 12406 // All the remaining cases expect both operands to be an integer 12407 if (!LHSVal.isInt() || !RHSVal.isInt()) 12408 return Error(E); 12409 12410 // Set up the width and signedness manually, in case it can't be deduced 12411 // from the operation we're performing. 12412 // FIXME: Don't do this in the cases where we can deduce it. 12413 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12414 E->getType()->isUnsignedIntegerOrEnumerationType()); 12415 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12416 RHSVal.getInt(), Value)) 12417 return false; 12418 return Success(Value, E, Result); 12419 } 12420 12421 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12422 Job &job = Queue.back(); 12423 12424 switch (job.Kind) { 12425 case Job::AnyExprKind: { 12426 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12427 if (shouldEnqueue(Bop)) { 12428 job.Kind = Job::BinOpKind; 12429 enqueue(Bop->getLHS()); 12430 return; 12431 } 12432 } 12433 12434 EvaluateExpr(job.E, Result); 12435 Queue.pop_back(); 12436 return; 12437 } 12438 12439 case Job::BinOpKind: { 12440 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12441 bool SuppressRHSDiags = false; 12442 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12443 Queue.pop_back(); 12444 return; 12445 } 12446 if (SuppressRHSDiags) 12447 job.startSpeculativeEval(Info); 12448 job.LHSResult.swap(Result); 12449 job.Kind = Job::BinOpVisitedLHSKind; 12450 enqueue(Bop->getRHS()); 12451 return; 12452 } 12453 12454 case Job::BinOpVisitedLHSKind: { 12455 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12456 EvalResult RHS; 12457 RHS.swap(Result); 12458 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12459 Queue.pop_back(); 12460 return; 12461 } 12462 } 12463 12464 llvm_unreachable("Invalid Job::Kind!"); 12465 } 12466 12467 namespace { 12468 enum class CmpResult { 12469 Unequal, 12470 Less, 12471 Equal, 12472 Greater, 12473 Unordered, 12474 }; 12475 } 12476 12477 template <class SuccessCB, class AfterCB> 12478 static bool 12479 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12480 SuccessCB &&Success, AfterCB &&DoAfter) { 12481 assert(!E->isValueDependent()); 12482 assert(E->isComparisonOp() && "expected comparison operator"); 12483 assert((E->getOpcode() == BO_Cmp || 12484 E->getType()->isIntegralOrEnumerationType()) && 12485 "unsupported binary expression evaluation"); 12486 auto Error = [&](const Expr *E) { 12487 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12488 return false; 12489 }; 12490 12491 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12492 bool IsEquality = E->isEqualityOp(); 12493 12494 QualType LHSTy = E->getLHS()->getType(); 12495 QualType RHSTy = E->getRHS()->getType(); 12496 12497 if (LHSTy->isIntegralOrEnumerationType() && 12498 RHSTy->isIntegralOrEnumerationType()) { 12499 APSInt LHS, RHS; 12500 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12501 if (!LHSOK && !Info.noteFailure()) 12502 return false; 12503 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12504 return false; 12505 if (LHS < RHS) 12506 return Success(CmpResult::Less, E); 12507 if (LHS > RHS) 12508 return Success(CmpResult::Greater, E); 12509 return Success(CmpResult::Equal, E); 12510 } 12511 12512 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12513 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12514 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12515 12516 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12517 if (!LHSOK && !Info.noteFailure()) 12518 return false; 12519 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12520 return false; 12521 if (LHSFX < RHSFX) 12522 return Success(CmpResult::Less, E); 12523 if (LHSFX > RHSFX) 12524 return Success(CmpResult::Greater, E); 12525 return Success(CmpResult::Equal, E); 12526 } 12527 12528 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12529 ComplexValue LHS, RHS; 12530 bool LHSOK; 12531 if (E->isAssignmentOp()) { 12532 LValue LV; 12533 EvaluateLValue(E->getLHS(), LV, Info); 12534 LHSOK = false; 12535 } else if (LHSTy->isRealFloatingType()) { 12536 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12537 if (LHSOK) { 12538 LHS.makeComplexFloat(); 12539 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12540 } 12541 } else { 12542 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12543 } 12544 if (!LHSOK && !Info.noteFailure()) 12545 return false; 12546 12547 if (E->getRHS()->getType()->isRealFloatingType()) { 12548 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12549 return false; 12550 RHS.makeComplexFloat(); 12551 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12552 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12553 return false; 12554 12555 if (LHS.isComplexFloat()) { 12556 APFloat::cmpResult CR_r = 12557 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12558 APFloat::cmpResult CR_i = 12559 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12560 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12561 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12562 } else { 12563 assert(IsEquality && "invalid complex comparison"); 12564 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12565 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12566 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12567 } 12568 } 12569 12570 if (LHSTy->isRealFloatingType() && 12571 RHSTy->isRealFloatingType()) { 12572 APFloat RHS(0.0), LHS(0.0); 12573 12574 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12575 if (!LHSOK && !Info.noteFailure()) 12576 return false; 12577 12578 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12579 return false; 12580 12581 assert(E->isComparisonOp() && "Invalid binary operator!"); 12582 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12583 if (!Info.InConstantContext && 12584 APFloatCmpResult == APFloat::cmpUnordered && 12585 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12586 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12587 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12588 return false; 12589 } 12590 auto GetCmpRes = [&]() { 12591 switch (APFloatCmpResult) { 12592 case APFloat::cmpEqual: 12593 return CmpResult::Equal; 12594 case APFloat::cmpLessThan: 12595 return CmpResult::Less; 12596 case APFloat::cmpGreaterThan: 12597 return CmpResult::Greater; 12598 case APFloat::cmpUnordered: 12599 return CmpResult::Unordered; 12600 } 12601 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12602 }; 12603 return Success(GetCmpRes(), E); 12604 } 12605 12606 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12607 LValue LHSValue, RHSValue; 12608 12609 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12610 if (!LHSOK && !Info.noteFailure()) 12611 return false; 12612 12613 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12614 return false; 12615 12616 // Reject differing bases from the normal codepath; we special-case 12617 // comparisons to null. 12618 if (!HasSameBase(LHSValue, RHSValue)) { 12619 // Inequalities and subtractions between unrelated pointers have 12620 // unspecified or undefined behavior. 12621 if (!IsEquality) { 12622 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12623 return false; 12624 } 12625 // A constant address may compare equal to the address of a symbol. 12626 // The one exception is that address of an object cannot compare equal 12627 // to a null pointer constant. 12628 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12629 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12630 return Error(E); 12631 // It's implementation-defined whether distinct literals will have 12632 // distinct addresses. In clang, the result of such a comparison is 12633 // unspecified, so it is not a constant expression. However, we do know 12634 // that the address of a literal will be non-null. 12635 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12636 LHSValue.Base && RHSValue.Base) 12637 return Error(E); 12638 // We can't tell whether weak symbols will end up pointing to the same 12639 // object. 12640 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12641 return Error(E); 12642 // We can't compare the address of the start of one object with the 12643 // past-the-end address of another object, per C++ DR1652. 12644 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12645 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12646 (RHSValue.Base && RHSValue.Offset.isZero() && 12647 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12648 return Error(E); 12649 // We can't tell whether an object is at the same address as another 12650 // zero sized object. 12651 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12652 (LHSValue.Base && isZeroSized(RHSValue))) 12653 return Error(E); 12654 return Success(CmpResult::Unequal, E); 12655 } 12656 12657 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12658 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12659 12660 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12661 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12662 12663 // C++11 [expr.rel]p3: 12664 // Pointers to void (after pointer conversions) can be compared, with a 12665 // result defined as follows: If both pointers represent the same 12666 // address or are both the null pointer value, the result is true if the 12667 // operator is <= or >= and false otherwise; otherwise the result is 12668 // unspecified. 12669 // We interpret this as applying to pointers to *cv* void. 12670 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12671 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12672 12673 // C++11 [expr.rel]p2: 12674 // - If two pointers point to non-static data members of the same object, 12675 // or to subobjects or array elements fo such members, recursively, the 12676 // pointer to the later declared member compares greater provided the 12677 // two members have the same access control and provided their class is 12678 // not a union. 12679 // [...] 12680 // - Otherwise pointer comparisons are unspecified. 12681 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12682 bool WasArrayIndex; 12683 unsigned Mismatch = FindDesignatorMismatch( 12684 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12685 // At the point where the designators diverge, the comparison has a 12686 // specified value if: 12687 // - we are comparing array indices 12688 // - we are comparing fields of a union, or fields with the same access 12689 // Otherwise, the result is unspecified and thus the comparison is not a 12690 // constant expression. 12691 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12692 Mismatch < RHSDesignator.Entries.size()) { 12693 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12694 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12695 if (!LF && !RF) 12696 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12697 else if (!LF) 12698 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12699 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12700 << RF->getParent() << RF; 12701 else if (!RF) 12702 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12703 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12704 << LF->getParent() << LF; 12705 else if (!LF->getParent()->isUnion() && 12706 LF->getAccess() != RF->getAccess()) 12707 Info.CCEDiag(E, 12708 diag::note_constexpr_pointer_comparison_differing_access) 12709 << LF << LF->getAccess() << RF << RF->getAccess() 12710 << LF->getParent(); 12711 } 12712 } 12713 12714 // The comparison here must be unsigned, and performed with the same 12715 // width as the pointer. 12716 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12717 uint64_t CompareLHS = LHSOffset.getQuantity(); 12718 uint64_t CompareRHS = RHSOffset.getQuantity(); 12719 assert(PtrSize <= 64 && "Unexpected pointer width"); 12720 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12721 CompareLHS &= Mask; 12722 CompareRHS &= Mask; 12723 12724 // If there is a base and this is a relational operator, we can only 12725 // compare pointers within the object in question; otherwise, the result 12726 // depends on where the object is located in memory. 12727 if (!LHSValue.Base.isNull() && IsRelational) { 12728 QualType BaseTy = getType(LHSValue.Base); 12729 if (BaseTy->isIncompleteType()) 12730 return Error(E); 12731 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12732 uint64_t OffsetLimit = Size.getQuantity(); 12733 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12734 return Error(E); 12735 } 12736 12737 if (CompareLHS < CompareRHS) 12738 return Success(CmpResult::Less, E); 12739 if (CompareLHS > CompareRHS) 12740 return Success(CmpResult::Greater, E); 12741 return Success(CmpResult::Equal, E); 12742 } 12743 12744 if (LHSTy->isMemberPointerType()) { 12745 assert(IsEquality && "unexpected member pointer operation"); 12746 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12747 12748 MemberPtr LHSValue, RHSValue; 12749 12750 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12751 if (!LHSOK && !Info.noteFailure()) 12752 return false; 12753 12754 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12755 return false; 12756 12757 // C++11 [expr.eq]p2: 12758 // If both operands are null, they compare equal. Otherwise if only one is 12759 // null, they compare unequal. 12760 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12761 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12762 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12763 } 12764 12765 // Otherwise if either is a pointer to a virtual member function, the 12766 // result is unspecified. 12767 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12768 if (MD->isVirtual()) 12769 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12770 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12771 if (MD->isVirtual()) 12772 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12773 12774 // Otherwise they compare equal if and only if they would refer to the 12775 // same member of the same most derived object or the same subobject if 12776 // they were dereferenced with a hypothetical object of the associated 12777 // class type. 12778 bool Equal = LHSValue == RHSValue; 12779 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12780 } 12781 12782 if (LHSTy->isNullPtrType()) { 12783 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12784 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12785 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12786 // are compared, the result is true of the operator is <=, >= or ==, and 12787 // false otherwise. 12788 return Success(CmpResult::Equal, E); 12789 } 12790 12791 return DoAfter(); 12792 } 12793 12794 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12795 if (!CheckLiteralType(Info, E)) 12796 return false; 12797 12798 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12799 ComparisonCategoryResult CCR; 12800 switch (CR) { 12801 case CmpResult::Unequal: 12802 llvm_unreachable("should never produce Unequal for three-way comparison"); 12803 case CmpResult::Less: 12804 CCR = ComparisonCategoryResult::Less; 12805 break; 12806 case CmpResult::Equal: 12807 CCR = ComparisonCategoryResult::Equal; 12808 break; 12809 case CmpResult::Greater: 12810 CCR = ComparisonCategoryResult::Greater; 12811 break; 12812 case CmpResult::Unordered: 12813 CCR = ComparisonCategoryResult::Unordered; 12814 break; 12815 } 12816 // Evaluation succeeded. Lookup the information for the comparison category 12817 // type and fetch the VarDecl for the result. 12818 const ComparisonCategoryInfo &CmpInfo = 12819 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12820 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12821 // Check and evaluate the result as a constant expression. 12822 LValue LV; 12823 LV.set(VD); 12824 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12825 return false; 12826 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12827 ConstantExprKind::Normal); 12828 }; 12829 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12830 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12831 }); 12832 } 12833 12834 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12835 // We don't support assignment in C. C++ assignments don't get here because 12836 // assignment is an lvalue in C++. 12837 if (E->isAssignmentOp()) { 12838 Error(E); 12839 if (!Info.noteFailure()) 12840 return false; 12841 } 12842 12843 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12844 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12845 12846 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12847 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12848 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12849 12850 if (E->isComparisonOp()) { 12851 // Evaluate builtin binary comparisons by evaluating them as three-way 12852 // comparisons and then translating the result. 12853 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12854 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12855 "should only produce Unequal for equality comparisons"); 12856 bool IsEqual = CR == CmpResult::Equal, 12857 IsLess = CR == CmpResult::Less, 12858 IsGreater = CR == CmpResult::Greater; 12859 auto Op = E->getOpcode(); 12860 switch (Op) { 12861 default: 12862 llvm_unreachable("unsupported binary operator"); 12863 case BO_EQ: 12864 case BO_NE: 12865 return Success(IsEqual == (Op == BO_EQ), E); 12866 case BO_LT: 12867 return Success(IsLess, E); 12868 case BO_GT: 12869 return Success(IsGreater, E); 12870 case BO_LE: 12871 return Success(IsEqual || IsLess, E); 12872 case BO_GE: 12873 return Success(IsEqual || IsGreater, E); 12874 } 12875 }; 12876 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12877 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12878 }); 12879 } 12880 12881 QualType LHSTy = E->getLHS()->getType(); 12882 QualType RHSTy = E->getRHS()->getType(); 12883 12884 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12885 E->getOpcode() == BO_Sub) { 12886 LValue LHSValue, RHSValue; 12887 12888 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12889 if (!LHSOK && !Info.noteFailure()) 12890 return false; 12891 12892 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12893 return false; 12894 12895 // Reject differing bases from the normal codepath; we special-case 12896 // comparisons to null. 12897 if (!HasSameBase(LHSValue, RHSValue)) { 12898 // Handle &&A - &&B. 12899 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12900 return Error(E); 12901 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12902 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12903 if (!LHSExpr || !RHSExpr) 12904 return Error(E); 12905 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12906 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12907 if (!LHSAddrExpr || !RHSAddrExpr) 12908 return Error(E); 12909 // Make sure both labels come from the same function. 12910 if (LHSAddrExpr->getLabel()->getDeclContext() != 12911 RHSAddrExpr->getLabel()->getDeclContext()) 12912 return Error(E); 12913 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12914 } 12915 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12916 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12917 12918 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12919 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12920 12921 // C++11 [expr.add]p6: 12922 // Unless both pointers point to elements of the same array object, or 12923 // one past the last element of the array object, the behavior is 12924 // undefined. 12925 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12926 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12927 RHSDesignator)) 12928 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12929 12930 QualType Type = E->getLHS()->getType(); 12931 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12932 12933 CharUnits ElementSize; 12934 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12935 return false; 12936 12937 // As an extension, a type may have zero size (empty struct or union in 12938 // C, array of zero length). Pointer subtraction in such cases has 12939 // undefined behavior, so is not constant. 12940 if (ElementSize.isZero()) { 12941 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12942 << ElementType; 12943 return false; 12944 } 12945 12946 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12947 // and produce incorrect results when it overflows. Such behavior 12948 // appears to be non-conforming, but is common, so perhaps we should 12949 // assume the standard intended for such cases to be undefined behavior 12950 // and check for them. 12951 12952 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12953 // overflow in the final conversion to ptrdiff_t. 12954 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12955 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12956 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12957 false); 12958 APSInt TrueResult = (LHS - RHS) / ElemSize; 12959 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12960 12961 if (Result.extend(65) != TrueResult && 12962 !HandleOverflow(Info, E, TrueResult, E->getType())) 12963 return false; 12964 return Success(Result, E); 12965 } 12966 12967 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12968 } 12969 12970 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12971 /// a result as the expression's type. 12972 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12973 const UnaryExprOrTypeTraitExpr *E) { 12974 switch(E->getKind()) { 12975 case UETT_PreferredAlignOf: 12976 case UETT_AlignOf: { 12977 if (E->isArgumentType()) 12978 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12979 E); 12980 else 12981 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12982 E); 12983 } 12984 12985 case UETT_VecStep: { 12986 QualType Ty = E->getTypeOfArgument(); 12987 12988 if (Ty->isVectorType()) { 12989 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12990 12991 // The vec_step built-in functions that take a 3-component 12992 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12993 if (n == 3) 12994 n = 4; 12995 12996 return Success(n, E); 12997 } else 12998 return Success(1, E); 12999 } 13000 13001 case UETT_SizeOf: { 13002 QualType SrcTy = E->getTypeOfArgument(); 13003 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13004 // the result is the size of the referenced type." 13005 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13006 SrcTy = Ref->getPointeeType(); 13007 13008 CharUnits Sizeof; 13009 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13010 return false; 13011 return Success(Sizeof, E); 13012 } 13013 case UETT_OpenMPRequiredSimdAlign: 13014 assert(E->isArgumentType()); 13015 return Success( 13016 Info.Ctx.toCharUnitsFromBits( 13017 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13018 .getQuantity(), 13019 E); 13020 } 13021 13022 llvm_unreachable("unknown expr/type trait"); 13023 } 13024 13025 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13026 CharUnits Result; 13027 unsigned n = OOE->getNumComponents(); 13028 if (n == 0) 13029 return Error(OOE); 13030 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13031 for (unsigned i = 0; i != n; ++i) { 13032 OffsetOfNode ON = OOE->getComponent(i); 13033 switch (ON.getKind()) { 13034 case OffsetOfNode::Array: { 13035 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13036 APSInt IdxResult; 13037 if (!EvaluateInteger(Idx, IdxResult, Info)) 13038 return false; 13039 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13040 if (!AT) 13041 return Error(OOE); 13042 CurrentType = AT->getElementType(); 13043 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13044 Result += IdxResult.getSExtValue() * ElementSize; 13045 break; 13046 } 13047 13048 case OffsetOfNode::Field: { 13049 FieldDecl *MemberDecl = ON.getField(); 13050 const RecordType *RT = CurrentType->getAs<RecordType>(); 13051 if (!RT) 13052 return Error(OOE); 13053 RecordDecl *RD = RT->getDecl(); 13054 if (RD->isInvalidDecl()) return false; 13055 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13056 unsigned i = MemberDecl->getFieldIndex(); 13057 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13058 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13059 CurrentType = MemberDecl->getType().getNonReferenceType(); 13060 break; 13061 } 13062 13063 case OffsetOfNode::Identifier: 13064 llvm_unreachable("dependent __builtin_offsetof"); 13065 13066 case OffsetOfNode::Base: { 13067 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13068 if (BaseSpec->isVirtual()) 13069 return Error(OOE); 13070 13071 // Find the layout of the class whose base we are looking into. 13072 const RecordType *RT = CurrentType->getAs<RecordType>(); 13073 if (!RT) 13074 return Error(OOE); 13075 RecordDecl *RD = RT->getDecl(); 13076 if (RD->isInvalidDecl()) return false; 13077 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13078 13079 // Find the base class itself. 13080 CurrentType = BaseSpec->getType(); 13081 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13082 if (!BaseRT) 13083 return Error(OOE); 13084 13085 // Add the offset to the base. 13086 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13087 break; 13088 } 13089 } 13090 } 13091 return Success(Result, OOE); 13092 } 13093 13094 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13095 switch (E->getOpcode()) { 13096 default: 13097 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13098 // See C99 6.6p3. 13099 return Error(E); 13100 case UO_Extension: 13101 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13102 // If so, we could clear the diagnostic ID. 13103 return Visit(E->getSubExpr()); 13104 case UO_Plus: 13105 // The result is just the value. 13106 return Visit(E->getSubExpr()); 13107 case UO_Minus: { 13108 if (!Visit(E->getSubExpr())) 13109 return false; 13110 if (!Result.isInt()) return Error(E); 13111 const APSInt &Value = Result.getInt(); 13112 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13113 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13114 E->getType())) 13115 return false; 13116 return Success(-Value, E); 13117 } 13118 case UO_Not: { 13119 if (!Visit(E->getSubExpr())) 13120 return false; 13121 if (!Result.isInt()) return Error(E); 13122 return Success(~Result.getInt(), E); 13123 } 13124 case UO_LNot: { 13125 bool bres; 13126 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13127 return false; 13128 return Success(!bres, E); 13129 } 13130 } 13131 } 13132 13133 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13134 /// result type is integer. 13135 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13136 const Expr *SubExpr = E->getSubExpr(); 13137 QualType DestType = E->getType(); 13138 QualType SrcType = SubExpr->getType(); 13139 13140 switch (E->getCastKind()) { 13141 case CK_BaseToDerived: 13142 case CK_DerivedToBase: 13143 case CK_UncheckedDerivedToBase: 13144 case CK_Dynamic: 13145 case CK_ToUnion: 13146 case CK_ArrayToPointerDecay: 13147 case CK_FunctionToPointerDecay: 13148 case CK_NullToPointer: 13149 case CK_NullToMemberPointer: 13150 case CK_BaseToDerivedMemberPointer: 13151 case CK_DerivedToBaseMemberPointer: 13152 case CK_ReinterpretMemberPointer: 13153 case CK_ConstructorConversion: 13154 case CK_IntegralToPointer: 13155 case CK_ToVoid: 13156 case CK_VectorSplat: 13157 case CK_IntegralToFloating: 13158 case CK_FloatingCast: 13159 case CK_CPointerToObjCPointerCast: 13160 case CK_BlockPointerToObjCPointerCast: 13161 case CK_AnyPointerToBlockPointerCast: 13162 case CK_ObjCObjectLValueCast: 13163 case CK_FloatingRealToComplex: 13164 case CK_FloatingComplexToReal: 13165 case CK_FloatingComplexCast: 13166 case CK_FloatingComplexToIntegralComplex: 13167 case CK_IntegralRealToComplex: 13168 case CK_IntegralComplexCast: 13169 case CK_IntegralComplexToFloatingComplex: 13170 case CK_BuiltinFnToFnPtr: 13171 case CK_ZeroToOCLOpaqueType: 13172 case CK_NonAtomicToAtomic: 13173 case CK_AddressSpaceConversion: 13174 case CK_IntToOCLSampler: 13175 case CK_FloatingToFixedPoint: 13176 case CK_FixedPointToFloating: 13177 case CK_FixedPointCast: 13178 case CK_IntegralToFixedPoint: 13179 case CK_MatrixCast: 13180 llvm_unreachable("invalid cast kind for integral value"); 13181 13182 case CK_BitCast: 13183 case CK_Dependent: 13184 case CK_LValueBitCast: 13185 case CK_ARCProduceObject: 13186 case CK_ARCConsumeObject: 13187 case CK_ARCReclaimReturnedObject: 13188 case CK_ARCExtendBlockObject: 13189 case CK_CopyAndAutoreleaseBlockObject: 13190 return Error(E); 13191 13192 case CK_UserDefinedConversion: 13193 case CK_LValueToRValue: 13194 case CK_AtomicToNonAtomic: 13195 case CK_NoOp: 13196 case CK_LValueToRValueBitCast: 13197 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13198 13199 case CK_MemberPointerToBoolean: 13200 case CK_PointerToBoolean: 13201 case CK_IntegralToBoolean: 13202 case CK_FloatingToBoolean: 13203 case CK_BooleanToSignedIntegral: 13204 case CK_FloatingComplexToBoolean: 13205 case CK_IntegralComplexToBoolean: { 13206 bool BoolResult; 13207 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13208 return false; 13209 uint64_t IntResult = BoolResult; 13210 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13211 IntResult = (uint64_t)-1; 13212 return Success(IntResult, E); 13213 } 13214 13215 case CK_FixedPointToIntegral: { 13216 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13217 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13218 return false; 13219 bool Overflowed; 13220 llvm::APSInt Result = Src.convertToInt( 13221 Info.Ctx.getIntWidth(DestType), 13222 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13223 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13224 return false; 13225 return Success(Result, E); 13226 } 13227 13228 case CK_FixedPointToBoolean: { 13229 // Unsigned padding does not affect this. 13230 APValue Val; 13231 if (!Evaluate(Val, Info, SubExpr)) 13232 return false; 13233 return Success(Val.getFixedPoint().getBoolValue(), E); 13234 } 13235 13236 case CK_IntegralCast: { 13237 if (!Visit(SubExpr)) 13238 return false; 13239 13240 if (!Result.isInt()) { 13241 // Allow casts of address-of-label differences if they are no-ops 13242 // or narrowing. (The narrowing case isn't actually guaranteed to 13243 // be constant-evaluatable except in some narrow cases which are hard 13244 // to detect here. We let it through on the assumption the user knows 13245 // what they are doing.) 13246 if (Result.isAddrLabelDiff()) 13247 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13248 // Only allow casts of lvalues if they are lossless. 13249 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13250 } 13251 13252 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13253 Result.getInt()), E); 13254 } 13255 13256 case CK_PointerToIntegral: { 13257 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13258 13259 LValue LV; 13260 if (!EvaluatePointer(SubExpr, LV, Info)) 13261 return false; 13262 13263 if (LV.getLValueBase()) { 13264 // Only allow based lvalue casts if they are lossless. 13265 // FIXME: Allow a larger integer size than the pointer size, and allow 13266 // narrowing back down to pointer width in subsequent integral casts. 13267 // FIXME: Check integer type's active bits, not its type size. 13268 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13269 return Error(E); 13270 13271 LV.Designator.setInvalid(); 13272 LV.moveInto(Result); 13273 return true; 13274 } 13275 13276 APSInt AsInt; 13277 APValue V; 13278 LV.moveInto(V); 13279 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13280 llvm_unreachable("Can't cast this!"); 13281 13282 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13283 } 13284 13285 case CK_IntegralComplexToReal: { 13286 ComplexValue C; 13287 if (!EvaluateComplex(SubExpr, C, Info)) 13288 return false; 13289 return Success(C.getComplexIntReal(), E); 13290 } 13291 13292 case CK_FloatingToIntegral: { 13293 APFloat F(0.0); 13294 if (!EvaluateFloat(SubExpr, F, Info)) 13295 return false; 13296 13297 APSInt Value; 13298 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13299 return false; 13300 return Success(Value, E); 13301 } 13302 } 13303 13304 llvm_unreachable("unknown cast resulting in integral value"); 13305 } 13306 13307 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13308 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13309 ComplexValue LV; 13310 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13311 return false; 13312 if (!LV.isComplexInt()) 13313 return Error(E); 13314 return Success(LV.getComplexIntReal(), E); 13315 } 13316 13317 return Visit(E->getSubExpr()); 13318 } 13319 13320 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13321 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13322 ComplexValue LV; 13323 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13324 return false; 13325 if (!LV.isComplexInt()) 13326 return Error(E); 13327 return Success(LV.getComplexIntImag(), E); 13328 } 13329 13330 VisitIgnoredValue(E->getSubExpr()); 13331 return Success(0, E); 13332 } 13333 13334 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13335 return Success(E->getPackLength(), E); 13336 } 13337 13338 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13339 return Success(E->getValue(), E); 13340 } 13341 13342 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13343 const ConceptSpecializationExpr *E) { 13344 return Success(E->isSatisfied(), E); 13345 } 13346 13347 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13348 return Success(E->isSatisfied(), E); 13349 } 13350 13351 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13352 switch (E->getOpcode()) { 13353 default: 13354 // Invalid unary operators 13355 return Error(E); 13356 case UO_Plus: 13357 // The result is just the value. 13358 return Visit(E->getSubExpr()); 13359 case UO_Minus: { 13360 if (!Visit(E->getSubExpr())) return false; 13361 if (!Result.isFixedPoint()) 13362 return Error(E); 13363 bool Overflowed; 13364 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13365 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13366 return false; 13367 return Success(Negated, E); 13368 } 13369 case UO_LNot: { 13370 bool bres; 13371 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13372 return false; 13373 return Success(!bres, E); 13374 } 13375 } 13376 } 13377 13378 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13379 const Expr *SubExpr = E->getSubExpr(); 13380 QualType DestType = E->getType(); 13381 assert(DestType->isFixedPointType() && 13382 "Expected destination type to be a fixed point type"); 13383 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13384 13385 switch (E->getCastKind()) { 13386 case CK_FixedPointCast: { 13387 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13388 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13389 return false; 13390 bool Overflowed; 13391 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13392 if (Overflowed) { 13393 if (Info.checkingForUndefinedBehavior()) 13394 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13395 diag::warn_fixedpoint_constant_overflow) 13396 << Result.toString() << E->getType(); 13397 if (!HandleOverflow(Info, E, Result, E->getType())) 13398 return false; 13399 } 13400 return Success(Result, E); 13401 } 13402 case CK_IntegralToFixedPoint: { 13403 APSInt Src; 13404 if (!EvaluateInteger(SubExpr, Src, Info)) 13405 return false; 13406 13407 bool Overflowed; 13408 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13409 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13410 13411 if (Overflowed) { 13412 if (Info.checkingForUndefinedBehavior()) 13413 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13414 diag::warn_fixedpoint_constant_overflow) 13415 << IntResult.toString() << E->getType(); 13416 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13417 return false; 13418 } 13419 13420 return Success(IntResult, E); 13421 } 13422 case CK_FloatingToFixedPoint: { 13423 APFloat Src(0.0); 13424 if (!EvaluateFloat(SubExpr, Src, Info)) 13425 return false; 13426 13427 bool Overflowed; 13428 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13429 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13430 13431 if (Overflowed) { 13432 if (Info.checkingForUndefinedBehavior()) 13433 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13434 diag::warn_fixedpoint_constant_overflow) 13435 << Result.toString() << E->getType(); 13436 if (!HandleOverflow(Info, E, Result, E->getType())) 13437 return false; 13438 } 13439 13440 return Success(Result, E); 13441 } 13442 case CK_NoOp: 13443 case CK_LValueToRValue: 13444 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13445 default: 13446 return Error(E); 13447 } 13448 } 13449 13450 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13451 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13452 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13453 13454 const Expr *LHS = E->getLHS(); 13455 const Expr *RHS = E->getRHS(); 13456 FixedPointSemantics ResultFXSema = 13457 Info.Ctx.getFixedPointSemantics(E->getType()); 13458 13459 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13460 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13461 return false; 13462 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13463 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13464 return false; 13465 13466 bool OpOverflow = false, ConversionOverflow = false; 13467 APFixedPoint Result(LHSFX.getSemantics()); 13468 switch (E->getOpcode()) { 13469 case BO_Add: { 13470 Result = LHSFX.add(RHSFX, &OpOverflow) 13471 .convert(ResultFXSema, &ConversionOverflow); 13472 break; 13473 } 13474 case BO_Sub: { 13475 Result = LHSFX.sub(RHSFX, &OpOverflow) 13476 .convert(ResultFXSema, &ConversionOverflow); 13477 break; 13478 } 13479 case BO_Mul: { 13480 Result = LHSFX.mul(RHSFX, &OpOverflow) 13481 .convert(ResultFXSema, &ConversionOverflow); 13482 break; 13483 } 13484 case BO_Div: { 13485 if (RHSFX.getValue() == 0) { 13486 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13487 return false; 13488 } 13489 Result = LHSFX.div(RHSFX, &OpOverflow) 13490 .convert(ResultFXSema, &ConversionOverflow); 13491 break; 13492 } 13493 case BO_Shl: 13494 case BO_Shr: { 13495 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13496 llvm::APSInt RHSVal = RHSFX.getValue(); 13497 13498 unsigned ShiftBW = 13499 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13500 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13501 // Embedded-C 4.1.6.2.2: 13502 // The right operand must be nonnegative and less than the total number 13503 // of (nonpadding) bits of the fixed-point operand ... 13504 if (RHSVal.isNegative()) 13505 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13506 else if (Amt != RHSVal) 13507 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13508 << RHSVal << E->getType() << ShiftBW; 13509 13510 if (E->getOpcode() == BO_Shl) 13511 Result = LHSFX.shl(Amt, &OpOverflow); 13512 else 13513 Result = LHSFX.shr(Amt, &OpOverflow); 13514 break; 13515 } 13516 default: 13517 return false; 13518 } 13519 if (OpOverflow || ConversionOverflow) { 13520 if (Info.checkingForUndefinedBehavior()) 13521 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13522 diag::warn_fixedpoint_constant_overflow) 13523 << Result.toString() << E->getType(); 13524 if (!HandleOverflow(Info, E, Result, E->getType())) 13525 return false; 13526 } 13527 return Success(Result, E); 13528 } 13529 13530 //===----------------------------------------------------------------------===// 13531 // Float Evaluation 13532 //===----------------------------------------------------------------------===// 13533 13534 namespace { 13535 class FloatExprEvaluator 13536 : public ExprEvaluatorBase<FloatExprEvaluator> { 13537 APFloat &Result; 13538 public: 13539 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13540 : ExprEvaluatorBaseTy(info), Result(result) {} 13541 13542 bool Success(const APValue &V, const Expr *e) { 13543 Result = V.getFloat(); 13544 return true; 13545 } 13546 13547 bool ZeroInitialization(const Expr *E) { 13548 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13549 return true; 13550 } 13551 13552 bool VisitCallExpr(const CallExpr *E); 13553 13554 bool VisitUnaryOperator(const UnaryOperator *E); 13555 bool VisitBinaryOperator(const BinaryOperator *E); 13556 bool VisitFloatingLiteral(const FloatingLiteral *E); 13557 bool VisitCastExpr(const CastExpr *E); 13558 13559 bool VisitUnaryReal(const UnaryOperator *E); 13560 bool VisitUnaryImag(const UnaryOperator *E); 13561 13562 // FIXME: Missing: array subscript of vector, member of vector 13563 }; 13564 } // end anonymous namespace 13565 13566 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13567 assert(!E->isValueDependent()); 13568 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 13569 return FloatExprEvaluator(Info, Result).Visit(E); 13570 } 13571 13572 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13573 QualType ResultTy, 13574 const Expr *Arg, 13575 bool SNaN, 13576 llvm::APFloat &Result) { 13577 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13578 if (!S) return false; 13579 13580 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13581 13582 llvm::APInt fill; 13583 13584 // Treat empty strings as if they were zero. 13585 if (S->getString().empty()) 13586 fill = llvm::APInt(32, 0); 13587 else if (S->getString().getAsInteger(0, fill)) 13588 return false; 13589 13590 if (Context.getTargetInfo().isNan2008()) { 13591 if (SNaN) 13592 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13593 else 13594 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13595 } else { 13596 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13597 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13598 // a different encoding to what became a standard in 2008, and for pre- 13599 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13600 // sNaN. This is now known as "legacy NaN" encoding. 13601 if (SNaN) 13602 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13603 else 13604 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13605 } 13606 13607 return true; 13608 } 13609 13610 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13611 switch (E->getBuiltinCallee()) { 13612 default: 13613 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13614 13615 case Builtin::BI__builtin_huge_val: 13616 case Builtin::BI__builtin_huge_valf: 13617 case Builtin::BI__builtin_huge_vall: 13618 case Builtin::BI__builtin_huge_valf128: 13619 case Builtin::BI__builtin_inf: 13620 case Builtin::BI__builtin_inff: 13621 case Builtin::BI__builtin_infl: 13622 case Builtin::BI__builtin_inff128: { 13623 const llvm::fltSemantics &Sem = 13624 Info.Ctx.getFloatTypeSemantics(E->getType()); 13625 Result = llvm::APFloat::getInf(Sem); 13626 return true; 13627 } 13628 13629 case Builtin::BI__builtin_nans: 13630 case Builtin::BI__builtin_nansf: 13631 case Builtin::BI__builtin_nansl: 13632 case Builtin::BI__builtin_nansf128: 13633 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13634 true, Result)) 13635 return Error(E); 13636 return true; 13637 13638 case Builtin::BI__builtin_nan: 13639 case Builtin::BI__builtin_nanf: 13640 case Builtin::BI__builtin_nanl: 13641 case Builtin::BI__builtin_nanf128: 13642 // If this is __builtin_nan() turn this into a nan, otherwise we 13643 // can't constant fold it. 13644 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13645 false, Result)) 13646 return Error(E); 13647 return true; 13648 13649 case Builtin::BI__builtin_fabs: 13650 case Builtin::BI__builtin_fabsf: 13651 case Builtin::BI__builtin_fabsl: 13652 case Builtin::BI__builtin_fabsf128: 13653 // The C standard says "fabs raises no floating-point exceptions, 13654 // even if x is a signaling NaN. The returned value is independent of 13655 // the current rounding direction mode." Therefore constant folding can 13656 // proceed without regard to the floating point settings. 13657 // Reference, WG14 N2478 F.10.4.3 13658 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13659 return false; 13660 13661 if (Result.isNegative()) 13662 Result.changeSign(); 13663 return true; 13664 13665 case Builtin::BI__arithmetic_fence: 13666 return EvaluateFloat(E->getArg(0), Result, Info); 13667 13668 // FIXME: Builtin::BI__builtin_powi 13669 // FIXME: Builtin::BI__builtin_powif 13670 // FIXME: Builtin::BI__builtin_powil 13671 13672 case Builtin::BI__builtin_copysign: 13673 case Builtin::BI__builtin_copysignf: 13674 case Builtin::BI__builtin_copysignl: 13675 case Builtin::BI__builtin_copysignf128: { 13676 APFloat RHS(0.); 13677 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13678 !EvaluateFloat(E->getArg(1), RHS, Info)) 13679 return false; 13680 Result.copySign(RHS); 13681 return true; 13682 } 13683 } 13684 } 13685 13686 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13687 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13688 ComplexValue CV; 13689 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13690 return false; 13691 Result = CV.FloatReal; 13692 return true; 13693 } 13694 13695 return Visit(E->getSubExpr()); 13696 } 13697 13698 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13699 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13700 ComplexValue CV; 13701 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13702 return false; 13703 Result = CV.FloatImag; 13704 return true; 13705 } 13706 13707 VisitIgnoredValue(E->getSubExpr()); 13708 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13709 Result = llvm::APFloat::getZero(Sem); 13710 return true; 13711 } 13712 13713 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13714 switch (E->getOpcode()) { 13715 default: return Error(E); 13716 case UO_Plus: 13717 return EvaluateFloat(E->getSubExpr(), Result, Info); 13718 case UO_Minus: 13719 // In C standard, WG14 N2478 F.3 p4 13720 // "the unary - raises no floating point exceptions, 13721 // even if the operand is signalling." 13722 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13723 return false; 13724 Result.changeSign(); 13725 return true; 13726 } 13727 } 13728 13729 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13730 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13731 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13732 13733 APFloat RHS(0.0); 13734 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13735 if (!LHSOK && !Info.noteFailure()) 13736 return false; 13737 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13738 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13739 } 13740 13741 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13742 Result = E->getValue(); 13743 return true; 13744 } 13745 13746 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13747 const Expr* SubExpr = E->getSubExpr(); 13748 13749 switch (E->getCastKind()) { 13750 default: 13751 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13752 13753 case CK_IntegralToFloating: { 13754 APSInt IntResult; 13755 const FPOptions FPO = E->getFPFeaturesInEffect( 13756 Info.Ctx.getLangOpts()); 13757 return EvaluateInteger(SubExpr, IntResult, Info) && 13758 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13759 IntResult, E->getType(), Result); 13760 } 13761 13762 case CK_FixedPointToFloating: { 13763 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13764 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13765 return false; 13766 Result = 13767 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13768 return true; 13769 } 13770 13771 case CK_FloatingCast: { 13772 if (!Visit(SubExpr)) 13773 return false; 13774 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13775 Result); 13776 } 13777 13778 case CK_FloatingComplexToReal: { 13779 ComplexValue V; 13780 if (!EvaluateComplex(SubExpr, V, Info)) 13781 return false; 13782 Result = V.getComplexFloatReal(); 13783 return true; 13784 } 13785 } 13786 } 13787 13788 //===----------------------------------------------------------------------===// 13789 // Complex Evaluation (for float and integer) 13790 //===----------------------------------------------------------------------===// 13791 13792 namespace { 13793 class ComplexExprEvaluator 13794 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13795 ComplexValue &Result; 13796 13797 public: 13798 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13799 : ExprEvaluatorBaseTy(info), Result(Result) {} 13800 13801 bool Success(const APValue &V, const Expr *e) { 13802 Result.setFrom(V); 13803 return true; 13804 } 13805 13806 bool ZeroInitialization(const Expr *E); 13807 13808 //===--------------------------------------------------------------------===// 13809 // Visitor Methods 13810 //===--------------------------------------------------------------------===// 13811 13812 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13813 bool VisitCastExpr(const CastExpr *E); 13814 bool VisitBinaryOperator(const BinaryOperator *E); 13815 bool VisitUnaryOperator(const UnaryOperator *E); 13816 bool VisitInitListExpr(const InitListExpr *E); 13817 bool VisitCallExpr(const CallExpr *E); 13818 }; 13819 } // end anonymous namespace 13820 13821 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13822 EvalInfo &Info) { 13823 assert(!E->isValueDependent()); 13824 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 13825 return ComplexExprEvaluator(Info, Result).Visit(E); 13826 } 13827 13828 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13829 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13830 if (ElemTy->isRealFloatingType()) { 13831 Result.makeComplexFloat(); 13832 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13833 Result.FloatReal = Zero; 13834 Result.FloatImag = Zero; 13835 } else { 13836 Result.makeComplexInt(); 13837 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13838 Result.IntReal = Zero; 13839 Result.IntImag = Zero; 13840 } 13841 return true; 13842 } 13843 13844 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13845 const Expr* SubExpr = E->getSubExpr(); 13846 13847 if (SubExpr->getType()->isRealFloatingType()) { 13848 Result.makeComplexFloat(); 13849 APFloat &Imag = Result.FloatImag; 13850 if (!EvaluateFloat(SubExpr, Imag, Info)) 13851 return false; 13852 13853 Result.FloatReal = APFloat(Imag.getSemantics()); 13854 return true; 13855 } else { 13856 assert(SubExpr->getType()->isIntegerType() && 13857 "Unexpected imaginary literal."); 13858 13859 Result.makeComplexInt(); 13860 APSInt &Imag = Result.IntImag; 13861 if (!EvaluateInteger(SubExpr, Imag, Info)) 13862 return false; 13863 13864 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13865 return true; 13866 } 13867 } 13868 13869 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13870 13871 switch (E->getCastKind()) { 13872 case CK_BitCast: 13873 case CK_BaseToDerived: 13874 case CK_DerivedToBase: 13875 case CK_UncheckedDerivedToBase: 13876 case CK_Dynamic: 13877 case CK_ToUnion: 13878 case CK_ArrayToPointerDecay: 13879 case CK_FunctionToPointerDecay: 13880 case CK_NullToPointer: 13881 case CK_NullToMemberPointer: 13882 case CK_BaseToDerivedMemberPointer: 13883 case CK_DerivedToBaseMemberPointer: 13884 case CK_MemberPointerToBoolean: 13885 case CK_ReinterpretMemberPointer: 13886 case CK_ConstructorConversion: 13887 case CK_IntegralToPointer: 13888 case CK_PointerToIntegral: 13889 case CK_PointerToBoolean: 13890 case CK_ToVoid: 13891 case CK_VectorSplat: 13892 case CK_IntegralCast: 13893 case CK_BooleanToSignedIntegral: 13894 case CK_IntegralToBoolean: 13895 case CK_IntegralToFloating: 13896 case CK_FloatingToIntegral: 13897 case CK_FloatingToBoolean: 13898 case CK_FloatingCast: 13899 case CK_CPointerToObjCPointerCast: 13900 case CK_BlockPointerToObjCPointerCast: 13901 case CK_AnyPointerToBlockPointerCast: 13902 case CK_ObjCObjectLValueCast: 13903 case CK_FloatingComplexToReal: 13904 case CK_FloatingComplexToBoolean: 13905 case CK_IntegralComplexToReal: 13906 case CK_IntegralComplexToBoolean: 13907 case CK_ARCProduceObject: 13908 case CK_ARCConsumeObject: 13909 case CK_ARCReclaimReturnedObject: 13910 case CK_ARCExtendBlockObject: 13911 case CK_CopyAndAutoreleaseBlockObject: 13912 case CK_BuiltinFnToFnPtr: 13913 case CK_ZeroToOCLOpaqueType: 13914 case CK_NonAtomicToAtomic: 13915 case CK_AddressSpaceConversion: 13916 case CK_IntToOCLSampler: 13917 case CK_FloatingToFixedPoint: 13918 case CK_FixedPointToFloating: 13919 case CK_FixedPointCast: 13920 case CK_FixedPointToBoolean: 13921 case CK_FixedPointToIntegral: 13922 case CK_IntegralToFixedPoint: 13923 case CK_MatrixCast: 13924 llvm_unreachable("invalid cast kind for complex value"); 13925 13926 case CK_LValueToRValue: 13927 case CK_AtomicToNonAtomic: 13928 case CK_NoOp: 13929 case CK_LValueToRValueBitCast: 13930 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13931 13932 case CK_Dependent: 13933 case CK_LValueBitCast: 13934 case CK_UserDefinedConversion: 13935 return Error(E); 13936 13937 case CK_FloatingRealToComplex: { 13938 APFloat &Real = Result.FloatReal; 13939 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13940 return false; 13941 13942 Result.makeComplexFloat(); 13943 Result.FloatImag = APFloat(Real.getSemantics()); 13944 return true; 13945 } 13946 13947 case CK_FloatingComplexCast: { 13948 if (!Visit(E->getSubExpr())) 13949 return false; 13950 13951 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13952 QualType From 13953 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13954 13955 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13956 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13957 } 13958 13959 case CK_FloatingComplexToIntegralComplex: { 13960 if (!Visit(E->getSubExpr())) 13961 return false; 13962 13963 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13964 QualType From 13965 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13966 Result.makeComplexInt(); 13967 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13968 To, Result.IntReal) && 13969 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13970 To, Result.IntImag); 13971 } 13972 13973 case CK_IntegralRealToComplex: { 13974 APSInt &Real = Result.IntReal; 13975 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13976 return false; 13977 13978 Result.makeComplexInt(); 13979 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13980 return true; 13981 } 13982 13983 case CK_IntegralComplexCast: { 13984 if (!Visit(E->getSubExpr())) 13985 return false; 13986 13987 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13988 QualType From 13989 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13990 13991 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13992 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13993 return true; 13994 } 13995 13996 case CK_IntegralComplexToFloatingComplex: { 13997 if (!Visit(E->getSubExpr())) 13998 return false; 13999 14000 const FPOptions FPO = E->getFPFeaturesInEffect( 14001 Info.Ctx.getLangOpts()); 14002 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14003 QualType From 14004 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14005 Result.makeComplexFloat(); 14006 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14007 To, Result.FloatReal) && 14008 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14009 To, Result.FloatImag); 14010 } 14011 } 14012 14013 llvm_unreachable("unknown cast resulting in complex value"); 14014 } 14015 14016 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14017 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14018 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14019 14020 // Track whether the LHS or RHS is real at the type system level. When this is 14021 // the case we can simplify our evaluation strategy. 14022 bool LHSReal = false, RHSReal = false; 14023 14024 bool LHSOK; 14025 if (E->getLHS()->getType()->isRealFloatingType()) { 14026 LHSReal = true; 14027 APFloat &Real = Result.FloatReal; 14028 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14029 if (LHSOK) { 14030 Result.makeComplexFloat(); 14031 Result.FloatImag = APFloat(Real.getSemantics()); 14032 } 14033 } else { 14034 LHSOK = Visit(E->getLHS()); 14035 } 14036 if (!LHSOK && !Info.noteFailure()) 14037 return false; 14038 14039 ComplexValue RHS; 14040 if (E->getRHS()->getType()->isRealFloatingType()) { 14041 RHSReal = true; 14042 APFloat &Real = RHS.FloatReal; 14043 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14044 return false; 14045 RHS.makeComplexFloat(); 14046 RHS.FloatImag = APFloat(Real.getSemantics()); 14047 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14048 return false; 14049 14050 assert(!(LHSReal && RHSReal) && 14051 "Cannot have both operands of a complex operation be real."); 14052 switch (E->getOpcode()) { 14053 default: return Error(E); 14054 case BO_Add: 14055 if (Result.isComplexFloat()) { 14056 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14057 APFloat::rmNearestTiesToEven); 14058 if (LHSReal) 14059 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14060 else if (!RHSReal) 14061 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14062 APFloat::rmNearestTiesToEven); 14063 } else { 14064 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14065 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14066 } 14067 break; 14068 case BO_Sub: 14069 if (Result.isComplexFloat()) { 14070 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14071 APFloat::rmNearestTiesToEven); 14072 if (LHSReal) { 14073 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14074 Result.getComplexFloatImag().changeSign(); 14075 } else if (!RHSReal) { 14076 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14077 APFloat::rmNearestTiesToEven); 14078 } 14079 } else { 14080 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14081 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14082 } 14083 break; 14084 case BO_Mul: 14085 if (Result.isComplexFloat()) { 14086 // This is an implementation of complex multiplication according to the 14087 // constraints laid out in C11 Annex G. The implementation uses the 14088 // following naming scheme: 14089 // (a + ib) * (c + id) 14090 ComplexValue LHS = Result; 14091 APFloat &A = LHS.getComplexFloatReal(); 14092 APFloat &B = LHS.getComplexFloatImag(); 14093 APFloat &C = RHS.getComplexFloatReal(); 14094 APFloat &D = RHS.getComplexFloatImag(); 14095 APFloat &ResR = Result.getComplexFloatReal(); 14096 APFloat &ResI = Result.getComplexFloatImag(); 14097 if (LHSReal) { 14098 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14099 ResR = A * C; 14100 ResI = A * D; 14101 } else if (RHSReal) { 14102 ResR = C * A; 14103 ResI = C * B; 14104 } else { 14105 // In the fully general case, we need to handle NaNs and infinities 14106 // robustly. 14107 APFloat AC = A * C; 14108 APFloat BD = B * D; 14109 APFloat AD = A * D; 14110 APFloat BC = B * C; 14111 ResR = AC - BD; 14112 ResI = AD + BC; 14113 if (ResR.isNaN() && ResI.isNaN()) { 14114 bool Recalc = false; 14115 if (A.isInfinity() || B.isInfinity()) { 14116 A = APFloat::copySign( 14117 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14118 B = APFloat::copySign( 14119 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14120 if (C.isNaN()) 14121 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14122 if (D.isNaN()) 14123 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14124 Recalc = true; 14125 } 14126 if (C.isInfinity() || D.isInfinity()) { 14127 C = APFloat::copySign( 14128 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14129 D = APFloat::copySign( 14130 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14131 if (A.isNaN()) 14132 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14133 if (B.isNaN()) 14134 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14135 Recalc = true; 14136 } 14137 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14138 AD.isInfinity() || BC.isInfinity())) { 14139 if (A.isNaN()) 14140 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14141 if (B.isNaN()) 14142 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14143 if (C.isNaN()) 14144 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14145 if (D.isNaN()) 14146 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14147 Recalc = true; 14148 } 14149 if (Recalc) { 14150 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14151 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14152 } 14153 } 14154 } 14155 } else { 14156 ComplexValue LHS = Result; 14157 Result.getComplexIntReal() = 14158 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14159 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14160 Result.getComplexIntImag() = 14161 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14162 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14163 } 14164 break; 14165 case BO_Div: 14166 if (Result.isComplexFloat()) { 14167 // This is an implementation of complex division according to the 14168 // constraints laid out in C11 Annex G. The implementation uses the 14169 // following naming scheme: 14170 // (a + ib) / (c + id) 14171 ComplexValue LHS = Result; 14172 APFloat &A = LHS.getComplexFloatReal(); 14173 APFloat &B = LHS.getComplexFloatImag(); 14174 APFloat &C = RHS.getComplexFloatReal(); 14175 APFloat &D = RHS.getComplexFloatImag(); 14176 APFloat &ResR = Result.getComplexFloatReal(); 14177 APFloat &ResI = Result.getComplexFloatImag(); 14178 if (RHSReal) { 14179 ResR = A / C; 14180 ResI = B / C; 14181 } else { 14182 if (LHSReal) { 14183 // No real optimizations we can do here, stub out with zero. 14184 B = APFloat::getZero(A.getSemantics()); 14185 } 14186 int DenomLogB = 0; 14187 APFloat MaxCD = maxnum(abs(C), abs(D)); 14188 if (MaxCD.isFinite()) { 14189 DenomLogB = ilogb(MaxCD); 14190 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14191 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14192 } 14193 APFloat Denom = C * C + D * D; 14194 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14195 APFloat::rmNearestTiesToEven); 14196 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14197 APFloat::rmNearestTiesToEven); 14198 if (ResR.isNaN() && ResI.isNaN()) { 14199 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14200 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14201 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14202 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14203 D.isFinite()) { 14204 A = APFloat::copySign( 14205 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14206 B = APFloat::copySign( 14207 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14208 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14209 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14210 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14211 C = APFloat::copySign( 14212 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14213 D = APFloat::copySign( 14214 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14215 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14216 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14217 } 14218 } 14219 } 14220 } else { 14221 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14222 return Error(E, diag::note_expr_divide_by_zero); 14223 14224 ComplexValue LHS = Result; 14225 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14226 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14227 Result.getComplexIntReal() = 14228 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14229 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14230 Result.getComplexIntImag() = 14231 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14232 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14233 } 14234 break; 14235 } 14236 14237 return true; 14238 } 14239 14240 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14241 // Get the operand value into 'Result'. 14242 if (!Visit(E->getSubExpr())) 14243 return false; 14244 14245 switch (E->getOpcode()) { 14246 default: 14247 return Error(E); 14248 case UO_Extension: 14249 return true; 14250 case UO_Plus: 14251 // The result is always just the subexpr. 14252 return true; 14253 case UO_Minus: 14254 if (Result.isComplexFloat()) { 14255 Result.getComplexFloatReal().changeSign(); 14256 Result.getComplexFloatImag().changeSign(); 14257 } 14258 else { 14259 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14260 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14261 } 14262 return true; 14263 case UO_Not: 14264 if (Result.isComplexFloat()) 14265 Result.getComplexFloatImag().changeSign(); 14266 else 14267 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14268 return true; 14269 } 14270 } 14271 14272 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14273 if (E->getNumInits() == 2) { 14274 if (E->getType()->isComplexType()) { 14275 Result.makeComplexFloat(); 14276 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14277 return false; 14278 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14279 return false; 14280 } else { 14281 Result.makeComplexInt(); 14282 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14283 return false; 14284 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14285 return false; 14286 } 14287 return true; 14288 } 14289 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14290 } 14291 14292 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14293 switch (E->getBuiltinCallee()) { 14294 case Builtin::BI__builtin_complex: 14295 Result.makeComplexFloat(); 14296 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14297 return false; 14298 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14299 return false; 14300 return true; 14301 14302 default: 14303 break; 14304 } 14305 14306 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14307 } 14308 14309 //===----------------------------------------------------------------------===// 14310 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14311 // implicit conversion. 14312 //===----------------------------------------------------------------------===// 14313 14314 namespace { 14315 class AtomicExprEvaluator : 14316 public ExprEvaluatorBase<AtomicExprEvaluator> { 14317 const LValue *This; 14318 APValue &Result; 14319 public: 14320 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14321 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14322 14323 bool Success(const APValue &V, const Expr *E) { 14324 Result = V; 14325 return true; 14326 } 14327 14328 bool ZeroInitialization(const Expr *E) { 14329 ImplicitValueInitExpr VIE( 14330 E->getType()->castAs<AtomicType>()->getValueType()); 14331 // For atomic-qualified class (and array) types in C++, initialize the 14332 // _Atomic-wrapped subobject directly, in-place. 14333 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14334 : Evaluate(Result, Info, &VIE); 14335 } 14336 14337 bool VisitCastExpr(const CastExpr *E) { 14338 switch (E->getCastKind()) { 14339 default: 14340 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14341 case CK_NonAtomicToAtomic: 14342 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14343 : Evaluate(Result, Info, E->getSubExpr()); 14344 } 14345 } 14346 }; 14347 } // end anonymous namespace 14348 14349 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14350 EvalInfo &Info) { 14351 assert(!E->isValueDependent()); 14352 assert(E->isPRValue() && E->getType()->isAtomicType()); 14353 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14354 } 14355 14356 //===----------------------------------------------------------------------===// 14357 // Void expression evaluation, primarily for a cast to void on the LHS of a 14358 // comma operator 14359 //===----------------------------------------------------------------------===// 14360 14361 namespace { 14362 class VoidExprEvaluator 14363 : public ExprEvaluatorBase<VoidExprEvaluator> { 14364 public: 14365 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14366 14367 bool Success(const APValue &V, const Expr *e) { return true; } 14368 14369 bool ZeroInitialization(const Expr *E) { return true; } 14370 14371 bool VisitCastExpr(const CastExpr *E) { 14372 switch (E->getCastKind()) { 14373 default: 14374 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14375 case CK_ToVoid: 14376 VisitIgnoredValue(E->getSubExpr()); 14377 return true; 14378 } 14379 } 14380 14381 bool VisitCallExpr(const CallExpr *E) { 14382 switch (E->getBuiltinCallee()) { 14383 case Builtin::BI__assume: 14384 case Builtin::BI__builtin_assume: 14385 // The argument is not evaluated! 14386 return true; 14387 14388 case Builtin::BI__builtin_operator_delete: 14389 return HandleOperatorDeleteCall(Info, E); 14390 14391 default: 14392 break; 14393 } 14394 14395 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14396 } 14397 14398 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14399 }; 14400 } // end anonymous namespace 14401 14402 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14403 // We cannot speculatively evaluate a delete expression. 14404 if (Info.SpeculativeEvaluationDepth) 14405 return false; 14406 14407 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14408 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14409 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14410 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14411 return false; 14412 } 14413 14414 const Expr *Arg = E->getArgument(); 14415 14416 LValue Pointer; 14417 if (!EvaluatePointer(Arg, Pointer, Info)) 14418 return false; 14419 if (Pointer.Designator.Invalid) 14420 return false; 14421 14422 // Deleting a null pointer has no effect. 14423 if (Pointer.isNullPointer()) { 14424 // This is the only case where we need to produce an extension warning: 14425 // the only other way we can succeed is if we find a dynamic allocation, 14426 // and we will have warned when we allocated it in that case. 14427 if (!Info.getLangOpts().CPlusPlus20) 14428 Info.CCEDiag(E, diag::note_constexpr_new); 14429 return true; 14430 } 14431 14432 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14433 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14434 if (!Alloc) 14435 return false; 14436 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14437 14438 // For the non-array case, the designator must be empty if the static type 14439 // does not have a virtual destructor. 14440 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14441 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14442 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14443 << Arg->getType()->getPointeeType() << AllocType; 14444 return false; 14445 } 14446 14447 // For a class type with a virtual destructor, the selected operator delete 14448 // is the one looked up when building the destructor. 14449 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14450 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14451 if (VirtualDelete && 14452 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14453 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14454 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14455 return false; 14456 } 14457 } 14458 14459 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14460 (*Alloc)->Value, AllocType)) 14461 return false; 14462 14463 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14464 // The element was already erased. This means the destructor call also 14465 // deleted the object. 14466 // FIXME: This probably results in undefined behavior before we get this 14467 // far, and should be diagnosed elsewhere first. 14468 Info.FFDiag(E, diag::note_constexpr_double_delete); 14469 return false; 14470 } 14471 14472 return true; 14473 } 14474 14475 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14476 assert(!E->isValueDependent()); 14477 assert(E->isPRValue() && E->getType()->isVoidType()); 14478 return VoidExprEvaluator(Info).Visit(E); 14479 } 14480 14481 //===----------------------------------------------------------------------===// 14482 // Top level Expr::EvaluateAsRValue method. 14483 //===----------------------------------------------------------------------===// 14484 14485 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14486 assert(!E->isValueDependent()); 14487 // In C, function designators are not lvalues, but we evaluate them as if they 14488 // are. 14489 QualType T = E->getType(); 14490 if (E->isGLValue() || T->isFunctionType()) { 14491 LValue LV; 14492 if (!EvaluateLValue(E, LV, Info)) 14493 return false; 14494 LV.moveInto(Result); 14495 } else if (T->isVectorType()) { 14496 if (!EvaluateVector(E, Result, Info)) 14497 return false; 14498 } else if (T->isIntegralOrEnumerationType()) { 14499 if (!IntExprEvaluator(Info, Result).Visit(E)) 14500 return false; 14501 } else if (T->hasPointerRepresentation()) { 14502 LValue LV; 14503 if (!EvaluatePointer(E, LV, Info)) 14504 return false; 14505 LV.moveInto(Result); 14506 } else if (T->isRealFloatingType()) { 14507 llvm::APFloat F(0.0); 14508 if (!EvaluateFloat(E, F, Info)) 14509 return false; 14510 Result = APValue(F); 14511 } else if (T->isAnyComplexType()) { 14512 ComplexValue C; 14513 if (!EvaluateComplex(E, C, Info)) 14514 return false; 14515 C.moveInto(Result); 14516 } else if (T->isFixedPointType()) { 14517 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14518 } else if (T->isMemberPointerType()) { 14519 MemberPtr P; 14520 if (!EvaluateMemberPointer(E, P, Info)) 14521 return false; 14522 P.moveInto(Result); 14523 return true; 14524 } else if (T->isArrayType()) { 14525 LValue LV; 14526 APValue &Value = 14527 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14528 if (!EvaluateArray(E, LV, Value, Info)) 14529 return false; 14530 Result = Value; 14531 } else if (T->isRecordType()) { 14532 LValue LV; 14533 APValue &Value = 14534 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14535 if (!EvaluateRecord(E, LV, Value, Info)) 14536 return false; 14537 Result = Value; 14538 } else if (T->isVoidType()) { 14539 if (!Info.getLangOpts().CPlusPlus11) 14540 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14541 << E->getType(); 14542 if (!EvaluateVoid(E, Info)) 14543 return false; 14544 } else if (T->isAtomicType()) { 14545 QualType Unqual = T.getAtomicUnqualifiedType(); 14546 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14547 LValue LV; 14548 APValue &Value = Info.CurrentCall->createTemporary( 14549 E, Unqual, ScopeKind::FullExpression, LV); 14550 if (!EvaluateAtomic(E, &LV, Value, Info)) 14551 return false; 14552 } else { 14553 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14554 return false; 14555 } 14556 } else if (Info.getLangOpts().CPlusPlus11) { 14557 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14558 return false; 14559 } else { 14560 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14561 return false; 14562 } 14563 14564 return true; 14565 } 14566 14567 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14568 /// cases, the in-place evaluation is essential, since later initializers for 14569 /// an object can indirectly refer to subobjects which were initialized earlier. 14570 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14571 const Expr *E, bool AllowNonLiteralTypes) { 14572 assert(!E->isValueDependent()); 14573 14574 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14575 return false; 14576 14577 if (E->isPRValue()) { 14578 // Evaluate arrays and record types in-place, so that later initializers can 14579 // refer to earlier-initialized members of the object. 14580 QualType T = E->getType(); 14581 if (T->isArrayType()) 14582 return EvaluateArray(E, This, Result, Info); 14583 else if (T->isRecordType()) 14584 return EvaluateRecord(E, This, Result, Info); 14585 else if (T->isAtomicType()) { 14586 QualType Unqual = T.getAtomicUnqualifiedType(); 14587 if (Unqual->isArrayType() || Unqual->isRecordType()) 14588 return EvaluateAtomic(E, &This, Result, Info); 14589 } 14590 } 14591 14592 // For any other type, in-place evaluation is unimportant. 14593 return Evaluate(Result, Info, E); 14594 } 14595 14596 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14597 /// lvalue-to-rvalue cast if it is an lvalue. 14598 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14599 assert(!E->isValueDependent()); 14600 if (Info.EnableNewConstInterp) { 14601 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14602 return false; 14603 } else { 14604 if (E->getType().isNull()) 14605 return false; 14606 14607 if (!CheckLiteralType(Info, E)) 14608 return false; 14609 14610 if (!::Evaluate(Result, Info, E)) 14611 return false; 14612 14613 if (E->isGLValue()) { 14614 LValue LV; 14615 LV.setFrom(Info.Ctx, Result); 14616 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14617 return false; 14618 } 14619 } 14620 14621 // Check this core constant expression is a constant expression. 14622 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14623 ConstantExprKind::Normal) && 14624 CheckMemoryLeaks(Info); 14625 } 14626 14627 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14628 const ASTContext &Ctx, bool &IsConst) { 14629 // Fast-path evaluations of integer literals, since we sometimes see files 14630 // containing vast quantities of these. 14631 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14632 Result.Val = APValue(APSInt(L->getValue(), 14633 L->getType()->isUnsignedIntegerType())); 14634 IsConst = true; 14635 return true; 14636 } 14637 14638 // This case should be rare, but we need to check it before we check on 14639 // the type below. 14640 if (Exp->getType().isNull()) { 14641 IsConst = false; 14642 return true; 14643 } 14644 14645 // FIXME: Evaluating values of large array and record types can cause 14646 // performance problems. Only do so in C++11 for now. 14647 if (Exp->isPRValue() && 14648 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && 14649 !Ctx.getLangOpts().CPlusPlus11) { 14650 IsConst = false; 14651 return true; 14652 } 14653 return false; 14654 } 14655 14656 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14657 Expr::SideEffectsKind SEK) { 14658 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14659 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14660 } 14661 14662 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14663 const ASTContext &Ctx, EvalInfo &Info) { 14664 assert(!E->isValueDependent()); 14665 bool IsConst; 14666 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14667 return IsConst; 14668 14669 return EvaluateAsRValue(Info, E, Result.Val); 14670 } 14671 14672 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14673 const ASTContext &Ctx, 14674 Expr::SideEffectsKind AllowSideEffects, 14675 EvalInfo &Info) { 14676 assert(!E->isValueDependent()); 14677 if (!E->getType()->isIntegralOrEnumerationType()) 14678 return false; 14679 14680 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14681 !ExprResult.Val.isInt() || 14682 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14683 return false; 14684 14685 return true; 14686 } 14687 14688 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14689 const ASTContext &Ctx, 14690 Expr::SideEffectsKind AllowSideEffects, 14691 EvalInfo &Info) { 14692 assert(!E->isValueDependent()); 14693 if (!E->getType()->isFixedPointType()) 14694 return false; 14695 14696 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14697 return false; 14698 14699 if (!ExprResult.Val.isFixedPoint() || 14700 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14701 return false; 14702 14703 return true; 14704 } 14705 14706 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14707 /// any crazy technique (that has nothing to do with language standards) that 14708 /// we want to. If this function returns true, it returns the folded constant 14709 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14710 /// will be applied to the result. 14711 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14712 bool InConstantContext) const { 14713 assert(!isValueDependent() && 14714 "Expression evaluator can't be called on a dependent expression."); 14715 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14716 Info.InConstantContext = InConstantContext; 14717 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14718 } 14719 14720 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14721 bool InConstantContext) const { 14722 assert(!isValueDependent() && 14723 "Expression evaluator can't be called on a dependent expression."); 14724 EvalResult Scratch; 14725 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14726 HandleConversionToBool(Scratch.Val, Result); 14727 } 14728 14729 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14730 SideEffectsKind AllowSideEffects, 14731 bool InConstantContext) const { 14732 assert(!isValueDependent() && 14733 "Expression evaluator can't be called on a dependent expression."); 14734 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14735 Info.InConstantContext = InConstantContext; 14736 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14737 } 14738 14739 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14740 SideEffectsKind AllowSideEffects, 14741 bool InConstantContext) const { 14742 assert(!isValueDependent() && 14743 "Expression evaluator can't be called on a dependent expression."); 14744 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14745 Info.InConstantContext = InConstantContext; 14746 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14747 } 14748 14749 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14750 SideEffectsKind AllowSideEffects, 14751 bool InConstantContext) const { 14752 assert(!isValueDependent() && 14753 "Expression evaluator can't be called on a dependent expression."); 14754 14755 if (!getType()->isRealFloatingType()) 14756 return false; 14757 14758 EvalResult ExprResult; 14759 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14760 !ExprResult.Val.isFloat() || 14761 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14762 return false; 14763 14764 Result = ExprResult.Val.getFloat(); 14765 return true; 14766 } 14767 14768 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14769 bool InConstantContext) const { 14770 assert(!isValueDependent() && 14771 "Expression evaluator can't be called on a dependent expression."); 14772 14773 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14774 Info.InConstantContext = InConstantContext; 14775 LValue LV; 14776 CheckedTemporaries CheckedTemps; 14777 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14778 Result.HasSideEffects || 14779 !CheckLValueConstantExpression(Info, getExprLoc(), 14780 Ctx.getLValueReferenceType(getType()), LV, 14781 ConstantExprKind::Normal, CheckedTemps)) 14782 return false; 14783 14784 LV.moveInto(Result.Val); 14785 return true; 14786 } 14787 14788 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14789 APValue DestroyedValue, QualType Type, 14790 SourceLocation Loc, Expr::EvalStatus &EStatus, 14791 bool IsConstantDestruction) { 14792 EvalInfo Info(Ctx, EStatus, 14793 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14794 : EvalInfo::EM_ConstantFold); 14795 Info.setEvaluatingDecl(Base, DestroyedValue, 14796 EvalInfo::EvaluatingDeclKind::Dtor); 14797 Info.InConstantContext = IsConstantDestruction; 14798 14799 LValue LVal; 14800 LVal.set(Base); 14801 14802 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14803 EStatus.HasSideEffects) 14804 return false; 14805 14806 if (!Info.discardCleanups()) 14807 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14808 14809 return true; 14810 } 14811 14812 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14813 ConstantExprKind Kind) const { 14814 assert(!isValueDependent() && 14815 "Expression evaluator can't be called on a dependent expression."); 14816 14817 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14818 EvalInfo Info(Ctx, Result, EM); 14819 Info.InConstantContext = true; 14820 14821 // The type of the object we're initializing is 'const T' for a class NTTP. 14822 QualType T = getType(); 14823 if (Kind == ConstantExprKind::ClassTemplateArgument) 14824 T.addConst(); 14825 14826 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14827 // represent the result of the evaluation. CheckConstantExpression ensures 14828 // this doesn't escape. 14829 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14830 APValue::LValueBase Base(&BaseMTE); 14831 14832 Info.setEvaluatingDecl(Base, Result.Val); 14833 LValue LVal; 14834 LVal.set(Base); 14835 14836 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14837 return false; 14838 14839 if (!Info.discardCleanups()) 14840 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14841 14842 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14843 Result.Val, Kind)) 14844 return false; 14845 if (!CheckMemoryLeaks(Info)) 14846 return false; 14847 14848 // If this is a class template argument, it's required to have constant 14849 // destruction too. 14850 if (Kind == ConstantExprKind::ClassTemplateArgument && 14851 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 14852 true) || 14853 Result.HasSideEffects)) { 14854 // FIXME: Prefix a note to indicate that the problem is lack of constant 14855 // destruction. 14856 return false; 14857 } 14858 14859 return true; 14860 } 14861 14862 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14863 const VarDecl *VD, 14864 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14865 bool IsConstantInitialization) const { 14866 assert(!isValueDependent() && 14867 "Expression evaluator can't be called on a dependent expression."); 14868 14869 // FIXME: Evaluating initializers for large array and record types can cause 14870 // performance problems. Only do so in C++11 for now. 14871 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14872 !Ctx.getLangOpts().CPlusPlus11) 14873 return false; 14874 14875 Expr::EvalStatus EStatus; 14876 EStatus.Diag = &Notes; 14877 14878 EvalInfo Info(Ctx, EStatus, 14879 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14880 ? EvalInfo::EM_ConstantExpression 14881 : EvalInfo::EM_ConstantFold); 14882 Info.setEvaluatingDecl(VD, Value); 14883 Info.InConstantContext = IsConstantInitialization; 14884 14885 SourceLocation DeclLoc = VD->getLocation(); 14886 QualType DeclTy = VD->getType(); 14887 14888 if (Info.EnableNewConstInterp) { 14889 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14890 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14891 return false; 14892 } else { 14893 LValue LVal; 14894 LVal.set(VD); 14895 14896 if (!EvaluateInPlace(Value, Info, LVal, this, 14897 /*AllowNonLiteralTypes=*/true) || 14898 EStatus.HasSideEffects) 14899 return false; 14900 14901 // At this point, any lifetime-extended temporaries are completely 14902 // initialized. 14903 Info.performLifetimeExtension(); 14904 14905 if (!Info.discardCleanups()) 14906 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14907 } 14908 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 14909 ConstantExprKind::Normal) && 14910 CheckMemoryLeaks(Info); 14911 } 14912 14913 bool VarDecl::evaluateDestruction( 14914 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14915 Expr::EvalStatus EStatus; 14916 EStatus.Diag = &Notes; 14917 14918 // Only treat the destruction as constant destruction if we formally have 14919 // constant initialization (or are usable in a constant expression). 14920 bool IsConstantDestruction = hasConstantInitialization(); 14921 14922 // Make a copy of the value for the destructor to mutate, if we know it. 14923 // Otherwise, treat the value as default-initialized; if the destructor works 14924 // anyway, then the destruction is constant (and must be essentially empty). 14925 APValue DestroyedValue; 14926 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14927 DestroyedValue = *getEvaluatedValue(); 14928 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14929 return false; 14930 14931 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 14932 getType(), getLocation(), EStatus, 14933 IsConstantDestruction) || 14934 EStatus.HasSideEffects) 14935 return false; 14936 14937 ensureEvaluatedStmt()->HasConstantDestruction = true; 14938 return true; 14939 } 14940 14941 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14942 /// constant folded, but discard the result. 14943 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14944 assert(!isValueDependent() && 14945 "Expression evaluator can't be called on a dependent expression."); 14946 14947 EvalResult Result; 14948 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14949 !hasUnacceptableSideEffect(Result, SEK); 14950 } 14951 14952 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14953 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14954 assert(!isValueDependent() && 14955 "Expression evaluator can't be called on a dependent expression."); 14956 14957 EvalResult EVResult; 14958 EVResult.Diag = Diag; 14959 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14960 Info.InConstantContext = true; 14961 14962 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14963 (void)Result; 14964 assert(Result && "Could not evaluate expression"); 14965 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14966 14967 return EVResult.Val.getInt(); 14968 } 14969 14970 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14971 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14972 assert(!isValueDependent() && 14973 "Expression evaluator can't be called on a dependent expression."); 14974 14975 EvalResult EVResult; 14976 EVResult.Diag = Diag; 14977 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14978 Info.InConstantContext = true; 14979 Info.CheckingForUndefinedBehavior = true; 14980 14981 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14982 (void)Result; 14983 assert(Result && "Could not evaluate expression"); 14984 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14985 14986 return EVResult.Val.getInt(); 14987 } 14988 14989 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14990 assert(!isValueDependent() && 14991 "Expression evaluator can't be called on a dependent expression."); 14992 14993 bool IsConst; 14994 EvalResult EVResult; 14995 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14996 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14997 Info.CheckingForUndefinedBehavior = true; 14998 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14999 } 15000 } 15001 15002 bool Expr::EvalResult::isGlobalLValue() const { 15003 assert(Val.isLValue()); 15004 return IsGlobalLValue(Val.getLValueBase()); 15005 } 15006 15007 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15008 /// an integer constant expression. 15009 15010 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15011 /// comma, etc 15012 15013 // CheckICE - This function does the fundamental ICE checking: the returned 15014 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15015 // and a (possibly null) SourceLocation indicating the location of the problem. 15016 // 15017 // Note that to reduce code duplication, this helper does no evaluation 15018 // itself; the caller checks whether the expression is evaluatable, and 15019 // in the rare cases where CheckICE actually cares about the evaluated 15020 // value, it calls into Evaluate. 15021 15022 namespace { 15023 15024 enum ICEKind { 15025 /// This expression is an ICE. 15026 IK_ICE, 15027 /// This expression is not an ICE, but if it isn't evaluated, it's 15028 /// a legal subexpression for an ICE. This return value is used to handle 15029 /// the comma operator in C99 mode, and non-constant subexpressions. 15030 IK_ICEIfUnevaluated, 15031 /// This expression is not an ICE, and is not a legal subexpression for one. 15032 IK_NotICE 15033 }; 15034 15035 struct ICEDiag { 15036 ICEKind Kind; 15037 SourceLocation Loc; 15038 15039 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15040 }; 15041 15042 } 15043 15044 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15045 15046 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15047 15048 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15049 Expr::EvalResult EVResult; 15050 Expr::EvalStatus Status; 15051 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15052 15053 Info.InConstantContext = true; 15054 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15055 !EVResult.Val.isInt()) 15056 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15057 15058 return NoDiag(); 15059 } 15060 15061 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15062 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15063 if (!E->getType()->isIntegralOrEnumerationType()) 15064 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15065 15066 switch (E->getStmtClass()) { 15067 #define ABSTRACT_STMT(Node) 15068 #define STMT(Node, Base) case Expr::Node##Class: 15069 #define EXPR(Node, Base) 15070 #include "clang/AST/StmtNodes.inc" 15071 case Expr::PredefinedExprClass: 15072 case Expr::FloatingLiteralClass: 15073 case Expr::ImaginaryLiteralClass: 15074 case Expr::StringLiteralClass: 15075 case Expr::ArraySubscriptExprClass: 15076 case Expr::MatrixSubscriptExprClass: 15077 case Expr::OMPArraySectionExprClass: 15078 case Expr::OMPArrayShapingExprClass: 15079 case Expr::OMPIteratorExprClass: 15080 case Expr::MemberExprClass: 15081 case Expr::CompoundAssignOperatorClass: 15082 case Expr::CompoundLiteralExprClass: 15083 case Expr::ExtVectorElementExprClass: 15084 case Expr::DesignatedInitExprClass: 15085 case Expr::ArrayInitLoopExprClass: 15086 case Expr::ArrayInitIndexExprClass: 15087 case Expr::NoInitExprClass: 15088 case Expr::DesignatedInitUpdateExprClass: 15089 case Expr::ImplicitValueInitExprClass: 15090 case Expr::ParenListExprClass: 15091 case Expr::VAArgExprClass: 15092 case Expr::AddrLabelExprClass: 15093 case Expr::StmtExprClass: 15094 case Expr::CXXMemberCallExprClass: 15095 case Expr::CUDAKernelCallExprClass: 15096 case Expr::CXXAddrspaceCastExprClass: 15097 case Expr::CXXDynamicCastExprClass: 15098 case Expr::CXXTypeidExprClass: 15099 case Expr::CXXUuidofExprClass: 15100 case Expr::MSPropertyRefExprClass: 15101 case Expr::MSPropertySubscriptExprClass: 15102 case Expr::CXXNullPtrLiteralExprClass: 15103 case Expr::UserDefinedLiteralClass: 15104 case Expr::CXXThisExprClass: 15105 case Expr::CXXThrowExprClass: 15106 case Expr::CXXNewExprClass: 15107 case Expr::CXXDeleteExprClass: 15108 case Expr::CXXPseudoDestructorExprClass: 15109 case Expr::UnresolvedLookupExprClass: 15110 case Expr::TypoExprClass: 15111 case Expr::RecoveryExprClass: 15112 case Expr::DependentScopeDeclRefExprClass: 15113 case Expr::CXXConstructExprClass: 15114 case Expr::CXXInheritedCtorInitExprClass: 15115 case Expr::CXXStdInitializerListExprClass: 15116 case Expr::CXXBindTemporaryExprClass: 15117 case Expr::ExprWithCleanupsClass: 15118 case Expr::CXXTemporaryObjectExprClass: 15119 case Expr::CXXUnresolvedConstructExprClass: 15120 case Expr::CXXDependentScopeMemberExprClass: 15121 case Expr::UnresolvedMemberExprClass: 15122 case Expr::ObjCStringLiteralClass: 15123 case Expr::ObjCBoxedExprClass: 15124 case Expr::ObjCArrayLiteralClass: 15125 case Expr::ObjCDictionaryLiteralClass: 15126 case Expr::ObjCEncodeExprClass: 15127 case Expr::ObjCMessageExprClass: 15128 case Expr::ObjCSelectorExprClass: 15129 case Expr::ObjCProtocolExprClass: 15130 case Expr::ObjCIvarRefExprClass: 15131 case Expr::ObjCPropertyRefExprClass: 15132 case Expr::ObjCSubscriptRefExprClass: 15133 case Expr::ObjCIsaExprClass: 15134 case Expr::ObjCAvailabilityCheckExprClass: 15135 case Expr::ShuffleVectorExprClass: 15136 case Expr::ConvertVectorExprClass: 15137 case Expr::BlockExprClass: 15138 case Expr::NoStmtClass: 15139 case Expr::OpaqueValueExprClass: 15140 case Expr::PackExpansionExprClass: 15141 case Expr::SubstNonTypeTemplateParmPackExprClass: 15142 case Expr::FunctionParmPackExprClass: 15143 case Expr::AsTypeExprClass: 15144 case Expr::ObjCIndirectCopyRestoreExprClass: 15145 case Expr::MaterializeTemporaryExprClass: 15146 case Expr::PseudoObjectExprClass: 15147 case Expr::AtomicExprClass: 15148 case Expr::LambdaExprClass: 15149 case Expr::CXXFoldExprClass: 15150 case Expr::CoawaitExprClass: 15151 case Expr::DependentCoawaitExprClass: 15152 case Expr::CoyieldExprClass: 15153 case Expr::SYCLUniqueStableNameExprClass: 15154 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15155 15156 case Expr::InitListExprClass: { 15157 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15158 // form "T x = { a };" is equivalent to "T x = a;". 15159 // Unless we're initializing a reference, T is a scalar as it is known to be 15160 // of integral or enumeration type. 15161 if (E->isPRValue()) 15162 if (cast<InitListExpr>(E)->getNumInits() == 1) 15163 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15164 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15165 } 15166 15167 case Expr::SizeOfPackExprClass: 15168 case Expr::GNUNullExprClass: 15169 case Expr::SourceLocExprClass: 15170 return NoDiag(); 15171 15172 case Expr::SubstNonTypeTemplateParmExprClass: 15173 return 15174 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15175 15176 case Expr::ConstantExprClass: 15177 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15178 15179 case Expr::ParenExprClass: 15180 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15181 case Expr::GenericSelectionExprClass: 15182 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15183 case Expr::IntegerLiteralClass: 15184 case Expr::FixedPointLiteralClass: 15185 case Expr::CharacterLiteralClass: 15186 case Expr::ObjCBoolLiteralExprClass: 15187 case Expr::CXXBoolLiteralExprClass: 15188 case Expr::CXXScalarValueInitExprClass: 15189 case Expr::TypeTraitExprClass: 15190 case Expr::ConceptSpecializationExprClass: 15191 case Expr::RequiresExprClass: 15192 case Expr::ArrayTypeTraitExprClass: 15193 case Expr::ExpressionTraitExprClass: 15194 case Expr::CXXNoexceptExprClass: 15195 return NoDiag(); 15196 case Expr::CallExprClass: 15197 case Expr::CXXOperatorCallExprClass: { 15198 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15199 // constant expressions, but they can never be ICEs because an ICE cannot 15200 // contain an operand of (pointer to) function type. 15201 const CallExpr *CE = cast<CallExpr>(E); 15202 if (CE->getBuiltinCallee()) 15203 return CheckEvalInICE(E, Ctx); 15204 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15205 } 15206 case Expr::CXXRewrittenBinaryOperatorClass: 15207 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15208 Ctx); 15209 case Expr::DeclRefExprClass: { 15210 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15211 if (isa<EnumConstantDecl>(D)) 15212 return NoDiag(); 15213 15214 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15215 // integer variables in constant expressions: 15216 // 15217 // C++ 7.1.5.1p2 15218 // A variable of non-volatile const-qualified integral or enumeration 15219 // type initialized by an ICE can be used in ICEs. 15220 // 15221 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15222 // that mode, use of reference variables should not be allowed. 15223 const VarDecl *VD = dyn_cast<VarDecl>(D); 15224 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15225 !VD->getType()->isReferenceType()) 15226 return NoDiag(); 15227 15228 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15229 } 15230 case Expr::UnaryOperatorClass: { 15231 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15232 switch (Exp->getOpcode()) { 15233 case UO_PostInc: 15234 case UO_PostDec: 15235 case UO_PreInc: 15236 case UO_PreDec: 15237 case UO_AddrOf: 15238 case UO_Deref: 15239 case UO_Coawait: 15240 // C99 6.6/3 allows increment and decrement within unevaluated 15241 // subexpressions of constant expressions, but they can never be ICEs 15242 // because an ICE cannot contain an lvalue operand. 15243 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15244 case UO_Extension: 15245 case UO_LNot: 15246 case UO_Plus: 15247 case UO_Minus: 15248 case UO_Not: 15249 case UO_Real: 15250 case UO_Imag: 15251 return CheckICE(Exp->getSubExpr(), Ctx); 15252 } 15253 llvm_unreachable("invalid unary operator class"); 15254 } 15255 case Expr::OffsetOfExprClass: { 15256 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15257 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15258 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15259 // compliance: we should warn earlier for offsetof expressions with 15260 // array subscripts that aren't ICEs, and if the array subscripts 15261 // are ICEs, the value of the offsetof must be an integer constant. 15262 return CheckEvalInICE(E, Ctx); 15263 } 15264 case Expr::UnaryExprOrTypeTraitExprClass: { 15265 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15266 if ((Exp->getKind() == UETT_SizeOf) && 15267 Exp->getTypeOfArgument()->isVariableArrayType()) 15268 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15269 return NoDiag(); 15270 } 15271 case Expr::BinaryOperatorClass: { 15272 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15273 switch (Exp->getOpcode()) { 15274 case BO_PtrMemD: 15275 case BO_PtrMemI: 15276 case BO_Assign: 15277 case BO_MulAssign: 15278 case BO_DivAssign: 15279 case BO_RemAssign: 15280 case BO_AddAssign: 15281 case BO_SubAssign: 15282 case BO_ShlAssign: 15283 case BO_ShrAssign: 15284 case BO_AndAssign: 15285 case BO_XorAssign: 15286 case BO_OrAssign: 15287 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15288 // constant expressions, but they can never be ICEs because an ICE cannot 15289 // contain an lvalue operand. 15290 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15291 15292 case BO_Mul: 15293 case BO_Div: 15294 case BO_Rem: 15295 case BO_Add: 15296 case BO_Sub: 15297 case BO_Shl: 15298 case BO_Shr: 15299 case BO_LT: 15300 case BO_GT: 15301 case BO_LE: 15302 case BO_GE: 15303 case BO_EQ: 15304 case BO_NE: 15305 case BO_And: 15306 case BO_Xor: 15307 case BO_Or: 15308 case BO_Comma: 15309 case BO_Cmp: { 15310 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15311 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15312 if (Exp->getOpcode() == BO_Div || 15313 Exp->getOpcode() == BO_Rem) { 15314 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15315 // we don't evaluate one. 15316 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15317 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15318 if (REval == 0) 15319 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15320 if (REval.isSigned() && REval.isAllOnesValue()) { 15321 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15322 if (LEval.isMinSignedValue()) 15323 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15324 } 15325 } 15326 } 15327 if (Exp->getOpcode() == BO_Comma) { 15328 if (Ctx.getLangOpts().C99) { 15329 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15330 // if it isn't evaluated. 15331 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15332 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15333 } else { 15334 // In both C89 and C++, commas in ICEs are illegal. 15335 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15336 } 15337 } 15338 return Worst(LHSResult, RHSResult); 15339 } 15340 case BO_LAnd: 15341 case BO_LOr: { 15342 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15343 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15344 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15345 // Rare case where the RHS has a comma "side-effect"; we need 15346 // to actually check the condition to see whether the side 15347 // with the comma is evaluated. 15348 if ((Exp->getOpcode() == BO_LAnd) != 15349 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15350 return RHSResult; 15351 return NoDiag(); 15352 } 15353 15354 return Worst(LHSResult, RHSResult); 15355 } 15356 } 15357 llvm_unreachable("invalid binary operator kind"); 15358 } 15359 case Expr::ImplicitCastExprClass: 15360 case Expr::CStyleCastExprClass: 15361 case Expr::CXXFunctionalCastExprClass: 15362 case Expr::CXXStaticCastExprClass: 15363 case Expr::CXXReinterpretCastExprClass: 15364 case Expr::CXXConstCastExprClass: 15365 case Expr::ObjCBridgedCastExprClass: { 15366 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15367 if (isa<ExplicitCastExpr>(E)) { 15368 if (const FloatingLiteral *FL 15369 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15370 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15371 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15372 APSInt IgnoredVal(DestWidth, !DestSigned); 15373 bool Ignored; 15374 // If the value does not fit in the destination type, the behavior is 15375 // undefined, so we are not required to treat it as a constant 15376 // expression. 15377 if (FL->getValue().convertToInteger(IgnoredVal, 15378 llvm::APFloat::rmTowardZero, 15379 &Ignored) & APFloat::opInvalidOp) 15380 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15381 return NoDiag(); 15382 } 15383 } 15384 switch (cast<CastExpr>(E)->getCastKind()) { 15385 case CK_LValueToRValue: 15386 case CK_AtomicToNonAtomic: 15387 case CK_NonAtomicToAtomic: 15388 case CK_NoOp: 15389 case CK_IntegralToBoolean: 15390 case CK_IntegralCast: 15391 return CheckICE(SubExpr, Ctx); 15392 default: 15393 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15394 } 15395 } 15396 case Expr::BinaryConditionalOperatorClass: { 15397 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15398 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15399 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15400 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15401 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15402 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15403 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15404 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15405 return FalseResult; 15406 } 15407 case Expr::ConditionalOperatorClass: { 15408 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15409 // If the condition (ignoring parens) is a __builtin_constant_p call, 15410 // then only the true side is actually considered in an integer constant 15411 // expression, and it is fully evaluated. This is an important GNU 15412 // extension. See GCC PR38377 for discussion. 15413 if (const CallExpr *CallCE 15414 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15415 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15416 return CheckEvalInICE(E, Ctx); 15417 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15418 if (CondResult.Kind == IK_NotICE) 15419 return CondResult; 15420 15421 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15422 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15423 15424 if (TrueResult.Kind == IK_NotICE) 15425 return TrueResult; 15426 if (FalseResult.Kind == IK_NotICE) 15427 return FalseResult; 15428 if (CondResult.Kind == IK_ICEIfUnevaluated) 15429 return CondResult; 15430 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15431 return NoDiag(); 15432 // Rare case where the diagnostics depend on which side is evaluated 15433 // Note that if we get here, CondResult is 0, and at least one of 15434 // TrueResult and FalseResult is non-zero. 15435 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15436 return FalseResult; 15437 return TrueResult; 15438 } 15439 case Expr::CXXDefaultArgExprClass: 15440 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15441 case Expr::CXXDefaultInitExprClass: 15442 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15443 case Expr::ChooseExprClass: { 15444 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15445 } 15446 case Expr::BuiltinBitCastExprClass: { 15447 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15448 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15449 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15450 } 15451 } 15452 15453 llvm_unreachable("Invalid StmtClass!"); 15454 } 15455 15456 /// Evaluate an expression as a C++11 integral constant expression. 15457 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15458 const Expr *E, 15459 llvm::APSInt *Value, 15460 SourceLocation *Loc) { 15461 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15462 if (Loc) *Loc = E->getExprLoc(); 15463 return false; 15464 } 15465 15466 APValue Result; 15467 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15468 return false; 15469 15470 if (!Result.isInt()) { 15471 if (Loc) *Loc = E->getExprLoc(); 15472 return false; 15473 } 15474 15475 if (Value) *Value = Result.getInt(); 15476 return true; 15477 } 15478 15479 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15480 SourceLocation *Loc) const { 15481 assert(!isValueDependent() && 15482 "Expression evaluator can't be called on a dependent expression."); 15483 15484 if (Ctx.getLangOpts().CPlusPlus11) 15485 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15486 15487 ICEDiag D = CheckICE(this, Ctx); 15488 if (D.Kind != IK_ICE) { 15489 if (Loc) *Loc = D.Loc; 15490 return false; 15491 } 15492 return true; 15493 } 15494 15495 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15496 SourceLocation *Loc, 15497 bool isEvaluated) const { 15498 assert(!isValueDependent() && 15499 "Expression evaluator can't be called on a dependent expression."); 15500 15501 APSInt Value; 15502 15503 if (Ctx.getLangOpts().CPlusPlus11) { 15504 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15505 return Value; 15506 return None; 15507 } 15508 15509 if (!isIntegerConstantExpr(Ctx, Loc)) 15510 return None; 15511 15512 // The only possible side-effects here are due to UB discovered in the 15513 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15514 // required to treat the expression as an ICE, so we produce the folded 15515 // value. 15516 EvalResult ExprResult; 15517 Expr::EvalStatus Status; 15518 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15519 Info.InConstantContext = true; 15520 15521 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15522 llvm_unreachable("ICE cannot be evaluated!"); 15523 15524 return ExprResult.Val.getInt(); 15525 } 15526 15527 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15528 assert(!isValueDependent() && 15529 "Expression evaluator can't be called on a dependent expression."); 15530 15531 return CheckICE(this, Ctx).Kind == IK_ICE; 15532 } 15533 15534 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15535 SourceLocation *Loc) const { 15536 assert(!isValueDependent() && 15537 "Expression evaluator can't be called on a dependent expression."); 15538 15539 // We support this checking in C++98 mode in order to diagnose compatibility 15540 // issues. 15541 assert(Ctx.getLangOpts().CPlusPlus); 15542 15543 // Build evaluation settings. 15544 Expr::EvalStatus Status; 15545 SmallVector<PartialDiagnosticAt, 8> Diags; 15546 Status.Diag = &Diags; 15547 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15548 15549 APValue Scratch; 15550 bool IsConstExpr = 15551 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15552 // FIXME: We don't produce a diagnostic for this, but the callers that 15553 // call us on arbitrary full-expressions should generally not care. 15554 Info.discardCleanups() && !Status.HasSideEffects; 15555 15556 if (!Diags.empty()) { 15557 IsConstExpr = false; 15558 if (Loc) *Loc = Diags[0].first; 15559 } else if (!IsConstExpr) { 15560 // FIXME: This shouldn't happen. 15561 if (Loc) *Loc = getExprLoc(); 15562 } 15563 15564 return IsConstExpr; 15565 } 15566 15567 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15568 const FunctionDecl *Callee, 15569 ArrayRef<const Expr*> Args, 15570 const Expr *This) const { 15571 assert(!isValueDependent() && 15572 "Expression evaluator can't be called on a dependent expression."); 15573 15574 Expr::EvalStatus Status; 15575 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15576 Info.InConstantContext = true; 15577 15578 LValue ThisVal; 15579 const LValue *ThisPtr = nullptr; 15580 if (This) { 15581 #ifndef NDEBUG 15582 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15583 assert(MD && "Don't provide `this` for non-methods."); 15584 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15585 #endif 15586 if (!This->isValueDependent() && 15587 EvaluateObjectArgument(Info, This, ThisVal) && 15588 !Info.EvalStatus.HasSideEffects) 15589 ThisPtr = &ThisVal; 15590 15591 // Ignore any side-effects from a failed evaluation. This is safe because 15592 // they can't interfere with any other argument evaluation. 15593 Info.EvalStatus.HasSideEffects = false; 15594 } 15595 15596 CallRef Call = Info.CurrentCall->createCall(Callee); 15597 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15598 I != E; ++I) { 15599 unsigned Idx = I - Args.begin(); 15600 if (Idx >= Callee->getNumParams()) 15601 break; 15602 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15603 if ((*I)->isValueDependent() || 15604 !EvaluateCallArg(PVD, *I, Call, Info) || 15605 Info.EvalStatus.HasSideEffects) { 15606 // If evaluation fails, throw away the argument entirely. 15607 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15608 *Slot = APValue(); 15609 } 15610 15611 // Ignore any side-effects from a failed evaluation. This is safe because 15612 // they can't interfere with any other argument evaluation. 15613 Info.EvalStatus.HasSideEffects = false; 15614 } 15615 15616 // Parameter cleanups happen in the caller and are not part of this 15617 // evaluation. 15618 Info.discardCleanups(); 15619 Info.EvalStatus.HasSideEffects = false; 15620 15621 // Build fake call to Callee. 15622 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15623 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15624 FullExpressionRAII Scope(Info); 15625 return Evaluate(Value, Info, this) && Scope.destroy() && 15626 !Info.EvalStatus.HasSideEffects; 15627 } 15628 15629 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15630 SmallVectorImpl< 15631 PartialDiagnosticAt> &Diags) { 15632 // FIXME: It would be useful to check constexpr function templates, but at the 15633 // moment the constant expression evaluator cannot cope with the non-rigorous 15634 // ASTs which we build for dependent expressions. 15635 if (FD->isDependentContext()) 15636 return true; 15637 15638 Expr::EvalStatus Status; 15639 Status.Diag = &Diags; 15640 15641 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15642 Info.InConstantContext = true; 15643 Info.CheckingPotentialConstantExpression = true; 15644 15645 // The constexpr VM attempts to compile all methods to bytecode here. 15646 if (Info.EnableNewConstInterp) { 15647 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15648 return Diags.empty(); 15649 } 15650 15651 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15652 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15653 15654 // Fabricate an arbitrary expression on the stack and pretend that it 15655 // is a temporary being used as the 'this' pointer. 15656 LValue This; 15657 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15658 This.set({&VIE, Info.CurrentCall->Index}); 15659 15660 ArrayRef<const Expr*> Args; 15661 15662 APValue Scratch; 15663 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15664 // Evaluate the call as a constant initializer, to allow the construction 15665 // of objects of non-literal types. 15666 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15667 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15668 } else { 15669 SourceLocation Loc = FD->getLocation(); 15670 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15671 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15672 } 15673 15674 return Diags.empty(); 15675 } 15676 15677 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15678 const FunctionDecl *FD, 15679 SmallVectorImpl< 15680 PartialDiagnosticAt> &Diags) { 15681 assert(!E->isValueDependent() && 15682 "Expression evaluator can't be called on a dependent expression."); 15683 15684 Expr::EvalStatus Status; 15685 Status.Diag = &Diags; 15686 15687 EvalInfo Info(FD->getASTContext(), Status, 15688 EvalInfo::EM_ConstantExpressionUnevaluated); 15689 Info.InConstantContext = true; 15690 Info.CheckingPotentialConstantExpression = true; 15691 15692 // Fabricate a call stack frame to give the arguments a plausible cover story. 15693 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15694 15695 APValue ResultScratch; 15696 Evaluate(ResultScratch, Info, E); 15697 return Diags.empty(); 15698 } 15699 15700 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15701 unsigned Type) const { 15702 if (!getType()->isPointerType()) 15703 return false; 15704 15705 Expr::EvalStatus Status; 15706 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15707 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15708 } 15709 15710 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 15711 EvalInfo &Info) { 15712 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 15713 return false; 15714 15715 LValue String; 15716 15717 if (!EvaluatePointer(E, String, Info)) 15718 return false; 15719 15720 QualType CharTy = E->getType()->getPointeeType(); 15721 15722 // Fast path: if it's a string literal, search the string value. 15723 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 15724 String.getLValueBase().dyn_cast<const Expr *>())) { 15725 StringRef Str = S->getBytes(); 15726 int64_t Off = String.Offset.getQuantity(); 15727 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 15728 S->getCharByteWidth() == 1 && 15729 // FIXME: Add fast-path for wchar_t too. 15730 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 15731 Str = Str.substr(Off); 15732 15733 StringRef::size_type Pos = Str.find(0); 15734 if (Pos != StringRef::npos) 15735 Str = Str.substr(0, Pos); 15736 15737 Result = Str.size(); 15738 return true; 15739 } 15740 15741 // Fall through to slow path. 15742 } 15743 15744 // Slow path: scan the bytes of the string looking for the terminating 0. 15745 for (uint64_t Strlen = 0; /**/; ++Strlen) { 15746 APValue Char; 15747 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 15748 !Char.isInt()) 15749 return false; 15750 if (!Char.getInt()) { 15751 Result = Strlen; 15752 return true; 15753 } 15754 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 15755 return false; 15756 } 15757 } 15758 15759 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 15760 Expr::EvalStatus Status; 15761 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15762 return EvaluateBuiltinStrLen(this, Result, Info); 15763 } 15764