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 ASTContext &getCtx() const override { return Ctx; } 987 988 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 989 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 990 EvaluatingDecl = Base; 991 IsEvaluatingDecl = EDK; 992 EvaluatingDeclValue = &Value; 993 } 994 995 bool CheckCallLimit(SourceLocation Loc) { 996 // Don't perform any constexpr calls (other than the call we're checking) 997 // when checking a potential constant expression. 998 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 999 return false; 1000 if (NextCallIndex == 0) { 1001 // NextCallIndex has wrapped around. 1002 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1003 return false; 1004 } 1005 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1006 return true; 1007 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1008 << getLangOpts().ConstexprCallDepth; 1009 return false; 1010 } 1011 1012 std::pair<CallStackFrame *, unsigned> 1013 getCallFrameAndDepth(unsigned CallIndex) { 1014 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1015 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1016 // be null in this loop. 1017 unsigned Depth = CallStackDepth; 1018 CallStackFrame *Frame = CurrentCall; 1019 while (Frame->Index > CallIndex) { 1020 Frame = Frame->Caller; 1021 --Depth; 1022 } 1023 if (Frame->Index == CallIndex) 1024 return {Frame, Depth}; 1025 return {nullptr, 0}; 1026 } 1027 1028 bool nextStep(const Stmt *S) { 1029 if (!StepsLeft) { 1030 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1031 return false; 1032 } 1033 --StepsLeft; 1034 return true; 1035 } 1036 1037 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1038 1039 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1040 Optional<DynAlloc*> Result; 1041 auto It = HeapAllocs.find(DA); 1042 if (It != HeapAllocs.end()) 1043 Result = &It->second; 1044 return Result; 1045 } 1046 1047 /// Get the allocated storage for the given parameter of the given call. 1048 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1049 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1050 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1051 : nullptr; 1052 } 1053 1054 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1055 struct StdAllocatorCaller { 1056 unsigned FrameIndex; 1057 QualType ElemType; 1058 explicit operator bool() const { return FrameIndex != 0; }; 1059 }; 1060 1061 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1062 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1063 Call = Call->Caller) { 1064 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1065 if (!MD) 1066 continue; 1067 const IdentifierInfo *FnII = MD->getIdentifier(); 1068 if (!FnII || !FnII->isStr(FnName)) 1069 continue; 1070 1071 const auto *CTSD = 1072 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1073 if (!CTSD) 1074 continue; 1075 1076 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1077 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1078 if (CTSD->isInStdNamespace() && ClassII && 1079 ClassII->isStr("allocator") && TAL.size() >= 1 && 1080 TAL[0].getKind() == TemplateArgument::Type) 1081 return {Call->Index, TAL[0].getAsType()}; 1082 } 1083 1084 return {}; 1085 } 1086 1087 void performLifetimeExtension() { 1088 // Disable the cleanups for lifetime-extended temporaries. 1089 llvm::erase_if(CleanupStack, [](Cleanup &C) { 1090 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); 1091 }); 1092 } 1093 1094 /// Throw away any remaining cleanups at the end of evaluation. If any 1095 /// cleanups would have had a side-effect, note that as an unmodeled 1096 /// side-effect and return false. Otherwise, return true. 1097 bool discardCleanups() { 1098 for (Cleanup &C : CleanupStack) { 1099 if (C.hasSideEffect() && !noteSideEffect()) { 1100 CleanupStack.clear(); 1101 return false; 1102 } 1103 } 1104 CleanupStack.clear(); 1105 return true; 1106 } 1107 1108 private: 1109 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1110 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1111 1112 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1113 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1114 1115 void setFoldFailureDiagnostic(bool Flag) override { 1116 HasFoldFailureDiagnostic = Flag; 1117 } 1118 1119 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1120 1121 // If we have a prior diagnostic, it will be noting that the expression 1122 // isn't a constant expression. This diagnostic is more important, 1123 // unless we require this evaluation to produce a constant expression. 1124 // 1125 // FIXME: We might want to show both diagnostics to the user in 1126 // EM_ConstantFold mode. 1127 bool hasPriorDiagnostic() override { 1128 if (!EvalStatus.Diag->empty()) { 1129 switch (EvalMode) { 1130 case EM_ConstantFold: 1131 case EM_IgnoreSideEffects: 1132 if (!HasFoldFailureDiagnostic) 1133 break; 1134 // We've already failed to fold something. Keep that diagnostic. 1135 LLVM_FALLTHROUGH; 1136 case EM_ConstantExpression: 1137 case EM_ConstantExpressionUnevaluated: 1138 setActiveDiagnostic(false); 1139 return true; 1140 } 1141 } 1142 return false; 1143 } 1144 1145 unsigned getCallStackDepth() override { return CallStackDepth; } 1146 1147 public: 1148 /// Should we continue evaluation after encountering a side-effect that we 1149 /// couldn't model? 1150 bool keepEvaluatingAfterSideEffect() { 1151 switch (EvalMode) { 1152 case EM_IgnoreSideEffects: 1153 return true; 1154 1155 case EM_ConstantExpression: 1156 case EM_ConstantExpressionUnevaluated: 1157 case EM_ConstantFold: 1158 // By default, assume any side effect might be valid in some other 1159 // evaluation of this expression from a different context. 1160 return checkingPotentialConstantExpression() || 1161 checkingForUndefinedBehavior(); 1162 } 1163 llvm_unreachable("Missed EvalMode case"); 1164 } 1165 1166 /// Note that we have had a side-effect, and determine whether we should 1167 /// keep evaluating. 1168 bool noteSideEffect() { 1169 EvalStatus.HasSideEffects = true; 1170 return keepEvaluatingAfterSideEffect(); 1171 } 1172 1173 /// Should we continue evaluation after encountering undefined behavior? 1174 bool keepEvaluatingAfterUndefinedBehavior() { 1175 switch (EvalMode) { 1176 case EM_IgnoreSideEffects: 1177 case EM_ConstantFold: 1178 return true; 1179 1180 case EM_ConstantExpression: 1181 case EM_ConstantExpressionUnevaluated: 1182 return checkingForUndefinedBehavior(); 1183 } 1184 llvm_unreachable("Missed EvalMode case"); 1185 } 1186 1187 /// Note that we hit something that was technically undefined behavior, but 1188 /// that we can evaluate past it (such as signed overflow or floating-point 1189 /// division by zero.) 1190 bool noteUndefinedBehavior() override { 1191 EvalStatus.HasUndefinedBehavior = true; 1192 return keepEvaluatingAfterUndefinedBehavior(); 1193 } 1194 1195 /// Should we continue evaluation as much as possible after encountering a 1196 /// construct which can't be reduced to a value? 1197 bool keepEvaluatingAfterFailure() const override { 1198 if (!StepsLeft) 1199 return false; 1200 1201 switch (EvalMode) { 1202 case EM_ConstantExpression: 1203 case EM_ConstantExpressionUnevaluated: 1204 case EM_ConstantFold: 1205 case EM_IgnoreSideEffects: 1206 return checkingPotentialConstantExpression() || 1207 checkingForUndefinedBehavior(); 1208 } 1209 llvm_unreachable("Missed EvalMode case"); 1210 } 1211 1212 /// Notes that we failed to evaluate an expression that other expressions 1213 /// directly depend on, and determine if we should keep evaluating. This 1214 /// should only be called if we actually intend to keep evaluating. 1215 /// 1216 /// Call noteSideEffect() instead if we may be able to ignore the value that 1217 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1218 /// 1219 /// (Foo(), 1) // use noteSideEffect 1220 /// (Foo() || true) // use noteSideEffect 1221 /// Foo() + 1 // use noteFailure 1222 LLVM_NODISCARD bool noteFailure() { 1223 // Failure when evaluating some expression often means there is some 1224 // subexpression whose evaluation was skipped. Therefore, (because we 1225 // don't track whether we skipped an expression when unwinding after an 1226 // evaluation failure) every evaluation failure that bubbles up from a 1227 // subexpression implies that a side-effect has potentially happened. We 1228 // skip setting the HasSideEffects flag to true until we decide to 1229 // continue evaluating after that point, which happens here. 1230 bool KeepGoing = keepEvaluatingAfterFailure(); 1231 EvalStatus.HasSideEffects |= KeepGoing; 1232 return KeepGoing; 1233 } 1234 1235 class ArrayInitLoopIndex { 1236 EvalInfo &Info; 1237 uint64_t OuterIndex; 1238 1239 public: 1240 ArrayInitLoopIndex(EvalInfo &Info) 1241 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1242 Info.ArrayInitIndex = 0; 1243 } 1244 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1245 1246 operator uint64_t&() { return Info.ArrayInitIndex; } 1247 }; 1248 }; 1249 1250 /// Object used to treat all foldable expressions as constant expressions. 1251 struct FoldConstant { 1252 EvalInfo &Info; 1253 bool Enabled; 1254 bool HadNoPriorDiags; 1255 EvalInfo::EvaluationMode OldMode; 1256 1257 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1258 : Info(Info), 1259 Enabled(Enabled), 1260 HadNoPriorDiags(Info.EvalStatus.Diag && 1261 Info.EvalStatus.Diag->empty() && 1262 !Info.EvalStatus.HasSideEffects), 1263 OldMode(Info.EvalMode) { 1264 if (Enabled) 1265 Info.EvalMode = EvalInfo::EM_ConstantFold; 1266 } 1267 void keepDiagnostics() { Enabled = false; } 1268 ~FoldConstant() { 1269 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1270 !Info.EvalStatus.HasSideEffects) 1271 Info.EvalStatus.Diag->clear(); 1272 Info.EvalMode = OldMode; 1273 } 1274 }; 1275 1276 /// RAII object used to set the current evaluation mode to ignore 1277 /// side-effects. 1278 struct IgnoreSideEffectsRAII { 1279 EvalInfo &Info; 1280 EvalInfo::EvaluationMode OldMode; 1281 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1282 : Info(Info), OldMode(Info.EvalMode) { 1283 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1284 } 1285 1286 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1287 }; 1288 1289 /// RAII object used to optionally suppress diagnostics and side-effects from 1290 /// a speculative evaluation. 1291 class SpeculativeEvaluationRAII { 1292 EvalInfo *Info = nullptr; 1293 Expr::EvalStatus OldStatus; 1294 unsigned OldSpeculativeEvaluationDepth; 1295 1296 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1297 Info = Other.Info; 1298 OldStatus = Other.OldStatus; 1299 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1300 Other.Info = nullptr; 1301 } 1302 1303 void maybeRestoreState() { 1304 if (!Info) 1305 return; 1306 1307 Info->EvalStatus = OldStatus; 1308 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1309 } 1310 1311 public: 1312 SpeculativeEvaluationRAII() = default; 1313 1314 SpeculativeEvaluationRAII( 1315 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1316 : Info(&Info), OldStatus(Info.EvalStatus), 1317 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1318 Info.EvalStatus.Diag = NewDiag; 1319 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1320 } 1321 1322 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1323 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1324 moveFromAndCancel(std::move(Other)); 1325 } 1326 1327 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1328 maybeRestoreState(); 1329 moveFromAndCancel(std::move(Other)); 1330 return *this; 1331 } 1332 1333 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1334 }; 1335 1336 /// RAII object wrapping a full-expression or block scope, and handling 1337 /// the ending of the lifetime of temporaries created within it. 1338 template<ScopeKind Kind> 1339 class ScopeRAII { 1340 EvalInfo &Info; 1341 unsigned OldStackSize; 1342 public: 1343 ScopeRAII(EvalInfo &Info) 1344 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1345 // Push a new temporary version. This is needed to distinguish between 1346 // temporaries created in different iterations of a loop. 1347 Info.CurrentCall->pushTempVersion(); 1348 } 1349 bool destroy(bool RunDestructors = true) { 1350 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1351 OldStackSize = -1U; 1352 return OK; 1353 } 1354 ~ScopeRAII() { 1355 if (OldStackSize != -1U) 1356 destroy(false); 1357 // Body moved to a static method to encourage the compiler to inline away 1358 // instances of this class. 1359 Info.CurrentCall->popTempVersion(); 1360 } 1361 private: 1362 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1363 unsigned OldStackSize) { 1364 assert(OldStackSize <= Info.CleanupStack.size() && 1365 "running cleanups out of order?"); 1366 1367 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1368 // for a full-expression scope. 1369 bool Success = true; 1370 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1371 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1372 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1373 Success = false; 1374 break; 1375 } 1376 } 1377 } 1378 1379 // Compact any retained cleanups. 1380 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1381 if (Kind != ScopeKind::Block) 1382 NewEnd = 1383 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1384 return C.isDestroyedAtEndOf(Kind); 1385 }); 1386 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1387 return Success; 1388 } 1389 }; 1390 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1391 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1392 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1393 } 1394 1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1396 CheckSubobjectKind CSK) { 1397 if (Invalid) 1398 return false; 1399 if (isOnePastTheEnd()) { 1400 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1401 << CSK; 1402 setInvalid(); 1403 return false; 1404 } 1405 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1406 // must actually be at least one array element; even a VLA cannot have a 1407 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1408 return true; 1409 } 1410 1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1412 const Expr *E) { 1413 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1414 // Do not set the designator as invalid: we can represent this situation, 1415 // and correct handling of __builtin_object_size requires us to do so. 1416 } 1417 1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1419 const Expr *E, 1420 const APSInt &N) { 1421 // If we're complaining, we must be able to statically determine the size of 1422 // the most derived array. 1423 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1424 Info.CCEDiag(E, diag::note_constexpr_array_index) 1425 << N << /*array*/ 0 1426 << static_cast<unsigned>(getMostDerivedArraySize()); 1427 else 1428 Info.CCEDiag(E, diag::note_constexpr_array_index) 1429 << N << /*non-array*/ 1; 1430 setInvalid(); 1431 } 1432 1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1434 const FunctionDecl *Callee, const LValue *This, 1435 CallRef Call) 1436 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1437 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1438 Info.CurrentCall = this; 1439 ++Info.CallStackDepth; 1440 } 1441 1442 CallStackFrame::~CallStackFrame() { 1443 assert(Info.CurrentCall == this && "calls retired out of order"); 1444 --Info.CallStackDepth; 1445 Info.CurrentCall = Caller; 1446 } 1447 1448 static bool isRead(AccessKinds AK) { 1449 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1450 } 1451 1452 static bool isModification(AccessKinds AK) { 1453 switch (AK) { 1454 case AK_Read: 1455 case AK_ReadObjectRepresentation: 1456 case AK_MemberCall: 1457 case AK_DynamicCast: 1458 case AK_TypeId: 1459 return false; 1460 case AK_Assign: 1461 case AK_Increment: 1462 case AK_Decrement: 1463 case AK_Construct: 1464 case AK_Destroy: 1465 return true; 1466 } 1467 llvm_unreachable("unknown access kind"); 1468 } 1469 1470 static bool isAnyAccess(AccessKinds AK) { 1471 return isRead(AK) || isModification(AK); 1472 } 1473 1474 /// Is this an access per the C++ definition? 1475 static bool isFormalAccess(AccessKinds AK) { 1476 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1477 } 1478 1479 /// Is this kind of axcess valid on an indeterminate object value? 1480 static bool isValidIndeterminateAccess(AccessKinds AK) { 1481 switch (AK) { 1482 case AK_Read: 1483 case AK_Increment: 1484 case AK_Decrement: 1485 // These need the object's value. 1486 return false; 1487 1488 case AK_ReadObjectRepresentation: 1489 case AK_Assign: 1490 case AK_Construct: 1491 case AK_Destroy: 1492 // Construction and destruction don't need the value. 1493 return true; 1494 1495 case AK_MemberCall: 1496 case AK_DynamicCast: 1497 case AK_TypeId: 1498 // These aren't really meaningful on scalars. 1499 return true; 1500 } 1501 llvm_unreachable("unknown access kind"); 1502 } 1503 1504 namespace { 1505 struct ComplexValue { 1506 private: 1507 bool IsInt; 1508 1509 public: 1510 APSInt IntReal, IntImag; 1511 APFloat FloatReal, FloatImag; 1512 1513 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1514 1515 void makeComplexFloat() { IsInt = false; } 1516 bool isComplexFloat() const { return !IsInt; } 1517 APFloat &getComplexFloatReal() { return FloatReal; } 1518 APFloat &getComplexFloatImag() { return FloatImag; } 1519 1520 void makeComplexInt() { IsInt = true; } 1521 bool isComplexInt() const { return IsInt; } 1522 APSInt &getComplexIntReal() { return IntReal; } 1523 APSInt &getComplexIntImag() { return IntImag; } 1524 1525 void moveInto(APValue &v) const { 1526 if (isComplexFloat()) 1527 v = APValue(FloatReal, FloatImag); 1528 else 1529 v = APValue(IntReal, IntImag); 1530 } 1531 void setFrom(const APValue &v) { 1532 assert(v.isComplexFloat() || v.isComplexInt()); 1533 if (v.isComplexFloat()) { 1534 makeComplexFloat(); 1535 FloatReal = v.getComplexFloatReal(); 1536 FloatImag = v.getComplexFloatImag(); 1537 } else { 1538 makeComplexInt(); 1539 IntReal = v.getComplexIntReal(); 1540 IntImag = v.getComplexIntImag(); 1541 } 1542 } 1543 }; 1544 1545 struct LValue { 1546 APValue::LValueBase Base; 1547 CharUnits Offset; 1548 SubobjectDesignator Designator; 1549 bool IsNullPtr : 1; 1550 bool InvalidBase : 1; 1551 1552 const APValue::LValueBase getLValueBase() const { return Base; } 1553 CharUnits &getLValueOffset() { return Offset; } 1554 const CharUnits &getLValueOffset() const { return Offset; } 1555 SubobjectDesignator &getLValueDesignator() { return Designator; } 1556 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1557 bool isNullPointer() const { return IsNullPtr;} 1558 1559 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1560 unsigned getLValueVersion() const { return Base.getVersion(); } 1561 1562 void moveInto(APValue &V) const { 1563 if (Designator.Invalid) 1564 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1565 else { 1566 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1567 V = APValue(Base, Offset, Designator.Entries, 1568 Designator.IsOnePastTheEnd, IsNullPtr); 1569 } 1570 } 1571 void setFrom(ASTContext &Ctx, const APValue &V) { 1572 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1573 Base = V.getLValueBase(); 1574 Offset = V.getLValueOffset(); 1575 InvalidBase = false; 1576 Designator = SubobjectDesignator(Ctx, V); 1577 IsNullPtr = V.isNullPointer(); 1578 } 1579 1580 void set(APValue::LValueBase B, bool BInvalid = false) { 1581 #ifndef NDEBUG 1582 // We only allow a few types of invalid bases. Enforce that here. 1583 if (BInvalid) { 1584 const auto *E = B.get<const Expr *>(); 1585 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1586 "Unexpected type of invalid base"); 1587 } 1588 #endif 1589 1590 Base = B; 1591 Offset = CharUnits::fromQuantity(0); 1592 InvalidBase = BInvalid; 1593 Designator = SubobjectDesignator(getType(B)); 1594 IsNullPtr = false; 1595 } 1596 1597 void setNull(ASTContext &Ctx, QualType PointerTy) { 1598 Base = (const ValueDecl *)nullptr; 1599 Offset = 1600 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1601 InvalidBase = false; 1602 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1603 IsNullPtr = true; 1604 } 1605 1606 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1607 set(B, true); 1608 } 1609 1610 std::string toString(ASTContext &Ctx, QualType T) const { 1611 APValue Printable; 1612 moveInto(Printable); 1613 return Printable.getAsString(Ctx, T); 1614 } 1615 1616 private: 1617 // Check that this LValue is not based on a null pointer. If it is, produce 1618 // a diagnostic and mark the designator as invalid. 1619 template <typename GenDiagType> 1620 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1621 if (Designator.Invalid) 1622 return false; 1623 if (IsNullPtr) { 1624 GenDiag(); 1625 Designator.setInvalid(); 1626 return false; 1627 } 1628 return true; 1629 } 1630 1631 public: 1632 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1633 CheckSubobjectKind CSK) { 1634 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1635 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1636 }); 1637 } 1638 1639 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1640 AccessKinds AK) { 1641 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1642 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1643 }); 1644 } 1645 1646 // Check this LValue refers to an object. If not, set the designator to be 1647 // invalid and emit a diagnostic. 1648 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1649 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1650 Designator.checkSubobject(Info, E, CSK); 1651 } 1652 1653 void addDecl(EvalInfo &Info, const Expr *E, 1654 const Decl *D, bool Virtual = false) { 1655 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1656 Designator.addDeclUnchecked(D, Virtual); 1657 } 1658 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1659 if (!Designator.Entries.empty()) { 1660 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1661 Designator.setInvalid(); 1662 return; 1663 } 1664 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1665 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1666 Designator.FirstEntryIsAnUnsizedArray = true; 1667 Designator.addUnsizedArrayUnchecked(ElemTy); 1668 } 1669 } 1670 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1671 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1672 Designator.addArrayUnchecked(CAT); 1673 } 1674 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1675 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1676 Designator.addComplexUnchecked(EltTy, Imag); 1677 } 1678 void clearIsNullPointer() { 1679 IsNullPtr = false; 1680 } 1681 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1682 const APSInt &Index, CharUnits ElementSize) { 1683 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1684 // but we're not required to diagnose it and it's valid in C++.) 1685 if (!Index) 1686 return; 1687 1688 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1689 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1690 // offsets. 1691 uint64_t Offset64 = Offset.getQuantity(); 1692 uint64_t ElemSize64 = ElementSize.getQuantity(); 1693 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1694 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1695 1696 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1697 Designator.adjustIndex(Info, E, Index); 1698 clearIsNullPointer(); 1699 } 1700 void adjustOffset(CharUnits N) { 1701 Offset += N; 1702 if (N.getQuantity()) 1703 clearIsNullPointer(); 1704 } 1705 }; 1706 1707 struct MemberPtr { 1708 MemberPtr() {} 1709 explicit MemberPtr(const ValueDecl *Decl) 1710 : DeclAndIsDerivedMember(Decl, false) {} 1711 1712 /// The member or (direct or indirect) field referred to by this member 1713 /// pointer, or 0 if this is a null member pointer. 1714 const ValueDecl *getDecl() const { 1715 return DeclAndIsDerivedMember.getPointer(); 1716 } 1717 /// Is this actually a member of some type derived from the relevant class? 1718 bool isDerivedMember() const { 1719 return DeclAndIsDerivedMember.getInt(); 1720 } 1721 /// Get the class which the declaration actually lives in. 1722 const CXXRecordDecl *getContainingRecord() const { 1723 return cast<CXXRecordDecl>( 1724 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1725 } 1726 1727 void moveInto(APValue &V) const { 1728 V = APValue(getDecl(), isDerivedMember(), Path); 1729 } 1730 void setFrom(const APValue &V) { 1731 assert(V.isMemberPointer()); 1732 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1733 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1734 Path.clear(); 1735 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1736 Path.insert(Path.end(), P.begin(), P.end()); 1737 } 1738 1739 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1740 /// whether the member is a member of some class derived from the class type 1741 /// of the member pointer. 1742 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1743 /// Path - The path of base/derived classes from the member declaration's 1744 /// class (exclusive) to the class type of the member pointer (inclusive). 1745 SmallVector<const CXXRecordDecl*, 4> Path; 1746 1747 /// Perform a cast towards the class of the Decl (either up or down the 1748 /// hierarchy). 1749 bool castBack(const CXXRecordDecl *Class) { 1750 assert(!Path.empty()); 1751 const CXXRecordDecl *Expected; 1752 if (Path.size() >= 2) 1753 Expected = Path[Path.size() - 2]; 1754 else 1755 Expected = getContainingRecord(); 1756 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1757 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1758 // if B does not contain the original member and is not a base or 1759 // derived class of the class containing the original member, the result 1760 // of the cast is undefined. 1761 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1762 // (D::*). We consider that to be a language defect. 1763 return false; 1764 } 1765 Path.pop_back(); 1766 return true; 1767 } 1768 /// Perform a base-to-derived member pointer cast. 1769 bool castToDerived(const CXXRecordDecl *Derived) { 1770 if (!getDecl()) 1771 return true; 1772 if (!isDerivedMember()) { 1773 Path.push_back(Derived); 1774 return true; 1775 } 1776 if (!castBack(Derived)) 1777 return false; 1778 if (Path.empty()) 1779 DeclAndIsDerivedMember.setInt(false); 1780 return true; 1781 } 1782 /// Perform a derived-to-base member pointer cast. 1783 bool castToBase(const CXXRecordDecl *Base) { 1784 if (!getDecl()) 1785 return true; 1786 if (Path.empty()) 1787 DeclAndIsDerivedMember.setInt(true); 1788 if (isDerivedMember()) { 1789 Path.push_back(Base); 1790 return true; 1791 } 1792 return castBack(Base); 1793 } 1794 }; 1795 1796 /// Compare two member pointers, which are assumed to be of the same type. 1797 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1798 if (!LHS.getDecl() || !RHS.getDecl()) 1799 return !LHS.getDecl() && !RHS.getDecl(); 1800 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1801 return false; 1802 return LHS.Path == RHS.Path; 1803 } 1804 } 1805 1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1808 const LValue &This, const Expr *E, 1809 bool AllowNonLiteralTypes = false); 1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1811 bool InvalidBaseOK = false); 1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1813 bool InvalidBaseOK = false); 1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1815 EvalInfo &Info); 1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1819 EvalInfo &Info); 1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1823 EvalInfo &Info); 1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 1826 EvalInfo &Info); 1827 1828 /// Evaluate an integer or fixed point expression into an APResult. 1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1830 EvalInfo &Info); 1831 1832 /// Evaluate only a fixed point expression into an APResult. 1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1834 EvalInfo &Info); 1835 1836 //===----------------------------------------------------------------------===// 1837 // Misc utilities 1838 //===----------------------------------------------------------------------===// 1839 1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1841 /// preserving its value (by extending by up to one bit as needed). 1842 static void negateAsSigned(APSInt &Int) { 1843 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1844 Int = Int.extend(Int.getBitWidth() + 1); 1845 Int.setIsSigned(true); 1846 } 1847 Int = -Int; 1848 } 1849 1850 template<typename KeyT> 1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1852 ScopeKind Scope, LValue &LV) { 1853 unsigned Version = getTempVersion(); 1854 APValue::LValueBase Base(Key, Index, Version); 1855 LV.set(Base); 1856 return createLocal(Base, Key, T, Scope); 1857 } 1858 1859 /// Allocate storage for a parameter of a function call made in this frame. 1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1861 LValue &LV) { 1862 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1863 APValue::LValueBase Base(PVD, Index, Args.Version); 1864 LV.set(Base); 1865 // We always destroy parameters at the end of the call, even if we'd allow 1866 // them to live to the end of the full-expression at runtime, in order to 1867 // give portable results and match other compilers. 1868 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1869 } 1870 1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1872 QualType T, ScopeKind Scope) { 1873 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1874 unsigned Version = Base.getVersion(); 1875 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1876 assert(Result.isAbsent() && "local created multiple times"); 1877 1878 // If we're creating a local immediately in the operand of a speculative 1879 // evaluation, don't register a cleanup to be run outside the speculative 1880 // evaluation context, since we won't actually be able to initialize this 1881 // object. 1882 if (Index <= Info.SpeculativeEvaluationDepth) { 1883 if (T.isDestructedType()) 1884 Info.noteSideEffect(); 1885 } else { 1886 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1887 } 1888 return Result; 1889 } 1890 1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1892 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1893 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1894 return nullptr; 1895 } 1896 1897 DynamicAllocLValue DA(NumHeapAllocs++); 1898 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1899 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1900 std::forward_as_tuple(DA), std::tuple<>()); 1901 assert(Result.second && "reused a heap alloc index?"); 1902 Result.first->second.AllocExpr = E; 1903 return &Result.first->second.Value; 1904 } 1905 1906 /// Produce a string describing the given constexpr call. 1907 void CallStackFrame::describe(raw_ostream &Out) { 1908 unsigned ArgIndex = 0; 1909 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1910 !isa<CXXConstructorDecl>(Callee) && 1911 cast<CXXMethodDecl>(Callee)->isInstance(); 1912 1913 if (!IsMemberCall) 1914 Out << *Callee << '('; 1915 1916 if (This && IsMemberCall) { 1917 APValue Val; 1918 This->moveInto(Val); 1919 Val.printPretty(Out, Info.Ctx, 1920 This->Designator.MostDerivedType); 1921 // FIXME: Add parens around Val if needed. 1922 Out << "->" << *Callee << '('; 1923 IsMemberCall = false; 1924 } 1925 1926 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1927 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1928 if (ArgIndex > (unsigned)IsMemberCall) 1929 Out << ", "; 1930 1931 const ParmVarDecl *Param = *I; 1932 APValue *V = Info.getParamSlot(Arguments, Param); 1933 if (V) 1934 V->printPretty(Out, Info.Ctx, Param->getType()); 1935 else 1936 Out << "<...>"; 1937 1938 if (ArgIndex == 0 && IsMemberCall) 1939 Out << "->" << *Callee << '('; 1940 } 1941 1942 Out << ')'; 1943 } 1944 1945 /// Evaluate an expression to see if it had side-effects, and discard its 1946 /// result. 1947 /// \return \c true if the caller should keep evaluating. 1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1949 assert(!E->isValueDependent()); 1950 APValue Scratch; 1951 if (!Evaluate(Scratch, Info, E)) 1952 // We don't need the value, but we might have skipped a side effect here. 1953 return Info.noteSideEffect(); 1954 return true; 1955 } 1956 1957 /// Should this call expression be treated as a constant? 1958 static bool IsConstantCall(const CallExpr *E) { 1959 unsigned Builtin = E->getBuiltinCallee(); 1960 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1961 Builtin == Builtin::BI__builtin___NSStringMakeConstantString || 1962 Builtin == Builtin::BI__builtin_function_start); 1963 } 1964 1965 static bool IsGlobalLValue(APValue::LValueBase B) { 1966 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1967 // constant expression of pointer type that evaluates to... 1968 1969 // ... a null pointer value, or a prvalue core constant expression of type 1970 // std::nullptr_t. 1971 if (!B) return true; 1972 1973 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1974 // ... the address of an object with static storage duration, 1975 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1976 return VD->hasGlobalStorage(); 1977 if (isa<TemplateParamObjectDecl>(D)) 1978 return true; 1979 // ... the address of a function, 1980 // ... the address of a GUID [MS extension], 1981 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1982 } 1983 1984 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1985 return true; 1986 1987 const Expr *E = B.get<const Expr*>(); 1988 switch (E->getStmtClass()) { 1989 default: 1990 return false; 1991 case Expr::CompoundLiteralExprClass: { 1992 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1993 return CLE->isFileScope() && CLE->isLValue(); 1994 } 1995 case Expr::MaterializeTemporaryExprClass: 1996 // A materialized temporary might have been lifetime-extended to static 1997 // storage duration. 1998 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1999 // A string literal has static storage duration. 2000 case Expr::StringLiteralClass: 2001 case Expr::PredefinedExprClass: 2002 case Expr::ObjCStringLiteralClass: 2003 case Expr::ObjCEncodeExprClass: 2004 return true; 2005 case Expr::ObjCBoxedExprClass: 2006 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2007 case Expr::CallExprClass: 2008 return IsConstantCall(cast<CallExpr>(E)); 2009 // For GCC compatibility, &&label has static storage duration. 2010 case Expr::AddrLabelExprClass: 2011 return true; 2012 // A Block literal expression may be used as the initialization value for 2013 // Block variables at global or local static scope. 2014 case Expr::BlockExprClass: 2015 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2016 case Expr::ImplicitValueInitExprClass: 2017 // FIXME: 2018 // We can never form an lvalue with an implicit value initialization as its 2019 // base through expression evaluation, so these only appear in one case: the 2020 // implicit variable declaration we invent when checking whether a constexpr 2021 // constructor can produce a constant expression. We must assume that such 2022 // an expression might be a global lvalue. 2023 return true; 2024 } 2025 } 2026 2027 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2028 return LVal.Base.dyn_cast<const ValueDecl*>(); 2029 } 2030 2031 static bool IsLiteralLValue(const LValue &Value) { 2032 if (Value.getLValueCallIndex()) 2033 return false; 2034 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2035 return E && !isa<MaterializeTemporaryExpr>(E); 2036 } 2037 2038 static bool IsWeakLValue(const LValue &Value) { 2039 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2040 return Decl && Decl->isWeak(); 2041 } 2042 2043 static bool isZeroSized(const LValue &Value) { 2044 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2045 if (Decl && isa<VarDecl>(Decl)) { 2046 QualType Ty = Decl->getType(); 2047 if (Ty->isArrayType()) 2048 return Ty->isIncompleteType() || 2049 Decl->getASTContext().getTypeSize(Ty) == 0; 2050 } 2051 return false; 2052 } 2053 2054 static bool HasSameBase(const LValue &A, const LValue &B) { 2055 if (!A.getLValueBase()) 2056 return !B.getLValueBase(); 2057 if (!B.getLValueBase()) 2058 return false; 2059 2060 if (A.getLValueBase().getOpaqueValue() != 2061 B.getLValueBase().getOpaqueValue()) 2062 return false; 2063 2064 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2065 A.getLValueVersion() == B.getLValueVersion(); 2066 } 2067 2068 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2069 assert(Base && "no location for a null lvalue"); 2070 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2071 2072 // For a parameter, find the corresponding call stack frame (if it still 2073 // exists), and point at the parameter of the function definition we actually 2074 // invoked. 2075 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2076 unsigned Idx = PVD->getFunctionScopeIndex(); 2077 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2078 if (F->Arguments.CallIndex == Base.getCallIndex() && 2079 F->Arguments.Version == Base.getVersion() && F->Callee && 2080 Idx < F->Callee->getNumParams()) { 2081 VD = F->Callee->getParamDecl(Idx); 2082 break; 2083 } 2084 } 2085 } 2086 2087 if (VD) 2088 Info.Note(VD->getLocation(), diag::note_declared_at); 2089 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2090 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2091 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2092 // FIXME: Produce a note for dangling pointers too. 2093 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2094 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2095 diag::note_constexpr_dynamic_alloc_here); 2096 } 2097 // We have no information to show for a typeid(T) object. 2098 } 2099 2100 enum class CheckEvaluationResultKind { 2101 ConstantExpression, 2102 FullyInitialized, 2103 }; 2104 2105 /// Materialized temporaries that we've already checked to determine if they're 2106 /// initializsed by a constant expression. 2107 using CheckedTemporaries = 2108 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2109 2110 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2111 EvalInfo &Info, SourceLocation DiagLoc, 2112 QualType Type, const APValue &Value, 2113 ConstantExprKind Kind, 2114 SourceLocation SubobjectLoc, 2115 CheckedTemporaries &CheckedTemps); 2116 2117 /// Check that this reference or pointer core constant expression is a valid 2118 /// value for an address or reference constant expression. Return true if we 2119 /// can fold this expression, whether or not it's a constant expression. 2120 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2121 QualType Type, const LValue &LVal, 2122 ConstantExprKind Kind, 2123 CheckedTemporaries &CheckedTemps) { 2124 bool IsReferenceType = Type->isReferenceType(); 2125 2126 APValue::LValueBase Base = LVal.getLValueBase(); 2127 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2128 2129 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2130 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2131 2132 // Additional restrictions apply in a template argument. We only enforce the 2133 // C++20 restrictions here; additional syntactic and semantic restrictions 2134 // are applied elsewhere. 2135 if (isTemplateArgument(Kind)) { 2136 int InvalidBaseKind = -1; 2137 StringRef Ident; 2138 if (Base.is<TypeInfoLValue>()) 2139 InvalidBaseKind = 0; 2140 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2141 InvalidBaseKind = 1; 2142 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2143 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2144 InvalidBaseKind = 2; 2145 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2146 InvalidBaseKind = 3; 2147 Ident = PE->getIdentKindName(); 2148 } 2149 2150 if (InvalidBaseKind != -1) { 2151 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2152 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2153 << Ident; 2154 return false; 2155 } 2156 } 2157 2158 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2159 if (FD->isConsteval()) { 2160 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2161 << !Type->isAnyPointerType(); 2162 Info.Note(FD->getLocation(), diag::note_declared_at); 2163 return false; 2164 } 2165 } 2166 2167 // Check that the object is a global. Note that the fake 'this' object we 2168 // manufacture when checking potential constant expressions is conservatively 2169 // assumed to be global here. 2170 if (!IsGlobalLValue(Base)) { 2171 if (Info.getLangOpts().CPlusPlus11) { 2172 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2173 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2174 << IsReferenceType << !Designator.Entries.empty() 2175 << !!VD << VD; 2176 2177 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2178 if (VarD && VarD->isConstexpr()) { 2179 // Non-static local constexpr variables have unintuitive semantics: 2180 // constexpr int a = 1; 2181 // constexpr const int *p = &a; 2182 // ... is invalid because the address of 'a' is not constant. Suggest 2183 // adding a 'static' in this case. 2184 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2185 << VarD 2186 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2187 } else { 2188 NoteLValueLocation(Info, Base); 2189 } 2190 } else { 2191 Info.FFDiag(Loc); 2192 } 2193 // Don't allow references to temporaries to escape. 2194 return false; 2195 } 2196 assert((Info.checkingPotentialConstantExpression() || 2197 LVal.getLValueCallIndex() == 0) && 2198 "have call index for global lvalue"); 2199 2200 if (Base.is<DynamicAllocLValue>()) { 2201 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2202 << IsReferenceType << !Designator.Entries.empty(); 2203 NoteLValueLocation(Info, Base); 2204 return false; 2205 } 2206 2207 if (BaseVD) { 2208 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2209 // Check if this is a thread-local variable. 2210 if (Var->getTLSKind()) 2211 // FIXME: Diagnostic! 2212 return false; 2213 2214 // A dllimport variable never acts like a constant, unless we're 2215 // evaluating a value for use only in name mangling. 2216 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2217 // FIXME: Diagnostic! 2218 return false; 2219 2220 // In CUDA/HIP device compilation, only device side variables have 2221 // constant addresses. 2222 if (Info.getCtx().getLangOpts().CUDA && 2223 Info.getCtx().getLangOpts().CUDAIsDevice && 2224 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) { 2225 if ((!Var->hasAttr<CUDADeviceAttr>() && 2226 !Var->hasAttr<CUDAConstantAttr>() && 2227 !Var->getType()->isCUDADeviceBuiltinSurfaceType() && 2228 !Var->getType()->isCUDADeviceBuiltinTextureType()) || 2229 Var->hasAttr<HIPManagedAttr>()) 2230 return false; 2231 } 2232 } 2233 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2234 // __declspec(dllimport) must be handled very carefully: 2235 // We must never initialize an expression with the thunk in C++. 2236 // Doing otherwise would allow the same id-expression to yield 2237 // different addresses for the same function in different translation 2238 // units. However, this means that we must dynamically initialize the 2239 // expression with the contents of the import address table at runtime. 2240 // 2241 // The C language has no notion of ODR; furthermore, it has no notion of 2242 // dynamic initialization. This means that we are permitted to 2243 // perform initialization with the address of the thunk. 2244 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2245 FD->hasAttr<DLLImportAttr>()) 2246 // FIXME: Diagnostic! 2247 return false; 2248 } 2249 } else if (const auto *MTE = 2250 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2251 if (CheckedTemps.insert(MTE).second) { 2252 QualType TempType = getType(Base); 2253 if (TempType.isDestructedType()) { 2254 Info.FFDiag(MTE->getExprLoc(), 2255 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2256 << TempType; 2257 return false; 2258 } 2259 2260 APValue *V = MTE->getOrCreateValue(false); 2261 assert(V && "evasluation result refers to uninitialised temporary"); 2262 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2263 Info, MTE->getExprLoc(), TempType, *V, 2264 Kind, SourceLocation(), CheckedTemps)) 2265 return false; 2266 } 2267 } 2268 2269 // Allow address constant expressions to be past-the-end pointers. This is 2270 // an extension: the standard requires them to point to an object. 2271 if (!IsReferenceType) 2272 return true; 2273 2274 // A reference constant expression must refer to an object. 2275 if (!Base) { 2276 // FIXME: diagnostic 2277 Info.CCEDiag(Loc); 2278 return true; 2279 } 2280 2281 // Does this refer one past the end of some object? 2282 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2283 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2284 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2285 NoteLValueLocation(Info, Base); 2286 } 2287 2288 return true; 2289 } 2290 2291 /// Member pointers are constant expressions unless they point to a 2292 /// non-virtual dllimport member function. 2293 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2294 SourceLocation Loc, 2295 QualType Type, 2296 const APValue &Value, 2297 ConstantExprKind Kind) { 2298 const ValueDecl *Member = Value.getMemberPointerDecl(); 2299 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2300 if (!FD) 2301 return true; 2302 if (FD->isConsteval()) { 2303 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2304 Info.Note(FD->getLocation(), diag::note_declared_at); 2305 return false; 2306 } 2307 return isForManglingOnly(Kind) || FD->isVirtual() || 2308 !FD->hasAttr<DLLImportAttr>(); 2309 } 2310 2311 /// Check that this core constant expression is of literal type, and if not, 2312 /// produce an appropriate diagnostic. 2313 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2314 const LValue *This = nullptr) { 2315 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2316 return true; 2317 2318 // C++1y: A constant initializer for an object o [...] may also invoke 2319 // constexpr constructors for o and its subobjects even if those objects 2320 // are of non-literal class types. 2321 // 2322 // C++11 missed this detail for aggregates, so classes like this: 2323 // struct foo_t { union { int i; volatile int j; } u; }; 2324 // are not (obviously) initializable like so: 2325 // __attribute__((__require_constant_initialization__)) 2326 // static const foo_t x = {{0}}; 2327 // because "i" is a subobject with non-literal initialization (due to the 2328 // volatile member of the union). See: 2329 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2330 // Therefore, we use the C++1y behavior. 2331 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2332 return true; 2333 2334 // Prvalue constant expressions must be of literal types. 2335 if (Info.getLangOpts().CPlusPlus11) 2336 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2337 << E->getType(); 2338 else 2339 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2340 return false; 2341 } 2342 2343 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2344 EvalInfo &Info, SourceLocation DiagLoc, 2345 QualType Type, const APValue &Value, 2346 ConstantExprKind Kind, 2347 SourceLocation SubobjectLoc, 2348 CheckedTemporaries &CheckedTemps) { 2349 if (!Value.hasValue()) { 2350 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2351 << true << Type; 2352 if (SubobjectLoc.isValid()) 2353 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2354 return false; 2355 } 2356 2357 // We allow _Atomic(T) to be initialized from anything that T can be 2358 // initialized from. 2359 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2360 Type = AT->getValueType(); 2361 2362 // Core issue 1454: For a literal constant expression of array or class type, 2363 // each subobject of its value shall have been initialized by a constant 2364 // expression. 2365 if (Value.isArray()) { 2366 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2367 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2368 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2369 Value.getArrayInitializedElt(I), Kind, 2370 SubobjectLoc, CheckedTemps)) 2371 return false; 2372 } 2373 if (!Value.hasArrayFiller()) 2374 return true; 2375 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2376 Value.getArrayFiller(), Kind, SubobjectLoc, 2377 CheckedTemps); 2378 } 2379 if (Value.isUnion() && Value.getUnionField()) { 2380 return CheckEvaluationResult( 2381 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2382 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2383 CheckedTemps); 2384 } 2385 if (Value.isStruct()) { 2386 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2387 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2388 unsigned BaseIndex = 0; 2389 for (const CXXBaseSpecifier &BS : CD->bases()) { 2390 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2391 Value.getStructBase(BaseIndex), Kind, 2392 BS.getBeginLoc(), CheckedTemps)) 2393 return false; 2394 ++BaseIndex; 2395 } 2396 } 2397 for (const auto *I : RD->fields()) { 2398 if (I->isUnnamedBitfield()) 2399 continue; 2400 2401 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2402 Value.getStructField(I->getFieldIndex()), 2403 Kind, I->getLocation(), CheckedTemps)) 2404 return false; 2405 } 2406 } 2407 2408 if (Value.isLValue() && 2409 CERK == CheckEvaluationResultKind::ConstantExpression) { 2410 LValue LVal; 2411 LVal.setFrom(Info.Ctx, Value); 2412 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2413 CheckedTemps); 2414 } 2415 2416 if (Value.isMemberPointer() && 2417 CERK == CheckEvaluationResultKind::ConstantExpression) 2418 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2419 2420 // Everything else is fine. 2421 return true; 2422 } 2423 2424 /// Check that this core constant expression value is a valid value for a 2425 /// constant expression. If not, report an appropriate diagnostic. Does not 2426 /// check that the expression is of literal type. 2427 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2428 QualType Type, const APValue &Value, 2429 ConstantExprKind Kind) { 2430 // Nothing to check for a constant expression of type 'cv void'. 2431 if (Type->isVoidType()) 2432 return true; 2433 2434 CheckedTemporaries CheckedTemps; 2435 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2436 Info, DiagLoc, Type, Value, Kind, 2437 SourceLocation(), CheckedTemps); 2438 } 2439 2440 /// Check that this evaluated value is fully-initialized and can be loaded by 2441 /// an lvalue-to-rvalue conversion. 2442 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2443 QualType Type, const APValue &Value) { 2444 CheckedTemporaries CheckedTemps; 2445 return CheckEvaluationResult( 2446 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2447 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2448 } 2449 2450 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2451 /// "the allocated storage is deallocated within the evaluation". 2452 static bool CheckMemoryLeaks(EvalInfo &Info) { 2453 if (!Info.HeapAllocs.empty()) { 2454 // We can still fold to a constant despite a compile-time memory leak, 2455 // so long as the heap allocation isn't referenced in the result (we check 2456 // that in CheckConstantExpression). 2457 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2458 diag::note_constexpr_memory_leak) 2459 << unsigned(Info.HeapAllocs.size() - 1); 2460 } 2461 return true; 2462 } 2463 2464 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2465 // A null base expression indicates a null pointer. These are always 2466 // evaluatable, and they are false unless the offset is zero. 2467 if (!Value.getLValueBase()) { 2468 Result = !Value.getLValueOffset().isZero(); 2469 return true; 2470 } 2471 2472 // We have a non-null base. These are generally known to be true, but if it's 2473 // a weak declaration it can be null at runtime. 2474 Result = true; 2475 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2476 return !Decl || !Decl->isWeak(); 2477 } 2478 2479 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2480 switch (Val.getKind()) { 2481 case APValue::None: 2482 case APValue::Indeterminate: 2483 return false; 2484 case APValue::Int: 2485 Result = Val.getInt().getBoolValue(); 2486 return true; 2487 case APValue::FixedPoint: 2488 Result = Val.getFixedPoint().getBoolValue(); 2489 return true; 2490 case APValue::Float: 2491 Result = !Val.getFloat().isZero(); 2492 return true; 2493 case APValue::ComplexInt: 2494 Result = Val.getComplexIntReal().getBoolValue() || 2495 Val.getComplexIntImag().getBoolValue(); 2496 return true; 2497 case APValue::ComplexFloat: 2498 Result = !Val.getComplexFloatReal().isZero() || 2499 !Val.getComplexFloatImag().isZero(); 2500 return true; 2501 case APValue::LValue: 2502 return EvalPointerValueAsBool(Val, Result); 2503 case APValue::MemberPointer: 2504 Result = Val.getMemberPointerDecl(); 2505 return true; 2506 case APValue::Vector: 2507 case APValue::Array: 2508 case APValue::Struct: 2509 case APValue::Union: 2510 case APValue::AddrLabelDiff: 2511 return false; 2512 } 2513 2514 llvm_unreachable("unknown APValue kind"); 2515 } 2516 2517 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2518 EvalInfo &Info) { 2519 assert(!E->isValueDependent()); 2520 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2521 APValue Val; 2522 if (!Evaluate(Val, Info, E)) 2523 return false; 2524 return HandleConversionToBool(Val, Result); 2525 } 2526 2527 template<typename T> 2528 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2529 const T &SrcValue, QualType DestType) { 2530 Info.CCEDiag(E, diag::note_constexpr_overflow) 2531 << SrcValue << DestType; 2532 return Info.noteUndefinedBehavior(); 2533 } 2534 2535 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2536 QualType SrcType, const APFloat &Value, 2537 QualType DestType, APSInt &Result) { 2538 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2539 // Determine whether we are converting to unsigned or signed. 2540 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2541 2542 Result = APSInt(DestWidth, !DestSigned); 2543 bool ignored; 2544 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2545 & APFloat::opInvalidOp) 2546 return HandleOverflow(Info, E, Value, DestType); 2547 return true; 2548 } 2549 2550 /// Get rounding mode used for evaluation of the specified expression. 2551 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2552 /// dynamic. 2553 /// If rounding mode is unknown at compile time, still try to evaluate the 2554 /// expression. If the result is exact, it does not depend on rounding mode. 2555 /// So return "tonearest" mode instead of "dynamic". 2556 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2557 bool &DynamicRM) { 2558 llvm::RoundingMode RM = 2559 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2560 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2561 if (DynamicRM) 2562 RM = llvm::RoundingMode::NearestTiesToEven; 2563 return RM; 2564 } 2565 2566 /// Check if the given evaluation result is allowed for constant evaluation. 2567 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2568 APFloat::opStatus St) { 2569 // In a constant context, assume that any dynamic rounding mode or FP 2570 // exception state matches the default floating-point environment. 2571 if (Info.InConstantContext) 2572 return true; 2573 2574 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2575 if ((St & APFloat::opInexact) && 2576 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2577 // Inexact result means that it depends on rounding mode. If the requested 2578 // mode is dynamic, the evaluation cannot be made in compile time. 2579 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2580 return false; 2581 } 2582 2583 if ((St != APFloat::opOK) && 2584 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2585 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2586 FPO.getAllowFEnvAccess())) { 2587 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2588 return false; 2589 } 2590 2591 if ((St & APFloat::opStatus::opInvalidOp) && 2592 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2593 // There is no usefully definable result. 2594 Info.FFDiag(E); 2595 return false; 2596 } 2597 2598 // FIXME: if: 2599 // - evaluation triggered other FP exception, and 2600 // - exception mode is not "ignore", and 2601 // - the expression being evaluated is not a part of global variable 2602 // initializer, 2603 // the evaluation probably need to be rejected. 2604 return true; 2605 } 2606 2607 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2608 QualType SrcType, QualType DestType, 2609 APFloat &Result) { 2610 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2611 bool DynamicRM; 2612 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2613 APFloat::opStatus St; 2614 APFloat Value = Result; 2615 bool ignored; 2616 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2617 return checkFloatingPointResult(Info, E, St); 2618 } 2619 2620 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2621 QualType DestType, QualType SrcType, 2622 const APSInt &Value) { 2623 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2624 // Figure out if this is a truncate, extend or noop cast. 2625 // If the input is signed, do a sign extend, noop, or truncate. 2626 APSInt Result = Value.extOrTrunc(DestWidth); 2627 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2628 if (DestType->isBooleanType()) 2629 Result = Value.getBoolValue(); 2630 return Result; 2631 } 2632 2633 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2634 const FPOptions FPO, 2635 QualType SrcType, const APSInt &Value, 2636 QualType DestType, APFloat &Result) { 2637 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2638 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2639 APFloat::rmNearestTiesToEven); 2640 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2641 FPO.isFPConstrained()) { 2642 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2643 return false; 2644 } 2645 return true; 2646 } 2647 2648 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2649 APValue &Value, const FieldDecl *FD) { 2650 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2651 2652 if (!Value.isInt()) { 2653 // Trying to store a pointer-cast-to-integer into a bitfield. 2654 // FIXME: In this case, we should provide the diagnostic for casting 2655 // a pointer to an integer. 2656 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2657 Info.FFDiag(E); 2658 return false; 2659 } 2660 2661 APSInt &Int = Value.getInt(); 2662 unsigned OldBitWidth = Int.getBitWidth(); 2663 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2664 if (NewBitWidth < OldBitWidth) 2665 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2666 return true; 2667 } 2668 2669 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2670 llvm::APInt &Res) { 2671 APValue SVal; 2672 if (!Evaluate(SVal, Info, E)) 2673 return false; 2674 if (SVal.isInt()) { 2675 Res = SVal.getInt(); 2676 return true; 2677 } 2678 if (SVal.isFloat()) { 2679 Res = SVal.getFloat().bitcastToAPInt(); 2680 return true; 2681 } 2682 if (SVal.isVector()) { 2683 QualType VecTy = E->getType(); 2684 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2685 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2686 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2687 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2688 Res = llvm::APInt::getZero(VecSize); 2689 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2690 APValue &Elt = SVal.getVectorElt(i); 2691 llvm::APInt EltAsInt; 2692 if (Elt.isInt()) { 2693 EltAsInt = Elt.getInt(); 2694 } else if (Elt.isFloat()) { 2695 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2696 } else { 2697 // Don't try to handle vectors of anything other than int or float 2698 // (not sure if it's possible to hit this case). 2699 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2700 return false; 2701 } 2702 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2703 if (BigEndian) 2704 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2705 else 2706 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2707 } 2708 return true; 2709 } 2710 // Give up if the input isn't an int, float, or vector. For example, we 2711 // reject "(v4i16)(intptr_t)&a". 2712 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2713 return false; 2714 } 2715 2716 /// Perform the given integer operation, which is known to need at most BitWidth 2717 /// bits, and check for overflow in the original type (if that type was not an 2718 /// unsigned type). 2719 template<typename Operation> 2720 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2721 const APSInt &LHS, const APSInt &RHS, 2722 unsigned BitWidth, Operation Op, 2723 APSInt &Result) { 2724 if (LHS.isUnsigned()) { 2725 Result = Op(LHS, RHS); 2726 return true; 2727 } 2728 2729 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2730 Result = Value.trunc(LHS.getBitWidth()); 2731 if (Result.extend(BitWidth) != Value) { 2732 if (Info.checkingForUndefinedBehavior()) 2733 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2734 diag::warn_integer_constant_overflow) 2735 << toString(Result, 10) << E->getType(); 2736 return HandleOverflow(Info, E, Value, E->getType()); 2737 } 2738 return true; 2739 } 2740 2741 /// Perform the given binary integer operation. 2742 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2743 BinaryOperatorKind Opcode, APSInt RHS, 2744 APSInt &Result) { 2745 switch (Opcode) { 2746 default: 2747 Info.FFDiag(E); 2748 return false; 2749 case BO_Mul: 2750 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2751 std::multiplies<APSInt>(), Result); 2752 case BO_Add: 2753 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2754 std::plus<APSInt>(), Result); 2755 case BO_Sub: 2756 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2757 std::minus<APSInt>(), Result); 2758 case BO_And: Result = LHS & RHS; return true; 2759 case BO_Xor: Result = LHS ^ RHS; return true; 2760 case BO_Or: Result = LHS | RHS; return true; 2761 case BO_Div: 2762 case BO_Rem: 2763 if (RHS == 0) { 2764 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2765 return false; 2766 } 2767 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2768 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2769 // this operation and gives the two's complement result. 2770 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && 2771 LHS.isMinSignedValue()) 2772 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2773 E->getType()); 2774 return true; 2775 case BO_Shl: { 2776 if (Info.getLangOpts().OpenCL) 2777 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2778 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2779 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2780 RHS.isUnsigned()); 2781 else if (RHS.isSigned() && RHS.isNegative()) { 2782 // During constant-folding, a negative shift is an opposite shift. Such 2783 // a shift is not a constant expression. 2784 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2785 RHS = -RHS; 2786 goto shift_right; 2787 } 2788 shift_left: 2789 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2790 // the shifted type. 2791 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2792 if (SA != RHS) { 2793 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2794 << RHS << E->getType() << LHS.getBitWidth(); 2795 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2796 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2797 // operand, and must not overflow the corresponding unsigned type. 2798 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2799 // E1 x 2^E2 module 2^N. 2800 if (LHS.isNegative()) 2801 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2802 else if (LHS.countLeadingZeros() < SA) 2803 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2804 } 2805 Result = LHS << SA; 2806 return true; 2807 } 2808 case BO_Shr: { 2809 if (Info.getLangOpts().OpenCL) 2810 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2811 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2812 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2813 RHS.isUnsigned()); 2814 else if (RHS.isSigned() && RHS.isNegative()) { 2815 // During constant-folding, a negative shift is an opposite shift. Such a 2816 // shift is not a constant expression. 2817 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2818 RHS = -RHS; 2819 goto shift_left; 2820 } 2821 shift_right: 2822 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2823 // shifted type. 2824 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2825 if (SA != RHS) 2826 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2827 << RHS << E->getType() << LHS.getBitWidth(); 2828 Result = LHS >> SA; 2829 return true; 2830 } 2831 2832 case BO_LT: Result = LHS < RHS; return true; 2833 case BO_GT: Result = LHS > RHS; return true; 2834 case BO_LE: Result = LHS <= RHS; return true; 2835 case BO_GE: Result = LHS >= RHS; return true; 2836 case BO_EQ: Result = LHS == RHS; return true; 2837 case BO_NE: Result = LHS != RHS; return true; 2838 case BO_Cmp: 2839 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2840 } 2841 } 2842 2843 /// Perform the given binary floating-point operation, in-place, on LHS. 2844 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2845 APFloat &LHS, BinaryOperatorKind Opcode, 2846 const APFloat &RHS) { 2847 bool DynamicRM; 2848 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2849 APFloat::opStatus St; 2850 switch (Opcode) { 2851 default: 2852 Info.FFDiag(E); 2853 return false; 2854 case BO_Mul: 2855 St = LHS.multiply(RHS, RM); 2856 break; 2857 case BO_Add: 2858 St = LHS.add(RHS, RM); 2859 break; 2860 case BO_Sub: 2861 St = LHS.subtract(RHS, RM); 2862 break; 2863 case BO_Div: 2864 // [expr.mul]p4: 2865 // If the second operand of / or % is zero the behavior is undefined. 2866 if (RHS.isZero()) 2867 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2868 St = LHS.divide(RHS, RM); 2869 break; 2870 } 2871 2872 // [expr.pre]p4: 2873 // If during the evaluation of an expression, the result is not 2874 // mathematically defined [...], the behavior is undefined. 2875 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2876 if (LHS.isNaN()) { 2877 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2878 return Info.noteUndefinedBehavior(); 2879 } 2880 2881 return checkFloatingPointResult(Info, E, St); 2882 } 2883 2884 static bool handleLogicalOpForVector(const APInt &LHSValue, 2885 BinaryOperatorKind Opcode, 2886 const APInt &RHSValue, APInt &Result) { 2887 bool LHS = (LHSValue != 0); 2888 bool RHS = (RHSValue != 0); 2889 2890 if (Opcode == BO_LAnd) 2891 Result = LHS && RHS; 2892 else 2893 Result = LHS || RHS; 2894 return true; 2895 } 2896 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2897 BinaryOperatorKind Opcode, 2898 const APFloat &RHSValue, APInt &Result) { 2899 bool LHS = !LHSValue.isZero(); 2900 bool RHS = !RHSValue.isZero(); 2901 2902 if (Opcode == BO_LAnd) 2903 Result = LHS && RHS; 2904 else 2905 Result = LHS || RHS; 2906 return true; 2907 } 2908 2909 static bool handleLogicalOpForVector(const APValue &LHSValue, 2910 BinaryOperatorKind Opcode, 2911 const APValue &RHSValue, APInt &Result) { 2912 // The result is always an int type, however operands match the first. 2913 if (LHSValue.getKind() == APValue::Int) 2914 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2915 RHSValue.getInt(), Result); 2916 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2917 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2918 RHSValue.getFloat(), Result); 2919 } 2920 2921 template <typename APTy> 2922 static bool 2923 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2924 const APTy &RHSValue, APInt &Result) { 2925 switch (Opcode) { 2926 default: 2927 llvm_unreachable("unsupported binary operator"); 2928 case BO_EQ: 2929 Result = (LHSValue == RHSValue); 2930 break; 2931 case BO_NE: 2932 Result = (LHSValue != RHSValue); 2933 break; 2934 case BO_LT: 2935 Result = (LHSValue < RHSValue); 2936 break; 2937 case BO_GT: 2938 Result = (LHSValue > RHSValue); 2939 break; 2940 case BO_LE: 2941 Result = (LHSValue <= RHSValue); 2942 break; 2943 case BO_GE: 2944 Result = (LHSValue >= RHSValue); 2945 break; 2946 } 2947 2948 // The boolean operations on these vector types use an instruction that 2949 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 2950 // to -1 to make sure that we produce the correct value. 2951 Result.negate(); 2952 2953 return true; 2954 } 2955 2956 static bool handleCompareOpForVector(const APValue &LHSValue, 2957 BinaryOperatorKind Opcode, 2958 const APValue &RHSValue, APInt &Result) { 2959 // The result is always an int type, however operands match the first. 2960 if (LHSValue.getKind() == APValue::Int) 2961 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2962 RHSValue.getInt(), Result); 2963 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2964 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2965 RHSValue.getFloat(), Result); 2966 } 2967 2968 // Perform binary operations for vector types, in place on the LHS. 2969 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2970 BinaryOperatorKind Opcode, 2971 APValue &LHSValue, 2972 const APValue &RHSValue) { 2973 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2974 "Operation not supported on vector types"); 2975 2976 const auto *VT = E->getType()->castAs<VectorType>(); 2977 unsigned NumElements = VT->getNumElements(); 2978 QualType EltTy = VT->getElementType(); 2979 2980 // In the cases (typically C as I've observed) where we aren't evaluating 2981 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2982 // just give up. 2983 if (!LHSValue.isVector()) { 2984 assert(LHSValue.isLValue() && 2985 "A vector result that isn't a vector OR uncalculated LValue"); 2986 Info.FFDiag(E); 2987 return false; 2988 } 2989 2990 assert(LHSValue.getVectorLength() == NumElements && 2991 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2992 2993 SmallVector<APValue, 4> ResultElements; 2994 2995 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2996 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2997 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2998 2999 if (EltTy->isIntegerType()) { 3000 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 3001 EltTy->isUnsignedIntegerType()}; 3002 bool Success = true; 3003 3004 if (BinaryOperator::isLogicalOp(Opcode)) 3005 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3006 else if (BinaryOperator::isComparisonOp(Opcode)) 3007 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3008 else 3009 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 3010 RHSElt.getInt(), EltResult); 3011 3012 if (!Success) { 3013 Info.FFDiag(E); 3014 return false; 3015 } 3016 ResultElements.emplace_back(EltResult); 3017 3018 } else if (EltTy->isFloatingType()) { 3019 assert(LHSElt.getKind() == APValue::Float && 3020 RHSElt.getKind() == APValue::Float && 3021 "Mismatched LHS/RHS/Result Type"); 3022 APFloat LHSFloat = LHSElt.getFloat(); 3023 3024 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3025 RHSElt.getFloat())) { 3026 Info.FFDiag(E); 3027 return false; 3028 } 3029 3030 ResultElements.emplace_back(LHSFloat); 3031 } 3032 } 3033 3034 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3035 return true; 3036 } 3037 3038 /// Cast an lvalue referring to a base subobject to a derived class, by 3039 /// truncating the lvalue's path to the given length. 3040 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3041 const RecordDecl *TruncatedType, 3042 unsigned TruncatedElements) { 3043 SubobjectDesignator &D = Result.Designator; 3044 3045 // Check we actually point to a derived class object. 3046 if (TruncatedElements == D.Entries.size()) 3047 return true; 3048 assert(TruncatedElements >= D.MostDerivedPathLength && 3049 "not casting to a derived class"); 3050 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3051 return false; 3052 3053 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3054 const RecordDecl *RD = TruncatedType; 3055 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3056 if (RD->isInvalidDecl()) return false; 3057 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3058 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3059 if (isVirtualBaseClass(D.Entries[I])) 3060 Result.Offset -= Layout.getVBaseClassOffset(Base); 3061 else 3062 Result.Offset -= Layout.getBaseClassOffset(Base); 3063 RD = Base; 3064 } 3065 D.Entries.resize(TruncatedElements); 3066 return true; 3067 } 3068 3069 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3070 const CXXRecordDecl *Derived, 3071 const CXXRecordDecl *Base, 3072 const ASTRecordLayout *RL = nullptr) { 3073 if (!RL) { 3074 if (Derived->isInvalidDecl()) return false; 3075 RL = &Info.Ctx.getASTRecordLayout(Derived); 3076 } 3077 3078 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3079 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3080 return true; 3081 } 3082 3083 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3084 const CXXRecordDecl *DerivedDecl, 3085 const CXXBaseSpecifier *Base) { 3086 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3087 3088 if (!Base->isVirtual()) 3089 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3090 3091 SubobjectDesignator &D = Obj.Designator; 3092 if (D.Invalid) 3093 return false; 3094 3095 // Extract most-derived object and corresponding type. 3096 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3097 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3098 return false; 3099 3100 // Find the virtual base class. 3101 if (DerivedDecl->isInvalidDecl()) return false; 3102 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3103 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3104 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3105 return true; 3106 } 3107 3108 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3109 QualType Type, LValue &Result) { 3110 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3111 PathE = E->path_end(); 3112 PathI != PathE; ++PathI) { 3113 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3114 *PathI)) 3115 return false; 3116 Type = (*PathI)->getType(); 3117 } 3118 return true; 3119 } 3120 3121 /// Cast an lvalue referring to a derived class to a known base subobject. 3122 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3123 const CXXRecordDecl *DerivedRD, 3124 const CXXRecordDecl *BaseRD) { 3125 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3126 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3127 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3128 llvm_unreachable("Class must be derived from the passed in base class!"); 3129 3130 for (CXXBasePathElement &Elem : Paths.front()) 3131 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3132 return false; 3133 return true; 3134 } 3135 3136 /// Update LVal to refer to the given field, which must be a member of the type 3137 /// currently described by LVal. 3138 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3139 const FieldDecl *FD, 3140 const ASTRecordLayout *RL = nullptr) { 3141 if (!RL) { 3142 if (FD->getParent()->isInvalidDecl()) return false; 3143 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3144 } 3145 3146 unsigned I = FD->getFieldIndex(); 3147 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3148 LVal.addDecl(Info, E, FD); 3149 return true; 3150 } 3151 3152 /// Update LVal to refer to the given indirect field. 3153 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3154 LValue &LVal, 3155 const IndirectFieldDecl *IFD) { 3156 for (const auto *C : IFD->chain()) 3157 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3158 return false; 3159 return true; 3160 } 3161 3162 /// Get the size of the given type in char units. 3163 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3164 QualType Type, CharUnits &Size) { 3165 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3166 // extension. 3167 if (Type->isVoidType() || Type->isFunctionType()) { 3168 Size = CharUnits::One(); 3169 return true; 3170 } 3171 3172 if (Type->isDependentType()) { 3173 Info.FFDiag(Loc); 3174 return false; 3175 } 3176 3177 if (!Type->isConstantSizeType()) { 3178 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3179 // FIXME: Better diagnostic. 3180 Info.FFDiag(Loc); 3181 return false; 3182 } 3183 3184 Size = Info.Ctx.getTypeSizeInChars(Type); 3185 return true; 3186 } 3187 3188 /// Update a pointer value to model pointer arithmetic. 3189 /// \param Info - Information about the ongoing evaluation. 3190 /// \param E - The expression being evaluated, for diagnostic purposes. 3191 /// \param LVal - The pointer value to be updated. 3192 /// \param EltTy - The pointee type represented by LVal. 3193 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3194 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3195 LValue &LVal, QualType EltTy, 3196 APSInt Adjustment) { 3197 CharUnits SizeOfPointee; 3198 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3199 return false; 3200 3201 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3202 return true; 3203 } 3204 3205 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3206 LValue &LVal, QualType EltTy, 3207 int64_t Adjustment) { 3208 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3209 APSInt::get(Adjustment)); 3210 } 3211 3212 /// Update an lvalue to refer to a component of a complex number. 3213 /// \param Info - Information about the ongoing evaluation. 3214 /// \param LVal - The lvalue to be updated. 3215 /// \param EltTy - The complex number's component type. 3216 /// \param Imag - False for the real component, true for the imaginary. 3217 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3218 LValue &LVal, QualType EltTy, 3219 bool Imag) { 3220 if (Imag) { 3221 CharUnits SizeOfComponent; 3222 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3223 return false; 3224 LVal.Offset += SizeOfComponent; 3225 } 3226 LVal.addComplex(Info, E, EltTy, Imag); 3227 return true; 3228 } 3229 3230 /// Try to evaluate the initializer for a variable declaration. 3231 /// 3232 /// \param Info Information about the ongoing evaluation. 3233 /// \param E An expression to be used when printing diagnostics. 3234 /// \param VD The variable whose initializer should be obtained. 3235 /// \param Version The version of the variable within the frame. 3236 /// \param Frame The frame in which the variable was created. Must be null 3237 /// if this variable is not local to the evaluation. 3238 /// \param Result Filled in with a pointer to the value of the variable. 3239 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3240 const VarDecl *VD, CallStackFrame *Frame, 3241 unsigned Version, APValue *&Result) { 3242 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3243 3244 // If this is a local variable, dig out its value. 3245 if (Frame) { 3246 Result = Frame->getTemporary(VD, Version); 3247 if (Result) 3248 return true; 3249 3250 if (!isa<ParmVarDecl>(VD)) { 3251 // Assume variables referenced within a lambda's call operator that were 3252 // not declared within the call operator are captures and during checking 3253 // of a potential constant expression, assume they are unknown constant 3254 // expressions. 3255 assert(isLambdaCallOperator(Frame->Callee) && 3256 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3257 "missing value for local variable"); 3258 if (Info.checkingPotentialConstantExpression()) 3259 return false; 3260 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3261 // still reachable at all? 3262 Info.FFDiag(E->getBeginLoc(), 3263 diag::note_unimplemented_constexpr_lambda_feature_ast) 3264 << "captures not currently allowed"; 3265 return false; 3266 } 3267 } 3268 3269 // If we're currently evaluating the initializer of this declaration, use that 3270 // in-flight value. 3271 if (Info.EvaluatingDecl == Base) { 3272 Result = Info.EvaluatingDeclValue; 3273 return true; 3274 } 3275 3276 if (isa<ParmVarDecl>(VD)) { 3277 // Assume parameters of a potential constant expression are usable in 3278 // constant expressions. 3279 if (!Info.checkingPotentialConstantExpression() || 3280 !Info.CurrentCall->Callee || 3281 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3282 if (Info.getLangOpts().CPlusPlus11) { 3283 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3284 << VD; 3285 NoteLValueLocation(Info, Base); 3286 } else { 3287 Info.FFDiag(E); 3288 } 3289 } 3290 return false; 3291 } 3292 3293 // Dig out the initializer, and use the declaration which it's attached to. 3294 // FIXME: We should eventually check whether the variable has a reachable 3295 // initializing declaration. 3296 const Expr *Init = VD->getAnyInitializer(VD); 3297 if (!Init) { 3298 // Don't diagnose during potential constant expression checking; an 3299 // initializer might be added later. 3300 if (!Info.checkingPotentialConstantExpression()) { 3301 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3302 << VD; 3303 NoteLValueLocation(Info, Base); 3304 } 3305 return false; 3306 } 3307 3308 if (Init->isValueDependent()) { 3309 // The DeclRefExpr is not value-dependent, but the variable it refers to 3310 // has a value-dependent initializer. This should only happen in 3311 // constant-folding cases, where the variable is not actually of a suitable 3312 // type for use in a constant expression (otherwise the DeclRefExpr would 3313 // have been value-dependent too), so diagnose that. 3314 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3315 if (!Info.checkingPotentialConstantExpression()) { 3316 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3317 ? diag::note_constexpr_ltor_non_constexpr 3318 : diag::note_constexpr_ltor_non_integral, 1) 3319 << VD << VD->getType(); 3320 NoteLValueLocation(Info, Base); 3321 } 3322 return false; 3323 } 3324 3325 // Check that we can fold the initializer. In C++, we will have already done 3326 // this in the cases where it matters for conformance. 3327 if (!VD->evaluateValue()) { 3328 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3329 NoteLValueLocation(Info, Base); 3330 return false; 3331 } 3332 3333 // Check that the variable is actually usable in constant expressions. For a 3334 // const integral variable or a reference, we might have a non-constant 3335 // initializer that we can nonetheless evaluate the initializer for. Such 3336 // variables are not usable in constant expressions. In C++98, the 3337 // initializer also syntactically needs to be an ICE. 3338 // 3339 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3340 // expressions here; doing so would regress diagnostics for things like 3341 // reading from a volatile constexpr variable. 3342 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3343 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3344 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3345 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3346 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3347 NoteLValueLocation(Info, Base); 3348 } 3349 3350 // Never use the initializer of a weak variable, not even for constant 3351 // folding. We can't be sure that this is the definition that will be used. 3352 if (VD->isWeak()) { 3353 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3354 NoteLValueLocation(Info, Base); 3355 return false; 3356 } 3357 3358 Result = VD->getEvaluatedValue(); 3359 return true; 3360 } 3361 3362 /// Get the base index of the given base class within an APValue representing 3363 /// the given derived class. 3364 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3365 const CXXRecordDecl *Base) { 3366 Base = Base->getCanonicalDecl(); 3367 unsigned Index = 0; 3368 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3369 E = Derived->bases_end(); I != E; ++I, ++Index) { 3370 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3371 return Index; 3372 } 3373 3374 llvm_unreachable("base class missing from derived class's bases list"); 3375 } 3376 3377 /// Extract the value of a character from a string literal. 3378 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3379 uint64_t Index) { 3380 assert(!isa<SourceLocExpr>(Lit) && 3381 "SourceLocExpr should have already been converted to a StringLiteral"); 3382 3383 // FIXME: Support MakeStringConstant 3384 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3385 std::string Str; 3386 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3387 assert(Index <= Str.size() && "Index too large"); 3388 return APSInt::getUnsigned(Str.c_str()[Index]); 3389 } 3390 3391 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3392 Lit = PE->getFunctionName(); 3393 const StringLiteral *S = cast<StringLiteral>(Lit); 3394 const ConstantArrayType *CAT = 3395 Info.Ctx.getAsConstantArrayType(S->getType()); 3396 assert(CAT && "string literal isn't an array"); 3397 QualType CharType = CAT->getElementType(); 3398 assert(CharType->isIntegerType() && "unexpected character type"); 3399 3400 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3401 CharType->isUnsignedIntegerType()); 3402 if (Index < S->getLength()) 3403 Value = S->getCodeUnit(Index); 3404 return Value; 3405 } 3406 3407 // Expand a string literal into an array of characters. 3408 // 3409 // FIXME: This is inefficient; we should probably introduce something similar 3410 // to the LLVM ConstantDataArray to make this cheaper. 3411 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3412 APValue &Result, 3413 QualType AllocType = QualType()) { 3414 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3415 AllocType.isNull() ? S->getType() : AllocType); 3416 assert(CAT && "string literal isn't an array"); 3417 QualType CharType = CAT->getElementType(); 3418 assert(CharType->isIntegerType() && "unexpected character type"); 3419 3420 unsigned Elts = CAT->getSize().getZExtValue(); 3421 Result = APValue(APValue::UninitArray(), 3422 std::min(S->getLength(), Elts), Elts); 3423 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3424 CharType->isUnsignedIntegerType()); 3425 if (Result.hasArrayFiller()) 3426 Result.getArrayFiller() = APValue(Value); 3427 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3428 Value = S->getCodeUnit(I); 3429 Result.getArrayInitializedElt(I) = APValue(Value); 3430 } 3431 } 3432 3433 // Expand an array so that it has more than Index filled elements. 3434 static void expandArray(APValue &Array, unsigned Index) { 3435 unsigned Size = Array.getArraySize(); 3436 assert(Index < Size); 3437 3438 // Always at least double the number of elements for which we store a value. 3439 unsigned OldElts = Array.getArrayInitializedElts(); 3440 unsigned NewElts = std::max(Index+1, OldElts * 2); 3441 NewElts = std::min(Size, std::max(NewElts, 8u)); 3442 3443 // Copy the data across. 3444 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3445 for (unsigned I = 0; I != OldElts; ++I) 3446 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3447 for (unsigned I = OldElts; I != NewElts; ++I) 3448 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3449 if (NewValue.hasArrayFiller()) 3450 NewValue.getArrayFiller() = Array.getArrayFiller(); 3451 Array.swap(NewValue); 3452 } 3453 3454 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3455 /// conversion. If it's of class type, we may assume that the copy operation 3456 /// is trivial. Note that this is never true for a union type with fields 3457 /// (because the copy always "reads" the active member) and always true for 3458 /// a non-class type. 3459 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3460 static bool isReadByLvalueToRvalueConversion(QualType T) { 3461 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3462 return !RD || isReadByLvalueToRvalueConversion(RD); 3463 } 3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3465 // FIXME: A trivial copy of a union copies the object representation, even if 3466 // the union is empty. 3467 if (RD->isUnion()) 3468 return !RD->field_empty(); 3469 if (RD->isEmpty()) 3470 return false; 3471 3472 for (auto *Field : RD->fields()) 3473 if (!Field->isUnnamedBitfield() && 3474 isReadByLvalueToRvalueConversion(Field->getType())) 3475 return true; 3476 3477 for (auto &BaseSpec : RD->bases()) 3478 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3479 return true; 3480 3481 return false; 3482 } 3483 3484 /// Diagnose an attempt to read from any unreadable field within the specified 3485 /// type, which might be a class type. 3486 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3487 QualType T) { 3488 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3489 if (!RD) 3490 return false; 3491 3492 if (!RD->hasMutableFields()) 3493 return false; 3494 3495 for (auto *Field : RD->fields()) { 3496 // If we're actually going to read this field in some way, then it can't 3497 // be mutable. If we're in a union, then assigning to a mutable field 3498 // (even an empty one) can change the active member, so that's not OK. 3499 // FIXME: Add core issue number for the union case. 3500 if (Field->isMutable() && 3501 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3502 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3503 Info.Note(Field->getLocation(), diag::note_declared_at); 3504 return true; 3505 } 3506 3507 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3508 return true; 3509 } 3510 3511 for (auto &BaseSpec : RD->bases()) 3512 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3513 return true; 3514 3515 // All mutable fields were empty, and thus not actually read. 3516 return false; 3517 } 3518 3519 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3520 APValue::LValueBase Base, 3521 bool MutableSubobject = false) { 3522 // A temporary or transient heap allocation we created. 3523 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3524 return true; 3525 3526 switch (Info.IsEvaluatingDecl) { 3527 case EvalInfo::EvaluatingDeclKind::None: 3528 return false; 3529 3530 case EvalInfo::EvaluatingDeclKind::Ctor: 3531 // The variable whose initializer we're evaluating. 3532 if (Info.EvaluatingDecl == Base) 3533 return true; 3534 3535 // A temporary lifetime-extended by the variable whose initializer we're 3536 // evaluating. 3537 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3538 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3539 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3540 return false; 3541 3542 case EvalInfo::EvaluatingDeclKind::Dtor: 3543 // C++2a [expr.const]p6: 3544 // [during constant destruction] the lifetime of a and its non-mutable 3545 // subobjects (but not its mutable subobjects) [are] considered to start 3546 // within e. 3547 if (MutableSubobject || Base != Info.EvaluatingDecl) 3548 return false; 3549 // FIXME: We can meaningfully extend this to cover non-const objects, but 3550 // we will need special handling: we should be able to access only 3551 // subobjects of such objects that are themselves declared const. 3552 QualType T = getType(Base); 3553 return T.isConstQualified() || T->isReferenceType(); 3554 } 3555 3556 llvm_unreachable("unknown evaluating decl kind"); 3557 } 3558 3559 namespace { 3560 /// A handle to a complete object (an object that is not a subobject of 3561 /// another object). 3562 struct CompleteObject { 3563 /// The identity of the object. 3564 APValue::LValueBase Base; 3565 /// The value of the complete object. 3566 APValue *Value; 3567 /// The type of the complete object. 3568 QualType Type; 3569 3570 CompleteObject() : Value(nullptr) {} 3571 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3572 : Base(Base), Value(Value), Type(Type) {} 3573 3574 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3575 // If this isn't a "real" access (eg, if it's just accessing the type 3576 // info), allow it. We assume the type doesn't change dynamically for 3577 // subobjects of constexpr objects (even though we'd hit UB here if it 3578 // did). FIXME: Is this right? 3579 if (!isAnyAccess(AK)) 3580 return true; 3581 3582 // In C++14 onwards, it is permitted to read a mutable member whose 3583 // lifetime began within the evaluation. 3584 // FIXME: Should we also allow this in C++11? 3585 if (!Info.getLangOpts().CPlusPlus14) 3586 return false; 3587 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3588 } 3589 3590 explicit operator bool() const { return !Type.isNull(); } 3591 }; 3592 } // end anonymous namespace 3593 3594 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3595 bool IsMutable = false) { 3596 // C++ [basic.type.qualifier]p1: 3597 // - A const object is an object of type const T or a non-mutable subobject 3598 // of a const object. 3599 if (ObjType.isConstQualified() && !IsMutable) 3600 SubobjType.addConst(); 3601 // - A volatile object is an object of type const T or a subobject of a 3602 // volatile object. 3603 if (ObjType.isVolatileQualified()) 3604 SubobjType.addVolatile(); 3605 return SubobjType; 3606 } 3607 3608 /// Find the designated sub-object of an rvalue. 3609 template<typename SubobjectHandler> 3610 typename SubobjectHandler::result_type 3611 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3612 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3613 if (Sub.Invalid) 3614 // A diagnostic will have already been produced. 3615 return handler.failed(); 3616 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3617 if (Info.getLangOpts().CPlusPlus11) 3618 Info.FFDiag(E, Sub.isOnePastTheEnd() 3619 ? diag::note_constexpr_access_past_end 3620 : diag::note_constexpr_access_unsized_array) 3621 << handler.AccessKind; 3622 else 3623 Info.FFDiag(E); 3624 return handler.failed(); 3625 } 3626 3627 APValue *O = Obj.Value; 3628 QualType ObjType = Obj.Type; 3629 const FieldDecl *LastField = nullptr; 3630 const FieldDecl *VolatileField = nullptr; 3631 3632 // Walk the designator's path to find the subobject. 3633 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3634 // Reading an indeterminate value is undefined, but assigning over one is OK. 3635 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3636 (O->isIndeterminate() && 3637 !isValidIndeterminateAccess(handler.AccessKind))) { 3638 if (!Info.checkingPotentialConstantExpression()) 3639 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3640 << handler.AccessKind << O->isIndeterminate(); 3641 return handler.failed(); 3642 } 3643 3644 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3645 // const and volatile semantics are not applied on an object under 3646 // {con,de}struction. 3647 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3648 ObjType->isRecordType() && 3649 Info.isEvaluatingCtorDtor( 3650 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3651 Sub.Entries.begin() + I)) != 3652 ConstructionPhase::None) { 3653 ObjType = Info.Ctx.getCanonicalType(ObjType); 3654 ObjType.removeLocalConst(); 3655 ObjType.removeLocalVolatile(); 3656 } 3657 3658 // If this is our last pass, check that the final object type is OK. 3659 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3660 // Accesses to volatile objects are prohibited. 3661 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3662 if (Info.getLangOpts().CPlusPlus) { 3663 int DiagKind; 3664 SourceLocation Loc; 3665 const NamedDecl *Decl = nullptr; 3666 if (VolatileField) { 3667 DiagKind = 2; 3668 Loc = VolatileField->getLocation(); 3669 Decl = VolatileField; 3670 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3671 DiagKind = 1; 3672 Loc = VD->getLocation(); 3673 Decl = VD; 3674 } else { 3675 DiagKind = 0; 3676 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3677 Loc = E->getExprLoc(); 3678 } 3679 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3680 << handler.AccessKind << DiagKind << Decl; 3681 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3682 } else { 3683 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3684 } 3685 return handler.failed(); 3686 } 3687 3688 // If we are reading an object of class type, there may still be more 3689 // things we need to check: if there are any mutable subobjects, we 3690 // cannot perform this read. (This only happens when performing a trivial 3691 // copy or assignment.) 3692 if (ObjType->isRecordType() && 3693 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3694 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3695 return handler.failed(); 3696 } 3697 3698 if (I == N) { 3699 if (!handler.found(*O, ObjType)) 3700 return false; 3701 3702 // If we modified a bit-field, truncate it to the right width. 3703 if (isModification(handler.AccessKind) && 3704 LastField && LastField->isBitField() && 3705 !truncateBitfieldValue(Info, E, *O, LastField)) 3706 return false; 3707 3708 return true; 3709 } 3710 3711 LastField = nullptr; 3712 if (ObjType->isArrayType()) { 3713 // Next subobject is an array element. 3714 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3715 assert(CAT && "vla in literal type?"); 3716 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3717 if (CAT->getSize().ule(Index)) { 3718 // Note, it should not be possible to form a pointer with a valid 3719 // designator which points more than one past the end of the array. 3720 if (Info.getLangOpts().CPlusPlus11) 3721 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3722 << handler.AccessKind; 3723 else 3724 Info.FFDiag(E); 3725 return handler.failed(); 3726 } 3727 3728 ObjType = CAT->getElementType(); 3729 3730 if (O->getArrayInitializedElts() > Index) 3731 O = &O->getArrayInitializedElt(Index); 3732 else if (!isRead(handler.AccessKind)) { 3733 expandArray(*O, Index); 3734 O = &O->getArrayInitializedElt(Index); 3735 } else 3736 O = &O->getArrayFiller(); 3737 } else if (ObjType->isAnyComplexType()) { 3738 // Next subobject is a complex number. 3739 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3740 if (Index > 1) { 3741 if (Info.getLangOpts().CPlusPlus11) 3742 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3743 << handler.AccessKind; 3744 else 3745 Info.FFDiag(E); 3746 return handler.failed(); 3747 } 3748 3749 ObjType = getSubobjectType( 3750 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3751 3752 assert(I == N - 1 && "extracting subobject of scalar?"); 3753 if (O->isComplexInt()) { 3754 return handler.found(Index ? O->getComplexIntImag() 3755 : O->getComplexIntReal(), ObjType); 3756 } else { 3757 assert(O->isComplexFloat()); 3758 return handler.found(Index ? O->getComplexFloatImag() 3759 : O->getComplexFloatReal(), ObjType); 3760 } 3761 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3762 if (Field->isMutable() && 3763 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3764 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3765 << handler.AccessKind << Field; 3766 Info.Note(Field->getLocation(), diag::note_declared_at); 3767 return handler.failed(); 3768 } 3769 3770 // Next subobject is a class, struct or union field. 3771 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3772 if (RD->isUnion()) { 3773 const FieldDecl *UnionField = O->getUnionField(); 3774 if (!UnionField || 3775 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3776 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3777 // Placement new onto an inactive union member makes it active. 3778 O->setUnion(Field, APValue()); 3779 } else { 3780 // FIXME: If O->getUnionValue() is absent, report that there's no 3781 // active union member rather than reporting the prior active union 3782 // member. We'll need to fix nullptr_t to not use APValue() as its 3783 // representation first. 3784 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3785 << handler.AccessKind << Field << !UnionField << UnionField; 3786 return handler.failed(); 3787 } 3788 } 3789 O = &O->getUnionValue(); 3790 } else 3791 O = &O->getStructField(Field->getFieldIndex()); 3792 3793 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3794 LastField = Field; 3795 if (Field->getType().isVolatileQualified()) 3796 VolatileField = Field; 3797 } else { 3798 // Next subobject is a base class. 3799 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3800 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3801 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3802 3803 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3804 } 3805 } 3806 } 3807 3808 namespace { 3809 struct ExtractSubobjectHandler { 3810 EvalInfo &Info; 3811 const Expr *E; 3812 APValue &Result; 3813 const AccessKinds AccessKind; 3814 3815 typedef bool result_type; 3816 bool failed() { return false; } 3817 bool found(APValue &Subobj, QualType SubobjType) { 3818 Result = Subobj; 3819 if (AccessKind == AK_ReadObjectRepresentation) 3820 return true; 3821 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3822 } 3823 bool found(APSInt &Value, QualType SubobjType) { 3824 Result = APValue(Value); 3825 return true; 3826 } 3827 bool found(APFloat &Value, QualType SubobjType) { 3828 Result = APValue(Value); 3829 return true; 3830 } 3831 }; 3832 } // end anonymous namespace 3833 3834 /// Extract the designated sub-object of an rvalue. 3835 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3836 const CompleteObject &Obj, 3837 const SubobjectDesignator &Sub, APValue &Result, 3838 AccessKinds AK = AK_Read) { 3839 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3840 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3841 return findSubobject(Info, E, Obj, Sub, Handler); 3842 } 3843 3844 namespace { 3845 struct ModifySubobjectHandler { 3846 EvalInfo &Info; 3847 APValue &NewVal; 3848 const Expr *E; 3849 3850 typedef bool result_type; 3851 static const AccessKinds AccessKind = AK_Assign; 3852 3853 bool checkConst(QualType QT) { 3854 // Assigning to a const object has undefined behavior. 3855 if (QT.isConstQualified()) { 3856 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3857 return false; 3858 } 3859 return true; 3860 } 3861 3862 bool failed() { return false; } 3863 bool found(APValue &Subobj, QualType SubobjType) { 3864 if (!checkConst(SubobjType)) 3865 return false; 3866 // We've been given ownership of NewVal, so just swap it in. 3867 Subobj.swap(NewVal); 3868 return true; 3869 } 3870 bool found(APSInt &Value, QualType SubobjType) { 3871 if (!checkConst(SubobjType)) 3872 return false; 3873 if (!NewVal.isInt()) { 3874 // Maybe trying to write a cast pointer value into a complex? 3875 Info.FFDiag(E); 3876 return false; 3877 } 3878 Value = NewVal.getInt(); 3879 return true; 3880 } 3881 bool found(APFloat &Value, QualType SubobjType) { 3882 if (!checkConst(SubobjType)) 3883 return false; 3884 Value = NewVal.getFloat(); 3885 return true; 3886 } 3887 }; 3888 } // end anonymous namespace 3889 3890 const AccessKinds ModifySubobjectHandler::AccessKind; 3891 3892 /// Update the designated sub-object of an rvalue to the given value. 3893 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3894 const CompleteObject &Obj, 3895 const SubobjectDesignator &Sub, 3896 APValue &NewVal) { 3897 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3898 return findSubobject(Info, E, Obj, Sub, Handler); 3899 } 3900 3901 /// Find the position where two subobject designators diverge, or equivalently 3902 /// the length of the common initial subsequence. 3903 static unsigned FindDesignatorMismatch(QualType ObjType, 3904 const SubobjectDesignator &A, 3905 const SubobjectDesignator &B, 3906 bool &WasArrayIndex) { 3907 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3908 for (/**/; I != N; ++I) { 3909 if (!ObjType.isNull() && 3910 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3911 // Next subobject is an array element. 3912 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3913 WasArrayIndex = true; 3914 return I; 3915 } 3916 if (ObjType->isAnyComplexType()) 3917 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3918 else 3919 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3920 } else { 3921 if (A.Entries[I].getAsBaseOrMember() != 3922 B.Entries[I].getAsBaseOrMember()) { 3923 WasArrayIndex = false; 3924 return I; 3925 } 3926 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3927 // Next subobject is a field. 3928 ObjType = FD->getType(); 3929 else 3930 // Next subobject is a base class. 3931 ObjType = QualType(); 3932 } 3933 } 3934 WasArrayIndex = false; 3935 return I; 3936 } 3937 3938 /// Determine whether the given subobject designators refer to elements of the 3939 /// same array object. 3940 static bool AreElementsOfSameArray(QualType ObjType, 3941 const SubobjectDesignator &A, 3942 const SubobjectDesignator &B) { 3943 if (A.Entries.size() != B.Entries.size()) 3944 return false; 3945 3946 bool IsArray = A.MostDerivedIsArrayElement; 3947 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3948 // A is a subobject of the array element. 3949 return false; 3950 3951 // If A (and B) designates an array element, the last entry will be the array 3952 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3953 // of length 1' case, and the entire path must match. 3954 bool WasArrayIndex; 3955 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3956 return CommonLength >= A.Entries.size() - IsArray; 3957 } 3958 3959 /// Find the complete object to which an LValue refers. 3960 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3961 AccessKinds AK, const LValue &LVal, 3962 QualType LValType) { 3963 if (LVal.InvalidBase) { 3964 Info.FFDiag(E); 3965 return CompleteObject(); 3966 } 3967 3968 if (!LVal.Base) { 3969 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3970 return CompleteObject(); 3971 } 3972 3973 CallStackFrame *Frame = nullptr; 3974 unsigned Depth = 0; 3975 if (LVal.getLValueCallIndex()) { 3976 std::tie(Frame, Depth) = 3977 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3978 if (!Frame) { 3979 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3980 << AK << LVal.Base.is<const ValueDecl*>(); 3981 NoteLValueLocation(Info, LVal.Base); 3982 return CompleteObject(); 3983 } 3984 } 3985 3986 bool IsAccess = isAnyAccess(AK); 3987 3988 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3989 // is not a constant expression (even if the object is non-volatile). We also 3990 // apply this rule to C++98, in order to conform to the expected 'volatile' 3991 // semantics. 3992 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3993 if (Info.getLangOpts().CPlusPlus) 3994 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3995 << AK << LValType; 3996 else 3997 Info.FFDiag(E); 3998 return CompleteObject(); 3999 } 4000 4001 // Compute value storage location and type of base object. 4002 APValue *BaseVal = nullptr; 4003 QualType BaseType = getType(LVal.Base); 4004 4005 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 4006 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4007 // This is the object whose initializer we're evaluating, so its lifetime 4008 // started in the current evaluation. 4009 BaseVal = Info.EvaluatingDeclValue; 4010 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4011 // Allow reading from a GUID declaration. 4012 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4013 if (isModification(AK)) { 4014 // All the remaining cases do not permit modification of the object. 4015 Info.FFDiag(E, diag::note_constexpr_modify_global); 4016 return CompleteObject(); 4017 } 4018 APValue &V = GD->getAsAPValue(); 4019 if (V.isAbsent()) { 4020 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4021 << GD->getType(); 4022 return CompleteObject(); 4023 } 4024 return CompleteObject(LVal.Base, &V, GD->getType()); 4025 } 4026 4027 // Allow reading from template parameter objects. 4028 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4029 if (isModification(AK)) { 4030 Info.FFDiag(E, diag::note_constexpr_modify_global); 4031 return CompleteObject(); 4032 } 4033 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4034 TPO->getType()); 4035 } 4036 4037 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4038 // In C++11, constexpr, non-volatile variables initialized with constant 4039 // expressions are constant expressions too. Inside constexpr functions, 4040 // parameters are constant expressions even if they're non-const. 4041 // In C++1y, objects local to a constant expression (those with a Frame) are 4042 // both readable and writable inside constant expressions. 4043 // In C, such things can also be folded, although they are not ICEs. 4044 const VarDecl *VD = dyn_cast<VarDecl>(D); 4045 if (VD) { 4046 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4047 VD = VDef; 4048 } 4049 if (!VD || VD->isInvalidDecl()) { 4050 Info.FFDiag(E); 4051 return CompleteObject(); 4052 } 4053 4054 bool IsConstant = BaseType.isConstant(Info.Ctx); 4055 4056 // Unless we're looking at a local variable or argument in a constexpr call, 4057 // the variable we're reading must be const. 4058 if (!Frame) { 4059 if (IsAccess && isa<ParmVarDecl>(VD)) { 4060 // Access of a parameter that's not associated with a frame isn't going 4061 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4062 // suitable diagnostic. 4063 } else if (Info.getLangOpts().CPlusPlus14 && 4064 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4065 // OK, we can read and modify an object if we're in the process of 4066 // evaluating its initializer, because its lifetime began in this 4067 // evaluation. 4068 } else if (isModification(AK)) { 4069 // All the remaining cases do not permit modification of the object. 4070 Info.FFDiag(E, diag::note_constexpr_modify_global); 4071 return CompleteObject(); 4072 } else if (VD->isConstexpr()) { 4073 // OK, we can read this variable. 4074 } else if (BaseType->isIntegralOrEnumerationType()) { 4075 if (!IsConstant) { 4076 if (!IsAccess) 4077 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4078 if (Info.getLangOpts().CPlusPlus) { 4079 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4080 Info.Note(VD->getLocation(), diag::note_declared_at); 4081 } else { 4082 Info.FFDiag(E); 4083 } 4084 return CompleteObject(); 4085 } 4086 } else if (!IsAccess) { 4087 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4088 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4089 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4090 // This variable might end up being constexpr. Don't diagnose it yet. 4091 } else if (IsConstant) { 4092 // Keep evaluating to see what we can do. In particular, we support 4093 // folding of const floating-point types, in order to make static const 4094 // data members of such types (supported as an extension) more useful. 4095 if (Info.getLangOpts().CPlusPlus) { 4096 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4097 ? diag::note_constexpr_ltor_non_constexpr 4098 : diag::note_constexpr_ltor_non_integral, 1) 4099 << VD << BaseType; 4100 Info.Note(VD->getLocation(), diag::note_declared_at); 4101 } else { 4102 Info.CCEDiag(E); 4103 } 4104 } else { 4105 // Never allow reading a non-const value. 4106 if (Info.getLangOpts().CPlusPlus) { 4107 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4108 ? diag::note_constexpr_ltor_non_constexpr 4109 : diag::note_constexpr_ltor_non_integral, 1) 4110 << VD << BaseType; 4111 Info.Note(VD->getLocation(), diag::note_declared_at); 4112 } else { 4113 Info.FFDiag(E); 4114 } 4115 return CompleteObject(); 4116 } 4117 } 4118 4119 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4120 return CompleteObject(); 4121 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4122 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4123 if (!Alloc) { 4124 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4125 return CompleteObject(); 4126 } 4127 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4128 LVal.Base.getDynamicAllocType()); 4129 } else { 4130 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4131 4132 if (!Frame) { 4133 if (const MaterializeTemporaryExpr *MTE = 4134 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4135 assert(MTE->getStorageDuration() == SD_Static && 4136 "should have a frame for a non-global materialized temporary"); 4137 4138 // C++20 [expr.const]p4: [DR2126] 4139 // An object or reference is usable in constant expressions if it is 4140 // - a temporary object of non-volatile const-qualified literal type 4141 // whose lifetime is extended to that of a variable that is usable 4142 // in constant expressions 4143 // 4144 // C++20 [expr.const]p5: 4145 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4146 // - a non-volatile glvalue that refers to an object that is usable 4147 // in constant expressions, or 4148 // - a non-volatile glvalue of literal type that refers to a 4149 // non-volatile object whose lifetime began within the evaluation 4150 // of E; 4151 // 4152 // C++11 misses the 'began within the evaluation of e' check and 4153 // instead allows all temporaries, including things like: 4154 // int &&r = 1; 4155 // int x = ++r; 4156 // constexpr int k = r; 4157 // Therefore we use the C++14-onwards rules in C++11 too. 4158 // 4159 // Note that temporaries whose lifetimes began while evaluating a 4160 // variable's constructor are not usable while evaluating the 4161 // corresponding destructor, not even if they're of const-qualified 4162 // types. 4163 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4164 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4165 if (!IsAccess) 4166 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4167 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4168 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4169 return CompleteObject(); 4170 } 4171 4172 BaseVal = MTE->getOrCreateValue(false); 4173 assert(BaseVal && "got reference to unevaluated temporary"); 4174 } else { 4175 if (!IsAccess) 4176 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4177 APValue Val; 4178 LVal.moveInto(Val); 4179 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4180 << AK 4181 << Val.getAsString(Info.Ctx, 4182 Info.Ctx.getLValueReferenceType(LValType)); 4183 NoteLValueLocation(Info, LVal.Base); 4184 return CompleteObject(); 4185 } 4186 } else { 4187 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4188 assert(BaseVal && "missing value for temporary"); 4189 } 4190 } 4191 4192 // In C++14, we can't safely access any mutable state when we might be 4193 // evaluating after an unmodeled side effect. Parameters are modeled as state 4194 // in the caller, but aren't visible once the call returns, so they can be 4195 // modified in a speculatively-evaluated call. 4196 // 4197 // FIXME: Not all local state is mutable. Allow local constant subobjects 4198 // to be read here (but take care with 'mutable' fields). 4199 unsigned VisibleDepth = Depth; 4200 if (llvm::isa_and_nonnull<ParmVarDecl>( 4201 LVal.Base.dyn_cast<const ValueDecl *>())) 4202 ++VisibleDepth; 4203 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4204 Info.EvalStatus.HasSideEffects) || 4205 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4206 return CompleteObject(); 4207 4208 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4209 } 4210 4211 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4212 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4213 /// glvalue referred to by an entity of reference type. 4214 /// 4215 /// \param Info - Information about the ongoing evaluation. 4216 /// \param Conv - The expression for which we are performing the conversion. 4217 /// Used for diagnostics. 4218 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4219 /// case of a non-class type). 4220 /// \param LVal - The glvalue on which we are attempting to perform this action. 4221 /// \param RVal - The produced value will be placed here. 4222 /// \param WantObjectRepresentation - If true, we're looking for the object 4223 /// representation rather than the value, and in particular, 4224 /// there is no requirement that the result be fully initialized. 4225 static bool 4226 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4227 const LValue &LVal, APValue &RVal, 4228 bool WantObjectRepresentation = false) { 4229 if (LVal.Designator.Invalid) 4230 return false; 4231 4232 // Check for special cases where there is no existing APValue to look at. 4233 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4234 4235 AccessKinds AK = 4236 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4237 4238 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4239 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4240 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4241 // initializer until now for such expressions. Such an expression can't be 4242 // an ICE in C, so this only matters for fold. 4243 if (Type.isVolatileQualified()) { 4244 Info.FFDiag(Conv); 4245 return false; 4246 } 4247 APValue Lit; 4248 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4249 return false; 4250 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4251 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4252 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4253 // Special-case character extraction so we don't have to construct an 4254 // APValue for the whole string. 4255 assert(LVal.Designator.Entries.size() <= 1 && 4256 "Can only read characters from string literals"); 4257 if (LVal.Designator.Entries.empty()) { 4258 // Fail for now for LValue to RValue conversion of an array. 4259 // (This shouldn't show up in C/C++, but it could be triggered by a 4260 // weird EvaluateAsRValue call from a tool.) 4261 Info.FFDiag(Conv); 4262 return false; 4263 } 4264 if (LVal.Designator.isOnePastTheEnd()) { 4265 if (Info.getLangOpts().CPlusPlus11) 4266 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4267 else 4268 Info.FFDiag(Conv); 4269 return false; 4270 } 4271 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4272 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4273 return true; 4274 } 4275 } 4276 4277 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4278 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4279 } 4280 4281 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4282 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4283 QualType LValType, APValue &Val) { 4284 if (LVal.Designator.Invalid) 4285 return false; 4286 4287 if (!Info.getLangOpts().CPlusPlus14) { 4288 Info.FFDiag(E); 4289 return false; 4290 } 4291 4292 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4293 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4294 } 4295 4296 namespace { 4297 struct CompoundAssignSubobjectHandler { 4298 EvalInfo &Info; 4299 const CompoundAssignOperator *E; 4300 QualType PromotedLHSType; 4301 BinaryOperatorKind Opcode; 4302 const APValue &RHS; 4303 4304 static const AccessKinds AccessKind = AK_Assign; 4305 4306 typedef bool result_type; 4307 4308 bool checkConst(QualType QT) { 4309 // Assigning to a const object has undefined behavior. 4310 if (QT.isConstQualified()) { 4311 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4312 return false; 4313 } 4314 return true; 4315 } 4316 4317 bool failed() { return false; } 4318 bool found(APValue &Subobj, QualType SubobjType) { 4319 switch (Subobj.getKind()) { 4320 case APValue::Int: 4321 return found(Subobj.getInt(), SubobjType); 4322 case APValue::Float: 4323 return found(Subobj.getFloat(), SubobjType); 4324 case APValue::ComplexInt: 4325 case APValue::ComplexFloat: 4326 // FIXME: Implement complex compound assignment. 4327 Info.FFDiag(E); 4328 return false; 4329 case APValue::LValue: 4330 return foundPointer(Subobj, SubobjType); 4331 case APValue::Vector: 4332 return foundVector(Subobj, SubobjType); 4333 default: 4334 // FIXME: can this happen? 4335 Info.FFDiag(E); 4336 return false; 4337 } 4338 } 4339 4340 bool foundVector(APValue &Value, QualType SubobjType) { 4341 if (!checkConst(SubobjType)) 4342 return false; 4343 4344 if (!SubobjType->isVectorType()) { 4345 Info.FFDiag(E); 4346 return false; 4347 } 4348 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4349 } 4350 4351 bool found(APSInt &Value, QualType SubobjType) { 4352 if (!checkConst(SubobjType)) 4353 return false; 4354 4355 if (!SubobjType->isIntegerType()) { 4356 // We don't support compound assignment on integer-cast-to-pointer 4357 // values. 4358 Info.FFDiag(E); 4359 return false; 4360 } 4361 4362 if (RHS.isInt()) { 4363 APSInt LHS = 4364 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4365 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4366 return false; 4367 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4368 return true; 4369 } else if (RHS.isFloat()) { 4370 const FPOptions FPO = E->getFPFeaturesInEffect( 4371 Info.Ctx.getLangOpts()); 4372 APFloat FValue(0.0); 4373 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4374 PromotedLHSType, FValue) && 4375 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4376 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4377 Value); 4378 } 4379 4380 Info.FFDiag(E); 4381 return false; 4382 } 4383 bool found(APFloat &Value, QualType SubobjType) { 4384 return checkConst(SubobjType) && 4385 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4386 Value) && 4387 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4388 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4389 } 4390 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4391 if (!checkConst(SubobjType)) 4392 return false; 4393 4394 QualType PointeeType; 4395 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4396 PointeeType = PT->getPointeeType(); 4397 4398 if (PointeeType.isNull() || !RHS.isInt() || 4399 (Opcode != BO_Add && Opcode != BO_Sub)) { 4400 Info.FFDiag(E); 4401 return false; 4402 } 4403 4404 APSInt Offset = RHS.getInt(); 4405 if (Opcode == BO_Sub) 4406 negateAsSigned(Offset); 4407 4408 LValue LVal; 4409 LVal.setFrom(Info.Ctx, Subobj); 4410 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4411 return false; 4412 LVal.moveInto(Subobj); 4413 return true; 4414 } 4415 }; 4416 } // end anonymous namespace 4417 4418 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4419 4420 /// Perform a compound assignment of LVal <op>= RVal. 4421 static bool handleCompoundAssignment(EvalInfo &Info, 4422 const CompoundAssignOperator *E, 4423 const LValue &LVal, QualType LValType, 4424 QualType PromotedLValType, 4425 BinaryOperatorKind Opcode, 4426 const APValue &RVal) { 4427 if (LVal.Designator.Invalid) 4428 return false; 4429 4430 if (!Info.getLangOpts().CPlusPlus14) { 4431 Info.FFDiag(E); 4432 return false; 4433 } 4434 4435 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4436 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4437 RVal }; 4438 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4439 } 4440 4441 namespace { 4442 struct IncDecSubobjectHandler { 4443 EvalInfo &Info; 4444 const UnaryOperator *E; 4445 AccessKinds AccessKind; 4446 APValue *Old; 4447 4448 typedef bool result_type; 4449 4450 bool checkConst(QualType QT) { 4451 // Assigning to a const object has undefined behavior. 4452 if (QT.isConstQualified()) { 4453 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4454 return false; 4455 } 4456 return true; 4457 } 4458 4459 bool failed() { return false; } 4460 bool found(APValue &Subobj, QualType SubobjType) { 4461 // Stash the old value. Also clear Old, so we don't clobber it later 4462 // if we're post-incrementing a complex. 4463 if (Old) { 4464 *Old = Subobj; 4465 Old = nullptr; 4466 } 4467 4468 switch (Subobj.getKind()) { 4469 case APValue::Int: 4470 return found(Subobj.getInt(), SubobjType); 4471 case APValue::Float: 4472 return found(Subobj.getFloat(), SubobjType); 4473 case APValue::ComplexInt: 4474 return found(Subobj.getComplexIntReal(), 4475 SubobjType->castAs<ComplexType>()->getElementType() 4476 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4477 case APValue::ComplexFloat: 4478 return found(Subobj.getComplexFloatReal(), 4479 SubobjType->castAs<ComplexType>()->getElementType() 4480 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4481 case APValue::LValue: 4482 return foundPointer(Subobj, SubobjType); 4483 default: 4484 // FIXME: can this happen? 4485 Info.FFDiag(E); 4486 return false; 4487 } 4488 } 4489 bool found(APSInt &Value, QualType SubobjType) { 4490 if (!checkConst(SubobjType)) 4491 return false; 4492 4493 if (!SubobjType->isIntegerType()) { 4494 // We don't support increment / decrement on integer-cast-to-pointer 4495 // values. 4496 Info.FFDiag(E); 4497 return false; 4498 } 4499 4500 if (Old) *Old = APValue(Value); 4501 4502 // bool arithmetic promotes to int, and the conversion back to bool 4503 // doesn't reduce mod 2^n, so special-case it. 4504 if (SubobjType->isBooleanType()) { 4505 if (AccessKind == AK_Increment) 4506 Value = 1; 4507 else 4508 Value = !Value; 4509 return true; 4510 } 4511 4512 bool WasNegative = Value.isNegative(); 4513 if (AccessKind == AK_Increment) { 4514 ++Value; 4515 4516 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4517 APSInt ActualValue(Value, /*IsUnsigned*/true); 4518 return HandleOverflow(Info, E, ActualValue, SubobjType); 4519 } 4520 } else { 4521 --Value; 4522 4523 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4524 unsigned BitWidth = Value.getBitWidth(); 4525 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4526 ActualValue.setBit(BitWidth); 4527 return HandleOverflow(Info, E, ActualValue, SubobjType); 4528 } 4529 } 4530 return true; 4531 } 4532 bool found(APFloat &Value, QualType SubobjType) { 4533 if (!checkConst(SubobjType)) 4534 return false; 4535 4536 if (Old) *Old = APValue(Value); 4537 4538 APFloat One(Value.getSemantics(), 1); 4539 if (AccessKind == AK_Increment) 4540 Value.add(One, APFloat::rmNearestTiesToEven); 4541 else 4542 Value.subtract(One, APFloat::rmNearestTiesToEven); 4543 return true; 4544 } 4545 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4546 if (!checkConst(SubobjType)) 4547 return false; 4548 4549 QualType PointeeType; 4550 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4551 PointeeType = PT->getPointeeType(); 4552 else { 4553 Info.FFDiag(E); 4554 return false; 4555 } 4556 4557 LValue LVal; 4558 LVal.setFrom(Info.Ctx, Subobj); 4559 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4560 AccessKind == AK_Increment ? 1 : -1)) 4561 return false; 4562 LVal.moveInto(Subobj); 4563 return true; 4564 } 4565 }; 4566 } // end anonymous namespace 4567 4568 /// Perform an increment or decrement on LVal. 4569 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4570 QualType LValType, bool IsIncrement, APValue *Old) { 4571 if (LVal.Designator.Invalid) 4572 return false; 4573 4574 if (!Info.getLangOpts().CPlusPlus14) { 4575 Info.FFDiag(E); 4576 return false; 4577 } 4578 4579 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4580 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4581 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4582 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4583 } 4584 4585 /// Build an lvalue for the object argument of a member function call. 4586 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4587 LValue &This) { 4588 if (Object->getType()->isPointerType() && Object->isPRValue()) 4589 return EvaluatePointer(Object, This, Info); 4590 4591 if (Object->isGLValue()) 4592 return EvaluateLValue(Object, This, Info); 4593 4594 if (Object->getType()->isLiteralType(Info.Ctx)) 4595 return EvaluateTemporary(Object, This, Info); 4596 4597 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4598 return false; 4599 } 4600 4601 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4602 /// lvalue referring to the result. 4603 /// 4604 /// \param Info - Information about the ongoing evaluation. 4605 /// \param LV - An lvalue referring to the base of the member pointer. 4606 /// \param RHS - The member pointer expression. 4607 /// \param IncludeMember - Specifies whether the member itself is included in 4608 /// the resulting LValue subobject designator. This is not possible when 4609 /// creating a bound member function. 4610 /// \return The field or method declaration to which the member pointer refers, 4611 /// or 0 if evaluation fails. 4612 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4613 QualType LVType, 4614 LValue &LV, 4615 const Expr *RHS, 4616 bool IncludeMember = true) { 4617 MemberPtr MemPtr; 4618 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4619 return nullptr; 4620 4621 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4622 // member value, the behavior is undefined. 4623 if (!MemPtr.getDecl()) { 4624 // FIXME: Specific diagnostic. 4625 Info.FFDiag(RHS); 4626 return nullptr; 4627 } 4628 4629 if (MemPtr.isDerivedMember()) { 4630 // This is a member of some derived class. Truncate LV appropriately. 4631 // The end of the derived-to-base path for the base object must match the 4632 // derived-to-base path for the member pointer. 4633 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4634 LV.Designator.Entries.size()) { 4635 Info.FFDiag(RHS); 4636 return nullptr; 4637 } 4638 unsigned PathLengthToMember = 4639 LV.Designator.Entries.size() - MemPtr.Path.size(); 4640 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4641 const CXXRecordDecl *LVDecl = getAsBaseClass( 4642 LV.Designator.Entries[PathLengthToMember + I]); 4643 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4644 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4645 Info.FFDiag(RHS); 4646 return nullptr; 4647 } 4648 } 4649 4650 // Truncate the lvalue to the appropriate derived class. 4651 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4652 PathLengthToMember)) 4653 return nullptr; 4654 } else if (!MemPtr.Path.empty()) { 4655 // Extend the LValue path with the member pointer's path. 4656 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4657 MemPtr.Path.size() + IncludeMember); 4658 4659 // Walk down to the appropriate base class. 4660 if (const PointerType *PT = LVType->getAs<PointerType>()) 4661 LVType = PT->getPointeeType(); 4662 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4663 assert(RD && "member pointer access on non-class-type expression"); 4664 // The first class in the path is that of the lvalue. 4665 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4666 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4667 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4668 return nullptr; 4669 RD = Base; 4670 } 4671 // Finally cast to the class containing the member. 4672 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4673 MemPtr.getContainingRecord())) 4674 return nullptr; 4675 } 4676 4677 // Add the member. Note that we cannot build bound member functions here. 4678 if (IncludeMember) { 4679 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4680 if (!HandleLValueMember(Info, RHS, LV, FD)) 4681 return nullptr; 4682 } else if (const IndirectFieldDecl *IFD = 4683 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4684 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4685 return nullptr; 4686 } else { 4687 llvm_unreachable("can't construct reference to bound member function"); 4688 } 4689 } 4690 4691 return MemPtr.getDecl(); 4692 } 4693 4694 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4695 const BinaryOperator *BO, 4696 LValue &LV, 4697 bool IncludeMember = true) { 4698 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4699 4700 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4701 if (Info.noteFailure()) { 4702 MemberPtr MemPtr; 4703 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4704 } 4705 return nullptr; 4706 } 4707 4708 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4709 BO->getRHS(), IncludeMember); 4710 } 4711 4712 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4713 /// the provided lvalue, which currently refers to the base object. 4714 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4715 LValue &Result) { 4716 SubobjectDesignator &D = Result.Designator; 4717 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4718 return false; 4719 4720 QualType TargetQT = E->getType(); 4721 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4722 TargetQT = PT->getPointeeType(); 4723 4724 // Check this cast lands within the final derived-to-base subobject path. 4725 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4726 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4727 << D.MostDerivedType << TargetQT; 4728 return false; 4729 } 4730 4731 // Check the type of the final cast. We don't need to check the path, 4732 // since a cast can only be formed if the path is unique. 4733 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4734 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4735 const CXXRecordDecl *FinalType; 4736 if (NewEntriesSize == D.MostDerivedPathLength) 4737 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4738 else 4739 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4740 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4741 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4742 << D.MostDerivedType << TargetQT; 4743 return false; 4744 } 4745 4746 // Truncate the lvalue to the appropriate derived class. 4747 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4748 } 4749 4750 /// Get the value to use for a default-initialized object of type T. 4751 /// Return false if it encounters something invalid. 4752 static bool getDefaultInitValue(QualType T, APValue &Result) { 4753 bool Success = true; 4754 if (auto *RD = T->getAsCXXRecordDecl()) { 4755 if (RD->isInvalidDecl()) { 4756 Result = APValue(); 4757 return false; 4758 } 4759 if (RD->isUnion()) { 4760 Result = APValue((const FieldDecl *)nullptr); 4761 return true; 4762 } 4763 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4764 std::distance(RD->field_begin(), RD->field_end())); 4765 4766 unsigned Index = 0; 4767 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4768 End = RD->bases_end(); 4769 I != End; ++I, ++Index) 4770 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4771 4772 for (const auto *I : RD->fields()) { 4773 if (I->isUnnamedBitfield()) 4774 continue; 4775 Success &= getDefaultInitValue(I->getType(), 4776 Result.getStructField(I->getFieldIndex())); 4777 } 4778 return Success; 4779 } 4780 4781 if (auto *AT = 4782 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4783 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4784 if (Result.hasArrayFiller()) 4785 Success &= 4786 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4787 4788 return Success; 4789 } 4790 4791 Result = APValue::IndeterminateValue(); 4792 return true; 4793 } 4794 4795 namespace { 4796 enum EvalStmtResult { 4797 /// Evaluation failed. 4798 ESR_Failed, 4799 /// Hit a 'return' statement. 4800 ESR_Returned, 4801 /// Evaluation succeeded. 4802 ESR_Succeeded, 4803 /// Hit a 'continue' statement. 4804 ESR_Continue, 4805 /// Hit a 'break' statement. 4806 ESR_Break, 4807 /// Still scanning for 'case' or 'default' statement. 4808 ESR_CaseNotFound 4809 }; 4810 } 4811 4812 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4813 // We don't need to evaluate the initializer for a static local. 4814 if (!VD->hasLocalStorage()) 4815 return true; 4816 4817 LValue Result; 4818 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4819 ScopeKind::Block, Result); 4820 4821 const Expr *InitE = VD->getInit(); 4822 if (!InitE) { 4823 if (VD->getType()->isDependentType()) 4824 return Info.noteSideEffect(); 4825 return getDefaultInitValue(VD->getType(), Val); 4826 } 4827 if (InitE->isValueDependent()) 4828 return false; 4829 4830 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4831 // Wipe out any partially-computed value, to allow tracking that this 4832 // evaluation failed. 4833 Val = APValue(); 4834 return false; 4835 } 4836 4837 return true; 4838 } 4839 4840 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4841 bool OK = true; 4842 4843 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4844 OK &= EvaluateVarDecl(Info, VD); 4845 4846 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4847 for (auto *BD : DD->bindings()) 4848 if (auto *VD = BD->getHoldingVar()) 4849 OK &= EvaluateDecl(Info, VD); 4850 4851 return OK; 4852 } 4853 4854 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4855 assert(E->isValueDependent()); 4856 if (Info.noteSideEffect()) 4857 return true; 4858 assert(E->containsErrors() && "valid value-dependent expression should never " 4859 "reach invalid code path."); 4860 return false; 4861 } 4862 4863 /// Evaluate a condition (either a variable declaration or an expression). 4864 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4865 const Expr *Cond, bool &Result) { 4866 if (Cond->isValueDependent()) 4867 return false; 4868 FullExpressionRAII Scope(Info); 4869 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4870 return false; 4871 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4872 return false; 4873 return Scope.destroy(); 4874 } 4875 4876 namespace { 4877 /// A location where the result (returned value) of evaluating a 4878 /// statement should be stored. 4879 struct StmtResult { 4880 /// The APValue that should be filled in with the returned value. 4881 APValue &Value; 4882 /// The location containing the result, if any (used to support RVO). 4883 const LValue *Slot; 4884 }; 4885 4886 struct TempVersionRAII { 4887 CallStackFrame &Frame; 4888 4889 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4890 Frame.pushTempVersion(); 4891 } 4892 4893 ~TempVersionRAII() { 4894 Frame.popTempVersion(); 4895 } 4896 }; 4897 4898 } 4899 4900 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4901 const Stmt *S, 4902 const SwitchCase *SC = nullptr); 4903 4904 /// Evaluate the body of a loop, and translate the result as appropriate. 4905 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4906 const Stmt *Body, 4907 const SwitchCase *Case = nullptr) { 4908 BlockScopeRAII Scope(Info); 4909 4910 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4911 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4912 ESR = ESR_Failed; 4913 4914 switch (ESR) { 4915 case ESR_Break: 4916 return ESR_Succeeded; 4917 case ESR_Succeeded: 4918 case ESR_Continue: 4919 return ESR_Continue; 4920 case ESR_Failed: 4921 case ESR_Returned: 4922 case ESR_CaseNotFound: 4923 return ESR; 4924 } 4925 llvm_unreachable("Invalid EvalStmtResult!"); 4926 } 4927 4928 /// Evaluate a switch statement. 4929 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4930 const SwitchStmt *SS) { 4931 BlockScopeRAII Scope(Info); 4932 4933 // Evaluate the switch condition. 4934 APSInt Value; 4935 { 4936 if (const Stmt *Init = SS->getInit()) { 4937 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4938 if (ESR != ESR_Succeeded) { 4939 if (ESR != ESR_Failed && !Scope.destroy()) 4940 ESR = ESR_Failed; 4941 return ESR; 4942 } 4943 } 4944 4945 FullExpressionRAII CondScope(Info); 4946 if (SS->getConditionVariable() && 4947 !EvaluateDecl(Info, SS->getConditionVariable())) 4948 return ESR_Failed; 4949 if (SS->getCond()->isValueDependent()) { 4950 if (!EvaluateDependentExpr(SS->getCond(), Info)) 4951 return ESR_Failed; 4952 } else { 4953 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4954 return ESR_Failed; 4955 } 4956 if (!CondScope.destroy()) 4957 return ESR_Failed; 4958 } 4959 4960 // Find the switch case corresponding to the value of the condition. 4961 // FIXME: Cache this lookup. 4962 const SwitchCase *Found = nullptr; 4963 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4964 SC = SC->getNextSwitchCase()) { 4965 if (isa<DefaultStmt>(SC)) { 4966 Found = SC; 4967 continue; 4968 } 4969 4970 const CaseStmt *CS = cast<CaseStmt>(SC); 4971 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4972 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4973 : LHS; 4974 if (LHS <= Value && Value <= RHS) { 4975 Found = SC; 4976 break; 4977 } 4978 } 4979 4980 if (!Found) 4981 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4982 4983 // Search the switch body for the switch case and evaluate it from there. 4984 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4985 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4986 return ESR_Failed; 4987 4988 switch (ESR) { 4989 case ESR_Break: 4990 return ESR_Succeeded; 4991 case ESR_Succeeded: 4992 case ESR_Continue: 4993 case ESR_Failed: 4994 case ESR_Returned: 4995 return ESR; 4996 case ESR_CaseNotFound: 4997 // This can only happen if the switch case is nested within a statement 4998 // expression. We have no intention of supporting that. 4999 Info.FFDiag(Found->getBeginLoc(), 5000 diag::note_constexpr_stmt_expr_unsupported); 5001 return ESR_Failed; 5002 } 5003 llvm_unreachable("Invalid EvalStmtResult!"); 5004 } 5005 5006 // Evaluate a statement. 5007 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 5008 const Stmt *S, const SwitchCase *Case) { 5009 if (!Info.nextStep(S)) 5010 return ESR_Failed; 5011 5012 // If we're hunting down a 'case' or 'default' label, recurse through 5013 // substatements until we hit the label. 5014 if (Case) { 5015 switch (S->getStmtClass()) { 5016 case Stmt::CompoundStmtClass: 5017 // FIXME: Precompute which substatement of a compound statement we 5018 // would jump to, and go straight there rather than performing a 5019 // linear scan each time. 5020 case Stmt::LabelStmtClass: 5021 case Stmt::AttributedStmtClass: 5022 case Stmt::DoStmtClass: 5023 break; 5024 5025 case Stmt::CaseStmtClass: 5026 case Stmt::DefaultStmtClass: 5027 if (Case == S) 5028 Case = nullptr; 5029 break; 5030 5031 case Stmt::IfStmtClass: { 5032 // FIXME: Precompute which side of an 'if' we would jump to, and go 5033 // straight there rather than scanning both sides. 5034 const IfStmt *IS = cast<IfStmt>(S); 5035 5036 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5037 // preceded by our switch label. 5038 BlockScopeRAII Scope(Info); 5039 5040 // Step into the init statement in case it brings an (uninitialized) 5041 // variable into scope. 5042 if (const Stmt *Init = IS->getInit()) { 5043 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5044 if (ESR != ESR_CaseNotFound) { 5045 assert(ESR != ESR_Succeeded); 5046 return ESR; 5047 } 5048 } 5049 5050 // Condition variable must be initialized if it exists. 5051 // FIXME: We can skip evaluating the body if there's a condition 5052 // variable, as there can't be any case labels within it. 5053 // (The same is true for 'for' statements.) 5054 5055 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5056 if (ESR == ESR_Failed) 5057 return ESR; 5058 if (ESR != ESR_CaseNotFound) 5059 return Scope.destroy() ? ESR : ESR_Failed; 5060 if (!IS->getElse()) 5061 return ESR_CaseNotFound; 5062 5063 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5064 if (ESR == ESR_Failed) 5065 return ESR; 5066 if (ESR != ESR_CaseNotFound) 5067 return Scope.destroy() ? ESR : ESR_Failed; 5068 return ESR_CaseNotFound; 5069 } 5070 5071 case Stmt::WhileStmtClass: { 5072 EvalStmtResult ESR = 5073 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5074 if (ESR != ESR_Continue) 5075 return ESR; 5076 break; 5077 } 5078 5079 case Stmt::ForStmtClass: { 5080 const ForStmt *FS = cast<ForStmt>(S); 5081 BlockScopeRAII Scope(Info); 5082 5083 // Step into the init statement in case it brings an (uninitialized) 5084 // variable into scope. 5085 if (const Stmt *Init = FS->getInit()) { 5086 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5087 if (ESR != ESR_CaseNotFound) { 5088 assert(ESR != ESR_Succeeded); 5089 return ESR; 5090 } 5091 } 5092 5093 EvalStmtResult ESR = 5094 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5095 if (ESR != ESR_Continue) 5096 return ESR; 5097 if (const auto *Inc = FS->getInc()) { 5098 if (Inc->isValueDependent()) { 5099 if (!EvaluateDependentExpr(Inc, Info)) 5100 return ESR_Failed; 5101 } else { 5102 FullExpressionRAII IncScope(Info); 5103 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5104 return ESR_Failed; 5105 } 5106 } 5107 break; 5108 } 5109 5110 case Stmt::DeclStmtClass: { 5111 // Start the lifetime of any uninitialized variables we encounter. They 5112 // might be used by the selected branch of the switch. 5113 const DeclStmt *DS = cast<DeclStmt>(S); 5114 for (const auto *D : DS->decls()) { 5115 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5116 if (VD->hasLocalStorage() && !VD->getInit()) 5117 if (!EvaluateVarDecl(Info, VD)) 5118 return ESR_Failed; 5119 // FIXME: If the variable has initialization that can't be jumped 5120 // over, bail out of any immediately-surrounding compound-statement 5121 // too. There can't be any case labels here. 5122 } 5123 } 5124 return ESR_CaseNotFound; 5125 } 5126 5127 default: 5128 return ESR_CaseNotFound; 5129 } 5130 } 5131 5132 switch (S->getStmtClass()) { 5133 default: 5134 if (const Expr *E = dyn_cast<Expr>(S)) { 5135 if (E->isValueDependent()) { 5136 if (!EvaluateDependentExpr(E, Info)) 5137 return ESR_Failed; 5138 } else { 5139 // Don't bother evaluating beyond an expression-statement which couldn't 5140 // be evaluated. 5141 // FIXME: Do we need the FullExpressionRAII object here? 5142 // VisitExprWithCleanups should create one when necessary. 5143 FullExpressionRAII Scope(Info); 5144 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5145 return ESR_Failed; 5146 } 5147 return ESR_Succeeded; 5148 } 5149 5150 Info.FFDiag(S->getBeginLoc()); 5151 return ESR_Failed; 5152 5153 case Stmt::NullStmtClass: 5154 return ESR_Succeeded; 5155 5156 case Stmt::DeclStmtClass: { 5157 const DeclStmt *DS = cast<DeclStmt>(S); 5158 for (const auto *D : DS->decls()) { 5159 // Each declaration initialization is its own full-expression. 5160 FullExpressionRAII Scope(Info); 5161 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5162 return ESR_Failed; 5163 if (!Scope.destroy()) 5164 return ESR_Failed; 5165 } 5166 return ESR_Succeeded; 5167 } 5168 5169 case Stmt::ReturnStmtClass: { 5170 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5171 FullExpressionRAII Scope(Info); 5172 if (RetExpr && RetExpr->isValueDependent()) { 5173 EvaluateDependentExpr(RetExpr, Info); 5174 // We know we returned, but we don't know what the value is. 5175 return ESR_Failed; 5176 } 5177 if (RetExpr && 5178 !(Result.Slot 5179 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5180 : Evaluate(Result.Value, Info, RetExpr))) 5181 return ESR_Failed; 5182 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5183 } 5184 5185 case Stmt::CompoundStmtClass: { 5186 BlockScopeRAII Scope(Info); 5187 5188 const CompoundStmt *CS = cast<CompoundStmt>(S); 5189 for (const auto *BI : CS->body()) { 5190 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5191 if (ESR == ESR_Succeeded) 5192 Case = nullptr; 5193 else if (ESR != ESR_CaseNotFound) { 5194 if (ESR != ESR_Failed && !Scope.destroy()) 5195 return ESR_Failed; 5196 return ESR; 5197 } 5198 } 5199 if (Case) 5200 return ESR_CaseNotFound; 5201 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5202 } 5203 5204 case Stmt::IfStmtClass: { 5205 const IfStmt *IS = cast<IfStmt>(S); 5206 5207 // Evaluate the condition, as either a var decl or as an expression. 5208 BlockScopeRAII Scope(Info); 5209 if (const Stmt *Init = IS->getInit()) { 5210 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5211 if (ESR != ESR_Succeeded) { 5212 if (ESR != ESR_Failed && !Scope.destroy()) 5213 return ESR_Failed; 5214 return ESR; 5215 } 5216 } 5217 bool Cond; 5218 if (IS->isConsteval()) 5219 Cond = IS->isNonNegatedConsteval(); 5220 else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5221 Cond)) 5222 return ESR_Failed; 5223 5224 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5225 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5226 if (ESR != ESR_Succeeded) { 5227 if (ESR != ESR_Failed && !Scope.destroy()) 5228 return ESR_Failed; 5229 return ESR; 5230 } 5231 } 5232 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5233 } 5234 5235 case Stmt::WhileStmtClass: { 5236 const WhileStmt *WS = cast<WhileStmt>(S); 5237 while (true) { 5238 BlockScopeRAII Scope(Info); 5239 bool Continue; 5240 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5241 Continue)) 5242 return ESR_Failed; 5243 if (!Continue) 5244 break; 5245 5246 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5247 if (ESR != ESR_Continue) { 5248 if (ESR != ESR_Failed && !Scope.destroy()) 5249 return ESR_Failed; 5250 return ESR; 5251 } 5252 if (!Scope.destroy()) 5253 return ESR_Failed; 5254 } 5255 return ESR_Succeeded; 5256 } 5257 5258 case Stmt::DoStmtClass: { 5259 const DoStmt *DS = cast<DoStmt>(S); 5260 bool Continue; 5261 do { 5262 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5263 if (ESR != ESR_Continue) 5264 return ESR; 5265 Case = nullptr; 5266 5267 if (DS->getCond()->isValueDependent()) { 5268 EvaluateDependentExpr(DS->getCond(), Info); 5269 // Bailout as we don't know whether to keep going or terminate the loop. 5270 return ESR_Failed; 5271 } 5272 FullExpressionRAII CondScope(Info); 5273 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5274 !CondScope.destroy()) 5275 return ESR_Failed; 5276 } while (Continue); 5277 return ESR_Succeeded; 5278 } 5279 5280 case Stmt::ForStmtClass: { 5281 const ForStmt *FS = cast<ForStmt>(S); 5282 BlockScopeRAII ForScope(Info); 5283 if (FS->getInit()) { 5284 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5285 if (ESR != ESR_Succeeded) { 5286 if (ESR != ESR_Failed && !ForScope.destroy()) 5287 return ESR_Failed; 5288 return ESR; 5289 } 5290 } 5291 while (true) { 5292 BlockScopeRAII IterScope(Info); 5293 bool Continue = true; 5294 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5295 FS->getCond(), Continue)) 5296 return ESR_Failed; 5297 if (!Continue) 5298 break; 5299 5300 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5301 if (ESR != ESR_Continue) { 5302 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5303 return ESR_Failed; 5304 return ESR; 5305 } 5306 5307 if (const auto *Inc = FS->getInc()) { 5308 if (Inc->isValueDependent()) { 5309 if (!EvaluateDependentExpr(Inc, Info)) 5310 return ESR_Failed; 5311 } else { 5312 FullExpressionRAII IncScope(Info); 5313 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5314 return ESR_Failed; 5315 } 5316 } 5317 5318 if (!IterScope.destroy()) 5319 return ESR_Failed; 5320 } 5321 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5322 } 5323 5324 case Stmt::CXXForRangeStmtClass: { 5325 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5326 BlockScopeRAII Scope(Info); 5327 5328 // Evaluate the init-statement if present. 5329 if (FS->getInit()) { 5330 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5331 if (ESR != ESR_Succeeded) { 5332 if (ESR != ESR_Failed && !Scope.destroy()) 5333 return ESR_Failed; 5334 return ESR; 5335 } 5336 } 5337 5338 // Initialize the __range variable. 5339 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5340 if (ESR != ESR_Succeeded) { 5341 if (ESR != ESR_Failed && !Scope.destroy()) 5342 return ESR_Failed; 5343 return ESR; 5344 } 5345 5346 // In error-recovery cases it's possible to get here even if we failed to 5347 // synthesize the __begin and __end variables. 5348 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5349 return ESR_Failed; 5350 5351 // Create the __begin and __end iterators. 5352 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5353 if (ESR != ESR_Succeeded) { 5354 if (ESR != ESR_Failed && !Scope.destroy()) 5355 return ESR_Failed; 5356 return ESR; 5357 } 5358 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5359 if (ESR != ESR_Succeeded) { 5360 if (ESR != ESR_Failed && !Scope.destroy()) 5361 return ESR_Failed; 5362 return ESR; 5363 } 5364 5365 while (true) { 5366 // Condition: __begin != __end. 5367 { 5368 if (FS->getCond()->isValueDependent()) { 5369 EvaluateDependentExpr(FS->getCond(), Info); 5370 // We don't know whether to keep going or terminate the loop. 5371 return ESR_Failed; 5372 } 5373 bool Continue = true; 5374 FullExpressionRAII CondExpr(Info); 5375 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5376 return ESR_Failed; 5377 if (!Continue) 5378 break; 5379 } 5380 5381 // User's variable declaration, initialized by *__begin. 5382 BlockScopeRAII InnerScope(Info); 5383 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5384 if (ESR != ESR_Succeeded) { 5385 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5386 return ESR_Failed; 5387 return ESR; 5388 } 5389 5390 // Loop body. 5391 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5392 if (ESR != ESR_Continue) { 5393 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5394 return ESR_Failed; 5395 return ESR; 5396 } 5397 if (FS->getInc()->isValueDependent()) { 5398 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5399 return ESR_Failed; 5400 } else { 5401 // Increment: ++__begin 5402 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5403 return ESR_Failed; 5404 } 5405 5406 if (!InnerScope.destroy()) 5407 return ESR_Failed; 5408 } 5409 5410 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5411 } 5412 5413 case Stmt::SwitchStmtClass: 5414 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5415 5416 case Stmt::ContinueStmtClass: 5417 return ESR_Continue; 5418 5419 case Stmt::BreakStmtClass: 5420 return ESR_Break; 5421 5422 case Stmt::LabelStmtClass: 5423 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5424 5425 case Stmt::AttributedStmtClass: 5426 // As a general principle, C++11 attributes can be ignored without 5427 // any semantic impact. 5428 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5429 Case); 5430 5431 case Stmt::CaseStmtClass: 5432 case Stmt::DefaultStmtClass: 5433 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5434 case Stmt::CXXTryStmtClass: 5435 // Evaluate try blocks by evaluating all sub statements. 5436 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5437 } 5438 } 5439 5440 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5441 /// default constructor. If so, we'll fold it whether or not it's marked as 5442 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5443 /// so we need special handling. 5444 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5445 const CXXConstructorDecl *CD, 5446 bool IsValueInitialization) { 5447 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5448 return false; 5449 5450 // Value-initialization does not call a trivial default constructor, so such a 5451 // call is a core constant expression whether or not the constructor is 5452 // constexpr. 5453 if (!CD->isConstexpr() && !IsValueInitialization) { 5454 if (Info.getLangOpts().CPlusPlus11) { 5455 // FIXME: If DiagDecl is an implicitly-declared special member function, 5456 // we should be much more explicit about why it's not constexpr. 5457 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5458 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5459 Info.Note(CD->getLocation(), diag::note_declared_at); 5460 } else { 5461 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5462 } 5463 } 5464 return true; 5465 } 5466 5467 /// CheckConstexprFunction - Check that a function can be called in a constant 5468 /// expression. 5469 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5470 const FunctionDecl *Declaration, 5471 const FunctionDecl *Definition, 5472 const Stmt *Body) { 5473 // Potential constant expressions can contain calls to declared, but not yet 5474 // defined, constexpr functions. 5475 if (Info.checkingPotentialConstantExpression() && !Definition && 5476 Declaration->isConstexpr()) 5477 return false; 5478 5479 // Bail out if the function declaration itself is invalid. We will 5480 // have produced a relevant diagnostic while parsing it, so just 5481 // note the problematic sub-expression. 5482 if (Declaration->isInvalidDecl()) { 5483 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5484 return false; 5485 } 5486 5487 // DR1872: An instantiated virtual constexpr function can't be called in a 5488 // constant expression (prior to C++20). We can still constant-fold such a 5489 // call. 5490 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5491 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5492 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5493 5494 if (Definition && Definition->isInvalidDecl()) { 5495 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5496 return false; 5497 } 5498 5499 // Can we evaluate this function call? 5500 if (Definition && Definition->isConstexpr() && Body) 5501 return true; 5502 5503 if (Info.getLangOpts().CPlusPlus11) { 5504 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5505 5506 // If this function is not constexpr because it is an inherited 5507 // non-constexpr constructor, diagnose that directly. 5508 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5509 if (CD && CD->isInheritingConstructor()) { 5510 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5511 if (!Inherited->isConstexpr()) 5512 DiagDecl = CD = Inherited; 5513 } 5514 5515 // FIXME: If DiagDecl is an implicitly-declared special member function 5516 // or an inheriting constructor, we should be much more explicit about why 5517 // it's not constexpr. 5518 if (CD && CD->isInheritingConstructor()) 5519 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5520 << CD->getInheritedConstructor().getConstructor()->getParent(); 5521 else 5522 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5523 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5524 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5525 } else { 5526 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5527 } 5528 return false; 5529 } 5530 5531 namespace { 5532 struct CheckDynamicTypeHandler { 5533 AccessKinds AccessKind; 5534 typedef bool result_type; 5535 bool failed() { return false; } 5536 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5537 bool found(APSInt &Value, QualType SubobjType) { return true; } 5538 bool found(APFloat &Value, QualType SubobjType) { return true; } 5539 }; 5540 } // end anonymous namespace 5541 5542 /// Check that we can access the notional vptr of an object / determine its 5543 /// dynamic type. 5544 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5545 AccessKinds AK, bool Polymorphic) { 5546 if (This.Designator.Invalid) 5547 return false; 5548 5549 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5550 5551 if (!Obj) 5552 return false; 5553 5554 if (!Obj.Value) { 5555 // The object is not usable in constant expressions, so we can't inspect 5556 // its value to see if it's in-lifetime or what the active union members 5557 // are. We can still check for a one-past-the-end lvalue. 5558 if (This.Designator.isOnePastTheEnd() || 5559 This.Designator.isMostDerivedAnUnsizedArray()) { 5560 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5561 ? diag::note_constexpr_access_past_end 5562 : diag::note_constexpr_access_unsized_array) 5563 << AK; 5564 return false; 5565 } else if (Polymorphic) { 5566 // Conservatively refuse to perform a polymorphic operation if we would 5567 // not be able to read a notional 'vptr' value. 5568 APValue Val; 5569 This.moveInto(Val); 5570 QualType StarThisType = 5571 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5572 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5573 << AK << Val.getAsString(Info.Ctx, StarThisType); 5574 return false; 5575 } 5576 return true; 5577 } 5578 5579 CheckDynamicTypeHandler Handler{AK}; 5580 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5581 } 5582 5583 /// Check that the pointee of the 'this' pointer in a member function call is 5584 /// either within its lifetime or in its period of construction or destruction. 5585 static bool 5586 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5587 const LValue &This, 5588 const CXXMethodDecl *NamedMember) { 5589 return checkDynamicType( 5590 Info, E, This, 5591 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5592 } 5593 5594 struct DynamicType { 5595 /// The dynamic class type of the object. 5596 const CXXRecordDecl *Type; 5597 /// The corresponding path length in the lvalue. 5598 unsigned PathLength; 5599 }; 5600 5601 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5602 unsigned PathLength) { 5603 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5604 Designator.Entries.size() && "invalid path length"); 5605 return (PathLength == Designator.MostDerivedPathLength) 5606 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5607 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5608 } 5609 5610 /// Determine the dynamic type of an object. 5611 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5612 LValue &This, AccessKinds AK) { 5613 // If we don't have an lvalue denoting an object of class type, there is no 5614 // meaningful dynamic type. (We consider objects of non-class type to have no 5615 // dynamic type.) 5616 if (!checkDynamicType(Info, E, This, AK, true)) 5617 return None; 5618 5619 // Refuse to compute a dynamic type in the presence of virtual bases. This 5620 // shouldn't happen other than in constant-folding situations, since literal 5621 // types can't have virtual bases. 5622 // 5623 // Note that consumers of DynamicType assume that the type has no virtual 5624 // bases, and will need modifications if this restriction is relaxed. 5625 const CXXRecordDecl *Class = 5626 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5627 if (!Class || Class->getNumVBases()) { 5628 Info.FFDiag(E); 5629 return None; 5630 } 5631 5632 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5633 // binary search here instead. But the overwhelmingly common case is that 5634 // we're not in the middle of a constructor, so it probably doesn't matter 5635 // in practice. 5636 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5637 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5638 PathLength <= Path.size(); ++PathLength) { 5639 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5640 Path.slice(0, PathLength))) { 5641 case ConstructionPhase::Bases: 5642 case ConstructionPhase::DestroyingBases: 5643 // We're constructing or destroying a base class. This is not the dynamic 5644 // type. 5645 break; 5646 5647 case ConstructionPhase::None: 5648 case ConstructionPhase::AfterBases: 5649 case ConstructionPhase::AfterFields: 5650 case ConstructionPhase::Destroying: 5651 // We've finished constructing the base classes and not yet started 5652 // destroying them again, so this is the dynamic type. 5653 return DynamicType{getBaseClassType(This.Designator, PathLength), 5654 PathLength}; 5655 } 5656 } 5657 5658 // CWG issue 1517: we're constructing a base class of the object described by 5659 // 'This', so that object has not yet begun its period of construction and 5660 // any polymorphic operation on it results in undefined behavior. 5661 Info.FFDiag(E); 5662 return None; 5663 } 5664 5665 /// Perform virtual dispatch. 5666 static const CXXMethodDecl *HandleVirtualDispatch( 5667 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5668 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5669 Optional<DynamicType> DynType = ComputeDynamicType( 5670 Info, E, This, 5671 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5672 if (!DynType) 5673 return nullptr; 5674 5675 // Find the final overrider. It must be declared in one of the classes on the 5676 // path from the dynamic type to the static type. 5677 // FIXME: If we ever allow literal types to have virtual base classes, that 5678 // won't be true. 5679 const CXXMethodDecl *Callee = Found; 5680 unsigned PathLength = DynType->PathLength; 5681 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5682 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5683 const CXXMethodDecl *Overrider = 5684 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5685 if (Overrider) { 5686 Callee = Overrider; 5687 break; 5688 } 5689 } 5690 5691 // C++2a [class.abstract]p6: 5692 // the effect of making a virtual call to a pure virtual function [...] is 5693 // undefined 5694 if (Callee->isPure()) { 5695 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5696 Info.Note(Callee->getLocation(), diag::note_declared_at); 5697 return nullptr; 5698 } 5699 5700 // If necessary, walk the rest of the path to determine the sequence of 5701 // covariant adjustment steps to apply. 5702 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5703 Found->getReturnType())) { 5704 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5705 for (unsigned CovariantPathLength = PathLength + 1; 5706 CovariantPathLength != This.Designator.Entries.size(); 5707 ++CovariantPathLength) { 5708 const CXXRecordDecl *NextClass = 5709 getBaseClassType(This.Designator, CovariantPathLength); 5710 const CXXMethodDecl *Next = 5711 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5712 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5713 Next->getReturnType(), CovariantAdjustmentPath.back())) 5714 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5715 } 5716 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5717 CovariantAdjustmentPath.back())) 5718 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5719 } 5720 5721 // Perform 'this' adjustment. 5722 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5723 return nullptr; 5724 5725 return Callee; 5726 } 5727 5728 /// Perform the adjustment from a value returned by a virtual function to 5729 /// a value of the statically expected type, which may be a pointer or 5730 /// reference to a base class of the returned type. 5731 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5732 APValue &Result, 5733 ArrayRef<QualType> Path) { 5734 assert(Result.isLValue() && 5735 "unexpected kind of APValue for covariant return"); 5736 if (Result.isNullPointer()) 5737 return true; 5738 5739 LValue LVal; 5740 LVal.setFrom(Info.Ctx, Result); 5741 5742 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5743 for (unsigned I = 1; I != Path.size(); ++I) { 5744 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5745 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5746 if (OldClass != NewClass && 5747 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5748 return false; 5749 OldClass = NewClass; 5750 } 5751 5752 LVal.moveInto(Result); 5753 return true; 5754 } 5755 5756 /// Determine whether \p Base, which is known to be a direct base class of 5757 /// \p Derived, is a public base class. 5758 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5759 const CXXRecordDecl *Base) { 5760 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5761 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5762 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5763 return BaseSpec.getAccessSpecifier() == AS_public; 5764 } 5765 llvm_unreachable("Base is not a direct base of Derived"); 5766 } 5767 5768 /// Apply the given dynamic cast operation on the provided lvalue. 5769 /// 5770 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5771 /// to find a suitable target subobject. 5772 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5773 LValue &Ptr) { 5774 // We can't do anything with a non-symbolic pointer value. 5775 SubobjectDesignator &D = Ptr.Designator; 5776 if (D.Invalid) 5777 return false; 5778 5779 // C++ [expr.dynamic.cast]p6: 5780 // If v is a null pointer value, the result is a null pointer value. 5781 if (Ptr.isNullPointer() && !E->isGLValue()) 5782 return true; 5783 5784 // For all the other cases, we need the pointer to point to an object within 5785 // its lifetime / period of construction / destruction, and we need to know 5786 // its dynamic type. 5787 Optional<DynamicType> DynType = 5788 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5789 if (!DynType) 5790 return false; 5791 5792 // C++ [expr.dynamic.cast]p7: 5793 // If T is "pointer to cv void", then the result is a pointer to the most 5794 // derived object 5795 if (E->getType()->isVoidPointerType()) 5796 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5797 5798 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5799 assert(C && "dynamic_cast target is not void pointer nor class"); 5800 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5801 5802 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5803 // C++ [expr.dynamic.cast]p9: 5804 if (!E->isGLValue()) { 5805 // The value of a failed cast to pointer type is the null pointer value 5806 // of the required result type. 5807 Ptr.setNull(Info.Ctx, E->getType()); 5808 return true; 5809 } 5810 5811 // A failed cast to reference type throws [...] std::bad_cast. 5812 unsigned DiagKind; 5813 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5814 DynType->Type->isDerivedFrom(C))) 5815 DiagKind = 0; 5816 else if (!Paths || Paths->begin() == Paths->end()) 5817 DiagKind = 1; 5818 else if (Paths->isAmbiguous(CQT)) 5819 DiagKind = 2; 5820 else { 5821 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5822 DiagKind = 3; 5823 } 5824 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5825 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5826 << Info.Ctx.getRecordType(DynType->Type) 5827 << E->getType().getUnqualifiedType(); 5828 return false; 5829 }; 5830 5831 // Runtime check, phase 1: 5832 // Walk from the base subobject towards the derived object looking for the 5833 // target type. 5834 for (int PathLength = Ptr.Designator.Entries.size(); 5835 PathLength >= (int)DynType->PathLength; --PathLength) { 5836 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5837 if (declaresSameEntity(Class, C)) 5838 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5839 // We can only walk across public inheritance edges. 5840 if (PathLength > (int)DynType->PathLength && 5841 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5842 Class)) 5843 return RuntimeCheckFailed(nullptr); 5844 } 5845 5846 // Runtime check, phase 2: 5847 // Search the dynamic type for an unambiguous public base of type C. 5848 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5849 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5850 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5851 Paths.front().Access == AS_public) { 5852 // Downcast to the dynamic type... 5853 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5854 return false; 5855 // ... then upcast to the chosen base class subobject. 5856 for (CXXBasePathElement &Elem : Paths.front()) 5857 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5858 return false; 5859 return true; 5860 } 5861 5862 // Otherwise, the runtime check fails. 5863 return RuntimeCheckFailed(&Paths); 5864 } 5865 5866 namespace { 5867 struct StartLifetimeOfUnionMemberHandler { 5868 EvalInfo &Info; 5869 const Expr *LHSExpr; 5870 const FieldDecl *Field; 5871 bool DuringInit; 5872 bool Failed = false; 5873 static const AccessKinds AccessKind = AK_Assign; 5874 5875 typedef bool result_type; 5876 bool failed() { return Failed; } 5877 bool found(APValue &Subobj, QualType SubobjType) { 5878 // We are supposed to perform no initialization but begin the lifetime of 5879 // the object. We interpret that as meaning to do what default 5880 // initialization of the object would do if all constructors involved were 5881 // trivial: 5882 // * All base, non-variant member, and array element subobjects' lifetimes 5883 // begin 5884 // * No variant members' lifetimes begin 5885 // * All scalar subobjects whose lifetimes begin have indeterminate values 5886 assert(SubobjType->isUnionType()); 5887 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5888 // This union member is already active. If it's also in-lifetime, there's 5889 // nothing to do. 5890 if (Subobj.getUnionValue().hasValue()) 5891 return true; 5892 } else if (DuringInit) { 5893 // We're currently in the process of initializing a different union 5894 // member. If we carried on, that initialization would attempt to 5895 // store to an inactive union member, resulting in undefined behavior. 5896 Info.FFDiag(LHSExpr, 5897 diag::note_constexpr_union_member_change_during_init); 5898 return false; 5899 } 5900 APValue Result; 5901 Failed = !getDefaultInitValue(Field->getType(), Result); 5902 Subobj.setUnion(Field, Result); 5903 return true; 5904 } 5905 bool found(APSInt &Value, QualType SubobjType) { 5906 llvm_unreachable("wrong value kind for union object"); 5907 } 5908 bool found(APFloat &Value, QualType SubobjType) { 5909 llvm_unreachable("wrong value kind for union object"); 5910 } 5911 }; 5912 } // end anonymous namespace 5913 5914 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5915 5916 /// Handle a builtin simple-assignment or a call to a trivial assignment 5917 /// operator whose left-hand side might involve a union member access. If it 5918 /// does, implicitly start the lifetime of any accessed union elements per 5919 /// C++20 [class.union]5. 5920 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5921 const LValue &LHS) { 5922 if (LHS.InvalidBase || LHS.Designator.Invalid) 5923 return false; 5924 5925 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5926 // C++ [class.union]p5: 5927 // define the set S(E) of subexpressions of E as follows: 5928 unsigned PathLength = LHS.Designator.Entries.size(); 5929 for (const Expr *E = LHSExpr; E != nullptr;) { 5930 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5931 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5932 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5933 // Note that we can't implicitly start the lifetime of a reference, 5934 // so we don't need to proceed any further if we reach one. 5935 if (!FD || FD->getType()->isReferenceType()) 5936 break; 5937 5938 // ... and also contains A.B if B names a union member ... 5939 if (FD->getParent()->isUnion()) { 5940 // ... of a non-class, non-array type, or of a class type with a 5941 // trivial default constructor that is not deleted, or an array of 5942 // such types. 5943 auto *RD = 5944 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5945 if (!RD || RD->hasTrivialDefaultConstructor()) 5946 UnionPathLengths.push_back({PathLength - 1, FD}); 5947 } 5948 5949 E = ME->getBase(); 5950 --PathLength; 5951 assert(declaresSameEntity(FD, 5952 LHS.Designator.Entries[PathLength] 5953 .getAsBaseOrMember().getPointer())); 5954 5955 // -- If E is of the form A[B] and is interpreted as a built-in array 5956 // subscripting operator, S(E) is [S(the array operand, if any)]. 5957 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5958 // Step over an ArrayToPointerDecay implicit cast. 5959 auto *Base = ASE->getBase()->IgnoreImplicit(); 5960 if (!Base->getType()->isArrayType()) 5961 break; 5962 5963 E = Base; 5964 --PathLength; 5965 5966 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5967 // Step over a derived-to-base conversion. 5968 E = ICE->getSubExpr(); 5969 if (ICE->getCastKind() == CK_NoOp) 5970 continue; 5971 if (ICE->getCastKind() != CK_DerivedToBase && 5972 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5973 break; 5974 // Walk path backwards as we walk up from the base to the derived class. 5975 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5976 --PathLength; 5977 (void)Elt; 5978 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5979 LHS.Designator.Entries[PathLength] 5980 .getAsBaseOrMember().getPointer())); 5981 } 5982 5983 // -- Otherwise, S(E) is empty. 5984 } else { 5985 break; 5986 } 5987 } 5988 5989 // Common case: no unions' lifetimes are started. 5990 if (UnionPathLengths.empty()) 5991 return true; 5992 5993 // if modification of X [would access an inactive union member], an object 5994 // of the type of X is implicitly created 5995 CompleteObject Obj = 5996 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5997 if (!Obj) 5998 return false; 5999 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 6000 llvm::reverse(UnionPathLengths)) { 6001 // Form a designator for the union object. 6002 SubobjectDesignator D = LHS.Designator; 6003 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 6004 6005 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 6006 ConstructionPhase::AfterBases; 6007 StartLifetimeOfUnionMemberHandler StartLifetime{ 6008 Info, LHSExpr, LengthAndField.second, DuringInit}; 6009 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 6010 return false; 6011 } 6012 6013 return true; 6014 } 6015 6016 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 6017 CallRef Call, EvalInfo &Info, 6018 bool NonNull = false) { 6019 LValue LV; 6020 // Create the parameter slot and register its destruction. For a vararg 6021 // argument, create a temporary. 6022 // FIXME: For calling conventions that destroy parameters in the callee, 6023 // should we consider performing destruction when the function returns 6024 // instead? 6025 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6026 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6027 ScopeKind::Call, LV); 6028 if (!EvaluateInPlace(V, Info, LV, Arg)) 6029 return false; 6030 6031 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6032 // undefined behavior, so is non-constant. 6033 if (NonNull && V.isLValue() && V.isNullPointer()) { 6034 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6035 return false; 6036 } 6037 6038 return true; 6039 } 6040 6041 /// Evaluate the arguments to a function call. 6042 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6043 EvalInfo &Info, const FunctionDecl *Callee, 6044 bool RightToLeft = false) { 6045 bool Success = true; 6046 llvm::SmallBitVector ForbiddenNullArgs; 6047 if (Callee->hasAttr<NonNullAttr>()) { 6048 ForbiddenNullArgs.resize(Args.size()); 6049 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6050 if (!Attr->args_size()) { 6051 ForbiddenNullArgs.set(); 6052 break; 6053 } else 6054 for (auto Idx : Attr->args()) { 6055 unsigned ASTIdx = Idx.getASTIndex(); 6056 if (ASTIdx >= Args.size()) 6057 continue; 6058 ForbiddenNullArgs[ASTIdx] = true; 6059 } 6060 } 6061 } 6062 for (unsigned I = 0; I < Args.size(); I++) { 6063 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6064 const ParmVarDecl *PVD = 6065 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6066 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6067 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6068 // If we're checking for a potential constant expression, evaluate all 6069 // initializers even if some of them fail. 6070 if (!Info.noteFailure()) 6071 return false; 6072 Success = false; 6073 } 6074 } 6075 return Success; 6076 } 6077 6078 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6079 /// constructor or assignment operator. 6080 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6081 const Expr *E, APValue &Result, 6082 bool CopyObjectRepresentation) { 6083 // Find the reference argument. 6084 CallStackFrame *Frame = Info.CurrentCall; 6085 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6086 if (!RefValue) { 6087 Info.FFDiag(E); 6088 return false; 6089 } 6090 6091 // Copy out the contents of the RHS object. 6092 LValue RefLValue; 6093 RefLValue.setFrom(Info.Ctx, *RefValue); 6094 return handleLValueToRValueConversion( 6095 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6096 CopyObjectRepresentation); 6097 } 6098 6099 /// Evaluate a function call. 6100 static bool HandleFunctionCall(SourceLocation CallLoc, 6101 const FunctionDecl *Callee, const LValue *This, 6102 ArrayRef<const Expr *> Args, CallRef Call, 6103 const Stmt *Body, EvalInfo &Info, 6104 APValue &Result, const LValue *ResultSlot) { 6105 if (!Info.CheckCallLimit(CallLoc)) 6106 return false; 6107 6108 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6109 6110 // For a trivial copy or move assignment, perform an APValue copy. This is 6111 // essential for unions, where the operations performed by the assignment 6112 // operator cannot be represented as statements. 6113 // 6114 // Skip this for non-union classes with no fields; in that case, the defaulted 6115 // copy/move does not actually read the object. 6116 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6117 if (MD && MD->isDefaulted() && 6118 (MD->getParent()->isUnion() || 6119 (MD->isTrivial() && 6120 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6121 assert(This && 6122 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6123 APValue RHSValue; 6124 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6125 MD->getParent()->isUnion())) 6126 return false; 6127 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6128 RHSValue)) 6129 return false; 6130 This->moveInto(Result); 6131 return true; 6132 } else if (MD && isLambdaCallOperator(MD)) { 6133 // We're in a lambda; determine the lambda capture field maps unless we're 6134 // just constexpr checking a lambda's call operator. constexpr checking is 6135 // done before the captures have been added to the closure object (unless 6136 // we're inferring constexpr-ness), so we don't have access to them in this 6137 // case. But since we don't need the captures to constexpr check, we can 6138 // just ignore them. 6139 if (!Info.checkingPotentialConstantExpression()) 6140 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6141 Frame.LambdaThisCaptureField); 6142 } 6143 6144 StmtResult Ret = {Result, ResultSlot}; 6145 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6146 if (ESR == ESR_Succeeded) { 6147 if (Callee->getReturnType()->isVoidType()) 6148 return true; 6149 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6150 } 6151 return ESR == ESR_Returned; 6152 } 6153 6154 /// Evaluate a constructor call. 6155 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6156 CallRef Call, 6157 const CXXConstructorDecl *Definition, 6158 EvalInfo &Info, APValue &Result) { 6159 SourceLocation CallLoc = E->getExprLoc(); 6160 if (!Info.CheckCallLimit(CallLoc)) 6161 return false; 6162 6163 const CXXRecordDecl *RD = Definition->getParent(); 6164 if (RD->getNumVBases()) { 6165 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6166 return false; 6167 } 6168 6169 EvalInfo::EvaluatingConstructorRAII EvalObj( 6170 Info, 6171 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6172 RD->getNumBases()); 6173 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6174 6175 // FIXME: Creating an APValue just to hold a nonexistent return value is 6176 // wasteful. 6177 APValue RetVal; 6178 StmtResult Ret = {RetVal, nullptr}; 6179 6180 // If it's a delegating constructor, delegate. 6181 if (Definition->isDelegatingConstructor()) { 6182 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6183 if ((*I)->getInit()->isValueDependent()) { 6184 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6185 return false; 6186 } else { 6187 FullExpressionRAII InitScope(Info); 6188 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6189 !InitScope.destroy()) 6190 return false; 6191 } 6192 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6193 } 6194 6195 // For a trivial copy or move constructor, perform an APValue copy. This is 6196 // essential for unions (or classes with anonymous union members), where the 6197 // operations performed by the constructor cannot be represented by 6198 // ctor-initializers. 6199 // 6200 // Skip this for empty non-union classes; we should not perform an 6201 // lvalue-to-rvalue conversion on them because their copy constructor does not 6202 // actually read them. 6203 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6204 (Definition->getParent()->isUnion() || 6205 (Definition->isTrivial() && 6206 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6207 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6208 Definition->getParent()->isUnion()); 6209 } 6210 6211 // Reserve space for the struct members. 6212 if (!Result.hasValue()) { 6213 if (!RD->isUnion()) 6214 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6215 std::distance(RD->field_begin(), RD->field_end())); 6216 else 6217 // A union starts with no active member. 6218 Result = APValue((const FieldDecl*)nullptr); 6219 } 6220 6221 if (RD->isInvalidDecl()) return false; 6222 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6223 6224 // A scope for temporaries lifetime-extended by reference members. 6225 BlockScopeRAII LifetimeExtendedScope(Info); 6226 6227 bool Success = true; 6228 unsigned BasesSeen = 0; 6229 #ifndef NDEBUG 6230 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6231 #endif 6232 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6233 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6234 // We might be initializing the same field again if this is an indirect 6235 // field initialization. 6236 if (FieldIt == RD->field_end() || 6237 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6238 assert(Indirect && "fields out of order?"); 6239 return; 6240 } 6241 6242 // Default-initialize any fields with no explicit initializer. 6243 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6244 assert(FieldIt != RD->field_end() && "missing field?"); 6245 if (!FieldIt->isUnnamedBitfield()) 6246 Success &= getDefaultInitValue( 6247 FieldIt->getType(), 6248 Result.getStructField(FieldIt->getFieldIndex())); 6249 } 6250 ++FieldIt; 6251 }; 6252 for (const auto *I : Definition->inits()) { 6253 LValue Subobject = This; 6254 LValue SubobjectParent = This; 6255 APValue *Value = &Result; 6256 6257 // Determine the subobject to initialize. 6258 FieldDecl *FD = nullptr; 6259 if (I->isBaseInitializer()) { 6260 QualType BaseType(I->getBaseClass(), 0); 6261 #ifndef NDEBUG 6262 // Non-virtual base classes are initialized in the order in the class 6263 // definition. We have already checked for virtual base classes. 6264 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6265 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6266 "base class initializers not in expected order"); 6267 ++BaseIt; 6268 #endif 6269 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6270 BaseType->getAsCXXRecordDecl(), &Layout)) 6271 return false; 6272 Value = &Result.getStructBase(BasesSeen++); 6273 } else if ((FD = I->getMember())) { 6274 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6275 return false; 6276 if (RD->isUnion()) { 6277 Result = APValue(FD); 6278 Value = &Result.getUnionValue(); 6279 } else { 6280 SkipToField(FD, false); 6281 Value = &Result.getStructField(FD->getFieldIndex()); 6282 } 6283 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6284 // Walk the indirect field decl's chain to find the object to initialize, 6285 // and make sure we've initialized every step along it. 6286 auto IndirectFieldChain = IFD->chain(); 6287 for (auto *C : IndirectFieldChain) { 6288 FD = cast<FieldDecl>(C); 6289 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6290 // Switch the union field if it differs. This happens if we had 6291 // preceding zero-initialization, and we're now initializing a union 6292 // subobject other than the first. 6293 // FIXME: In this case, the values of the other subobjects are 6294 // specified, since zero-initialization sets all padding bits to zero. 6295 if (!Value->hasValue() || 6296 (Value->isUnion() && Value->getUnionField() != FD)) { 6297 if (CD->isUnion()) 6298 *Value = APValue(FD); 6299 else 6300 // FIXME: This immediately starts the lifetime of all members of 6301 // an anonymous struct. It would be preferable to strictly start 6302 // member lifetime in initialization order. 6303 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6304 } 6305 // Store Subobject as its parent before updating it for the last element 6306 // in the chain. 6307 if (C == IndirectFieldChain.back()) 6308 SubobjectParent = Subobject; 6309 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6310 return false; 6311 if (CD->isUnion()) 6312 Value = &Value->getUnionValue(); 6313 else { 6314 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6315 SkipToField(FD, true); 6316 Value = &Value->getStructField(FD->getFieldIndex()); 6317 } 6318 } 6319 } else { 6320 llvm_unreachable("unknown base initializer kind"); 6321 } 6322 6323 // Need to override This for implicit field initializers as in this case 6324 // This refers to innermost anonymous struct/union containing initializer, 6325 // not to currently constructed class. 6326 const Expr *Init = I->getInit(); 6327 if (Init->isValueDependent()) { 6328 if (!EvaluateDependentExpr(Init, Info)) 6329 return false; 6330 } else { 6331 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6332 isa<CXXDefaultInitExpr>(Init)); 6333 FullExpressionRAII InitScope(Info); 6334 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6335 (FD && FD->isBitField() && 6336 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6337 // If we're checking for a potential constant expression, evaluate all 6338 // initializers even if some of them fail. 6339 if (!Info.noteFailure()) 6340 return false; 6341 Success = false; 6342 } 6343 } 6344 6345 // This is the point at which the dynamic type of the object becomes this 6346 // class type. 6347 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6348 EvalObj.finishedConstructingBases(); 6349 } 6350 6351 // Default-initialize any remaining fields. 6352 if (!RD->isUnion()) { 6353 for (; FieldIt != RD->field_end(); ++FieldIt) { 6354 if (!FieldIt->isUnnamedBitfield()) 6355 Success &= getDefaultInitValue( 6356 FieldIt->getType(), 6357 Result.getStructField(FieldIt->getFieldIndex())); 6358 } 6359 } 6360 6361 EvalObj.finishedConstructingFields(); 6362 6363 return Success && 6364 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6365 LifetimeExtendedScope.destroy(); 6366 } 6367 6368 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6369 ArrayRef<const Expr*> Args, 6370 const CXXConstructorDecl *Definition, 6371 EvalInfo &Info, APValue &Result) { 6372 CallScopeRAII CallScope(Info); 6373 CallRef Call = Info.CurrentCall->createCall(Definition); 6374 if (!EvaluateArgs(Args, Call, Info, Definition)) 6375 return false; 6376 6377 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6378 CallScope.destroy(); 6379 } 6380 6381 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6382 const LValue &This, APValue &Value, 6383 QualType T) { 6384 // Objects can only be destroyed while they're within their lifetimes. 6385 // FIXME: We have no representation for whether an object of type nullptr_t 6386 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6387 // as indeterminate instead? 6388 if (Value.isAbsent() && !T->isNullPtrType()) { 6389 APValue Printable; 6390 This.moveInto(Printable); 6391 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6392 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6393 return false; 6394 } 6395 6396 // Invent an expression for location purposes. 6397 // FIXME: We shouldn't need to do this. 6398 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6399 6400 // For arrays, destroy elements right-to-left. 6401 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6402 uint64_t Size = CAT->getSize().getZExtValue(); 6403 QualType ElemT = CAT->getElementType(); 6404 6405 LValue ElemLV = This; 6406 ElemLV.addArray(Info, &LocE, CAT); 6407 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6408 return false; 6409 6410 // Ensure that we have actual array elements available to destroy; the 6411 // destructors might mutate the value, so we can't run them on the array 6412 // filler. 6413 if (Size && Size > Value.getArrayInitializedElts()) 6414 expandArray(Value, Value.getArraySize() - 1); 6415 6416 for (; Size != 0; --Size) { 6417 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6418 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6419 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6420 return false; 6421 } 6422 6423 // End the lifetime of this array now. 6424 Value = APValue(); 6425 return true; 6426 } 6427 6428 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6429 if (!RD) { 6430 if (T.isDestructedType()) { 6431 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6432 return false; 6433 } 6434 6435 Value = APValue(); 6436 return true; 6437 } 6438 6439 if (RD->getNumVBases()) { 6440 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6441 return false; 6442 } 6443 6444 const CXXDestructorDecl *DD = RD->getDestructor(); 6445 if (!DD && !RD->hasTrivialDestructor()) { 6446 Info.FFDiag(CallLoc); 6447 return false; 6448 } 6449 6450 if (!DD || DD->isTrivial() || 6451 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6452 // A trivial destructor just ends the lifetime of the object. Check for 6453 // this case before checking for a body, because we might not bother 6454 // building a body for a trivial destructor. Note that it doesn't matter 6455 // whether the destructor is constexpr in this case; all trivial 6456 // destructors are constexpr. 6457 // 6458 // If an anonymous union would be destroyed, some enclosing destructor must 6459 // have been explicitly defined, and the anonymous union destruction should 6460 // have no effect. 6461 Value = APValue(); 6462 return true; 6463 } 6464 6465 if (!Info.CheckCallLimit(CallLoc)) 6466 return false; 6467 6468 const FunctionDecl *Definition = nullptr; 6469 const Stmt *Body = DD->getBody(Definition); 6470 6471 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6472 return false; 6473 6474 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6475 6476 // We're now in the period of destruction of this object. 6477 unsigned BasesLeft = RD->getNumBases(); 6478 EvalInfo::EvaluatingDestructorRAII EvalObj( 6479 Info, 6480 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6481 if (!EvalObj.DidInsert) { 6482 // C++2a [class.dtor]p19: 6483 // the behavior is undefined if the destructor is invoked for an object 6484 // whose lifetime has ended 6485 // (Note that formally the lifetime ends when the period of destruction 6486 // begins, even though certain uses of the object remain valid until the 6487 // period of destruction ends.) 6488 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6489 return false; 6490 } 6491 6492 // FIXME: Creating an APValue just to hold a nonexistent return value is 6493 // wasteful. 6494 APValue RetVal; 6495 StmtResult Ret = {RetVal, nullptr}; 6496 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6497 return false; 6498 6499 // A union destructor does not implicitly destroy its members. 6500 if (RD->isUnion()) 6501 return true; 6502 6503 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6504 6505 // We don't have a good way to iterate fields in reverse, so collect all the 6506 // fields first and then walk them backwards. 6507 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6508 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6509 if (FD->isUnnamedBitfield()) 6510 continue; 6511 6512 LValue Subobject = This; 6513 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6514 return false; 6515 6516 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6517 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6518 FD->getType())) 6519 return false; 6520 } 6521 6522 if (BasesLeft != 0) 6523 EvalObj.startedDestroyingBases(); 6524 6525 // Destroy base classes in reverse order. 6526 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6527 --BasesLeft; 6528 6529 QualType BaseType = Base.getType(); 6530 LValue Subobject = This; 6531 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6532 BaseType->getAsCXXRecordDecl(), &Layout)) 6533 return false; 6534 6535 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6536 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6537 BaseType)) 6538 return false; 6539 } 6540 assert(BasesLeft == 0 && "NumBases was wrong?"); 6541 6542 // The period of destruction ends now. The object is gone. 6543 Value = APValue(); 6544 return true; 6545 } 6546 6547 namespace { 6548 struct DestroyObjectHandler { 6549 EvalInfo &Info; 6550 const Expr *E; 6551 const LValue &This; 6552 const AccessKinds AccessKind; 6553 6554 typedef bool result_type; 6555 bool failed() { return false; } 6556 bool found(APValue &Subobj, QualType SubobjType) { 6557 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6558 SubobjType); 6559 } 6560 bool found(APSInt &Value, QualType SubobjType) { 6561 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6562 return false; 6563 } 6564 bool found(APFloat &Value, QualType SubobjType) { 6565 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6566 return false; 6567 } 6568 }; 6569 } 6570 6571 /// Perform a destructor or pseudo-destructor call on the given object, which 6572 /// might in general not be a complete object. 6573 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6574 const LValue &This, QualType ThisType) { 6575 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6576 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6577 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6578 } 6579 6580 /// Destroy and end the lifetime of the given complete object. 6581 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6582 APValue::LValueBase LVBase, APValue &Value, 6583 QualType T) { 6584 // If we've had an unmodeled side-effect, we can't rely on mutable state 6585 // (such as the object we're about to destroy) being correct. 6586 if (Info.EvalStatus.HasSideEffects) 6587 return false; 6588 6589 LValue LV; 6590 LV.set({LVBase}); 6591 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6592 } 6593 6594 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6595 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6596 LValue &Result) { 6597 if (Info.checkingPotentialConstantExpression() || 6598 Info.SpeculativeEvaluationDepth) 6599 return false; 6600 6601 // This is permitted only within a call to std::allocator<T>::allocate. 6602 auto Caller = Info.getStdAllocatorCaller("allocate"); 6603 if (!Caller) { 6604 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6605 ? diag::note_constexpr_new_untyped 6606 : diag::note_constexpr_new); 6607 return false; 6608 } 6609 6610 QualType ElemType = Caller.ElemType; 6611 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6612 Info.FFDiag(E->getExprLoc(), 6613 diag::note_constexpr_new_not_complete_object_type) 6614 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6615 return false; 6616 } 6617 6618 APSInt ByteSize; 6619 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6620 return false; 6621 bool IsNothrow = false; 6622 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6623 EvaluateIgnoredValue(Info, E->getArg(I)); 6624 IsNothrow |= E->getType()->isNothrowT(); 6625 } 6626 6627 CharUnits ElemSize; 6628 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6629 return false; 6630 APInt Size, Remainder; 6631 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6632 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6633 if (Remainder != 0) { 6634 // This likely indicates a bug in the implementation of 'std::allocator'. 6635 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6636 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6637 return false; 6638 } 6639 6640 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6641 if (IsNothrow) { 6642 Result.setNull(Info.Ctx, E->getType()); 6643 return true; 6644 } 6645 6646 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6647 return false; 6648 } 6649 6650 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6651 ArrayType::Normal, 0); 6652 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6653 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6654 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6655 return true; 6656 } 6657 6658 static bool hasVirtualDestructor(QualType T) { 6659 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6660 if (CXXDestructorDecl *DD = RD->getDestructor()) 6661 return DD->isVirtual(); 6662 return false; 6663 } 6664 6665 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6666 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6667 if (CXXDestructorDecl *DD = RD->getDestructor()) 6668 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6669 return nullptr; 6670 } 6671 6672 /// Check that the given object is a suitable pointer to a heap allocation that 6673 /// still exists and is of the right kind for the purpose of a deletion. 6674 /// 6675 /// On success, returns the heap allocation to deallocate. On failure, produces 6676 /// a diagnostic and returns None. 6677 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6678 const LValue &Pointer, 6679 DynAlloc::Kind DeallocKind) { 6680 auto PointerAsString = [&] { 6681 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6682 }; 6683 6684 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6685 if (!DA) { 6686 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6687 << PointerAsString(); 6688 if (Pointer.Base) 6689 NoteLValueLocation(Info, Pointer.Base); 6690 return None; 6691 } 6692 6693 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6694 if (!Alloc) { 6695 Info.FFDiag(E, diag::note_constexpr_double_delete); 6696 return None; 6697 } 6698 6699 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6700 if (DeallocKind != (*Alloc)->getKind()) { 6701 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6702 << DeallocKind << (*Alloc)->getKind() << AllocType; 6703 NoteLValueLocation(Info, Pointer.Base); 6704 return None; 6705 } 6706 6707 bool Subobject = false; 6708 if (DeallocKind == DynAlloc::New) { 6709 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6710 Pointer.Designator.isOnePastTheEnd(); 6711 } else { 6712 Subobject = Pointer.Designator.Entries.size() != 1 || 6713 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6714 } 6715 if (Subobject) { 6716 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6717 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6718 return None; 6719 } 6720 6721 return Alloc; 6722 } 6723 6724 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6725 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6726 if (Info.checkingPotentialConstantExpression() || 6727 Info.SpeculativeEvaluationDepth) 6728 return false; 6729 6730 // This is permitted only within a call to std::allocator<T>::deallocate. 6731 if (!Info.getStdAllocatorCaller("deallocate")) { 6732 Info.FFDiag(E->getExprLoc()); 6733 return true; 6734 } 6735 6736 LValue Pointer; 6737 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6738 return false; 6739 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6740 EvaluateIgnoredValue(Info, E->getArg(I)); 6741 6742 if (Pointer.Designator.Invalid) 6743 return false; 6744 6745 // Deleting a null pointer would have no effect, but it's not permitted by 6746 // std::allocator<T>::deallocate's contract. 6747 if (Pointer.isNullPointer()) { 6748 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6749 return true; 6750 } 6751 6752 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6753 return false; 6754 6755 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6756 return true; 6757 } 6758 6759 //===----------------------------------------------------------------------===// 6760 // Generic Evaluation 6761 //===----------------------------------------------------------------------===// 6762 namespace { 6763 6764 class BitCastBuffer { 6765 // FIXME: We're going to need bit-level granularity when we support 6766 // bit-fields. 6767 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6768 // we don't support a host or target where that is the case. Still, we should 6769 // use a more generic type in case we ever do. 6770 SmallVector<Optional<unsigned char>, 32> Bytes; 6771 6772 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6773 "Need at least 8 bit unsigned char"); 6774 6775 bool TargetIsLittleEndian; 6776 6777 public: 6778 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6779 : Bytes(Width.getQuantity()), 6780 TargetIsLittleEndian(TargetIsLittleEndian) {} 6781 6782 LLVM_NODISCARD 6783 bool readObject(CharUnits Offset, CharUnits Width, 6784 SmallVectorImpl<unsigned char> &Output) const { 6785 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6786 // If a byte of an integer is uninitialized, then the whole integer is 6787 // uninitialized. 6788 if (!Bytes[I.getQuantity()]) 6789 return false; 6790 Output.push_back(*Bytes[I.getQuantity()]); 6791 } 6792 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6793 std::reverse(Output.begin(), Output.end()); 6794 return true; 6795 } 6796 6797 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6798 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6799 std::reverse(Input.begin(), Input.end()); 6800 6801 size_t Index = 0; 6802 for (unsigned char Byte : Input) { 6803 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6804 Bytes[Offset.getQuantity() + Index] = Byte; 6805 ++Index; 6806 } 6807 } 6808 6809 size_t size() { return Bytes.size(); } 6810 }; 6811 6812 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6813 /// target would represent the value at runtime. 6814 class APValueToBufferConverter { 6815 EvalInfo &Info; 6816 BitCastBuffer Buffer; 6817 const CastExpr *BCE; 6818 6819 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6820 const CastExpr *BCE) 6821 : Info(Info), 6822 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6823 BCE(BCE) {} 6824 6825 bool visit(const APValue &Val, QualType Ty) { 6826 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6827 } 6828 6829 // Write out Val with type Ty into Buffer starting at Offset. 6830 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6831 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6832 6833 // As a special case, nullptr_t has an indeterminate value. 6834 if (Ty->isNullPtrType()) 6835 return true; 6836 6837 // Dig through Src to find the byte at SrcOffset. 6838 switch (Val.getKind()) { 6839 case APValue::Indeterminate: 6840 case APValue::None: 6841 return true; 6842 6843 case APValue::Int: 6844 return visitInt(Val.getInt(), Ty, Offset); 6845 case APValue::Float: 6846 return visitFloat(Val.getFloat(), Ty, Offset); 6847 case APValue::Array: 6848 return visitArray(Val, Ty, Offset); 6849 case APValue::Struct: 6850 return visitRecord(Val, Ty, Offset); 6851 6852 case APValue::ComplexInt: 6853 case APValue::ComplexFloat: 6854 case APValue::Vector: 6855 case APValue::FixedPoint: 6856 // FIXME: We should support these. 6857 6858 case APValue::Union: 6859 case APValue::MemberPointer: 6860 case APValue::AddrLabelDiff: { 6861 Info.FFDiag(BCE->getBeginLoc(), 6862 diag::note_constexpr_bit_cast_unsupported_type) 6863 << Ty; 6864 return false; 6865 } 6866 6867 case APValue::LValue: 6868 llvm_unreachable("LValue subobject in bit_cast?"); 6869 } 6870 llvm_unreachable("Unhandled APValue::ValueKind"); 6871 } 6872 6873 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6874 const RecordDecl *RD = Ty->getAsRecordDecl(); 6875 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6876 6877 // Visit the base classes. 6878 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6879 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6880 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6881 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6882 6883 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6884 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6885 return false; 6886 } 6887 } 6888 6889 // Visit the fields. 6890 unsigned FieldIdx = 0; 6891 for (FieldDecl *FD : RD->fields()) { 6892 if (FD->isBitField()) { 6893 Info.FFDiag(BCE->getBeginLoc(), 6894 diag::note_constexpr_bit_cast_unsupported_bitfield); 6895 return false; 6896 } 6897 6898 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6899 6900 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6901 "only bit-fields can have sub-char alignment"); 6902 CharUnits FieldOffset = 6903 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6904 QualType FieldTy = FD->getType(); 6905 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6906 return false; 6907 ++FieldIdx; 6908 } 6909 6910 return true; 6911 } 6912 6913 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6914 const auto *CAT = 6915 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6916 if (!CAT) 6917 return false; 6918 6919 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6920 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6921 unsigned ArraySize = Val.getArraySize(); 6922 // First, initialize the initialized elements. 6923 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6924 const APValue &SubObj = Val.getArrayInitializedElt(I); 6925 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6926 return false; 6927 } 6928 6929 // Next, initialize the rest of the array using the filler. 6930 if (Val.hasArrayFiller()) { 6931 const APValue &Filler = Val.getArrayFiller(); 6932 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6933 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6934 return false; 6935 } 6936 } 6937 6938 return true; 6939 } 6940 6941 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6942 APSInt AdjustedVal = Val; 6943 unsigned Width = AdjustedVal.getBitWidth(); 6944 if (Ty->isBooleanType()) { 6945 Width = Info.Ctx.getTypeSize(Ty); 6946 AdjustedVal = AdjustedVal.extend(Width); 6947 } 6948 6949 SmallVector<unsigned char, 8> Bytes(Width / 8); 6950 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6951 Buffer.writeObject(Offset, Bytes); 6952 return true; 6953 } 6954 6955 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6956 APSInt AsInt(Val.bitcastToAPInt()); 6957 return visitInt(AsInt, Ty, Offset); 6958 } 6959 6960 public: 6961 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6962 const CastExpr *BCE) { 6963 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6964 APValueToBufferConverter Converter(Info, DstSize, BCE); 6965 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6966 return None; 6967 return Converter.Buffer; 6968 } 6969 }; 6970 6971 /// Write an BitCastBuffer into an APValue. 6972 class BufferToAPValueConverter { 6973 EvalInfo &Info; 6974 const BitCastBuffer &Buffer; 6975 const CastExpr *BCE; 6976 6977 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6978 const CastExpr *BCE) 6979 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6980 6981 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6982 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6983 // Ideally this will be unreachable. 6984 llvm::NoneType unsupportedType(QualType Ty) { 6985 Info.FFDiag(BCE->getBeginLoc(), 6986 diag::note_constexpr_bit_cast_unsupported_type) 6987 << Ty; 6988 return None; 6989 } 6990 6991 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6992 Info.FFDiag(BCE->getBeginLoc(), 6993 diag::note_constexpr_bit_cast_unrepresentable_value) 6994 << Ty << toString(Val, /*Radix=*/10); 6995 return None; 6996 } 6997 6998 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6999 const EnumType *EnumSugar = nullptr) { 7000 if (T->isNullPtrType()) { 7001 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 7002 return APValue((Expr *)nullptr, 7003 /*Offset=*/CharUnits::fromQuantity(NullValue), 7004 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 7005 } 7006 7007 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 7008 7009 // Work around floating point types that contain unused padding bytes. This 7010 // is really just `long double` on x86, which is the only fundamental type 7011 // with padding bytes. 7012 if (T->isRealFloatingType()) { 7013 const llvm::fltSemantics &Semantics = 7014 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7015 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 7016 assert(NumBits % 8 == 0); 7017 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 7018 if (NumBytes != SizeOf) 7019 SizeOf = NumBytes; 7020 } 7021 7022 SmallVector<uint8_t, 8> Bytes; 7023 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7024 // If this is std::byte or unsigned char, then its okay to store an 7025 // indeterminate value. 7026 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7027 bool IsUChar = 7028 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7029 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7030 if (!IsStdByte && !IsUChar) { 7031 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7032 Info.FFDiag(BCE->getExprLoc(), 7033 diag::note_constexpr_bit_cast_indet_dest) 7034 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7035 return None; 7036 } 7037 7038 return APValue::IndeterminateValue(); 7039 } 7040 7041 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7042 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7043 7044 if (T->isIntegralOrEnumerationType()) { 7045 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7046 7047 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7048 if (IntWidth != Val.getBitWidth()) { 7049 APSInt Truncated = Val.trunc(IntWidth); 7050 if (Truncated.extend(Val.getBitWidth()) != Val) 7051 return unrepresentableValue(QualType(T, 0), Val); 7052 Val = Truncated; 7053 } 7054 7055 return APValue(Val); 7056 } 7057 7058 if (T->isRealFloatingType()) { 7059 const llvm::fltSemantics &Semantics = 7060 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7061 return APValue(APFloat(Semantics, Val)); 7062 } 7063 7064 return unsupportedType(QualType(T, 0)); 7065 } 7066 7067 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7068 const RecordDecl *RD = RTy->getAsRecordDecl(); 7069 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7070 7071 unsigned NumBases = 0; 7072 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7073 NumBases = CXXRD->getNumBases(); 7074 7075 APValue ResultVal(APValue::UninitStruct(), NumBases, 7076 std::distance(RD->field_begin(), RD->field_end())); 7077 7078 // Visit the base classes. 7079 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7080 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7081 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7082 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7083 if (BaseDecl->isEmpty() || 7084 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7085 continue; 7086 7087 Optional<APValue> SubObj = visitType( 7088 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7089 if (!SubObj) 7090 return None; 7091 ResultVal.getStructBase(I) = *SubObj; 7092 } 7093 } 7094 7095 // Visit the fields. 7096 unsigned FieldIdx = 0; 7097 for (FieldDecl *FD : RD->fields()) { 7098 // FIXME: We don't currently support bit-fields. A lot of the logic for 7099 // this is in CodeGen, so we need to factor it around. 7100 if (FD->isBitField()) { 7101 Info.FFDiag(BCE->getBeginLoc(), 7102 diag::note_constexpr_bit_cast_unsupported_bitfield); 7103 return None; 7104 } 7105 7106 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7107 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7108 7109 CharUnits FieldOffset = 7110 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7111 Offset; 7112 QualType FieldTy = FD->getType(); 7113 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7114 if (!SubObj) 7115 return None; 7116 ResultVal.getStructField(FieldIdx) = *SubObj; 7117 ++FieldIdx; 7118 } 7119 7120 return ResultVal; 7121 } 7122 7123 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7124 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7125 assert(!RepresentationType.isNull() && 7126 "enum forward decl should be caught by Sema"); 7127 const auto *AsBuiltin = 7128 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7129 // Recurse into the underlying type. Treat std::byte transparently as 7130 // unsigned char. 7131 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7132 } 7133 7134 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7135 size_t Size = Ty->getSize().getLimitedValue(); 7136 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7137 7138 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7139 for (size_t I = 0; I != Size; ++I) { 7140 Optional<APValue> ElementValue = 7141 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7142 if (!ElementValue) 7143 return None; 7144 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7145 } 7146 7147 return ArrayValue; 7148 } 7149 7150 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7151 return unsupportedType(QualType(Ty, 0)); 7152 } 7153 7154 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7155 QualType Can = Ty.getCanonicalType(); 7156 7157 switch (Can->getTypeClass()) { 7158 #define TYPE(Class, Base) \ 7159 case Type::Class: \ 7160 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7161 #define ABSTRACT_TYPE(Class, Base) 7162 #define NON_CANONICAL_TYPE(Class, Base) \ 7163 case Type::Class: \ 7164 llvm_unreachable("non-canonical type should be impossible!"); 7165 #define DEPENDENT_TYPE(Class, Base) \ 7166 case Type::Class: \ 7167 llvm_unreachable( \ 7168 "dependent types aren't supported in the constant evaluator!"); 7169 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7170 case Type::Class: \ 7171 llvm_unreachable("either dependent or not canonical!"); 7172 #include "clang/AST/TypeNodes.inc" 7173 } 7174 llvm_unreachable("Unhandled Type::TypeClass"); 7175 } 7176 7177 public: 7178 // Pull out a full value of type DstType. 7179 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7180 const CastExpr *BCE) { 7181 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7182 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7183 } 7184 }; 7185 7186 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7187 QualType Ty, EvalInfo *Info, 7188 const ASTContext &Ctx, 7189 bool CheckingDest) { 7190 Ty = Ty.getCanonicalType(); 7191 7192 auto diag = [&](int Reason) { 7193 if (Info) 7194 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7195 << CheckingDest << (Reason == 4) << Reason; 7196 return false; 7197 }; 7198 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7199 if (Info) 7200 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7201 << NoteTy << Construct << Ty; 7202 return false; 7203 }; 7204 7205 if (Ty->isUnionType()) 7206 return diag(0); 7207 if (Ty->isPointerType()) 7208 return diag(1); 7209 if (Ty->isMemberPointerType()) 7210 return diag(2); 7211 if (Ty.isVolatileQualified()) 7212 return diag(3); 7213 7214 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7215 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7216 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7217 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7218 CheckingDest)) 7219 return note(1, BS.getType(), BS.getBeginLoc()); 7220 } 7221 for (FieldDecl *FD : Record->fields()) { 7222 if (FD->getType()->isReferenceType()) 7223 return diag(4); 7224 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7225 CheckingDest)) 7226 return note(0, FD->getType(), FD->getBeginLoc()); 7227 } 7228 } 7229 7230 if (Ty->isArrayType() && 7231 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7232 Info, Ctx, CheckingDest)) 7233 return false; 7234 7235 return true; 7236 } 7237 7238 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7239 const ASTContext &Ctx, 7240 const CastExpr *BCE) { 7241 bool DestOK = checkBitCastConstexprEligibilityType( 7242 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7243 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7244 BCE->getBeginLoc(), 7245 BCE->getSubExpr()->getType(), Info, Ctx, false); 7246 return SourceOK; 7247 } 7248 7249 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7250 APValue &SourceValue, 7251 const CastExpr *BCE) { 7252 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7253 "no host or target supports non 8-bit chars"); 7254 assert(SourceValue.isLValue() && 7255 "LValueToRValueBitcast requires an lvalue operand!"); 7256 7257 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7258 return false; 7259 7260 LValue SourceLValue; 7261 APValue SourceRValue; 7262 SourceLValue.setFrom(Info.Ctx, SourceValue); 7263 if (!handleLValueToRValueConversion( 7264 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7265 SourceRValue, /*WantObjectRepresentation=*/true)) 7266 return false; 7267 7268 // Read out SourceValue into a char buffer. 7269 Optional<BitCastBuffer> Buffer = 7270 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7271 if (!Buffer) 7272 return false; 7273 7274 // Write out the buffer into a new APValue. 7275 Optional<APValue> MaybeDestValue = 7276 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7277 if (!MaybeDestValue) 7278 return false; 7279 7280 DestValue = std::move(*MaybeDestValue); 7281 return true; 7282 } 7283 7284 template <class Derived> 7285 class ExprEvaluatorBase 7286 : public ConstStmtVisitor<Derived, bool> { 7287 private: 7288 Derived &getDerived() { return static_cast<Derived&>(*this); } 7289 bool DerivedSuccess(const APValue &V, const Expr *E) { 7290 return getDerived().Success(V, E); 7291 } 7292 bool DerivedZeroInitialization(const Expr *E) { 7293 return getDerived().ZeroInitialization(E); 7294 } 7295 7296 // Check whether a conditional operator with a non-constant condition is a 7297 // potential constant expression. If neither arm is a potential constant 7298 // expression, then the conditional operator is not either. 7299 template<typename ConditionalOperator> 7300 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7301 assert(Info.checkingPotentialConstantExpression()); 7302 7303 // Speculatively evaluate both arms. 7304 SmallVector<PartialDiagnosticAt, 8> Diag; 7305 { 7306 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7307 StmtVisitorTy::Visit(E->getFalseExpr()); 7308 if (Diag.empty()) 7309 return; 7310 } 7311 7312 { 7313 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7314 Diag.clear(); 7315 StmtVisitorTy::Visit(E->getTrueExpr()); 7316 if (Diag.empty()) 7317 return; 7318 } 7319 7320 Error(E, diag::note_constexpr_conditional_never_const); 7321 } 7322 7323 7324 template<typename ConditionalOperator> 7325 bool HandleConditionalOperator(const ConditionalOperator *E) { 7326 bool BoolResult; 7327 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7328 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7329 CheckPotentialConstantConditional(E); 7330 return false; 7331 } 7332 if (Info.noteFailure()) { 7333 StmtVisitorTy::Visit(E->getTrueExpr()); 7334 StmtVisitorTy::Visit(E->getFalseExpr()); 7335 } 7336 return false; 7337 } 7338 7339 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7340 return StmtVisitorTy::Visit(EvalExpr); 7341 } 7342 7343 protected: 7344 EvalInfo &Info; 7345 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7346 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7347 7348 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7349 return Info.CCEDiag(E, D); 7350 } 7351 7352 bool ZeroInitialization(const Expr *E) { return Error(E); } 7353 7354 public: 7355 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7356 7357 EvalInfo &getEvalInfo() { return Info; } 7358 7359 /// Report an evaluation error. This should only be called when an error is 7360 /// first discovered. When propagating an error, just return false. 7361 bool Error(const Expr *E, diag::kind D) { 7362 Info.FFDiag(E, D); 7363 return false; 7364 } 7365 bool Error(const Expr *E) { 7366 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7367 } 7368 7369 bool VisitStmt(const Stmt *) { 7370 llvm_unreachable("Expression evaluator should not be called on stmts"); 7371 } 7372 bool VisitExpr(const Expr *E) { 7373 return Error(E); 7374 } 7375 7376 bool VisitConstantExpr(const ConstantExpr *E) { 7377 if (E->hasAPValueResult()) 7378 return DerivedSuccess(E->getAPValueResult(), E); 7379 7380 return StmtVisitorTy::Visit(E->getSubExpr()); 7381 } 7382 7383 bool VisitParenExpr(const ParenExpr *E) 7384 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7385 bool VisitUnaryExtension(const UnaryOperator *E) 7386 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7387 bool VisitUnaryPlus(const UnaryOperator *E) 7388 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7389 bool VisitChooseExpr(const ChooseExpr *E) 7390 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7391 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7392 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7393 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7394 { return StmtVisitorTy::Visit(E->getReplacement()); } 7395 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7396 TempVersionRAII RAII(*Info.CurrentCall); 7397 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7398 return StmtVisitorTy::Visit(E->getExpr()); 7399 } 7400 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7401 TempVersionRAII RAII(*Info.CurrentCall); 7402 // The initializer may not have been parsed yet, or might be erroneous. 7403 if (!E->getExpr()) 7404 return Error(E); 7405 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7406 return StmtVisitorTy::Visit(E->getExpr()); 7407 } 7408 7409 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7410 FullExpressionRAII Scope(Info); 7411 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7412 } 7413 7414 // Temporaries are registered when created, so we don't care about 7415 // CXXBindTemporaryExpr. 7416 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7417 return StmtVisitorTy::Visit(E->getSubExpr()); 7418 } 7419 7420 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7421 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7422 return static_cast<Derived*>(this)->VisitCastExpr(E); 7423 } 7424 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7425 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7426 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7427 return static_cast<Derived*>(this)->VisitCastExpr(E); 7428 } 7429 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7430 return static_cast<Derived*>(this)->VisitCastExpr(E); 7431 } 7432 7433 bool VisitBinaryOperator(const BinaryOperator *E) { 7434 switch (E->getOpcode()) { 7435 default: 7436 return Error(E); 7437 7438 case BO_Comma: 7439 VisitIgnoredValue(E->getLHS()); 7440 return StmtVisitorTy::Visit(E->getRHS()); 7441 7442 case BO_PtrMemD: 7443 case BO_PtrMemI: { 7444 LValue Obj; 7445 if (!HandleMemberPointerAccess(Info, E, Obj)) 7446 return false; 7447 APValue Result; 7448 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7449 return false; 7450 return DerivedSuccess(Result, E); 7451 } 7452 } 7453 } 7454 7455 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7456 return StmtVisitorTy::Visit(E->getSemanticForm()); 7457 } 7458 7459 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7460 // Evaluate and cache the common expression. We treat it as a temporary, 7461 // even though it's not quite the same thing. 7462 LValue CommonLV; 7463 if (!Evaluate(Info.CurrentCall->createTemporary( 7464 E->getOpaqueValue(), 7465 getStorageType(Info.Ctx, E->getOpaqueValue()), 7466 ScopeKind::FullExpression, CommonLV), 7467 Info, E->getCommon())) 7468 return false; 7469 7470 return HandleConditionalOperator(E); 7471 } 7472 7473 bool VisitConditionalOperator(const ConditionalOperator *E) { 7474 bool IsBcpCall = false; 7475 // If the condition (ignoring parens) is a __builtin_constant_p call, 7476 // the result is a constant expression if it can be folded without 7477 // side-effects. This is an important GNU extension. See GCC PR38377 7478 // for discussion. 7479 if (const CallExpr *CallCE = 7480 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7481 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7482 IsBcpCall = true; 7483 7484 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7485 // constant expression; we can't check whether it's potentially foldable. 7486 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7487 // it would return 'false' in this mode. 7488 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7489 return false; 7490 7491 FoldConstant Fold(Info, IsBcpCall); 7492 if (!HandleConditionalOperator(E)) { 7493 Fold.keepDiagnostics(); 7494 return false; 7495 } 7496 7497 return true; 7498 } 7499 7500 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7501 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7502 return DerivedSuccess(*Value, E); 7503 7504 const Expr *Source = E->getSourceExpr(); 7505 if (!Source) 7506 return Error(E); 7507 if (Source == E) { 7508 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7509 return Error(E); 7510 } 7511 return StmtVisitorTy::Visit(Source); 7512 } 7513 7514 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7515 for (const Expr *SemE : E->semantics()) { 7516 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7517 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7518 // result expression: there could be two different LValues that would 7519 // refer to the same object in that case, and we can't model that. 7520 if (SemE == E->getResultExpr()) 7521 return Error(E); 7522 7523 // Unique OVEs get evaluated if and when we encounter them when 7524 // emitting the rest of the semantic form, rather than eagerly. 7525 if (OVE->isUnique()) 7526 continue; 7527 7528 LValue LV; 7529 if (!Evaluate(Info.CurrentCall->createTemporary( 7530 OVE, getStorageType(Info.Ctx, OVE), 7531 ScopeKind::FullExpression, LV), 7532 Info, OVE->getSourceExpr())) 7533 return false; 7534 } else if (SemE == E->getResultExpr()) { 7535 if (!StmtVisitorTy::Visit(SemE)) 7536 return false; 7537 } else { 7538 if (!EvaluateIgnoredValue(Info, SemE)) 7539 return false; 7540 } 7541 } 7542 return true; 7543 } 7544 7545 bool VisitCallExpr(const CallExpr *E) { 7546 APValue Result; 7547 if (!handleCallExpr(E, Result, nullptr)) 7548 return false; 7549 return DerivedSuccess(Result, E); 7550 } 7551 7552 bool handleCallExpr(const CallExpr *E, APValue &Result, 7553 const LValue *ResultSlot) { 7554 CallScopeRAII CallScope(Info); 7555 7556 const Expr *Callee = E->getCallee()->IgnoreParens(); 7557 QualType CalleeType = Callee->getType(); 7558 7559 const FunctionDecl *FD = nullptr; 7560 LValue *This = nullptr, ThisVal; 7561 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7562 bool HasQualifier = false; 7563 7564 CallRef Call; 7565 7566 // Extract function decl and 'this' pointer from the callee. 7567 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7568 const CXXMethodDecl *Member = nullptr; 7569 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7570 // Explicit bound member calls, such as x.f() or p->g(); 7571 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7572 return false; 7573 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7574 if (!Member) 7575 return Error(Callee); 7576 This = &ThisVal; 7577 HasQualifier = ME->hasQualifier(); 7578 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7579 // Indirect bound member calls ('.*' or '->*'). 7580 const ValueDecl *D = 7581 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7582 if (!D) 7583 return false; 7584 Member = dyn_cast<CXXMethodDecl>(D); 7585 if (!Member) 7586 return Error(Callee); 7587 This = &ThisVal; 7588 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7589 if (!Info.getLangOpts().CPlusPlus20) 7590 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7591 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7592 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7593 } else 7594 return Error(Callee); 7595 FD = Member; 7596 } else if (CalleeType->isFunctionPointerType()) { 7597 LValue CalleeLV; 7598 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7599 return false; 7600 7601 if (!CalleeLV.getLValueOffset().isZero()) 7602 return Error(Callee); 7603 FD = dyn_cast_or_null<FunctionDecl>( 7604 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7605 if (!FD) 7606 return Error(Callee); 7607 // Don't call function pointers which have been cast to some other type. 7608 // Per DR (no number yet), the caller and callee can differ in noexcept. 7609 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7610 CalleeType->getPointeeType(), FD->getType())) { 7611 return Error(E); 7612 } 7613 7614 // For an (overloaded) assignment expression, evaluate the RHS before the 7615 // LHS. 7616 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7617 if (OCE && OCE->isAssignmentOp()) { 7618 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7619 Call = Info.CurrentCall->createCall(FD); 7620 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7621 Info, FD, /*RightToLeft=*/true)) 7622 return false; 7623 } 7624 7625 // Overloaded operator calls to member functions are represented as normal 7626 // calls with '*this' as the first argument. 7627 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7628 if (MD && !MD->isStatic()) { 7629 // FIXME: When selecting an implicit conversion for an overloaded 7630 // operator delete, we sometimes try to evaluate calls to conversion 7631 // operators without a 'this' parameter! 7632 if (Args.empty()) 7633 return Error(E); 7634 7635 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7636 return false; 7637 This = &ThisVal; 7638 7639 // If this is syntactically a simple assignment using a trivial 7640 // assignment operator, start the lifetimes of union members as needed, 7641 // per C++20 [class.union]5. 7642 if (Info.getLangOpts().CPlusPlus20 && OCE && 7643 OCE->getOperator() == OO_Equal && MD->isTrivial() && 7644 !HandleUnionActiveMemberChange(Info, Args[0], ThisVal)) 7645 return false; 7646 7647 Args = Args.slice(1); 7648 } else if (MD && MD->isLambdaStaticInvoker()) { 7649 // Map the static invoker for the lambda back to the call operator. 7650 // Conveniently, we don't have to slice out the 'this' argument (as is 7651 // being done for the non-static case), since a static member function 7652 // doesn't have an implicit argument passed in. 7653 const CXXRecordDecl *ClosureClass = MD->getParent(); 7654 assert( 7655 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7656 "Number of captures must be zero for conversion to function-ptr"); 7657 7658 const CXXMethodDecl *LambdaCallOp = 7659 ClosureClass->getLambdaCallOperator(); 7660 7661 // Set 'FD', the function that will be called below, to the call 7662 // operator. If the closure object represents a generic lambda, find 7663 // the corresponding specialization of the call operator. 7664 7665 if (ClosureClass->isGenericLambda()) { 7666 assert(MD->isFunctionTemplateSpecialization() && 7667 "A generic lambda's static-invoker function must be a " 7668 "template specialization"); 7669 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7670 FunctionTemplateDecl *CallOpTemplate = 7671 LambdaCallOp->getDescribedFunctionTemplate(); 7672 void *InsertPos = nullptr; 7673 FunctionDecl *CorrespondingCallOpSpecialization = 7674 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7675 assert(CorrespondingCallOpSpecialization && 7676 "We must always have a function call operator specialization " 7677 "that corresponds to our static invoker specialization"); 7678 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7679 } else 7680 FD = LambdaCallOp; 7681 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7682 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7683 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7684 LValue Ptr; 7685 if (!HandleOperatorNewCall(Info, E, Ptr)) 7686 return false; 7687 Ptr.moveInto(Result); 7688 return CallScope.destroy(); 7689 } else { 7690 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7691 } 7692 } 7693 } else 7694 return Error(E); 7695 7696 // Evaluate the arguments now if we've not already done so. 7697 if (!Call) { 7698 Call = Info.CurrentCall->createCall(FD); 7699 if (!EvaluateArgs(Args, Call, Info, FD)) 7700 return false; 7701 } 7702 7703 SmallVector<QualType, 4> CovariantAdjustmentPath; 7704 if (This) { 7705 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7706 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7707 // Perform virtual dispatch, if necessary. 7708 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7709 CovariantAdjustmentPath); 7710 if (!FD) 7711 return false; 7712 } else { 7713 // Check that the 'this' pointer points to an object of the right type. 7714 // FIXME: If this is an assignment operator call, we may need to change 7715 // the active union member before we check this. 7716 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7717 return false; 7718 } 7719 } 7720 7721 // Destructor calls are different enough that they have their own codepath. 7722 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7723 assert(This && "no 'this' pointer for destructor call"); 7724 return HandleDestruction(Info, E, *This, 7725 Info.Ctx.getRecordType(DD->getParent())) && 7726 CallScope.destroy(); 7727 } 7728 7729 const FunctionDecl *Definition = nullptr; 7730 Stmt *Body = FD->getBody(Definition); 7731 7732 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7733 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7734 Body, Info, Result, ResultSlot)) 7735 return false; 7736 7737 if (!CovariantAdjustmentPath.empty() && 7738 !HandleCovariantReturnAdjustment(Info, E, Result, 7739 CovariantAdjustmentPath)) 7740 return false; 7741 7742 return CallScope.destroy(); 7743 } 7744 7745 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7746 return StmtVisitorTy::Visit(E->getInitializer()); 7747 } 7748 bool VisitInitListExpr(const InitListExpr *E) { 7749 if (E->getNumInits() == 0) 7750 return DerivedZeroInitialization(E); 7751 if (E->getNumInits() == 1) 7752 return StmtVisitorTy::Visit(E->getInit(0)); 7753 return Error(E); 7754 } 7755 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7756 return DerivedZeroInitialization(E); 7757 } 7758 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7759 return DerivedZeroInitialization(E); 7760 } 7761 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7762 return DerivedZeroInitialization(E); 7763 } 7764 7765 /// A member expression where the object is a prvalue is itself a prvalue. 7766 bool VisitMemberExpr(const MemberExpr *E) { 7767 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7768 "missing temporary materialization conversion"); 7769 assert(!E->isArrow() && "missing call to bound member function?"); 7770 7771 APValue Val; 7772 if (!Evaluate(Val, Info, E->getBase())) 7773 return false; 7774 7775 QualType BaseTy = E->getBase()->getType(); 7776 7777 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7778 if (!FD) return Error(E); 7779 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7780 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7781 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7782 7783 // Note: there is no lvalue base here. But this case should only ever 7784 // happen in C or in C++98, where we cannot be evaluating a constexpr 7785 // constructor, which is the only case the base matters. 7786 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7787 SubobjectDesignator Designator(BaseTy); 7788 Designator.addDeclUnchecked(FD); 7789 7790 APValue Result; 7791 return extractSubobject(Info, E, Obj, Designator, Result) && 7792 DerivedSuccess(Result, E); 7793 } 7794 7795 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7796 APValue Val; 7797 if (!Evaluate(Val, Info, E->getBase())) 7798 return false; 7799 7800 if (Val.isVector()) { 7801 SmallVector<uint32_t, 4> Indices; 7802 E->getEncodedElementAccess(Indices); 7803 if (Indices.size() == 1) { 7804 // Return scalar. 7805 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7806 } else { 7807 // Construct new APValue vector. 7808 SmallVector<APValue, 4> Elts; 7809 for (unsigned I = 0; I < Indices.size(); ++I) { 7810 Elts.push_back(Val.getVectorElt(Indices[I])); 7811 } 7812 APValue VecResult(Elts.data(), Indices.size()); 7813 return DerivedSuccess(VecResult, E); 7814 } 7815 } 7816 7817 return false; 7818 } 7819 7820 bool VisitCastExpr(const CastExpr *E) { 7821 switch (E->getCastKind()) { 7822 default: 7823 break; 7824 7825 case CK_AtomicToNonAtomic: { 7826 APValue AtomicVal; 7827 // This does not need to be done in place even for class/array types: 7828 // atomic-to-non-atomic conversion implies copying the object 7829 // representation. 7830 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7831 return false; 7832 return DerivedSuccess(AtomicVal, E); 7833 } 7834 7835 case CK_NoOp: 7836 case CK_UserDefinedConversion: 7837 return StmtVisitorTy::Visit(E->getSubExpr()); 7838 7839 case CK_LValueToRValue: { 7840 LValue LVal; 7841 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7842 return false; 7843 APValue RVal; 7844 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7845 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7846 LVal, RVal)) 7847 return false; 7848 return DerivedSuccess(RVal, E); 7849 } 7850 case CK_LValueToRValueBitCast: { 7851 APValue DestValue, SourceValue; 7852 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7853 return false; 7854 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7855 return false; 7856 return DerivedSuccess(DestValue, E); 7857 } 7858 7859 case CK_AddressSpaceConversion: { 7860 APValue Value; 7861 if (!Evaluate(Value, Info, E->getSubExpr())) 7862 return false; 7863 return DerivedSuccess(Value, E); 7864 } 7865 } 7866 7867 return Error(E); 7868 } 7869 7870 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7871 return VisitUnaryPostIncDec(UO); 7872 } 7873 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7874 return VisitUnaryPostIncDec(UO); 7875 } 7876 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7877 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7878 return Error(UO); 7879 7880 LValue LVal; 7881 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7882 return false; 7883 APValue RVal; 7884 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7885 UO->isIncrementOp(), &RVal)) 7886 return false; 7887 return DerivedSuccess(RVal, UO); 7888 } 7889 7890 bool VisitStmtExpr(const StmtExpr *E) { 7891 // We will have checked the full-expressions inside the statement expression 7892 // when they were completed, and don't need to check them again now. 7893 llvm::SaveAndRestore<bool> NotCheckingForUB( 7894 Info.CheckingForUndefinedBehavior, false); 7895 7896 const CompoundStmt *CS = E->getSubStmt(); 7897 if (CS->body_empty()) 7898 return true; 7899 7900 BlockScopeRAII Scope(Info); 7901 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7902 BE = CS->body_end(); 7903 /**/; ++BI) { 7904 if (BI + 1 == BE) { 7905 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7906 if (!FinalExpr) { 7907 Info.FFDiag((*BI)->getBeginLoc(), 7908 diag::note_constexpr_stmt_expr_unsupported); 7909 return false; 7910 } 7911 return this->Visit(FinalExpr) && Scope.destroy(); 7912 } 7913 7914 APValue ReturnValue; 7915 StmtResult Result = { ReturnValue, nullptr }; 7916 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7917 if (ESR != ESR_Succeeded) { 7918 // FIXME: If the statement-expression terminated due to 'return', 7919 // 'break', or 'continue', it would be nice to propagate that to 7920 // the outer statement evaluation rather than bailing out. 7921 if (ESR != ESR_Failed) 7922 Info.FFDiag((*BI)->getBeginLoc(), 7923 diag::note_constexpr_stmt_expr_unsupported); 7924 return false; 7925 } 7926 } 7927 7928 llvm_unreachable("Return from function from the loop above."); 7929 } 7930 7931 /// Visit a value which is evaluated, but whose value is ignored. 7932 void VisitIgnoredValue(const Expr *E) { 7933 EvaluateIgnoredValue(Info, E); 7934 } 7935 7936 /// Potentially visit a MemberExpr's base expression. 7937 void VisitIgnoredBaseExpression(const Expr *E) { 7938 // While MSVC doesn't evaluate the base expression, it does diagnose the 7939 // presence of side-effecting behavior. 7940 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7941 return; 7942 VisitIgnoredValue(E); 7943 } 7944 }; 7945 7946 } // namespace 7947 7948 //===----------------------------------------------------------------------===// 7949 // Common base class for lvalue and temporary evaluation. 7950 //===----------------------------------------------------------------------===// 7951 namespace { 7952 template<class Derived> 7953 class LValueExprEvaluatorBase 7954 : public ExprEvaluatorBase<Derived> { 7955 protected: 7956 LValue &Result; 7957 bool InvalidBaseOK; 7958 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7959 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7960 7961 bool Success(APValue::LValueBase B) { 7962 Result.set(B); 7963 return true; 7964 } 7965 7966 bool evaluatePointer(const Expr *E, LValue &Result) { 7967 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7968 } 7969 7970 public: 7971 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7972 : ExprEvaluatorBaseTy(Info), Result(Result), 7973 InvalidBaseOK(InvalidBaseOK) {} 7974 7975 bool Success(const APValue &V, const Expr *E) { 7976 Result.setFrom(this->Info.Ctx, V); 7977 return true; 7978 } 7979 7980 bool VisitMemberExpr(const MemberExpr *E) { 7981 // Handle non-static data members. 7982 QualType BaseTy; 7983 bool EvalOK; 7984 if (E->isArrow()) { 7985 EvalOK = evaluatePointer(E->getBase(), Result); 7986 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7987 } else if (E->getBase()->isPRValue()) { 7988 assert(E->getBase()->getType()->isRecordType()); 7989 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7990 BaseTy = E->getBase()->getType(); 7991 } else { 7992 EvalOK = this->Visit(E->getBase()); 7993 BaseTy = E->getBase()->getType(); 7994 } 7995 if (!EvalOK) { 7996 if (!InvalidBaseOK) 7997 return false; 7998 Result.setInvalid(E); 7999 return true; 8000 } 8001 8002 const ValueDecl *MD = E->getMemberDecl(); 8003 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 8004 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 8005 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 8006 (void)BaseTy; 8007 if (!HandleLValueMember(this->Info, E, Result, FD)) 8008 return false; 8009 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 8010 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 8011 return false; 8012 } else 8013 return this->Error(E); 8014 8015 if (MD->getType()->isReferenceType()) { 8016 APValue RefValue; 8017 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 8018 RefValue)) 8019 return false; 8020 return Success(RefValue, E); 8021 } 8022 return true; 8023 } 8024 8025 bool VisitBinaryOperator(const BinaryOperator *E) { 8026 switch (E->getOpcode()) { 8027 default: 8028 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8029 8030 case BO_PtrMemD: 8031 case BO_PtrMemI: 8032 return HandleMemberPointerAccess(this->Info, E, Result); 8033 } 8034 } 8035 8036 bool VisitCastExpr(const CastExpr *E) { 8037 switch (E->getCastKind()) { 8038 default: 8039 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8040 8041 case CK_DerivedToBase: 8042 case CK_UncheckedDerivedToBase: 8043 if (!this->Visit(E->getSubExpr())) 8044 return false; 8045 8046 // Now figure out the necessary offset to add to the base LV to get from 8047 // the derived class to the base class. 8048 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8049 Result); 8050 } 8051 } 8052 }; 8053 } 8054 8055 //===----------------------------------------------------------------------===// 8056 // LValue Evaluation 8057 // 8058 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8059 // function designators (in C), decl references to void objects (in C), and 8060 // temporaries (if building with -Wno-address-of-temporary). 8061 // 8062 // LValue evaluation produces values comprising a base expression of one of the 8063 // following types: 8064 // - Declarations 8065 // * VarDecl 8066 // * FunctionDecl 8067 // - Literals 8068 // * CompoundLiteralExpr in C (and in global scope in C++) 8069 // * StringLiteral 8070 // * PredefinedExpr 8071 // * ObjCStringLiteralExpr 8072 // * ObjCEncodeExpr 8073 // * AddrLabelExpr 8074 // * BlockExpr 8075 // * CallExpr for a MakeStringConstant builtin 8076 // - typeid(T) expressions, as TypeInfoLValues 8077 // - Locals and temporaries 8078 // * MaterializeTemporaryExpr 8079 // * Any Expr, with a CallIndex indicating the function in which the temporary 8080 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8081 // from the AST (FIXME). 8082 // * A MaterializeTemporaryExpr that has static storage duration, with no 8083 // CallIndex, for a lifetime-extended temporary. 8084 // * The ConstantExpr that is currently being evaluated during evaluation of an 8085 // immediate invocation. 8086 // plus an offset in bytes. 8087 //===----------------------------------------------------------------------===// 8088 namespace { 8089 class LValueExprEvaluator 8090 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8091 public: 8092 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8093 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8094 8095 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8096 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8097 8098 bool VisitDeclRefExpr(const DeclRefExpr *E); 8099 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8100 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8101 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8102 bool VisitMemberExpr(const MemberExpr *E); 8103 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8104 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8105 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8106 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8107 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8108 bool VisitUnaryDeref(const UnaryOperator *E); 8109 bool VisitUnaryReal(const UnaryOperator *E); 8110 bool VisitUnaryImag(const UnaryOperator *E); 8111 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8112 return VisitUnaryPreIncDec(UO); 8113 } 8114 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8115 return VisitUnaryPreIncDec(UO); 8116 } 8117 bool VisitBinAssign(const BinaryOperator *BO); 8118 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8119 8120 bool VisitCastExpr(const CastExpr *E) { 8121 switch (E->getCastKind()) { 8122 default: 8123 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8124 8125 case CK_LValueBitCast: 8126 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8127 if (!Visit(E->getSubExpr())) 8128 return false; 8129 Result.Designator.setInvalid(); 8130 return true; 8131 8132 case CK_BaseToDerived: 8133 if (!Visit(E->getSubExpr())) 8134 return false; 8135 return HandleBaseToDerivedCast(Info, E, Result); 8136 8137 case CK_Dynamic: 8138 if (!Visit(E->getSubExpr())) 8139 return false; 8140 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8141 } 8142 } 8143 }; 8144 } // end anonymous namespace 8145 8146 /// Evaluate an expression as an lvalue. This can be legitimately called on 8147 /// expressions which are not glvalues, in three cases: 8148 /// * function designators in C, and 8149 /// * "extern void" objects 8150 /// * @selector() expressions in Objective-C 8151 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8152 bool InvalidBaseOK) { 8153 assert(!E->isValueDependent()); 8154 assert(E->isGLValue() || E->getType()->isFunctionType() || 8155 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8156 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8157 } 8158 8159 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8160 const NamedDecl *D = E->getDecl(); 8161 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8162 return Success(cast<ValueDecl>(D)); 8163 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8164 return VisitVarDecl(E, VD); 8165 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8166 return Visit(BD->getBinding()); 8167 return Error(E); 8168 } 8169 8170 8171 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8172 8173 // If we are within a lambda's call operator, check whether the 'VD' referred 8174 // to within 'E' actually represents a lambda-capture that maps to a 8175 // data-member/field within the closure object, and if so, evaluate to the 8176 // field or what the field refers to. 8177 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8178 isa<DeclRefExpr>(E) && 8179 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8180 // We don't always have a complete capture-map when checking or inferring if 8181 // the function call operator meets the requirements of a constexpr function 8182 // - but we don't need to evaluate the captures to determine constexprness 8183 // (dcl.constexpr C++17). 8184 if (Info.checkingPotentialConstantExpression()) 8185 return false; 8186 8187 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8188 // Start with 'Result' referring to the complete closure object... 8189 Result = *Info.CurrentCall->This; 8190 // ... then update it to refer to the field of the closure object 8191 // that represents the capture. 8192 if (!HandleLValueMember(Info, E, Result, FD)) 8193 return false; 8194 // And if the field is of reference type, update 'Result' to refer to what 8195 // the field refers to. 8196 if (FD->getType()->isReferenceType()) { 8197 APValue RVal; 8198 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8199 RVal)) 8200 return false; 8201 Result.setFrom(Info.Ctx, RVal); 8202 } 8203 return true; 8204 } 8205 } 8206 8207 CallStackFrame *Frame = nullptr; 8208 unsigned Version = 0; 8209 if (VD->hasLocalStorage()) { 8210 // Only if a local variable was declared in the function currently being 8211 // evaluated, do we expect to be able to find its value in the current 8212 // frame. (Otherwise it was likely declared in an enclosing context and 8213 // could either have a valid evaluatable value (for e.g. a constexpr 8214 // variable) or be ill-formed (and trigger an appropriate evaluation 8215 // diagnostic)). 8216 CallStackFrame *CurrFrame = Info.CurrentCall; 8217 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8218 // Function parameters are stored in some caller's frame. (Usually the 8219 // immediate caller, but for an inherited constructor they may be more 8220 // distant.) 8221 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8222 if (CurrFrame->Arguments) { 8223 VD = CurrFrame->Arguments.getOrigParam(PVD); 8224 Frame = 8225 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8226 Version = CurrFrame->Arguments.Version; 8227 } 8228 } else { 8229 Frame = CurrFrame; 8230 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8231 } 8232 } 8233 } 8234 8235 if (!VD->getType()->isReferenceType()) { 8236 if (Frame) { 8237 Result.set({VD, Frame->Index, Version}); 8238 return true; 8239 } 8240 return Success(VD); 8241 } 8242 8243 if (!Info.getLangOpts().CPlusPlus11) { 8244 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8245 << VD << VD->getType(); 8246 Info.Note(VD->getLocation(), diag::note_declared_at); 8247 } 8248 8249 APValue *V; 8250 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8251 return false; 8252 if (!V->hasValue()) { 8253 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8254 // adjust the diagnostic to say that. 8255 if (!Info.checkingPotentialConstantExpression()) 8256 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8257 return false; 8258 } 8259 return Success(*V, E); 8260 } 8261 8262 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8263 const MaterializeTemporaryExpr *E) { 8264 // Walk through the expression to find the materialized temporary itself. 8265 SmallVector<const Expr *, 2> CommaLHSs; 8266 SmallVector<SubobjectAdjustment, 2> Adjustments; 8267 const Expr *Inner = 8268 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8269 8270 // If we passed any comma operators, evaluate their LHSs. 8271 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8272 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8273 return false; 8274 8275 // A materialized temporary with static storage duration can appear within the 8276 // result of a constant expression evaluation, so we need to preserve its 8277 // value for use outside this evaluation. 8278 APValue *Value; 8279 if (E->getStorageDuration() == SD_Static) { 8280 // FIXME: What about SD_Thread? 8281 Value = E->getOrCreateValue(true); 8282 *Value = APValue(); 8283 Result.set(E); 8284 } else { 8285 Value = &Info.CurrentCall->createTemporary( 8286 E, E->getType(), 8287 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8288 : ScopeKind::Block, 8289 Result); 8290 } 8291 8292 QualType Type = Inner->getType(); 8293 8294 // Materialize the temporary itself. 8295 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8296 *Value = APValue(); 8297 return false; 8298 } 8299 8300 // Adjust our lvalue to refer to the desired subobject. 8301 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8302 --I; 8303 switch (Adjustments[I].Kind) { 8304 case SubobjectAdjustment::DerivedToBaseAdjustment: 8305 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8306 Type, Result)) 8307 return false; 8308 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8309 break; 8310 8311 case SubobjectAdjustment::FieldAdjustment: 8312 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8313 return false; 8314 Type = Adjustments[I].Field->getType(); 8315 break; 8316 8317 case SubobjectAdjustment::MemberPointerAdjustment: 8318 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8319 Adjustments[I].Ptr.RHS)) 8320 return false; 8321 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8322 break; 8323 } 8324 } 8325 8326 return true; 8327 } 8328 8329 bool 8330 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8331 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8332 "lvalue compound literal in c++?"); 8333 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8334 // only see this when folding in C, so there's no standard to follow here. 8335 return Success(E); 8336 } 8337 8338 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8339 TypeInfoLValue TypeInfo; 8340 8341 if (!E->isPotentiallyEvaluated()) { 8342 if (E->isTypeOperand()) 8343 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8344 else 8345 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8346 } else { 8347 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8348 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8349 << E->getExprOperand()->getType() 8350 << E->getExprOperand()->getSourceRange(); 8351 } 8352 8353 if (!Visit(E->getExprOperand())) 8354 return false; 8355 8356 Optional<DynamicType> DynType = 8357 ComputeDynamicType(Info, E, Result, AK_TypeId); 8358 if (!DynType) 8359 return false; 8360 8361 TypeInfo = 8362 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8363 } 8364 8365 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8366 } 8367 8368 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8369 return Success(E->getGuidDecl()); 8370 } 8371 8372 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8373 // Handle static data members. 8374 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8375 VisitIgnoredBaseExpression(E->getBase()); 8376 return VisitVarDecl(E, VD); 8377 } 8378 8379 // Handle static member functions. 8380 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8381 if (MD->isStatic()) { 8382 VisitIgnoredBaseExpression(E->getBase()); 8383 return Success(MD); 8384 } 8385 } 8386 8387 // Handle non-static data members. 8388 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8389 } 8390 8391 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8392 // FIXME: Deal with vectors as array subscript bases. 8393 if (E->getBase()->getType()->isVectorType()) 8394 return Error(E); 8395 8396 APSInt Index; 8397 bool Success = true; 8398 8399 // C++17's rules require us to evaluate the LHS first, regardless of which 8400 // side is the base. 8401 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8402 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8403 : !EvaluateInteger(SubExpr, Index, Info)) { 8404 if (!Info.noteFailure()) 8405 return false; 8406 Success = false; 8407 } 8408 } 8409 8410 return Success && 8411 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8412 } 8413 8414 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8415 return evaluatePointer(E->getSubExpr(), Result); 8416 } 8417 8418 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8419 if (!Visit(E->getSubExpr())) 8420 return false; 8421 // __real is a no-op on scalar lvalues. 8422 if (E->getSubExpr()->getType()->isAnyComplexType()) 8423 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8424 return true; 8425 } 8426 8427 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8428 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8429 "lvalue __imag__ on scalar?"); 8430 if (!Visit(E->getSubExpr())) 8431 return false; 8432 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8433 return true; 8434 } 8435 8436 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8437 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8438 return Error(UO); 8439 8440 if (!this->Visit(UO->getSubExpr())) 8441 return false; 8442 8443 return handleIncDec( 8444 this->Info, UO, Result, UO->getSubExpr()->getType(), 8445 UO->isIncrementOp(), nullptr); 8446 } 8447 8448 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8449 const CompoundAssignOperator *CAO) { 8450 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8451 return Error(CAO); 8452 8453 bool Success = true; 8454 8455 // C++17 onwards require that we evaluate the RHS first. 8456 APValue RHS; 8457 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8458 if (!Info.noteFailure()) 8459 return false; 8460 Success = false; 8461 } 8462 8463 // The overall lvalue result is the result of evaluating the LHS. 8464 if (!this->Visit(CAO->getLHS()) || !Success) 8465 return false; 8466 8467 return handleCompoundAssignment( 8468 this->Info, CAO, 8469 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8470 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8471 } 8472 8473 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8474 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8475 return Error(E); 8476 8477 bool Success = true; 8478 8479 // C++17 onwards require that we evaluate the RHS first. 8480 APValue NewVal; 8481 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8482 if (!Info.noteFailure()) 8483 return false; 8484 Success = false; 8485 } 8486 8487 if (!this->Visit(E->getLHS()) || !Success) 8488 return false; 8489 8490 if (Info.getLangOpts().CPlusPlus20 && 8491 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8492 return false; 8493 8494 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8495 NewVal); 8496 } 8497 8498 //===----------------------------------------------------------------------===// 8499 // Pointer Evaluation 8500 //===----------------------------------------------------------------------===// 8501 8502 /// Attempts to compute the number of bytes available at the pointer 8503 /// returned by a function with the alloc_size attribute. Returns true if we 8504 /// were successful. Places an unsigned number into `Result`. 8505 /// 8506 /// This expects the given CallExpr to be a call to a function with an 8507 /// alloc_size attribute. 8508 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8509 const CallExpr *Call, 8510 llvm::APInt &Result) { 8511 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8512 8513 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8514 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8515 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8516 if (Call->getNumArgs() <= SizeArgNo) 8517 return false; 8518 8519 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8520 Expr::EvalResult ExprResult; 8521 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8522 return false; 8523 Into = ExprResult.Val.getInt(); 8524 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8525 return false; 8526 Into = Into.zextOrSelf(BitsInSizeT); 8527 return true; 8528 }; 8529 8530 APSInt SizeOfElem; 8531 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8532 return false; 8533 8534 if (!AllocSize->getNumElemsParam().isValid()) { 8535 Result = std::move(SizeOfElem); 8536 return true; 8537 } 8538 8539 APSInt NumberOfElems; 8540 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8541 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8542 return false; 8543 8544 bool Overflow; 8545 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8546 if (Overflow) 8547 return false; 8548 8549 Result = std::move(BytesAvailable); 8550 return true; 8551 } 8552 8553 /// Convenience function. LVal's base must be a call to an alloc_size 8554 /// function. 8555 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8556 const LValue &LVal, 8557 llvm::APInt &Result) { 8558 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8559 "Can't get the size of a non alloc_size function"); 8560 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8561 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8562 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8563 } 8564 8565 /// Attempts to evaluate the given LValueBase as the result of a call to 8566 /// a function with the alloc_size attribute. If it was possible to do so, this 8567 /// function will return true, make Result's Base point to said function call, 8568 /// and mark Result's Base as invalid. 8569 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8570 LValue &Result) { 8571 if (Base.isNull()) 8572 return false; 8573 8574 // Because we do no form of static analysis, we only support const variables. 8575 // 8576 // Additionally, we can't support parameters, nor can we support static 8577 // variables (in the latter case, use-before-assign isn't UB; in the former, 8578 // we have no clue what they'll be assigned to). 8579 const auto *VD = 8580 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8581 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8582 return false; 8583 8584 const Expr *Init = VD->getAnyInitializer(); 8585 if (!Init) 8586 return false; 8587 8588 const Expr *E = Init->IgnoreParens(); 8589 if (!tryUnwrapAllocSizeCall(E)) 8590 return false; 8591 8592 // Store E instead of E unwrapped so that the type of the LValue's base is 8593 // what the user wanted. 8594 Result.setInvalid(E); 8595 8596 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8597 Result.addUnsizedArray(Info, E, Pointee); 8598 return true; 8599 } 8600 8601 namespace { 8602 class PointerExprEvaluator 8603 : public ExprEvaluatorBase<PointerExprEvaluator> { 8604 LValue &Result; 8605 bool InvalidBaseOK; 8606 8607 bool Success(const Expr *E) { 8608 Result.set(E); 8609 return true; 8610 } 8611 8612 bool evaluateLValue(const Expr *E, LValue &Result) { 8613 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8614 } 8615 8616 bool evaluatePointer(const Expr *E, LValue &Result) { 8617 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8618 } 8619 8620 bool visitNonBuiltinCallExpr(const CallExpr *E); 8621 public: 8622 8623 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8624 : ExprEvaluatorBaseTy(info), Result(Result), 8625 InvalidBaseOK(InvalidBaseOK) {} 8626 8627 bool Success(const APValue &V, const Expr *E) { 8628 Result.setFrom(Info.Ctx, V); 8629 return true; 8630 } 8631 bool ZeroInitialization(const Expr *E) { 8632 Result.setNull(Info.Ctx, E->getType()); 8633 return true; 8634 } 8635 8636 bool VisitBinaryOperator(const BinaryOperator *E); 8637 bool VisitCastExpr(const CastExpr* E); 8638 bool VisitUnaryAddrOf(const UnaryOperator *E); 8639 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8640 { return Success(E); } 8641 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8642 if (E->isExpressibleAsConstantInitializer()) 8643 return Success(E); 8644 if (Info.noteFailure()) 8645 EvaluateIgnoredValue(Info, E->getSubExpr()); 8646 return Error(E); 8647 } 8648 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8649 { return Success(E); } 8650 bool VisitCallExpr(const CallExpr *E); 8651 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8652 bool VisitBlockExpr(const BlockExpr *E) { 8653 if (!E->getBlockDecl()->hasCaptures()) 8654 return Success(E); 8655 return Error(E); 8656 } 8657 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8658 // Can't look at 'this' when checking a potential constant expression. 8659 if (Info.checkingPotentialConstantExpression()) 8660 return false; 8661 if (!Info.CurrentCall->This) { 8662 if (Info.getLangOpts().CPlusPlus11) 8663 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8664 else 8665 Info.FFDiag(E); 8666 return false; 8667 } 8668 Result = *Info.CurrentCall->This; 8669 // If we are inside a lambda's call operator, the 'this' expression refers 8670 // to the enclosing '*this' object (either by value or reference) which is 8671 // either copied into the closure object's field that represents the '*this' 8672 // or refers to '*this'. 8673 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8674 // Ensure we actually have captured 'this'. (an error will have 8675 // been previously reported if not). 8676 if (!Info.CurrentCall->LambdaThisCaptureField) 8677 return false; 8678 8679 // Update 'Result' to refer to the data member/field of the closure object 8680 // that represents the '*this' capture. 8681 if (!HandleLValueMember(Info, E, Result, 8682 Info.CurrentCall->LambdaThisCaptureField)) 8683 return false; 8684 // If we captured '*this' by reference, replace the field with its referent. 8685 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8686 ->isPointerType()) { 8687 APValue RVal; 8688 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8689 RVal)) 8690 return false; 8691 8692 Result.setFrom(Info.Ctx, RVal); 8693 } 8694 } 8695 return true; 8696 } 8697 8698 bool VisitCXXNewExpr(const CXXNewExpr *E); 8699 8700 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8701 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8702 APValue LValResult = E->EvaluateInContext( 8703 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8704 Result.setFrom(Info.Ctx, LValResult); 8705 return true; 8706 } 8707 8708 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8709 std::string ResultStr = E->ComputeName(Info.Ctx); 8710 8711 QualType CharTy = Info.Ctx.CharTy.withConst(); 8712 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8713 ResultStr.size() + 1); 8714 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8715 ArrayType::Normal, 0); 8716 8717 StringLiteral *SL = 8718 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, 8719 /*Pascal*/ false, ArrayTy, E->getLocation()); 8720 8721 evaluateLValue(SL, Result); 8722 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8723 return true; 8724 } 8725 8726 // FIXME: Missing: @protocol, @selector 8727 }; 8728 } // end anonymous namespace 8729 8730 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8731 bool InvalidBaseOK) { 8732 assert(!E->isValueDependent()); 8733 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8734 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8735 } 8736 8737 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8738 if (E->getOpcode() != BO_Add && 8739 E->getOpcode() != BO_Sub) 8740 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8741 8742 const Expr *PExp = E->getLHS(); 8743 const Expr *IExp = E->getRHS(); 8744 if (IExp->getType()->isPointerType()) 8745 std::swap(PExp, IExp); 8746 8747 bool EvalPtrOK = evaluatePointer(PExp, Result); 8748 if (!EvalPtrOK && !Info.noteFailure()) 8749 return false; 8750 8751 llvm::APSInt Offset; 8752 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8753 return false; 8754 8755 if (E->getOpcode() == BO_Sub) 8756 negateAsSigned(Offset); 8757 8758 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8759 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8760 } 8761 8762 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8763 return evaluateLValue(E->getSubExpr(), Result); 8764 } 8765 8766 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8767 const Expr *SubExpr = E->getSubExpr(); 8768 8769 switch (E->getCastKind()) { 8770 default: 8771 break; 8772 case CK_BitCast: 8773 case CK_CPointerToObjCPointerCast: 8774 case CK_BlockPointerToObjCPointerCast: 8775 case CK_AnyPointerToBlockPointerCast: 8776 case CK_AddressSpaceConversion: 8777 if (!Visit(SubExpr)) 8778 return false; 8779 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8780 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8781 // also static_casts, but we disallow them as a resolution to DR1312. 8782 if (!E->getType()->isVoidPointerType()) { 8783 if (!Result.InvalidBase && !Result.Designator.Invalid && 8784 !Result.IsNullPtr && 8785 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8786 E->getType()->getPointeeType()) && 8787 Info.getStdAllocatorCaller("allocate")) { 8788 // Inside a call to std::allocator::allocate and friends, we permit 8789 // casting from void* back to cv1 T* for a pointer that points to a 8790 // cv2 T. 8791 } else { 8792 Result.Designator.setInvalid(); 8793 if (SubExpr->getType()->isVoidPointerType()) 8794 CCEDiag(E, diag::note_constexpr_invalid_cast) 8795 << 3 << SubExpr->getType(); 8796 else 8797 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8798 } 8799 } 8800 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8801 ZeroInitialization(E); 8802 return true; 8803 8804 case CK_DerivedToBase: 8805 case CK_UncheckedDerivedToBase: 8806 if (!evaluatePointer(E->getSubExpr(), Result)) 8807 return false; 8808 if (!Result.Base && Result.Offset.isZero()) 8809 return true; 8810 8811 // Now figure out the necessary offset to add to the base LV to get from 8812 // the derived class to the base class. 8813 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8814 castAs<PointerType>()->getPointeeType(), 8815 Result); 8816 8817 case CK_BaseToDerived: 8818 if (!Visit(E->getSubExpr())) 8819 return false; 8820 if (!Result.Base && Result.Offset.isZero()) 8821 return true; 8822 return HandleBaseToDerivedCast(Info, E, Result); 8823 8824 case CK_Dynamic: 8825 if (!Visit(E->getSubExpr())) 8826 return false; 8827 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8828 8829 case CK_NullToPointer: 8830 VisitIgnoredValue(E->getSubExpr()); 8831 return ZeroInitialization(E); 8832 8833 case CK_IntegralToPointer: { 8834 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8835 8836 APValue Value; 8837 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8838 break; 8839 8840 if (Value.isInt()) { 8841 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8842 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8843 Result.Base = (Expr*)nullptr; 8844 Result.InvalidBase = false; 8845 Result.Offset = CharUnits::fromQuantity(N); 8846 Result.Designator.setInvalid(); 8847 Result.IsNullPtr = false; 8848 return true; 8849 } else { 8850 // Cast is of an lvalue, no need to change value. 8851 Result.setFrom(Info.Ctx, Value); 8852 return true; 8853 } 8854 } 8855 8856 case CK_ArrayToPointerDecay: { 8857 if (SubExpr->isGLValue()) { 8858 if (!evaluateLValue(SubExpr, Result)) 8859 return false; 8860 } else { 8861 APValue &Value = Info.CurrentCall->createTemporary( 8862 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8863 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8864 return false; 8865 } 8866 // The result is a pointer to the first element of the array. 8867 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8868 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8869 Result.addArray(Info, E, CAT); 8870 else 8871 Result.addUnsizedArray(Info, E, AT->getElementType()); 8872 return true; 8873 } 8874 8875 case CK_FunctionToPointerDecay: 8876 return evaluateLValue(SubExpr, Result); 8877 8878 case CK_LValueToRValue: { 8879 LValue LVal; 8880 if (!evaluateLValue(E->getSubExpr(), LVal)) 8881 return false; 8882 8883 APValue RVal; 8884 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8885 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8886 LVal, RVal)) 8887 return InvalidBaseOK && 8888 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8889 return Success(RVal, E); 8890 } 8891 } 8892 8893 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8894 } 8895 8896 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8897 UnaryExprOrTypeTrait ExprKind) { 8898 // C++ [expr.alignof]p3: 8899 // When alignof is applied to a reference type, the result is the 8900 // alignment of the referenced type. 8901 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8902 T = Ref->getPointeeType(); 8903 8904 if (T.getQualifiers().hasUnaligned()) 8905 return CharUnits::One(); 8906 8907 const bool AlignOfReturnsPreferred = 8908 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8909 8910 // __alignof is defined to return the preferred alignment. 8911 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8912 // as well. 8913 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8914 return Info.Ctx.toCharUnitsFromBits( 8915 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8916 // alignof and _Alignof are defined to return the ABI alignment. 8917 else if (ExprKind == UETT_AlignOf) 8918 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8919 else 8920 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8921 } 8922 8923 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8924 UnaryExprOrTypeTrait ExprKind) { 8925 E = E->IgnoreParens(); 8926 8927 // The kinds of expressions that we have special-case logic here for 8928 // should be kept up to date with the special checks for those 8929 // expressions in Sema. 8930 8931 // alignof decl is always accepted, even if it doesn't make sense: we default 8932 // to 1 in those cases. 8933 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8934 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8935 /*RefAsPointee*/true); 8936 8937 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8938 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8939 /*RefAsPointee*/true); 8940 8941 return GetAlignOfType(Info, E->getType(), ExprKind); 8942 } 8943 8944 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8945 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8946 return Info.Ctx.getDeclAlign(VD); 8947 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8948 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8949 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8950 } 8951 8952 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8953 /// __builtin_is_aligned and __builtin_assume_aligned. 8954 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8955 EvalInfo &Info, APSInt &Alignment) { 8956 if (!EvaluateInteger(E, Alignment, Info)) 8957 return false; 8958 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8959 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8960 return false; 8961 } 8962 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8963 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8964 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8965 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8966 << MaxValue << ForType << Alignment; 8967 return false; 8968 } 8969 // Ensure both alignment and source value have the same bit width so that we 8970 // don't assert when computing the resulting value. 8971 APSInt ExtAlignment = 8972 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8973 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8974 "Alignment should not be changed by ext/trunc"); 8975 Alignment = ExtAlignment; 8976 assert(Alignment.getBitWidth() == SrcWidth); 8977 return true; 8978 } 8979 8980 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8981 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8982 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8983 return true; 8984 8985 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8986 return false; 8987 8988 Result.setInvalid(E); 8989 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8990 Result.addUnsizedArray(Info, E, PointeeTy); 8991 return true; 8992 } 8993 8994 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8995 if (IsConstantCall(E)) 8996 return Success(E); 8997 8998 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8999 return VisitBuiltinCallExpr(E, BuiltinOp); 9000 9001 return visitNonBuiltinCallExpr(E); 9002 } 9003 9004 // Determine if T is a character type for which we guarantee that 9005 // sizeof(T) == 1. 9006 static bool isOneByteCharacterType(QualType T) { 9007 return T->isCharType() || T->isChar8Type(); 9008 } 9009 9010 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9011 unsigned BuiltinOp) { 9012 switch (BuiltinOp) { 9013 case Builtin::BI__builtin_addressof: 9014 return evaluateLValue(E->getArg(0), Result); 9015 case Builtin::BI__builtin_assume_aligned: { 9016 // We need to be very careful here because: if the pointer does not have the 9017 // asserted alignment, then the behavior is undefined, and undefined 9018 // behavior is non-constant. 9019 if (!evaluatePointer(E->getArg(0), Result)) 9020 return false; 9021 9022 LValue OffsetResult(Result); 9023 APSInt Alignment; 9024 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9025 Alignment)) 9026 return false; 9027 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 9028 9029 if (E->getNumArgs() > 2) { 9030 APSInt Offset; 9031 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9032 return false; 9033 9034 int64_t AdditionalOffset = -Offset.getZExtValue(); 9035 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9036 } 9037 9038 // If there is a base object, then it must have the correct alignment. 9039 if (OffsetResult.Base) { 9040 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9041 9042 if (BaseAlignment < Align) { 9043 Result.Designator.setInvalid(); 9044 // FIXME: Add support to Diagnostic for long / long long. 9045 CCEDiag(E->getArg(0), 9046 diag::note_constexpr_baa_insufficient_alignment) << 0 9047 << (unsigned)BaseAlignment.getQuantity() 9048 << (unsigned)Align.getQuantity(); 9049 return false; 9050 } 9051 } 9052 9053 // The offset must also have the correct alignment. 9054 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9055 Result.Designator.setInvalid(); 9056 9057 (OffsetResult.Base 9058 ? CCEDiag(E->getArg(0), 9059 diag::note_constexpr_baa_insufficient_alignment) << 1 9060 : CCEDiag(E->getArg(0), 9061 diag::note_constexpr_baa_value_insufficient_alignment)) 9062 << (int)OffsetResult.Offset.getQuantity() 9063 << (unsigned)Align.getQuantity(); 9064 return false; 9065 } 9066 9067 return true; 9068 } 9069 case Builtin::BI__builtin_align_up: 9070 case Builtin::BI__builtin_align_down: { 9071 if (!evaluatePointer(E->getArg(0), Result)) 9072 return false; 9073 APSInt Alignment; 9074 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9075 Alignment)) 9076 return false; 9077 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9078 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9079 // For align_up/align_down, we can return the same value if the alignment 9080 // is known to be greater or equal to the requested value. 9081 if (PtrAlign.getQuantity() >= Alignment) 9082 return true; 9083 9084 // The alignment could be greater than the minimum at run-time, so we cannot 9085 // infer much about the resulting pointer value. One case is possible: 9086 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9087 // can infer the correct index if the requested alignment is smaller than 9088 // the base alignment so we can perform the computation on the offset. 9089 if (BaseAlignment.getQuantity() >= Alignment) { 9090 assert(Alignment.getBitWidth() <= 64 && 9091 "Cannot handle > 64-bit address-space"); 9092 uint64_t Alignment64 = Alignment.getZExtValue(); 9093 CharUnits NewOffset = CharUnits::fromQuantity( 9094 BuiltinOp == Builtin::BI__builtin_align_down 9095 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9096 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9097 Result.adjustOffset(NewOffset - Result.Offset); 9098 // TODO: diagnose out-of-bounds values/only allow for arrays? 9099 return true; 9100 } 9101 // Otherwise, we cannot constant-evaluate the result. 9102 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9103 << Alignment; 9104 return false; 9105 } 9106 case Builtin::BI__builtin_operator_new: 9107 return HandleOperatorNewCall(Info, E, Result); 9108 case Builtin::BI__builtin_launder: 9109 return evaluatePointer(E->getArg(0), Result); 9110 case Builtin::BIstrchr: 9111 case Builtin::BIwcschr: 9112 case Builtin::BImemchr: 9113 case Builtin::BIwmemchr: 9114 if (Info.getLangOpts().CPlusPlus11) 9115 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9116 << /*isConstexpr*/0 << /*isConstructor*/0 9117 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9118 else 9119 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9120 LLVM_FALLTHROUGH; 9121 case Builtin::BI__builtin_strchr: 9122 case Builtin::BI__builtin_wcschr: 9123 case Builtin::BI__builtin_memchr: 9124 case Builtin::BI__builtin_char_memchr: 9125 case Builtin::BI__builtin_wmemchr: { 9126 if (!Visit(E->getArg(0))) 9127 return false; 9128 APSInt Desired; 9129 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9130 return false; 9131 uint64_t MaxLength = uint64_t(-1); 9132 if (BuiltinOp != Builtin::BIstrchr && 9133 BuiltinOp != Builtin::BIwcschr && 9134 BuiltinOp != Builtin::BI__builtin_strchr && 9135 BuiltinOp != Builtin::BI__builtin_wcschr) { 9136 APSInt N; 9137 if (!EvaluateInteger(E->getArg(2), N, Info)) 9138 return false; 9139 MaxLength = N.getExtValue(); 9140 } 9141 // We cannot find the value if there are no candidates to match against. 9142 if (MaxLength == 0u) 9143 return ZeroInitialization(E); 9144 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9145 Result.Designator.Invalid) 9146 return false; 9147 QualType CharTy = Result.Designator.getType(Info.Ctx); 9148 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9149 BuiltinOp == Builtin::BI__builtin_memchr; 9150 assert(IsRawByte || 9151 Info.Ctx.hasSameUnqualifiedType( 9152 CharTy, E->getArg(0)->getType()->getPointeeType())); 9153 // Pointers to const void may point to objects of incomplete type. 9154 if (IsRawByte && CharTy->isIncompleteType()) { 9155 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9156 return false; 9157 } 9158 // Give up on byte-oriented matching against multibyte elements. 9159 // FIXME: We can compare the bytes in the correct order. 9160 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9161 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9162 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9163 << CharTy; 9164 return false; 9165 } 9166 // Figure out what value we're actually looking for (after converting to 9167 // the corresponding unsigned type if necessary). 9168 uint64_t DesiredVal; 9169 bool StopAtNull = false; 9170 switch (BuiltinOp) { 9171 case Builtin::BIstrchr: 9172 case Builtin::BI__builtin_strchr: 9173 // strchr compares directly to the passed integer, and therefore 9174 // always fails if given an int that is not a char. 9175 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9176 E->getArg(1)->getType(), 9177 Desired), 9178 Desired)) 9179 return ZeroInitialization(E); 9180 StopAtNull = true; 9181 LLVM_FALLTHROUGH; 9182 case Builtin::BImemchr: 9183 case Builtin::BI__builtin_memchr: 9184 case Builtin::BI__builtin_char_memchr: 9185 // memchr compares by converting both sides to unsigned char. That's also 9186 // correct for strchr if we get this far (to cope with plain char being 9187 // unsigned in the strchr case). 9188 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9189 break; 9190 9191 case Builtin::BIwcschr: 9192 case Builtin::BI__builtin_wcschr: 9193 StopAtNull = true; 9194 LLVM_FALLTHROUGH; 9195 case Builtin::BIwmemchr: 9196 case Builtin::BI__builtin_wmemchr: 9197 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9198 DesiredVal = Desired.getZExtValue(); 9199 break; 9200 } 9201 9202 for (; MaxLength; --MaxLength) { 9203 APValue Char; 9204 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9205 !Char.isInt()) 9206 return false; 9207 if (Char.getInt().getZExtValue() == DesiredVal) 9208 return true; 9209 if (StopAtNull && !Char.getInt()) 9210 break; 9211 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9212 return false; 9213 } 9214 // Not found: return nullptr. 9215 return ZeroInitialization(E); 9216 } 9217 9218 case Builtin::BImemcpy: 9219 case Builtin::BImemmove: 9220 case Builtin::BIwmemcpy: 9221 case Builtin::BIwmemmove: 9222 if (Info.getLangOpts().CPlusPlus11) 9223 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9224 << /*isConstexpr*/0 << /*isConstructor*/0 9225 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9226 else 9227 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9228 LLVM_FALLTHROUGH; 9229 case Builtin::BI__builtin_memcpy: 9230 case Builtin::BI__builtin_memmove: 9231 case Builtin::BI__builtin_wmemcpy: 9232 case Builtin::BI__builtin_wmemmove: { 9233 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9234 BuiltinOp == Builtin::BIwmemmove || 9235 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9236 BuiltinOp == Builtin::BI__builtin_wmemmove; 9237 bool Move = BuiltinOp == Builtin::BImemmove || 9238 BuiltinOp == Builtin::BIwmemmove || 9239 BuiltinOp == Builtin::BI__builtin_memmove || 9240 BuiltinOp == Builtin::BI__builtin_wmemmove; 9241 9242 // The result of mem* is the first argument. 9243 if (!Visit(E->getArg(0))) 9244 return false; 9245 LValue Dest = Result; 9246 9247 LValue Src; 9248 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9249 return false; 9250 9251 APSInt N; 9252 if (!EvaluateInteger(E->getArg(2), N, Info)) 9253 return false; 9254 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9255 9256 // If the size is zero, we treat this as always being a valid no-op. 9257 // (Even if one of the src and dest pointers is null.) 9258 if (!N) 9259 return true; 9260 9261 // Otherwise, if either of the operands is null, we can't proceed. Don't 9262 // try to determine the type of the copied objects, because there aren't 9263 // any. 9264 if (!Src.Base || !Dest.Base) { 9265 APValue Val; 9266 (!Src.Base ? Src : Dest).moveInto(Val); 9267 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9268 << Move << WChar << !!Src.Base 9269 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9270 return false; 9271 } 9272 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9273 return false; 9274 9275 // We require that Src and Dest are both pointers to arrays of 9276 // trivially-copyable type. (For the wide version, the designator will be 9277 // invalid if the designated object is not a wchar_t.) 9278 QualType T = Dest.Designator.getType(Info.Ctx); 9279 QualType SrcT = Src.Designator.getType(Info.Ctx); 9280 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9281 // FIXME: Consider using our bit_cast implementation to support this. 9282 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9283 return false; 9284 } 9285 if (T->isIncompleteType()) { 9286 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9287 return false; 9288 } 9289 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9290 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9291 return false; 9292 } 9293 9294 // Figure out how many T's we're copying. 9295 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9296 if (!WChar) { 9297 uint64_t Remainder; 9298 llvm::APInt OrigN = N; 9299 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9300 if (Remainder) { 9301 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9302 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9303 << (unsigned)TSize; 9304 return false; 9305 } 9306 } 9307 9308 // Check that the copying will remain within the arrays, just so that we 9309 // can give a more meaningful diagnostic. This implicitly also checks that 9310 // N fits into 64 bits. 9311 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9312 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9313 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9314 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9315 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9316 << toString(N, 10, /*Signed*/false); 9317 return false; 9318 } 9319 uint64_t NElems = N.getZExtValue(); 9320 uint64_t NBytes = NElems * TSize; 9321 9322 // Check for overlap. 9323 int Direction = 1; 9324 if (HasSameBase(Src, Dest)) { 9325 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9326 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9327 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9328 // Dest is inside the source region. 9329 if (!Move) { 9330 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9331 return false; 9332 } 9333 // For memmove and friends, copy backwards. 9334 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9335 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9336 return false; 9337 Direction = -1; 9338 } else if (!Move && SrcOffset >= DestOffset && 9339 SrcOffset - DestOffset < NBytes) { 9340 // Src is inside the destination region for memcpy: invalid. 9341 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9342 return false; 9343 } 9344 } 9345 9346 while (true) { 9347 APValue Val; 9348 // FIXME: Set WantObjectRepresentation to true if we're copying a 9349 // char-like type? 9350 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9351 !handleAssignment(Info, E, Dest, T, Val)) 9352 return false; 9353 // Do not iterate past the last element; if we're copying backwards, that 9354 // might take us off the start of the array. 9355 if (--NElems == 0) 9356 return true; 9357 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9358 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9359 return false; 9360 } 9361 } 9362 9363 default: 9364 break; 9365 } 9366 9367 return visitNonBuiltinCallExpr(E); 9368 } 9369 9370 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9371 APValue &Result, const InitListExpr *ILE, 9372 QualType AllocType); 9373 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9374 APValue &Result, 9375 const CXXConstructExpr *CCE, 9376 QualType AllocType); 9377 9378 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9379 if (!Info.getLangOpts().CPlusPlus20) 9380 Info.CCEDiag(E, diag::note_constexpr_new); 9381 9382 // We cannot speculatively evaluate a delete expression. 9383 if (Info.SpeculativeEvaluationDepth) 9384 return false; 9385 9386 FunctionDecl *OperatorNew = E->getOperatorNew(); 9387 9388 bool IsNothrow = false; 9389 bool IsPlacement = false; 9390 if (OperatorNew->isReservedGlobalPlacementOperator() && 9391 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9392 // FIXME Support array placement new. 9393 assert(E->getNumPlacementArgs() == 1); 9394 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9395 return false; 9396 if (Result.Designator.Invalid) 9397 return false; 9398 IsPlacement = true; 9399 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9400 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9401 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9402 return false; 9403 } else if (E->getNumPlacementArgs()) { 9404 // The only new-placement list we support is of the form (std::nothrow). 9405 // 9406 // FIXME: There is no restriction on this, but it's not clear that any 9407 // other form makes any sense. We get here for cases such as: 9408 // 9409 // new (std::align_val_t{N}) X(int) 9410 // 9411 // (which should presumably be valid only if N is a multiple of 9412 // alignof(int), and in any case can't be deallocated unless N is 9413 // alignof(X) and X has new-extended alignment). 9414 if (E->getNumPlacementArgs() != 1 || 9415 !E->getPlacementArg(0)->getType()->isNothrowT()) 9416 return Error(E, diag::note_constexpr_new_placement); 9417 9418 LValue Nothrow; 9419 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9420 return false; 9421 IsNothrow = true; 9422 } 9423 9424 const Expr *Init = E->getInitializer(); 9425 const InitListExpr *ResizedArrayILE = nullptr; 9426 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9427 bool ValueInit = false; 9428 9429 QualType AllocType = E->getAllocatedType(); 9430 if (Optional<const Expr *> ArraySize = E->getArraySize()) { 9431 const Expr *Stripped = *ArraySize; 9432 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9433 Stripped = ICE->getSubExpr()) 9434 if (ICE->getCastKind() != CK_NoOp && 9435 ICE->getCastKind() != CK_IntegralCast) 9436 break; 9437 9438 llvm::APSInt ArrayBound; 9439 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9440 return false; 9441 9442 // C++ [expr.new]p9: 9443 // The expression is erroneous if: 9444 // -- [...] its value before converting to size_t [or] applying the 9445 // second standard conversion sequence is less than zero 9446 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9447 if (IsNothrow) 9448 return ZeroInitialization(E); 9449 9450 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9451 << ArrayBound << (*ArraySize)->getSourceRange(); 9452 return false; 9453 } 9454 9455 // -- its value is such that the size of the allocated object would 9456 // exceed the implementation-defined limit 9457 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9458 ArrayBound) > 9459 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9460 if (IsNothrow) 9461 return ZeroInitialization(E); 9462 9463 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9464 << ArrayBound << (*ArraySize)->getSourceRange(); 9465 return false; 9466 } 9467 9468 // -- the new-initializer is a braced-init-list and the number of 9469 // array elements for which initializers are provided [...] 9470 // exceeds the number of elements to initialize 9471 if (!Init) { 9472 // No initialization is performed. 9473 } else if (isa<CXXScalarValueInitExpr>(Init) || 9474 isa<ImplicitValueInitExpr>(Init)) { 9475 ValueInit = true; 9476 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9477 ResizedArrayCCE = CCE; 9478 } else { 9479 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9480 assert(CAT && "unexpected type for array initializer"); 9481 9482 unsigned Bits = 9483 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9484 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9485 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9486 if (InitBound.ugt(AllocBound)) { 9487 if (IsNothrow) 9488 return ZeroInitialization(E); 9489 9490 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9491 << toString(AllocBound, 10, /*Signed=*/false) 9492 << toString(InitBound, 10, /*Signed=*/false) 9493 << (*ArraySize)->getSourceRange(); 9494 return false; 9495 } 9496 9497 // If the sizes differ, we must have an initializer list, and we need 9498 // special handling for this case when we initialize. 9499 if (InitBound != AllocBound) 9500 ResizedArrayILE = cast<InitListExpr>(Init); 9501 } 9502 9503 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9504 ArrayType::Normal, 0); 9505 } else { 9506 assert(!AllocType->isArrayType() && 9507 "array allocation with non-array new"); 9508 } 9509 9510 APValue *Val; 9511 if (IsPlacement) { 9512 AccessKinds AK = AK_Construct; 9513 struct FindObjectHandler { 9514 EvalInfo &Info; 9515 const Expr *E; 9516 QualType AllocType; 9517 const AccessKinds AccessKind; 9518 APValue *Value; 9519 9520 typedef bool result_type; 9521 bool failed() { return false; } 9522 bool found(APValue &Subobj, QualType SubobjType) { 9523 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9524 // old name of the object to be used to name the new object. 9525 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9526 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9527 SubobjType << AllocType; 9528 return false; 9529 } 9530 Value = &Subobj; 9531 return true; 9532 } 9533 bool found(APSInt &Value, QualType SubobjType) { 9534 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9535 return false; 9536 } 9537 bool found(APFloat &Value, QualType SubobjType) { 9538 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9539 return false; 9540 } 9541 } Handler = {Info, E, AllocType, AK, nullptr}; 9542 9543 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9544 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9545 return false; 9546 9547 Val = Handler.Value; 9548 9549 // [basic.life]p1: 9550 // The lifetime of an object o of type T ends when [...] the storage 9551 // which the object occupies is [...] reused by an object that is not 9552 // nested within o (6.6.2). 9553 *Val = APValue(); 9554 } else { 9555 // Perform the allocation and obtain a pointer to the resulting object. 9556 Val = Info.createHeapAlloc(E, AllocType, Result); 9557 if (!Val) 9558 return false; 9559 } 9560 9561 if (ValueInit) { 9562 ImplicitValueInitExpr VIE(AllocType); 9563 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9564 return false; 9565 } else if (ResizedArrayILE) { 9566 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9567 AllocType)) 9568 return false; 9569 } else if (ResizedArrayCCE) { 9570 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9571 AllocType)) 9572 return false; 9573 } else if (Init) { 9574 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9575 return false; 9576 } else if (!getDefaultInitValue(AllocType, *Val)) { 9577 return false; 9578 } 9579 9580 // Array new returns a pointer to the first element, not a pointer to the 9581 // array. 9582 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9583 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9584 9585 return true; 9586 } 9587 //===----------------------------------------------------------------------===// 9588 // Member Pointer Evaluation 9589 //===----------------------------------------------------------------------===// 9590 9591 namespace { 9592 class MemberPointerExprEvaluator 9593 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9594 MemberPtr &Result; 9595 9596 bool Success(const ValueDecl *D) { 9597 Result = MemberPtr(D); 9598 return true; 9599 } 9600 public: 9601 9602 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9603 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9604 9605 bool Success(const APValue &V, const Expr *E) { 9606 Result.setFrom(V); 9607 return true; 9608 } 9609 bool ZeroInitialization(const Expr *E) { 9610 return Success((const ValueDecl*)nullptr); 9611 } 9612 9613 bool VisitCastExpr(const CastExpr *E); 9614 bool VisitUnaryAddrOf(const UnaryOperator *E); 9615 }; 9616 } // end anonymous namespace 9617 9618 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9619 EvalInfo &Info) { 9620 assert(!E->isValueDependent()); 9621 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9622 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9623 } 9624 9625 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9626 switch (E->getCastKind()) { 9627 default: 9628 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9629 9630 case CK_NullToMemberPointer: 9631 VisitIgnoredValue(E->getSubExpr()); 9632 return ZeroInitialization(E); 9633 9634 case CK_BaseToDerivedMemberPointer: { 9635 if (!Visit(E->getSubExpr())) 9636 return false; 9637 if (E->path_empty()) 9638 return true; 9639 // Base-to-derived member pointer casts store the path in derived-to-base 9640 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9641 // the wrong end of the derived->base arc, so stagger the path by one class. 9642 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9643 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9644 PathI != PathE; ++PathI) { 9645 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9646 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9647 if (!Result.castToDerived(Derived)) 9648 return Error(E); 9649 } 9650 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9651 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9652 return Error(E); 9653 return true; 9654 } 9655 9656 case CK_DerivedToBaseMemberPointer: 9657 if (!Visit(E->getSubExpr())) 9658 return false; 9659 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9660 PathE = E->path_end(); PathI != PathE; ++PathI) { 9661 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9662 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9663 if (!Result.castToBase(Base)) 9664 return Error(E); 9665 } 9666 return true; 9667 } 9668 } 9669 9670 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9671 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9672 // member can be formed. 9673 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9674 } 9675 9676 //===----------------------------------------------------------------------===// 9677 // Record Evaluation 9678 //===----------------------------------------------------------------------===// 9679 9680 namespace { 9681 class RecordExprEvaluator 9682 : public ExprEvaluatorBase<RecordExprEvaluator> { 9683 const LValue &This; 9684 APValue &Result; 9685 public: 9686 9687 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9688 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9689 9690 bool Success(const APValue &V, const Expr *E) { 9691 Result = V; 9692 return true; 9693 } 9694 bool ZeroInitialization(const Expr *E) { 9695 return ZeroInitialization(E, E->getType()); 9696 } 9697 bool ZeroInitialization(const Expr *E, QualType T); 9698 9699 bool VisitCallExpr(const CallExpr *E) { 9700 return handleCallExpr(E, Result, &This); 9701 } 9702 bool VisitCastExpr(const CastExpr *E); 9703 bool VisitInitListExpr(const InitListExpr *E); 9704 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9705 return VisitCXXConstructExpr(E, E->getType()); 9706 } 9707 bool VisitLambdaExpr(const LambdaExpr *E); 9708 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9709 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9710 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9711 bool VisitBinCmp(const BinaryOperator *E); 9712 }; 9713 } 9714 9715 /// Perform zero-initialization on an object of non-union class type. 9716 /// C++11 [dcl.init]p5: 9717 /// To zero-initialize an object or reference of type T means: 9718 /// [...] 9719 /// -- if T is a (possibly cv-qualified) non-union class type, 9720 /// each non-static data member and each base-class subobject is 9721 /// zero-initialized 9722 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9723 const RecordDecl *RD, 9724 const LValue &This, APValue &Result) { 9725 assert(!RD->isUnion() && "Expected non-union class type"); 9726 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9727 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9728 std::distance(RD->field_begin(), RD->field_end())); 9729 9730 if (RD->isInvalidDecl()) return false; 9731 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9732 9733 if (CD) { 9734 unsigned Index = 0; 9735 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9736 End = CD->bases_end(); I != End; ++I, ++Index) { 9737 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9738 LValue Subobject = This; 9739 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9740 return false; 9741 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9742 Result.getStructBase(Index))) 9743 return false; 9744 } 9745 } 9746 9747 for (const auto *I : RD->fields()) { 9748 // -- if T is a reference type, no initialization is performed. 9749 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9750 continue; 9751 9752 LValue Subobject = This; 9753 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9754 return false; 9755 9756 ImplicitValueInitExpr VIE(I->getType()); 9757 if (!EvaluateInPlace( 9758 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9759 return false; 9760 } 9761 9762 return true; 9763 } 9764 9765 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9766 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9767 if (RD->isInvalidDecl()) return false; 9768 if (RD->isUnion()) { 9769 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9770 // object's first non-static named data member is zero-initialized 9771 RecordDecl::field_iterator I = RD->field_begin(); 9772 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9773 ++I; 9774 if (I == RD->field_end()) { 9775 Result = APValue((const FieldDecl*)nullptr); 9776 return true; 9777 } 9778 9779 LValue Subobject = This; 9780 if (!HandleLValueMember(Info, E, Subobject, *I)) 9781 return false; 9782 Result = APValue(*I); 9783 ImplicitValueInitExpr VIE(I->getType()); 9784 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9785 } 9786 9787 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9788 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9789 return false; 9790 } 9791 9792 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9793 } 9794 9795 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9796 switch (E->getCastKind()) { 9797 default: 9798 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9799 9800 case CK_ConstructorConversion: 9801 return Visit(E->getSubExpr()); 9802 9803 case CK_DerivedToBase: 9804 case CK_UncheckedDerivedToBase: { 9805 APValue DerivedObject; 9806 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9807 return false; 9808 if (!DerivedObject.isStruct()) 9809 return Error(E->getSubExpr()); 9810 9811 // Derived-to-base rvalue conversion: just slice off the derived part. 9812 APValue *Value = &DerivedObject; 9813 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9814 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9815 PathE = E->path_end(); PathI != PathE; ++PathI) { 9816 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9817 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9818 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9819 RD = Base; 9820 } 9821 Result = *Value; 9822 return true; 9823 } 9824 } 9825 } 9826 9827 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9828 if (E->isTransparent()) 9829 return Visit(E->getInit(0)); 9830 9831 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9832 if (RD->isInvalidDecl()) return false; 9833 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9834 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9835 9836 EvalInfo::EvaluatingConstructorRAII EvalObj( 9837 Info, 9838 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9839 CXXRD && CXXRD->getNumBases()); 9840 9841 if (RD->isUnion()) { 9842 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9843 Result = APValue(Field); 9844 if (!Field) 9845 return true; 9846 9847 // If the initializer list for a union does not contain any elements, the 9848 // first element of the union is value-initialized. 9849 // FIXME: The element should be initialized from an initializer list. 9850 // Is this difference ever observable for initializer lists which 9851 // we don't build? 9852 ImplicitValueInitExpr VIE(Field->getType()); 9853 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9854 9855 LValue Subobject = This; 9856 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9857 return false; 9858 9859 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9860 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9861 isa<CXXDefaultInitExpr>(InitExpr)); 9862 9863 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9864 if (Field->isBitField()) 9865 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9866 Field); 9867 return true; 9868 } 9869 9870 return false; 9871 } 9872 9873 if (!Result.hasValue()) 9874 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9875 std::distance(RD->field_begin(), RD->field_end())); 9876 unsigned ElementNo = 0; 9877 bool Success = true; 9878 9879 // Initialize base classes. 9880 if (CXXRD && CXXRD->getNumBases()) { 9881 for (const auto &Base : CXXRD->bases()) { 9882 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9883 const Expr *Init = E->getInit(ElementNo); 9884 9885 LValue Subobject = This; 9886 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9887 return false; 9888 9889 APValue &FieldVal = Result.getStructBase(ElementNo); 9890 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9891 if (!Info.noteFailure()) 9892 return false; 9893 Success = false; 9894 } 9895 ++ElementNo; 9896 } 9897 9898 EvalObj.finishedConstructingBases(); 9899 } 9900 9901 // Initialize members. 9902 for (const auto *Field : RD->fields()) { 9903 // Anonymous bit-fields are not considered members of the class for 9904 // purposes of aggregate initialization. 9905 if (Field->isUnnamedBitfield()) 9906 continue; 9907 9908 LValue Subobject = This; 9909 9910 bool HaveInit = ElementNo < E->getNumInits(); 9911 9912 // FIXME: Diagnostics here should point to the end of the initializer 9913 // list, not the start. 9914 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9915 Subobject, Field, &Layout)) 9916 return false; 9917 9918 // Perform an implicit value-initialization for members beyond the end of 9919 // the initializer list. 9920 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9921 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9922 9923 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9924 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9925 isa<CXXDefaultInitExpr>(Init)); 9926 9927 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9928 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9929 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9930 FieldVal, Field))) { 9931 if (!Info.noteFailure()) 9932 return false; 9933 Success = false; 9934 } 9935 } 9936 9937 EvalObj.finishedConstructingFields(); 9938 9939 return Success; 9940 } 9941 9942 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9943 QualType T) { 9944 // Note that E's type is not necessarily the type of our class here; we might 9945 // be initializing an array element instead. 9946 const CXXConstructorDecl *FD = E->getConstructor(); 9947 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9948 9949 bool ZeroInit = E->requiresZeroInitialization(); 9950 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9951 // If we've already performed zero-initialization, we're already done. 9952 if (Result.hasValue()) 9953 return true; 9954 9955 if (ZeroInit) 9956 return ZeroInitialization(E, T); 9957 9958 return getDefaultInitValue(T, Result); 9959 } 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 // Avoid materializing a temporary for an elidable copy/move constructor. 9968 if (E->isElidable() && !ZeroInit) { 9969 // FIXME: This only handles the simplest case, where the source object 9970 // is passed directly as the first argument to the constructor. 9971 // This should also handle stepping though implicit casts and 9972 // and conversion sequences which involve two steps, with a 9973 // conversion operator followed by a converting constructor. 9974 const Expr *SrcObj = E->getArg(0); 9975 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 9976 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 9977 if (const MaterializeTemporaryExpr *ME = 9978 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 9979 return Visit(ME->getSubExpr()); 9980 } 9981 9982 if (ZeroInit && !ZeroInitialization(E, T)) 9983 return false; 9984 9985 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9986 return HandleConstructorCall(E, This, Args, 9987 cast<CXXConstructorDecl>(Definition), Info, 9988 Result); 9989 } 9990 9991 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9992 const CXXInheritedCtorInitExpr *E) { 9993 if (!Info.CurrentCall) { 9994 assert(Info.checkingPotentialConstantExpression()); 9995 return false; 9996 } 9997 9998 const CXXConstructorDecl *FD = E->getConstructor(); 9999 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 10000 return false; 10001 10002 const FunctionDecl *Definition = nullptr; 10003 auto Body = FD->getBody(Definition); 10004 10005 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10006 return false; 10007 10008 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 10009 cast<CXXConstructorDecl>(Definition), Info, 10010 Result); 10011 } 10012 10013 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 10014 const CXXStdInitializerListExpr *E) { 10015 const ConstantArrayType *ArrayType = 10016 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 10017 10018 LValue Array; 10019 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 10020 return false; 10021 10022 // Get a pointer to the first element of the array. 10023 Array.addArray(Info, E, ArrayType); 10024 10025 auto InvalidType = [&] { 10026 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 10027 << E->getType(); 10028 return false; 10029 }; 10030 10031 // FIXME: Perform the checks on the field types in SemaInit. 10032 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10033 RecordDecl::field_iterator Field = Record->field_begin(); 10034 if (Field == Record->field_end()) 10035 return InvalidType(); 10036 10037 // Start pointer. 10038 if (!Field->getType()->isPointerType() || 10039 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10040 ArrayType->getElementType())) 10041 return InvalidType(); 10042 10043 // FIXME: What if the initializer_list type has base classes, etc? 10044 Result = APValue(APValue::UninitStruct(), 0, 2); 10045 Array.moveInto(Result.getStructField(0)); 10046 10047 if (++Field == Record->field_end()) 10048 return InvalidType(); 10049 10050 if (Field->getType()->isPointerType() && 10051 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10052 ArrayType->getElementType())) { 10053 // End pointer. 10054 if (!HandleLValueArrayAdjustment(Info, E, Array, 10055 ArrayType->getElementType(), 10056 ArrayType->getSize().getZExtValue())) 10057 return false; 10058 Array.moveInto(Result.getStructField(1)); 10059 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10060 // Length. 10061 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10062 else 10063 return InvalidType(); 10064 10065 if (++Field != Record->field_end()) 10066 return InvalidType(); 10067 10068 return true; 10069 } 10070 10071 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10072 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10073 if (ClosureClass->isInvalidDecl()) 10074 return false; 10075 10076 const size_t NumFields = 10077 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10078 10079 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10080 E->capture_init_end()) && 10081 "The number of lambda capture initializers should equal the number of " 10082 "fields within the closure type"); 10083 10084 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10085 // Iterate through all the lambda's closure object's fields and initialize 10086 // them. 10087 auto *CaptureInitIt = E->capture_init_begin(); 10088 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10089 bool Success = true; 10090 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10091 for (const auto *Field : ClosureClass->fields()) { 10092 assert(CaptureInitIt != E->capture_init_end()); 10093 // Get the initializer for this field 10094 Expr *const CurFieldInit = *CaptureInitIt++; 10095 10096 // If there is no initializer, either this is a VLA or an error has 10097 // occurred. 10098 if (!CurFieldInit) 10099 return Error(E); 10100 10101 LValue Subobject = This; 10102 10103 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10104 return false; 10105 10106 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10107 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10108 if (!Info.keepEvaluatingAfterFailure()) 10109 return false; 10110 Success = false; 10111 } 10112 ++CaptureIt; 10113 } 10114 return Success; 10115 } 10116 10117 static bool EvaluateRecord(const Expr *E, const LValue &This, 10118 APValue &Result, EvalInfo &Info) { 10119 assert(!E->isValueDependent()); 10120 assert(E->isPRValue() && E->getType()->isRecordType() && 10121 "can't evaluate expression as a record rvalue"); 10122 return RecordExprEvaluator(Info, This, Result).Visit(E); 10123 } 10124 10125 //===----------------------------------------------------------------------===// 10126 // Temporary Evaluation 10127 // 10128 // Temporaries are represented in the AST as rvalues, but generally behave like 10129 // lvalues. The full-object of which the temporary is a subobject is implicitly 10130 // materialized so that a reference can bind to it. 10131 //===----------------------------------------------------------------------===// 10132 namespace { 10133 class TemporaryExprEvaluator 10134 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10135 public: 10136 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10137 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10138 10139 /// Visit an expression which constructs the value of this temporary. 10140 bool VisitConstructExpr(const Expr *E) { 10141 APValue &Value = Info.CurrentCall->createTemporary( 10142 E, E->getType(), ScopeKind::FullExpression, Result); 10143 return EvaluateInPlace(Value, Info, Result, E); 10144 } 10145 10146 bool VisitCastExpr(const CastExpr *E) { 10147 switch (E->getCastKind()) { 10148 default: 10149 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10150 10151 case CK_ConstructorConversion: 10152 return VisitConstructExpr(E->getSubExpr()); 10153 } 10154 } 10155 bool VisitInitListExpr(const InitListExpr *E) { 10156 return VisitConstructExpr(E); 10157 } 10158 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10159 return VisitConstructExpr(E); 10160 } 10161 bool VisitCallExpr(const CallExpr *E) { 10162 return VisitConstructExpr(E); 10163 } 10164 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10165 return VisitConstructExpr(E); 10166 } 10167 bool VisitLambdaExpr(const LambdaExpr *E) { 10168 return VisitConstructExpr(E); 10169 } 10170 }; 10171 } // end anonymous namespace 10172 10173 /// Evaluate an expression of record type as a temporary. 10174 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10175 assert(!E->isValueDependent()); 10176 assert(E->isPRValue() && E->getType()->isRecordType()); 10177 return TemporaryExprEvaluator(Info, Result).Visit(E); 10178 } 10179 10180 //===----------------------------------------------------------------------===// 10181 // Vector Evaluation 10182 //===----------------------------------------------------------------------===// 10183 10184 namespace { 10185 class VectorExprEvaluator 10186 : public ExprEvaluatorBase<VectorExprEvaluator> { 10187 APValue &Result; 10188 public: 10189 10190 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10191 : ExprEvaluatorBaseTy(info), Result(Result) {} 10192 10193 bool Success(ArrayRef<APValue> V, const Expr *E) { 10194 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10195 // FIXME: remove this APValue copy. 10196 Result = APValue(V.data(), V.size()); 10197 return true; 10198 } 10199 bool Success(const APValue &V, const Expr *E) { 10200 assert(V.isVector()); 10201 Result = V; 10202 return true; 10203 } 10204 bool ZeroInitialization(const Expr *E); 10205 10206 bool VisitUnaryReal(const UnaryOperator *E) 10207 { return Visit(E->getSubExpr()); } 10208 bool VisitCastExpr(const CastExpr* E); 10209 bool VisitInitListExpr(const InitListExpr *E); 10210 bool VisitUnaryImag(const UnaryOperator *E); 10211 bool VisitBinaryOperator(const BinaryOperator *E); 10212 bool VisitUnaryOperator(const UnaryOperator *E); 10213 // FIXME: Missing: conditional operator (for GNU 10214 // conditional select), shufflevector, ExtVectorElementExpr 10215 }; 10216 } // end anonymous namespace 10217 10218 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10219 assert(E->isPRValue() && E->getType()->isVectorType() && 10220 "not a vector prvalue"); 10221 return VectorExprEvaluator(Info, Result).Visit(E); 10222 } 10223 10224 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10225 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10226 unsigned NElts = VTy->getNumElements(); 10227 10228 const Expr *SE = E->getSubExpr(); 10229 QualType SETy = SE->getType(); 10230 10231 switch (E->getCastKind()) { 10232 case CK_VectorSplat: { 10233 APValue Val = APValue(); 10234 if (SETy->isIntegerType()) { 10235 APSInt IntResult; 10236 if (!EvaluateInteger(SE, IntResult, Info)) 10237 return false; 10238 Val = APValue(std::move(IntResult)); 10239 } else if (SETy->isRealFloatingType()) { 10240 APFloat FloatResult(0.0); 10241 if (!EvaluateFloat(SE, FloatResult, Info)) 10242 return false; 10243 Val = APValue(std::move(FloatResult)); 10244 } else { 10245 return Error(E); 10246 } 10247 10248 // Splat and create vector APValue. 10249 SmallVector<APValue, 4> Elts(NElts, Val); 10250 return Success(Elts, E); 10251 } 10252 case CK_BitCast: { 10253 // Evaluate the operand into an APInt we can extract from. 10254 llvm::APInt SValInt; 10255 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10256 return false; 10257 // Extract the elements 10258 QualType EltTy = VTy->getElementType(); 10259 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10260 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10261 SmallVector<APValue, 4> Elts; 10262 if (EltTy->isRealFloatingType()) { 10263 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10264 unsigned FloatEltSize = EltSize; 10265 if (&Sem == &APFloat::x87DoubleExtended()) 10266 FloatEltSize = 80; 10267 for (unsigned i = 0; i < NElts; i++) { 10268 llvm::APInt Elt; 10269 if (BigEndian) 10270 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10271 else 10272 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10273 Elts.push_back(APValue(APFloat(Sem, Elt))); 10274 } 10275 } else if (EltTy->isIntegerType()) { 10276 for (unsigned i = 0; i < NElts; i++) { 10277 llvm::APInt Elt; 10278 if (BigEndian) 10279 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10280 else 10281 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10282 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10283 } 10284 } else { 10285 return Error(E); 10286 } 10287 return Success(Elts, E); 10288 } 10289 default: 10290 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10291 } 10292 } 10293 10294 bool 10295 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10296 const VectorType *VT = E->getType()->castAs<VectorType>(); 10297 unsigned NumInits = E->getNumInits(); 10298 unsigned NumElements = VT->getNumElements(); 10299 10300 QualType EltTy = VT->getElementType(); 10301 SmallVector<APValue, 4> Elements; 10302 10303 // The number of initializers can be less than the number of 10304 // vector elements. For OpenCL, this can be due to nested vector 10305 // initialization. For GCC compatibility, missing trailing elements 10306 // should be initialized with zeroes. 10307 unsigned CountInits = 0, CountElts = 0; 10308 while (CountElts < NumElements) { 10309 // Handle nested vector initialization. 10310 if (CountInits < NumInits 10311 && E->getInit(CountInits)->getType()->isVectorType()) { 10312 APValue v; 10313 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10314 return Error(E); 10315 unsigned vlen = v.getVectorLength(); 10316 for (unsigned j = 0; j < vlen; j++) 10317 Elements.push_back(v.getVectorElt(j)); 10318 CountElts += vlen; 10319 } else if (EltTy->isIntegerType()) { 10320 llvm::APSInt sInt(32); 10321 if (CountInits < NumInits) { 10322 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10323 return false; 10324 } else // trailing integer zero. 10325 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10326 Elements.push_back(APValue(sInt)); 10327 CountElts++; 10328 } else { 10329 llvm::APFloat f(0.0); 10330 if (CountInits < NumInits) { 10331 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10332 return false; 10333 } else // trailing float zero. 10334 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10335 Elements.push_back(APValue(f)); 10336 CountElts++; 10337 } 10338 CountInits++; 10339 } 10340 return Success(Elements, E); 10341 } 10342 10343 bool 10344 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10345 const auto *VT = E->getType()->castAs<VectorType>(); 10346 QualType EltTy = VT->getElementType(); 10347 APValue ZeroElement; 10348 if (EltTy->isIntegerType()) 10349 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10350 else 10351 ZeroElement = 10352 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10353 10354 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10355 return Success(Elements, E); 10356 } 10357 10358 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10359 VisitIgnoredValue(E->getSubExpr()); 10360 return ZeroInitialization(E); 10361 } 10362 10363 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10364 BinaryOperatorKind Op = E->getOpcode(); 10365 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10366 "Operation not supported on vector types"); 10367 10368 if (Op == BO_Comma) 10369 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10370 10371 Expr *LHS = E->getLHS(); 10372 Expr *RHS = E->getRHS(); 10373 10374 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10375 "Must both be vector types"); 10376 // Checking JUST the types are the same would be fine, except shifts don't 10377 // need to have their types be the same (since you always shift by an int). 10378 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10379 E->getType()->castAs<VectorType>()->getNumElements() && 10380 RHS->getType()->castAs<VectorType>()->getNumElements() == 10381 E->getType()->castAs<VectorType>()->getNumElements() && 10382 "All operands must be the same size."); 10383 10384 APValue LHSValue; 10385 APValue RHSValue; 10386 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10387 if (!LHSOK && !Info.noteFailure()) 10388 return false; 10389 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10390 return false; 10391 10392 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10393 return false; 10394 10395 return Success(LHSValue, E); 10396 } 10397 10398 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, 10399 QualType ResultTy, 10400 UnaryOperatorKind Op, 10401 APValue Elt) { 10402 switch (Op) { 10403 case UO_Plus: 10404 // Nothing to do here. 10405 return Elt; 10406 case UO_Minus: 10407 if (Elt.getKind() == APValue::Int) { 10408 Elt.getInt().negate(); 10409 } else { 10410 assert(Elt.getKind() == APValue::Float && 10411 "Vector can only be int or float type"); 10412 Elt.getFloat().changeSign(); 10413 } 10414 return Elt; 10415 case UO_Not: 10416 // This is only valid for integral types anyway, so we don't have to handle 10417 // float here. 10418 assert(Elt.getKind() == APValue::Int && 10419 "Vector operator ~ can only be int"); 10420 Elt.getInt().flipAllBits(); 10421 return Elt; 10422 case UO_LNot: { 10423 if (Elt.getKind() == APValue::Int) { 10424 Elt.getInt() = !Elt.getInt(); 10425 // operator ! on vectors returns -1 for 'truth', so negate it. 10426 Elt.getInt().negate(); 10427 return Elt; 10428 } 10429 assert(Elt.getKind() == APValue::Float && 10430 "Vector can only be int or float type"); 10431 // Float types result in an int of the same size, but -1 for true, or 0 for 10432 // false. 10433 APSInt EltResult{Ctx.getIntWidth(ResultTy), 10434 ResultTy->isUnsignedIntegerType()}; 10435 if (Elt.getFloat().isZero()) 10436 EltResult.setAllBits(); 10437 else 10438 EltResult.clearAllBits(); 10439 10440 return APValue{EltResult}; 10441 } 10442 default: 10443 // FIXME: Implement the rest of the unary operators. 10444 return llvm::None; 10445 } 10446 } 10447 10448 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10449 Expr *SubExpr = E->getSubExpr(); 10450 const auto *VD = SubExpr->getType()->castAs<VectorType>(); 10451 // This result element type differs in the case of negating a floating point 10452 // vector, since the result type is the a vector of the equivilant sized 10453 // integer. 10454 const QualType ResultEltTy = VD->getElementType(); 10455 UnaryOperatorKind Op = E->getOpcode(); 10456 10457 APValue SubExprValue; 10458 if (!Evaluate(SubExprValue, Info, SubExpr)) 10459 return false; 10460 10461 // FIXME: This vector evaluator someday needs to be changed to be LValue 10462 // aware/keep LValue information around, rather than dealing with just vector 10463 // types directly. Until then, we cannot handle cases where the operand to 10464 // these unary operators is an LValue. The only case I've been able to see 10465 // cause this is operator++ assigning to a member expression (only valid in 10466 // altivec compilations) in C mode, so this shouldn't limit us too much. 10467 if (SubExprValue.isLValue()) 10468 return false; 10469 10470 assert(SubExprValue.getVectorLength() == VD->getNumElements() && 10471 "Vector length doesn't match type?"); 10472 10473 SmallVector<APValue, 4> ResultElements; 10474 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { 10475 llvm::Optional<APValue> Elt = handleVectorUnaryOperator( 10476 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); 10477 if (!Elt) 10478 return false; 10479 ResultElements.push_back(*Elt); 10480 } 10481 return Success(APValue(ResultElements.data(), ResultElements.size()), E); 10482 } 10483 10484 //===----------------------------------------------------------------------===// 10485 // Array Evaluation 10486 //===----------------------------------------------------------------------===// 10487 10488 namespace { 10489 class ArrayExprEvaluator 10490 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10491 const LValue &This; 10492 APValue &Result; 10493 public: 10494 10495 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10496 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10497 10498 bool Success(const APValue &V, const Expr *E) { 10499 assert(V.isArray() && "expected array"); 10500 Result = V; 10501 return true; 10502 } 10503 10504 bool ZeroInitialization(const Expr *E) { 10505 const ConstantArrayType *CAT = 10506 Info.Ctx.getAsConstantArrayType(E->getType()); 10507 if (!CAT) { 10508 if (E->getType()->isIncompleteArrayType()) { 10509 // We can be asked to zero-initialize a flexible array member; this 10510 // is represented as an ImplicitValueInitExpr of incomplete array 10511 // type. In this case, the array has zero elements. 10512 Result = APValue(APValue::UninitArray(), 0, 0); 10513 return true; 10514 } 10515 // FIXME: We could handle VLAs here. 10516 return Error(E); 10517 } 10518 10519 Result = APValue(APValue::UninitArray(), 0, 10520 CAT->getSize().getZExtValue()); 10521 if (!Result.hasArrayFiller()) 10522 return true; 10523 10524 // Zero-initialize all elements. 10525 LValue Subobject = This; 10526 Subobject.addArray(Info, E, CAT); 10527 ImplicitValueInitExpr VIE(CAT->getElementType()); 10528 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10529 } 10530 10531 bool VisitCallExpr(const CallExpr *E) { 10532 return handleCallExpr(E, Result, &This); 10533 } 10534 bool VisitInitListExpr(const InitListExpr *E, 10535 QualType AllocType = QualType()); 10536 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10537 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10538 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10539 const LValue &Subobject, 10540 APValue *Value, QualType Type); 10541 bool VisitStringLiteral(const StringLiteral *E, 10542 QualType AllocType = QualType()) { 10543 expandStringLiteral(Info, E, Result, AllocType); 10544 return true; 10545 } 10546 }; 10547 } // end anonymous namespace 10548 10549 static bool EvaluateArray(const Expr *E, const LValue &This, 10550 APValue &Result, EvalInfo &Info) { 10551 assert(!E->isValueDependent()); 10552 assert(E->isPRValue() && E->getType()->isArrayType() && 10553 "not an array prvalue"); 10554 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10555 } 10556 10557 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10558 APValue &Result, const InitListExpr *ILE, 10559 QualType AllocType) { 10560 assert(!ILE->isValueDependent()); 10561 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10562 "not an array prvalue"); 10563 return ArrayExprEvaluator(Info, This, Result) 10564 .VisitInitListExpr(ILE, AllocType); 10565 } 10566 10567 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10568 APValue &Result, 10569 const CXXConstructExpr *CCE, 10570 QualType AllocType) { 10571 assert(!CCE->isValueDependent()); 10572 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10573 "not an array prvalue"); 10574 return ArrayExprEvaluator(Info, This, Result) 10575 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10576 } 10577 10578 // Return true iff the given array filler may depend on the element index. 10579 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10580 // For now, just allow non-class value-initialization and initialization 10581 // lists comprised of them. 10582 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10583 return false; 10584 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10585 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10586 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10587 return true; 10588 } 10589 return false; 10590 } 10591 return true; 10592 } 10593 10594 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10595 QualType AllocType) { 10596 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10597 AllocType.isNull() ? E->getType() : AllocType); 10598 if (!CAT) 10599 return Error(E); 10600 10601 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10602 // an appropriately-typed string literal enclosed in braces. 10603 if (E->isStringLiteralInit()) { 10604 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10605 // FIXME: Support ObjCEncodeExpr here once we support it in 10606 // ArrayExprEvaluator generally. 10607 if (!SL) 10608 return Error(E); 10609 return VisitStringLiteral(SL, AllocType); 10610 } 10611 // Any other transparent list init will need proper handling of the 10612 // AllocType; we can't just recurse to the inner initializer. 10613 assert(!E->isTransparent() && 10614 "transparent array list initialization is not string literal init?"); 10615 10616 bool Success = true; 10617 10618 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10619 "zero-initialized array shouldn't have any initialized elts"); 10620 APValue Filler; 10621 if (Result.isArray() && Result.hasArrayFiller()) 10622 Filler = Result.getArrayFiller(); 10623 10624 unsigned NumEltsToInit = E->getNumInits(); 10625 unsigned NumElts = CAT->getSize().getZExtValue(); 10626 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10627 10628 // If the initializer might depend on the array index, run it for each 10629 // array element. 10630 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10631 NumEltsToInit = NumElts; 10632 10633 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10634 << NumEltsToInit << ".\n"); 10635 10636 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10637 10638 // If the array was previously zero-initialized, preserve the 10639 // zero-initialized values. 10640 if (Filler.hasValue()) { 10641 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10642 Result.getArrayInitializedElt(I) = Filler; 10643 if (Result.hasArrayFiller()) 10644 Result.getArrayFiller() = Filler; 10645 } 10646 10647 LValue Subobject = This; 10648 Subobject.addArray(Info, E, CAT); 10649 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10650 const Expr *Init = 10651 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10652 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10653 Info, Subobject, Init) || 10654 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10655 CAT->getElementType(), 1)) { 10656 if (!Info.noteFailure()) 10657 return false; 10658 Success = false; 10659 } 10660 } 10661 10662 if (!Result.hasArrayFiller()) 10663 return Success; 10664 10665 // If we get here, we have a trivial filler, which we can just evaluate 10666 // once and splat over the rest of the array elements. 10667 assert(FillerExpr && "no array filler for incomplete init list"); 10668 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10669 FillerExpr) && Success; 10670 } 10671 10672 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10673 LValue CommonLV; 10674 if (E->getCommonExpr() && 10675 !Evaluate(Info.CurrentCall->createTemporary( 10676 E->getCommonExpr(), 10677 getStorageType(Info.Ctx, E->getCommonExpr()), 10678 ScopeKind::FullExpression, CommonLV), 10679 Info, E->getCommonExpr()->getSourceExpr())) 10680 return false; 10681 10682 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10683 10684 uint64_t Elements = CAT->getSize().getZExtValue(); 10685 Result = APValue(APValue::UninitArray(), Elements, Elements); 10686 10687 LValue Subobject = This; 10688 Subobject.addArray(Info, E, CAT); 10689 10690 bool Success = true; 10691 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10692 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10693 Info, Subobject, E->getSubExpr()) || 10694 !HandleLValueArrayAdjustment(Info, E, Subobject, 10695 CAT->getElementType(), 1)) { 10696 if (!Info.noteFailure()) 10697 return false; 10698 Success = false; 10699 } 10700 } 10701 10702 return Success; 10703 } 10704 10705 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10706 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10707 } 10708 10709 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10710 const LValue &Subobject, 10711 APValue *Value, 10712 QualType Type) { 10713 bool HadZeroInit = Value->hasValue(); 10714 10715 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10716 unsigned FinalSize = CAT->getSize().getZExtValue(); 10717 10718 // Preserve the array filler if we had prior zero-initialization. 10719 APValue Filler = 10720 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10721 : APValue(); 10722 10723 *Value = APValue(APValue::UninitArray(), 0, FinalSize); 10724 if (FinalSize == 0) 10725 return true; 10726 10727 LValue ArrayElt = Subobject; 10728 ArrayElt.addArray(Info, E, CAT); 10729 // We do the whole initialization in two passes, first for just one element, 10730 // then for the whole array. It's possible we may find out we can't do const 10731 // init in the first pass, in which case we avoid allocating a potentially 10732 // large array. We don't do more passes because expanding array requires 10733 // copying the data, which is wasteful. 10734 for (const unsigned N : {1u, FinalSize}) { 10735 unsigned OldElts = Value->getArrayInitializedElts(); 10736 if (OldElts == N) 10737 break; 10738 10739 // Expand the array to appropriate size. 10740 APValue NewValue(APValue::UninitArray(), N, FinalSize); 10741 for (unsigned I = 0; I < OldElts; ++I) 10742 NewValue.getArrayInitializedElt(I).swap( 10743 Value->getArrayInitializedElt(I)); 10744 Value->swap(NewValue); 10745 10746 if (HadZeroInit) 10747 for (unsigned I = OldElts; I < N; ++I) 10748 Value->getArrayInitializedElt(I) = Filler; 10749 10750 // Initialize the elements. 10751 for (unsigned I = OldElts; I < N; ++I) { 10752 if (!VisitCXXConstructExpr(E, ArrayElt, 10753 &Value->getArrayInitializedElt(I), 10754 CAT->getElementType()) || 10755 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10756 CAT->getElementType(), 1)) 10757 return false; 10758 // When checking for const initilization any diagnostic is considered 10759 // an error. 10760 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && 10761 !Info.keepEvaluatingAfterFailure()) 10762 return false; 10763 } 10764 } 10765 10766 return true; 10767 } 10768 10769 if (!Type->isRecordType()) 10770 return Error(E); 10771 10772 return RecordExprEvaluator(Info, Subobject, *Value) 10773 .VisitCXXConstructExpr(E, Type); 10774 } 10775 10776 //===----------------------------------------------------------------------===// 10777 // Integer Evaluation 10778 // 10779 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10780 // types and back in constant folding. Integer values are thus represented 10781 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10782 //===----------------------------------------------------------------------===// 10783 10784 namespace { 10785 class IntExprEvaluator 10786 : public ExprEvaluatorBase<IntExprEvaluator> { 10787 APValue &Result; 10788 public: 10789 IntExprEvaluator(EvalInfo &info, APValue &result) 10790 : ExprEvaluatorBaseTy(info), Result(result) {} 10791 10792 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10793 assert(E->getType()->isIntegralOrEnumerationType() && 10794 "Invalid evaluation result."); 10795 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10796 "Invalid evaluation result."); 10797 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10798 "Invalid evaluation result."); 10799 Result = APValue(SI); 10800 return true; 10801 } 10802 bool Success(const llvm::APSInt &SI, const Expr *E) { 10803 return Success(SI, E, Result); 10804 } 10805 10806 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10807 assert(E->getType()->isIntegralOrEnumerationType() && 10808 "Invalid evaluation result."); 10809 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10810 "Invalid evaluation result."); 10811 Result = APValue(APSInt(I)); 10812 Result.getInt().setIsUnsigned( 10813 E->getType()->isUnsignedIntegerOrEnumerationType()); 10814 return true; 10815 } 10816 bool Success(const llvm::APInt &I, const Expr *E) { 10817 return Success(I, E, Result); 10818 } 10819 10820 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10821 assert(E->getType()->isIntegralOrEnumerationType() && 10822 "Invalid evaluation result."); 10823 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10824 return true; 10825 } 10826 bool Success(uint64_t Value, const Expr *E) { 10827 return Success(Value, E, Result); 10828 } 10829 10830 bool Success(CharUnits Size, const Expr *E) { 10831 return Success(Size.getQuantity(), E); 10832 } 10833 10834 bool Success(const APValue &V, const Expr *E) { 10835 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10836 Result = V; 10837 return true; 10838 } 10839 return Success(V.getInt(), E); 10840 } 10841 10842 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10843 10844 //===--------------------------------------------------------------------===// 10845 // Visitor Methods 10846 //===--------------------------------------------------------------------===// 10847 10848 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10849 return Success(E->getValue(), E); 10850 } 10851 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10852 return Success(E->getValue(), E); 10853 } 10854 10855 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10856 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10857 if (CheckReferencedDecl(E, E->getDecl())) 10858 return true; 10859 10860 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10861 } 10862 bool VisitMemberExpr(const MemberExpr *E) { 10863 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10864 VisitIgnoredBaseExpression(E->getBase()); 10865 return true; 10866 } 10867 10868 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10869 } 10870 10871 bool VisitCallExpr(const CallExpr *E); 10872 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10873 bool VisitBinaryOperator(const BinaryOperator *E); 10874 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10875 bool VisitUnaryOperator(const UnaryOperator *E); 10876 10877 bool VisitCastExpr(const CastExpr* E); 10878 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10879 10880 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10881 return Success(E->getValue(), E); 10882 } 10883 10884 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10885 return Success(E->getValue(), E); 10886 } 10887 10888 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10889 if (Info.ArrayInitIndex == uint64_t(-1)) { 10890 // We were asked to evaluate this subexpression independent of the 10891 // enclosing ArrayInitLoopExpr. We can't do that. 10892 Info.FFDiag(E); 10893 return false; 10894 } 10895 return Success(Info.ArrayInitIndex, E); 10896 } 10897 10898 // Note, GNU defines __null as an integer, not a pointer. 10899 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10900 return ZeroInitialization(E); 10901 } 10902 10903 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10904 return Success(E->getValue(), E); 10905 } 10906 10907 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10908 return Success(E->getValue(), E); 10909 } 10910 10911 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10912 return Success(E->getValue(), E); 10913 } 10914 10915 bool VisitUnaryReal(const UnaryOperator *E); 10916 bool VisitUnaryImag(const UnaryOperator *E); 10917 10918 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10919 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10920 bool VisitSourceLocExpr(const SourceLocExpr *E); 10921 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10922 bool VisitRequiresExpr(const RequiresExpr *E); 10923 // FIXME: Missing: array subscript of vector, member of vector 10924 }; 10925 10926 class FixedPointExprEvaluator 10927 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10928 APValue &Result; 10929 10930 public: 10931 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10932 : ExprEvaluatorBaseTy(info), Result(result) {} 10933 10934 bool Success(const llvm::APInt &I, const Expr *E) { 10935 return Success( 10936 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10937 } 10938 10939 bool Success(uint64_t Value, const Expr *E) { 10940 return Success( 10941 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10942 } 10943 10944 bool Success(const APValue &V, const Expr *E) { 10945 return Success(V.getFixedPoint(), E); 10946 } 10947 10948 bool Success(const APFixedPoint &V, const Expr *E) { 10949 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10950 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10951 "Invalid evaluation result."); 10952 Result = APValue(V); 10953 return true; 10954 } 10955 10956 //===--------------------------------------------------------------------===// 10957 // Visitor Methods 10958 //===--------------------------------------------------------------------===// 10959 10960 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10961 return Success(E->getValue(), E); 10962 } 10963 10964 bool VisitCastExpr(const CastExpr *E); 10965 bool VisitUnaryOperator(const UnaryOperator *E); 10966 bool VisitBinaryOperator(const BinaryOperator *E); 10967 }; 10968 } // end anonymous namespace 10969 10970 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10971 /// produce either the integer value or a pointer. 10972 /// 10973 /// GCC has a heinous extension which folds casts between pointer types and 10974 /// pointer-sized integral types. We support this by allowing the evaluation of 10975 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10976 /// Some simple arithmetic on such values is supported (they are treated much 10977 /// like char*). 10978 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10979 EvalInfo &Info) { 10980 assert(!E->isValueDependent()); 10981 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 10982 return IntExprEvaluator(Info, Result).Visit(E); 10983 } 10984 10985 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10986 assert(!E->isValueDependent()); 10987 APValue Val; 10988 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10989 return false; 10990 if (!Val.isInt()) { 10991 // FIXME: It would be better to produce the diagnostic for casting 10992 // a pointer to an integer. 10993 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10994 return false; 10995 } 10996 Result = Val.getInt(); 10997 return true; 10998 } 10999 11000 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 11001 APValue Evaluated = E->EvaluateInContext( 11002 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 11003 return Success(Evaluated, E); 11004 } 11005 11006 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 11007 EvalInfo &Info) { 11008 assert(!E->isValueDependent()); 11009 if (E->getType()->isFixedPointType()) { 11010 APValue Val; 11011 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 11012 return false; 11013 if (!Val.isFixedPoint()) 11014 return false; 11015 11016 Result = Val.getFixedPoint(); 11017 return true; 11018 } 11019 return false; 11020 } 11021 11022 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 11023 EvalInfo &Info) { 11024 assert(!E->isValueDependent()); 11025 if (E->getType()->isIntegerType()) { 11026 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 11027 APSInt Val; 11028 if (!EvaluateInteger(E, Val, Info)) 11029 return false; 11030 Result = APFixedPoint(Val, FXSema); 11031 return true; 11032 } else if (E->getType()->isFixedPointType()) { 11033 return EvaluateFixedPoint(E, Result, Info); 11034 } 11035 return false; 11036 } 11037 11038 /// Check whether the given declaration can be directly converted to an integral 11039 /// rvalue. If not, no diagnostic is produced; there are other things we can 11040 /// try. 11041 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 11042 // Enums are integer constant exprs. 11043 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 11044 // Check for signedness/width mismatches between E type and ECD value. 11045 bool SameSign = (ECD->getInitVal().isSigned() 11046 == E->getType()->isSignedIntegerOrEnumerationType()); 11047 bool SameWidth = (ECD->getInitVal().getBitWidth() 11048 == Info.Ctx.getIntWidth(E->getType())); 11049 if (SameSign && SameWidth) 11050 return Success(ECD->getInitVal(), E); 11051 else { 11052 // Get rid of mismatch (otherwise Success assertions will fail) 11053 // by computing a new value matching the type of E. 11054 llvm::APSInt Val = ECD->getInitVal(); 11055 if (!SameSign) 11056 Val.setIsSigned(!ECD->getInitVal().isSigned()); 11057 if (!SameWidth) 11058 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 11059 return Success(Val, E); 11060 } 11061 } 11062 return false; 11063 } 11064 11065 /// Values returned by __builtin_classify_type, chosen to match the values 11066 /// produced by GCC's builtin. 11067 enum class GCCTypeClass { 11068 None = -1, 11069 Void = 0, 11070 Integer = 1, 11071 // GCC reserves 2 for character types, but instead classifies them as 11072 // integers. 11073 Enum = 3, 11074 Bool = 4, 11075 Pointer = 5, 11076 // GCC reserves 6 for references, but appears to never use it (because 11077 // expressions never have reference type, presumably). 11078 PointerToDataMember = 7, 11079 RealFloat = 8, 11080 Complex = 9, 11081 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 11082 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 11083 // GCC claims to reserve 11 for pointers to member functions, but *actually* 11084 // uses 12 for that purpose, same as for a class or struct. Maybe it 11085 // internally implements a pointer to member as a struct? Who knows. 11086 PointerToMemberFunction = 12, // Not a bug, see above. 11087 ClassOrStruct = 12, 11088 Union = 13, 11089 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 11090 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 11091 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 11092 // literals. 11093 }; 11094 11095 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11096 /// as GCC. 11097 static GCCTypeClass 11098 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 11099 assert(!T->isDependentType() && "unexpected dependent type"); 11100 11101 QualType CanTy = T.getCanonicalType(); 11102 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 11103 11104 switch (CanTy->getTypeClass()) { 11105 #define TYPE(ID, BASE) 11106 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 11107 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 11108 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 11109 #include "clang/AST/TypeNodes.inc" 11110 case Type::Auto: 11111 case Type::DeducedTemplateSpecialization: 11112 llvm_unreachable("unexpected non-canonical or dependent type"); 11113 11114 case Type::Builtin: 11115 switch (BT->getKind()) { 11116 #define BUILTIN_TYPE(ID, SINGLETON_ID) 11117 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 11118 case BuiltinType::ID: return GCCTypeClass::Integer; 11119 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 11120 case BuiltinType::ID: return GCCTypeClass::RealFloat; 11121 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 11122 case BuiltinType::ID: break; 11123 #include "clang/AST/BuiltinTypes.def" 11124 case BuiltinType::Void: 11125 return GCCTypeClass::Void; 11126 11127 case BuiltinType::Bool: 11128 return GCCTypeClass::Bool; 11129 11130 case BuiltinType::Char_U: 11131 case BuiltinType::UChar: 11132 case BuiltinType::WChar_U: 11133 case BuiltinType::Char8: 11134 case BuiltinType::Char16: 11135 case BuiltinType::Char32: 11136 case BuiltinType::UShort: 11137 case BuiltinType::UInt: 11138 case BuiltinType::ULong: 11139 case BuiltinType::ULongLong: 11140 case BuiltinType::UInt128: 11141 return GCCTypeClass::Integer; 11142 11143 case BuiltinType::UShortAccum: 11144 case BuiltinType::UAccum: 11145 case BuiltinType::ULongAccum: 11146 case BuiltinType::UShortFract: 11147 case BuiltinType::UFract: 11148 case BuiltinType::ULongFract: 11149 case BuiltinType::SatUShortAccum: 11150 case BuiltinType::SatUAccum: 11151 case BuiltinType::SatULongAccum: 11152 case BuiltinType::SatUShortFract: 11153 case BuiltinType::SatUFract: 11154 case BuiltinType::SatULongFract: 11155 return GCCTypeClass::None; 11156 11157 case BuiltinType::NullPtr: 11158 11159 case BuiltinType::ObjCId: 11160 case BuiltinType::ObjCClass: 11161 case BuiltinType::ObjCSel: 11162 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11163 case BuiltinType::Id: 11164 #include "clang/Basic/OpenCLImageTypes.def" 11165 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11166 case BuiltinType::Id: 11167 #include "clang/Basic/OpenCLExtensionTypes.def" 11168 case BuiltinType::OCLSampler: 11169 case BuiltinType::OCLEvent: 11170 case BuiltinType::OCLClkEvent: 11171 case BuiltinType::OCLQueue: 11172 case BuiltinType::OCLReserveID: 11173 #define SVE_TYPE(Name, Id, SingletonId) \ 11174 case BuiltinType::Id: 11175 #include "clang/Basic/AArch64SVEACLETypes.def" 11176 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11177 case BuiltinType::Id: 11178 #include "clang/Basic/PPCTypes.def" 11179 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11180 #include "clang/Basic/RISCVVTypes.def" 11181 return GCCTypeClass::None; 11182 11183 case BuiltinType::Dependent: 11184 llvm_unreachable("unexpected dependent type"); 11185 }; 11186 llvm_unreachable("unexpected placeholder type"); 11187 11188 case Type::Enum: 11189 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11190 11191 case Type::Pointer: 11192 case Type::ConstantArray: 11193 case Type::VariableArray: 11194 case Type::IncompleteArray: 11195 case Type::FunctionNoProto: 11196 case Type::FunctionProto: 11197 return GCCTypeClass::Pointer; 11198 11199 case Type::MemberPointer: 11200 return CanTy->isMemberDataPointerType() 11201 ? GCCTypeClass::PointerToDataMember 11202 : GCCTypeClass::PointerToMemberFunction; 11203 11204 case Type::Complex: 11205 return GCCTypeClass::Complex; 11206 11207 case Type::Record: 11208 return CanTy->isUnionType() ? GCCTypeClass::Union 11209 : GCCTypeClass::ClassOrStruct; 11210 11211 case Type::Atomic: 11212 // GCC classifies _Atomic T the same as T. 11213 return EvaluateBuiltinClassifyType( 11214 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11215 11216 case Type::BlockPointer: 11217 case Type::Vector: 11218 case Type::ExtVector: 11219 case Type::ConstantMatrix: 11220 case Type::ObjCObject: 11221 case Type::ObjCInterface: 11222 case Type::ObjCObjectPointer: 11223 case Type::Pipe: 11224 case Type::BitInt: 11225 // GCC classifies vectors as None. We follow its lead and classify all 11226 // other types that don't fit into the regular classification the same way. 11227 return GCCTypeClass::None; 11228 11229 case Type::LValueReference: 11230 case Type::RValueReference: 11231 llvm_unreachable("invalid type for expression"); 11232 } 11233 11234 llvm_unreachable("unexpected type class"); 11235 } 11236 11237 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11238 /// as GCC. 11239 static GCCTypeClass 11240 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11241 // If no argument was supplied, default to None. This isn't 11242 // ideal, however it is what gcc does. 11243 if (E->getNumArgs() == 0) 11244 return GCCTypeClass::None; 11245 11246 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11247 // being an ICE, but still folds it to a constant using the type of the first 11248 // argument. 11249 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11250 } 11251 11252 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11253 /// __builtin_constant_p when applied to the given pointer. 11254 /// 11255 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11256 /// or it points to the first character of a string literal. 11257 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11258 APValue::LValueBase Base = LV.getLValueBase(); 11259 if (Base.isNull()) { 11260 // A null base is acceptable. 11261 return true; 11262 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11263 if (!isa<StringLiteral>(E)) 11264 return false; 11265 return LV.getLValueOffset().isZero(); 11266 } else if (Base.is<TypeInfoLValue>()) { 11267 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11268 // evaluate to true. 11269 return true; 11270 } else { 11271 // Any other base is not constant enough for GCC. 11272 return false; 11273 } 11274 } 11275 11276 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11277 /// GCC as we can manage. 11278 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11279 // This evaluation is not permitted to have side-effects, so evaluate it in 11280 // a speculative evaluation context. 11281 SpeculativeEvaluationRAII SpeculativeEval(Info); 11282 11283 // Constant-folding is always enabled for the operand of __builtin_constant_p 11284 // (even when the enclosing evaluation context otherwise requires a strict 11285 // language-specific constant expression). 11286 FoldConstant Fold(Info, true); 11287 11288 QualType ArgType = Arg->getType(); 11289 11290 // __builtin_constant_p always has one operand. The rules which gcc follows 11291 // are not precisely documented, but are as follows: 11292 // 11293 // - If the operand is of integral, floating, complex or enumeration type, 11294 // and can be folded to a known value of that type, it returns 1. 11295 // - If the operand can be folded to a pointer to the first character 11296 // of a string literal (or such a pointer cast to an integral type) 11297 // or to a null pointer or an integer cast to a pointer, it returns 1. 11298 // 11299 // Otherwise, it returns 0. 11300 // 11301 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11302 // its support for this did not work prior to GCC 9 and is not yet well 11303 // understood. 11304 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11305 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11306 ArgType->isNullPtrType()) { 11307 APValue V; 11308 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11309 Fold.keepDiagnostics(); 11310 return false; 11311 } 11312 11313 // For a pointer (possibly cast to integer), there are special rules. 11314 if (V.getKind() == APValue::LValue) 11315 return EvaluateBuiltinConstantPForLValue(V); 11316 11317 // Otherwise, any constant value is good enough. 11318 return V.hasValue(); 11319 } 11320 11321 // Anything else isn't considered to be sufficiently constant. 11322 return false; 11323 } 11324 11325 /// Retrieves the "underlying object type" of the given expression, 11326 /// as used by __builtin_object_size. 11327 static QualType getObjectType(APValue::LValueBase B) { 11328 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11329 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11330 return VD->getType(); 11331 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11332 if (isa<CompoundLiteralExpr>(E)) 11333 return E->getType(); 11334 } else if (B.is<TypeInfoLValue>()) { 11335 return B.getTypeInfoType(); 11336 } else if (B.is<DynamicAllocLValue>()) { 11337 return B.getDynamicAllocType(); 11338 } 11339 11340 return QualType(); 11341 } 11342 11343 /// A more selective version of E->IgnoreParenCasts for 11344 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11345 /// to change the type of E. 11346 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11347 /// 11348 /// Always returns an RValue with a pointer representation. 11349 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11350 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11351 11352 auto *NoParens = E->IgnoreParens(); 11353 auto *Cast = dyn_cast<CastExpr>(NoParens); 11354 if (Cast == nullptr) 11355 return NoParens; 11356 11357 // We only conservatively allow a few kinds of casts, because this code is 11358 // inherently a simple solution that seeks to support the common case. 11359 auto CastKind = Cast->getCastKind(); 11360 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11361 CastKind != CK_AddressSpaceConversion) 11362 return NoParens; 11363 11364 auto *SubExpr = Cast->getSubExpr(); 11365 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11366 return NoParens; 11367 return ignorePointerCastsAndParens(SubExpr); 11368 } 11369 11370 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11371 /// record layout. e.g. 11372 /// struct { struct { int a, b; } fst, snd; } obj; 11373 /// obj.fst // no 11374 /// obj.snd // yes 11375 /// obj.fst.a // no 11376 /// obj.fst.b // no 11377 /// obj.snd.a // no 11378 /// obj.snd.b // yes 11379 /// 11380 /// Please note: this function is specialized for how __builtin_object_size 11381 /// views "objects". 11382 /// 11383 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11384 /// correct result, it will always return true. 11385 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11386 assert(!LVal.Designator.Invalid); 11387 11388 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11389 const RecordDecl *Parent = FD->getParent(); 11390 Invalid = Parent->isInvalidDecl(); 11391 if (Invalid || Parent->isUnion()) 11392 return true; 11393 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11394 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11395 }; 11396 11397 auto &Base = LVal.getLValueBase(); 11398 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11399 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11400 bool Invalid; 11401 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11402 return Invalid; 11403 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11404 for (auto *FD : IFD->chain()) { 11405 bool Invalid; 11406 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11407 return Invalid; 11408 } 11409 } 11410 } 11411 11412 unsigned I = 0; 11413 QualType BaseType = getType(Base); 11414 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11415 // If we don't know the array bound, conservatively assume we're looking at 11416 // the final array element. 11417 ++I; 11418 if (BaseType->isIncompleteArrayType()) 11419 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11420 else 11421 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11422 } 11423 11424 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11425 const auto &Entry = LVal.Designator.Entries[I]; 11426 if (BaseType->isArrayType()) { 11427 // Because __builtin_object_size treats arrays as objects, we can ignore 11428 // the index iff this is the last array in the Designator. 11429 if (I + 1 == E) 11430 return true; 11431 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11432 uint64_t Index = Entry.getAsArrayIndex(); 11433 if (Index + 1 != CAT->getSize()) 11434 return false; 11435 BaseType = CAT->getElementType(); 11436 } else if (BaseType->isAnyComplexType()) { 11437 const auto *CT = BaseType->castAs<ComplexType>(); 11438 uint64_t Index = Entry.getAsArrayIndex(); 11439 if (Index != 1) 11440 return false; 11441 BaseType = CT->getElementType(); 11442 } else if (auto *FD = getAsField(Entry)) { 11443 bool Invalid; 11444 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11445 return Invalid; 11446 BaseType = FD->getType(); 11447 } else { 11448 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11449 return false; 11450 } 11451 } 11452 return true; 11453 } 11454 11455 /// Tests to see if the LValue has a user-specified designator (that isn't 11456 /// necessarily valid). Note that this always returns 'true' if the LValue has 11457 /// an unsized array as its first designator entry, because there's currently no 11458 /// way to tell if the user typed *foo or foo[0]. 11459 static bool refersToCompleteObject(const LValue &LVal) { 11460 if (LVal.Designator.Invalid) 11461 return false; 11462 11463 if (!LVal.Designator.Entries.empty()) 11464 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11465 11466 if (!LVal.InvalidBase) 11467 return true; 11468 11469 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11470 // the LValueBase. 11471 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11472 return !E || !isa<MemberExpr>(E); 11473 } 11474 11475 /// Attempts to detect a user writing into a piece of memory that's impossible 11476 /// to figure out the size of by just using types. 11477 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11478 const SubobjectDesignator &Designator = LVal.Designator; 11479 // Notes: 11480 // - Users can only write off of the end when we have an invalid base. Invalid 11481 // bases imply we don't know where the memory came from. 11482 // - We used to be a bit more aggressive here; we'd only be conservative if 11483 // the array at the end was flexible, or if it had 0 or 1 elements. This 11484 // broke some common standard library extensions (PR30346), but was 11485 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11486 // with some sort of list. OTOH, it seems that GCC is always 11487 // conservative with the last element in structs (if it's an array), so our 11488 // current behavior is more compatible than an explicit list approach would 11489 // be. 11490 return LVal.InvalidBase && 11491 Designator.Entries.size() == Designator.MostDerivedPathLength && 11492 Designator.MostDerivedIsArrayElement && 11493 isDesignatorAtObjectEnd(Ctx, LVal); 11494 } 11495 11496 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11497 /// Fails if the conversion would cause loss of precision. 11498 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11499 CharUnits &Result) { 11500 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11501 if (Int.ugt(CharUnitsMax)) 11502 return false; 11503 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11504 return true; 11505 } 11506 11507 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11508 /// determine how many bytes exist from the beginning of the object to either 11509 /// the end of the current subobject, or the end of the object itself, depending 11510 /// on what the LValue looks like + the value of Type. 11511 /// 11512 /// If this returns false, the value of Result is undefined. 11513 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11514 unsigned Type, const LValue &LVal, 11515 CharUnits &EndOffset) { 11516 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11517 11518 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11519 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11520 return false; 11521 return HandleSizeof(Info, ExprLoc, Ty, Result); 11522 }; 11523 11524 // We want to evaluate the size of the entire object. This is a valid fallback 11525 // for when Type=1 and the designator is invalid, because we're asked for an 11526 // upper-bound. 11527 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11528 // Type=3 wants a lower bound, so we can't fall back to this. 11529 if (Type == 3 && !DetermineForCompleteObject) 11530 return false; 11531 11532 llvm::APInt APEndOffset; 11533 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11534 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11535 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11536 11537 if (LVal.InvalidBase) 11538 return false; 11539 11540 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11541 return CheckedHandleSizeof(BaseTy, EndOffset); 11542 } 11543 11544 // We want to evaluate the size of a subobject. 11545 const SubobjectDesignator &Designator = LVal.Designator; 11546 11547 // The following is a moderately common idiom in C: 11548 // 11549 // struct Foo { int a; char c[1]; }; 11550 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11551 // strcpy(&F->c[0], Bar); 11552 // 11553 // In order to not break too much legacy code, we need to support it. 11554 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11555 // If we can resolve this to an alloc_size call, we can hand that back, 11556 // because we know for certain how many bytes there are to write to. 11557 llvm::APInt APEndOffset; 11558 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11559 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11560 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11561 11562 // If we cannot determine the size of the initial allocation, then we can't 11563 // given an accurate upper-bound. However, we are still able to give 11564 // conservative lower-bounds for Type=3. 11565 if (Type == 1) 11566 return false; 11567 } 11568 11569 CharUnits BytesPerElem; 11570 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11571 return false; 11572 11573 // According to the GCC documentation, we want the size of the subobject 11574 // denoted by the pointer. But that's not quite right -- what we actually 11575 // want is the size of the immediately-enclosing array, if there is one. 11576 int64_t ElemsRemaining; 11577 if (Designator.MostDerivedIsArrayElement && 11578 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11579 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11580 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11581 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11582 } else { 11583 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11584 } 11585 11586 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11587 return true; 11588 } 11589 11590 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11591 /// returns true and stores the result in @p Size. 11592 /// 11593 /// If @p WasError is non-null, this will report whether the failure to evaluate 11594 /// is to be treated as an Error in IntExprEvaluator. 11595 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11596 EvalInfo &Info, uint64_t &Size) { 11597 // Determine the denoted object. 11598 LValue LVal; 11599 { 11600 // The operand of __builtin_object_size is never evaluated for side-effects. 11601 // If there are any, but we can determine the pointed-to object anyway, then 11602 // ignore the side-effects. 11603 SpeculativeEvaluationRAII SpeculativeEval(Info); 11604 IgnoreSideEffectsRAII Fold(Info); 11605 11606 if (E->isGLValue()) { 11607 // It's possible for us to be given GLValues if we're called via 11608 // Expr::tryEvaluateObjectSize. 11609 APValue RVal; 11610 if (!EvaluateAsRValue(Info, E, RVal)) 11611 return false; 11612 LVal.setFrom(Info.Ctx, RVal); 11613 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11614 /*InvalidBaseOK=*/true)) 11615 return false; 11616 } 11617 11618 // If we point to before the start of the object, there are no accessible 11619 // bytes. 11620 if (LVal.getLValueOffset().isNegative()) { 11621 Size = 0; 11622 return true; 11623 } 11624 11625 CharUnits EndOffset; 11626 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11627 return false; 11628 11629 // If we've fallen outside of the end offset, just pretend there's nothing to 11630 // write to/read from. 11631 if (EndOffset <= LVal.getLValueOffset()) 11632 Size = 0; 11633 else 11634 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11635 return true; 11636 } 11637 11638 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11639 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11640 return VisitBuiltinCallExpr(E, BuiltinOp); 11641 11642 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11643 } 11644 11645 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11646 APValue &Val, APSInt &Alignment) { 11647 QualType SrcTy = E->getArg(0)->getType(); 11648 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11649 return false; 11650 // Even though we are evaluating integer expressions we could get a pointer 11651 // argument for the __builtin_is_aligned() case. 11652 if (SrcTy->isPointerType()) { 11653 LValue Ptr; 11654 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11655 return false; 11656 Ptr.moveInto(Val); 11657 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11658 Info.FFDiag(E->getArg(0)); 11659 return false; 11660 } else { 11661 APSInt SrcInt; 11662 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11663 return false; 11664 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11665 "Bit widths must be the same"); 11666 Val = APValue(SrcInt); 11667 } 11668 assert(Val.hasValue()); 11669 return true; 11670 } 11671 11672 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11673 unsigned BuiltinOp) { 11674 switch (BuiltinOp) { 11675 default: 11676 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11677 11678 case Builtin::BI__builtin_dynamic_object_size: 11679 case Builtin::BI__builtin_object_size: { 11680 // The type was checked when we built the expression. 11681 unsigned Type = 11682 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11683 assert(Type <= 3 && "unexpected type"); 11684 11685 uint64_t Size; 11686 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11687 return Success(Size, E); 11688 11689 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11690 return Success((Type & 2) ? 0 : -1, E); 11691 11692 // Expression had no side effects, but we couldn't statically determine the 11693 // size of the referenced object. 11694 switch (Info.EvalMode) { 11695 case EvalInfo::EM_ConstantExpression: 11696 case EvalInfo::EM_ConstantFold: 11697 case EvalInfo::EM_IgnoreSideEffects: 11698 // Leave it to IR generation. 11699 return Error(E); 11700 case EvalInfo::EM_ConstantExpressionUnevaluated: 11701 // Reduce it to a constant now. 11702 return Success((Type & 2) ? 0 : -1, E); 11703 } 11704 11705 llvm_unreachable("unexpected EvalMode"); 11706 } 11707 11708 case Builtin::BI__builtin_os_log_format_buffer_size: { 11709 analyze_os_log::OSLogBufferLayout Layout; 11710 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11711 return Success(Layout.size().getQuantity(), E); 11712 } 11713 11714 case Builtin::BI__builtin_is_aligned: { 11715 APValue Src; 11716 APSInt Alignment; 11717 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11718 return false; 11719 if (Src.isLValue()) { 11720 // If we evaluated a pointer, check the minimum known alignment. 11721 LValue Ptr; 11722 Ptr.setFrom(Info.Ctx, Src); 11723 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11724 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11725 // We can return true if the known alignment at the computed offset is 11726 // greater than the requested alignment. 11727 assert(PtrAlign.isPowerOfTwo()); 11728 assert(Alignment.isPowerOf2()); 11729 if (PtrAlign.getQuantity() >= Alignment) 11730 return Success(1, E); 11731 // If the alignment is not known to be sufficient, some cases could still 11732 // be aligned at run time. However, if the requested alignment is less or 11733 // equal to the base alignment and the offset is not aligned, we know that 11734 // the run-time value can never be aligned. 11735 if (BaseAlignment.getQuantity() >= Alignment && 11736 PtrAlign.getQuantity() < Alignment) 11737 return Success(0, E); 11738 // Otherwise we can't infer whether the value is sufficiently aligned. 11739 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11740 // in cases where we can't fully evaluate the pointer. 11741 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11742 << Alignment; 11743 return false; 11744 } 11745 assert(Src.isInt()); 11746 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11747 } 11748 case Builtin::BI__builtin_align_up: { 11749 APValue Src; 11750 APSInt Alignment; 11751 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11752 return false; 11753 if (!Src.isInt()) 11754 return Error(E); 11755 APSInt AlignedVal = 11756 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11757 Src.getInt().isUnsigned()); 11758 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11759 return Success(AlignedVal, E); 11760 } 11761 case Builtin::BI__builtin_align_down: { 11762 APValue Src; 11763 APSInt Alignment; 11764 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11765 return false; 11766 if (!Src.isInt()) 11767 return Error(E); 11768 APSInt AlignedVal = 11769 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11770 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11771 return Success(AlignedVal, E); 11772 } 11773 11774 case Builtin::BI__builtin_bitreverse8: 11775 case Builtin::BI__builtin_bitreverse16: 11776 case Builtin::BI__builtin_bitreverse32: 11777 case Builtin::BI__builtin_bitreverse64: { 11778 APSInt Val; 11779 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11780 return false; 11781 11782 return Success(Val.reverseBits(), E); 11783 } 11784 11785 case Builtin::BI__builtin_bswap16: 11786 case Builtin::BI__builtin_bswap32: 11787 case Builtin::BI__builtin_bswap64: { 11788 APSInt Val; 11789 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11790 return false; 11791 11792 return Success(Val.byteSwap(), E); 11793 } 11794 11795 case Builtin::BI__builtin_classify_type: 11796 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11797 11798 case Builtin::BI__builtin_clrsb: 11799 case Builtin::BI__builtin_clrsbl: 11800 case Builtin::BI__builtin_clrsbll: { 11801 APSInt Val; 11802 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11803 return false; 11804 11805 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11806 } 11807 11808 case Builtin::BI__builtin_clz: 11809 case Builtin::BI__builtin_clzl: 11810 case Builtin::BI__builtin_clzll: 11811 case Builtin::BI__builtin_clzs: { 11812 APSInt Val; 11813 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11814 return false; 11815 if (!Val) 11816 return Error(E); 11817 11818 return Success(Val.countLeadingZeros(), E); 11819 } 11820 11821 case Builtin::BI__builtin_constant_p: { 11822 const Expr *Arg = E->getArg(0); 11823 if (EvaluateBuiltinConstantP(Info, Arg)) 11824 return Success(true, E); 11825 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11826 // Outside a constant context, eagerly evaluate to false in the presence 11827 // of side-effects in order to avoid -Wunsequenced false-positives in 11828 // a branch on __builtin_constant_p(expr). 11829 return Success(false, E); 11830 } 11831 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11832 return false; 11833 } 11834 11835 case Builtin::BI__builtin_is_constant_evaluated: { 11836 const auto *Callee = Info.CurrentCall->getCallee(); 11837 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11838 (Info.CallStackDepth == 1 || 11839 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11840 Callee->getIdentifier() && 11841 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11842 // FIXME: Find a better way to avoid duplicated diagnostics. 11843 if (Info.EvalStatus.Diag) 11844 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11845 : Info.CurrentCall->CallLoc, 11846 diag::warn_is_constant_evaluated_always_true_constexpr) 11847 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11848 : "std::is_constant_evaluated"); 11849 } 11850 11851 return Success(Info.InConstantContext, E); 11852 } 11853 11854 case Builtin::BI__builtin_ctz: 11855 case Builtin::BI__builtin_ctzl: 11856 case Builtin::BI__builtin_ctzll: 11857 case Builtin::BI__builtin_ctzs: { 11858 APSInt Val; 11859 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11860 return false; 11861 if (!Val) 11862 return Error(E); 11863 11864 return Success(Val.countTrailingZeros(), E); 11865 } 11866 11867 case Builtin::BI__builtin_eh_return_data_regno: { 11868 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11869 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11870 return Success(Operand, E); 11871 } 11872 11873 case Builtin::BI__builtin_expect: 11874 case Builtin::BI__builtin_expect_with_probability: 11875 return Visit(E->getArg(0)); 11876 11877 case Builtin::BI__builtin_ffs: 11878 case Builtin::BI__builtin_ffsl: 11879 case Builtin::BI__builtin_ffsll: { 11880 APSInt Val; 11881 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11882 return false; 11883 11884 unsigned N = Val.countTrailingZeros(); 11885 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11886 } 11887 11888 case Builtin::BI__builtin_fpclassify: { 11889 APFloat Val(0.0); 11890 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11891 return false; 11892 unsigned Arg; 11893 switch (Val.getCategory()) { 11894 case APFloat::fcNaN: Arg = 0; break; 11895 case APFloat::fcInfinity: Arg = 1; break; 11896 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11897 case APFloat::fcZero: Arg = 4; break; 11898 } 11899 return Visit(E->getArg(Arg)); 11900 } 11901 11902 case Builtin::BI__builtin_isinf_sign: { 11903 APFloat Val(0.0); 11904 return EvaluateFloat(E->getArg(0), Val, Info) && 11905 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11906 } 11907 11908 case Builtin::BI__builtin_isinf: { 11909 APFloat Val(0.0); 11910 return EvaluateFloat(E->getArg(0), Val, Info) && 11911 Success(Val.isInfinity() ? 1 : 0, E); 11912 } 11913 11914 case Builtin::BI__builtin_isfinite: { 11915 APFloat Val(0.0); 11916 return EvaluateFloat(E->getArg(0), Val, Info) && 11917 Success(Val.isFinite() ? 1 : 0, E); 11918 } 11919 11920 case Builtin::BI__builtin_isnan: { 11921 APFloat Val(0.0); 11922 return EvaluateFloat(E->getArg(0), Val, Info) && 11923 Success(Val.isNaN() ? 1 : 0, E); 11924 } 11925 11926 case Builtin::BI__builtin_isnormal: { 11927 APFloat Val(0.0); 11928 return EvaluateFloat(E->getArg(0), Val, Info) && 11929 Success(Val.isNormal() ? 1 : 0, E); 11930 } 11931 11932 case Builtin::BI__builtin_parity: 11933 case Builtin::BI__builtin_parityl: 11934 case Builtin::BI__builtin_parityll: { 11935 APSInt Val; 11936 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11937 return false; 11938 11939 return Success(Val.countPopulation() % 2, E); 11940 } 11941 11942 case Builtin::BI__builtin_popcount: 11943 case Builtin::BI__builtin_popcountl: 11944 case Builtin::BI__builtin_popcountll: { 11945 APSInt Val; 11946 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11947 return false; 11948 11949 return Success(Val.countPopulation(), E); 11950 } 11951 11952 case Builtin::BI__builtin_rotateleft8: 11953 case Builtin::BI__builtin_rotateleft16: 11954 case Builtin::BI__builtin_rotateleft32: 11955 case Builtin::BI__builtin_rotateleft64: 11956 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11957 case Builtin::BI_rotl16: 11958 case Builtin::BI_rotl: 11959 case Builtin::BI_lrotl: 11960 case Builtin::BI_rotl64: { 11961 APSInt Val, Amt; 11962 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11963 !EvaluateInteger(E->getArg(1), Amt, Info)) 11964 return false; 11965 11966 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11967 } 11968 11969 case Builtin::BI__builtin_rotateright8: 11970 case Builtin::BI__builtin_rotateright16: 11971 case Builtin::BI__builtin_rotateright32: 11972 case Builtin::BI__builtin_rotateright64: 11973 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11974 case Builtin::BI_rotr16: 11975 case Builtin::BI_rotr: 11976 case Builtin::BI_lrotr: 11977 case Builtin::BI_rotr64: { 11978 APSInt Val, Amt; 11979 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11980 !EvaluateInteger(E->getArg(1), Amt, Info)) 11981 return false; 11982 11983 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11984 } 11985 11986 case Builtin::BIstrlen: 11987 case Builtin::BIwcslen: 11988 // A call to strlen is not a constant expression. 11989 if (Info.getLangOpts().CPlusPlus11) 11990 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11991 << /*isConstexpr*/0 << /*isConstructor*/0 11992 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11993 else 11994 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11995 LLVM_FALLTHROUGH; 11996 case Builtin::BI__builtin_strlen: 11997 case Builtin::BI__builtin_wcslen: { 11998 // As an extension, we support __builtin_strlen() as a constant expression, 11999 // and support folding strlen() to a constant. 12000 uint64_t StrLen; 12001 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 12002 return Success(StrLen, E); 12003 return false; 12004 } 12005 12006 case Builtin::BIstrcmp: 12007 case Builtin::BIwcscmp: 12008 case Builtin::BIstrncmp: 12009 case Builtin::BIwcsncmp: 12010 case Builtin::BImemcmp: 12011 case Builtin::BIbcmp: 12012 case Builtin::BIwmemcmp: 12013 // A call to strlen is not a constant expression. 12014 if (Info.getLangOpts().CPlusPlus11) 12015 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12016 << /*isConstexpr*/0 << /*isConstructor*/0 12017 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 12018 else 12019 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12020 LLVM_FALLTHROUGH; 12021 case Builtin::BI__builtin_strcmp: 12022 case Builtin::BI__builtin_wcscmp: 12023 case Builtin::BI__builtin_strncmp: 12024 case Builtin::BI__builtin_wcsncmp: 12025 case Builtin::BI__builtin_memcmp: 12026 case Builtin::BI__builtin_bcmp: 12027 case Builtin::BI__builtin_wmemcmp: { 12028 LValue String1, String2; 12029 if (!EvaluatePointer(E->getArg(0), String1, Info) || 12030 !EvaluatePointer(E->getArg(1), String2, Info)) 12031 return false; 12032 12033 uint64_t MaxLength = uint64_t(-1); 12034 if (BuiltinOp != Builtin::BIstrcmp && 12035 BuiltinOp != Builtin::BIwcscmp && 12036 BuiltinOp != Builtin::BI__builtin_strcmp && 12037 BuiltinOp != Builtin::BI__builtin_wcscmp) { 12038 APSInt N; 12039 if (!EvaluateInteger(E->getArg(2), N, Info)) 12040 return false; 12041 MaxLength = N.getExtValue(); 12042 } 12043 12044 // Empty substrings compare equal by definition. 12045 if (MaxLength == 0u) 12046 return Success(0, E); 12047 12048 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12049 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12050 String1.Designator.Invalid || String2.Designator.Invalid) 12051 return false; 12052 12053 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 12054 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 12055 12056 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 12057 BuiltinOp == Builtin::BIbcmp || 12058 BuiltinOp == Builtin::BI__builtin_memcmp || 12059 BuiltinOp == Builtin::BI__builtin_bcmp; 12060 12061 assert(IsRawByte || 12062 (Info.Ctx.hasSameUnqualifiedType( 12063 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 12064 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 12065 12066 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 12067 // 'char8_t', but no other types. 12068 if (IsRawByte && 12069 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 12070 // FIXME: Consider using our bit_cast implementation to support this. 12071 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 12072 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 12073 << CharTy1 << CharTy2; 12074 return false; 12075 } 12076 12077 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 12078 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 12079 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 12080 Char1.isInt() && Char2.isInt(); 12081 }; 12082 const auto &AdvanceElems = [&] { 12083 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 12084 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 12085 }; 12086 12087 bool StopAtNull = 12088 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 12089 BuiltinOp != Builtin::BIwmemcmp && 12090 BuiltinOp != Builtin::BI__builtin_memcmp && 12091 BuiltinOp != Builtin::BI__builtin_bcmp && 12092 BuiltinOp != Builtin::BI__builtin_wmemcmp); 12093 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 12094 BuiltinOp == Builtin::BIwcsncmp || 12095 BuiltinOp == Builtin::BIwmemcmp || 12096 BuiltinOp == Builtin::BI__builtin_wcscmp || 12097 BuiltinOp == Builtin::BI__builtin_wcsncmp || 12098 BuiltinOp == Builtin::BI__builtin_wmemcmp; 12099 12100 for (; MaxLength; --MaxLength) { 12101 APValue Char1, Char2; 12102 if (!ReadCurElems(Char1, Char2)) 12103 return false; 12104 if (Char1.getInt().ne(Char2.getInt())) { 12105 if (IsWide) // wmemcmp compares with wchar_t signedness. 12106 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 12107 // memcmp always compares unsigned chars. 12108 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 12109 } 12110 if (StopAtNull && !Char1.getInt()) 12111 return Success(0, E); 12112 assert(!(StopAtNull && !Char2.getInt())); 12113 if (!AdvanceElems()) 12114 return false; 12115 } 12116 // We hit the strncmp / memcmp limit. 12117 return Success(0, E); 12118 } 12119 12120 case Builtin::BI__atomic_always_lock_free: 12121 case Builtin::BI__atomic_is_lock_free: 12122 case Builtin::BI__c11_atomic_is_lock_free: { 12123 APSInt SizeVal; 12124 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 12125 return false; 12126 12127 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12128 // of two less than or equal to the maximum inline atomic width, we know it 12129 // is lock-free. If the size isn't a power of two, or greater than the 12130 // maximum alignment where we promote atomics, we know it is not lock-free 12131 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12132 // the answer can only be determined at runtime; for example, 16-byte 12133 // atomics have lock-free implementations on some, but not all, 12134 // x86-64 processors. 12135 12136 // Check power-of-two. 12137 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12138 if (Size.isPowerOfTwo()) { 12139 // Check against inlining width. 12140 unsigned InlineWidthBits = 12141 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12142 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12143 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12144 Size == CharUnits::One() || 12145 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12146 Expr::NPC_NeverValueDependent)) 12147 // OK, we will inline appropriately-aligned operations of this size, 12148 // and _Atomic(T) is appropriately-aligned. 12149 return Success(1, E); 12150 12151 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12152 castAs<PointerType>()->getPointeeType(); 12153 if (!PointeeType->isIncompleteType() && 12154 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12155 // OK, we will inline operations on this object. 12156 return Success(1, E); 12157 } 12158 } 12159 } 12160 12161 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12162 Success(0, E) : Error(E); 12163 } 12164 case Builtin::BI__builtin_add_overflow: 12165 case Builtin::BI__builtin_sub_overflow: 12166 case Builtin::BI__builtin_mul_overflow: 12167 case Builtin::BI__builtin_sadd_overflow: 12168 case Builtin::BI__builtin_uadd_overflow: 12169 case Builtin::BI__builtin_uaddl_overflow: 12170 case Builtin::BI__builtin_uaddll_overflow: 12171 case Builtin::BI__builtin_usub_overflow: 12172 case Builtin::BI__builtin_usubl_overflow: 12173 case Builtin::BI__builtin_usubll_overflow: 12174 case Builtin::BI__builtin_umul_overflow: 12175 case Builtin::BI__builtin_umull_overflow: 12176 case Builtin::BI__builtin_umulll_overflow: 12177 case Builtin::BI__builtin_saddl_overflow: 12178 case Builtin::BI__builtin_saddll_overflow: 12179 case Builtin::BI__builtin_ssub_overflow: 12180 case Builtin::BI__builtin_ssubl_overflow: 12181 case Builtin::BI__builtin_ssubll_overflow: 12182 case Builtin::BI__builtin_smul_overflow: 12183 case Builtin::BI__builtin_smull_overflow: 12184 case Builtin::BI__builtin_smulll_overflow: { 12185 LValue ResultLValue; 12186 APSInt LHS, RHS; 12187 12188 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12189 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12190 !EvaluateInteger(E->getArg(1), RHS, Info) || 12191 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12192 return false; 12193 12194 APSInt Result; 12195 bool DidOverflow = false; 12196 12197 // If the types don't have to match, enlarge all 3 to the largest of them. 12198 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12199 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12200 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12201 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12202 ResultType->isSignedIntegerOrEnumerationType(); 12203 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12204 ResultType->isSignedIntegerOrEnumerationType(); 12205 uint64_t LHSSize = LHS.getBitWidth(); 12206 uint64_t RHSSize = RHS.getBitWidth(); 12207 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12208 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12209 12210 // Add an additional bit if the signedness isn't uniformly agreed to. We 12211 // could do this ONLY if there is a signed and an unsigned that both have 12212 // MaxBits, but the code to check that is pretty nasty. The issue will be 12213 // caught in the shrink-to-result later anyway. 12214 if (IsSigned && !AllSigned) 12215 ++MaxBits; 12216 12217 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12218 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12219 Result = APSInt(MaxBits, !IsSigned); 12220 } 12221 12222 // Find largest int. 12223 switch (BuiltinOp) { 12224 default: 12225 llvm_unreachable("Invalid value for BuiltinOp"); 12226 case Builtin::BI__builtin_add_overflow: 12227 case Builtin::BI__builtin_sadd_overflow: 12228 case Builtin::BI__builtin_saddl_overflow: 12229 case Builtin::BI__builtin_saddll_overflow: 12230 case Builtin::BI__builtin_uadd_overflow: 12231 case Builtin::BI__builtin_uaddl_overflow: 12232 case Builtin::BI__builtin_uaddll_overflow: 12233 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12234 : LHS.uadd_ov(RHS, DidOverflow); 12235 break; 12236 case Builtin::BI__builtin_sub_overflow: 12237 case Builtin::BI__builtin_ssub_overflow: 12238 case Builtin::BI__builtin_ssubl_overflow: 12239 case Builtin::BI__builtin_ssubll_overflow: 12240 case Builtin::BI__builtin_usub_overflow: 12241 case Builtin::BI__builtin_usubl_overflow: 12242 case Builtin::BI__builtin_usubll_overflow: 12243 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12244 : LHS.usub_ov(RHS, DidOverflow); 12245 break; 12246 case Builtin::BI__builtin_mul_overflow: 12247 case Builtin::BI__builtin_smul_overflow: 12248 case Builtin::BI__builtin_smull_overflow: 12249 case Builtin::BI__builtin_smulll_overflow: 12250 case Builtin::BI__builtin_umul_overflow: 12251 case Builtin::BI__builtin_umull_overflow: 12252 case Builtin::BI__builtin_umulll_overflow: 12253 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12254 : LHS.umul_ov(RHS, DidOverflow); 12255 break; 12256 } 12257 12258 // In the case where multiple sizes are allowed, truncate and see if 12259 // the values are the same. 12260 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12261 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12262 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12263 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12264 // since it will give us the behavior of a TruncOrSelf in the case where 12265 // its parameter <= its size. We previously set Result to be at least the 12266 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12267 // will work exactly like TruncOrSelf. 12268 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12269 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12270 12271 if (!APSInt::isSameValue(Temp, Result)) 12272 DidOverflow = true; 12273 Result = Temp; 12274 } 12275 12276 APValue APV{Result}; 12277 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12278 return false; 12279 return Success(DidOverflow, E); 12280 } 12281 } 12282 } 12283 12284 /// Determine whether this is a pointer past the end of the complete 12285 /// object referred to by the lvalue. 12286 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12287 const LValue &LV) { 12288 // A null pointer can be viewed as being "past the end" but we don't 12289 // choose to look at it that way here. 12290 if (!LV.getLValueBase()) 12291 return false; 12292 12293 // If the designator is valid and refers to a subobject, we're not pointing 12294 // past the end. 12295 if (!LV.getLValueDesignator().Invalid && 12296 !LV.getLValueDesignator().isOnePastTheEnd()) 12297 return false; 12298 12299 // A pointer to an incomplete type might be past-the-end if the type's size is 12300 // zero. We cannot tell because the type is incomplete. 12301 QualType Ty = getType(LV.getLValueBase()); 12302 if (Ty->isIncompleteType()) 12303 return true; 12304 12305 // We're a past-the-end pointer if we point to the byte after the object, 12306 // no matter what our type or path is. 12307 auto Size = Ctx.getTypeSizeInChars(Ty); 12308 return LV.getLValueOffset() == Size; 12309 } 12310 12311 namespace { 12312 12313 /// Data recursive integer evaluator of certain binary operators. 12314 /// 12315 /// We use a data recursive algorithm for binary operators so that we are able 12316 /// to handle extreme cases of chained binary operators without causing stack 12317 /// overflow. 12318 class DataRecursiveIntBinOpEvaluator { 12319 struct EvalResult { 12320 APValue Val; 12321 bool Failed; 12322 12323 EvalResult() : Failed(false) { } 12324 12325 void swap(EvalResult &RHS) { 12326 Val.swap(RHS.Val); 12327 Failed = RHS.Failed; 12328 RHS.Failed = false; 12329 } 12330 }; 12331 12332 struct Job { 12333 const Expr *E; 12334 EvalResult LHSResult; // meaningful only for binary operator expression. 12335 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12336 12337 Job() = default; 12338 Job(Job &&) = default; 12339 12340 void startSpeculativeEval(EvalInfo &Info) { 12341 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12342 } 12343 12344 private: 12345 SpeculativeEvaluationRAII SpecEvalRAII; 12346 }; 12347 12348 SmallVector<Job, 16> Queue; 12349 12350 IntExprEvaluator &IntEval; 12351 EvalInfo &Info; 12352 APValue &FinalResult; 12353 12354 public: 12355 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12356 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12357 12358 /// True if \param E is a binary operator that we are going to handle 12359 /// data recursively. 12360 /// We handle binary operators that are comma, logical, or that have operands 12361 /// with integral or enumeration type. 12362 static bool shouldEnqueue(const BinaryOperator *E) { 12363 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12364 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12365 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12366 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12367 } 12368 12369 bool Traverse(const BinaryOperator *E) { 12370 enqueue(E); 12371 EvalResult PrevResult; 12372 while (!Queue.empty()) 12373 process(PrevResult); 12374 12375 if (PrevResult.Failed) return false; 12376 12377 FinalResult.swap(PrevResult.Val); 12378 return true; 12379 } 12380 12381 private: 12382 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12383 return IntEval.Success(Value, E, Result); 12384 } 12385 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12386 return IntEval.Success(Value, E, Result); 12387 } 12388 bool Error(const Expr *E) { 12389 return IntEval.Error(E); 12390 } 12391 bool Error(const Expr *E, diag::kind D) { 12392 return IntEval.Error(E, D); 12393 } 12394 12395 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12396 return Info.CCEDiag(E, D); 12397 } 12398 12399 // Returns true if visiting the RHS is necessary, false otherwise. 12400 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12401 bool &SuppressRHSDiags); 12402 12403 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12404 const BinaryOperator *E, APValue &Result); 12405 12406 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12407 Result.Failed = !Evaluate(Result.Val, Info, E); 12408 if (Result.Failed) 12409 Result.Val = APValue(); 12410 } 12411 12412 void process(EvalResult &Result); 12413 12414 void enqueue(const Expr *E) { 12415 E = E->IgnoreParens(); 12416 Queue.resize(Queue.size()+1); 12417 Queue.back().E = E; 12418 Queue.back().Kind = Job::AnyExprKind; 12419 } 12420 }; 12421 12422 } 12423 12424 bool DataRecursiveIntBinOpEvaluator:: 12425 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12426 bool &SuppressRHSDiags) { 12427 if (E->getOpcode() == BO_Comma) { 12428 // Ignore LHS but note if we could not evaluate it. 12429 if (LHSResult.Failed) 12430 return Info.noteSideEffect(); 12431 return true; 12432 } 12433 12434 if (E->isLogicalOp()) { 12435 bool LHSAsBool; 12436 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12437 // We were able to evaluate the LHS, see if we can get away with not 12438 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12439 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12440 Success(LHSAsBool, E, LHSResult.Val); 12441 return false; // Ignore RHS 12442 } 12443 } else { 12444 LHSResult.Failed = true; 12445 12446 // Since we weren't able to evaluate the left hand side, it 12447 // might have had side effects. 12448 if (!Info.noteSideEffect()) 12449 return false; 12450 12451 // We can't evaluate the LHS; however, sometimes the result 12452 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12453 // Don't ignore RHS and suppress diagnostics from this arm. 12454 SuppressRHSDiags = true; 12455 } 12456 12457 return true; 12458 } 12459 12460 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12461 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12462 12463 if (LHSResult.Failed && !Info.noteFailure()) 12464 return false; // Ignore RHS; 12465 12466 return true; 12467 } 12468 12469 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12470 bool IsSub) { 12471 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12472 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12473 // offsets. 12474 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12475 CharUnits &Offset = LVal.getLValueOffset(); 12476 uint64_t Offset64 = Offset.getQuantity(); 12477 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12478 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12479 : Offset64 + Index64); 12480 } 12481 12482 bool DataRecursiveIntBinOpEvaluator:: 12483 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12484 const BinaryOperator *E, APValue &Result) { 12485 if (E->getOpcode() == BO_Comma) { 12486 if (RHSResult.Failed) 12487 return false; 12488 Result = RHSResult.Val; 12489 return true; 12490 } 12491 12492 if (E->isLogicalOp()) { 12493 bool lhsResult, rhsResult; 12494 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12495 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12496 12497 if (LHSIsOK) { 12498 if (RHSIsOK) { 12499 if (E->getOpcode() == BO_LOr) 12500 return Success(lhsResult || rhsResult, E, Result); 12501 else 12502 return Success(lhsResult && rhsResult, E, Result); 12503 } 12504 } else { 12505 if (RHSIsOK) { 12506 // We can't evaluate the LHS; however, sometimes the result 12507 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12508 if (rhsResult == (E->getOpcode() == BO_LOr)) 12509 return Success(rhsResult, E, Result); 12510 } 12511 } 12512 12513 return false; 12514 } 12515 12516 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12517 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12518 12519 if (LHSResult.Failed || RHSResult.Failed) 12520 return false; 12521 12522 const APValue &LHSVal = LHSResult.Val; 12523 const APValue &RHSVal = RHSResult.Val; 12524 12525 // Handle cases like (unsigned long)&a + 4. 12526 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12527 Result = LHSVal; 12528 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12529 return true; 12530 } 12531 12532 // Handle cases like 4 + (unsigned long)&a 12533 if (E->getOpcode() == BO_Add && 12534 RHSVal.isLValue() && LHSVal.isInt()) { 12535 Result = RHSVal; 12536 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12537 return true; 12538 } 12539 12540 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12541 // Handle (intptr_t)&&A - (intptr_t)&&B. 12542 if (!LHSVal.getLValueOffset().isZero() || 12543 !RHSVal.getLValueOffset().isZero()) 12544 return false; 12545 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12546 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12547 if (!LHSExpr || !RHSExpr) 12548 return false; 12549 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12550 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12551 if (!LHSAddrExpr || !RHSAddrExpr) 12552 return false; 12553 // Make sure both labels come from the same function. 12554 if (LHSAddrExpr->getLabel()->getDeclContext() != 12555 RHSAddrExpr->getLabel()->getDeclContext()) 12556 return false; 12557 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12558 return true; 12559 } 12560 12561 // All the remaining cases expect both operands to be an integer 12562 if (!LHSVal.isInt() || !RHSVal.isInt()) 12563 return Error(E); 12564 12565 // Set up the width and signedness manually, in case it can't be deduced 12566 // from the operation we're performing. 12567 // FIXME: Don't do this in the cases where we can deduce it. 12568 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12569 E->getType()->isUnsignedIntegerOrEnumerationType()); 12570 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12571 RHSVal.getInt(), Value)) 12572 return false; 12573 return Success(Value, E, Result); 12574 } 12575 12576 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12577 Job &job = Queue.back(); 12578 12579 switch (job.Kind) { 12580 case Job::AnyExprKind: { 12581 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12582 if (shouldEnqueue(Bop)) { 12583 job.Kind = Job::BinOpKind; 12584 enqueue(Bop->getLHS()); 12585 return; 12586 } 12587 } 12588 12589 EvaluateExpr(job.E, Result); 12590 Queue.pop_back(); 12591 return; 12592 } 12593 12594 case Job::BinOpKind: { 12595 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12596 bool SuppressRHSDiags = false; 12597 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12598 Queue.pop_back(); 12599 return; 12600 } 12601 if (SuppressRHSDiags) 12602 job.startSpeculativeEval(Info); 12603 job.LHSResult.swap(Result); 12604 job.Kind = Job::BinOpVisitedLHSKind; 12605 enqueue(Bop->getRHS()); 12606 return; 12607 } 12608 12609 case Job::BinOpVisitedLHSKind: { 12610 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12611 EvalResult RHS; 12612 RHS.swap(Result); 12613 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12614 Queue.pop_back(); 12615 return; 12616 } 12617 } 12618 12619 llvm_unreachable("Invalid Job::Kind!"); 12620 } 12621 12622 namespace { 12623 enum class CmpResult { 12624 Unequal, 12625 Less, 12626 Equal, 12627 Greater, 12628 Unordered, 12629 }; 12630 } 12631 12632 template <class SuccessCB, class AfterCB> 12633 static bool 12634 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12635 SuccessCB &&Success, AfterCB &&DoAfter) { 12636 assert(!E->isValueDependent()); 12637 assert(E->isComparisonOp() && "expected comparison operator"); 12638 assert((E->getOpcode() == BO_Cmp || 12639 E->getType()->isIntegralOrEnumerationType()) && 12640 "unsupported binary expression evaluation"); 12641 auto Error = [&](const Expr *E) { 12642 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12643 return false; 12644 }; 12645 12646 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12647 bool IsEquality = E->isEqualityOp(); 12648 12649 QualType LHSTy = E->getLHS()->getType(); 12650 QualType RHSTy = E->getRHS()->getType(); 12651 12652 if (LHSTy->isIntegralOrEnumerationType() && 12653 RHSTy->isIntegralOrEnumerationType()) { 12654 APSInt LHS, RHS; 12655 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12656 if (!LHSOK && !Info.noteFailure()) 12657 return false; 12658 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12659 return false; 12660 if (LHS < RHS) 12661 return Success(CmpResult::Less, E); 12662 if (LHS > RHS) 12663 return Success(CmpResult::Greater, E); 12664 return Success(CmpResult::Equal, E); 12665 } 12666 12667 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12668 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12669 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12670 12671 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12672 if (!LHSOK && !Info.noteFailure()) 12673 return false; 12674 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12675 return false; 12676 if (LHSFX < RHSFX) 12677 return Success(CmpResult::Less, E); 12678 if (LHSFX > RHSFX) 12679 return Success(CmpResult::Greater, E); 12680 return Success(CmpResult::Equal, E); 12681 } 12682 12683 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12684 ComplexValue LHS, RHS; 12685 bool LHSOK; 12686 if (E->isAssignmentOp()) { 12687 LValue LV; 12688 EvaluateLValue(E->getLHS(), LV, Info); 12689 LHSOK = false; 12690 } else if (LHSTy->isRealFloatingType()) { 12691 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12692 if (LHSOK) { 12693 LHS.makeComplexFloat(); 12694 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12695 } 12696 } else { 12697 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12698 } 12699 if (!LHSOK && !Info.noteFailure()) 12700 return false; 12701 12702 if (E->getRHS()->getType()->isRealFloatingType()) { 12703 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12704 return false; 12705 RHS.makeComplexFloat(); 12706 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12707 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12708 return false; 12709 12710 if (LHS.isComplexFloat()) { 12711 APFloat::cmpResult CR_r = 12712 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12713 APFloat::cmpResult CR_i = 12714 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12715 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12716 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12717 } else { 12718 assert(IsEquality && "invalid complex comparison"); 12719 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12720 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12721 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12722 } 12723 } 12724 12725 if (LHSTy->isRealFloatingType() && 12726 RHSTy->isRealFloatingType()) { 12727 APFloat RHS(0.0), LHS(0.0); 12728 12729 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12730 if (!LHSOK && !Info.noteFailure()) 12731 return false; 12732 12733 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12734 return false; 12735 12736 assert(E->isComparisonOp() && "Invalid binary operator!"); 12737 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12738 if (!Info.InConstantContext && 12739 APFloatCmpResult == APFloat::cmpUnordered && 12740 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12741 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12742 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12743 return false; 12744 } 12745 auto GetCmpRes = [&]() { 12746 switch (APFloatCmpResult) { 12747 case APFloat::cmpEqual: 12748 return CmpResult::Equal; 12749 case APFloat::cmpLessThan: 12750 return CmpResult::Less; 12751 case APFloat::cmpGreaterThan: 12752 return CmpResult::Greater; 12753 case APFloat::cmpUnordered: 12754 return CmpResult::Unordered; 12755 } 12756 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12757 }; 12758 return Success(GetCmpRes(), E); 12759 } 12760 12761 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12762 LValue LHSValue, RHSValue; 12763 12764 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12765 if (!LHSOK && !Info.noteFailure()) 12766 return false; 12767 12768 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12769 return false; 12770 12771 // Reject differing bases from the normal codepath; we special-case 12772 // comparisons to null. 12773 if (!HasSameBase(LHSValue, RHSValue)) { 12774 // Inequalities and subtractions between unrelated pointers have 12775 // unspecified or undefined behavior. 12776 if (!IsEquality) { 12777 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12778 return false; 12779 } 12780 // A constant address may compare equal to the address of a symbol. 12781 // The one exception is that address of an object cannot compare equal 12782 // to a null pointer constant. 12783 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12784 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12785 return Error(E); 12786 // It's implementation-defined whether distinct literals will have 12787 // distinct addresses. In clang, the result of such a comparison is 12788 // unspecified, so it is not a constant expression. However, we do know 12789 // that the address of a literal will be non-null. 12790 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12791 LHSValue.Base && RHSValue.Base) 12792 return Error(E); 12793 // We can't tell whether weak symbols will end up pointing to the same 12794 // object. 12795 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12796 return Error(E); 12797 // We can't compare the address of the start of one object with the 12798 // past-the-end address of another object, per C++ DR1652. 12799 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12800 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12801 (RHSValue.Base && RHSValue.Offset.isZero() && 12802 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12803 return Error(E); 12804 // We can't tell whether an object is at the same address as another 12805 // zero sized object. 12806 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12807 (LHSValue.Base && isZeroSized(RHSValue))) 12808 return Error(E); 12809 return Success(CmpResult::Unequal, E); 12810 } 12811 12812 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12813 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12814 12815 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12816 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12817 12818 // C++11 [expr.rel]p3: 12819 // Pointers to void (after pointer conversions) can be compared, with a 12820 // result defined as follows: If both pointers represent the same 12821 // address or are both the null pointer value, the result is true if the 12822 // operator is <= or >= and false otherwise; otherwise the result is 12823 // unspecified. 12824 // We interpret this as applying to pointers to *cv* void. 12825 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12826 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12827 12828 // C++11 [expr.rel]p2: 12829 // - If two pointers point to non-static data members of the same object, 12830 // or to subobjects or array elements fo such members, recursively, the 12831 // pointer to the later declared member compares greater provided the 12832 // two members have the same access control and provided their class is 12833 // not a union. 12834 // [...] 12835 // - Otherwise pointer comparisons are unspecified. 12836 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12837 bool WasArrayIndex; 12838 unsigned Mismatch = FindDesignatorMismatch( 12839 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12840 // At the point where the designators diverge, the comparison has a 12841 // specified value if: 12842 // - we are comparing array indices 12843 // - we are comparing fields of a union, or fields with the same access 12844 // Otherwise, the result is unspecified and thus the comparison is not a 12845 // constant expression. 12846 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12847 Mismatch < RHSDesignator.Entries.size()) { 12848 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12849 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12850 if (!LF && !RF) 12851 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12852 else if (!LF) 12853 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12854 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12855 << RF->getParent() << RF; 12856 else if (!RF) 12857 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12858 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12859 << LF->getParent() << LF; 12860 else if (!LF->getParent()->isUnion() && 12861 LF->getAccess() != RF->getAccess()) 12862 Info.CCEDiag(E, 12863 diag::note_constexpr_pointer_comparison_differing_access) 12864 << LF << LF->getAccess() << RF << RF->getAccess() 12865 << LF->getParent(); 12866 } 12867 } 12868 12869 // The comparison here must be unsigned, and performed with the same 12870 // width as the pointer. 12871 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12872 uint64_t CompareLHS = LHSOffset.getQuantity(); 12873 uint64_t CompareRHS = RHSOffset.getQuantity(); 12874 assert(PtrSize <= 64 && "Unexpected pointer width"); 12875 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12876 CompareLHS &= Mask; 12877 CompareRHS &= Mask; 12878 12879 // If there is a base and this is a relational operator, we can only 12880 // compare pointers within the object in question; otherwise, the result 12881 // depends on where the object is located in memory. 12882 if (!LHSValue.Base.isNull() && IsRelational) { 12883 QualType BaseTy = getType(LHSValue.Base); 12884 if (BaseTy->isIncompleteType()) 12885 return Error(E); 12886 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12887 uint64_t OffsetLimit = Size.getQuantity(); 12888 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12889 return Error(E); 12890 } 12891 12892 if (CompareLHS < CompareRHS) 12893 return Success(CmpResult::Less, E); 12894 if (CompareLHS > CompareRHS) 12895 return Success(CmpResult::Greater, E); 12896 return Success(CmpResult::Equal, E); 12897 } 12898 12899 if (LHSTy->isMemberPointerType()) { 12900 assert(IsEquality && "unexpected member pointer operation"); 12901 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12902 12903 MemberPtr LHSValue, RHSValue; 12904 12905 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12906 if (!LHSOK && !Info.noteFailure()) 12907 return false; 12908 12909 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12910 return false; 12911 12912 // C++11 [expr.eq]p2: 12913 // If both operands are null, they compare equal. Otherwise if only one is 12914 // null, they compare unequal. 12915 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12916 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12917 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12918 } 12919 12920 // Otherwise if either is a pointer to a virtual member function, the 12921 // result is unspecified. 12922 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12923 if (MD->isVirtual()) 12924 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12925 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12926 if (MD->isVirtual()) 12927 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12928 12929 // Otherwise they compare equal if and only if they would refer to the 12930 // same member of the same most derived object or the same subobject if 12931 // they were dereferenced with a hypothetical object of the associated 12932 // class type. 12933 bool Equal = LHSValue == RHSValue; 12934 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12935 } 12936 12937 if (LHSTy->isNullPtrType()) { 12938 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12939 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12940 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12941 // are compared, the result is true of the operator is <=, >= or ==, and 12942 // false otherwise. 12943 return Success(CmpResult::Equal, E); 12944 } 12945 12946 return DoAfter(); 12947 } 12948 12949 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12950 if (!CheckLiteralType(Info, E)) 12951 return false; 12952 12953 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12954 ComparisonCategoryResult CCR; 12955 switch (CR) { 12956 case CmpResult::Unequal: 12957 llvm_unreachable("should never produce Unequal for three-way comparison"); 12958 case CmpResult::Less: 12959 CCR = ComparisonCategoryResult::Less; 12960 break; 12961 case CmpResult::Equal: 12962 CCR = ComparisonCategoryResult::Equal; 12963 break; 12964 case CmpResult::Greater: 12965 CCR = ComparisonCategoryResult::Greater; 12966 break; 12967 case CmpResult::Unordered: 12968 CCR = ComparisonCategoryResult::Unordered; 12969 break; 12970 } 12971 // Evaluation succeeded. Lookup the information for the comparison category 12972 // type and fetch the VarDecl for the result. 12973 const ComparisonCategoryInfo &CmpInfo = 12974 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12975 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12976 // Check and evaluate the result as a constant expression. 12977 LValue LV; 12978 LV.set(VD); 12979 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12980 return false; 12981 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12982 ConstantExprKind::Normal); 12983 }; 12984 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12985 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12986 }); 12987 } 12988 12989 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12990 // We don't support assignment in C. C++ assignments don't get here because 12991 // assignment is an lvalue in C++. 12992 if (E->isAssignmentOp()) { 12993 Error(E); 12994 if (!Info.noteFailure()) 12995 return false; 12996 } 12997 12998 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12999 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 13000 13001 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 13002 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 13003 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 13004 13005 if (E->isComparisonOp()) { 13006 // Evaluate builtin binary comparisons by evaluating them as three-way 13007 // comparisons and then translating the result. 13008 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13009 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 13010 "should only produce Unequal for equality comparisons"); 13011 bool IsEqual = CR == CmpResult::Equal, 13012 IsLess = CR == CmpResult::Less, 13013 IsGreater = CR == CmpResult::Greater; 13014 auto Op = E->getOpcode(); 13015 switch (Op) { 13016 default: 13017 llvm_unreachable("unsupported binary operator"); 13018 case BO_EQ: 13019 case BO_NE: 13020 return Success(IsEqual == (Op == BO_EQ), E); 13021 case BO_LT: 13022 return Success(IsLess, E); 13023 case BO_GT: 13024 return Success(IsGreater, E); 13025 case BO_LE: 13026 return Success(IsEqual || IsLess, E); 13027 case BO_GE: 13028 return Success(IsEqual || IsGreater, E); 13029 } 13030 }; 13031 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13032 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13033 }); 13034 } 13035 13036 QualType LHSTy = E->getLHS()->getType(); 13037 QualType RHSTy = E->getRHS()->getType(); 13038 13039 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 13040 E->getOpcode() == BO_Sub) { 13041 LValue LHSValue, RHSValue; 13042 13043 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13044 if (!LHSOK && !Info.noteFailure()) 13045 return false; 13046 13047 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13048 return false; 13049 13050 // Reject differing bases from the normal codepath; we special-case 13051 // comparisons to null. 13052 if (!HasSameBase(LHSValue, RHSValue)) { 13053 // Handle &&A - &&B. 13054 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 13055 return Error(E); 13056 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 13057 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 13058 if (!LHSExpr || !RHSExpr) 13059 return Error(E); 13060 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13061 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13062 if (!LHSAddrExpr || !RHSAddrExpr) 13063 return Error(E); 13064 // Make sure both labels come from the same function. 13065 if (LHSAddrExpr->getLabel()->getDeclContext() != 13066 RHSAddrExpr->getLabel()->getDeclContext()) 13067 return Error(E); 13068 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 13069 } 13070 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13071 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13072 13073 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13074 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13075 13076 // C++11 [expr.add]p6: 13077 // Unless both pointers point to elements of the same array object, or 13078 // one past the last element of the array object, the behavior is 13079 // undefined. 13080 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 13081 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 13082 RHSDesignator)) 13083 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 13084 13085 QualType Type = E->getLHS()->getType(); 13086 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 13087 13088 CharUnits ElementSize; 13089 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 13090 return false; 13091 13092 // As an extension, a type may have zero size (empty struct or union in 13093 // C, array of zero length). Pointer subtraction in such cases has 13094 // undefined behavior, so is not constant. 13095 if (ElementSize.isZero()) { 13096 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 13097 << ElementType; 13098 return false; 13099 } 13100 13101 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 13102 // and produce incorrect results when it overflows. Such behavior 13103 // appears to be non-conforming, but is common, so perhaps we should 13104 // assume the standard intended for such cases to be undefined behavior 13105 // and check for them. 13106 13107 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 13108 // overflow in the final conversion to ptrdiff_t. 13109 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 13110 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 13111 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 13112 false); 13113 APSInt TrueResult = (LHS - RHS) / ElemSize; 13114 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 13115 13116 if (Result.extend(65) != TrueResult && 13117 !HandleOverflow(Info, E, TrueResult, E->getType())) 13118 return false; 13119 return Success(Result, E); 13120 } 13121 13122 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13123 } 13124 13125 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 13126 /// a result as the expression's type. 13127 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13128 const UnaryExprOrTypeTraitExpr *E) { 13129 switch(E->getKind()) { 13130 case UETT_PreferredAlignOf: 13131 case UETT_AlignOf: { 13132 if (E->isArgumentType()) 13133 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13134 E); 13135 else 13136 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13137 E); 13138 } 13139 13140 case UETT_VecStep: { 13141 QualType Ty = E->getTypeOfArgument(); 13142 13143 if (Ty->isVectorType()) { 13144 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13145 13146 // The vec_step built-in functions that take a 3-component 13147 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13148 if (n == 3) 13149 n = 4; 13150 13151 return Success(n, E); 13152 } else 13153 return Success(1, E); 13154 } 13155 13156 case UETT_SizeOf: { 13157 QualType SrcTy = E->getTypeOfArgument(); 13158 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13159 // the result is the size of the referenced type." 13160 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13161 SrcTy = Ref->getPointeeType(); 13162 13163 CharUnits Sizeof; 13164 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13165 return false; 13166 return Success(Sizeof, E); 13167 } 13168 case UETT_OpenMPRequiredSimdAlign: 13169 assert(E->isArgumentType()); 13170 return Success( 13171 Info.Ctx.toCharUnitsFromBits( 13172 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13173 .getQuantity(), 13174 E); 13175 } 13176 13177 llvm_unreachable("unknown expr/type trait"); 13178 } 13179 13180 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13181 CharUnits Result; 13182 unsigned n = OOE->getNumComponents(); 13183 if (n == 0) 13184 return Error(OOE); 13185 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13186 for (unsigned i = 0; i != n; ++i) { 13187 OffsetOfNode ON = OOE->getComponent(i); 13188 switch (ON.getKind()) { 13189 case OffsetOfNode::Array: { 13190 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13191 APSInt IdxResult; 13192 if (!EvaluateInteger(Idx, IdxResult, Info)) 13193 return false; 13194 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13195 if (!AT) 13196 return Error(OOE); 13197 CurrentType = AT->getElementType(); 13198 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13199 Result += IdxResult.getSExtValue() * ElementSize; 13200 break; 13201 } 13202 13203 case OffsetOfNode::Field: { 13204 FieldDecl *MemberDecl = ON.getField(); 13205 const RecordType *RT = CurrentType->getAs<RecordType>(); 13206 if (!RT) 13207 return Error(OOE); 13208 RecordDecl *RD = RT->getDecl(); 13209 if (RD->isInvalidDecl()) return false; 13210 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13211 unsigned i = MemberDecl->getFieldIndex(); 13212 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13213 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13214 CurrentType = MemberDecl->getType().getNonReferenceType(); 13215 break; 13216 } 13217 13218 case OffsetOfNode::Identifier: 13219 llvm_unreachable("dependent __builtin_offsetof"); 13220 13221 case OffsetOfNode::Base: { 13222 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13223 if (BaseSpec->isVirtual()) 13224 return Error(OOE); 13225 13226 // Find the layout of the class whose base we are looking into. 13227 const RecordType *RT = CurrentType->getAs<RecordType>(); 13228 if (!RT) 13229 return Error(OOE); 13230 RecordDecl *RD = RT->getDecl(); 13231 if (RD->isInvalidDecl()) return false; 13232 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13233 13234 // Find the base class itself. 13235 CurrentType = BaseSpec->getType(); 13236 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13237 if (!BaseRT) 13238 return Error(OOE); 13239 13240 // Add the offset to the base. 13241 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13242 break; 13243 } 13244 } 13245 } 13246 return Success(Result, OOE); 13247 } 13248 13249 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13250 switch (E->getOpcode()) { 13251 default: 13252 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13253 // See C99 6.6p3. 13254 return Error(E); 13255 case UO_Extension: 13256 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13257 // If so, we could clear the diagnostic ID. 13258 return Visit(E->getSubExpr()); 13259 case UO_Plus: 13260 // The result is just the value. 13261 return Visit(E->getSubExpr()); 13262 case UO_Minus: { 13263 if (!Visit(E->getSubExpr())) 13264 return false; 13265 if (!Result.isInt()) return Error(E); 13266 const APSInt &Value = Result.getInt(); 13267 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13268 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13269 E->getType())) 13270 return false; 13271 return Success(-Value, E); 13272 } 13273 case UO_Not: { 13274 if (!Visit(E->getSubExpr())) 13275 return false; 13276 if (!Result.isInt()) return Error(E); 13277 return Success(~Result.getInt(), E); 13278 } 13279 case UO_LNot: { 13280 bool bres; 13281 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13282 return false; 13283 return Success(!bres, E); 13284 } 13285 } 13286 } 13287 13288 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13289 /// result type is integer. 13290 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13291 const Expr *SubExpr = E->getSubExpr(); 13292 QualType DestType = E->getType(); 13293 QualType SrcType = SubExpr->getType(); 13294 13295 switch (E->getCastKind()) { 13296 case CK_BaseToDerived: 13297 case CK_DerivedToBase: 13298 case CK_UncheckedDerivedToBase: 13299 case CK_Dynamic: 13300 case CK_ToUnion: 13301 case CK_ArrayToPointerDecay: 13302 case CK_FunctionToPointerDecay: 13303 case CK_NullToPointer: 13304 case CK_NullToMemberPointer: 13305 case CK_BaseToDerivedMemberPointer: 13306 case CK_DerivedToBaseMemberPointer: 13307 case CK_ReinterpretMemberPointer: 13308 case CK_ConstructorConversion: 13309 case CK_IntegralToPointer: 13310 case CK_ToVoid: 13311 case CK_VectorSplat: 13312 case CK_IntegralToFloating: 13313 case CK_FloatingCast: 13314 case CK_CPointerToObjCPointerCast: 13315 case CK_BlockPointerToObjCPointerCast: 13316 case CK_AnyPointerToBlockPointerCast: 13317 case CK_ObjCObjectLValueCast: 13318 case CK_FloatingRealToComplex: 13319 case CK_FloatingComplexToReal: 13320 case CK_FloatingComplexCast: 13321 case CK_FloatingComplexToIntegralComplex: 13322 case CK_IntegralRealToComplex: 13323 case CK_IntegralComplexCast: 13324 case CK_IntegralComplexToFloatingComplex: 13325 case CK_BuiltinFnToFnPtr: 13326 case CK_ZeroToOCLOpaqueType: 13327 case CK_NonAtomicToAtomic: 13328 case CK_AddressSpaceConversion: 13329 case CK_IntToOCLSampler: 13330 case CK_FloatingToFixedPoint: 13331 case CK_FixedPointToFloating: 13332 case CK_FixedPointCast: 13333 case CK_IntegralToFixedPoint: 13334 case CK_MatrixCast: 13335 llvm_unreachable("invalid cast kind for integral value"); 13336 13337 case CK_BitCast: 13338 case CK_Dependent: 13339 case CK_LValueBitCast: 13340 case CK_ARCProduceObject: 13341 case CK_ARCConsumeObject: 13342 case CK_ARCReclaimReturnedObject: 13343 case CK_ARCExtendBlockObject: 13344 case CK_CopyAndAutoreleaseBlockObject: 13345 return Error(E); 13346 13347 case CK_UserDefinedConversion: 13348 case CK_LValueToRValue: 13349 case CK_AtomicToNonAtomic: 13350 case CK_NoOp: 13351 case CK_LValueToRValueBitCast: 13352 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13353 13354 case CK_MemberPointerToBoolean: 13355 case CK_PointerToBoolean: 13356 case CK_IntegralToBoolean: 13357 case CK_FloatingToBoolean: 13358 case CK_BooleanToSignedIntegral: 13359 case CK_FloatingComplexToBoolean: 13360 case CK_IntegralComplexToBoolean: { 13361 bool BoolResult; 13362 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13363 return false; 13364 uint64_t IntResult = BoolResult; 13365 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13366 IntResult = (uint64_t)-1; 13367 return Success(IntResult, E); 13368 } 13369 13370 case CK_FixedPointToIntegral: { 13371 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13372 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13373 return false; 13374 bool Overflowed; 13375 llvm::APSInt Result = Src.convertToInt( 13376 Info.Ctx.getIntWidth(DestType), 13377 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13378 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13379 return false; 13380 return Success(Result, E); 13381 } 13382 13383 case CK_FixedPointToBoolean: { 13384 // Unsigned padding does not affect this. 13385 APValue Val; 13386 if (!Evaluate(Val, Info, SubExpr)) 13387 return false; 13388 return Success(Val.getFixedPoint().getBoolValue(), E); 13389 } 13390 13391 case CK_IntegralCast: { 13392 if (!Visit(SubExpr)) 13393 return false; 13394 13395 if (!Result.isInt()) { 13396 // Allow casts of address-of-label differences if they are no-ops 13397 // or narrowing. (The narrowing case isn't actually guaranteed to 13398 // be constant-evaluatable except in some narrow cases which are hard 13399 // to detect here. We let it through on the assumption the user knows 13400 // what they are doing.) 13401 if (Result.isAddrLabelDiff()) 13402 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13403 // Only allow casts of lvalues if they are lossless. 13404 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13405 } 13406 13407 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13408 Result.getInt()), E); 13409 } 13410 13411 case CK_PointerToIntegral: { 13412 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13413 13414 LValue LV; 13415 if (!EvaluatePointer(SubExpr, LV, Info)) 13416 return false; 13417 13418 if (LV.getLValueBase()) { 13419 // Only allow based lvalue casts if they are lossless. 13420 // FIXME: Allow a larger integer size than the pointer size, and allow 13421 // narrowing back down to pointer width in subsequent integral casts. 13422 // FIXME: Check integer type's active bits, not its type size. 13423 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13424 return Error(E); 13425 13426 LV.Designator.setInvalid(); 13427 LV.moveInto(Result); 13428 return true; 13429 } 13430 13431 APSInt AsInt; 13432 APValue V; 13433 LV.moveInto(V); 13434 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13435 llvm_unreachable("Can't cast this!"); 13436 13437 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13438 } 13439 13440 case CK_IntegralComplexToReal: { 13441 ComplexValue C; 13442 if (!EvaluateComplex(SubExpr, C, Info)) 13443 return false; 13444 return Success(C.getComplexIntReal(), E); 13445 } 13446 13447 case CK_FloatingToIntegral: { 13448 APFloat F(0.0); 13449 if (!EvaluateFloat(SubExpr, F, Info)) 13450 return false; 13451 13452 APSInt Value; 13453 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13454 return false; 13455 return Success(Value, E); 13456 } 13457 } 13458 13459 llvm_unreachable("unknown cast resulting in integral value"); 13460 } 13461 13462 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13463 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13464 ComplexValue LV; 13465 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13466 return false; 13467 if (!LV.isComplexInt()) 13468 return Error(E); 13469 return Success(LV.getComplexIntReal(), E); 13470 } 13471 13472 return Visit(E->getSubExpr()); 13473 } 13474 13475 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13476 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13477 ComplexValue LV; 13478 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13479 return false; 13480 if (!LV.isComplexInt()) 13481 return Error(E); 13482 return Success(LV.getComplexIntImag(), E); 13483 } 13484 13485 VisitIgnoredValue(E->getSubExpr()); 13486 return Success(0, E); 13487 } 13488 13489 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13490 return Success(E->getPackLength(), E); 13491 } 13492 13493 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13494 return Success(E->getValue(), E); 13495 } 13496 13497 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13498 const ConceptSpecializationExpr *E) { 13499 return Success(E->isSatisfied(), E); 13500 } 13501 13502 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13503 return Success(E->isSatisfied(), E); 13504 } 13505 13506 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13507 switch (E->getOpcode()) { 13508 default: 13509 // Invalid unary operators 13510 return Error(E); 13511 case UO_Plus: 13512 // The result is just the value. 13513 return Visit(E->getSubExpr()); 13514 case UO_Minus: { 13515 if (!Visit(E->getSubExpr())) return false; 13516 if (!Result.isFixedPoint()) 13517 return Error(E); 13518 bool Overflowed; 13519 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13520 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13521 return false; 13522 return Success(Negated, E); 13523 } 13524 case UO_LNot: { 13525 bool bres; 13526 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13527 return false; 13528 return Success(!bres, E); 13529 } 13530 } 13531 } 13532 13533 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13534 const Expr *SubExpr = E->getSubExpr(); 13535 QualType DestType = E->getType(); 13536 assert(DestType->isFixedPointType() && 13537 "Expected destination type to be a fixed point type"); 13538 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13539 13540 switch (E->getCastKind()) { 13541 case CK_FixedPointCast: { 13542 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13543 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13544 return false; 13545 bool Overflowed; 13546 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13547 if (Overflowed) { 13548 if (Info.checkingForUndefinedBehavior()) 13549 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13550 diag::warn_fixedpoint_constant_overflow) 13551 << Result.toString() << E->getType(); 13552 if (!HandleOverflow(Info, E, Result, E->getType())) 13553 return false; 13554 } 13555 return Success(Result, E); 13556 } 13557 case CK_IntegralToFixedPoint: { 13558 APSInt Src; 13559 if (!EvaluateInteger(SubExpr, Src, Info)) 13560 return false; 13561 13562 bool Overflowed; 13563 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13564 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13565 13566 if (Overflowed) { 13567 if (Info.checkingForUndefinedBehavior()) 13568 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13569 diag::warn_fixedpoint_constant_overflow) 13570 << IntResult.toString() << E->getType(); 13571 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13572 return false; 13573 } 13574 13575 return Success(IntResult, E); 13576 } 13577 case CK_FloatingToFixedPoint: { 13578 APFloat Src(0.0); 13579 if (!EvaluateFloat(SubExpr, Src, Info)) 13580 return false; 13581 13582 bool Overflowed; 13583 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13584 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13585 13586 if (Overflowed) { 13587 if (Info.checkingForUndefinedBehavior()) 13588 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13589 diag::warn_fixedpoint_constant_overflow) 13590 << Result.toString() << E->getType(); 13591 if (!HandleOverflow(Info, E, Result, E->getType())) 13592 return false; 13593 } 13594 13595 return Success(Result, E); 13596 } 13597 case CK_NoOp: 13598 case CK_LValueToRValue: 13599 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13600 default: 13601 return Error(E); 13602 } 13603 } 13604 13605 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13606 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13607 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13608 13609 const Expr *LHS = E->getLHS(); 13610 const Expr *RHS = E->getRHS(); 13611 FixedPointSemantics ResultFXSema = 13612 Info.Ctx.getFixedPointSemantics(E->getType()); 13613 13614 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13615 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13616 return false; 13617 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13618 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13619 return false; 13620 13621 bool OpOverflow = false, ConversionOverflow = false; 13622 APFixedPoint Result(LHSFX.getSemantics()); 13623 switch (E->getOpcode()) { 13624 case BO_Add: { 13625 Result = LHSFX.add(RHSFX, &OpOverflow) 13626 .convert(ResultFXSema, &ConversionOverflow); 13627 break; 13628 } 13629 case BO_Sub: { 13630 Result = LHSFX.sub(RHSFX, &OpOverflow) 13631 .convert(ResultFXSema, &ConversionOverflow); 13632 break; 13633 } 13634 case BO_Mul: { 13635 Result = LHSFX.mul(RHSFX, &OpOverflow) 13636 .convert(ResultFXSema, &ConversionOverflow); 13637 break; 13638 } 13639 case BO_Div: { 13640 if (RHSFX.getValue() == 0) { 13641 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13642 return false; 13643 } 13644 Result = LHSFX.div(RHSFX, &OpOverflow) 13645 .convert(ResultFXSema, &ConversionOverflow); 13646 break; 13647 } 13648 case BO_Shl: 13649 case BO_Shr: { 13650 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13651 llvm::APSInt RHSVal = RHSFX.getValue(); 13652 13653 unsigned ShiftBW = 13654 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13655 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13656 // Embedded-C 4.1.6.2.2: 13657 // The right operand must be nonnegative and less than the total number 13658 // of (nonpadding) bits of the fixed-point operand ... 13659 if (RHSVal.isNegative()) 13660 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13661 else if (Amt != RHSVal) 13662 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13663 << RHSVal << E->getType() << ShiftBW; 13664 13665 if (E->getOpcode() == BO_Shl) 13666 Result = LHSFX.shl(Amt, &OpOverflow); 13667 else 13668 Result = LHSFX.shr(Amt, &OpOverflow); 13669 break; 13670 } 13671 default: 13672 return false; 13673 } 13674 if (OpOverflow || ConversionOverflow) { 13675 if (Info.checkingForUndefinedBehavior()) 13676 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13677 diag::warn_fixedpoint_constant_overflow) 13678 << Result.toString() << E->getType(); 13679 if (!HandleOverflow(Info, E, Result, E->getType())) 13680 return false; 13681 } 13682 return Success(Result, E); 13683 } 13684 13685 //===----------------------------------------------------------------------===// 13686 // Float Evaluation 13687 //===----------------------------------------------------------------------===// 13688 13689 namespace { 13690 class FloatExprEvaluator 13691 : public ExprEvaluatorBase<FloatExprEvaluator> { 13692 APFloat &Result; 13693 public: 13694 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13695 : ExprEvaluatorBaseTy(info), Result(result) {} 13696 13697 bool Success(const APValue &V, const Expr *e) { 13698 Result = V.getFloat(); 13699 return true; 13700 } 13701 13702 bool ZeroInitialization(const Expr *E) { 13703 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13704 return true; 13705 } 13706 13707 bool VisitCallExpr(const CallExpr *E); 13708 13709 bool VisitUnaryOperator(const UnaryOperator *E); 13710 bool VisitBinaryOperator(const BinaryOperator *E); 13711 bool VisitFloatingLiteral(const FloatingLiteral *E); 13712 bool VisitCastExpr(const CastExpr *E); 13713 13714 bool VisitUnaryReal(const UnaryOperator *E); 13715 bool VisitUnaryImag(const UnaryOperator *E); 13716 13717 // FIXME: Missing: array subscript of vector, member of vector 13718 }; 13719 } // end anonymous namespace 13720 13721 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13722 assert(!E->isValueDependent()); 13723 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 13724 return FloatExprEvaluator(Info, Result).Visit(E); 13725 } 13726 13727 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13728 QualType ResultTy, 13729 const Expr *Arg, 13730 bool SNaN, 13731 llvm::APFloat &Result) { 13732 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13733 if (!S) return false; 13734 13735 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13736 13737 llvm::APInt fill; 13738 13739 // Treat empty strings as if they were zero. 13740 if (S->getString().empty()) 13741 fill = llvm::APInt(32, 0); 13742 else if (S->getString().getAsInteger(0, fill)) 13743 return false; 13744 13745 if (Context.getTargetInfo().isNan2008()) { 13746 if (SNaN) 13747 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13748 else 13749 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13750 } else { 13751 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13752 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13753 // a different encoding to what became a standard in 2008, and for pre- 13754 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13755 // sNaN. This is now known as "legacy NaN" encoding. 13756 if (SNaN) 13757 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13758 else 13759 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13760 } 13761 13762 return true; 13763 } 13764 13765 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13766 switch (E->getBuiltinCallee()) { 13767 default: 13768 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13769 13770 case Builtin::BI__builtin_huge_val: 13771 case Builtin::BI__builtin_huge_valf: 13772 case Builtin::BI__builtin_huge_vall: 13773 case Builtin::BI__builtin_huge_valf128: 13774 case Builtin::BI__builtin_inf: 13775 case Builtin::BI__builtin_inff: 13776 case Builtin::BI__builtin_infl: 13777 case Builtin::BI__builtin_inff128: { 13778 const llvm::fltSemantics &Sem = 13779 Info.Ctx.getFloatTypeSemantics(E->getType()); 13780 Result = llvm::APFloat::getInf(Sem); 13781 return true; 13782 } 13783 13784 case Builtin::BI__builtin_nans: 13785 case Builtin::BI__builtin_nansf: 13786 case Builtin::BI__builtin_nansl: 13787 case Builtin::BI__builtin_nansf128: 13788 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13789 true, Result)) 13790 return Error(E); 13791 return true; 13792 13793 case Builtin::BI__builtin_nan: 13794 case Builtin::BI__builtin_nanf: 13795 case Builtin::BI__builtin_nanl: 13796 case Builtin::BI__builtin_nanf128: 13797 // If this is __builtin_nan() turn this into a nan, otherwise we 13798 // can't constant fold it. 13799 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13800 false, Result)) 13801 return Error(E); 13802 return true; 13803 13804 case Builtin::BI__builtin_fabs: 13805 case Builtin::BI__builtin_fabsf: 13806 case Builtin::BI__builtin_fabsl: 13807 case Builtin::BI__builtin_fabsf128: 13808 // The C standard says "fabs raises no floating-point exceptions, 13809 // even if x is a signaling NaN. The returned value is independent of 13810 // the current rounding direction mode." Therefore constant folding can 13811 // proceed without regard to the floating point settings. 13812 // Reference, WG14 N2478 F.10.4.3 13813 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13814 return false; 13815 13816 if (Result.isNegative()) 13817 Result.changeSign(); 13818 return true; 13819 13820 case Builtin::BI__arithmetic_fence: 13821 return EvaluateFloat(E->getArg(0), Result, Info); 13822 13823 // FIXME: Builtin::BI__builtin_powi 13824 // FIXME: Builtin::BI__builtin_powif 13825 // FIXME: Builtin::BI__builtin_powil 13826 13827 case Builtin::BI__builtin_copysign: 13828 case Builtin::BI__builtin_copysignf: 13829 case Builtin::BI__builtin_copysignl: 13830 case Builtin::BI__builtin_copysignf128: { 13831 APFloat RHS(0.); 13832 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13833 !EvaluateFloat(E->getArg(1), RHS, Info)) 13834 return false; 13835 Result.copySign(RHS); 13836 return true; 13837 } 13838 } 13839 } 13840 13841 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13842 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13843 ComplexValue CV; 13844 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13845 return false; 13846 Result = CV.FloatReal; 13847 return true; 13848 } 13849 13850 return Visit(E->getSubExpr()); 13851 } 13852 13853 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13854 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13855 ComplexValue CV; 13856 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13857 return false; 13858 Result = CV.FloatImag; 13859 return true; 13860 } 13861 13862 VisitIgnoredValue(E->getSubExpr()); 13863 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13864 Result = llvm::APFloat::getZero(Sem); 13865 return true; 13866 } 13867 13868 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13869 switch (E->getOpcode()) { 13870 default: return Error(E); 13871 case UO_Plus: 13872 return EvaluateFloat(E->getSubExpr(), Result, Info); 13873 case UO_Minus: 13874 // In C standard, WG14 N2478 F.3 p4 13875 // "the unary - raises no floating point exceptions, 13876 // even if the operand is signalling." 13877 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13878 return false; 13879 Result.changeSign(); 13880 return true; 13881 } 13882 } 13883 13884 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13885 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13886 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13887 13888 APFloat RHS(0.0); 13889 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13890 if (!LHSOK && !Info.noteFailure()) 13891 return false; 13892 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13893 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13894 } 13895 13896 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13897 Result = E->getValue(); 13898 return true; 13899 } 13900 13901 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13902 const Expr* SubExpr = E->getSubExpr(); 13903 13904 switch (E->getCastKind()) { 13905 default: 13906 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13907 13908 case CK_IntegralToFloating: { 13909 APSInt IntResult; 13910 const FPOptions FPO = E->getFPFeaturesInEffect( 13911 Info.Ctx.getLangOpts()); 13912 return EvaluateInteger(SubExpr, IntResult, Info) && 13913 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13914 IntResult, E->getType(), Result); 13915 } 13916 13917 case CK_FixedPointToFloating: { 13918 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13919 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13920 return false; 13921 Result = 13922 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13923 return true; 13924 } 13925 13926 case CK_FloatingCast: { 13927 if (!Visit(SubExpr)) 13928 return false; 13929 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13930 Result); 13931 } 13932 13933 case CK_FloatingComplexToReal: { 13934 ComplexValue V; 13935 if (!EvaluateComplex(SubExpr, V, Info)) 13936 return false; 13937 Result = V.getComplexFloatReal(); 13938 return true; 13939 } 13940 } 13941 } 13942 13943 //===----------------------------------------------------------------------===// 13944 // Complex Evaluation (for float and integer) 13945 //===----------------------------------------------------------------------===// 13946 13947 namespace { 13948 class ComplexExprEvaluator 13949 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13950 ComplexValue &Result; 13951 13952 public: 13953 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13954 : ExprEvaluatorBaseTy(info), Result(Result) {} 13955 13956 bool Success(const APValue &V, const Expr *e) { 13957 Result.setFrom(V); 13958 return true; 13959 } 13960 13961 bool ZeroInitialization(const Expr *E); 13962 13963 //===--------------------------------------------------------------------===// 13964 // Visitor Methods 13965 //===--------------------------------------------------------------------===// 13966 13967 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13968 bool VisitCastExpr(const CastExpr *E); 13969 bool VisitBinaryOperator(const BinaryOperator *E); 13970 bool VisitUnaryOperator(const UnaryOperator *E); 13971 bool VisitInitListExpr(const InitListExpr *E); 13972 bool VisitCallExpr(const CallExpr *E); 13973 }; 13974 } // end anonymous namespace 13975 13976 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13977 EvalInfo &Info) { 13978 assert(!E->isValueDependent()); 13979 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 13980 return ComplexExprEvaluator(Info, Result).Visit(E); 13981 } 13982 13983 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13984 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13985 if (ElemTy->isRealFloatingType()) { 13986 Result.makeComplexFloat(); 13987 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13988 Result.FloatReal = Zero; 13989 Result.FloatImag = Zero; 13990 } else { 13991 Result.makeComplexInt(); 13992 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13993 Result.IntReal = Zero; 13994 Result.IntImag = Zero; 13995 } 13996 return true; 13997 } 13998 13999 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 14000 const Expr* SubExpr = E->getSubExpr(); 14001 14002 if (SubExpr->getType()->isRealFloatingType()) { 14003 Result.makeComplexFloat(); 14004 APFloat &Imag = Result.FloatImag; 14005 if (!EvaluateFloat(SubExpr, Imag, Info)) 14006 return false; 14007 14008 Result.FloatReal = APFloat(Imag.getSemantics()); 14009 return true; 14010 } else { 14011 assert(SubExpr->getType()->isIntegerType() && 14012 "Unexpected imaginary literal."); 14013 14014 Result.makeComplexInt(); 14015 APSInt &Imag = Result.IntImag; 14016 if (!EvaluateInteger(SubExpr, Imag, Info)) 14017 return false; 14018 14019 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 14020 return true; 14021 } 14022 } 14023 14024 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 14025 14026 switch (E->getCastKind()) { 14027 case CK_BitCast: 14028 case CK_BaseToDerived: 14029 case CK_DerivedToBase: 14030 case CK_UncheckedDerivedToBase: 14031 case CK_Dynamic: 14032 case CK_ToUnion: 14033 case CK_ArrayToPointerDecay: 14034 case CK_FunctionToPointerDecay: 14035 case CK_NullToPointer: 14036 case CK_NullToMemberPointer: 14037 case CK_BaseToDerivedMemberPointer: 14038 case CK_DerivedToBaseMemberPointer: 14039 case CK_MemberPointerToBoolean: 14040 case CK_ReinterpretMemberPointer: 14041 case CK_ConstructorConversion: 14042 case CK_IntegralToPointer: 14043 case CK_PointerToIntegral: 14044 case CK_PointerToBoolean: 14045 case CK_ToVoid: 14046 case CK_VectorSplat: 14047 case CK_IntegralCast: 14048 case CK_BooleanToSignedIntegral: 14049 case CK_IntegralToBoolean: 14050 case CK_IntegralToFloating: 14051 case CK_FloatingToIntegral: 14052 case CK_FloatingToBoolean: 14053 case CK_FloatingCast: 14054 case CK_CPointerToObjCPointerCast: 14055 case CK_BlockPointerToObjCPointerCast: 14056 case CK_AnyPointerToBlockPointerCast: 14057 case CK_ObjCObjectLValueCast: 14058 case CK_FloatingComplexToReal: 14059 case CK_FloatingComplexToBoolean: 14060 case CK_IntegralComplexToReal: 14061 case CK_IntegralComplexToBoolean: 14062 case CK_ARCProduceObject: 14063 case CK_ARCConsumeObject: 14064 case CK_ARCReclaimReturnedObject: 14065 case CK_ARCExtendBlockObject: 14066 case CK_CopyAndAutoreleaseBlockObject: 14067 case CK_BuiltinFnToFnPtr: 14068 case CK_ZeroToOCLOpaqueType: 14069 case CK_NonAtomicToAtomic: 14070 case CK_AddressSpaceConversion: 14071 case CK_IntToOCLSampler: 14072 case CK_FloatingToFixedPoint: 14073 case CK_FixedPointToFloating: 14074 case CK_FixedPointCast: 14075 case CK_FixedPointToBoolean: 14076 case CK_FixedPointToIntegral: 14077 case CK_IntegralToFixedPoint: 14078 case CK_MatrixCast: 14079 llvm_unreachable("invalid cast kind for complex value"); 14080 14081 case CK_LValueToRValue: 14082 case CK_AtomicToNonAtomic: 14083 case CK_NoOp: 14084 case CK_LValueToRValueBitCast: 14085 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14086 14087 case CK_Dependent: 14088 case CK_LValueBitCast: 14089 case CK_UserDefinedConversion: 14090 return Error(E); 14091 14092 case CK_FloatingRealToComplex: { 14093 APFloat &Real = Result.FloatReal; 14094 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 14095 return false; 14096 14097 Result.makeComplexFloat(); 14098 Result.FloatImag = APFloat(Real.getSemantics()); 14099 return true; 14100 } 14101 14102 case CK_FloatingComplexCast: { 14103 if (!Visit(E->getSubExpr())) 14104 return false; 14105 14106 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14107 QualType From 14108 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14109 14110 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 14111 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 14112 } 14113 14114 case CK_FloatingComplexToIntegralComplex: { 14115 if (!Visit(E->getSubExpr())) 14116 return false; 14117 14118 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14119 QualType From 14120 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14121 Result.makeComplexInt(); 14122 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 14123 To, Result.IntReal) && 14124 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 14125 To, Result.IntImag); 14126 } 14127 14128 case CK_IntegralRealToComplex: { 14129 APSInt &Real = Result.IntReal; 14130 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14131 return false; 14132 14133 Result.makeComplexInt(); 14134 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14135 return true; 14136 } 14137 14138 case CK_IntegralComplexCast: { 14139 if (!Visit(E->getSubExpr())) 14140 return false; 14141 14142 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14143 QualType From 14144 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14145 14146 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14147 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14148 return true; 14149 } 14150 14151 case CK_IntegralComplexToFloatingComplex: { 14152 if (!Visit(E->getSubExpr())) 14153 return false; 14154 14155 const FPOptions FPO = E->getFPFeaturesInEffect( 14156 Info.Ctx.getLangOpts()); 14157 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14158 QualType From 14159 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14160 Result.makeComplexFloat(); 14161 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14162 To, Result.FloatReal) && 14163 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14164 To, Result.FloatImag); 14165 } 14166 } 14167 14168 llvm_unreachable("unknown cast resulting in complex value"); 14169 } 14170 14171 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14172 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14173 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14174 14175 // Track whether the LHS or RHS is real at the type system level. When this is 14176 // the case we can simplify our evaluation strategy. 14177 bool LHSReal = false, RHSReal = false; 14178 14179 bool LHSOK; 14180 if (E->getLHS()->getType()->isRealFloatingType()) { 14181 LHSReal = true; 14182 APFloat &Real = Result.FloatReal; 14183 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14184 if (LHSOK) { 14185 Result.makeComplexFloat(); 14186 Result.FloatImag = APFloat(Real.getSemantics()); 14187 } 14188 } else { 14189 LHSOK = Visit(E->getLHS()); 14190 } 14191 if (!LHSOK && !Info.noteFailure()) 14192 return false; 14193 14194 ComplexValue RHS; 14195 if (E->getRHS()->getType()->isRealFloatingType()) { 14196 RHSReal = true; 14197 APFloat &Real = RHS.FloatReal; 14198 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14199 return false; 14200 RHS.makeComplexFloat(); 14201 RHS.FloatImag = APFloat(Real.getSemantics()); 14202 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14203 return false; 14204 14205 assert(!(LHSReal && RHSReal) && 14206 "Cannot have both operands of a complex operation be real."); 14207 switch (E->getOpcode()) { 14208 default: return Error(E); 14209 case BO_Add: 14210 if (Result.isComplexFloat()) { 14211 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14212 APFloat::rmNearestTiesToEven); 14213 if (LHSReal) 14214 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14215 else if (!RHSReal) 14216 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14217 APFloat::rmNearestTiesToEven); 14218 } else { 14219 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14220 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14221 } 14222 break; 14223 case BO_Sub: 14224 if (Result.isComplexFloat()) { 14225 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14226 APFloat::rmNearestTiesToEven); 14227 if (LHSReal) { 14228 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14229 Result.getComplexFloatImag().changeSign(); 14230 } else if (!RHSReal) { 14231 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14232 APFloat::rmNearestTiesToEven); 14233 } 14234 } else { 14235 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14236 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14237 } 14238 break; 14239 case BO_Mul: 14240 if (Result.isComplexFloat()) { 14241 // This is an implementation of complex multiplication according to the 14242 // constraints laid out in C11 Annex G. The implementation uses the 14243 // following naming scheme: 14244 // (a + ib) * (c + id) 14245 ComplexValue LHS = Result; 14246 APFloat &A = LHS.getComplexFloatReal(); 14247 APFloat &B = LHS.getComplexFloatImag(); 14248 APFloat &C = RHS.getComplexFloatReal(); 14249 APFloat &D = RHS.getComplexFloatImag(); 14250 APFloat &ResR = Result.getComplexFloatReal(); 14251 APFloat &ResI = Result.getComplexFloatImag(); 14252 if (LHSReal) { 14253 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14254 ResR = A * C; 14255 ResI = A * D; 14256 } else if (RHSReal) { 14257 ResR = C * A; 14258 ResI = C * B; 14259 } else { 14260 // In the fully general case, we need to handle NaNs and infinities 14261 // robustly. 14262 APFloat AC = A * C; 14263 APFloat BD = B * D; 14264 APFloat AD = A * D; 14265 APFloat BC = B * C; 14266 ResR = AC - BD; 14267 ResI = AD + BC; 14268 if (ResR.isNaN() && ResI.isNaN()) { 14269 bool Recalc = false; 14270 if (A.isInfinity() || B.isInfinity()) { 14271 A = APFloat::copySign( 14272 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14273 B = APFloat::copySign( 14274 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14275 if (C.isNaN()) 14276 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14277 if (D.isNaN()) 14278 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14279 Recalc = true; 14280 } 14281 if (C.isInfinity() || D.isInfinity()) { 14282 C = APFloat::copySign( 14283 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14284 D = APFloat::copySign( 14285 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14286 if (A.isNaN()) 14287 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14288 if (B.isNaN()) 14289 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14290 Recalc = true; 14291 } 14292 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14293 AD.isInfinity() || BC.isInfinity())) { 14294 if (A.isNaN()) 14295 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14296 if (B.isNaN()) 14297 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14298 if (C.isNaN()) 14299 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14300 if (D.isNaN()) 14301 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14302 Recalc = true; 14303 } 14304 if (Recalc) { 14305 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14306 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14307 } 14308 } 14309 } 14310 } else { 14311 ComplexValue LHS = Result; 14312 Result.getComplexIntReal() = 14313 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14314 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14315 Result.getComplexIntImag() = 14316 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14317 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14318 } 14319 break; 14320 case BO_Div: 14321 if (Result.isComplexFloat()) { 14322 // This is an implementation of complex division according to the 14323 // constraints laid out in C11 Annex G. The implementation uses the 14324 // following naming scheme: 14325 // (a + ib) / (c + id) 14326 ComplexValue LHS = Result; 14327 APFloat &A = LHS.getComplexFloatReal(); 14328 APFloat &B = LHS.getComplexFloatImag(); 14329 APFloat &C = RHS.getComplexFloatReal(); 14330 APFloat &D = RHS.getComplexFloatImag(); 14331 APFloat &ResR = Result.getComplexFloatReal(); 14332 APFloat &ResI = Result.getComplexFloatImag(); 14333 if (RHSReal) { 14334 ResR = A / C; 14335 ResI = B / C; 14336 } else { 14337 if (LHSReal) { 14338 // No real optimizations we can do here, stub out with zero. 14339 B = APFloat::getZero(A.getSemantics()); 14340 } 14341 int DenomLogB = 0; 14342 APFloat MaxCD = maxnum(abs(C), abs(D)); 14343 if (MaxCD.isFinite()) { 14344 DenomLogB = ilogb(MaxCD); 14345 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14346 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14347 } 14348 APFloat Denom = C * C + D * D; 14349 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14350 APFloat::rmNearestTiesToEven); 14351 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14352 APFloat::rmNearestTiesToEven); 14353 if (ResR.isNaN() && ResI.isNaN()) { 14354 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14355 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14356 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14357 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14358 D.isFinite()) { 14359 A = APFloat::copySign( 14360 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14361 B = APFloat::copySign( 14362 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14363 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14364 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14365 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14366 C = APFloat::copySign( 14367 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14368 D = APFloat::copySign( 14369 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14370 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14371 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14372 } 14373 } 14374 } 14375 } else { 14376 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14377 return Error(E, diag::note_expr_divide_by_zero); 14378 14379 ComplexValue LHS = Result; 14380 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14381 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14382 Result.getComplexIntReal() = 14383 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14384 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14385 Result.getComplexIntImag() = 14386 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14387 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14388 } 14389 break; 14390 } 14391 14392 return true; 14393 } 14394 14395 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14396 // Get the operand value into 'Result'. 14397 if (!Visit(E->getSubExpr())) 14398 return false; 14399 14400 switch (E->getOpcode()) { 14401 default: 14402 return Error(E); 14403 case UO_Extension: 14404 return true; 14405 case UO_Plus: 14406 // The result is always just the subexpr. 14407 return true; 14408 case UO_Minus: 14409 if (Result.isComplexFloat()) { 14410 Result.getComplexFloatReal().changeSign(); 14411 Result.getComplexFloatImag().changeSign(); 14412 } 14413 else { 14414 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14415 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14416 } 14417 return true; 14418 case UO_Not: 14419 if (Result.isComplexFloat()) 14420 Result.getComplexFloatImag().changeSign(); 14421 else 14422 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14423 return true; 14424 } 14425 } 14426 14427 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14428 if (E->getNumInits() == 2) { 14429 if (E->getType()->isComplexType()) { 14430 Result.makeComplexFloat(); 14431 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14432 return false; 14433 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14434 return false; 14435 } else { 14436 Result.makeComplexInt(); 14437 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14438 return false; 14439 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14440 return false; 14441 } 14442 return true; 14443 } 14444 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14445 } 14446 14447 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14448 switch (E->getBuiltinCallee()) { 14449 case Builtin::BI__builtin_complex: 14450 Result.makeComplexFloat(); 14451 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14452 return false; 14453 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14454 return false; 14455 return true; 14456 14457 default: 14458 break; 14459 } 14460 14461 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14462 } 14463 14464 //===----------------------------------------------------------------------===// 14465 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14466 // implicit conversion. 14467 //===----------------------------------------------------------------------===// 14468 14469 namespace { 14470 class AtomicExprEvaluator : 14471 public ExprEvaluatorBase<AtomicExprEvaluator> { 14472 const LValue *This; 14473 APValue &Result; 14474 public: 14475 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14476 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14477 14478 bool Success(const APValue &V, const Expr *E) { 14479 Result = V; 14480 return true; 14481 } 14482 14483 bool ZeroInitialization(const Expr *E) { 14484 ImplicitValueInitExpr VIE( 14485 E->getType()->castAs<AtomicType>()->getValueType()); 14486 // For atomic-qualified class (and array) types in C++, initialize the 14487 // _Atomic-wrapped subobject directly, in-place. 14488 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14489 : Evaluate(Result, Info, &VIE); 14490 } 14491 14492 bool VisitCastExpr(const CastExpr *E) { 14493 switch (E->getCastKind()) { 14494 default: 14495 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14496 case CK_NonAtomicToAtomic: 14497 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14498 : Evaluate(Result, Info, E->getSubExpr()); 14499 } 14500 } 14501 }; 14502 } // end anonymous namespace 14503 14504 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14505 EvalInfo &Info) { 14506 assert(!E->isValueDependent()); 14507 assert(E->isPRValue() && E->getType()->isAtomicType()); 14508 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14509 } 14510 14511 //===----------------------------------------------------------------------===// 14512 // Void expression evaluation, primarily for a cast to void on the LHS of a 14513 // comma operator 14514 //===----------------------------------------------------------------------===// 14515 14516 namespace { 14517 class VoidExprEvaluator 14518 : public ExprEvaluatorBase<VoidExprEvaluator> { 14519 public: 14520 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14521 14522 bool Success(const APValue &V, const Expr *e) { return true; } 14523 14524 bool ZeroInitialization(const Expr *E) { return true; } 14525 14526 bool VisitCastExpr(const CastExpr *E) { 14527 switch (E->getCastKind()) { 14528 default: 14529 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14530 case CK_ToVoid: 14531 VisitIgnoredValue(E->getSubExpr()); 14532 return true; 14533 } 14534 } 14535 14536 bool VisitCallExpr(const CallExpr *E) { 14537 switch (E->getBuiltinCallee()) { 14538 case Builtin::BI__assume: 14539 case Builtin::BI__builtin_assume: 14540 // The argument is not evaluated! 14541 return true; 14542 14543 case Builtin::BI__builtin_operator_delete: 14544 return HandleOperatorDeleteCall(Info, E); 14545 14546 default: 14547 break; 14548 } 14549 14550 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14551 } 14552 14553 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14554 }; 14555 } // end anonymous namespace 14556 14557 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14558 // We cannot speculatively evaluate a delete expression. 14559 if (Info.SpeculativeEvaluationDepth) 14560 return false; 14561 14562 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14563 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14564 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14565 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14566 return false; 14567 } 14568 14569 const Expr *Arg = E->getArgument(); 14570 14571 LValue Pointer; 14572 if (!EvaluatePointer(Arg, Pointer, Info)) 14573 return false; 14574 if (Pointer.Designator.Invalid) 14575 return false; 14576 14577 // Deleting a null pointer has no effect. 14578 if (Pointer.isNullPointer()) { 14579 // This is the only case where we need to produce an extension warning: 14580 // the only other way we can succeed is if we find a dynamic allocation, 14581 // and we will have warned when we allocated it in that case. 14582 if (!Info.getLangOpts().CPlusPlus20) 14583 Info.CCEDiag(E, diag::note_constexpr_new); 14584 return true; 14585 } 14586 14587 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14588 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14589 if (!Alloc) 14590 return false; 14591 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14592 14593 // For the non-array case, the designator must be empty if the static type 14594 // does not have a virtual destructor. 14595 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14596 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14597 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14598 << Arg->getType()->getPointeeType() << AllocType; 14599 return false; 14600 } 14601 14602 // For a class type with a virtual destructor, the selected operator delete 14603 // is the one looked up when building the destructor. 14604 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14605 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14606 if (VirtualDelete && 14607 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14608 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14609 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14610 return false; 14611 } 14612 } 14613 14614 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14615 (*Alloc)->Value, AllocType)) 14616 return false; 14617 14618 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14619 // The element was already erased. This means the destructor call also 14620 // deleted the object. 14621 // FIXME: This probably results in undefined behavior before we get this 14622 // far, and should be diagnosed elsewhere first. 14623 Info.FFDiag(E, diag::note_constexpr_double_delete); 14624 return false; 14625 } 14626 14627 return true; 14628 } 14629 14630 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14631 assert(!E->isValueDependent()); 14632 assert(E->isPRValue() && E->getType()->isVoidType()); 14633 return VoidExprEvaluator(Info).Visit(E); 14634 } 14635 14636 //===----------------------------------------------------------------------===// 14637 // Top level Expr::EvaluateAsRValue method. 14638 //===----------------------------------------------------------------------===// 14639 14640 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14641 assert(!E->isValueDependent()); 14642 // In C, function designators are not lvalues, but we evaluate them as if they 14643 // are. 14644 QualType T = E->getType(); 14645 if (E->isGLValue() || T->isFunctionType()) { 14646 LValue LV; 14647 if (!EvaluateLValue(E, LV, Info)) 14648 return false; 14649 LV.moveInto(Result); 14650 } else if (T->isVectorType()) { 14651 if (!EvaluateVector(E, Result, Info)) 14652 return false; 14653 } else if (T->isIntegralOrEnumerationType()) { 14654 if (!IntExprEvaluator(Info, Result).Visit(E)) 14655 return false; 14656 } else if (T->hasPointerRepresentation()) { 14657 LValue LV; 14658 if (!EvaluatePointer(E, LV, Info)) 14659 return false; 14660 LV.moveInto(Result); 14661 } else if (T->isRealFloatingType()) { 14662 llvm::APFloat F(0.0); 14663 if (!EvaluateFloat(E, F, Info)) 14664 return false; 14665 Result = APValue(F); 14666 } else if (T->isAnyComplexType()) { 14667 ComplexValue C; 14668 if (!EvaluateComplex(E, C, Info)) 14669 return false; 14670 C.moveInto(Result); 14671 } else if (T->isFixedPointType()) { 14672 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14673 } else if (T->isMemberPointerType()) { 14674 MemberPtr P; 14675 if (!EvaluateMemberPointer(E, P, Info)) 14676 return false; 14677 P.moveInto(Result); 14678 return true; 14679 } else if (T->isArrayType()) { 14680 LValue LV; 14681 APValue &Value = 14682 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14683 if (!EvaluateArray(E, LV, Value, Info)) 14684 return false; 14685 Result = Value; 14686 } else if (T->isRecordType()) { 14687 LValue LV; 14688 APValue &Value = 14689 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14690 if (!EvaluateRecord(E, LV, Value, Info)) 14691 return false; 14692 Result = Value; 14693 } else if (T->isVoidType()) { 14694 if (!Info.getLangOpts().CPlusPlus11) 14695 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14696 << E->getType(); 14697 if (!EvaluateVoid(E, Info)) 14698 return false; 14699 } else if (T->isAtomicType()) { 14700 QualType Unqual = T.getAtomicUnqualifiedType(); 14701 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14702 LValue LV; 14703 APValue &Value = Info.CurrentCall->createTemporary( 14704 E, Unqual, ScopeKind::FullExpression, LV); 14705 if (!EvaluateAtomic(E, &LV, Value, Info)) 14706 return false; 14707 } else { 14708 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14709 return false; 14710 } 14711 } else if (Info.getLangOpts().CPlusPlus11) { 14712 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14713 return false; 14714 } else { 14715 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14716 return false; 14717 } 14718 14719 return true; 14720 } 14721 14722 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14723 /// cases, the in-place evaluation is essential, since later initializers for 14724 /// an object can indirectly refer to subobjects which were initialized earlier. 14725 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14726 const Expr *E, bool AllowNonLiteralTypes) { 14727 assert(!E->isValueDependent()); 14728 14729 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14730 return false; 14731 14732 if (E->isPRValue()) { 14733 // Evaluate arrays and record types in-place, so that later initializers can 14734 // refer to earlier-initialized members of the object. 14735 QualType T = E->getType(); 14736 if (T->isArrayType()) 14737 return EvaluateArray(E, This, Result, Info); 14738 else if (T->isRecordType()) 14739 return EvaluateRecord(E, This, Result, Info); 14740 else if (T->isAtomicType()) { 14741 QualType Unqual = T.getAtomicUnqualifiedType(); 14742 if (Unqual->isArrayType() || Unqual->isRecordType()) 14743 return EvaluateAtomic(E, &This, Result, Info); 14744 } 14745 } 14746 14747 // For any other type, in-place evaluation is unimportant. 14748 return Evaluate(Result, Info, E); 14749 } 14750 14751 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14752 /// lvalue-to-rvalue cast if it is an lvalue. 14753 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14754 assert(!E->isValueDependent()); 14755 if (Info.EnableNewConstInterp) { 14756 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14757 return false; 14758 } else { 14759 if (E->getType().isNull()) 14760 return false; 14761 14762 if (!CheckLiteralType(Info, E)) 14763 return false; 14764 14765 if (!::Evaluate(Result, Info, E)) 14766 return false; 14767 14768 if (E->isGLValue()) { 14769 LValue LV; 14770 LV.setFrom(Info.Ctx, Result); 14771 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14772 return false; 14773 } 14774 } 14775 14776 // Check this core constant expression is a constant expression. 14777 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14778 ConstantExprKind::Normal) && 14779 CheckMemoryLeaks(Info); 14780 } 14781 14782 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14783 const ASTContext &Ctx, bool &IsConst) { 14784 // Fast-path evaluations of integer literals, since we sometimes see files 14785 // containing vast quantities of these. 14786 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14787 Result.Val = APValue(APSInt(L->getValue(), 14788 L->getType()->isUnsignedIntegerType())); 14789 IsConst = true; 14790 return true; 14791 } 14792 14793 // This case should be rare, but we need to check it before we check on 14794 // the type below. 14795 if (Exp->getType().isNull()) { 14796 IsConst = false; 14797 return true; 14798 } 14799 14800 // FIXME: Evaluating values of large array and record types can cause 14801 // performance problems. Only do so in C++11 for now. 14802 if (Exp->isPRValue() && 14803 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && 14804 !Ctx.getLangOpts().CPlusPlus11) { 14805 IsConst = false; 14806 return true; 14807 } 14808 return false; 14809 } 14810 14811 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14812 Expr::SideEffectsKind SEK) { 14813 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14814 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14815 } 14816 14817 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14818 const ASTContext &Ctx, EvalInfo &Info) { 14819 assert(!E->isValueDependent()); 14820 bool IsConst; 14821 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14822 return IsConst; 14823 14824 return EvaluateAsRValue(Info, E, Result.Val); 14825 } 14826 14827 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14828 const ASTContext &Ctx, 14829 Expr::SideEffectsKind AllowSideEffects, 14830 EvalInfo &Info) { 14831 assert(!E->isValueDependent()); 14832 if (!E->getType()->isIntegralOrEnumerationType()) 14833 return false; 14834 14835 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14836 !ExprResult.Val.isInt() || 14837 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14838 return false; 14839 14840 return true; 14841 } 14842 14843 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14844 const ASTContext &Ctx, 14845 Expr::SideEffectsKind AllowSideEffects, 14846 EvalInfo &Info) { 14847 assert(!E->isValueDependent()); 14848 if (!E->getType()->isFixedPointType()) 14849 return false; 14850 14851 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14852 return false; 14853 14854 if (!ExprResult.Val.isFixedPoint() || 14855 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14856 return false; 14857 14858 return true; 14859 } 14860 14861 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14862 /// any crazy technique (that has nothing to do with language standards) that 14863 /// we want to. If this function returns true, it returns the folded constant 14864 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14865 /// will be applied to the result. 14866 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14867 bool InConstantContext) const { 14868 assert(!isValueDependent() && 14869 "Expression evaluator can't be called on a dependent expression."); 14870 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14871 Info.InConstantContext = InConstantContext; 14872 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14873 } 14874 14875 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14876 bool InConstantContext) const { 14877 assert(!isValueDependent() && 14878 "Expression evaluator can't be called on a dependent expression."); 14879 EvalResult Scratch; 14880 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14881 HandleConversionToBool(Scratch.Val, Result); 14882 } 14883 14884 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14885 SideEffectsKind AllowSideEffects, 14886 bool InConstantContext) const { 14887 assert(!isValueDependent() && 14888 "Expression evaluator can't be called on a dependent expression."); 14889 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14890 Info.InConstantContext = InConstantContext; 14891 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14892 } 14893 14894 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14895 SideEffectsKind AllowSideEffects, 14896 bool InConstantContext) const { 14897 assert(!isValueDependent() && 14898 "Expression evaluator can't be called on a dependent expression."); 14899 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14900 Info.InConstantContext = InConstantContext; 14901 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14902 } 14903 14904 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14905 SideEffectsKind AllowSideEffects, 14906 bool InConstantContext) const { 14907 assert(!isValueDependent() && 14908 "Expression evaluator can't be called on a dependent expression."); 14909 14910 if (!getType()->isRealFloatingType()) 14911 return false; 14912 14913 EvalResult ExprResult; 14914 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14915 !ExprResult.Val.isFloat() || 14916 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14917 return false; 14918 14919 Result = ExprResult.Val.getFloat(); 14920 return true; 14921 } 14922 14923 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14924 bool InConstantContext) const { 14925 assert(!isValueDependent() && 14926 "Expression evaluator can't be called on a dependent expression."); 14927 14928 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14929 Info.InConstantContext = InConstantContext; 14930 LValue LV; 14931 CheckedTemporaries CheckedTemps; 14932 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14933 Result.HasSideEffects || 14934 !CheckLValueConstantExpression(Info, getExprLoc(), 14935 Ctx.getLValueReferenceType(getType()), LV, 14936 ConstantExprKind::Normal, CheckedTemps)) 14937 return false; 14938 14939 LV.moveInto(Result.Val); 14940 return true; 14941 } 14942 14943 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14944 APValue DestroyedValue, QualType Type, 14945 SourceLocation Loc, Expr::EvalStatus &EStatus, 14946 bool IsConstantDestruction) { 14947 EvalInfo Info(Ctx, EStatus, 14948 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14949 : EvalInfo::EM_ConstantFold); 14950 Info.setEvaluatingDecl(Base, DestroyedValue, 14951 EvalInfo::EvaluatingDeclKind::Dtor); 14952 Info.InConstantContext = IsConstantDestruction; 14953 14954 LValue LVal; 14955 LVal.set(Base); 14956 14957 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14958 EStatus.HasSideEffects) 14959 return false; 14960 14961 if (!Info.discardCleanups()) 14962 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14963 14964 return true; 14965 } 14966 14967 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14968 ConstantExprKind Kind) const { 14969 assert(!isValueDependent() && 14970 "Expression evaluator can't be called on a dependent expression."); 14971 14972 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14973 EvalInfo Info(Ctx, Result, EM); 14974 Info.InConstantContext = true; 14975 14976 // The type of the object we're initializing is 'const T' for a class NTTP. 14977 QualType T = getType(); 14978 if (Kind == ConstantExprKind::ClassTemplateArgument) 14979 T.addConst(); 14980 14981 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14982 // represent the result of the evaluation. CheckConstantExpression ensures 14983 // this doesn't escape. 14984 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14985 APValue::LValueBase Base(&BaseMTE); 14986 14987 Info.setEvaluatingDecl(Base, Result.Val); 14988 LValue LVal; 14989 LVal.set(Base); 14990 14991 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14992 return false; 14993 14994 if (!Info.discardCleanups()) 14995 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14996 14997 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14998 Result.Val, Kind)) 14999 return false; 15000 if (!CheckMemoryLeaks(Info)) 15001 return false; 15002 15003 // If this is a class template argument, it's required to have constant 15004 // destruction too. 15005 if (Kind == ConstantExprKind::ClassTemplateArgument && 15006 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 15007 true) || 15008 Result.HasSideEffects)) { 15009 // FIXME: Prefix a note to indicate that the problem is lack of constant 15010 // destruction. 15011 return false; 15012 } 15013 15014 return true; 15015 } 15016 15017 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 15018 const VarDecl *VD, 15019 SmallVectorImpl<PartialDiagnosticAt> &Notes, 15020 bool IsConstantInitialization) const { 15021 assert(!isValueDependent() && 15022 "Expression evaluator can't be called on a dependent expression."); 15023 15024 // FIXME: Evaluating initializers for large array and record types can cause 15025 // performance problems. Only do so in C++11 for now. 15026 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 15027 !Ctx.getLangOpts().CPlusPlus11) 15028 return false; 15029 15030 Expr::EvalStatus EStatus; 15031 EStatus.Diag = &Notes; 15032 15033 EvalInfo Info(Ctx, EStatus, 15034 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 15035 ? EvalInfo::EM_ConstantExpression 15036 : EvalInfo::EM_ConstantFold); 15037 Info.setEvaluatingDecl(VD, Value); 15038 Info.InConstantContext = IsConstantInitialization; 15039 15040 SourceLocation DeclLoc = VD->getLocation(); 15041 QualType DeclTy = VD->getType(); 15042 15043 if (Info.EnableNewConstInterp) { 15044 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 15045 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 15046 return false; 15047 } else { 15048 LValue LVal; 15049 LVal.set(VD); 15050 15051 if (!EvaluateInPlace(Value, Info, LVal, this, 15052 /*AllowNonLiteralTypes=*/true) || 15053 EStatus.HasSideEffects) 15054 return false; 15055 15056 // At this point, any lifetime-extended temporaries are completely 15057 // initialized. 15058 Info.performLifetimeExtension(); 15059 15060 if (!Info.discardCleanups()) 15061 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15062 } 15063 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 15064 ConstantExprKind::Normal) && 15065 CheckMemoryLeaks(Info); 15066 } 15067 15068 bool VarDecl::evaluateDestruction( 15069 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15070 Expr::EvalStatus EStatus; 15071 EStatus.Diag = &Notes; 15072 15073 // Only treat the destruction as constant destruction if we formally have 15074 // constant initialization (or are usable in a constant expression). 15075 bool IsConstantDestruction = hasConstantInitialization(); 15076 15077 // Make a copy of the value for the destructor to mutate, if we know it. 15078 // Otherwise, treat the value as default-initialized; if the destructor works 15079 // anyway, then the destruction is constant (and must be essentially empty). 15080 APValue DestroyedValue; 15081 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 15082 DestroyedValue = *getEvaluatedValue(); 15083 else if (!getDefaultInitValue(getType(), DestroyedValue)) 15084 return false; 15085 15086 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 15087 getType(), getLocation(), EStatus, 15088 IsConstantDestruction) || 15089 EStatus.HasSideEffects) 15090 return false; 15091 15092 ensureEvaluatedStmt()->HasConstantDestruction = true; 15093 return true; 15094 } 15095 15096 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 15097 /// constant folded, but discard the result. 15098 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 15099 assert(!isValueDependent() && 15100 "Expression evaluator can't be called on a dependent expression."); 15101 15102 EvalResult Result; 15103 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 15104 !hasUnacceptableSideEffect(Result, SEK); 15105 } 15106 15107 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 15108 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15109 assert(!isValueDependent() && 15110 "Expression evaluator can't be called on a dependent expression."); 15111 15112 EvalResult EVResult; 15113 EVResult.Diag = Diag; 15114 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15115 Info.InConstantContext = true; 15116 15117 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 15118 (void)Result; 15119 assert(Result && "Could not evaluate expression"); 15120 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15121 15122 return EVResult.Val.getInt(); 15123 } 15124 15125 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 15126 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15127 assert(!isValueDependent() && 15128 "Expression evaluator can't be called on a dependent expression."); 15129 15130 EvalResult EVResult; 15131 EVResult.Diag = Diag; 15132 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15133 Info.InConstantContext = true; 15134 Info.CheckingForUndefinedBehavior = true; 15135 15136 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15137 (void)Result; 15138 assert(Result && "Could not evaluate expression"); 15139 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15140 15141 return EVResult.Val.getInt(); 15142 } 15143 15144 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15145 assert(!isValueDependent() && 15146 "Expression evaluator can't be called on a dependent expression."); 15147 15148 bool IsConst; 15149 EvalResult EVResult; 15150 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15151 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15152 Info.CheckingForUndefinedBehavior = true; 15153 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15154 } 15155 } 15156 15157 bool Expr::EvalResult::isGlobalLValue() const { 15158 assert(Val.isLValue()); 15159 return IsGlobalLValue(Val.getLValueBase()); 15160 } 15161 15162 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15163 /// an integer constant expression. 15164 15165 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15166 /// comma, etc 15167 15168 // CheckICE - This function does the fundamental ICE checking: the returned 15169 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15170 // and a (possibly null) SourceLocation indicating the location of the problem. 15171 // 15172 // Note that to reduce code duplication, this helper does no evaluation 15173 // itself; the caller checks whether the expression is evaluatable, and 15174 // in the rare cases where CheckICE actually cares about the evaluated 15175 // value, it calls into Evaluate. 15176 15177 namespace { 15178 15179 enum ICEKind { 15180 /// This expression is an ICE. 15181 IK_ICE, 15182 /// This expression is not an ICE, but if it isn't evaluated, it's 15183 /// a legal subexpression for an ICE. This return value is used to handle 15184 /// the comma operator in C99 mode, and non-constant subexpressions. 15185 IK_ICEIfUnevaluated, 15186 /// This expression is not an ICE, and is not a legal subexpression for one. 15187 IK_NotICE 15188 }; 15189 15190 struct ICEDiag { 15191 ICEKind Kind; 15192 SourceLocation Loc; 15193 15194 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15195 }; 15196 15197 } 15198 15199 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15200 15201 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15202 15203 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15204 Expr::EvalResult EVResult; 15205 Expr::EvalStatus Status; 15206 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15207 15208 Info.InConstantContext = true; 15209 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15210 !EVResult.Val.isInt()) 15211 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15212 15213 return NoDiag(); 15214 } 15215 15216 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15217 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15218 if (!E->getType()->isIntegralOrEnumerationType()) 15219 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15220 15221 switch (E->getStmtClass()) { 15222 #define ABSTRACT_STMT(Node) 15223 #define STMT(Node, Base) case Expr::Node##Class: 15224 #define EXPR(Node, Base) 15225 #include "clang/AST/StmtNodes.inc" 15226 case Expr::PredefinedExprClass: 15227 case Expr::FloatingLiteralClass: 15228 case Expr::ImaginaryLiteralClass: 15229 case Expr::StringLiteralClass: 15230 case Expr::ArraySubscriptExprClass: 15231 case Expr::MatrixSubscriptExprClass: 15232 case Expr::OMPArraySectionExprClass: 15233 case Expr::OMPArrayShapingExprClass: 15234 case Expr::OMPIteratorExprClass: 15235 case Expr::MemberExprClass: 15236 case Expr::CompoundAssignOperatorClass: 15237 case Expr::CompoundLiteralExprClass: 15238 case Expr::ExtVectorElementExprClass: 15239 case Expr::DesignatedInitExprClass: 15240 case Expr::ArrayInitLoopExprClass: 15241 case Expr::ArrayInitIndexExprClass: 15242 case Expr::NoInitExprClass: 15243 case Expr::DesignatedInitUpdateExprClass: 15244 case Expr::ImplicitValueInitExprClass: 15245 case Expr::ParenListExprClass: 15246 case Expr::VAArgExprClass: 15247 case Expr::AddrLabelExprClass: 15248 case Expr::StmtExprClass: 15249 case Expr::CXXMemberCallExprClass: 15250 case Expr::CUDAKernelCallExprClass: 15251 case Expr::CXXAddrspaceCastExprClass: 15252 case Expr::CXXDynamicCastExprClass: 15253 case Expr::CXXTypeidExprClass: 15254 case Expr::CXXUuidofExprClass: 15255 case Expr::MSPropertyRefExprClass: 15256 case Expr::MSPropertySubscriptExprClass: 15257 case Expr::CXXNullPtrLiteralExprClass: 15258 case Expr::UserDefinedLiteralClass: 15259 case Expr::CXXThisExprClass: 15260 case Expr::CXXThrowExprClass: 15261 case Expr::CXXNewExprClass: 15262 case Expr::CXXDeleteExprClass: 15263 case Expr::CXXPseudoDestructorExprClass: 15264 case Expr::UnresolvedLookupExprClass: 15265 case Expr::TypoExprClass: 15266 case Expr::RecoveryExprClass: 15267 case Expr::DependentScopeDeclRefExprClass: 15268 case Expr::CXXConstructExprClass: 15269 case Expr::CXXInheritedCtorInitExprClass: 15270 case Expr::CXXStdInitializerListExprClass: 15271 case Expr::CXXBindTemporaryExprClass: 15272 case Expr::ExprWithCleanupsClass: 15273 case Expr::CXXTemporaryObjectExprClass: 15274 case Expr::CXXUnresolvedConstructExprClass: 15275 case Expr::CXXDependentScopeMemberExprClass: 15276 case Expr::UnresolvedMemberExprClass: 15277 case Expr::ObjCStringLiteralClass: 15278 case Expr::ObjCBoxedExprClass: 15279 case Expr::ObjCArrayLiteralClass: 15280 case Expr::ObjCDictionaryLiteralClass: 15281 case Expr::ObjCEncodeExprClass: 15282 case Expr::ObjCMessageExprClass: 15283 case Expr::ObjCSelectorExprClass: 15284 case Expr::ObjCProtocolExprClass: 15285 case Expr::ObjCIvarRefExprClass: 15286 case Expr::ObjCPropertyRefExprClass: 15287 case Expr::ObjCSubscriptRefExprClass: 15288 case Expr::ObjCIsaExprClass: 15289 case Expr::ObjCAvailabilityCheckExprClass: 15290 case Expr::ShuffleVectorExprClass: 15291 case Expr::ConvertVectorExprClass: 15292 case Expr::BlockExprClass: 15293 case Expr::NoStmtClass: 15294 case Expr::OpaqueValueExprClass: 15295 case Expr::PackExpansionExprClass: 15296 case Expr::SubstNonTypeTemplateParmPackExprClass: 15297 case Expr::FunctionParmPackExprClass: 15298 case Expr::AsTypeExprClass: 15299 case Expr::ObjCIndirectCopyRestoreExprClass: 15300 case Expr::MaterializeTemporaryExprClass: 15301 case Expr::PseudoObjectExprClass: 15302 case Expr::AtomicExprClass: 15303 case Expr::LambdaExprClass: 15304 case Expr::CXXFoldExprClass: 15305 case Expr::CoawaitExprClass: 15306 case Expr::DependentCoawaitExprClass: 15307 case Expr::CoyieldExprClass: 15308 case Expr::SYCLUniqueStableNameExprClass: 15309 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15310 15311 case Expr::InitListExprClass: { 15312 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15313 // form "T x = { a };" is equivalent to "T x = a;". 15314 // Unless we're initializing a reference, T is a scalar as it is known to be 15315 // of integral or enumeration type. 15316 if (E->isPRValue()) 15317 if (cast<InitListExpr>(E)->getNumInits() == 1) 15318 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15319 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15320 } 15321 15322 case Expr::SizeOfPackExprClass: 15323 case Expr::GNUNullExprClass: 15324 case Expr::SourceLocExprClass: 15325 return NoDiag(); 15326 15327 case Expr::SubstNonTypeTemplateParmExprClass: 15328 return 15329 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15330 15331 case Expr::ConstantExprClass: 15332 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15333 15334 case Expr::ParenExprClass: 15335 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15336 case Expr::GenericSelectionExprClass: 15337 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15338 case Expr::IntegerLiteralClass: 15339 case Expr::FixedPointLiteralClass: 15340 case Expr::CharacterLiteralClass: 15341 case Expr::ObjCBoolLiteralExprClass: 15342 case Expr::CXXBoolLiteralExprClass: 15343 case Expr::CXXScalarValueInitExprClass: 15344 case Expr::TypeTraitExprClass: 15345 case Expr::ConceptSpecializationExprClass: 15346 case Expr::RequiresExprClass: 15347 case Expr::ArrayTypeTraitExprClass: 15348 case Expr::ExpressionTraitExprClass: 15349 case Expr::CXXNoexceptExprClass: 15350 return NoDiag(); 15351 case Expr::CallExprClass: 15352 case Expr::CXXOperatorCallExprClass: { 15353 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15354 // constant expressions, but they can never be ICEs because an ICE cannot 15355 // contain an operand of (pointer to) function type. 15356 const CallExpr *CE = cast<CallExpr>(E); 15357 if (CE->getBuiltinCallee()) 15358 return CheckEvalInICE(E, Ctx); 15359 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15360 } 15361 case Expr::CXXRewrittenBinaryOperatorClass: 15362 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15363 Ctx); 15364 case Expr::DeclRefExprClass: { 15365 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15366 if (isa<EnumConstantDecl>(D)) 15367 return NoDiag(); 15368 15369 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15370 // integer variables in constant expressions: 15371 // 15372 // C++ 7.1.5.1p2 15373 // A variable of non-volatile const-qualified integral or enumeration 15374 // type initialized by an ICE can be used in ICEs. 15375 // 15376 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15377 // that mode, use of reference variables should not be allowed. 15378 const VarDecl *VD = dyn_cast<VarDecl>(D); 15379 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15380 !VD->getType()->isReferenceType()) 15381 return NoDiag(); 15382 15383 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15384 } 15385 case Expr::UnaryOperatorClass: { 15386 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15387 switch (Exp->getOpcode()) { 15388 case UO_PostInc: 15389 case UO_PostDec: 15390 case UO_PreInc: 15391 case UO_PreDec: 15392 case UO_AddrOf: 15393 case UO_Deref: 15394 case UO_Coawait: 15395 // C99 6.6/3 allows increment and decrement within unevaluated 15396 // subexpressions of constant expressions, but they can never be ICEs 15397 // because an ICE cannot contain an lvalue operand. 15398 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15399 case UO_Extension: 15400 case UO_LNot: 15401 case UO_Plus: 15402 case UO_Minus: 15403 case UO_Not: 15404 case UO_Real: 15405 case UO_Imag: 15406 return CheckICE(Exp->getSubExpr(), Ctx); 15407 } 15408 llvm_unreachable("invalid unary operator class"); 15409 } 15410 case Expr::OffsetOfExprClass: { 15411 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15412 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15413 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15414 // compliance: we should warn earlier for offsetof expressions with 15415 // array subscripts that aren't ICEs, and if the array subscripts 15416 // are ICEs, the value of the offsetof must be an integer constant. 15417 return CheckEvalInICE(E, Ctx); 15418 } 15419 case Expr::UnaryExprOrTypeTraitExprClass: { 15420 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15421 if ((Exp->getKind() == UETT_SizeOf) && 15422 Exp->getTypeOfArgument()->isVariableArrayType()) 15423 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15424 return NoDiag(); 15425 } 15426 case Expr::BinaryOperatorClass: { 15427 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15428 switch (Exp->getOpcode()) { 15429 case BO_PtrMemD: 15430 case BO_PtrMemI: 15431 case BO_Assign: 15432 case BO_MulAssign: 15433 case BO_DivAssign: 15434 case BO_RemAssign: 15435 case BO_AddAssign: 15436 case BO_SubAssign: 15437 case BO_ShlAssign: 15438 case BO_ShrAssign: 15439 case BO_AndAssign: 15440 case BO_XorAssign: 15441 case BO_OrAssign: 15442 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15443 // constant expressions, but they can never be ICEs because an ICE cannot 15444 // contain an lvalue operand. 15445 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15446 15447 case BO_Mul: 15448 case BO_Div: 15449 case BO_Rem: 15450 case BO_Add: 15451 case BO_Sub: 15452 case BO_Shl: 15453 case BO_Shr: 15454 case BO_LT: 15455 case BO_GT: 15456 case BO_LE: 15457 case BO_GE: 15458 case BO_EQ: 15459 case BO_NE: 15460 case BO_And: 15461 case BO_Xor: 15462 case BO_Or: 15463 case BO_Comma: 15464 case BO_Cmp: { 15465 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15466 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15467 if (Exp->getOpcode() == BO_Div || 15468 Exp->getOpcode() == BO_Rem) { 15469 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15470 // we don't evaluate one. 15471 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15472 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15473 if (REval == 0) 15474 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15475 if (REval.isSigned() && REval.isAllOnes()) { 15476 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15477 if (LEval.isMinSignedValue()) 15478 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15479 } 15480 } 15481 } 15482 if (Exp->getOpcode() == BO_Comma) { 15483 if (Ctx.getLangOpts().C99) { 15484 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15485 // if it isn't evaluated. 15486 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15487 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15488 } else { 15489 // In both C89 and C++, commas in ICEs are illegal. 15490 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15491 } 15492 } 15493 return Worst(LHSResult, RHSResult); 15494 } 15495 case BO_LAnd: 15496 case BO_LOr: { 15497 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15498 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15499 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15500 // Rare case where the RHS has a comma "side-effect"; we need 15501 // to actually check the condition to see whether the side 15502 // with the comma is evaluated. 15503 if ((Exp->getOpcode() == BO_LAnd) != 15504 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15505 return RHSResult; 15506 return NoDiag(); 15507 } 15508 15509 return Worst(LHSResult, RHSResult); 15510 } 15511 } 15512 llvm_unreachable("invalid binary operator kind"); 15513 } 15514 case Expr::ImplicitCastExprClass: 15515 case Expr::CStyleCastExprClass: 15516 case Expr::CXXFunctionalCastExprClass: 15517 case Expr::CXXStaticCastExprClass: 15518 case Expr::CXXReinterpretCastExprClass: 15519 case Expr::CXXConstCastExprClass: 15520 case Expr::ObjCBridgedCastExprClass: { 15521 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15522 if (isa<ExplicitCastExpr>(E)) { 15523 if (const FloatingLiteral *FL 15524 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15525 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15526 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15527 APSInt IgnoredVal(DestWidth, !DestSigned); 15528 bool Ignored; 15529 // If the value does not fit in the destination type, the behavior is 15530 // undefined, so we are not required to treat it as a constant 15531 // expression. 15532 if (FL->getValue().convertToInteger(IgnoredVal, 15533 llvm::APFloat::rmTowardZero, 15534 &Ignored) & APFloat::opInvalidOp) 15535 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15536 return NoDiag(); 15537 } 15538 } 15539 switch (cast<CastExpr>(E)->getCastKind()) { 15540 case CK_LValueToRValue: 15541 case CK_AtomicToNonAtomic: 15542 case CK_NonAtomicToAtomic: 15543 case CK_NoOp: 15544 case CK_IntegralToBoolean: 15545 case CK_IntegralCast: 15546 return CheckICE(SubExpr, Ctx); 15547 default: 15548 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15549 } 15550 } 15551 case Expr::BinaryConditionalOperatorClass: { 15552 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15553 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15554 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15555 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15556 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15557 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15558 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15559 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15560 return FalseResult; 15561 } 15562 case Expr::ConditionalOperatorClass: { 15563 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15564 // If the condition (ignoring parens) is a __builtin_constant_p call, 15565 // then only the true side is actually considered in an integer constant 15566 // expression, and it is fully evaluated. This is an important GNU 15567 // extension. See GCC PR38377 for discussion. 15568 if (const CallExpr *CallCE 15569 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15570 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15571 return CheckEvalInICE(E, Ctx); 15572 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15573 if (CondResult.Kind == IK_NotICE) 15574 return CondResult; 15575 15576 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15577 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15578 15579 if (TrueResult.Kind == IK_NotICE) 15580 return TrueResult; 15581 if (FalseResult.Kind == IK_NotICE) 15582 return FalseResult; 15583 if (CondResult.Kind == IK_ICEIfUnevaluated) 15584 return CondResult; 15585 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15586 return NoDiag(); 15587 // Rare case where the diagnostics depend on which side is evaluated 15588 // Note that if we get here, CondResult is 0, and at least one of 15589 // TrueResult and FalseResult is non-zero. 15590 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15591 return FalseResult; 15592 return TrueResult; 15593 } 15594 case Expr::CXXDefaultArgExprClass: 15595 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15596 case Expr::CXXDefaultInitExprClass: 15597 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15598 case Expr::ChooseExprClass: { 15599 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15600 } 15601 case Expr::BuiltinBitCastExprClass: { 15602 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15603 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15604 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15605 } 15606 } 15607 15608 llvm_unreachable("Invalid StmtClass!"); 15609 } 15610 15611 /// Evaluate an expression as a C++11 integral constant expression. 15612 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15613 const Expr *E, 15614 llvm::APSInt *Value, 15615 SourceLocation *Loc) { 15616 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15617 if (Loc) *Loc = E->getExprLoc(); 15618 return false; 15619 } 15620 15621 APValue Result; 15622 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15623 return false; 15624 15625 if (!Result.isInt()) { 15626 if (Loc) *Loc = E->getExprLoc(); 15627 return false; 15628 } 15629 15630 if (Value) *Value = Result.getInt(); 15631 return true; 15632 } 15633 15634 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15635 SourceLocation *Loc) const { 15636 assert(!isValueDependent() && 15637 "Expression evaluator can't be called on a dependent expression."); 15638 15639 if (Ctx.getLangOpts().CPlusPlus11) 15640 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15641 15642 ICEDiag D = CheckICE(this, Ctx); 15643 if (D.Kind != IK_ICE) { 15644 if (Loc) *Loc = D.Loc; 15645 return false; 15646 } 15647 return true; 15648 } 15649 15650 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15651 SourceLocation *Loc, 15652 bool isEvaluated) const { 15653 if (isValueDependent()) { 15654 // Expression evaluator can't succeed on a dependent expression. 15655 return None; 15656 } 15657 15658 APSInt Value; 15659 15660 if (Ctx.getLangOpts().CPlusPlus11) { 15661 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15662 return Value; 15663 return None; 15664 } 15665 15666 if (!isIntegerConstantExpr(Ctx, Loc)) 15667 return None; 15668 15669 // The only possible side-effects here are due to UB discovered in the 15670 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15671 // required to treat the expression as an ICE, so we produce the folded 15672 // value. 15673 EvalResult ExprResult; 15674 Expr::EvalStatus Status; 15675 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15676 Info.InConstantContext = true; 15677 15678 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15679 llvm_unreachable("ICE cannot be evaluated!"); 15680 15681 return ExprResult.Val.getInt(); 15682 } 15683 15684 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15685 assert(!isValueDependent() && 15686 "Expression evaluator can't be called on a dependent expression."); 15687 15688 return CheckICE(this, Ctx).Kind == IK_ICE; 15689 } 15690 15691 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15692 SourceLocation *Loc) const { 15693 assert(!isValueDependent() && 15694 "Expression evaluator can't be called on a dependent expression."); 15695 15696 // We support this checking in C++98 mode in order to diagnose compatibility 15697 // issues. 15698 assert(Ctx.getLangOpts().CPlusPlus); 15699 15700 // Build evaluation settings. 15701 Expr::EvalStatus Status; 15702 SmallVector<PartialDiagnosticAt, 8> Diags; 15703 Status.Diag = &Diags; 15704 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15705 15706 APValue Scratch; 15707 bool IsConstExpr = 15708 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15709 // FIXME: We don't produce a diagnostic for this, but the callers that 15710 // call us on arbitrary full-expressions should generally not care. 15711 Info.discardCleanups() && !Status.HasSideEffects; 15712 15713 if (!Diags.empty()) { 15714 IsConstExpr = false; 15715 if (Loc) *Loc = Diags[0].first; 15716 } else if (!IsConstExpr) { 15717 // FIXME: This shouldn't happen. 15718 if (Loc) *Loc = getExprLoc(); 15719 } 15720 15721 return IsConstExpr; 15722 } 15723 15724 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15725 const FunctionDecl *Callee, 15726 ArrayRef<const Expr*> Args, 15727 const Expr *This) const { 15728 assert(!isValueDependent() && 15729 "Expression evaluator can't be called on a dependent expression."); 15730 15731 Expr::EvalStatus Status; 15732 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15733 Info.InConstantContext = true; 15734 15735 LValue ThisVal; 15736 const LValue *ThisPtr = nullptr; 15737 if (This) { 15738 #ifndef NDEBUG 15739 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15740 assert(MD && "Don't provide `this` for non-methods."); 15741 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15742 #endif 15743 if (!This->isValueDependent() && 15744 EvaluateObjectArgument(Info, This, ThisVal) && 15745 !Info.EvalStatus.HasSideEffects) 15746 ThisPtr = &ThisVal; 15747 15748 // Ignore any side-effects from a failed evaluation. This is safe because 15749 // they can't interfere with any other argument evaluation. 15750 Info.EvalStatus.HasSideEffects = false; 15751 } 15752 15753 CallRef Call = Info.CurrentCall->createCall(Callee); 15754 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15755 I != E; ++I) { 15756 unsigned Idx = I - Args.begin(); 15757 if (Idx >= Callee->getNumParams()) 15758 break; 15759 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15760 if ((*I)->isValueDependent() || 15761 !EvaluateCallArg(PVD, *I, Call, Info) || 15762 Info.EvalStatus.HasSideEffects) { 15763 // If evaluation fails, throw away the argument entirely. 15764 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15765 *Slot = APValue(); 15766 } 15767 15768 // Ignore any side-effects from a failed evaluation. This is safe because 15769 // they can't interfere with any other argument evaluation. 15770 Info.EvalStatus.HasSideEffects = false; 15771 } 15772 15773 // Parameter cleanups happen in the caller and are not part of this 15774 // evaluation. 15775 Info.discardCleanups(); 15776 Info.EvalStatus.HasSideEffects = false; 15777 15778 // Build fake call to Callee. 15779 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15780 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15781 FullExpressionRAII Scope(Info); 15782 return Evaluate(Value, Info, this) && Scope.destroy() && 15783 !Info.EvalStatus.HasSideEffects; 15784 } 15785 15786 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15787 SmallVectorImpl< 15788 PartialDiagnosticAt> &Diags) { 15789 // FIXME: It would be useful to check constexpr function templates, but at the 15790 // moment the constant expression evaluator cannot cope with the non-rigorous 15791 // ASTs which we build for dependent expressions. 15792 if (FD->isDependentContext()) 15793 return true; 15794 15795 Expr::EvalStatus Status; 15796 Status.Diag = &Diags; 15797 15798 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15799 Info.InConstantContext = true; 15800 Info.CheckingPotentialConstantExpression = true; 15801 15802 // The constexpr VM attempts to compile all methods to bytecode here. 15803 if (Info.EnableNewConstInterp) { 15804 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15805 return Diags.empty(); 15806 } 15807 15808 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15809 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15810 15811 // Fabricate an arbitrary expression on the stack and pretend that it 15812 // is a temporary being used as the 'this' pointer. 15813 LValue This; 15814 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15815 This.set({&VIE, Info.CurrentCall->Index}); 15816 15817 ArrayRef<const Expr*> Args; 15818 15819 APValue Scratch; 15820 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15821 // Evaluate the call as a constant initializer, to allow the construction 15822 // of objects of non-literal types. 15823 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15824 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15825 } else { 15826 SourceLocation Loc = FD->getLocation(); 15827 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15828 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15829 } 15830 15831 return Diags.empty(); 15832 } 15833 15834 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15835 const FunctionDecl *FD, 15836 SmallVectorImpl< 15837 PartialDiagnosticAt> &Diags) { 15838 assert(!E->isValueDependent() && 15839 "Expression evaluator can't be called on a dependent expression."); 15840 15841 Expr::EvalStatus Status; 15842 Status.Diag = &Diags; 15843 15844 EvalInfo Info(FD->getASTContext(), Status, 15845 EvalInfo::EM_ConstantExpressionUnevaluated); 15846 Info.InConstantContext = true; 15847 Info.CheckingPotentialConstantExpression = true; 15848 15849 // Fabricate a call stack frame to give the arguments a plausible cover story. 15850 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15851 15852 APValue ResultScratch; 15853 Evaluate(ResultScratch, Info, E); 15854 return Diags.empty(); 15855 } 15856 15857 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15858 unsigned Type) const { 15859 if (!getType()->isPointerType()) 15860 return false; 15861 15862 Expr::EvalStatus Status; 15863 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15864 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15865 } 15866 15867 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 15868 EvalInfo &Info) { 15869 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 15870 return false; 15871 15872 LValue String; 15873 15874 if (!EvaluatePointer(E, String, Info)) 15875 return false; 15876 15877 QualType CharTy = E->getType()->getPointeeType(); 15878 15879 // Fast path: if it's a string literal, search the string value. 15880 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 15881 String.getLValueBase().dyn_cast<const Expr *>())) { 15882 StringRef Str = S->getBytes(); 15883 int64_t Off = String.Offset.getQuantity(); 15884 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 15885 S->getCharByteWidth() == 1 && 15886 // FIXME: Add fast-path for wchar_t too. 15887 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 15888 Str = Str.substr(Off); 15889 15890 StringRef::size_type Pos = Str.find(0); 15891 if (Pos != StringRef::npos) 15892 Str = Str.substr(0, Pos); 15893 15894 Result = Str.size(); 15895 return true; 15896 } 15897 15898 // Fall through to slow path. 15899 } 15900 15901 // Slow path: scan the bytes of the string looking for the terminating 0. 15902 for (uint64_t Strlen = 0; /**/; ++Strlen) { 15903 APValue Char; 15904 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 15905 !Char.isInt()) 15906 return false; 15907 if (!Char.getInt()) { 15908 Result = Strlen; 15909 return true; 15910 } 15911 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 15912 return false; 15913 } 15914 } 15915 15916 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 15917 Expr::EvalStatus Status; 15918 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15919 return EvaluateBuiltinStrLen(this, Result, Info); 15920 } 15921