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 SmallVector<PartialDiagnosticAt, 8> Notes; 3328 if (!VD->evaluateValue(Notes)) { 3329 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 3330 Notes.size() + 1) << VD; 3331 NoteLValueLocation(Info, Base); 3332 Info.addNotes(Notes); 3333 return false; 3334 } 3335 3336 // Check that the variable is actually usable in constant expressions. For a 3337 // const integral variable or a reference, we might have a non-constant 3338 // initializer that we can nonetheless evaluate the initializer for. Such 3339 // variables are not usable in constant expressions. In C++98, the 3340 // initializer also syntactically needs to be an ICE. 3341 // 3342 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3343 // expressions here; doing so would regress diagnostics for things like 3344 // reading from a volatile constexpr variable. 3345 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3346 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3347 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3348 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3349 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3350 NoteLValueLocation(Info, Base); 3351 } 3352 3353 // Never use the initializer of a weak variable, not even for constant 3354 // folding. We can't be sure that this is the definition that will be used. 3355 if (VD->isWeak()) { 3356 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3357 NoteLValueLocation(Info, Base); 3358 return false; 3359 } 3360 3361 Result = VD->getEvaluatedValue(); 3362 return true; 3363 } 3364 3365 /// Get the base index of the given base class within an APValue representing 3366 /// the given derived class. 3367 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3368 const CXXRecordDecl *Base) { 3369 Base = Base->getCanonicalDecl(); 3370 unsigned Index = 0; 3371 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3372 E = Derived->bases_end(); I != E; ++I, ++Index) { 3373 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3374 return Index; 3375 } 3376 3377 llvm_unreachable("base class missing from derived class's bases list"); 3378 } 3379 3380 /// Extract the value of a character from a string literal. 3381 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3382 uint64_t Index) { 3383 assert(!isa<SourceLocExpr>(Lit) && 3384 "SourceLocExpr should have already been converted to a StringLiteral"); 3385 3386 // FIXME: Support MakeStringConstant 3387 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3388 std::string Str; 3389 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3390 assert(Index <= Str.size() && "Index too large"); 3391 return APSInt::getUnsigned(Str.c_str()[Index]); 3392 } 3393 3394 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3395 Lit = PE->getFunctionName(); 3396 const StringLiteral *S = cast<StringLiteral>(Lit); 3397 const ConstantArrayType *CAT = 3398 Info.Ctx.getAsConstantArrayType(S->getType()); 3399 assert(CAT && "string literal isn't an array"); 3400 QualType CharType = CAT->getElementType(); 3401 assert(CharType->isIntegerType() && "unexpected character type"); 3402 3403 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3404 CharType->isUnsignedIntegerType()); 3405 if (Index < S->getLength()) 3406 Value = S->getCodeUnit(Index); 3407 return Value; 3408 } 3409 3410 // Expand a string literal into an array of characters. 3411 // 3412 // FIXME: This is inefficient; we should probably introduce something similar 3413 // to the LLVM ConstantDataArray to make this cheaper. 3414 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3415 APValue &Result, 3416 QualType AllocType = QualType()) { 3417 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3418 AllocType.isNull() ? S->getType() : AllocType); 3419 assert(CAT && "string literal isn't an array"); 3420 QualType CharType = CAT->getElementType(); 3421 assert(CharType->isIntegerType() && "unexpected character type"); 3422 3423 unsigned Elts = CAT->getSize().getZExtValue(); 3424 Result = APValue(APValue::UninitArray(), 3425 std::min(S->getLength(), Elts), Elts); 3426 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3427 CharType->isUnsignedIntegerType()); 3428 if (Result.hasArrayFiller()) 3429 Result.getArrayFiller() = APValue(Value); 3430 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3431 Value = S->getCodeUnit(I); 3432 Result.getArrayInitializedElt(I) = APValue(Value); 3433 } 3434 } 3435 3436 // Expand an array so that it has more than Index filled elements. 3437 static void expandArray(APValue &Array, unsigned Index) { 3438 unsigned Size = Array.getArraySize(); 3439 assert(Index < Size); 3440 3441 // Always at least double the number of elements for which we store a value. 3442 unsigned OldElts = Array.getArrayInitializedElts(); 3443 unsigned NewElts = std::max(Index+1, OldElts * 2); 3444 NewElts = std::min(Size, std::max(NewElts, 8u)); 3445 3446 // Copy the data across. 3447 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3448 for (unsigned I = 0; I != OldElts; ++I) 3449 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3450 for (unsigned I = OldElts; I != NewElts; ++I) 3451 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3452 if (NewValue.hasArrayFiller()) 3453 NewValue.getArrayFiller() = Array.getArrayFiller(); 3454 Array.swap(NewValue); 3455 } 3456 3457 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3458 /// conversion. If it's of class type, we may assume that the copy operation 3459 /// is trivial. Note that this is never true for a union type with fields 3460 /// (because the copy always "reads" the active member) and always true for 3461 /// a non-class type. 3462 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3463 static bool isReadByLvalueToRvalueConversion(QualType T) { 3464 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3465 return !RD || isReadByLvalueToRvalueConversion(RD); 3466 } 3467 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3468 // FIXME: A trivial copy of a union copies the object representation, even if 3469 // the union is empty. 3470 if (RD->isUnion()) 3471 return !RD->field_empty(); 3472 if (RD->isEmpty()) 3473 return false; 3474 3475 for (auto *Field : RD->fields()) 3476 if (!Field->isUnnamedBitfield() && 3477 isReadByLvalueToRvalueConversion(Field->getType())) 3478 return true; 3479 3480 for (auto &BaseSpec : RD->bases()) 3481 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3482 return true; 3483 3484 return false; 3485 } 3486 3487 /// Diagnose an attempt to read from any unreadable field within the specified 3488 /// type, which might be a class type. 3489 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3490 QualType T) { 3491 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3492 if (!RD) 3493 return false; 3494 3495 if (!RD->hasMutableFields()) 3496 return false; 3497 3498 for (auto *Field : RD->fields()) { 3499 // If we're actually going to read this field in some way, then it can't 3500 // be mutable. If we're in a union, then assigning to a mutable field 3501 // (even an empty one) can change the active member, so that's not OK. 3502 // FIXME: Add core issue number for the union case. 3503 if (Field->isMutable() && 3504 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3505 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3506 Info.Note(Field->getLocation(), diag::note_declared_at); 3507 return true; 3508 } 3509 3510 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3511 return true; 3512 } 3513 3514 for (auto &BaseSpec : RD->bases()) 3515 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3516 return true; 3517 3518 // All mutable fields were empty, and thus not actually read. 3519 return false; 3520 } 3521 3522 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3523 APValue::LValueBase Base, 3524 bool MutableSubobject = false) { 3525 // A temporary or transient heap allocation we created. 3526 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3527 return true; 3528 3529 switch (Info.IsEvaluatingDecl) { 3530 case EvalInfo::EvaluatingDeclKind::None: 3531 return false; 3532 3533 case EvalInfo::EvaluatingDeclKind::Ctor: 3534 // The variable whose initializer we're evaluating. 3535 if (Info.EvaluatingDecl == Base) 3536 return true; 3537 3538 // A temporary lifetime-extended by the variable whose initializer we're 3539 // evaluating. 3540 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3541 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3542 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3543 return false; 3544 3545 case EvalInfo::EvaluatingDeclKind::Dtor: 3546 // C++2a [expr.const]p6: 3547 // [during constant destruction] the lifetime of a and its non-mutable 3548 // subobjects (but not its mutable subobjects) [are] considered to start 3549 // within e. 3550 if (MutableSubobject || Base != Info.EvaluatingDecl) 3551 return false; 3552 // FIXME: We can meaningfully extend this to cover non-const objects, but 3553 // we will need special handling: we should be able to access only 3554 // subobjects of such objects that are themselves declared const. 3555 QualType T = getType(Base); 3556 return T.isConstQualified() || T->isReferenceType(); 3557 } 3558 3559 llvm_unreachable("unknown evaluating decl kind"); 3560 } 3561 3562 namespace { 3563 /// A handle to a complete object (an object that is not a subobject of 3564 /// another object). 3565 struct CompleteObject { 3566 /// The identity of the object. 3567 APValue::LValueBase Base; 3568 /// The value of the complete object. 3569 APValue *Value; 3570 /// The type of the complete object. 3571 QualType Type; 3572 3573 CompleteObject() : Value(nullptr) {} 3574 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3575 : Base(Base), Value(Value), Type(Type) {} 3576 3577 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3578 // If this isn't a "real" access (eg, if it's just accessing the type 3579 // info), allow it. We assume the type doesn't change dynamically for 3580 // subobjects of constexpr objects (even though we'd hit UB here if it 3581 // did). FIXME: Is this right? 3582 if (!isAnyAccess(AK)) 3583 return true; 3584 3585 // In C++14 onwards, it is permitted to read a mutable member whose 3586 // lifetime began within the evaluation. 3587 // FIXME: Should we also allow this in C++11? 3588 if (!Info.getLangOpts().CPlusPlus14) 3589 return false; 3590 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3591 } 3592 3593 explicit operator bool() const { return !Type.isNull(); } 3594 }; 3595 } // end anonymous namespace 3596 3597 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3598 bool IsMutable = false) { 3599 // C++ [basic.type.qualifier]p1: 3600 // - A const object is an object of type const T or a non-mutable subobject 3601 // of a const object. 3602 if (ObjType.isConstQualified() && !IsMutable) 3603 SubobjType.addConst(); 3604 // - A volatile object is an object of type const T or a subobject of a 3605 // volatile object. 3606 if (ObjType.isVolatileQualified()) 3607 SubobjType.addVolatile(); 3608 return SubobjType; 3609 } 3610 3611 /// Find the designated sub-object of an rvalue. 3612 template<typename SubobjectHandler> 3613 typename SubobjectHandler::result_type 3614 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3615 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3616 if (Sub.Invalid) 3617 // A diagnostic will have already been produced. 3618 return handler.failed(); 3619 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3620 if (Info.getLangOpts().CPlusPlus11) 3621 Info.FFDiag(E, Sub.isOnePastTheEnd() 3622 ? diag::note_constexpr_access_past_end 3623 : diag::note_constexpr_access_unsized_array) 3624 << handler.AccessKind; 3625 else 3626 Info.FFDiag(E); 3627 return handler.failed(); 3628 } 3629 3630 APValue *O = Obj.Value; 3631 QualType ObjType = Obj.Type; 3632 const FieldDecl *LastField = nullptr; 3633 const FieldDecl *VolatileField = nullptr; 3634 3635 // Walk the designator's path to find the subobject. 3636 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3637 // Reading an indeterminate value is undefined, but assigning over one is OK. 3638 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3639 (O->isIndeterminate() && 3640 !isValidIndeterminateAccess(handler.AccessKind))) { 3641 if (!Info.checkingPotentialConstantExpression()) 3642 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3643 << handler.AccessKind << O->isIndeterminate(); 3644 return handler.failed(); 3645 } 3646 3647 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3648 // const and volatile semantics are not applied on an object under 3649 // {con,de}struction. 3650 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3651 ObjType->isRecordType() && 3652 Info.isEvaluatingCtorDtor( 3653 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3654 Sub.Entries.begin() + I)) != 3655 ConstructionPhase::None) { 3656 ObjType = Info.Ctx.getCanonicalType(ObjType); 3657 ObjType.removeLocalConst(); 3658 ObjType.removeLocalVolatile(); 3659 } 3660 3661 // If this is our last pass, check that the final object type is OK. 3662 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3663 // Accesses to volatile objects are prohibited. 3664 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3665 if (Info.getLangOpts().CPlusPlus) { 3666 int DiagKind; 3667 SourceLocation Loc; 3668 const NamedDecl *Decl = nullptr; 3669 if (VolatileField) { 3670 DiagKind = 2; 3671 Loc = VolatileField->getLocation(); 3672 Decl = VolatileField; 3673 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3674 DiagKind = 1; 3675 Loc = VD->getLocation(); 3676 Decl = VD; 3677 } else { 3678 DiagKind = 0; 3679 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3680 Loc = E->getExprLoc(); 3681 } 3682 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3683 << handler.AccessKind << DiagKind << Decl; 3684 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3685 } else { 3686 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3687 } 3688 return handler.failed(); 3689 } 3690 3691 // If we are reading an object of class type, there may still be more 3692 // things we need to check: if there are any mutable subobjects, we 3693 // cannot perform this read. (This only happens when performing a trivial 3694 // copy or assignment.) 3695 if (ObjType->isRecordType() && 3696 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3697 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3698 return handler.failed(); 3699 } 3700 3701 if (I == N) { 3702 if (!handler.found(*O, ObjType)) 3703 return false; 3704 3705 // If we modified a bit-field, truncate it to the right width. 3706 if (isModification(handler.AccessKind) && 3707 LastField && LastField->isBitField() && 3708 !truncateBitfieldValue(Info, E, *O, LastField)) 3709 return false; 3710 3711 return true; 3712 } 3713 3714 LastField = nullptr; 3715 if (ObjType->isArrayType()) { 3716 // Next subobject is an array element. 3717 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3718 assert(CAT && "vla in literal type?"); 3719 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3720 if (CAT->getSize().ule(Index)) { 3721 // Note, it should not be possible to form a pointer with a valid 3722 // designator which points more than one past the end of the array. 3723 if (Info.getLangOpts().CPlusPlus11) 3724 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3725 << handler.AccessKind; 3726 else 3727 Info.FFDiag(E); 3728 return handler.failed(); 3729 } 3730 3731 ObjType = CAT->getElementType(); 3732 3733 if (O->getArrayInitializedElts() > Index) 3734 O = &O->getArrayInitializedElt(Index); 3735 else if (!isRead(handler.AccessKind)) { 3736 expandArray(*O, Index); 3737 O = &O->getArrayInitializedElt(Index); 3738 } else 3739 O = &O->getArrayFiller(); 3740 } else if (ObjType->isAnyComplexType()) { 3741 // Next subobject is a complex number. 3742 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3743 if (Index > 1) { 3744 if (Info.getLangOpts().CPlusPlus11) 3745 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3746 << handler.AccessKind; 3747 else 3748 Info.FFDiag(E); 3749 return handler.failed(); 3750 } 3751 3752 ObjType = getSubobjectType( 3753 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3754 3755 assert(I == N - 1 && "extracting subobject of scalar?"); 3756 if (O->isComplexInt()) { 3757 return handler.found(Index ? O->getComplexIntImag() 3758 : O->getComplexIntReal(), ObjType); 3759 } else { 3760 assert(O->isComplexFloat()); 3761 return handler.found(Index ? O->getComplexFloatImag() 3762 : O->getComplexFloatReal(), ObjType); 3763 } 3764 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3765 if (Field->isMutable() && 3766 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3767 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3768 << handler.AccessKind << Field; 3769 Info.Note(Field->getLocation(), diag::note_declared_at); 3770 return handler.failed(); 3771 } 3772 3773 // Next subobject is a class, struct or union field. 3774 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3775 if (RD->isUnion()) { 3776 const FieldDecl *UnionField = O->getUnionField(); 3777 if (!UnionField || 3778 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3779 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3780 // Placement new onto an inactive union member makes it active. 3781 O->setUnion(Field, APValue()); 3782 } else { 3783 // FIXME: If O->getUnionValue() is absent, report that there's no 3784 // active union member rather than reporting the prior active union 3785 // member. We'll need to fix nullptr_t to not use APValue() as its 3786 // representation first. 3787 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3788 << handler.AccessKind << Field << !UnionField << UnionField; 3789 return handler.failed(); 3790 } 3791 } 3792 O = &O->getUnionValue(); 3793 } else 3794 O = &O->getStructField(Field->getFieldIndex()); 3795 3796 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3797 LastField = Field; 3798 if (Field->getType().isVolatileQualified()) 3799 VolatileField = Field; 3800 } else { 3801 // Next subobject is a base class. 3802 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3803 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3804 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3805 3806 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3807 } 3808 } 3809 } 3810 3811 namespace { 3812 struct ExtractSubobjectHandler { 3813 EvalInfo &Info; 3814 const Expr *E; 3815 APValue &Result; 3816 const AccessKinds AccessKind; 3817 3818 typedef bool result_type; 3819 bool failed() { return false; } 3820 bool found(APValue &Subobj, QualType SubobjType) { 3821 Result = Subobj; 3822 if (AccessKind == AK_ReadObjectRepresentation) 3823 return true; 3824 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3825 } 3826 bool found(APSInt &Value, QualType SubobjType) { 3827 Result = APValue(Value); 3828 return true; 3829 } 3830 bool found(APFloat &Value, QualType SubobjType) { 3831 Result = APValue(Value); 3832 return true; 3833 } 3834 }; 3835 } // end anonymous namespace 3836 3837 /// Extract the designated sub-object of an rvalue. 3838 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3839 const CompleteObject &Obj, 3840 const SubobjectDesignator &Sub, APValue &Result, 3841 AccessKinds AK = AK_Read) { 3842 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3843 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3844 return findSubobject(Info, E, Obj, Sub, Handler); 3845 } 3846 3847 namespace { 3848 struct ModifySubobjectHandler { 3849 EvalInfo &Info; 3850 APValue &NewVal; 3851 const Expr *E; 3852 3853 typedef bool result_type; 3854 static const AccessKinds AccessKind = AK_Assign; 3855 3856 bool checkConst(QualType QT) { 3857 // Assigning to a const object has undefined behavior. 3858 if (QT.isConstQualified()) { 3859 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3860 return false; 3861 } 3862 return true; 3863 } 3864 3865 bool failed() { return false; } 3866 bool found(APValue &Subobj, QualType SubobjType) { 3867 if (!checkConst(SubobjType)) 3868 return false; 3869 // We've been given ownership of NewVal, so just swap it in. 3870 Subobj.swap(NewVal); 3871 return true; 3872 } 3873 bool found(APSInt &Value, QualType SubobjType) { 3874 if (!checkConst(SubobjType)) 3875 return false; 3876 if (!NewVal.isInt()) { 3877 // Maybe trying to write a cast pointer value into a complex? 3878 Info.FFDiag(E); 3879 return false; 3880 } 3881 Value = NewVal.getInt(); 3882 return true; 3883 } 3884 bool found(APFloat &Value, QualType SubobjType) { 3885 if (!checkConst(SubobjType)) 3886 return false; 3887 Value = NewVal.getFloat(); 3888 return true; 3889 } 3890 }; 3891 } // end anonymous namespace 3892 3893 const AccessKinds ModifySubobjectHandler::AccessKind; 3894 3895 /// Update the designated sub-object of an rvalue to the given value. 3896 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3897 const CompleteObject &Obj, 3898 const SubobjectDesignator &Sub, 3899 APValue &NewVal) { 3900 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3901 return findSubobject(Info, E, Obj, Sub, Handler); 3902 } 3903 3904 /// Find the position where two subobject designators diverge, or equivalently 3905 /// the length of the common initial subsequence. 3906 static unsigned FindDesignatorMismatch(QualType ObjType, 3907 const SubobjectDesignator &A, 3908 const SubobjectDesignator &B, 3909 bool &WasArrayIndex) { 3910 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3911 for (/**/; I != N; ++I) { 3912 if (!ObjType.isNull() && 3913 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3914 // Next subobject is an array element. 3915 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3916 WasArrayIndex = true; 3917 return I; 3918 } 3919 if (ObjType->isAnyComplexType()) 3920 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3921 else 3922 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3923 } else { 3924 if (A.Entries[I].getAsBaseOrMember() != 3925 B.Entries[I].getAsBaseOrMember()) { 3926 WasArrayIndex = false; 3927 return I; 3928 } 3929 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3930 // Next subobject is a field. 3931 ObjType = FD->getType(); 3932 else 3933 // Next subobject is a base class. 3934 ObjType = QualType(); 3935 } 3936 } 3937 WasArrayIndex = false; 3938 return I; 3939 } 3940 3941 /// Determine whether the given subobject designators refer to elements of the 3942 /// same array object. 3943 static bool AreElementsOfSameArray(QualType ObjType, 3944 const SubobjectDesignator &A, 3945 const SubobjectDesignator &B) { 3946 if (A.Entries.size() != B.Entries.size()) 3947 return false; 3948 3949 bool IsArray = A.MostDerivedIsArrayElement; 3950 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3951 // A is a subobject of the array element. 3952 return false; 3953 3954 // If A (and B) designates an array element, the last entry will be the array 3955 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3956 // of length 1' case, and the entire path must match. 3957 bool WasArrayIndex; 3958 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3959 return CommonLength >= A.Entries.size() - IsArray; 3960 } 3961 3962 /// Find the complete object to which an LValue refers. 3963 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3964 AccessKinds AK, const LValue &LVal, 3965 QualType LValType) { 3966 if (LVal.InvalidBase) { 3967 Info.FFDiag(E); 3968 return CompleteObject(); 3969 } 3970 3971 if (!LVal.Base) { 3972 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3973 return CompleteObject(); 3974 } 3975 3976 CallStackFrame *Frame = nullptr; 3977 unsigned Depth = 0; 3978 if (LVal.getLValueCallIndex()) { 3979 std::tie(Frame, Depth) = 3980 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3981 if (!Frame) { 3982 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3983 << AK << LVal.Base.is<const ValueDecl*>(); 3984 NoteLValueLocation(Info, LVal.Base); 3985 return CompleteObject(); 3986 } 3987 } 3988 3989 bool IsAccess = isAnyAccess(AK); 3990 3991 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3992 // is not a constant expression (even if the object is non-volatile). We also 3993 // apply this rule to C++98, in order to conform to the expected 'volatile' 3994 // semantics. 3995 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3996 if (Info.getLangOpts().CPlusPlus) 3997 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3998 << AK << LValType; 3999 else 4000 Info.FFDiag(E); 4001 return CompleteObject(); 4002 } 4003 4004 // Compute value storage location and type of base object. 4005 APValue *BaseVal = nullptr; 4006 QualType BaseType = getType(LVal.Base); 4007 4008 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 4009 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4010 // This is the object whose initializer we're evaluating, so its lifetime 4011 // started in the current evaluation. 4012 BaseVal = Info.EvaluatingDeclValue; 4013 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4014 // Allow reading from a GUID declaration. 4015 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4016 if (isModification(AK)) { 4017 // All the remaining cases do not permit modification of the object. 4018 Info.FFDiag(E, diag::note_constexpr_modify_global); 4019 return CompleteObject(); 4020 } 4021 APValue &V = GD->getAsAPValue(); 4022 if (V.isAbsent()) { 4023 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4024 << GD->getType(); 4025 return CompleteObject(); 4026 } 4027 return CompleteObject(LVal.Base, &V, GD->getType()); 4028 } 4029 4030 // Allow reading from template parameter objects. 4031 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4032 if (isModification(AK)) { 4033 Info.FFDiag(E, diag::note_constexpr_modify_global); 4034 return CompleteObject(); 4035 } 4036 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4037 TPO->getType()); 4038 } 4039 4040 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4041 // In C++11, constexpr, non-volatile variables initialized with constant 4042 // expressions are constant expressions too. Inside constexpr functions, 4043 // parameters are constant expressions even if they're non-const. 4044 // In C++1y, objects local to a constant expression (those with a Frame) are 4045 // both readable and writable inside constant expressions. 4046 // In C, such things can also be folded, although they are not ICEs. 4047 const VarDecl *VD = dyn_cast<VarDecl>(D); 4048 if (VD) { 4049 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4050 VD = VDef; 4051 } 4052 if (!VD || VD->isInvalidDecl()) { 4053 Info.FFDiag(E); 4054 return CompleteObject(); 4055 } 4056 4057 bool IsConstant = BaseType.isConstant(Info.Ctx); 4058 4059 // Unless we're looking at a local variable or argument in a constexpr call, 4060 // the variable we're reading must be const. 4061 if (!Frame) { 4062 if (IsAccess && isa<ParmVarDecl>(VD)) { 4063 // Access of a parameter that's not associated with a frame isn't going 4064 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4065 // suitable diagnostic. 4066 } else if (Info.getLangOpts().CPlusPlus14 && 4067 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4068 // OK, we can read and modify an object if we're in the process of 4069 // evaluating its initializer, because its lifetime began in this 4070 // evaluation. 4071 } else if (isModification(AK)) { 4072 // All the remaining cases do not permit modification of the object. 4073 Info.FFDiag(E, diag::note_constexpr_modify_global); 4074 return CompleteObject(); 4075 } else if (VD->isConstexpr()) { 4076 // OK, we can read this variable. 4077 } else if (BaseType->isIntegralOrEnumerationType()) { 4078 if (!IsConstant) { 4079 if (!IsAccess) 4080 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4081 if (Info.getLangOpts().CPlusPlus) { 4082 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4083 Info.Note(VD->getLocation(), diag::note_declared_at); 4084 } else { 4085 Info.FFDiag(E); 4086 } 4087 return CompleteObject(); 4088 } 4089 } else if (!IsAccess) { 4090 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4091 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4092 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4093 // This variable might end up being constexpr. Don't diagnose it yet. 4094 } else if (IsConstant) { 4095 // Keep evaluating to see what we can do. In particular, we support 4096 // folding of const floating-point types, in order to make static const 4097 // data members of such types (supported as an extension) more useful. 4098 if (Info.getLangOpts().CPlusPlus) { 4099 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4100 ? diag::note_constexpr_ltor_non_constexpr 4101 : diag::note_constexpr_ltor_non_integral, 1) 4102 << VD << BaseType; 4103 Info.Note(VD->getLocation(), diag::note_declared_at); 4104 } else { 4105 Info.CCEDiag(E); 4106 } 4107 } else { 4108 // Never allow reading a non-const value. 4109 if (Info.getLangOpts().CPlusPlus) { 4110 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4111 ? diag::note_constexpr_ltor_non_constexpr 4112 : diag::note_constexpr_ltor_non_integral, 1) 4113 << VD << BaseType; 4114 Info.Note(VD->getLocation(), diag::note_declared_at); 4115 } else { 4116 Info.FFDiag(E); 4117 } 4118 return CompleteObject(); 4119 } 4120 } 4121 4122 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4123 return CompleteObject(); 4124 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4125 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4126 if (!Alloc) { 4127 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4128 return CompleteObject(); 4129 } 4130 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4131 LVal.Base.getDynamicAllocType()); 4132 } else { 4133 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4134 4135 if (!Frame) { 4136 if (const MaterializeTemporaryExpr *MTE = 4137 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4138 assert(MTE->getStorageDuration() == SD_Static && 4139 "should have a frame for a non-global materialized temporary"); 4140 4141 // C++20 [expr.const]p4: [DR2126] 4142 // An object or reference is usable in constant expressions if it is 4143 // - a temporary object of non-volatile const-qualified literal type 4144 // whose lifetime is extended to that of a variable that is usable 4145 // in constant expressions 4146 // 4147 // C++20 [expr.const]p5: 4148 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4149 // - a non-volatile glvalue that refers to an object that is usable 4150 // in constant expressions, or 4151 // - a non-volatile glvalue of literal type that refers to a 4152 // non-volatile object whose lifetime began within the evaluation 4153 // of E; 4154 // 4155 // C++11 misses the 'began within the evaluation of e' check and 4156 // instead allows all temporaries, including things like: 4157 // int &&r = 1; 4158 // int x = ++r; 4159 // constexpr int k = r; 4160 // Therefore we use the C++14-onwards rules in C++11 too. 4161 // 4162 // Note that temporaries whose lifetimes began while evaluating a 4163 // variable's constructor are not usable while evaluating the 4164 // corresponding destructor, not even if they're of const-qualified 4165 // types. 4166 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4167 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4168 if (!IsAccess) 4169 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4170 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4171 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4172 return CompleteObject(); 4173 } 4174 4175 BaseVal = MTE->getOrCreateValue(false); 4176 assert(BaseVal && "got reference to unevaluated temporary"); 4177 } else { 4178 if (!IsAccess) 4179 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4180 APValue Val; 4181 LVal.moveInto(Val); 4182 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4183 << AK 4184 << Val.getAsString(Info.Ctx, 4185 Info.Ctx.getLValueReferenceType(LValType)); 4186 NoteLValueLocation(Info, LVal.Base); 4187 return CompleteObject(); 4188 } 4189 } else { 4190 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4191 assert(BaseVal && "missing value for temporary"); 4192 } 4193 } 4194 4195 // In C++14, we can't safely access any mutable state when we might be 4196 // evaluating after an unmodeled side effect. Parameters are modeled as state 4197 // in the caller, but aren't visible once the call returns, so they can be 4198 // modified in a speculatively-evaluated call. 4199 // 4200 // FIXME: Not all local state is mutable. Allow local constant subobjects 4201 // to be read here (but take care with 'mutable' fields). 4202 unsigned VisibleDepth = Depth; 4203 if (llvm::isa_and_nonnull<ParmVarDecl>( 4204 LVal.Base.dyn_cast<const ValueDecl *>())) 4205 ++VisibleDepth; 4206 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4207 Info.EvalStatus.HasSideEffects) || 4208 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4209 return CompleteObject(); 4210 4211 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4212 } 4213 4214 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4215 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4216 /// glvalue referred to by an entity of reference type. 4217 /// 4218 /// \param Info - Information about the ongoing evaluation. 4219 /// \param Conv - The expression for which we are performing the conversion. 4220 /// Used for diagnostics. 4221 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4222 /// case of a non-class type). 4223 /// \param LVal - The glvalue on which we are attempting to perform this action. 4224 /// \param RVal - The produced value will be placed here. 4225 /// \param WantObjectRepresentation - If true, we're looking for the object 4226 /// representation rather than the value, and in particular, 4227 /// there is no requirement that the result be fully initialized. 4228 static bool 4229 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4230 const LValue &LVal, APValue &RVal, 4231 bool WantObjectRepresentation = false) { 4232 if (LVal.Designator.Invalid) 4233 return false; 4234 4235 // Check for special cases where there is no existing APValue to look at. 4236 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4237 4238 AccessKinds AK = 4239 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4240 4241 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4242 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4243 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4244 // initializer until now for such expressions. Such an expression can't be 4245 // an ICE in C, so this only matters for fold. 4246 if (Type.isVolatileQualified()) { 4247 Info.FFDiag(Conv); 4248 return false; 4249 } 4250 APValue Lit; 4251 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4252 return false; 4253 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4254 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4255 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4256 // Special-case character extraction so we don't have to construct an 4257 // APValue for the whole string. 4258 assert(LVal.Designator.Entries.size() <= 1 && 4259 "Can only read characters from string literals"); 4260 if (LVal.Designator.Entries.empty()) { 4261 // Fail for now for LValue to RValue conversion of an array. 4262 // (This shouldn't show up in C/C++, but it could be triggered by a 4263 // weird EvaluateAsRValue call from a tool.) 4264 Info.FFDiag(Conv); 4265 return false; 4266 } 4267 if (LVal.Designator.isOnePastTheEnd()) { 4268 if (Info.getLangOpts().CPlusPlus11) 4269 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4270 else 4271 Info.FFDiag(Conv); 4272 return false; 4273 } 4274 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4275 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4276 return true; 4277 } 4278 } 4279 4280 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4281 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4282 } 4283 4284 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4285 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4286 QualType LValType, APValue &Val) { 4287 if (LVal.Designator.Invalid) 4288 return false; 4289 4290 if (!Info.getLangOpts().CPlusPlus14) { 4291 Info.FFDiag(E); 4292 return false; 4293 } 4294 4295 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4296 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4297 } 4298 4299 namespace { 4300 struct CompoundAssignSubobjectHandler { 4301 EvalInfo &Info; 4302 const CompoundAssignOperator *E; 4303 QualType PromotedLHSType; 4304 BinaryOperatorKind Opcode; 4305 const APValue &RHS; 4306 4307 static const AccessKinds AccessKind = AK_Assign; 4308 4309 typedef bool result_type; 4310 4311 bool checkConst(QualType QT) { 4312 // Assigning to a const object has undefined behavior. 4313 if (QT.isConstQualified()) { 4314 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4315 return false; 4316 } 4317 return true; 4318 } 4319 4320 bool failed() { return false; } 4321 bool found(APValue &Subobj, QualType SubobjType) { 4322 switch (Subobj.getKind()) { 4323 case APValue::Int: 4324 return found(Subobj.getInt(), SubobjType); 4325 case APValue::Float: 4326 return found(Subobj.getFloat(), SubobjType); 4327 case APValue::ComplexInt: 4328 case APValue::ComplexFloat: 4329 // FIXME: Implement complex compound assignment. 4330 Info.FFDiag(E); 4331 return false; 4332 case APValue::LValue: 4333 return foundPointer(Subobj, SubobjType); 4334 case APValue::Vector: 4335 return foundVector(Subobj, SubobjType); 4336 default: 4337 // FIXME: can this happen? 4338 Info.FFDiag(E); 4339 return false; 4340 } 4341 } 4342 4343 bool foundVector(APValue &Value, QualType SubobjType) { 4344 if (!checkConst(SubobjType)) 4345 return false; 4346 4347 if (!SubobjType->isVectorType()) { 4348 Info.FFDiag(E); 4349 return false; 4350 } 4351 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4352 } 4353 4354 bool found(APSInt &Value, QualType SubobjType) { 4355 if (!checkConst(SubobjType)) 4356 return false; 4357 4358 if (!SubobjType->isIntegerType()) { 4359 // We don't support compound assignment on integer-cast-to-pointer 4360 // values. 4361 Info.FFDiag(E); 4362 return false; 4363 } 4364 4365 if (RHS.isInt()) { 4366 APSInt LHS = 4367 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4368 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4369 return false; 4370 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4371 return true; 4372 } else if (RHS.isFloat()) { 4373 const FPOptions FPO = E->getFPFeaturesInEffect( 4374 Info.Ctx.getLangOpts()); 4375 APFloat FValue(0.0); 4376 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4377 PromotedLHSType, FValue) && 4378 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4379 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4380 Value); 4381 } 4382 4383 Info.FFDiag(E); 4384 return false; 4385 } 4386 bool found(APFloat &Value, QualType SubobjType) { 4387 return checkConst(SubobjType) && 4388 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4389 Value) && 4390 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4391 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4392 } 4393 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4394 if (!checkConst(SubobjType)) 4395 return false; 4396 4397 QualType PointeeType; 4398 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4399 PointeeType = PT->getPointeeType(); 4400 4401 if (PointeeType.isNull() || !RHS.isInt() || 4402 (Opcode != BO_Add && Opcode != BO_Sub)) { 4403 Info.FFDiag(E); 4404 return false; 4405 } 4406 4407 APSInt Offset = RHS.getInt(); 4408 if (Opcode == BO_Sub) 4409 negateAsSigned(Offset); 4410 4411 LValue LVal; 4412 LVal.setFrom(Info.Ctx, Subobj); 4413 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4414 return false; 4415 LVal.moveInto(Subobj); 4416 return true; 4417 } 4418 }; 4419 } // end anonymous namespace 4420 4421 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4422 4423 /// Perform a compound assignment of LVal <op>= RVal. 4424 static bool handleCompoundAssignment(EvalInfo &Info, 4425 const CompoundAssignOperator *E, 4426 const LValue &LVal, QualType LValType, 4427 QualType PromotedLValType, 4428 BinaryOperatorKind Opcode, 4429 const APValue &RVal) { 4430 if (LVal.Designator.Invalid) 4431 return false; 4432 4433 if (!Info.getLangOpts().CPlusPlus14) { 4434 Info.FFDiag(E); 4435 return false; 4436 } 4437 4438 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4439 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4440 RVal }; 4441 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4442 } 4443 4444 namespace { 4445 struct IncDecSubobjectHandler { 4446 EvalInfo &Info; 4447 const UnaryOperator *E; 4448 AccessKinds AccessKind; 4449 APValue *Old; 4450 4451 typedef bool result_type; 4452 4453 bool checkConst(QualType QT) { 4454 // Assigning to a const object has undefined behavior. 4455 if (QT.isConstQualified()) { 4456 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4457 return false; 4458 } 4459 return true; 4460 } 4461 4462 bool failed() { return false; } 4463 bool found(APValue &Subobj, QualType SubobjType) { 4464 // Stash the old value. Also clear Old, so we don't clobber it later 4465 // if we're post-incrementing a complex. 4466 if (Old) { 4467 *Old = Subobj; 4468 Old = nullptr; 4469 } 4470 4471 switch (Subobj.getKind()) { 4472 case APValue::Int: 4473 return found(Subobj.getInt(), SubobjType); 4474 case APValue::Float: 4475 return found(Subobj.getFloat(), SubobjType); 4476 case APValue::ComplexInt: 4477 return found(Subobj.getComplexIntReal(), 4478 SubobjType->castAs<ComplexType>()->getElementType() 4479 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4480 case APValue::ComplexFloat: 4481 return found(Subobj.getComplexFloatReal(), 4482 SubobjType->castAs<ComplexType>()->getElementType() 4483 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4484 case APValue::LValue: 4485 return foundPointer(Subobj, SubobjType); 4486 default: 4487 // FIXME: can this happen? 4488 Info.FFDiag(E); 4489 return false; 4490 } 4491 } 4492 bool found(APSInt &Value, QualType SubobjType) { 4493 if (!checkConst(SubobjType)) 4494 return false; 4495 4496 if (!SubobjType->isIntegerType()) { 4497 // We don't support increment / decrement on integer-cast-to-pointer 4498 // values. 4499 Info.FFDiag(E); 4500 return false; 4501 } 4502 4503 if (Old) *Old = APValue(Value); 4504 4505 // bool arithmetic promotes to int, and the conversion back to bool 4506 // doesn't reduce mod 2^n, so special-case it. 4507 if (SubobjType->isBooleanType()) { 4508 if (AccessKind == AK_Increment) 4509 Value = 1; 4510 else 4511 Value = !Value; 4512 return true; 4513 } 4514 4515 bool WasNegative = Value.isNegative(); 4516 if (AccessKind == AK_Increment) { 4517 ++Value; 4518 4519 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4520 APSInt ActualValue(Value, /*IsUnsigned*/true); 4521 return HandleOverflow(Info, E, ActualValue, SubobjType); 4522 } 4523 } else { 4524 --Value; 4525 4526 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4527 unsigned BitWidth = Value.getBitWidth(); 4528 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4529 ActualValue.setBit(BitWidth); 4530 return HandleOverflow(Info, E, ActualValue, SubobjType); 4531 } 4532 } 4533 return true; 4534 } 4535 bool found(APFloat &Value, QualType SubobjType) { 4536 if (!checkConst(SubobjType)) 4537 return false; 4538 4539 if (Old) *Old = APValue(Value); 4540 4541 APFloat One(Value.getSemantics(), 1); 4542 if (AccessKind == AK_Increment) 4543 Value.add(One, APFloat::rmNearestTiesToEven); 4544 else 4545 Value.subtract(One, APFloat::rmNearestTiesToEven); 4546 return true; 4547 } 4548 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4549 if (!checkConst(SubobjType)) 4550 return false; 4551 4552 QualType PointeeType; 4553 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4554 PointeeType = PT->getPointeeType(); 4555 else { 4556 Info.FFDiag(E); 4557 return false; 4558 } 4559 4560 LValue LVal; 4561 LVal.setFrom(Info.Ctx, Subobj); 4562 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4563 AccessKind == AK_Increment ? 1 : -1)) 4564 return false; 4565 LVal.moveInto(Subobj); 4566 return true; 4567 } 4568 }; 4569 } // end anonymous namespace 4570 4571 /// Perform an increment or decrement on LVal. 4572 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4573 QualType LValType, bool IsIncrement, APValue *Old) { 4574 if (LVal.Designator.Invalid) 4575 return false; 4576 4577 if (!Info.getLangOpts().CPlusPlus14) { 4578 Info.FFDiag(E); 4579 return false; 4580 } 4581 4582 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4583 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4584 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4585 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4586 } 4587 4588 /// Build an lvalue for the object argument of a member function call. 4589 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4590 LValue &This) { 4591 if (Object->getType()->isPointerType() && Object->isPRValue()) 4592 return EvaluatePointer(Object, This, Info); 4593 4594 if (Object->isGLValue()) 4595 return EvaluateLValue(Object, This, Info); 4596 4597 if (Object->getType()->isLiteralType(Info.Ctx)) 4598 return EvaluateTemporary(Object, This, Info); 4599 4600 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4601 return false; 4602 } 4603 4604 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4605 /// lvalue referring to the result. 4606 /// 4607 /// \param Info - Information about the ongoing evaluation. 4608 /// \param LV - An lvalue referring to the base of the member pointer. 4609 /// \param RHS - The member pointer expression. 4610 /// \param IncludeMember - Specifies whether the member itself is included in 4611 /// the resulting LValue subobject designator. This is not possible when 4612 /// creating a bound member function. 4613 /// \return The field or method declaration to which the member pointer refers, 4614 /// or 0 if evaluation fails. 4615 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4616 QualType LVType, 4617 LValue &LV, 4618 const Expr *RHS, 4619 bool IncludeMember = true) { 4620 MemberPtr MemPtr; 4621 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4622 return nullptr; 4623 4624 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4625 // member value, the behavior is undefined. 4626 if (!MemPtr.getDecl()) { 4627 // FIXME: Specific diagnostic. 4628 Info.FFDiag(RHS); 4629 return nullptr; 4630 } 4631 4632 if (MemPtr.isDerivedMember()) { 4633 // This is a member of some derived class. Truncate LV appropriately. 4634 // The end of the derived-to-base path for the base object must match the 4635 // derived-to-base path for the member pointer. 4636 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4637 LV.Designator.Entries.size()) { 4638 Info.FFDiag(RHS); 4639 return nullptr; 4640 } 4641 unsigned PathLengthToMember = 4642 LV.Designator.Entries.size() - MemPtr.Path.size(); 4643 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4644 const CXXRecordDecl *LVDecl = getAsBaseClass( 4645 LV.Designator.Entries[PathLengthToMember + I]); 4646 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4647 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4648 Info.FFDiag(RHS); 4649 return nullptr; 4650 } 4651 } 4652 4653 // Truncate the lvalue to the appropriate derived class. 4654 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4655 PathLengthToMember)) 4656 return nullptr; 4657 } else if (!MemPtr.Path.empty()) { 4658 // Extend the LValue path with the member pointer's path. 4659 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4660 MemPtr.Path.size() + IncludeMember); 4661 4662 // Walk down to the appropriate base class. 4663 if (const PointerType *PT = LVType->getAs<PointerType>()) 4664 LVType = PT->getPointeeType(); 4665 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4666 assert(RD && "member pointer access on non-class-type expression"); 4667 // The first class in the path is that of the lvalue. 4668 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4669 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4670 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4671 return nullptr; 4672 RD = Base; 4673 } 4674 // Finally cast to the class containing the member. 4675 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4676 MemPtr.getContainingRecord())) 4677 return nullptr; 4678 } 4679 4680 // Add the member. Note that we cannot build bound member functions here. 4681 if (IncludeMember) { 4682 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4683 if (!HandleLValueMember(Info, RHS, LV, FD)) 4684 return nullptr; 4685 } else if (const IndirectFieldDecl *IFD = 4686 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4687 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4688 return nullptr; 4689 } else { 4690 llvm_unreachable("can't construct reference to bound member function"); 4691 } 4692 } 4693 4694 return MemPtr.getDecl(); 4695 } 4696 4697 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4698 const BinaryOperator *BO, 4699 LValue &LV, 4700 bool IncludeMember = true) { 4701 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4702 4703 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4704 if (Info.noteFailure()) { 4705 MemberPtr MemPtr; 4706 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4707 } 4708 return nullptr; 4709 } 4710 4711 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4712 BO->getRHS(), IncludeMember); 4713 } 4714 4715 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4716 /// the provided lvalue, which currently refers to the base object. 4717 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4718 LValue &Result) { 4719 SubobjectDesignator &D = Result.Designator; 4720 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4721 return false; 4722 4723 QualType TargetQT = E->getType(); 4724 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4725 TargetQT = PT->getPointeeType(); 4726 4727 // Check this cast lands within the final derived-to-base subobject path. 4728 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4729 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4730 << D.MostDerivedType << TargetQT; 4731 return false; 4732 } 4733 4734 // Check the type of the final cast. We don't need to check the path, 4735 // since a cast can only be formed if the path is unique. 4736 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4737 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4738 const CXXRecordDecl *FinalType; 4739 if (NewEntriesSize == D.MostDerivedPathLength) 4740 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4741 else 4742 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4743 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4744 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4745 << D.MostDerivedType << TargetQT; 4746 return false; 4747 } 4748 4749 // Truncate the lvalue to the appropriate derived class. 4750 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4751 } 4752 4753 /// Get the value to use for a default-initialized object of type T. 4754 /// Return false if it encounters something invalid. 4755 static bool getDefaultInitValue(QualType T, APValue &Result) { 4756 bool Success = true; 4757 if (auto *RD = T->getAsCXXRecordDecl()) { 4758 if (RD->isInvalidDecl()) { 4759 Result = APValue(); 4760 return false; 4761 } 4762 if (RD->isUnion()) { 4763 Result = APValue((const FieldDecl *)nullptr); 4764 return true; 4765 } 4766 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4767 std::distance(RD->field_begin(), RD->field_end())); 4768 4769 unsigned Index = 0; 4770 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4771 End = RD->bases_end(); 4772 I != End; ++I, ++Index) 4773 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4774 4775 for (const auto *I : RD->fields()) { 4776 if (I->isUnnamedBitfield()) 4777 continue; 4778 Success &= getDefaultInitValue(I->getType(), 4779 Result.getStructField(I->getFieldIndex())); 4780 } 4781 return Success; 4782 } 4783 4784 if (auto *AT = 4785 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4786 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4787 if (Result.hasArrayFiller()) 4788 Success &= 4789 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4790 4791 return Success; 4792 } 4793 4794 Result = APValue::IndeterminateValue(); 4795 return true; 4796 } 4797 4798 namespace { 4799 enum EvalStmtResult { 4800 /// Evaluation failed. 4801 ESR_Failed, 4802 /// Hit a 'return' statement. 4803 ESR_Returned, 4804 /// Evaluation succeeded. 4805 ESR_Succeeded, 4806 /// Hit a 'continue' statement. 4807 ESR_Continue, 4808 /// Hit a 'break' statement. 4809 ESR_Break, 4810 /// Still scanning for 'case' or 'default' statement. 4811 ESR_CaseNotFound 4812 }; 4813 } 4814 4815 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4816 // We don't need to evaluate the initializer for a static local. 4817 if (!VD->hasLocalStorage()) 4818 return true; 4819 4820 LValue Result; 4821 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4822 ScopeKind::Block, Result); 4823 4824 const Expr *InitE = VD->getInit(); 4825 if (!InitE) { 4826 if (VD->getType()->isDependentType()) 4827 return Info.noteSideEffect(); 4828 return getDefaultInitValue(VD->getType(), Val); 4829 } 4830 if (InitE->isValueDependent()) 4831 return false; 4832 4833 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4834 // Wipe out any partially-computed value, to allow tracking that this 4835 // evaluation failed. 4836 Val = APValue(); 4837 return false; 4838 } 4839 4840 return true; 4841 } 4842 4843 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4844 bool OK = true; 4845 4846 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4847 OK &= EvaluateVarDecl(Info, VD); 4848 4849 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4850 for (auto *BD : DD->bindings()) 4851 if (auto *VD = BD->getHoldingVar()) 4852 OK &= EvaluateDecl(Info, VD); 4853 4854 return OK; 4855 } 4856 4857 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4858 assert(E->isValueDependent()); 4859 if (Info.noteSideEffect()) 4860 return true; 4861 assert(E->containsErrors() && "valid value-dependent expression should never " 4862 "reach invalid code path."); 4863 return false; 4864 } 4865 4866 /// Evaluate a condition (either a variable declaration or an expression). 4867 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4868 const Expr *Cond, bool &Result) { 4869 if (Cond->isValueDependent()) 4870 return false; 4871 FullExpressionRAII Scope(Info); 4872 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4873 return false; 4874 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4875 return false; 4876 return Scope.destroy(); 4877 } 4878 4879 namespace { 4880 /// A location where the result (returned value) of evaluating a 4881 /// statement should be stored. 4882 struct StmtResult { 4883 /// The APValue that should be filled in with the returned value. 4884 APValue &Value; 4885 /// The location containing the result, if any (used to support RVO). 4886 const LValue *Slot; 4887 }; 4888 4889 struct TempVersionRAII { 4890 CallStackFrame &Frame; 4891 4892 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4893 Frame.pushTempVersion(); 4894 } 4895 4896 ~TempVersionRAII() { 4897 Frame.popTempVersion(); 4898 } 4899 }; 4900 4901 } 4902 4903 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4904 const Stmt *S, 4905 const SwitchCase *SC = nullptr); 4906 4907 /// Evaluate the body of a loop, and translate the result as appropriate. 4908 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4909 const Stmt *Body, 4910 const SwitchCase *Case = nullptr) { 4911 BlockScopeRAII Scope(Info); 4912 4913 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4914 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4915 ESR = ESR_Failed; 4916 4917 switch (ESR) { 4918 case ESR_Break: 4919 return ESR_Succeeded; 4920 case ESR_Succeeded: 4921 case ESR_Continue: 4922 return ESR_Continue; 4923 case ESR_Failed: 4924 case ESR_Returned: 4925 case ESR_CaseNotFound: 4926 return ESR; 4927 } 4928 llvm_unreachable("Invalid EvalStmtResult!"); 4929 } 4930 4931 /// Evaluate a switch statement. 4932 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4933 const SwitchStmt *SS) { 4934 BlockScopeRAII Scope(Info); 4935 4936 // Evaluate the switch condition. 4937 APSInt Value; 4938 { 4939 if (const Stmt *Init = SS->getInit()) { 4940 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4941 if (ESR != ESR_Succeeded) { 4942 if (ESR != ESR_Failed && !Scope.destroy()) 4943 ESR = ESR_Failed; 4944 return ESR; 4945 } 4946 } 4947 4948 FullExpressionRAII CondScope(Info); 4949 if (SS->getConditionVariable() && 4950 !EvaluateDecl(Info, SS->getConditionVariable())) 4951 return ESR_Failed; 4952 if (SS->getCond()->isValueDependent()) { 4953 if (!EvaluateDependentExpr(SS->getCond(), Info)) 4954 return ESR_Failed; 4955 } else { 4956 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4957 return ESR_Failed; 4958 } 4959 if (!CondScope.destroy()) 4960 return ESR_Failed; 4961 } 4962 4963 // Find the switch case corresponding to the value of the condition. 4964 // FIXME: Cache this lookup. 4965 const SwitchCase *Found = nullptr; 4966 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4967 SC = SC->getNextSwitchCase()) { 4968 if (isa<DefaultStmt>(SC)) { 4969 Found = SC; 4970 continue; 4971 } 4972 4973 const CaseStmt *CS = cast<CaseStmt>(SC); 4974 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4975 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4976 : LHS; 4977 if (LHS <= Value && Value <= RHS) { 4978 Found = SC; 4979 break; 4980 } 4981 } 4982 4983 if (!Found) 4984 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4985 4986 // Search the switch body for the switch case and evaluate it from there. 4987 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4988 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4989 return ESR_Failed; 4990 4991 switch (ESR) { 4992 case ESR_Break: 4993 return ESR_Succeeded; 4994 case ESR_Succeeded: 4995 case ESR_Continue: 4996 case ESR_Failed: 4997 case ESR_Returned: 4998 return ESR; 4999 case ESR_CaseNotFound: 5000 // This can only happen if the switch case is nested within a statement 5001 // expression. We have no intention of supporting that. 5002 Info.FFDiag(Found->getBeginLoc(), 5003 diag::note_constexpr_stmt_expr_unsupported); 5004 return ESR_Failed; 5005 } 5006 llvm_unreachable("Invalid EvalStmtResult!"); 5007 } 5008 5009 // Evaluate a statement. 5010 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 5011 const Stmt *S, const SwitchCase *Case) { 5012 if (!Info.nextStep(S)) 5013 return ESR_Failed; 5014 5015 // If we're hunting down a 'case' or 'default' label, recurse through 5016 // substatements until we hit the label. 5017 if (Case) { 5018 switch (S->getStmtClass()) { 5019 case Stmt::CompoundStmtClass: 5020 // FIXME: Precompute which substatement of a compound statement we 5021 // would jump to, and go straight there rather than performing a 5022 // linear scan each time. 5023 case Stmt::LabelStmtClass: 5024 case Stmt::AttributedStmtClass: 5025 case Stmt::DoStmtClass: 5026 break; 5027 5028 case Stmt::CaseStmtClass: 5029 case Stmt::DefaultStmtClass: 5030 if (Case == S) 5031 Case = nullptr; 5032 break; 5033 5034 case Stmt::IfStmtClass: { 5035 // FIXME: Precompute which side of an 'if' we would jump to, and go 5036 // straight there rather than scanning both sides. 5037 const IfStmt *IS = cast<IfStmt>(S); 5038 5039 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5040 // preceded by our switch label. 5041 BlockScopeRAII Scope(Info); 5042 5043 // Step into the init statement in case it brings an (uninitialized) 5044 // variable into scope. 5045 if (const Stmt *Init = IS->getInit()) { 5046 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5047 if (ESR != ESR_CaseNotFound) { 5048 assert(ESR != ESR_Succeeded); 5049 return ESR; 5050 } 5051 } 5052 5053 // Condition variable must be initialized if it exists. 5054 // FIXME: We can skip evaluating the body if there's a condition 5055 // variable, as there can't be any case labels within it. 5056 // (The same is true for 'for' statements.) 5057 5058 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5059 if (ESR == ESR_Failed) 5060 return ESR; 5061 if (ESR != ESR_CaseNotFound) 5062 return Scope.destroy() ? ESR : ESR_Failed; 5063 if (!IS->getElse()) 5064 return ESR_CaseNotFound; 5065 5066 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5067 if (ESR == ESR_Failed) 5068 return ESR; 5069 if (ESR != ESR_CaseNotFound) 5070 return Scope.destroy() ? ESR : ESR_Failed; 5071 return ESR_CaseNotFound; 5072 } 5073 5074 case Stmt::WhileStmtClass: { 5075 EvalStmtResult ESR = 5076 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5077 if (ESR != ESR_Continue) 5078 return ESR; 5079 break; 5080 } 5081 5082 case Stmt::ForStmtClass: { 5083 const ForStmt *FS = cast<ForStmt>(S); 5084 BlockScopeRAII Scope(Info); 5085 5086 // Step into the init statement in case it brings an (uninitialized) 5087 // variable into scope. 5088 if (const Stmt *Init = FS->getInit()) { 5089 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5090 if (ESR != ESR_CaseNotFound) { 5091 assert(ESR != ESR_Succeeded); 5092 return ESR; 5093 } 5094 } 5095 5096 EvalStmtResult ESR = 5097 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5098 if (ESR != ESR_Continue) 5099 return ESR; 5100 if (const auto *Inc = FS->getInc()) { 5101 if (Inc->isValueDependent()) { 5102 if (!EvaluateDependentExpr(Inc, Info)) 5103 return ESR_Failed; 5104 } else { 5105 FullExpressionRAII IncScope(Info); 5106 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5107 return ESR_Failed; 5108 } 5109 } 5110 break; 5111 } 5112 5113 case Stmt::DeclStmtClass: { 5114 // Start the lifetime of any uninitialized variables we encounter. They 5115 // might be used by the selected branch of the switch. 5116 const DeclStmt *DS = cast<DeclStmt>(S); 5117 for (const auto *D : DS->decls()) { 5118 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5119 if (VD->hasLocalStorage() && !VD->getInit()) 5120 if (!EvaluateVarDecl(Info, VD)) 5121 return ESR_Failed; 5122 // FIXME: If the variable has initialization that can't be jumped 5123 // over, bail out of any immediately-surrounding compound-statement 5124 // too. There can't be any case labels here. 5125 } 5126 } 5127 return ESR_CaseNotFound; 5128 } 5129 5130 default: 5131 return ESR_CaseNotFound; 5132 } 5133 } 5134 5135 switch (S->getStmtClass()) { 5136 default: 5137 if (const Expr *E = dyn_cast<Expr>(S)) { 5138 if (E->isValueDependent()) { 5139 if (!EvaluateDependentExpr(E, Info)) 5140 return ESR_Failed; 5141 } else { 5142 // Don't bother evaluating beyond an expression-statement which couldn't 5143 // be evaluated. 5144 // FIXME: Do we need the FullExpressionRAII object here? 5145 // VisitExprWithCleanups should create one when necessary. 5146 FullExpressionRAII Scope(Info); 5147 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5148 return ESR_Failed; 5149 } 5150 return ESR_Succeeded; 5151 } 5152 5153 Info.FFDiag(S->getBeginLoc()); 5154 return ESR_Failed; 5155 5156 case Stmt::NullStmtClass: 5157 return ESR_Succeeded; 5158 5159 case Stmt::DeclStmtClass: { 5160 const DeclStmt *DS = cast<DeclStmt>(S); 5161 for (const auto *D : DS->decls()) { 5162 // Each declaration initialization is its own full-expression. 5163 FullExpressionRAII Scope(Info); 5164 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5165 return ESR_Failed; 5166 if (!Scope.destroy()) 5167 return ESR_Failed; 5168 } 5169 return ESR_Succeeded; 5170 } 5171 5172 case Stmt::ReturnStmtClass: { 5173 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5174 FullExpressionRAII Scope(Info); 5175 if (RetExpr && RetExpr->isValueDependent()) { 5176 EvaluateDependentExpr(RetExpr, Info); 5177 // We know we returned, but we don't know what the value is. 5178 return ESR_Failed; 5179 } 5180 if (RetExpr && 5181 !(Result.Slot 5182 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5183 : Evaluate(Result.Value, Info, RetExpr))) 5184 return ESR_Failed; 5185 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5186 } 5187 5188 case Stmt::CompoundStmtClass: { 5189 BlockScopeRAII Scope(Info); 5190 5191 const CompoundStmt *CS = cast<CompoundStmt>(S); 5192 for (const auto *BI : CS->body()) { 5193 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5194 if (ESR == ESR_Succeeded) 5195 Case = nullptr; 5196 else if (ESR != ESR_CaseNotFound) { 5197 if (ESR != ESR_Failed && !Scope.destroy()) 5198 return ESR_Failed; 5199 return ESR; 5200 } 5201 } 5202 if (Case) 5203 return ESR_CaseNotFound; 5204 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5205 } 5206 5207 case Stmt::IfStmtClass: { 5208 const IfStmt *IS = cast<IfStmt>(S); 5209 5210 // Evaluate the condition, as either a var decl or as an expression. 5211 BlockScopeRAII Scope(Info); 5212 if (const Stmt *Init = IS->getInit()) { 5213 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5214 if (ESR != ESR_Succeeded) { 5215 if (ESR != ESR_Failed && !Scope.destroy()) 5216 return ESR_Failed; 5217 return ESR; 5218 } 5219 } 5220 bool Cond; 5221 if (IS->isConsteval()) 5222 Cond = IS->isNonNegatedConsteval(); 5223 else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5224 Cond)) 5225 return ESR_Failed; 5226 5227 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5228 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5229 if (ESR != ESR_Succeeded) { 5230 if (ESR != ESR_Failed && !Scope.destroy()) 5231 return ESR_Failed; 5232 return ESR; 5233 } 5234 } 5235 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5236 } 5237 5238 case Stmt::WhileStmtClass: { 5239 const WhileStmt *WS = cast<WhileStmt>(S); 5240 while (true) { 5241 BlockScopeRAII Scope(Info); 5242 bool Continue; 5243 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5244 Continue)) 5245 return ESR_Failed; 5246 if (!Continue) 5247 break; 5248 5249 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5250 if (ESR != ESR_Continue) { 5251 if (ESR != ESR_Failed && !Scope.destroy()) 5252 return ESR_Failed; 5253 return ESR; 5254 } 5255 if (!Scope.destroy()) 5256 return ESR_Failed; 5257 } 5258 return ESR_Succeeded; 5259 } 5260 5261 case Stmt::DoStmtClass: { 5262 const DoStmt *DS = cast<DoStmt>(S); 5263 bool Continue; 5264 do { 5265 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5266 if (ESR != ESR_Continue) 5267 return ESR; 5268 Case = nullptr; 5269 5270 if (DS->getCond()->isValueDependent()) { 5271 EvaluateDependentExpr(DS->getCond(), Info); 5272 // Bailout as we don't know whether to keep going or terminate the loop. 5273 return ESR_Failed; 5274 } 5275 FullExpressionRAII CondScope(Info); 5276 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5277 !CondScope.destroy()) 5278 return ESR_Failed; 5279 } while (Continue); 5280 return ESR_Succeeded; 5281 } 5282 5283 case Stmt::ForStmtClass: { 5284 const ForStmt *FS = cast<ForStmt>(S); 5285 BlockScopeRAII ForScope(Info); 5286 if (FS->getInit()) { 5287 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5288 if (ESR != ESR_Succeeded) { 5289 if (ESR != ESR_Failed && !ForScope.destroy()) 5290 return ESR_Failed; 5291 return ESR; 5292 } 5293 } 5294 while (true) { 5295 BlockScopeRAII IterScope(Info); 5296 bool Continue = true; 5297 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5298 FS->getCond(), Continue)) 5299 return ESR_Failed; 5300 if (!Continue) 5301 break; 5302 5303 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5304 if (ESR != ESR_Continue) { 5305 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5306 return ESR_Failed; 5307 return ESR; 5308 } 5309 5310 if (const auto *Inc = FS->getInc()) { 5311 if (Inc->isValueDependent()) { 5312 if (!EvaluateDependentExpr(Inc, Info)) 5313 return ESR_Failed; 5314 } else { 5315 FullExpressionRAII IncScope(Info); 5316 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5317 return ESR_Failed; 5318 } 5319 } 5320 5321 if (!IterScope.destroy()) 5322 return ESR_Failed; 5323 } 5324 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5325 } 5326 5327 case Stmt::CXXForRangeStmtClass: { 5328 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5329 BlockScopeRAII Scope(Info); 5330 5331 // Evaluate the init-statement if present. 5332 if (FS->getInit()) { 5333 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5334 if (ESR != ESR_Succeeded) { 5335 if (ESR != ESR_Failed && !Scope.destroy()) 5336 return ESR_Failed; 5337 return ESR; 5338 } 5339 } 5340 5341 // Initialize the __range variable. 5342 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5343 if (ESR != ESR_Succeeded) { 5344 if (ESR != ESR_Failed && !Scope.destroy()) 5345 return ESR_Failed; 5346 return ESR; 5347 } 5348 5349 // In error-recovery cases it's possible to get here even if we failed to 5350 // synthesize the __begin and __end variables. 5351 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5352 return ESR_Failed; 5353 5354 // Create the __begin and __end iterators. 5355 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5356 if (ESR != ESR_Succeeded) { 5357 if (ESR != ESR_Failed && !Scope.destroy()) 5358 return ESR_Failed; 5359 return ESR; 5360 } 5361 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5362 if (ESR != ESR_Succeeded) { 5363 if (ESR != ESR_Failed && !Scope.destroy()) 5364 return ESR_Failed; 5365 return ESR; 5366 } 5367 5368 while (true) { 5369 // Condition: __begin != __end. 5370 { 5371 if (FS->getCond()->isValueDependent()) { 5372 EvaluateDependentExpr(FS->getCond(), Info); 5373 // We don't know whether to keep going or terminate the loop. 5374 return ESR_Failed; 5375 } 5376 bool Continue = true; 5377 FullExpressionRAII CondExpr(Info); 5378 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5379 return ESR_Failed; 5380 if (!Continue) 5381 break; 5382 } 5383 5384 // User's variable declaration, initialized by *__begin. 5385 BlockScopeRAII InnerScope(Info); 5386 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5387 if (ESR != ESR_Succeeded) { 5388 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5389 return ESR_Failed; 5390 return ESR; 5391 } 5392 5393 // Loop body. 5394 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5395 if (ESR != ESR_Continue) { 5396 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5397 return ESR_Failed; 5398 return ESR; 5399 } 5400 if (FS->getInc()->isValueDependent()) { 5401 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5402 return ESR_Failed; 5403 } else { 5404 // Increment: ++__begin 5405 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5406 return ESR_Failed; 5407 } 5408 5409 if (!InnerScope.destroy()) 5410 return ESR_Failed; 5411 } 5412 5413 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5414 } 5415 5416 case Stmt::SwitchStmtClass: 5417 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5418 5419 case Stmt::ContinueStmtClass: 5420 return ESR_Continue; 5421 5422 case Stmt::BreakStmtClass: 5423 return ESR_Break; 5424 5425 case Stmt::LabelStmtClass: 5426 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5427 5428 case Stmt::AttributedStmtClass: 5429 // As a general principle, C++11 attributes can be ignored without 5430 // any semantic impact. 5431 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5432 Case); 5433 5434 case Stmt::CaseStmtClass: 5435 case Stmt::DefaultStmtClass: 5436 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5437 case Stmt::CXXTryStmtClass: 5438 // Evaluate try blocks by evaluating all sub statements. 5439 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5440 } 5441 } 5442 5443 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5444 /// default constructor. If so, we'll fold it whether or not it's marked as 5445 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5446 /// so we need special handling. 5447 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5448 const CXXConstructorDecl *CD, 5449 bool IsValueInitialization) { 5450 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5451 return false; 5452 5453 // Value-initialization does not call a trivial default constructor, so such a 5454 // call is a core constant expression whether or not the constructor is 5455 // constexpr. 5456 if (!CD->isConstexpr() && !IsValueInitialization) { 5457 if (Info.getLangOpts().CPlusPlus11) { 5458 // FIXME: If DiagDecl is an implicitly-declared special member function, 5459 // we should be much more explicit about why it's not constexpr. 5460 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5461 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5462 Info.Note(CD->getLocation(), diag::note_declared_at); 5463 } else { 5464 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5465 } 5466 } 5467 return true; 5468 } 5469 5470 /// CheckConstexprFunction - Check that a function can be called in a constant 5471 /// expression. 5472 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5473 const FunctionDecl *Declaration, 5474 const FunctionDecl *Definition, 5475 const Stmt *Body) { 5476 // Potential constant expressions can contain calls to declared, but not yet 5477 // defined, constexpr functions. 5478 if (Info.checkingPotentialConstantExpression() && !Definition && 5479 Declaration->isConstexpr()) 5480 return false; 5481 5482 // Bail out if the function declaration itself is invalid. We will 5483 // have produced a relevant diagnostic while parsing it, so just 5484 // note the problematic sub-expression. 5485 if (Declaration->isInvalidDecl()) { 5486 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5487 return false; 5488 } 5489 5490 // DR1872: An instantiated virtual constexpr function can't be called in a 5491 // constant expression (prior to C++20). We can still constant-fold such a 5492 // call. 5493 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5494 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5495 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5496 5497 if (Definition && Definition->isInvalidDecl()) { 5498 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5499 return false; 5500 } 5501 5502 // Can we evaluate this function call? 5503 if (Definition && Definition->isConstexpr() && Body) 5504 return true; 5505 5506 if (Info.getLangOpts().CPlusPlus11) { 5507 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5508 5509 // If this function is not constexpr because it is an inherited 5510 // non-constexpr constructor, diagnose that directly. 5511 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5512 if (CD && CD->isInheritingConstructor()) { 5513 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5514 if (!Inherited->isConstexpr()) 5515 DiagDecl = CD = Inherited; 5516 } 5517 5518 // FIXME: If DiagDecl is an implicitly-declared special member function 5519 // or an inheriting constructor, we should be much more explicit about why 5520 // it's not constexpr. 5521 if (CD && CD->isInheritingConstructor()) 5522 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5523 << CD->getInheritedConstructor().getConstructor()->getParent(); 5524 else 5525 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5526 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5527 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5528 } else { 5529 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5530 } 5531 return false; 5532 } 5533 5534 namespace { 5535 struct CheckDynamicTypeHandler { 5536 AccessKinds AccessKind; 5537 typedef bool result_type; 5538 bool failed() { return false; } 5539 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5540 bool found(APSInt &Value, QualType SubobjType) { return true; } 5541 bool found(APFloat &Value, QualType SubobjType) { return true; } 5542 }; 5543 } // end anonymous namespace 5544 5545 /// Check that we can access the notional vptr of an object / determine its 5546 /// dynamic type. 5547 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5548 AccessKinds AK, bool Polymorphic) { 5549 if (This.Designator.Invalid) 5550 return false; 5551 5552 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5553 5554 if (!Obj) 5555 return false; 5556 5557 if (!Obj.Value) { 5558 // The object is not usable in constant expressions, so we can't inspect 5559 // its value to see if it's in-lifetime or what the active union members 5560 // are. We can still check for a one-past-the-end lvalue. 5561 if (This.Designator.isOnePastTheEnd() || 5562 This.Designator.isMostDerivedAnUnsizedArray()) { 5563 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5564 ? diag::note_constexpr_access_past_end 5565 : diag::note_constexpr_access_unsized_array) 5566 << AK; 5567 return false; 5568 } else if (Polymorphic) { 5569 // Conservatively refuse to perform a polymorphic operation if we would 5570 // not be able to read a notional 'vptr' value. 5571 APValue Val; 5572 This.moveInto(Val); 5573 QualType StarThisType = 5574 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5575 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5576 << AK << Val.getAsString(Info.Ctx, StarThisType); 5577 return false; 5578 } 5579 return true; 5580 } 5581 5582 CheckDynamicTypeHandler Handler{AK}; 5583 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5584 } 5585 5586 /// Check that the pointee of the 'this' pointer in a member function call is 5587 /// either within its lifetime or in its period of construction or destruction. 5588 static bool 5589 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5590 const LValue &This, 5591 const CXXMethodDecl *NamedMember) { 5592 return checkDynamicType( 5593 Info, E, This, 5594 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5595 } 5596 5597 struct DynamicType { 5598 /// The dynamic class type of the object. 5599 const CXXRecordDecl *Type; 5600 /// The corresponding path length in the lvalue. 5601 unsigned PathLength; 5602 }; 5603 5604 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5605 unsigned PathLength) { 5606 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5607 Designator.Entries.size() && "invalid path length"); 5608 return (PathLength == Designator.MostDerivedPathLength) 5609 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5610 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5611 } 5612 5613 /// Determine the dynamic type of an object. 5614 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5615 LValue &This, AccessKinds AK) { 5616 // If we don't have an lvalue denoting an object of class type, there is no 5617 // meaningful dynamic type. (We consider objects of non-class type to have no 5618 // dynamic type.) 5619 if (!checkDynamicType(Info, E, This, AK, true)) 5620 return None; 5621 5622 // Refuse to compute a dynamic type in the presence of virtual bases. This 5623 // shouldn't happen other than in constant-folding situations, since literal 5624 // types can't have virtual bases. 5625 // 5626 // Note that consumers of DynamicType assume that the type has no virtual 5627 // bases, and will need modifications if this restriction is relaxed. 5628 const CXXRecordDecl *Class = 5629 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5630 if (!Class || Class->getNumVBases()) { 5631 Info.FFDiag(E); 5632 return None; 5633 } 5634 5635 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5636 // binary search here instead. But the overwhelmingly common case is that 5637 // we're not in the middle of a constructor, so it probably doesn't matter 5638 // in practice. 5639 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5640 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5641 PathLength <= Path.size(); ++PathLength) { 5642 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5643 Path.slice(0, PathLength))) { 5644 case ConstructionPhase::Bases: 5645 case ConstructionPhase::DestroyingBases: 5646 // We're constructing or destroying a base class. This is not the dynamic 5647 // type. 5648 break; 5649 5650 case ConstructionPhase::None: 5651 case ConstructionPhase::AfterBases: 5652 case ConstructionPhase::AfterFields: 5653 case ConstructionPhase::Destroying: 5654 // We've finished constructing the base classes and not yet started 5655 // destroying them again, so this is the dynamic type. 5656 return DynamicType{getBaseClassType(This.Designator, PathLength), 5657 PathLength}; 5658 } 5659 } 5660 5661 // CWG issue 1517: we're constructing a base class of the object described by 5662 // 'This', so that object has not yet begun its period of construction and 5663 // any polymorphic operation on it results in undefined behavior. 5664 Info.FFDiag(E); 5665 return None; 5666 } 5667 5668 /// Perform virtual dispatch. 5669 static const CXXMethodDecl *HandleVirtualDispatch( 5670 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5671 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5672 Optional<DynamicType> DynType = ComputeDynamicType( 5673 Info, E, This, 5674 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5675 if (!DynType) 5676 return nullptr; 5677 5678 // Find the final overrider. It must be declared in one of the classes on the 5679 // path from the dynamic type to the static type. 5680 // FIXME: If we ever allow literal types to have virtual base classes, that 5681 // won't be true. 5682 const CXXMethodDecl *Callee = Found; 5683 unsigned PathLength = DynType->PathLength; 5684 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5685 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5686 const CXXMethodDecl *Overrider = 5687 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5688 if (Overrider) { 5689 Callee = Overrider; 5690 break; 5691 } 5692 } 5693 5694 // C++2a [class.abstract]p6: 5695 // the effect of making a virtual call to a pure virtual function [...] is 5696 // undefined 5697 if (Callee->isPure()) { 5698 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5699 Info.Note(Callee->getLocation(), diag::note_declared_at); 5700 return nullptr; 5701 } 5702 5703 // If necessary, walk the rest of the path to determine the sequence of 5704 // covariant adjustment steps to apply. 5705 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5706 Found->getReturnType())) { 5707 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5708 for (unsigned CovariantPathLength = PathLength + 1; 5709 CovariantPathLength != This.Designator.Entries.size(); 5710 ++CovariantPathLength) { 5711 const CXXRecordDecl *NextClass = 5712 getBaseClassType(This.Designator, CovariantPathLength); 5713 const CXXMethodDecl *Next = 5714 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5715 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5716 Next->getReturnType(), CovariantAdjustmentPath.back())) 5717 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5718 } 5719 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5720 CovariantAdjustmentPath.back())) 5721 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5722 } 5723 5724 // Perform 'this' adjustment. 5725 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5726 return nullptr; 5727 5728 return Callee; 5729 } 5730 5731 /// Perform the adjustment from a value returned by a virtual function to 5732 /// a value of the statically expected type, which may be a pointer or 5733 /// reference to a base class of the returned type. 5734 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5735 APValue &Result, 5736 ArrayRef<QualType> Path) { 5737 assert(Result.isLValue() && 5738 "unexpected kind of APValue for covariant return"); 5739 if (Result.isNullPointer()) 5740 return true; 5741 5742 LValue LVal; 5743 LVal.setFrom(Info.Ctx, Result); 5744 5745 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5746 for (unsigned I = 1; I != Path.size(); ++I) { 5747 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5748 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5749 if (OldClass != NewClass && 5750 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5751 return false; 5752 OldClass = NewClass; 5753 } 5754 5755 LVal.moveInto(Result); 5756 return true; 5757 } 5758 5759 /// Determine whether \p Base, which is known to be a direct base class of 5760 /// \p Derived, is a public base class. 5761 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5762 const CXXRecordDecl *Base) { 5763 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5764 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5765 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5766 return BaseSpec.getAccessSpecifier() == AS_public; 5767 } 5768 llvm_unreachable("Base is not a direct base of Derived"); 5769 } 5770 5771 /// Apply the given dynamic cast operation on the provided lvalue. 5772 /// 5773 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5774 /// to find a suitable target subobject. 5775 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5776 LValue &Ptr) { 5777 // We can't do anything with a non-symbolic pointer value. 5778 SubobjectDesignator &D = Ptr.Designator; 5779 if (D.Invalid) 5780 return false; 5781 5782 // C++ [expr.dynamic.cast]p6: 5783 // If v is a null pointer value, the result is a null pointer value. 5784 if (Ptr.isNullPointer() && !E->isGLValue()) 5785 return true; 5786 5787 // For all the other cases, we need the pointer to point to an object within 5788 // its lifetime / period of construction / destruction, and we need to know 5789 // its dynamic type. 5790 Optional<DynamicType> DynType = 5791 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5792 if (!DynType) 5793 return false; 5794 5795 // C++ [expr.dynamic.cast]p7: 5796 // If T is "pointer to cv void", then the result is a pointer to the most 5797 // derived object 5798 if (E->getType()->isVoidPointerType()) 5799 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5800 5801 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5802 assert(C && "dynamic_cast target is not void pointer nor class"); 5803 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5804 5805 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5806 // C++ [expr.dynamic.cast]p9: 5807 if (!E->isGLValue()) { 5808 // The value of a failed cast to pointer type is the null pointer value 5809 // of the required result type. 5810 Ptr.setNull(Info.Ctx, E->getType()); 5811 return true; 5812 } 5813 5814 // A failed cast to reference type throws [...] std::bad_cast. 5815 unsigned DiagKind; 5816 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5817 DynType->Type->isDerivedFrom(C))) 5818 DiagKind = 0; 5819 else if (!Paths || Paths->begin() == Paths->end()) 5820 DiagKind = 1; 5821 else if (Paths->isAmbiguous(CQT)) 5822 DiagKind = 2; 5823 else { 5824 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5825 DiagKind = 3; 5826 } 5827 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5828 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5829 << Info.Ctx.getRecordType(DynType->Type) 5830 << E->getType().getUnqualifiedType(); 5831 return false; 5832 }; 5833 5834 // Runtime check, phase 1: 5835 // Walk from the base subobject towards the derived object looking for the 5836 // target type. 5837 for (int PathLength = Ptr.Designator.Entries.size(); 5838 PathLength >= (int)DynType->PathLength; --PathLength) { 5839 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5840 if (declaresSameEntity(Class, C)) 5841 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5842 // We can only walk across public inheritance edges. 5843 if (PathLength > (int)DynType->PathLength && 5844 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5845 Class)) 5846 return RuntimeCheckFailed(nullptr); 5847 } 5848 5849 // Runtime check, phase 2: 5850 // Search the dynamic type for an unambiguous public base of type C. 5851 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5852 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5853 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5854 Paths.front().Access == AS_public) { 5855 // Downcast to the dynamic type... 5856 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5857 return false; 5858 // ... then upcast to the chosen base class subobject. 5859 for (CXXBasePathElement &Elem : Paths.front()) 5860 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5861 return false; 5862 return true; 5863 } 5864 5865 // Otherwise, the runtime check fails. 5866 return RuntimeCheckFailed(&Paths); 5867 } 5868 5869 namespace { 5870 struct StartLifetimeOfUnionMemberHandler { 5871 EvalInfo &Info; 5872 const Expr *LHSExpr; 5873 const FieldDecl *Field; 5874 bool DuringInit; 5875 bool Failed = false; 5876 static const AccessKinds AccessKind = AK_Assign; 5877 5878 typedef bool result_type; 5879 bool failed() { return Failed; } 5880 bool found(APValue &Subobj, QualType SubobjType) { 5881 // We are supposed to perform no initialization but begin the lifetime of 5882 // the object. We interpret that as meaning to do what default 5883 // initialization of the object would do if all constructors involved were 5884 // trivial: 5885 // * All base, non-variant member, and array element subobjects' lifetimes 5886 // begin 5887 // * No variant members' lifetimes begin 5888 // * All scalar subobjects whose lifetimes begin have indeterminate values 5889 assert(SubobjType->isUnionType()); 5890 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5891 // This union member is already active. If it's also in-lifetime, there's 5892 // nothing to do. 5893 if (Subobj.getUnionValue().hasValue()) 5894 return true; 5895 } else if (DuringInit) { 5896 // We're currently in the process of initializing a different union 5897 // member. If we carried on, that initialization would attempt to 5898 // store to an inactive union member, resulting in undefined behavior. 5899 Info.FFDiag(LHSExpr, 5900 diag::note_constexpr_union_member_change_during_init); 5901 return false; 5902 } 5903 APValue Result; 5904 Failed = !getDefaultInitValue(Field->getType(), Result); 5905 Subobj.setUnion(Field, Result); 5906 return true; 5907 } 5908 bool found(APSInt &Value, QualType SubobjType) { 5909 llvm_unreachable("wrong value kind for union object"); 5910 } 5911 bool found(APFloat &Value, QualType SubobjType) { 5912 llvm_unreachable("wrong value kind for union object"); 5913 } 5914 }; 5915 } // end anonymous namespace 5916 5917 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5918 5919 /// Handle a builtin simple-assignment or a call to a trivial assignment 5920 /// operator whose left-hand side might involve a union member access. If it 5921 /// does, implicitly start the lifetime of any accessed union elements per 5922 /// C++20 [class.union]5. 5923 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5924 const LValue &LHS) { 5925 if (LHS.InvalidBase || LHS.Designator.Invalid) 5926 return false; 5927 5928 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5929 // C++ [class.union]p5: 5930 // define the set S(E) of subexpressions of E as follows: 5931 unsigned PathLength = LHS.Designator.Entries.size(); 5932 for (const Expr *E = LHSExpr; E != nullptr;) { 5933 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5934 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5935 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5936 // Note that we can't implicitly start the lifetime of a reference, 5937 // so we don't need to proceed any further if we reach one. 5938 if (!FD || FD->getType()->isReferenceType()) 5939 break; 5940 5941 // ... and also contains A.B if B names a union member ... 5942 if (FD->getParent()->isUnion()) { 5943 // ... of a non-class, non-array type, or of a class type with a 5944 // trivial default constructor that is not deleted, or an array of 5945 // such types. 5946 auto *RD = 5947 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5948 if (!RD || RD->hasTrivialDefaultConstructor()) 5949 UnionPathLengths.push_back({PathLength - 1, FD}); 5950 } 5951 5952 E = ME->getBase(); 5953 --PathLength; 5954 assert(declaresSameEntity(FD, 5955 LHS.Designator.Entries[PathLength] 5956 .getAsBaseOrMember().getPointer())); 5957 5958 // -- If E is of the form A[B] and is interpreted as a built-in array 5959 // subscripting operator, S(E) is [S(the array operand, if any)]. 5960 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5961 // Step over an ArrayToPointerDecay implicit cast. 5962 auto *Base = ASE->getBase()->IgnoreImplicit(); 5963 if (!Base->getType()->isArrayType()) 5964 break; 5965 5966 E = Base; 5967 --PathLength; 5968 5969 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5970 // Step over a derived-to-base conversion. 5971 E = ICE->getSubExpr(); 5972 if (ICE->getCastKind() == CK_NoOp) 5973 continue; 5974 if (ICE->getCastKind() != CK_DerivedToBase && 5975 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5976 break; 5977 // Walk path backwards as we walk up from the base to the derived class. 5978 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5979 --PathLength; 5980 (void)Elt; 5981 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5982 LHS.Designator.Entries[PathLength] 5983 .getAsBaseOrMember().getPointer())); 5984 } 5985 5986 // -- Otherwise, S(E) is empty. 5987 } else { 5988 break; 5989 } 5990 } 5991 5992 // Common case: no unions' lifetimes are started. 5993 if (UnionPathLengths.empty()) 5994 return true; 5995 5996 // if modification of X [would access an inactive union member], an object 5997 // of the type of X is implicitly created 5998 CompleteObject Obj = 5999 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 6000 if (!Obj) 6001 return false; 6002 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 6003 llvm::reverse(UnionPathLengths)) { 6004 // Form a designator for the union object. 6005 SubobjectDesignator D = LHS.Designator; 6006 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 6007 6008 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 6009 ConstructionPhase::AfterBases; 6010 StartLifetimeOfUnionMemberHandler StartLifetime{ 6011 Info, LHSExpr, LengthAndField.second, DuringInit}; 6012 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 6013 return false; 6014 } 6015 6016 return true; 6017 } 6018 6019 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 6020 CallRef Call, EvalInfo &Info, 6021 bool NonNull = false) { 6022 LValue LV; 6023 // Create the parameter slot and register its destruction. For a vararg 6024 // argument, create a temporary. 6025 // FIXME: For calling conventions that destroy parameters in the callee, 6026 // should we consider performing destruction when the function returns 6027 // instead? 6028 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6029 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6030 ScopeKind::Call, LV); 6031 if (!EvaluateInPlace(V, Info, LV, Arg)) 6032 return false; 6033 6034 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6035 // undefined behavior, so is non-constant. 6036 if (NonNull && V.isLValue() && V.isNullPointer()) { 6037 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6038 return false; 6039 } 6040 6041 return true; 6042 } 6043 6044 /// Evaluate the arguments to a function call. 6045 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6046 EvalInfo &Info, const FunctionDecl *Callee, 6047 bool RightToLeft = false) { 6048 bool Success = true; 6049 llvm::SmallBitVector ForbiddenNullArgs; 6050 if (Callee->hasAttr<NonNullAttr>()) { 6051 ForbiddenNullArgs.resize(Args.size()); 6052 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6053 if (!Attr->args_size()) { 6054 ForbiddenNullArgs.set(); 6055 break; 6056 } else 6057 for (auto Idx : Attr->args()) { 6058 unsigned ASTIdx = Idx.getASTIndex(); 6059 if (ASTIdx >= Args.size()) 6060 continue; 6061 ForbiddenNullArgs[ASTIdx] = true; 6062 } 6063 } 6064 } 6065 for (unsigned I = 0; I < Args.size(); I++) { 6066 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6067 const ParmVarDecl *PVD = 6068 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6069 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6070 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6071 // If we're checking for a potential constant expression, evaluate all 6072 // initializers even if some of them fail. 6073 if (!Info.noteFailure()) 6074 return false; 6075 Success = false; 6076 } 6077 } 6078 return Success; 6079 } 6080 6081 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6082 /// constructor or assignment operator. 6083 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6084 const Expr *E, APValue &Result, 6085 bool CopyObjectRepresentation) { 6086 // Find the reference argument. 6087 CallStackFrame *Frame = Info.CurrentCall; 6088 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6089 if (!RefValue) { 6090 Info.FFDiag(E); 6091 return false; 6092 } 6093 6094 // Copy out the contents of the RHS object. 6095 LValue RefLValue; 6096 RefLValue.setFrom(Info.Ctx, *RefValue); 6097 return handleLValueToRValueConversion( 6098 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6099 CopyObjectRepresentation); 6100 } 6101 6102 /// Evaluate a function call. 6103 static bool HandleFunctionCall(SourceLocation CallLoc, 6104 const FunctionDecl *Callee, const LValue *This, 6105 ArrayRef<const Expr *> Args, CallRef Call, 6106 const Stmt *Body, EvalInfo &Info, 6107 APValue &Result, const LValue *ResultSlot) { 6108 if (!Info.CheckCallLimit(CallLoc)) 6109 return false; 6110 6111 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6112 6113 // For a trivial copy or move assignment, perform an APValue copy. This is 6114 // essential for unions, where the operations performed by the assignment 6115 // operator cannot be represented as statements. 6116 // 6117 // Skip this for non-union classes with no fields; in that case, the defaulted 6118 // copy/move does not actually read the object. 6119 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6120 if (MD && MD->isDefaulted() && 6121 (MD->getParent()->isUnion() || 6122 (MD->isTrivial() && 6123 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6124 assert(This && 6125 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6126 APValue RHSValue; 6127 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6128 MD->getParent()->isUnion())) 6129 return false; 6130 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6131 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6132 return false; 6133 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6134 RHSValue)) 6135 return false; 6136 This->moveInto(Result); 6137 return true; 6138 } else if (MD && isLambdaCallOperator(MD)) { 6139 // We're in a lambda; determine the lambda capture field maps unless we're 6140 // just constexpr checking a lambda's call operator. constexpr checking is 6141 // done before the captures have been added to the closure object (unless 6142 // we're inferring constexpr-ness), so we don't have access to them in this 6143 // case. But since we don't need the captures to constexpr check, we can 6144 // just ignore them. 6145 if (!Info.checkingPotentialConstantExpression()) 6146 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6147 Frame.LambdaThisCaptureField); 6148 } 6149 6150 StmtResult Ret = {Result, ResultSlot}; 6151 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6152 if (ESR == ESR_Succeeded) { 6153 if (Callee->getReturnType()->isVoidType()) 6154 return true; 6155 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6156 } 6157 return ESR == ESR_Returned; 6158 } 6159 6160 /// Evaluate a constructor call. 6161 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6162 CallRef Call, 6163 const CXXConstructorDecl *Definition, 6164 EvalInfo &Info, APValue &Result) { 6165 SourceLocation CallLoc = E->getExprLoc(); 6166 if (!Info.CheckCallLimit(CallLoc)) 6167 return false; 6168 6169 const CXXRecordDecl *RD = Definition->getParent(); 6170 if (RD->getNumVBases()) { 6171 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6172 return false; 6173 } 6174 6175 EvalInfo::EvaluatingConstructorRAII EvalObj( 6176 Info, 6177 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6178 RD->getNumBases()); 6179 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6180 6181 // FIXME: Creating an APValue just to hold a nonexistent return value is 6182 // wasteful. 6183 APValue RetVal; 6184 StmtResult Ret = {RetVal, nullptr}; 6185 6186 // If it's a delegating constructor, delegate. 6187 if (Definition->isDelegatingConstructor()) { 6188 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6189 if ((*I)->getInit()->isValueDependent()) { 6190 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6191 return false; 6192 } else { 6193 FullExpressionRAII InitScope(Info); 6194 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6195 !InitScope.destroy()) 6196 return false; 6197 } 6198 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6199 } 6200 6201 // For a trivial copy or move constructor, perform an APValue copy. This is 6202 // essential for unions (or classes with anonymous union members), where the 6203 // operations performed by the constructor cannot be represented by 6204 // ctor-initializers. 6205 // 6206 // Skip this for empty non-union classes; we should not perform an 6207 // lvalue-to-rvalue conversion on them because their copy constructor does not 6208 // actually read them. 6209 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6210 (Definition->getParent()->isUnion() || 6211 (Definition->isTrivial() && 6212 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6213 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6214 Definition->getParent()->isUnion()); 6215 } 6216 6217 // Reserve space for the struct members. 6218 if (!Result.hasValue()) { 6219 if (!RD->isUnion()) 6220 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6221 std::distance(RD->field_begin(), RD->field_end())); 6222 else 6223 // A union starts with no active member. 6224 Result = APValue((const FieldDecl*)nullptr); 6225 } 6226 6227 if (RD->isInvalidDecl()) return false; 6228 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6229 6230 // A scope for temporaries lifetime-extended by reference members. 6231 BlockScopeRAII LifetimeExtendedScope(Info); 6232 6233 bool Success = true; 6234 unsigned BasesSeen = 0; 6235 #ifndef NDEBUG 6236 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6237 #endif 6238 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6239 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6240 // We might be initializing the same field again if this is an indirect 6241 // field initialization. 6242 if (FieldIt == RD->field_end() || 6243 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6244 assert(Indirect && "fields out of order?"); 6245 return; 6246 } 6247 6248 // Default-initialize any fields with no explicit initializer. 6249 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6250 assert(FieldIt != RD->field_end() && "missing field?"); 6251 if (!FieldIt->isUnnamedBitfield()) 6252 Success &= getDefaultInitValue( 6253 FieldIt->getType(), 6254 Result.getStructField(FieldIt->getFieldIndex())); 6255 } 6256 ++FieldIt; 6257 }; 6258 for (const auto *I : Definition->inits()) { 6259 LValue Subobject = This; 6260 LValue SubobjectParent = This; 6261 APValue *Value = &Result; 6262 6263 // Determine the subobject to initialize. 6264 FieldDecl *FD = nullptr; 6265 if (I->isBaseInitializer()) { 6266 QualType BaseType(I->getBaseClass(), 0); 6267 #ifndef NDEBUG 6268 // Non-virtual base classes are initialized in the order in the class 6269 // definition. We have already checked for virtual base classes. 6270 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6271 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6272 "base class initializers not in expected order"); 6273 ++BaseIt; 6274 #endif 6275 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6276 BaseType->getAsCXXRecordDecl(), &Layout)) 6277 return false; 6278 Value = &Result.getStructBase(BasesSeen++); 6279 } else if ((FD = I->getMember())) { 6280 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6281 return false; 6282 if (RD->isUnion()) { 6283 Result = APValue(FD); 6284 Value = &Result.getUnionValue(); 6285 } else { 6286 SkipToField(FD, false); 6287 Value = &Result.getStructField(FD->getFieldIndex()); 6288 } 6289 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6290 // Walk the indirect field decl's chain to find the object to initialize, 6291 // and make sure we've initialized every step along it. 6292 auto IndirectFieldChain = IFD->chain(); 6293 for (auto *C : IndirectFieldChain) { 6294 FD = cast<FieldDecl>(C); 6295 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6296 // Switch the union field if it differs. This happens if we had 6297 // preceding zero-initialization, and we're now initializing a union 6298 // subobject other than the first. 6299 // FIXME: In this case, the values of the other subobjects are 6300 // specified, since zero-initialization sets all padding bits to zero. 6301 if (!Value->hasValue() || 6302 (Value->isUnion() && Value->getUnionField() != FD)) { 6303 if (CD->isUnion()) 6304 *Value = APValue(FD); 6305 else 6306 // FIXME: This immediately starts the lifetime of all members of 6307 // an anonymous struct. It would be preferable to strictly start 6308 // member lifetime in initialization order. 6309 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6310 } 6311 // Store Subobject as its parent before updating it for the last element 6312 // in the chain. 6313 if (C == IndirectFieldChain.back()) 6314 SubobjectParent = Subobject; 6315 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6316 return false; 6317 if (CD->isUnion()) 6318 Value = &Value->getUnionValue(); 6319 else { 6320 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6321 SkipToField(FD, true); 6322 Value = &Value->getStructField(FD->getFieldIndex()); 6323 } 6324 } 6325 } else { 6326 llvm_unreachable("unknown base initializer kind"); 6327 } 6328 6329 // Need to override This for implicit field initializers as in this case 6330 // This refers to innermost anonymous struct/union containing initializer, 6331 // not to currently constructed class. 6332 const Expr *Init = I->getInit(); 6333 if (Init->isValueDependent()) { 6334 if (!EvaluateDependentExpr(Init, Info)) 6335 return false; 6336 } else { 6337 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6338 isa<CXXDefaultInitExpr>(Init)); 6339 FullExpressionRAII InitScope(Info); 6340 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6341 (FD && FD->isBitField() && 6342 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6343 // If we're checking for a potential constant expression, evaluate all 6344 // initializers even if some of them fail. 6345 if (!Info.noteFailure()) 6346 return false; 6347 Success = false; 6348 } 6349 } 6350 6351 // This is the point at which the dynamic type of the object becomes this 6352 // class type. 6353 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6354 EvalObj.finishedConstructingBases(); 6355 } 6356 6357 // Default-initialize any remaining fields. 6358 if (!RD->isUnion()) { 6359 for (; FieldIt != RD->field_end(); ++FieldIt) { 6360 if (!FieldIt->isUnnamedBitfield()) 6361 Success &= getDefaultInitValue( 6362 FieldIt->getType(), 6363 Result.getStructField(FieldIt->getFieldIndex())); 6364 } 6365 } 6366 6367 EvalObj.finishedConstructingFields(); 6368 6369 return Success && 6370 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6371 LifetimeExtendedScope.destroy(); 6372 } 6373 6374 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6375 ArrayRef<const Expr*> Args, 6376 const CXXConstructorDecl *Definition, 6377 EvalInfo &Info, APValue &Result) { 6378 CallScopeRAII CallScope(Info); 6379 CallRef Call = Info.CurrentCall->createCall(Definition); 6380 if (!EvaluateArgs(Args, Call, Info, Definition)) 6381 return false; 6382 6383 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6384 CallScope.destroy(); 6385 } 6386 6387 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6388 const LValue &This, APValue &Value, 6389 QualType T) { 6390 // Objects can only be destroyed while they're within their lifetimes. 6391 // FIXME: We have no representation for whether an object of type nullptr_t 6392 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6393 // as indeterminate instead? 6394 if (Value.isAbsent() && !T->isNullPtrType()) { 6395 APValue Printable; 6396 This.moveInto(Printable); 6397 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6398 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6399 return false; 6400 } 6401 6402 // Invent an expression for location purposes. 6403 // FIXME: We shouldn't need to do this. 6404 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6405 6406 // For arrays, destroy elements right-to-left. 6407 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6408 uint64_t Size = CAT->getSize().getZExtValue(); 6409 QualType ElemT = CAT->getElementType(); 6410 6411 LValue ElemLV = This; 6412 ElemLV.addArray(Info, &LocE, CAT); 6413 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6414 return false; 6415 6416 // Ensure that we have actual array elements available to destroy; the 6417 // destructors might mutate the value, so we can't run them on the array 6418 // filler. 6419 if (Size && Size > Value.getArrayInitializedElts()) 6420 expandArray(Value, Value.getArraySize() - 1); 6421 6422 for (; Size != 0; --Size) { 6423 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6424 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6425 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6426 return false; 6427 } 6428 6429 // End the lifetime of this array now. 6430 Value = APValue(); 6431 return true; 6432 } 6433 6434 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6435 if (!RD) { 6436 if (T.isDestructedType()) { 6437 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6438 return false; 6439 } 6440 6441 Value = APValue(); 6442 return true; 6443 } 6444 6445 if (RD->getNumVBases()) { 6446 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6447 return false; 6448 } 6449 6450 const CXXDestructorDecl *DD = RD->getDestructor(); 6451 if (!DD && !RD->hasTrivialDestructor()) { 6452 Info.FFDiag(CallLoc); 6453 return false; 6454 } 6455 6456 if (!DD || DD->isTrivial() || 6457 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6458 // A trivial destructor just ends the lifetime of the object. Check for 6459 // this case before checking for a body, because we might not bother 6460 // building a body for a trivial destructor. Note that it doesn't matter 6461 // whether the destructor is constexpr in this case; all trivial 6462 // destructors are constexpr. 6463 // 6464 // If an anonymous union would be destroyed, some enclosing destructor must 6465 // have been explicitly defined, and the anonymous union destruction should 6466 // have no effect. 6467 Value = APValue(); 6468 return true; 6469 } 6470 6471 if (!Info.CheckCallLimit(CallLoc)) 6472 return false; 6473 6474 const FunctionDecl *Definition = nullptr; 6475 const Stmt *Body = DD->getBody(Definition); 6476 6477 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6478 return false; 6479 6480 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6481 6482 // We're now in the period of destruction of this object. 6483 unsigned BasesLeft = RD->getNumBases(); 6484 EvalInfo::EvaluatingDestructorRAII EvalObj( 6485 Info, 6486 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6487 if (!EvalObj.DidInsert) { 6488 // C++2a [class.dtor]p19: 6489 // the behavior is undefined if the destructor is invoked for an object 6490 // whose lifetime has ended 6491 // (Note that formally the lifetime ends when the period of destruction 6492 // begins, even though certain uses of the object remain valid until the 6493 // period of destruction ends.) 6494 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6495 return false; 6496 } 6497 6498 // FIXME: Creating an APValue just to hold a nonexistent return value is 6499 // wasteful. 6500 APValue RetVal; 6501 StmtResult Ret = {RetVal, nullptr}; 6502 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6503 return false; 6504 6505 // A union destructor does not implicitly destroy its members. 6506 if (RD->isUnion()) 6507 return true; 6508 6509 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6510 6511 // We don't have a good way to iterate fields in reverse, so collect all the 6512 // fields first and then walk them backwards. 6513 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6514 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6515 if (FD->isUnnamedBitfield()) 6516 continue; 6517 6518 LValue Subobject = This; 6519 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6520 return false; 6521 6522 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6523 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6524 FD->getType())) 6525 return false; 6526 } 6527 6528 if (BasesLeft != 0) 6529 EvalObj.startedDestroyingBases(); 6530 6531 // Destroy base classes in reverse order. 6532 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6533 --BasesLeft; 6534 6535 QualType BaseType = Base.getType(); 6536 LValue Subobject = This; 6537 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6538 BaseType->getAsCXXRecordDecl(), &Layout)) 6539 return false; 6540 6541 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6542 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6543 BaseType)) 6544 return false; 6545 } 6546 assert(BasesLeft == 0 && "NumBases was wrong?"); 6547 6548 // The period of destruction ends now. The object is gone. 6549 Value = APValue(); 6550 return true; 6551 } 6552 6553 namespace { 6554 struct DestroyObjectHandler { 6555 EvalInfo &Info; 6556 const Expr *E; 6557 const LValue &This; 6558 const AccessKinds AccessKind; 6559 6560 typedef bool result_type; 6561 bool failed() { return false; } 6562 bool found(APValue &Subobj, QualType SubobjType) { 6563 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6564 SubobjType); 6565 } 6566 bool found(APSInt &Value, QualType SubobjType) { 6567 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6568 return false; 6569 } 6570 bool found(APFloat &Value, QualType SubobjType) { 6571 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6572 return false; 6573 } 6574 }; 6575 } 6576 6577 /// Perform a destructor or pseudo-destructor call on the given object, which 6578 /// might in general not be a complete object. 6579 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6580 const LValue &This, QualType ThisType) { 6581 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6582 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6583 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6584 } 6585 6586 /// Destroy and end the lifetime of the given complete object. 6587 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6588 APValue::LValueBase LVBase, APValue &Value, 6589 QualType T) { 6590 // If we've had an unmodeled side-effect, we can't rely on mutable state 6591 // (such as the object we're about to destroy) being correct. 6592 if (Info.EvalStatus.HasSideEffects) 6593 return false; 6594 6595 LValue LV; 6596 LV.set({LVBase}); 6597 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6598 } 6599 6600 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6601 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6602 LValue &Result) { 6603 if (Info.checkingPotentialConstantExpression() || 6604 Info.SpeculativeEvaluationDepth) 6605 return false; 6606 6607 // This is permitted only within a call to std::allocator<T>::allocate. 6608 auto Caller = Info.getStdAllocatorCaller("allocate"); 6609 if (!Caller) { 6610 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6611 ? diag::note_constexpr_new_untyped 6612 : diag::note_constexpr_new); 6613 return false; 6614 } 6615 6616 QualType ElemType = Caller.ElemType; 6617 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6618 Info.FFDiag(E->getExprLoc(), 6619 diag::note_constexpr_new_not_complete_object_type) 6620 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6621 return false; 6622 } 6623 6624 APSInt ByteSize; 6625 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6626 return false; 6627 bool IsNothrow = false; 6628 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6629 EvaluateIgnoredValue(Info, E->getArg(I)); 6630 IsNothrow |= E->getType()->isNothrowT(); 6631 } 6632 6633 CharUnits ElemSize; 6634 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6635 return false; 6636 APInt Size, Remainder; 6637 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6638 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6639 if (Remainder != 0) { 6640 // This likely indicates a bug in the implementation of 'std::allocator'. 6641 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6642 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6643 return false; 6644 } 6645 6646 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6647 if (IsNothrow) { 6648 Result.setNull(Info.Ctx, E->getType()); 6649 return true; 6650 } 6651 6652 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6653 return false; 6654 } 6655 6656 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6657 ArrayType::Normal, 0); 6658 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6659 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6660 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6661 return true; 6662 } 6663 6664 static bool hasVirtualDestructor(QualType T) { 6665 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6666 if (CXXDestructorDecl *DD = RD->getDestructor()) 6667 return DD->isVirtual(); 6668 return false; 6669 } 6670 6671 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6672 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6673 if (CXXDestructorDecl *DD = RD->getDestructor()) 6674 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6675 return nullptr; 6676 } 6677 6678 /// Check that the given object is a suitable pointer to a heap allocation that 6679 /// still exists and is of the right kind for the purpose of a deletion. 6680 /// 6681 /// On success, returns the heap allocation to deallocate. On failure, produces 6682 /// a diagnostic and returns None. 6683 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6684 const LValue &Pointer, 6685 DynAlloc::Kind DeallocKind) { 6686 auto PointerAsString = [&] { 6687 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6688 }; 6689 6690 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6691 if (!DA) { 6692 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6693 << PointerAsString(); 6694 if (Pointer.Base) 6695 NoteLValueLocation(Info, Pointer.Base); 6696 return None; 6697 } 6698 6699 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6700 if (!Alloc) { 6701 Info.FFDiag(E, diag::note_constexpr_double_delete); 6702 return None; 6703 } 6704 6705 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6706 if (DeallocKind != (*Alloc)->getKind()) { 6707 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6708 << DeallocKind << (*Alloc)->getKind() << AllocType; 6709 NoteLValueLocation(Info, Pointer.Base); 6710 return None; 6711 } 6712 6713 bool Subobject = false; 6714 if (DeallocKind == DynAlloc::New) { 6715 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6716 Pointer.Designator.isOnePastTheEnd(); 6717 } else { 6718 Subobject = Pointer.Designator.Entries.size() != 1 || 6719 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6720 } 6721 if (Subobject) { 6722 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6723 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6724 return None; 6725 } 6726 6727 return Alloc; 6728 } 6729 6730 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6731 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6732 if (Info.checkingPotentialConstantExpression() || 6733 Info.SpeculativeEvaluationDepth) 6734 return false; 6735 6736 // This is permitted only within a call to std::allocator<T>::deallocate. 6737 if (!Info.getStdAllocatorCaller("deallocate")) { 6738 Info.FFDiag(E->getExprLoc()); 6739 return true; 6740 } 6741 6742 LValue Pointer; 6743 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6744 return false; 6745 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6746 EvaluateIgnoredValue(Info, E->getArg(I)); 6747 6748 if (Pointer.Designator.Invalid) 6749 return false; 6750 6751 // Deleting a null pointer would have no effect, but it's not permitted by 6752 // std::allocator<T>::deallocate's contract. 6753 if (Pointer.isNullPointer()) { 6754 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6755 return true; 6756 } 6757 6758 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6759 return false; 6760 6761 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6762 return true; 6763 } 6764 6765 //===----------------------------------------------------------------------===// 6766 // Generic Evaluation 6767 //===----------------------------------------------------------------------===// 6768 namespace { 6769 6770 class BitCastBuffer { 6771 // FIXME: We're going to need bit-level granularity when we support 6772 // bit-fields. 6773 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6774 // we don't support a host or target where that is the case. Still, we should 6775 // use a more generic type in case we ever do. 6776 SmallVector<Optional<unsigned char>, 32> Bytes; 6777 6778 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6779 "Need at least 8 bit unsigned char"); 6780 6781 bool TargetIsLittleEndian; 6782 6783 public: 6784 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6785 : Bytes(Width.getQuantity()), 6786 TargetIsLittleEndian(TargetIsLittleEndian) {} 6787 6788 LLVM_NODISCARD 6789 bool readObject(CharUnits Offset, CharUnits Width, 6790 SmallVectorImpl<unsigned char> &Output) const { 6791 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6792 // If a byte of an integer is uninitialized, then the whole integer is 6793 // uninitialized. 6794 if (!Bytes[I.getQuantity()]) 6795 return false; 6796 Output.push_back(*Bytes[I.getQuantity()]); 6797 } 6798 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6799 std::reverse(Output.begin(), Output.end()); 6800 return true; 6801 } 6802 6803 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6804 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6805 std::reverse(Input.begin(), Input.end()); 6806 6807 size_t Index = 0; 6808 for (unsigned char Byte : Input) { 6809 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6810 Bytes[Offset.getQuantity() + Index] = Byte; 6811 ++Index; 6812 } 6813 } 6814 6815 size_t size() { return Bytes.size(); } 6816 }; 6817 6818 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6819 /// target would represent the value at runtime. 6820 class APValueToBufferConverter { 6821 EvalInfo &Info; 6822 BitCastBuffer Buffer; 6823 const CastExpr *BCE; 6824 6825 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6826 const CastExpr *BCE) 6827 : Info(Info), 6828 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6829 BCE(BCE) {} 6830 6831 bool visit(const APValue &Val, QualType Ty) { 6832 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6833 } 6834 6835 // Write out Val with type Ty into Buffer starting at Offset. 6836 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6837 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6838 6839 // As a special case, nullptr_t has an indeterminate value. 6840 if (Ty->isNullPtrType()) 6841 return true; 6842 6843 // Dig through Src to find the byte at SrcOffset. 6844 switch (Val.getKind()) { 6845 case APValue::Indeterminate: 6846 case APValue::None: 6847 return true; 6848 6849 case APValue::Int: 6850 return visitInt(Val.getInt(), Ty, Offset); 6851 case APValue::Float: 6852 return visitFloat(Val.getFloat(), Ty, Offset); 6853 case APValue::Array: 6854 return visitArray(Val, Ty, Offset); 6855 case APValue::Struct: 6856 return visitRecord(Val, Ty, Offset); 6857 6858 case APValue::ComplexInt: 6859 case APValue::ComplexFloat: 6860 case APValue::Vector: 6861 case APValue::FixedPoint: 6862 // FIXME: We should support these. 6863 6864 case APValue::Union: 6865 case APValue::MemberPointer: 6866 case APValue::AddrLabelDiff: { 6867 Info.FFDiag(BCE->getBeginLoc(), 6868 diag::note_constexpr_bit_cast_unsupported_type) 6869 << Ty; 6870 return false; 6871 } 6872 6873 case APValue::LValue: 6874 llvm_unreachable("LValue subobject in bit_cast?"); 6875 } 6876 llvm_unreachable("Unhandled APValue::ValueKind"); 6877 } 6878 6879 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6880 const RecordDecl *RD = Ty->getAsRecordDecl(); 6881 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6882 6883 // Visit the base classes. 6884 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6885 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6886 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6887 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6888 6889 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6890 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6891 return false; 6892 } 6893 } 6894 6895 // Visit the fields. 6896 unsigned FieldIdx = 0; 6897 for (FieldDecl *FD : RD->fields()) { 6898 if (FD->isBitField()) { 6899 Info.FFDiag(BCE->getBeginLoc(), 6900 diag::note_constexpr_bit_cast_unsupported_bitfield); 6901 return false; 6902 } 6903 6904 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6905 6906 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6907 "only bit-fields can have sub-char alignment"); 6908 CharUnits FieldOffset = 6909 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6910 QualType FieldTy = FD->getType(); 6911 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6912 return false; 6913 ++FieldIdx; 6914 } 6915 6916 return true; 6917 } 6918 6919 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6920 const auto *CAT = 6921 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6922 if (!CAT) 6923 return false; 6924 6925 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6926 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6927 unsigned ArraySize = Val.getArraySize(); 6928 // First, initialize the initialized elements. 6929 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6930 const APValue &SubObj = Val.getArrayInitializedElt(I); 6931 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6932 return false; 6933 } 6934 6935 // Next, initialize the rest of the array using the filler. 6936 if (Val.hasArrayFiller()) { 6937 const APValue &Filler = Val.getArrayFiller(); 6938 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6939 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6940 return false; 6941 } 6942 } 6943 6944 return true; 6945 } 6946 6947 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6948 APSInt AdjustedVal = Val; 6949 unsigned Width = AdjustedVal.getBitWidth(); 6950 if (Ty->isBooleanType()) { 6951 Width = Info.Ctx.getTypeSize(Ty); 6952 AdjustedVal = AdjustedVal.extend(Width); 6953 } 6954 6955 SmallVector<unsigned char, 8> Bytes(Width / 8); 6956 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6957 Buffer.writeObject(Offset, Bytes); 6958 return true; 6959 } 6960 6961 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6962 APSInt AsInt(Val.bitcastToAPInt()); 6963 return visitInt(AsInt, Ty, Offset); 6964 } 6965 6966 public: 6967 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6968 const CastExpr *BCE) { 6969 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6970 APValueToBufferConverter Converter(Info, DstSize, BCE); 6971 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6972 return None; 6973 return Converter.Buffer; 6974 } 6975 }; 6976 6977 /// Write an BitCastBuffer into an APValue. 6978 class BufferToAPValueConverter { 6979 EvalInfo &Info; 6980 const BitCastBuffer &Buffer; 6981 const CastExpr *BCE; 6982 6983 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6984 const CastExpr *BCE) 6985 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6986 6987 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6988 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6989 // Ideally this will be unreachable. 6990 llvm::NoneType unsupportedType(QualType Ty) { 6991 Info.FFDiag(BCE->getBeginLoc(), 6992 diag::note_constexpr_bit_cast_unsupported_type) 6993 << Ty; 6994 return None; 6995 } 6996 6997 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6998 Info.FFDiag(BCE->getBeginLoc(), 6999 diag::note_constexpr_bit_cast_unrepresentable_value) 7000 << Ty << toString(Val, /*Radix=*/10); 7001 return None; 7002 } 7003 7004 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 7005 const EnumType *EnumSugar = nullptr) { 7006 if (T->isNullPtrType()) { 7007 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 7008 return APValue((Expr *)nullptr, 7009 /*Offset=*/CharUnits::fromQuantity(NullValue), 7010 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 7011 } 7012 7013 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 7014 7015 // Work around floating point types that contain unused padding bytes. This 7016 // is really just `long double` on x86, which is the only fundamental type 7017 // with padding bytes. 7018 if (T->isRealFloatingType()) { 7019 const llvm::fltSemantics &Semantics = 7020 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7021 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 7022 assert(NumBits % 8 == 0); 7023 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 7024 if (NumBytes != SizeOf) 7025 SizeOf = NumBytes; 7026 } 7027 7028 SmallVector<uint8_t, 8> Bytes; 7029 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7030 // If this is std::byte or unsigned char, then its okay to store an 7031 // indeterminate value. 7032 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7033 bool IsUChar = 7034 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7035 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7036 if (!IsStdByte && !IsUChar) { 7037 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7038 Info.FFDiag(BCE->getExprLoc(), 7039 diag::note_constexpr_bit_cast_indet_dest) 7040 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7041 return None; 7042 } 7043 7044 return APValue::IndeterminateValue(); 7045 } 7046 7047 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7048 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7049 7050 if (T->isIntegralOrEnumerationType()) { 7051 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7052 7053 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7054 if (IntWidth != Val.getBitWidth()) { 7055 APSInt Truncated = Val.trunc(IntWidth); 7056 if (Truncated.extend(Val.getBitWidth()) != Val) 7057 return unrepresentableValue(QualType(T, 0), Val); 7058 Val = Truncated; 7059 } 7060 7061 return APValue(Val); 7062 } 7063 7064 if (T->isRealFloatingType()) { 7065 const llvm::fltSemantics &Semantics = 7066 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7067 return APValue(APFloat(Semantics, Val)); 7068 } 7069 7070 return unsupportedType(QualType(T, 0)); 7071 } 7072 7073 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7074 const RecordDecl *RD = RTy->getAsRecordDecl(); 7075 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7076 7077 unsigned NumBases = 0; 7078 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7079 NumBases = CXXRD->getNumBases(); 7080 7081 APValue ResultVal(APValue::UninitStruct(), NumBases, 7082 std::distance(RD->field_begin(), RD->field_end())); 7083 7084 // Visit the base classes. 7085 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7086 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7087 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7088 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7089 if (BaseDecl->isEmpty() || 7090 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7091 continue; 7092 7093 Optional<APValue> SubObj = visitType( 7094 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7095 if (!SubObj) 7096 return None; 7097 ResultVal.getStructBase(I) = *SubObj; 7098 } 7099 } 7100 7101 // Visit the fields. 7102 unsigned FieldIdx = 0; 7103 for (FieldDecl *FD : RD->fields()) { 7104 // FIXME: We don't currently support bit-fields. A lot of the logic for 7105 // this is in CodeGen, so we need to factor it around. 7106 if (FD->isBitField()) { 7107 Info.FFDiag(BCE->getBeginLoc(), 7108 diag::note_constexpr_bit_cast_unsupported_bitfield); 7109 return None; 7110 } 7111 7112 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7113 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7114 7115 CharUnits FieldOffset = 7116 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7117 Offset; 7118 QualType FieldTy = FD->getType(); 7119 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7120 if (!SubObj) 7121 return None; 7122 ResultVal.getStructField(FieldIdx) = *SubObj; 7123 ++FieldIdx; 7124 } 7125 7126 return ResultVal; 7127 } 7128 7129 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7130 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7131 assert(!RepresentationType.isNull() && 7132 "enum forward decl should be caught by Sema"); 7133 const auto *AsBuiltin = 7134 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7135 // Recurse into the underlying type. Treat std::byte transparently as 7136 // unsigned char. 7137 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7138 } 7139 7140 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7141 size_t Size = Ty->getSize().getLimitedValue(); 7142 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7143 7144 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7145 for (size_t I = 0; I != Size; ++I) { 7146 Optional<APValue> ElementValue = 7147 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7148 if (!ElementValue) 7149 return None; 7150 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7151 } 7152 7153 return ArrayValue; 7154 } 7155 7156 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7157 return unsupportedType(QualType(Ty, 0)); 7158 } 7159 7160 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7161 QualType Can = Ty.getCanonicalType(); 7162 7163 switch (Can->getTypeClass()) { 7164 #define TYPE(Class, Base) \ 7165 case Type::Class: \ 7166 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7167 #define ABSTRACT_TYPE(Class, Base) 7168 #define NON_CANONICAL_TYPE(Class, Base) \ 7169 case Type::Class: \ 7170 llvm_unreachable("non-canonical type should be impossible!"); 7171 #define DEPENDENT_TYPE(Class, Base) \ 7172 case Type::Class: \ 7173 llvm_unreachable( \ 7174 "dependent types aren't supported in the constant evaluator!"); 7175 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7176 case Type::Class: \ 7177 llvm_unreachable("either dependent or not canonical!"); 7178 #include "clang/AST/TypeNodes.inc" 7179 } 7180 llvm_unreachable("Unhandled Type::TypeClass"); 7181 } 7182 7183 public: 7184 // Pull out a full value of type DstType. 7185 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7186 const CastExpr *BCE) { 7187 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7188 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7189 } 7190 }; 7191 7192 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7193 QualType Ty, EvalInfo *Info, 7194 const ASTContext &Ctx, 7195 bool CheckingDest) { 7196 Ty = Ty.getCanonicalType(); 7197 7198 auto diag = [&](int Reason) { 7199 if (Info) 7200 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7201 << CheckingDest << (Reason == 4) << Reason; 7202 return false; 7203 }; 7204 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7205 if (Info) 7206 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7207 << NoteTy << Construct << Ty; 7208 return false; 7209 }; 7210 7211 if (Ty->isUnionType()) 7212 return diag(0); 7213 if (Ty->isPointerType()) 7214 return diag(1); 7215 if (Ty->isMemberPointerType()) 7216 return diag(2); 7217 if (Ty.isVolatileQualified()) 7218 return diag(3); 7219 7220 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7221 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7222 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7223 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7224 CheckingDest)) 7225 return note(1, BS.getType(), BS.getBeginLoc()); 7226 } 7227 for (FieldDecl *FD : Record->fields()) { 7228 if (FD->getType()->isReferenceType()) 7229 return diag(4); 7230 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7231 CheckingDest)) 7232 return note(0, FD->getType(), FD->getBeginLoc()); 7233 } 7234 } 7235 7236 if (Ty->isArrayType() && 7237 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7238 Info, Ctx, CheckingDest)) 7239 return false; 7240 7241 return true; 7242 } 7243 7244 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7245 const ASTContext &Ctx, 7246 const CastExpr *BCE) { 7247 bool DestOK = checkBitCastConstexprEligibilityType( 7248 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7249 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7250 BCE->getBeginLoc(), 7251 BCE->getSubExpr()->getType(), Info, Ctx, false); 7252 return SourceOK; 7253 } 7254 7255 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7256 APValue &SourceValue, 7257 const CastExpr *BCE) { 7258 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7259 "no host or target supports non 8-bit chars"); 7260 assert(SourceValue.isLValue() && 7261 "LValueToRValueBitcast requires an lvalue operand!"); 7262 7263 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7264 return false; 7265 7266 LValue SourceLValue; 7267 APValue SourceRValue; 7268 SourceLValue.setFrom(Info.Ctx, SourceValue); 7269 if (!handleLValueToRValueConversion( 7270 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7271 SourceRValue, /*WantObjectRepresentation=*/true)) 7272 return false; 7273 7274 // Read out SourceValue into a char buffer. 7275 Optional<BitCastBuffer> Buffer = 7276 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7277 if (!Buffer) 7278 return false; 7279 7280 // Write out the buffer into a new APValue. 7281 Optional<APValue> MaybeDestValue = 7282 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7283 if (!MaybeDestValue) 7284 return false; 7285 7286 DestValue = std::move(*MaybeDestValue); 7287 return true; 7288 } 7289 7290 template <class Derived> 7291 class ExprEvaluatorBase 7292 : public ConstStmtVisitor<Derived, bool> { 7293 private: 7294 Derived &getDerived() { return static_cast<Derived&>(*this); } 7295 bool DerivedSuccess(const APValue &V, const Expr *E) { 7296 return getDerived().Success(V, E); 7297 } 7298 bool DerivedZeroInitialization(const Expr *E) { 7299 return getDerived().ZeroInitialization(E); 7300 } 7301 7302 // Check whether a conditional operator with a non-constant condition is a 7303 // potential constant expression. If neither arm is a potential constant 7304 // expression, then the conditional operator is not either. 7305 template<typename ConditionalOperator> 7306 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7307 assert(Info.checkingPotentialConstantExpression()); 7308 7309 // Speculatively evaluate both arms. 7310 SmallVector<PartialDiagnosticAt, 8> Diag; 7311 { 7312 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7313 StmtVisitorTy::Visit(E->getFalseExpr()); 7314 if (Diag.empty()) 7315 return; 7316 } 7317 7318 { 7319 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7320 Diag.clear(); 7321 StmtVisitorTy::Visit(E->getTrueExpr()); 7322 if (Diag.empty()) 7323 return; 7324 } 7325 7326 Error(E, diag::note_constexpr_conditional_never_const); 7327 } 7328 7329 7330 template<typename ConditionalOperator> 7331 bool HandleConditionalOperator(const ConditionalOperator *E) { 7332 bool BoolResult; 7333 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7334 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7335 CheckPotentialConstantConditional(E); 7336 return false; 7337 } 7338 if (Info.noteFailure()) { 7339 StmtVisitorTy::Visit(E->getTrueExpr()); 7340 StmtVisitorTy::Visit(E->getFalseExpr()); 7341 } 7342 return false; 7343 } 7344 7345 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7346 return StmtVisitorTy::Visit(EvalExpr); 7347 } 7348 7349 protected: 7350 EvalInfo &Info; 7351 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7352 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7353 7354 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7355 return Info.CCEDiag(E, D); 7356 } 7357 7358 bool ZeroInitialization(const Expr *E) { return Error(E); } 7359 7360 public: 7361 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7362 7363 EvalInfo &getEvalInfo() { return Info; } 7364 7365 /// Report an evaluation error. This should only be called when an error is 7366 /// first discovered. When propagating an error, just return false. 7367 bool Error(const Expr *E, diag::kind D) { 7368 Info.FFDiag(E, D); 7369 return false; 7370 } 7371 bool Error(const Expr *E) { 7372 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7373 } 7374 7375 bool VisitStmt(const Stmt *) { 7376 llvm_unreachable("Expression evaluator should not be called on stmts"); 7377 } 7378 bool VisitExpr(const Expr *E) { 7379 return Error(E); 7380 } 7381 7382 bool VisitConstantExpr(const ConstantExpr *E) { 7383 if (E->hasAPValueResult()) 7384 return DerivedSuccess(E->getAPValueResult(), E); 7385 7386 return StmtVisitorTy::Visit(E->getSubExpr()); 7387 } 7388 7389 bool VisitParenExpr(const ParenExpr *E) 7390 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7391 bool VisitUnaryExtension(const UnaryOperator *E) 7392 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7393 bool VisitUnaryPlus(const UnaryOperator *E) 7394 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7395 bool VisitChooseExpr(const ChooseExpr *E) 7396 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7397 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7398 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7399 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7400 { return StmtVisitorTy::Visit(E->getReplacement()); } 7401 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7402 TempVersionRAII RAII(*Info.CurrentCall); 7403 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7404 return StmtVisitorTy::Visit(E->getExpr()); 7405 } 7406 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7407 TempVersionRAII RAII(*Info.CurrentCall); 7408 // The initializer may not have been parsed yet, or might be erroneous. 7409 if (!E->getExpr()) 7410 return Error(E); 7411 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7412 return StmtVisitorTy::Visit(E->getExpr()); 7413 } 7414 7415 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7416 FullExpressionRAII Scope(Info); 7417 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7418 } 7419 7420 // Temporaries are registered when created, so we don't care about 7421 // CXXBindTemporaryExpr. 7422 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7423 return StmtVisitorTy::Visit(E->getSubExpr()); 7424 } 7425 7426 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7427 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7428 return static_cast<Derived*>(this)->VisitCastExpr(E); 7429 } 7430 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7431 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7432 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7433 return static_cast<Derived*>(this)->VisitCastExpr(E); 7434 } 7435 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7436 return static_cast<Derived*>(this)->VisitCastExpr(E); 7437 } 7438 7439 bool VisitBinaryOperator(const BinaryOperator *E) { 7440 switch (E->getOpcode()) { 7441 default: 7442 return Error(E); 7443 7444 case BO_Comma: 7445 VisitIgnoredValue(E->getLHS()); 7446 return StmtVisitorTy::Visit(E->getRHS()); 7447 7448 case BO_PtrMemD: 7449 case BO_PtrMemI: { 7450 LValue Obj; 7451 if (!HandleMemberPointerAccess(Info, E, Obj)) 7452 return false; 7453 APValue Result; 7454 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7455 return false; 7456 return DerivedSuccess(Result, E); 7457 } 7458 } 7459 } 7460 7461 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7462 return StmtVisitorTy::Visit(E->getSemanticForm()); 7463 } 7464 7465 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7466 // Evaluate and cache the common expression. We treat it as a temporary, 7467 // even though it's not quite the same thing. 7468 LValue CommonLV; 7469 if (!Evaluate(Info.CurrentCall->createTemporary( 7470 E->getOpaqueValue(), 7471 getStorageType(Info.Ctx, E->getOpaqueValue()), 7472 ScopeKind::FullExpression, CommonLV), 7473 Info, E->getCommon())) 7474 return false; 7475 7476 return HandleConditionalOperator(E); 7477 } 7478 7479 bool VisitConditionalOperator(const ConditionalOperator *E) { 7480 bool IsBcpCall = false; 7481 // If the condition (ignoring parens) is a __builtin_constant_p call, 7482 // the result is a constant expression if it can be folded without 7483 // side-effects. This is an important GNU extension. See GCC PR38377 7484 // for discussion. 7485 if (const CallExpr *CallCE = 7486 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7487 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7488 IsBcpCall = true; 7489 7490 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7491 // constant expression; we can't check whether it's potentially foldable. 7492 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7493 // it would return 'false' in this mode. 7494 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7495 return false; 7496 7497 FoldConstant Fold(Info, IsBcpCall); 7498 if (!HandleConditionalOperator(E)) { 7499 Fold.keepDiagnostics(); 7500 return false; 7501 } 7502 7503 return true; 7504 } 7505 7506 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7507 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7508 return DerivedSuccess(*Value, E); 7509 7510 const Expr *Source = E->getSourceExpr(); 7511 if (!Source) 7512 return Error(E); 7513 if (Source == E) { 7514 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7515 return Error(E); 7516 } 7517 return StmtVisitorTy::Visit(Source); 7518 } 7519 7520 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7521 for (const Expr *SemE : E->semantics()) { 7522 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7523 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7524 // result expression: there could be two different LValues that would 7525 // refer to the same object in that case, and we can't model that. 7526 if (SemE == E->getResultExpr()) 7527 return Error(E); 7528 7529 // Unique OVEs get evaluated if and when we encounter them when 7530 // emitting the rest of the semantic form, rather than eagerly. 7531 if (OVE->isUnique()) 7532 continue; 7533 7534 LValue LV; 7535 if (!Evaluate(Info.CurrentCall->createTemporary( 7536 OVE, getStorageType(Info.Ctx, OVE), 7537 ScopeKind::FullExpression, LV), 7538 Info, OVE->getSourceExpr())) 7539 return false; 7540 } else if (SemE == E->getResultExpr()) { 7541 if (!StmtVisitorTy::Visit(SemE)) 7542 return false; 7543 } else { 7544 if (!EvaluateIgnoredValue(Info, SemE)) 7545 return false; 7546 } 7547 } 7548 return true; 7549 } 7550 7551 bool VisitCallExpr(const CallExpr *E) { 7552 APValue Result; 7553 if (!handleCallExpr(E, Result, nullptr)) 7554 return false; 7555 return DerivedSuccess(Result, E); 7556 } 7557 7558 bool handleCallExpr(const CallExpr *E, APValue &Result, 7559 const LValue *ResultSlot) { 7560 CallScopeRAII CallScope(Info); 7561 7562 const Expr *Callee = E->getCallee()->IgnoreParens(); 7563 QualType CalleeType = Callee->getType(); 7564 7565 const FunctionDecl *FD = nullptr; 7566 LValue *This = nullptr, ThisVal; 7567 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7568 bool HasQualifier = false; 7569 7570 CallRef Call; 7571 7572 // Extract function decl and 'this' pointer from the callee. 7573 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7574 const CXXMethodDecl *Member = nullptr; 7575 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7576 // Explicit bound member calls, such as x.f() or p->g(); 7577 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7578 return false; 7579 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7580 if (!Member) 7581 return Error(Callee); 7582 This = &ThisVal; 7583 HasQualifier = ME->hasQualifier(); 7584 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7585 // Indirect bound member calls ('.*' or '->*'). 7586 const ValueDecl *D = 7587 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7588 if (!D) 7589 return false; 7590 Member = dyn_cast<CXXMethodDecl>(D); 7591 if (!Member) 7592 return Error(Callee); 7593 This = &ThisVal; 7594 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7595 if (!Info.getLangOpts().CPlusPlus20) 7596 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7597 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7598 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7599 } else 7600 return Error(Callee); 7601 FD = Member; 7602 } else if (CalleeType->isFunctionPointerType()) { 7603 LValue CalleeLV; 7604 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7605 return false; 7606 7607 if (!CalleeLV.getLValueOffset().isZero()) 7608 return Error(Callee); 7609 FD = dyn_cast_or_null<FunctionDecl>( 7610 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7611 if (!FD) 7612 return Error(Callee); 7613 // Don't call function pointers which have been cast to some other type. 7614 // Per DR (no number yet), the caller and callee can differ in noexcept. 7615 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7616 CalleeType->getPointeeType(), FD->getType())) { 7617 return Error(E); 7618 } 7619 7620 // For an (overloaded) assignment expression, evaluate the RHS before the 7621 // LHS. 7622 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7623 if (OCE && OCE->isAssignmentOp()) { 7624 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7625 Call = Info.CurrentCall->createCall(FD); 7626 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7627 Info, FD, /*RightToLeft=*/true)) 7628 return false; 7629 } 7630 7631 // Overloaded operator calls to member functions are represented as normal 7632 // calls with '*this' as the first argument. 7633 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7634 if (MD && !MD->isStatic()) { 7635 // FIXME: When selecting an implicit conversion for an overloaded 7636 // operator delete, we sometimes try to evaluate calls to conversion 7637 // operators without a 'this' parameter! 7638 if (Args.empty()) 7639 return Error(E); 7640 7641 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7642 return false; 7643 This = &ThisVal; 7644 Args = Args.slice(1); 7645 } else if (MD && MD->isLambdaStaticInvoker()) { 7646 // Map the static invoker for the lambda back to the call operator. 7647 // Conveniently, we don't have to slice out the 'this' argument (as is 7648 // being done for the non-static case), since a static member function 7649 // doesn't have an implicit argument passed in. 7650 const CXXRecordDecl *ClosureClass = MD->getParent(); 7651 assert( 7652 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7653 "Number of captures must be zero for conversion to function-ptr"); 7654 7655 const CXXMethodDecl *LambdaCallOp = 7656 ClosureClass->getLambdaCallOperator(); 7657 7658 // Set 'FD', the function that will be called below, to the call 7659 // operator. If the closure object represents a generic lambda, find 7660 // the corresponding specialization of the call operator. 7661 7662 if (ClosureClass->isGenericLambda()) { 7663 assert(MD->isFunctionTemplateSpecialization() && 7664 "A generic lambda's static-invoker function must be a " 7665 "template specialization"); 7666 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7667 FunctionTemplateDecl *CallOpTemplate = 7668 LambdaCallOp->getDescribedFunctionTemplate(); 7669 void *InsertPos = nullptr; 7670 FunctionDecl *CorrespondingCallOpSpecialization = 7671 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7672 assert(CorrespondingCallOpSpecialization && 7673 "We must always have a function call operator specialization " 7674 "that corresponds to our static invoker specialization"); 7675 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7676 } else 7677 FD = LambdaCallOp; 7678 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7679 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7680 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7681 LValue Ptr; 7682 if (!HandleOperatorNewCall(Info, E, Ptr)) 7683 return false; 7684 Ptr.moveInto(Result); 7685 return CallScope.destroy(); 7686 } else { 7687 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7688 } 7689 } 7690 } else 7691 return Error(E); 7692 7693 // Evaluate the arguments now if we've not already done so. 7694 if (!Call) { 7695 Call = Info.CurrentCall->createCall(FD); 7696 if (!EvaluateArgs(Args, Call, Info, FD)) 7697 return false; 7698 } 7699 7700 SmallVector<QualType, 4> CovariantAdjustmentPath; 7701 if (This) { 7702 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7703 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7704 // Perform virtual dispatch, if necessary. 7705 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7706 CovariantAdjustmentPath); 7707 if (!FD) 7708 return false; 7709 } else { 7710 // Check that the 'this' pointer points to an object of the right type. 7711 // FIXME: If this is an assignment operator call, we may need to change 7712 // the active union member before we check this. 7713 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7714 return false; 7715 } 7716 } 7717 7718 // Destructor calls are different enough that they have their own codepath. 7719 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7720 assert(This && "no 'this' pointer for destructor call"); 7721 return HandleDestruction(Info, E, *This, 7722 Info.Ctx.getRecordType(DD->getParent())) && 7723 CallScope.destroy(); 7724 } 7725 7726 const FunctionDecl *Definition = nullptr; 7727 Stmt *Body = FD->getBody(Definition); 7728 7729 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7730 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7731 Body, Info, Result, ResultSlot)) 7732 return false; 7733 7734 if (!CovariantAdjustmentPath.empty() && 7735 !HandleCovariantReturnAdjustment(Info, E, Result, 7736 CovariantAdjustmentPath)) 7737 return false; 7738 7739 return CallScope.destroy(); 7740 } 7741 7742 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7743 return StmtVisitorTy::Visit(E->getInitializer()); 7744 } 7745 bool VisitInitListExpr(const InitListExpr *E) { 7746 if (E->getNumInits() == 0) 7747 return DerivedZeroInitialization(E); 7748 if (E->getNumInits() == 1) 7749 return StmtVisitorTy::Visit(E->getInit(0)); 7750 return Error(E); 7751 } 7752 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7753 return DerivedZeroInitialization(E); 7754 } 7755 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7756 return DerivedZeroInitialization(E); 7757 } 7758 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7759 return DerivedZeroInitialization(E); 7760 } 7761 7762 /// A member expression where the object is a prvalue is itself a prvalue. 7763 bool VisitMemberExpr(const MemberExpr *E) { 7764 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7765 "missing temporary materialization conversion"); 7766 assert(!E->isArrow() && "missing call to bound member function?"); 7767 7768 APValue Val; 7769 if (!Evaluate(Val, Info, E->getBase())) 7770 return false; 7771 7772 QualType BaseTy = E->getBase()->getType(); 7773 7774 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7775 if (!FD) return Error(E); 7776 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7777 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7778 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7779 7780 // Note: there is no lvalue base here. But this case should only ever 7781 // happen in C or in C++98, where we cannot be evaluating a constexpr 7782 // constructor, which is the only case the base matters. 7783 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7784 SubobjectDesignator Designator(BaseTy); 7785 Designator.addDeclUnchecked(FD); 7786 7787 APValue Result; 7788 return extractSubobject(Info, E, Obj, Designator, Result) && 7789 DerivedSuccess(Result, E); 7790 } 7791 7792 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7793 APValue Val; 7794 if (!Evaluate(Val, Info, E->getBase())) 7795 return false; 7796 7797 if (Val.isVector()) { 7798 SmallVector<uint32_t, 4> Indices; 7799 E->getEncodedElementAccess(Indices); 7800 if (Indices.size() == 1) { 7801 // Return scalar. 7802 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7803 } else { 7804 // Construct new APValue vector. 7805 SmallVector<APValue, 4> Elts; 7806 for (unsigned I = 0; I < Indices.size(); ++I) { 7807 Elts.push_back(Val.getVectorElt(Indices[I])); 7808 } 7809 APValue VecResult(Elts.data(), Indices.size()); 7810 return DerivedSuccess(VecResult, E); 7811 } 7812 } 7813 7814 return false; 7815 } 7816 7817 bool VisitCastExpr(const CastExpr *E) { 7818 switch (E->getCastKind()) { 7819 default: 7820 break; 7821 7822 case CK_AtomicToNonAtomic: { 7823 APValue AtomicVal; 7824 // This does not need to be done in place even for class/array types: 7825 // atomic-to-non-atomic conversion implies copying the object 7826 // representation. 7827 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7828 return false; 7829 return DerivedSuccess(AtomicVal, E); 7830 } 7831 7832 case CK_NoOp: 7833 case CK_UserDefinedConversion: 7834 return StmtVisitorTy::Visit(E->getSubExpr()); 7835 7836 case CK_LValueToRValue: { 7837 LValue LVal; 7838 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7839 return false; 7840 APValue RVal; 7841 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7842 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7843 LVal, RVal)) 7844 return false; 7845 return DerivedSuccess(RVal, E); 7846 } 7847 case CK_LValueToRValueBitCast: { 7848 APValue DestValue, SourceValue; 7849 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7850 return false; 7851 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7852 return false; 7853 return DerivedSuccess(DestValue, E); 7854 } 7855 7856 case CK_AddressSpaceConversion: { 7857 APValue Value; 7858 if (!Evaluate(Value, Info, E->getSubExpr())) 7859 return false; 7860 return DerivedSuccess(Value, E); 7861 } 7862 } 7863 7864 return Error(E); 7865 } 7866 7867 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7868 return VisitUnaryPostIncDec(UO); 7869 } 7870 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7871 return VisitUnaryPostIncDec(UO); 7872 } 7873 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7874 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7875 return Error(UO); 7876 7877 LValue LVal; 7878 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7879 return false; 7880 APValue RVal; 7881 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7882 UO->isIncrementOp(), &RVal)) 7883 return false; 7884 return DerivedSuccess(RVal, UO); 7885 } 7886 7887 bool VisitStmtExpr(const StmtExpr *E) { 7888 // We will have checked the full-expressions inside the statement expression 7889 // when they were completed, and don't need to check them again now. 7890 llvm::SaveAndRestore<bool> NotCheckingForUB( 7891 Info.CheckingForUndefinedBehavior, false); 7892 7893 const CompoundStmt *CS = E->getSubStmt(); 7894 if (CS->body_empty()) 7895 return true; 7896 7897 BlockScopeRAII Scope(Info); 7898 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7899 BE = CS->body_end(); 7900 /**/; ++BI) { 7901 if (BI + 1 == BE) { 7902 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7903 if (!FinalExpr) { 7904 Info.FFDiag((*BI)->getBeginLoc(), 7905 diag::note_constexpr_stmt_expr_unsupported); 7906 return false; 7907 } 7908 return this->Visit(FinalExpr) && Scope.destroy(); 7909 } 7910 7911 APValue ReturnValue; 7912 StmtResult Result = { ReturnValue, nullptr }; 7913 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7914 if (ESR != ESR_Succeeded) { 7915 // FIXME: If the statement-expression terminated due to 'return', 7916 // 'break', or 'continue', it would be nice to propagate that to 7917 // the outer statement evaluation rather than bailing out. 7918 if (ESR != ESR_Failed) 7919 Info.FFDiag((*BI)->getBeginLoc(), 7920 diag::note_constexpr_stmt_expr_unsupported); 7921 return false; 7922 } 7923 } 7924 7925 llvm_unreachable("Return from function from the loop above."); 7926 } 7927 7928 /// Visit a value which is evaluated, but whose value is ignored. 7929 void VisitIgnoredValue(const Expr *E) { 7930 EvaluateIgnoredValue(Info, E); 7931 } 7932 7933 /// Potentially visit a MemberExpr's base expression. 7934 void VisitIgnoredBaseExpression(const Expr *E) { 7935 // While MSVC doesn't evaluate the base expression, it does diagnose the 7936 // presence of side-effecting behavior. 7937 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7938 return; 7939 VisitIgnoredValue(E); 7940 } 7941 }; 7942 7943 } // namespace 7944 7945 //===----------------------------------------------------------------------===// 7946 // Common base class for lvalue and temporary evaluation. 7947 //===----------------------------------------------------------------------===// 7948 namespace { 7949 template<class Derived> 7950 class LValueExprEvaluatorBase 7951 : public ExprEvaluatorBase<Derived> { 7952 protected: 7953 LValue &Result; 7954 bool InvalidBaseOK; 7955 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7956 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7957 7958 bool Success(APValue::LValueBase B) { 7959 Result.set(B); 7960 return true; 7961 } 7962 7963 bool evaluatePointer(const Expr *E, LValue &Result) { 7964 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7965 } 7966 7967 public: 7968 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7969 : ExprEvaluatorBaseTy(Info), Result(Result), 7970 InvalidBaseOK(InvalidBaseOK) {} 7971 7972 bool Success(const APValue &V, const Expr *E) { 7973 Result.setFrom(this->Info.Ctx, V); 7974 return true; 7975 } 7976 7977 bool VisitMemberExpr(const MemberExpr *E) { 7978 // Handle non-static data members. 7979 QualType BaseTy; 7980 bool EvalOK; 7981 if (E->isArrow()) { 7982 EvalOK = evaluatePointer(E->getBase(), Result); 7983 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7984 } else if (E->getBase()->isPRValue()) { 7985 assert(E->getBase()->getType()->isRecordType()); 7986 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7987 BaseTy = E->getBase()->getType(); 7988 } else { 7989 EvalOK = this->Visit(E->getBase()); 7990 BaseTy = E->getBase()->getType(); 7991 } 7992 if (!EvalOK) { 7993 if (!InvalidBaseOK) 7994 return false; 7995 Result.setInvalid(E); 7996 return true; 7997 } 7998 7999 const ValueDecl *MD = E->getMemberDecl(); 8000 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 8001 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 8002 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 8003 (void)BaseTy; 8004 if (!HandleLValueMember(this->Info, E, Result, FD)) 8005 return false; 8006 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 8007 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 8008 return false; 8009 } else 8010 return this->Error(E); 8011 8012 if (MD->getType()->isReferenceType()) { 8013 APValue RefValue; 8014 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 8015 RefValue)) 8016 return false; 8017 return Success(RefValue, E); 8018 } 8019 return true; 8020 } 8021 8022 bool VisitBinaryOperator(const BinaryOperator *E) { 8023 switch (E->getOpcode()) { 8024 default: 8025 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8026 8027 case BO_PtrMemD: 8028 case BO_PtrMemI: 8029 return HandleMemberPointerAccess(this->Info, E, Result); 8030 } 8031 } 8032 8033 bool VisitCastExpr(const CastExpr *E) { 8034 switch (E->getCastKind()) { 8035 default: 8036 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8037 8038 case CK_DerivedToBase: 8039 case CK_UncheckedDerivedToBase: 8040 if (!this->Visit(E->getSubExpr())) 8041 return false; 8042 8043 // Now figure out the necessary offset to add to the base LV to get from 8044 // the derived class to the base class. 8045 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8046 Result); 8047 } 8048 } 8049 }; 8050 } 8051 8052 //===----------------------------------------------------------------------===// 8053 // LValue Evaluation 8054 // 8055 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8056 // function designators (in C), decl references to void objects (in C), and 8057 // temporaries (if building with -Wno-address-of-temporary). 8058 // 8059 // LValue evaluation produces values comprising a base expression of one of the 8060 // following types: 8061 // - Declarations 8062 // * VarDecl 8063 // * FunctionDecl 8064 // - Literals 8065 // * CompoundLiteralExpr in C (and in global scope in C++) 8066 // * StringLiteral 8067 // * PredefinedExpr 8068 // * ObjCStringLiteralExpr 8069 // * ObjCEncodeExpr 8070 // * AddrLabelExpr 8071 // * BlockExpr 8072 // * CallExpr for a MakeStringConstant builtin 8073 // - typeid(T) expressions, as TypeInfoLValues 8074 // - Locals and temporaries 8075 // * MaterializeTemporaryExpr 8076 // * Any Expr, with a CallIndex indicating the function in which the temporary 8077 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8078 // from the AST (FIXME). 8079 // * A MaterializeTemporaryExpr that has static storage duration, with no 8080 // CallIndex, for a lifetime-extended temporary. 8081 // * The ConstantExpr that is currently being evaluated during evaluation of an 8082 // immediate invocation. 8083 // plus an offset in bytes. 8084 //===----------------------------------------------------------------------===// 8085 namespace { 8086 class LValueExprEvaluator 8087 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8088 public: 8089 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8090 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8091 8092 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8093 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8094 8095 bool VisitDeclRefExpr(const DeclRefExpr *E); 8096 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8097 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8098 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8099 bool VisitMemberExpr(const MemberExpr *E); 8100 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8101 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8102 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8103 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8104 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8105 bool VisitUnaryDeref(const UnaryOperator *E); 8106 bool VisitUnaryReal(const UnaryOperator *E); 8107 bool VisitUnaryImag(const UnaryOperator *E); 8108 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8109 return VisitUnaryPreIncDec(UO); 8110 } 8111 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8112 return VisitUnaryPreIncDec(UO); 8113 } 8114 bool VisitBinAssign(const BinaryOperator *BO); 8115 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8116 8117 bool VisitCastExpr(const CastExpr *E) { 8118 switch (E->getCastKind()) { 8119 default: 8120 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8121 8122 case CK_LValueBitCast: 8123 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8124 if (!Visit(E->getSubExpr())) 8125 return false; 8126 Result.Designator.setInvalid(); 8127 return true; 8128 8129 case CK_BaseToDerived: 8130 if (!Visit(E->getSubExpr())) 8131 return false; 8132 return HandleBaseToDerivedCast(Info, E, Result); 8133 8134 case CK_Dynamic: 8135 if (!Visit(E->getSubExpr())) 8136 return false; 8137 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8138 } 8139 } 8140 }; 8141 } // end anonymous namespace 8142 8143 /// Evaluate an expression as an lvalue. This can be legitimately called on 8144 /// expressions which are not glvalues, in three cases: 8145 /// * function designators in C, and 8146 /// * "extern void" objects 8147 /// * @selector() expressions in Objective-C 8148 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8149 bool InvalidBaseOK) { 8150 assert(!E->isValueDependent()); 8151 assert(E->isGLValue() || E->getType()->isFunctionType() || 8152 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8153 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8154 } 8155 8156 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8157 const NamedDecl *D = E->getDecl(); 8158 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8159 return Success(cast<ValueDecl>(D)); 8160 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8161 return VisitVarDecl(E, VD); 8162 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8163 return Visit(BD->getBinding()); 8164 return Error(E); 8165 } 8166 8167 8168 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8169 8170 // If we are within a lambda's call operator, check whether the 'VD' referred 8171 // to within 'E' actually represents a lambda-capture that maps to a 8172 // data-member/field within the closure object, and if so, evaluate to the 8173 // field or what the field refers to. 8174 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8175 isa<DeclRefExpr>(E) && 8176 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8177 // We don't always have a complete capture-map when checking or inferring if 8178 // the function call operator meets the requirements of a constexpr function 8179 // - but we don't need to evaluate the captures to determine constexprness 8180 // (dcl.constexpr C++17). 8181 if (Info.checkingPotentialConstantExpression()) 8182 return false; 8183 8184 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8185 // Start with 'Result' referring to the complete closure object... 8186 Result = *Info.CurrentCall->This; 8187 // ... then update it to refer to the field of the closure object 8188 // that represents the capture. 8189 if (!HandleLValueMember(Info, E, Result, FD)) 8190 return false; 8191 // And if the field is of reference type, update 'Result' to refer to what 8192 // the field refers to. 8193 if (FD->getType()->isReferenceType()) { 8194 APValue RVal; 8195 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8196 RVal)) 8197 return false; 8198 Result.setFrom(Info.Ctx, RVal); 8199 } 8200 return true; 8201 } 8202 } 8203 8204 CallStackFrame *Frame = nullptr; 8205 unsigned Version = 0; 8206 if (VD->hasLocalStorage()) { 8207 // Only if a local variable was declared in the function currently being 8208 // evaluated, do we expect to be able to find its value in the current 8209 // frame. (Otherwise it was likely declared in an enclosing context and 8210 // could either have a valid evaluatable value (for e.g. a constexpr 8211 // variable) or be ill-formed (and trigger an appropriate evaluation 8212 // diagnostic)). 8213 CallStackFrame *CurrFrame = Info.CurrentCall; 8214 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8215 // Function parameters are stored in some caller's frame. (Usually the 8216 // immediate caller, but for an inherited constructor they may be more 8217 // distant.) 8218 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8219 if (CurrFrame->Arguments) { 8220 VD = CurrFrame->Arguments.getOrigParam(PVD); 8221 Frame = 8222 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8223 Version = CurrFrame->Arguments.Version; 8224 } 8225 } else { 8226 Frame = CurrFrame; 8227 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8228 } 8229 } 8230 } 8231 8232 if (!VD->getType()->isReferenceType()) { 8233 if (Frame) { 8234 Result.set({VD, Frame->Index, Version}); 8235 return true; 8236 } 8237 return Success(VD); 8238 } 8239 8240 if (!Info.getLangOpts().CPlusPlus11) { 8241 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8242 << VD << VD->getType(); 8243 Info.Note(VD->getLocation(), diag::note_declared_at); 8244 } 8245 8246 APValue *V; 8247 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8248 return false; 8249 if (!V->hasValue()) { 8250 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8251 // adjust the diagnostic to say that. 8252 if (!Info.checkingPotentialConstantExpression()) 8253 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8254 return false; 8255 } 8256 return Success(*V, E); 8257 } 8258 8259 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8260 const MaterializeTemporaryExpr *E) { 8261 // Walk through the expression to find the materialized temporary itself. 8262 SmallVector<const Expr *, 2> CommaLHSs; 8263 SmallVector<SubobjectAdjustment, 2> Adjustments; 8264 const Expr *Inner = 8265 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8266 8267 // If we passed any comma operators, evaluate their LHSs. 8268 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8269 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8270 return false; 8271 8272 // A materialized temporary with static storage duration can appear within the 8273 // result of a constant expression evaluation, so we need to preserve its 8274 // value for use outside this evaluation. 8275 APValue *Value; 8276 if (E->getStorageDuration() == SD_Static) { 8277 // FIXME: What about SD_Thread? 8278 Value = E->getOrCreateValue(true); 8279 *Value = APValue(); 8280 Result.set(E); 8281 } else { 8282 Value = &Info.CurrentCall->createTemporary( 8283 E, E->getType(), 8284 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8285 : ScopeKind::Block, 8286 Result); 8287 } 8288 8289 QualType Type = Inner->getType(); 8290 8291 // Materialize the temporary itself. 8292 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8293 *Value = APValue(); 8294 return false; 8295 } 8296 8297 // Adjust our lvalue to refer to the desired subobject. 8298 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8299 --I; 8300 switch (Adjustments[I].Kind) { 8301 case SubobjectAdjustment::DerivedToBaseAdjustment: 8302 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8303 Type, Result)) 8304 return false; 8305 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8306 break; 8307 8308 case SubobjectAdjustment::FieldAdjustment: 8309 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8310 return false; 8311 Type = Adjustments[I].Field->getType(); 8312 break; 8313 8314 case SubobjectAdjustment::MemberPointerAdjustment: 8315 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8316 Adjustments[I].Ptr.RHS)) 8317 return false; 8318 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8319 break; 8320 } 8321 } 8322 8323 return true; 8324 } 8325 8326 bool 8327 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8328 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8329 "lvalue compound literal in c++?"); 8330 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8331 // only see this when folding in C, so there's no standard to follow here. 8332 return Success(E); 8333 } 8334 8335 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8336 TypeInfoLValue TypeInfo; 8337 8338 if (!E->isPotentiallyEvaluated()) { 8339 if (E->isTypeOperand()) 8340 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8341 else 8342 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8343 } else { 8344 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8345 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8346 << E->getExprOperand()->getType() 8347 << E->getExprOperand()->getSourceRange(); 8348 } 8349 8350 if (!Visit(E->getExprOperand())) 8351 return false; 8352 8353 Optional<DynamicType> DynType = 8354 ComputeDynamicType(Info, E, Result, AK_TypeId); 8355 if (!DynType) 8356 return false; 8357 8358 TypeInfo = 8359 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8360 } 8361 8362 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8363 } 8364 8365 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8366 return Success(E->getGuidDecl()); 8367 } 8368 8369 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8370 // Handle static data members. 8371 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8372 VisitIgnoredBaseExpression(E->getBase()); 8373 return VisitVarDecl(E, VD); 8374 } 8375 8376 // Handle static member functions. 8377 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8378 if (MD->isStatic()) { 8379 VisitIgnoredBaseExpression(E->getBase()); 8380 return Success(MD); 8381 } 8382 } 8383 8384 // Handle non-static data members. 8385 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8386 } 8387 8388 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8389 // FIXME: Deal with vectors as array subscript bases. 8390 if (E->getBase()->getType()->isVectorType()) 8391 return Error(E); 8392 8393 APSInt Index; 8394 bool Success = true; 8395 8396 // C++17's rules require us to evaluate the LHS first, regardless of which 8397 // side is the base. 8398 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8399 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8400 : !EvaluateInteger(SubExpr, Index, Info)) { 8401 if (!Info.noteFailure()) 8402 return false; 8403 Success = false; 8404 } 8405 } 8406 8407 return Success && 8408 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8409 } 8410 8411 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8412 return evaluatePointer(E->getSubExpr(), Result); 8413 } 8414 8415 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8416 if (!Visit(E->getSubExpr())) 8417 return false; 8418 // __real is a no-op on scalar lvalues. 8419 if (E->getSubExpr()->getType()->isAnyComplexType()) 8420 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8421 return true; 8422 } 8423 8424 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8425 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8426 "lvalue __imag__ on scalar?"); 8427 if (!Visit(E->getSubExpr())) 8428 return false; 8429 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8430 return true; 8431 } 8432 8433 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8434 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8435 return Error(UO); 8436 8437 if (!this->Visit(UO->getSubExpr())) 8438 return false; 8439 8440 return handleIncDec( 8441 this->Info, UO, Result, UO->getSubExpr()->getType(), 8442 UO->isIncrementOp(), nullptr); 8443 } 8444 8445 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8446 const CompoundAssignOperator *CAO) { 8447 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8448 return Error(CAO); 8449 8450 bool Success = true; 8451 8452 // C++17 onwards require that we evaluate the RHS first. 8453 APValue RHS; 8454 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8455 if (!Info.noteFailure()) 8456 return false; 8457 Success = false; 8458 } 8459 8460 // The overall lvalue result is the result of evaluating the LHS. 8461 if (!this->Visit(CAO->getLHS()) || !Success) 8462 return false; 8463 8464 return handleCompoundAssignment( 8465 this->Info, CAO, 8466 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8467 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8468 } 8469 8470 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8471 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8472 return Error(E); 8473 8474 bool Success = true; 8475 8476 // C++17 onwards require that we evaluate the RHS first. 8477 APValue NewVal; 8478 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8479 if (!Info.noteFailure()) 8480 return false; 8481 Success = false; 8482 } 8483 8484 if (!this->Visit(E->getLHS()) || !Success) 8485 return false; 8486 8487 if (Info.getLangOpts().CPlusPlus20 && 8488 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8489 return false; 8490 8491 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8492 NewVal); 8493 } 8494 8495 //===----------------------------------------------------------------------===// 8496 // Pointer Evaluation 8497 //===----------------------------------------------------------------------===// 8498 8499 /// Attempts to compute the number of bytes available at the pointer 8500 /// returned by a function with the alloc_size attribute. Returns true if we 8501 /// were successful. Places an unsigned number into `Result`. 8502 /// 8503 /// This expects the given CallExpr to be a call to a function with an 8504 /// alloc_size attribute. 8505 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8506 const CallExpr *Call, 8507 llvm::APInt &Result) { 8508 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8509 8510 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8511 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8512 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8513 if (Call->getNumArgs() <= SizeArgNo) 8514 return false; 8515 8516 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8517 Expr::EvalResult ExprResult; 8518 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8519 return false; 8520 Into = ExprResult.Val.getInt(); 8521 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8522 return false; 8523 Into = Into.zextOrSelf(BitsInSizeT); 8524 return true; 8525 }; 8526 8527 APSInt SizeOfElem; 8528 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8529 return false; 8530 8531 if (!AllocSize->getNumElemsParam().isValid()) { 8532 Result = std::move(SizeOfElem); 8533 return true; 8534 } 8535 8536 APSInt NumberOfElems; 8537 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8538 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8539 return false; 8540 8541 bool Overflow; 8542 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8543 if (Overflow) 8544 return false; 8545 8546 Result = std::move(BytesAvailable); 8547 return true; 8548 } 8549 8550 /// Convenience function. LVal's base must be a call to an alloc_size 8551 /// function. 8552 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8553 const LValue &LVal, 8554 llvm::APInt &Result) { 8555 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8556 "Can't get the size of a non alloc_size function"); 8557 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8558 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8559 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8560 } 8561 8562 /// Attempts to evaluate the given LValueBase as the result of a call to 8563 /// a function with the alloc_size attribute. If it was possible to do so, this 8564 /// function will return true, make Result's Base point to said function call, 8565 /// and mark Result's Base as invalid. 8566 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8567 LValue &Result) { 8568 if (Base.isNull()) 8569 return false; 8570 8571 // Because we do no form of static analysis, we only support const variables. 8572 // 8573 // Additionally, we can't support parameters, nor can we support static 8574 // variables (in the latter case, use-before-assign isn't UB; in the former, 8575 // we have no clue what they'll be assigned to). 8576 const auto *VD = 8577 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8578 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8579 return false; 8580 8581 const Expr *Init = VD->getAnyInitializer(); 8582 if (!Init) 8583 return false; 8584 8585 const Expr *E = Init->IgnoreParens(); 8586 if (!tryUnwrapAllocSizeCall(E)) 8587 return false; 8588 8589 // Store E instead of E unwrapped so that the type of the LValue's base is 8590 // what the user wanted. 8591 Result.setInvalid(E); 8592 8593 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8594 Result.addUnsizedArray(Info, E, Pointee); 8595 return true; 8596 } 8597 8598 namespace { 8599 class PointerExprEvaluator 8600 : public ExprEvaluatorBase<PointerExprEvaluator> { 8601 LValue &Result; 8602 bool InvalidBaseOK; 8603 8604 bool Success(const Expr *E) { 8605 Result.set(E); 8606 return true; 8607 } 8608 8609 bool evaluateLValue(const Expr *E, LValue &Result) { 8610 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8611 } 8612 8613 bool evaluatePointer(const Expr *E, LValue &Result) { 8614 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8615 } 8616 8617 bool visitNonBuiltinCallExpr(const CallExpr *E); 8618 public: 8619 8620 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8621 : ExprEvaluatorBaseTy(info), Result(Result), 8622 InvalidBaseOK(InvalidBaseOK) {} 8623 8624 bool Success(const APValue &V, const Expr *E) { 8625 Result.setFrom(Info.Ctx, V); 8626 return true; 8627 } 8628 bool ZeroInitialization(const Expr *E) { 8629 Result.setNull(Info.Ctx, E->getType()); 8630 return true; 8631 } 8632 8633 bool VisitBinaryOperator(const BinaryOperator *E); 8634 bool VisitCastExpr(const CastExpr* E); 8635 bool VisitUnaryAddrOf(const UnaryOperator *E); 8636 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8637 { return Success(E); } 8638 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8639 if (E->isExpressibleAsConstantInitializer()) 8640 return Success(E); 8641 if (Info.noteFailure()) 8642 EvaluateIgnoredValue(Info, E->getSubExpr()); 8643 return Error(E); 8644 } 8645 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8646 { return Success(E); } 8647 bool VisitCallExpr(const CallExpr *E); 8648 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8649 bool VisitBlockExpr(const BlockExpr *E) { 8650 if (!E->getBlockDecl()->hasCaptures()) 8651 return Success(E); 8652 return Error(E); 8653 } 8654 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8655 // Can't look at 'this' when checking a potential constant expression. 8656 if (Info.checkingPotentialConstantExpression()) 8657 return false; 8658 if (!Info.CurrentCall->This) { 8659 if (Info.getLangOpts().CPlusPlus11) 8660 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8661 else 8662 Info.FFDiag(E); 8663 return false; 8664 } 8665 Result = *Info.CurrentCall->This; 8666 // If we are inside a lambda's call operator, the 'this' expression refers 8667 // to the enclosing '*this' object (either by value or reference) which is 8668 // either copied into the closure object's field that represents the '*this' 8669 // or refers to '*this'. 8670 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8671 // Ensure we actually have captured 'this'. (an error will have 8672 // been previously reported if not). 8673 if (!Info.CurrentCall->LambdaThisCaptureField) 8674 return false; 8675 8676 // Update 'Result' to refer to the data member/field of the closure object 8677 // that represents the '*this' capture. 8678 if (!HandleLValueMember(Info, E, Result, 8679 Info.CurrentCall->LambdaThisCaptureField)) 8680 return false; 8681 // If we captured '*this' by reference, replace the field with its referent. 8682 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8683 ->isPointerType()) { 8684 APValue RVal; 8685 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8686 RVal)) 8687 return false; 8688 8689 Result.setFrom(Info.Ctx, RVal); 8690 } 8691 } 8692 return true; 8693 } 8694 8695 bool VisitCXXNewExpr(const CXXNewExpr *E); 8696 8697 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8698 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8699 APValue LValResult = E->EvaluateInContext( 8700 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8701 Result.setFrom(Info.Ctx, LValResult); 8702 return true; 8703 } 8704 8705 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8706 std::string ResultStr = E->ComputeName(Info.Ctx); 8707 8708 QualType CharTy = Info.Ctx.CharTy.withConst(); 8709 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8710 ResultStr.size() + 1); 8711 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8712 ArrayType::Normal, 0); 8713 8714 StringLiteral *SL = 8715 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, 8716 /*Pascal*/ false, ArrayTy, E->getLocation()); 8717 8718 evaluateLValue(SL, Result); 8719 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8720 return true; 8721 } 8722 8723 // FIXME: Missing: @protocol, @selector 8724 }; 8725 } // end anonymous namespace 8726 8727 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8728 bool InvalidBaseOK) { 8729 assert(!E->isValueDependent()); 8730 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8731 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8732 } 8733 8734 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8735 if (E->getOpcode() != BO_Add && 8736 E->getOpcode() != BO_Sub) 8737 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8738 8739 const Expr *PExp = E->getLHS(); 8740 const Expr *IExp = E->getRHS(); 8741 if (IExp->getType()->isPointerType()) 8742 std::swap(PExp, IExp); 8743 8744 bool EvalPtrOK = evaluatePointer(PExp, Result); 8745 if (!EvalPtrOK && !Info.noteFailure()) 8746 return false; 8747 8748 llvm::APSInt Offset; 8749 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8750 return false; 8751 8752 if (E->getOpcode() == BO_Sub) 8753 negateAsSigned(Offset); 8754 8755 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8756 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8757 } 8758 8759 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8760 return evaluateLValue(E->getSubExpr(), Result); 8761 } 8762 8763 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8764 const Expr *SubExpr = E->getSubExpr(); 8765 8766 switch (E->getCastKind()) { 8767 default: 8768 break; 8769 case CK_BitCast: 8770 case CK_CPointerToObjCPointerCast: 8771 case CK_BlockPointerToObjCPointerCast: 8772 case CK_AnyPointerToBlockPointerCast: 8773 case CK_AddressSpaceConversion: 8774 if (!Visit(SubExpr)) 8775 return false; 8776 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8777 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8778 // also static_casts, but we disallow them as a resolution to DR1312. 8779 if (!E->getType()->isVoidPointerType()) { 8780 if (!Result.InvalidBase && !Result.Designator.Invalid && 8781 !Result.IsNullPtr && 8782 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8783 E->getType()->getPointeeType()) && 8784 Info.getStdAllocatorCaller("allocate")) { 8785 // Inside a call to std::allocator::allocate and friends, we permit 8786 // casting from void* back to cv1 T* for a pointer that points to a 8787 // cv2 T. 8788 } else { 8789 Result.Designator.setInvalid(); 8790 if (SubExpr->getType()->isVoidPointerType()) 8791 CCEDiag(E, diag::note_constexpr_invalid_cast) 8792 << 3 << SubExpr->getType(); 8793 else 8794 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8795 } 8796 } 8797 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8798 ZeroInitialization(E); 8799 return true; 8800 8801 case CK_DerivedToBase: 8802 case CK_UncheckedDerivedToBase: 8803 if (!evaluatePointer(E->getSubExpr(), Result)) 8804 return false; 8805 if (!Result.Base && Result.Offset.isZero()) 8806 return true; 8807 8808 // Now figure out the necessary offset to add to the base LV to get from 8809 // the derived class to the base class. 8810 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8811 castAs<PointerType>()->getPointeeType(), 8812 Result); 8813 8814 case CK_BaseToDerived: 8815 if (!Visit(E->getSubExpr())) 8816 return false; 8817 if (!Result.Base && Result.Offset.isZero()) 8818 return true; 8819 return HandleBaseToDerivedCast(Info, E, Result); 8820 8821 case CK_Dynamic: 8822 if (!Visit(E->getSubExpr())) 8823 return false; 8824 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8825 8826 case CK_NullToPointer: 8827 VisitIgnoredValue(E->getSubExpr()); 8828 return ZeroInitialization(E); 8829 8830 case CK_IntegralToPointer: { 8831 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8832 8833 APValue Value; 8834 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8835 break; 8836 8837 if (Value.isInt()) { 8838 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8839 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8840 Result.Base = (Expr*)nullptr; 8841 Result.InvalidBase = false; 8842 Result.Offset = CharUnits::fromQuantity(N); 8843 Result.Designator.setInvalid(); 8844 Result.IsNullPtr = false; 8845 return true; 8846 } else { 8847 // Cast is of an lvalue, no need to change value. 8848 Result.setFrom(Info.Ctx, Value); 8849 return true; 8850 } 8851 } 8852 8853 case CK_ArrayToPointerDecay: { 8854 if (SubExpr->isGLValue()) { 8855 if (!evaluateLValue(SubExpr, Result)) 8856 return false; 8857 } else { 8858 APValue &Value = Info.CurrentCall->createTemporary( 8859 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8860 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8861 return false; 8862 } 8863 // The result is a pointer to the first element of the array. 8864 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8865 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8866 Result.addArray(Info, E, CAT); 8867 else 8868 Result.addUnsizedArray(Info, E, AT->getElementType()); 8869 return true; 8870 } 8871 8872 case CK_FunctionToPointerDecay: 8873 return evaluateLValue(SubExpr, Result); 8874 8875 case CK_LValueToRValue: { 8876 LValue LVal; 8877 if (!evaluateLValue(E->getSubExpr(), LVal)) 8878 return false; 8879 8880 APValue RVal; 8881 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8882 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8883 LVal, RVal)) 8884 return InvalidBaseOK && 8885 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8886 return Success(RVal, E); 8887 } 8888 } 8889 8890 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8891 } 8892 8893 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8894 UnaryExprOrTypeTrait ExprKind) { 8895 // C++ [expr.alignof]p3: 8896 // When alignof is applied to a reference type, the result is the 8897 // alignment of the referenced type. 8898 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8899 T = Ref->getPointeeType(); 8900 8901 if (T.getQualifiers().hasUnaligned()) 8902 return CharUnits::One(); 8903 8904 const bool AlignOfReturnsPreferred = 8905 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8906 8907 // __alignof is defined to return the preferred alignment. 8908 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8909 // as well. 8910 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8911 return Info.Ctx.toCharUnitsFromBits( 8912 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8913 // alignof and _Alignof are defined to return the ABI alignment. 8914 else if (ExprKind == UETT_AlignOf) 8915 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8916 else 8917 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8918 } 8919 8920 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8921 UnaryExprOrTypeTrait ExprKind) { 8922 E = E->IgnoreParens(); 8923 8924 // The kinds of expressions that we have special-case logic here for 8925 // should be kept up to date with the special checks for those 8926 // expressions in Sema. 8927 8928 // alignof decl is always accepted, even if it doesn't make sense: we default 8929 // to 1 in those cases. 8930 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8931 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8932 /*RefAsPointee*/true); 8933 8934 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8935 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8936 /*RefAsPointee*/true); 8937 8938 return GetAlignOfType(Info, E->getType(), ExprKind); 8939 } 8940 8941 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8942 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8943 return Info.Ctx.getDeclAlign(VD); 8944 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8945 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8946 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8947 } 8948 8949 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8950 /// __builtin_is_aligned and __builtin_assume_aligned. 8951 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8952 EvalInfo &Info, APSInt &Alignment) { 8953 if (!EvaluateInteger(E, Alignment, Info)) 8954 return false; 8955 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8956 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8957 return false; 8958 } 8959 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8960 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8961 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8962 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8963 << MaxValue << ForType << Alignment; 8964 return false; 8965 } 8966 // Ensure both alignment and source value have the same bit width so that we 8967 // don't assert when computing the resulting value. 8968 APSInt ExtAlignment = 8969 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8970 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8971 "Alignment should not be changed by ext/trunc"); 8972 Alignment = ExtAlignment; 8973 assert(Alignment.getBitWidth() == SrcWidth); 8974 return true; 8975 } 8976 8977 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8978 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8979 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8980 return true; 8981 8982 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8983 return false; 8984 8985 Result.setInvalid(E); 8986 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8987 Result.addUnsizedArray(Info, E, PointeeTy); 8988 return true; 8989 } 8990 8991 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8992 if (IsConstantCall(E)) 8993 return Success(E); 8994 8995 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8996 return VisitBuiltinCallExpr(E, BuiltinOp); 8997 8998 return visitNonBuiltinCallExpr(E); 8999 } 9000 9001 // Determine if T is a character type for which we guarantee that 9002 // sizeof(T) == 1. 9003 static bool isOneByteCharacterType(QualType T) { 9004 return T->isCharType() || T->isChar8Type(); 9005 } 9006 9007 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9008 unsigned BuiltinOp) { 9009 switch (BuiltinOp) { 9010 case Builtin::BI__builtin_addressof: 9011 return evaluateLValue(E->getArg(0), Result); 9012 case Builtin::BI__builtin_assume_aligned: { 9013 // We need to be very careful here because: if the pointer does not have the 9014 // asserted alignment, then the behavior is undefined, and undefined 9015 // behavior is non-constant. 9016 if (!evaluatePointer(E->getArg(0), Result)) 9017 return false; 9018 9019 LValue OffsetResult(Result); 9020 APSInt Alignment; 9021 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9022 Alignment)) 9023 return false; 9024 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 9025 9026 if (E->getNumArgs() > 2) { 9027 APSInt Offset; 9028 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9029 return false; 9030 9031 int64_t AdditionalOffset = -Offset.getZExtValue(); 9032 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9033 } 9034 9035 // If there is a base object, then it must have the correct alignment. 9036 if (OffsetResult.Base) { 9037 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9038 9039 if (BaseAlignment < Align) { 9040 Result.Designator.setInvalid(); 9041 // FIXME: Add support to Diagnostic for long / long long. 9042 CCEDiag(E->getArg(0), 9043 diag::note_constexpr_baa_insufficient_alignment) << 0 9044 << (unsigned)BaseAlignment.getQuantity() 9045 << (unsigned)Align.getQuantity(); 9046 return false; 9047 } 9048 } 9049 9050 // The offset must also have the correct alignment. 9051 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9052 Result.Designator.setInvalid(); 9053 9054 (OffsetResult.Base 9055 ? CCEDiag(E->getArg(0), 9056 diag::note_constexpr_baa_insufficient_alignment) << 1 9057 : CCEDiag(E->getArg(0), 9058 diag::note_constexpr_baa_value_insufficient_alignment)) 9059 << (int)OffsetResult.Offset.getQuantity() 9060 << (unsigned)Align.getQuantity(); 9061 return false; 9062 } 9063 9064 return true; 9065 } 9066 case Builtin::BI__builtin_align_up: 9067 case Builtin::BI__builtin_align_down: { 9068 if (!evaluatePointer(E->getArg(0), Result)) 9069 return false; 9070 APSInt Alignment; 9071 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9072 Alignment)) 9073 return false; 9074 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9075 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9076 // For align_up/align_down, we can return the same value if the alignment 9077 // is known to be greater or equal to the requested value. 9078 if (PtrAlign.getQuantity() >= Alignment) 9079 return true; 9080 9081 // The alignment could be greater than the minimum at run-time, so we cannot 9082 // infer much about the resulting pointer value. One case is possible: 9083 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9084 // can infer the correct index if the requested alignment is smaller than 9085 // the base alignment so we can perform the computation on the offset. 9086 if (BaseAlignment.getQuantity() >= Alignment) { 9087 assert(Alignment.getBitWidth() <= 64 && 9088 "Cannot handle > 64-bit address-space"); 9089 uint64_t Alignment64 = Alignment.getZExtValue(); 9090 CharUnits NewOffset = CharUnits::fromQuantity( 9091 BuiltinOp == Builtin::BI__builtin_align_down 9092 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9093 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9094 Result.adjustOffset(NewOffset - Result.Offset); 9095 // TODO: diagnose out-of-bounds values/only allow for arrays? 9096 return true; 9097 } 9098 // Otherwise, we cannot constant-evaluate the result. 9099 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9100 << Alignment; 9101 return false; 9102 } 9103 case Builtin::BI__builtin_operator_new: 9104 return HandleOperatorNewCall(Info, E, Result); 9105 case Builtin::BI__builtin_launder: 9106 return evaluatePointer(E->getArg(0), Result); 9107 case Builtin::BIstrchr: 9108 case Builtin::BIwcschr: 9109 case Builtin::BImemchr: 9110 case Builtin::BIwmemchr: 9111 if (Info.getLangOpts().CPlusPlus11) 9112 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9113 << /*isConstexpr*/0 << /*isConstructor*/0 9114 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9115 else 9116 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9117 LLVM_FALLTHROUGH; 9118 case Builtin::BI__builtin_strchr: 9119 case Builtin::BI__builtin_wcschr: 9120 case Builtin::BI__builtin_memchr: 9121 case Builtin::BI__builtin_char_memchr: 9122 case Builtin::BI__builtin_wmemchr: { 9123 if (!Visit(E->getArg(0))) 9124 return false; 9125 APSInt Desired; 9126 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9127 return false; 9128 uint64_t MaxLength = uint64_t(-1); 9129 if (BuiltinOp != Builtin::BIstrchr && 9130 BuiltinOp != Builtin::BIwcschr && 9131 BuiltinOp != Builtin::BI__builtin_strchr && 9132 BuiltinOp != Builtin::BI__builtin_wcschr) { 9133 APSInt N; 9134 if (!EvaluateInteger(E->getArg(2), N, Info)) 9135 return false; 9136 MaxLength = N.getExtValue(); 9137 } 9138 // We cannot find the value if there are no candidates to match against. 9139 if (MaxLength == 0u) 9140 return ZeroInitialization(E); 9141 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9142 Result.Designator.Invalid) 9143 return false; 9144 QualType CharTy = Result.Designator.getType(Info.Ctx); 9145 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9146 BuiltinOp == Builtin::BI__builtin_memchr; 9147 assert(IsRawByte || 9148 Info.Ctx.hasSameUnqualifiedType( 9149 CharTy, E->getArg(0)->getType()->getPointeeType())); 9150 // Pointers to const void may point to objects of incomplete type. 9151 if (IsRawByte && CharTy->isIncompleteType()) { 9152 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9153 return false; 9154 } 9155 // Give up on byte-oriented matching against multibyte elements. 9156 // FIXME: We can compare the bytes in the correct order. 9157 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9158 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9159 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9160 << CharTy; 9161 return false; 9162 } 9163 // Figure out what value we're actually looking for (after converting to 9164 // the corresponding unsigned type if necessary). 9165 uint64_t DesiredVal; 9166 bool StopAtNull = false; 9167 switch (BuiltinOp) { 9168 case Builtin::BIstrchr: 9169 case Builtin::BI__builtin_strchr: 9170 // strchr compares directly to the passed integer, and therefore 9171 // always fails if given an int that is not a char. 9172 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9173 E->getArg(1)->getType(), 9174 Desired), 9175 Desired)) 9176 return ZeroInitialization(E); 9177 StopAtNull = true; 9178 LLVM_FALLTHROUGH; 9179 case Builtin::BImemchr: 9180 case Builtin::BI__builtin_memchr: 9181 case Builtin::BI__builtin_char_memchr: 9182 // memchr compares by converting both sides to unsigned char. That's also 9183 // correct for strchr if we get this far (to cope with plain char being 9184 // unsigned in the strchr case). 9185 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9186 break; 9187 9188 case Builtin::BIwcschr: 9189 case Builtin::BI__builtin_wcschr: 9190 StopAtNull = true; 9191 LLVM_FALLTHROUGH; 9192 case Builtin::BIwmemchr: 9193 case Builtin::BI__builtin_wmemchr: 9194 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9195 DesiredVal = Desired.getZExtValue(); 9196 break; 9197 } 9198 9199 for (; MaxLength; --MaxLength) { 9200 APValue Char; 9201 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9202 !Char.isInt()) 9203 return false; 9204 if (Char.getInt().getZExtValue() == DesiredVal) 9205 return true; 9206 if (StopAtNull && !Char.getInt()) 9207 break; 9208 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9209 return false; 9210 } 9211 // Not found: return nullptr. 9212 return ZeroInitialization(E); 9213 } 9214 9215 case Builtin::BImemcpy: 9216 case Builtin::BImemmove: 9217 case Builtin::BIwmemcpy: 9218 case Builtin::BIwmemmove: 9219 if (Info.getLangOpts().CPlusPlus11) 9220 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9221 << /*isConstexpr*/0 << /*isConstructor*/0 9222 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9223 else 9224 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9225 LLVM_FALLTHROUGH; 9226 case Builtin::BI__builtin_memcpy: 9227 case Builtin::BI__builtin_memmove: 9228 case Builtin::BI__builtin_wmemcpy: 9229 case Builtin::BI__builtin_wmemmove: { 9230 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9231 BuiltinOp == Builtin::BIwmemmove || 9232 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9233 BuiltinOp == Builtin::BI__builtin_wmemmove; 9234 bool Move = BuiltinOp == Builtin::BImemmove || 9235 BuiltinOp == Builtin::BIwmemmove || 9236 BuiltinOp == Builtin::BI__builtin_memmove || 9237 BuiltinOp == Builtin::BI__builtin_wmemmove; 9238 9239 // The result of mem* is the first argument. 9240 if (!Visit(E->getArg(0))) 9241 return false; 9242 LValue Dest = Result; 9243 9244 LValue Src; 9245 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9246 return false; 9247 9248 APSInt N; 9249 if (!EvaluateInteger(E->getArg(2), N, Info)) 9250 return false; 9251 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9252 9253 // If the size is zero, we treat this as always being a valid no-op. 9254 // (Even if one of the src and dest pointers is null.) 9255 if (!N) 9256 return true; 9257 9258 // Otherwise, if either of the operands is null, we can't proceed. Don't 9259 // try to determine the type of the copied objects, because there aren't 9260 // any. 9261 if (!Src.Base || !Dest.Base) { 9262 APValue Val; 9263 (!Src.Base ? Src : Dest).moveInto(Val); 9264 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9265 << Move << WChar << !!Src.Base 9266 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9267 return false; 9268 } 9269 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9270 return false; 9271 9272 // We require that Src and Dest are both pointers to arrays of 9273 // trivially-copyable type. (For the wide version, the designator will be 9274 // invalid if the designated object is not a wchar_t.) 9275 QualType T = Dest.Designator.getType(Info.Ctx); 9276 QualType SrcT = Src.Designator.getType(Info.Ctx); 9277 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9278 // FIXME: Consider using our bit_cast implementation to support this. 9279 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9280 return false; 9281 } 9282 if (T->isIncompleteType()) { 9283 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9284 return false; 9285 } 9286 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9287 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9288 return false; 9289 } 9290 9291 // Figure out how many T's we're copying. 9292 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9293 if (!WChar) { 9294 uint64_t Remainder; 9295 llvm::APInt OrigN = N; 9296 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9297 if (Remainder) { 9298 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9299 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9300 << (unsigned)TSize; 9301 return false; 9302 } 9303 } 9304 9305 // Check that the copying will remain within the arrays, just so that we 9306 // can give a more meaningful diagnostic. This implicitly also checks that 9307 // N fits into 64 bits. 9308 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9309 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9310 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9311 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9312 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9313 << toString(N, 10, /*Signed*/false); 9314 return false; 9315 } 9316 uint64_t NElems = N.getZExtValue(); 9317 uint64_t NBytes = NElems * TSize; 9318 9319 // Check for overlap. 9320 int Direction = 1; 9321 if (HasSameBase(Src, Dest)) { 9322 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9323 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9324 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9325 // Dest is inside the source region. 9326 if (!Move) { 9327 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9328 return false; 9329 } 9330 // For memmove and friends, copy backwards. 9331 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9332 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9333 return false; 9334 Direction = -1; 9335 } else if (!Move && SrcOffset >= DestOffset && 9336 SrcOffset - DestOffset < NBytes) { 9337 // Src is inside the destination region for memcpy: invalid. 9338 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9339 return false; 9340 } 9341 } 9342 9343 while (true) { 9344 APValue Val; 9345 // FIXME: Set WantObjectRepresentation to true if we're copying a 9346 // char-like type? 9347 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9348 !handleAssignment(Info, E, Dest, T, Val)) 9349 return false; 9350 // Do not iterate past the last element; if we're copying backwards, that 9351 // might take us off the start of the array. 9352 if (--NElems == 0) 9353 return true; 9354 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9355 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9356 return false; 9357 } 9358 } 9359 9360 default: 9361 break; 9362 } 9363 9364 return visitNonBuiltinCallExpr(E); 9365 } 9366 9367 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9368 APValue &Result, const InitListExpr *ILE, 9369 QualType AllocType); 9370 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9371 APValue &Result, 9372 const CXXConstructExpr *CCE, 9373 QualType AllocType); 9374 9375 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9376 if (!Info.getLangOpts().CPlusPlus20) 9377 Info.CCEDiag(E, diag::note_constexpr_new); 9378 9379 // We cannot speculatively evaluate a delete expression. 9380 if (Info.SpeculativeEvaluationDepth) 9381 return false; 9382 9383 FunctionDecl *OperatorNew = E->getOperatorNew(); 9384 9385 bool IsNothrow = false; 9386 bool IsPlacement = false; 9387 if (OperatorNew->isReservedGlobalPlacementOperator() && 9388 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9389 // FIXME Support array placement new. 9390 assert(E->getNumPlacementArgs() == 1); 9391 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9392 return false; 9393 if (Result.Designator.Invalid) 9394 return false; 9395 IsPlacement = true; 9396 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9397 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9398 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9399 return false; 9400 } else if (E->getNumPlacementArgs()) { 9401 // The only new-placement list we support is of the form (std::nothrow). 9402 // 9403 // FIXME: There is no restriction on this, but it's not clear that any 9404 // other form makes any sense. We get here for cases such as: 9405 // 9406 // new (std::align_val_t{N}) X(int) 9407 // 9408 // (which should presumably be valid only if N is a multiple of 9409 // alignof(int), and in any case can't be deallocated unless N is 9410 // alignof(X) and X has new-extended alignment). 9411 if (E->getNumPlacementArgs() != 1 || 9412 !E->getPlacementArg(0)->getType()->isNothrowT()) 9413 return Error(E, diag::note_constexpr_new_placement); 9414 9415 LValue Nothrow; 9416 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9417 return false; 9418 IsNothrow = true; 9419 } 9420 9421 const Expr *Init = E->getInitializer(); 9422 const InitListExpr *ResizedArrayILE = nullptr; 9423 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9424 bool ValueInit = false; 9425 9426 QualType AllocType = E->getAllocatedType(); 9427 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9428 const Expr *Stripped = *ArraySize; 9429 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9430 Stripped = ICE->getSubExpr()) 9431 if (ICE->getCastKind() != CK_NoOp && 9432 ICE->getCastKind() != CK_IntegralCast) 9433 break; 9434 9435 llvm::APSInt ArrayBound; 9436 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9437 return false; 9438 9439 // C++ [expr.new]p9: 9440 // The expression is erroneous if: 9441 // -- [...] its value before converting to size_t [or] applying the 9442 // second standard conversion sequence is less than zero 9443 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9444 if (IsNothrow) 9445 return ZeroInitialization(E); 9446 9447 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9448 << ArrayBound << (*ArraySize)->getSourceRange(); 9449 return false; 9450 } 9451 9452 // -- its value is such that the size of the allocated object would 9453 // exceed the implementation-defined limit 9454 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9455 ArrayBound) > 9456 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9457 if (IsNothrow) 9458 return ZeroInitialization(E); 9459 9460 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9461 << ArrayBound << (*ArraySize)->getSourceRange(); 9462 return false; 9463 } 9464 9465 // -- the new-initializer is a braced-init-list and the number of 9466 // array elements for which initializers are provided [...] 9467 // exceeds the number of elements to initialize 9468 if (!Init) { 9469 // No initialization is performed. 9470 } else if (isa<CXXScalarValueInitExpr>(Init) || 9471 isa<ImplicitValueInitExpr>(Init)) { 9472 ValueInit = true; 9473 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9474 ResizedArrayCCE = CCE; 9475 } else { 9476 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9477 assert(CAT && "unexpected type for array initializer"); 9478 9479 unsigned Bits = 9480 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9481 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9482 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9483 if (InitBound.ugt(AllocBound)) { 9484 if (IsNothrow) 9485 return ZeroInitialization(E); 9486 9487 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9488 << toString(AllocBound, 10, /*Signed=*/false) 9489 << toString(InitBound, 10, /*Signed=*/false) 9490 << (*ArraySize)->getSourceRange(); 9491 return false; 9492 } 9493 9494 // If the sizes differ, we must have an initializer list, and we need 9495 // special handling for this case when we initialize. 9496 if (InitBound != AllocBound) 9497 ResizedArrayILE = cast<InitListExpr>(Init); 9498 } 9499 9500 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9501 ArrayType::Normal, 0); 9502 } else { 9503 assert(!AllocType->isArrayType() && 9504 "array allocation with non-array new"); 9505 } 9506 9507 APValue *Val; 9508 if (IsPlacement) { 9509 AccessKinds AK = AK_Construct; 9510 struct FindObjectHandler { 9511 EvalInfo &Info; 9512 const Expr *E; 9513 QualType AllocType; 9514 const AccessKinds AccessKind; 9515 APValue *Value; 9516 9517 typedef bool result_type; 9518 bool failed() { return false; } 9519 bool found(APValue &Subobj, QualType SubobjType) { 9520 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9521 // old name of the object to be used to name the new object. 9522 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9523 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9524 SubobjType << AllocType; 9525 return false; 9526 } 9527 Value = &Subobj; 9528 return true; 9529 } 9530 bool found(APSInt &Value, QualType SubobjType) { 9531 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9532 return false; 9533 } 9534 bool found(APFloat &Value, QualType SubobjType) { 9535 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9536 return false; 9537 } 9538 } Handler = {Info, E, AllocType, AK, nullptr}; 9539 9540 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9541 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9542 return false; 9543 9544 Val = Handler.Value; 9545 9546 // [basic.life]p1: 9547 // The lifetime of an object o of type T ends when [...] the storage 9548 // which the object occupies is [...] reused by an object that is not 9549 // nested within o (6.6.2). 9550 *Val = APValue(); 9551 } else { 9552 // Perform the allocation and obtain a pointer to the resulting object. 9553 Val = Info.createHeapAlloc(E, AllocType, Result); 9554 if (!Val) 9555 return false; 9556 } 9557 9558 if (ValueInit) { 9559 ImplicitValueInitExpr VIE(AllocType); 9560 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9561 return false; 9562 } else if (ResizedArrayILE) { 9563 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9564 AllocType)) 9565 return false; 9566 } else if (ResizedArrayCCE) { 9567 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9568 AllocType)) 9569 return false; 9570 } else if (Init) { 9571 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9572 return false; 9573 } else if (!getDefaultInitValue(AllocType, *Val)) { 9574 return false; 9575 } 9576 9577 // Array new returns a pointer to the first element, not a pointer to the 9578 // array. 9579 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9580 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9581 9582 return true; 9583 } 9584 //===----------------------------------------------------------------------===// 9585 // Member Pointer Evaluation 9586 //===----------------------------------------------------------------------===// 9587 9588 namespace { 9589 class MemberPointerExprEvaluator 9590 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9591 MemberPtr &Result; 9592 9593 bool Success(const ValueDecl *D) { 9594 Result = MemberPtr(D); 9595 return true; 9596 } 9597 public: 9598 9599 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9600 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9601 9602 bool Success(const APValue &V, const Expr *E) { 9603 Result.setFrom(V); 9604 return true; 9605 } 9606 bool ZeroInitialization(const Expr *E) { 9607 return Success((const ValueDecl*)nullptr); 9608 } 9609 9610 bool VisitCastExpr(const CastExpr *E); 9611 bool VisitUnaryAddrOf(const UnaryOperator *E); 9612 }; 9613 } // end anonymous namespace 9614 9615 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9616 EvalInfo &Info) { 9617 assert(!E->isValueDependent()); 9618 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9619 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9620 } 9621 9622 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9623 switch (E->getCastKind()) { 9624 default: 9625 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9626 9627 case CK_NullToMemberPointer: 9628 VisitIgnoredValue(E->getSubExpr()); 9629 return ZeroInitialization(E); 9630 9631 case CK_BaseToDerivedMemberPointer: { 9632 if (!Visit(E->getSubExpr())) 9633 return false; 9634 if (E->path_empty()) 9635 return true; 9636 // Base-to-derived member pointer casts store the path in derived-to-base 9637 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9638 // the wrong end of the derived->base arc, so stagger the path by one class. 9639 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9640 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9641 PathI != PathE; ++PathI) { 9642 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9643 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9644 if (!Result.castToDerived(Derived)) 9645 return Error(E); 9646 } 9647 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9648 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9649 return Error(E); 9650 return true; 9651 } 9652 9653 case CK_DerivedToBaseMemberPointer: 9654 if (!Visit(E->getSubExpr())) 9655 return false; 9656 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9657 PathE = E->path_end(); PathI != PathE; ++PathI) { 9658 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9659 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9660 if (!Result.castToBase(Base)) 9661 return Error(E); 9662 } 9663 return true; 9664 } 9665 } 9666 9667 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9668 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9669 // member can be formed. 9670 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9671 } 9672 9673 //===----------------------------------------------------------------------===// 9674 // Record Evaluation 9675 //===----------------------------------------------------------------------===// 9676 9677 namespace { 9678 class RecordExprEvaluator 9679 : public ExprEvaluatorBase<RecordExprEvaluator> { 9680 const LValue &This; 9681 APValue &Result; 9682 public: 9683 9684 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9685 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9686 9687 bool Success(const APValue &V, const Expr *E) { 9688 Result = V; 9689 return true; 9690 } 9691 bool ZeroInitialization(const Expr *E) { 9692 return ZeroInitialization(E, E->getType()); 9693 } 9694 bool ZeroInitialization(const Expr *E, QualType T); 9695 9696 bool VisitCallExpr(const CallExpr *E) { 9697 return handleCallExpr(E, Result, &This); 9698 } 9699 bool VisitCastExpr(const CastExpr *E); 9700 bool VisitInitListExpr(const InitListExpr *E); 9701 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9702 return VisitCXXConstructExpr(E, E->getType()); 9703 } 9704 bool VisitLambdaExpr(const LambdaExpr *E); 9705 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9706 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9707 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9708 bool VisitBinCmp(const BinaryOperator *E); 9709 }; 9710 } 9711 9712 /// Perform zero-initialization on an object of non-union class type. 9713 /// C++11 [dcl.init]p5: 9714 /// To zero-initialize an object or reference of type T means: 9715 /// [...] 9716 /// -- if T is a (possibly cv-qualified) non-union class type, 9717 /// each non-static data member and each base-class subobject is 9718 /// zero-initialized 9719 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9720 const RecordDecl *RD, 9721 const LValue &This, APValue &Result) { 9722 assert(!RD->isUnion() && "Expected non-union class type"); 9723 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9724 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9725 std::distance(RD->field_begin(), RD->field_end())); 9726 9727 if (RD->isInvalidDecl()) return false; 9728 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9729 9730 if (CD) { 9731 unsigned Index = 0; 9732 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9733 End = CD->bases_end(); I != End; ++I, ++Index) { 9734 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9735 LValue Subobject = This; 9736 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9737 return false; 9738 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9739 Result.getStructBase(Index))) 9740 return false; 9741 } 9742 } 9743 9744 for (const auto *I : RD->fields()) { 9745 // -- if T is a reference type, no initialization is performed. 9746 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9747 continue; 9748 9749 LValue Subobject = This; 9750 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9751 return false; 9752 9753 ImplicitValueInitExpr VIE(I->getType()); 9754 if (!EvaluateInPlace( 9755 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9756 return false; 9757 } 9758 9759 return true; 9760 } 9761 9762 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9763 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9764 if (RD->isInvalidDecl()) return false; 9765 if (RD->isUnion()) { 9766 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9767 // object's first non-static named data member is zero-initialized 9768 RecordDecl::field_iterator I = RD->field_begin(); 9769 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9770 ++I; 9771 if (I == RD->field_end()) { 9772 Result = APValue((const FieldDecl*)nullptr); 9773 return true; 9774 } 9775 9776 LValue Subobject = This; 9777 if (!HandleLValueMember(Info, E, Subobject, *I)) 9778 return false; 9779 Result = APValue(*I); 9780 ImplicitValueInitExpr VIE(I->getType()); 9781 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9782 } 9783 9784 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9785 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9786 return false; 9787 } 9788 9789 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9790 } 9791 9792 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9793 switch (E->getCastKind()) { 9794 default: 9795 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9796 9797 case CK_ConstructorConversion: 9798 return Visit(E->getSubExpr()); 9799 9800 case CK_DerivedToBase: 9801 case CK_UncheckedDerivedToBase: { 9802 APValue DerivedObject; 9803 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9804 return false; 9805 if (!DerivedObject.isStruct()) 9806 return Error(E->getSubExpr()); 9807 9808 // Derived-to-base rvalue conversion: just slice off the derived part. 9809 APValue *Value = &DerivedObject; 9810 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9811 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9812 PathE = E->path_end(); PathI != PathE; ++PathI) { 9813 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9814 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9815 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9816 RD = Base; 9817 } 9818 Result = *Value; 9819 return true; 9820 } 9821 } 9822 } 9823 9824 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9825 if (E->isTransparent()) 9826 return Visit(E->getInit(0)); 9827 9828 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9829 if (RD->isInvalidDecl()) return false; 9830 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9831 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9832 9833 EvalInfo::EvaluatingConstructorRAII EvalObj( 9834 Info, 9835 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9836 CXXRD && CXXRD->getNumBases()); 9837 9838 if (RD->isUnion()) { 9839 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9840 Result = APValue(Field); 9841 if (!Field) 9842 return true; 9843 9844 // If the initializer list for a union does not contain any elements, the 9845 // first element of the union is value-initialized. 9846 // FIXME: The element should be initialized from an initializer list. 9847 // Is this difference ever observable for initializer lists which 9848 // we don't build? 9849 ImplicitValueInitExpr VIE(Field->getType()); 9850 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9851 9852 LValue Subobject = This; 9853 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9854 return false; 9855 9856 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9857 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9858 isa<CXXDefaultInitExpr>(InitExpr)); 9859 9860 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9861 if (Field->isBitField()) 9862 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9863 Field); 9864 return true; 9865 } 9866 9867 return false; 9868 } 9869 9870 if (!Result.hasValue()) 9871 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9872 std::distance(RD->field_begin(), RD->field_end())); 9873 unsigned ElementNo = 0; 9874 bool Success = true; 9875 9876 // Initialize base classes. 9877 if (CXXRD && CXXRD->getNumBases()) { 9878 for (const auto &Base : CXXRD->bases()) { 9879 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9880 const Expr *Init = E->getInit(ElementNo); 9881 9882 LValue Subobject = This; 9883 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9884 return false; 9885 9886 APValue &FieldVal = Result.getStructBase(ElementNo); 9887 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9888 if (!Info.noteFailure()) 9889 return false; 9890 Success = false; 9891 } 9892 ++ElementNo; 9893 } 9894 9895 EvalObj.finishedConstructingBases(); 9896 } 9897 9898 // Initialize members. 9899 for (const auto *Field : RD->fields()) { 9900 // Anonymous bit-fields are not considered members of the class for 9901 // purposes of aggregate initialization. 9902 if (Field->isUnnamedBitfield()) 9903 continue; 9904 9905 LValue Subobject = This; 9906 9907 bool HaveInit = ElementNo < E->getNumInits(); 9908 9909 // FIXME: Diagnostics here should point to the end of the initializer 9910 // list, not the start. 9911 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9912 Subobject, Field, &Layout)) 9913 return false; 9914 9915 // Perform an implicit value-initialization for members beyond the end of 9916 // the initializer list. 9917 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9918 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9919 9920 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9921 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9922 isa<CXXDefaultInitExpr>(Init)); 9923 9924 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9925 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9926 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9927 FieldVal, Field))) { 9928 if (!Info.noteFailure()) 9929 return false; 9930 Success = false; 9931 } 9932 } 9933 9934 EvalObj.finishedConstructingFields(); 9935 9936 return Success; 9937 } 9938 9939 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9940 QualType T) { 9941 // Note that E's type is not necessarily the type of our class here; we might 9942 // be initializing an array element instead. 9943 const CXXConstructorDecl *FD = E->getConstructor(); 9944 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9945 9946 bool ZeroInit = E->requiresZeroInitialization(); 9947 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9948 // If we've already performed zero-initialization, we're already done. 9949 if (Result.hasValue()) 9950 return true; 9951 9952 if (ZeroInit) 9953 return ZeroInitialization(E, T); 9954 9955 return getDefaultInitValue(T, Result); 9956 } 9957 9958 const FunctionDecl *Definition = nullptr; 9959 auto Body = FD->getBody(Definition); 9960 9961 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9962 return false; 9963 9964 // Avoid materializing a temporary for an elidable copy/move constructor. 9965 if (E->isElidable() && !ZeroInit) { 9966 // FIXME: This only handles the simplest case, where the source object 9967 // is passed directly as the first argument to the constructor. 9968 // This should also handle stepping though implicit casts and 9969 // and conversion sequences which involve two steps, with a 9970 // conversion operator followed by a converting constructor. 9971 const Expr *SrcObj = E->getArg(0); 9972 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 9973 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 9974 if (const MaterializeTemporaryExpr *ME = 9975 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 9976 return Visit(ME->getSubExpr()); 9977 } 9978 9979 if (ZeroInit && !ZeroInitialization(E, T)) 9980 return false; 9981 9982 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9983 return HandleConstructorCall(E, This, Args, 9984 cast<CXXConstructorDecl>(Definition), Info, 9985 Result); 9986 } 9987 9988 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9989 const CXXInheritedCtorInitExpr *E) { 9990 if (!Info.CurrentCall) { 9991 assert(Info.checkingPotentialConstantExpression()); 9992 return false; 9993 } 9994 9995 const CXXConstructorDecl *FD = E->getConstructor(); 9996 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9997 return false; 9998 9999 const FunctionDecl *Definition = nullptr; 10000 auto Body = FD->getBody(Definition); 10001 10002 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10003 return false; 10004 10005 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 10006 cast<CXXConstructorDecl>(Definition), Info, 10007 Result); 10008 } 10009 10010 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 10011 const CXXStdInitializerListExpr *E) { 10012 const ConstantArrayType *ArrayType = 10013 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 10014 10015 LValue Array; 10016 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 10017 return false; 10018 10019 // Get a pointer to the first element of the array. 10020 Array.addArray(Info, E, ArrayType); 10021 10022 auto InvalidType = [&] { 10023 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 10024 << E->getType(); 10025 return false; 10026 }; 10027 10028 // FIXME: Perform the checks on the field types in SemaInit. 10029 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10030 RecordDecl::field_iterator Field = Record->field_begin(); 10031 if (Field == Record->field_end()) 10032 return InvalidType(); 10033 10034 // Start pointer. 10035 if (!Field->getType()->isPointerType() || 10036 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10037 ArrayType->getElementType())) 10038 return InvalidType(); 10039 10040 // FIXME: What if the initializer_list type has base classes, etc? 10041 Result = APValue(APValue::UninitStruct(), 0, 2); 10042 Array.moveInto(Result.getStructField(0)); 10043 10044 if (++Field == Record->field_end()) 10045 return InvalidType(); 10046 10047 if (Field->getType()->isPointerType() && 10048 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10049 ArrayType->getElementType())) { 10050 // End pointer. 10051 if (!HandleLValueArrayAdjustment(Info, E, Array, 10052 ArrayType->getElementType(), 10053 ArrayType->getSize().getZExtValue())) 10054 return false; 10055 Array.moveInto(Result.getStructField(1)); 10056 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10057 // Length. 10058 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10059 else 10060 return InvalidType(); 10061 10062 if (++Field != Record->field_end()) 10063 return InvalidType(); 10064 10065 return true; 10066 } 10067 10068 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10069 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10070 if (ClosureClass->isInvalidDecl()) 10071 return false; 10072 10073 const size_t NumFields = 10074 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10075 10076 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10077 E->capture_init_end()) && 10078 "The number of lambda capture initializers should equal the number of " 10079 "fields within the closure type"); 10080 10081 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10082 // Iterate through all the lambda's closure object's fields and initialize 10083 // them. 10084 auto *CaptureInitIt = E->capture_init_begin(); 10085 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10086 bool Success = true; 10087 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10088 for (const auto *Field : ClosureClass->fields()) { 10089 assert(CaptureInitIt != E->capture_init_end()); 10090 // Get the initializer for this field 10091 Expr *const CurFieldInit = *CaptureInitIt++; 10092 10093 // If there is no initializer, either this is a VLA or an error has 10094 // occurred. 10095 if (!CurFieldInit) 10096 return Error(E); 10097 10098 LValue Subobject = This; 10099 10100 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10101 return false; 10102 10103 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10104 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10105 if (!Info.keepEvaluatingAfterFailure()) 10106 return false; 10107 Success = false; 10108 } 10109 ++CaptureIt; 10110 } 10111 return Success; 10112 } 10113 10114 static bool EvaluateRecord(const Expr *E, const LValue &This, 10115 APValue &Result, EvalInfo &Info) { 10116 assert(!E->isValueDependent()); 10117 assert(E->isPRValue() && E->getType()->isRecordType() && 10118 "can't evaluate expression as a record rvalue"); 10119 return RecordExprEvaluator(Info, This, Result).Visit(E); 10120 } 10121 10122 //===----------------------------------------------------------------------===// 10123 // Temporary Evaluation 10124 // 10125 // Temporaries are represented in the AST as rvalues, but generally behave like 10126 // lvalues. The full-object of which the temporary is a subobject is implicitly 10127 // materialized so that a reference can bind to it. 10128 //===----------------------------------------------------------------------===// 10129 namespace { 10130 class TemporaryExprEvaluator 10131 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10132 public: 10133 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10134 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10135 10136 /// Visit an expression which constructs the value of this temporary. 10137 bool VisitConstructExpr(const Expr *E) { 10138 APValue &Value = Info.CurrentCall->createTemporary( 10139 E, E->getType(), ScopeKind::FullExpression, Result); 10140 return EvaluateInPlace(Value, Info, Result, E); 10141 } 10142 10143 bool VisitCastExpr(const CastExpr *E) { 10144 switch (E->getCastKind()) { 10145 default: 10146 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10147 10148 case CK_ConstructorConversion: 10149 return VisitConstructExpr(E->getSubExpr()); 10150 } 10151 } 10152 bool VisitInitListExpr(const InitListExpr *E) { 10153 return VisitConstructExpr(E); 10154 } 10155 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10156 return VisitConstructExpr(E); 10157 } 10158 bool VisitCallExpr(const CallExpr *E) { 10159 return VisitConstructExpr(E); 10160 } 10161 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10162 return VisitConstructExpr(E); 10163 } 10164 bool VisitLambdaExpr(const LambdaExpr *E) { 10165 return VisitConstructExpr(E); 10166 } 10167 }; 10168 } // end anonymous namespace 10169 10170 /// Evaluate an expression of record type as a temporary. 10171 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10172 assert(!E->isValueDependent()); 10173 assert(E->isPRValue() && E->getType()->isRecordType()); 10174 return TemporaryExprEvaluator(Info, Result).Visit(E); 10175 } 10176 10177 //===----------------------------------------------------------------------===// 10178 // Vector Evaluation 10179 //===----------------------------------------------------------------------===// 10180 10181 namespace { 10182 class VectorExprEvaluator 10183 : public ExprEvaluatorBase<VectorExprEvaluator> { 10184 APValue &Result; 10185 public: 10186 10187 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10188 : ExprEvaluatorBaseTy(info), Result(Result) {} 10189 10190 bool Success(ArrayRef<APValue> V, const Expr *E) { 10191 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10192 // FIXME: remove this APValue copy. 10193 Result = APValue(V.data(), V.size()); 10194 return true; 10195 } 10196 bool Success(const APValue &V, const Expr *E) { 10197 assert(V.isVector()); 10198 Result = V; 10199 return true; 10200 } 10201 bool ZeroInitialization(const Expr *E); 10202 10203 bool VisitUnaryReal(const UnaryOperator *E) 10204 { return Visit(E->getSubExpr()); } 10205 bool VisitCastExpr(const CastExpr* E); 10206 bool VisitInitListExpr(const InitListExpr *E); 10207 bool VisitUnaryImag(const UnaryOperator *E); 10208 bool VisitBinaryOperator(const BinaryOperator *E); 10209 bool VisitUnaryOperator(const UnaryOperator *E); 10210 // FIXME: Missing: conditional operator (for GNU 10211 // conditional select), shufflevector, ExtVectorElementExpr 10212 }; 10213 } // end anonymous namespace 10214 10215 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10216 assert(E->isPRValue() && E->getType()->isVectorType() && 10217 "not a vector prvalue"); 10218 return VectorExprEvaluator(Info, Result).Visit(E); 10219 } 10220 10221 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10222 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10223 unsigned NElts = VTy->getNumElements(); 10224 10225 const Expr *SE = E->getSubExpr(); 10226 QualType SETy = SE->getType(); 10227 10228 switch (E->getCastKind()) { 10229 case CK_VectorSplat: { 10230 APValue Val = APValue(); 10231 if (SETy->isIntegerType()) { 10232 APSInt IntResult; 10233 if (!EvaluateInteger(SE, IntResult, Info)) 10234 return false; 10235 Val = APValue(std::move(IntResult)); 10236 } else if (SETy->isRealFloatingType()) { 10237 APFloat FloatResult(0.0); 10238 if (!EvaluateFloat(SE, FloatResult, Info)) 10239 return false; 10240 Val = APValue(std::move(FloatResult)); 10241 } else { 10242 return Error(E); 10243 } 10244 10245 // Splat and create vector APValue. 10246 SmallVector<APValue, 4> Elts(NElts, Val); 10247 return Success(Elts, E); 10248 } 10249 case CK_BitCast: { 10250 // Evaluate the operand into an APInt we can extract from. 10251 llvm::APInt SValInt; 10252 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10253 return false; 10254 // Extract the elements 10255 QualType EltTy = VTy->getElementType(); 10256 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10257 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10258 SmallVector<APValue, 4> Elts; 10259 if (EltTy->isRealFloatingType()) { 10260 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10261 unsigned FloatEltSize = EltSize; 10262 if (&Sem == &APFloat::x87DoubleExtended()) 10263 FloatEltSize = 80; 10264 for (unsigned i = 0; i < NElts; i++) { 10265 llvm::APInt Elt; 10266 if (BigEndian) 10267 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10268 else 10269 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10270 Elts.push_back(APValue(APFloat(Sem, Elt))); 10271 } 10272 } else if (EltTy->isIntegerType()) { 10273 for (unsigned i = 0; i < NElts; i++) { 10274 llvm::APInt Elt; 10275 if (BigEndian) 10276 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10277 else 10278 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10279 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10280 } 10281 } else { 10282 return Error(E); 10283 } 10284 return Success(Elts, E); 10285 } 10286 default: 10287 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10288 } 10289 } 10290 10291 bool 10292 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10293 const VectorType *VT = E->getType()->castAs<VectorType>(); 10294 unsigned NumInits = E->getNumInits(); 10295 unsigned NumElements = VT->getNumElements(); 10296 10297 QualType EltTy = VT->getElementType(); 10298 SmallVector<APValue, 4> Elements; 10299 10300 // The number of initializers can be less than the number of 10301 // vector elements. For OpenCL, this can be due to nested vector 10302 // initialization. For GCC compatibility, missing trailing elements 10303 // should be initialized with zeroes. 10304 unsigned CountInits = 0, CountElts = 0; 10305 while (CountElts < NumElements) { 10306 // Handle nested vector initialization. 10307 if (CountInits < NumInits 10308 && E->getInit(CountInits)->getType()->isVectorType()) { 10309 APValue v; 10310 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10311 return Error(E); 10312 unsigned vlen = v.getVectorLength(); 10313 for (unsigned j = 0; j < vlen; j++) 10314 Elements.push_back(v.getVectorElt(j)); 10315 CountElts += vlen; 10316 } else if (EltTy->isIntegerType()) { 10317 llvm::APSInt sInt(32); 10318 if (CountInits < NumInits) { 10319 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10320 return false; 10321 } else // trailing integer zero. 10322 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10323 Elements.push_back(APValue(sInt)); 10324 CountElts++; 10325 } else { 10326 llvm::APFloat f(0.0); 10327 if (CountInits < NumInits) { 10328 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10329 return false; 10330 } else // trailing float zero. 10331 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10332 Elements.push_back(APValue(f)); 10333 CountElts++; 10334 } 10335 CountInits++; 10336 } 10337 return Success(Elements, E); 10338 } 10339 10340 bool 10341 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10342 const auto *VT = E->getType()->castAs<VectorType>(); 10343 QualType EltTy = VT->getElementType(); 10344 APValue ZeroElement; 10345 if (EltTy->isIntegerType()) 10346 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10347 else 10348 ZeroElement = 10349 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10350 10351 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10352 return Success(Elements, E); 10353 } 10354 10355 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10356 VisitIgnoredValue(E->getSubExpr()); 10357 return ZeroInitialization(E); 10358 } 10359 10360 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10361 BinaryOperatorKind Op = E->getOpcode(); 10362 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10363 "Operation not supported on vector types"); 10364 10365 if (Op == BO_Comma) 10366 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10367 10368 Expr *LHS = E->getLHS(); 10369 Expr *RHS = E->getRHS(); 10370 10371 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10372 "Must both be vector types"); 10373 // Checking JUST the types are the same would be fine, except shifts don't 10374 // need to have their types be the same (since you always shift by an int). 10375 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10376 E->getType()->castAs<VectorType>()->getNumElements() && 10377 RHS->getType()->castAs<VectorType>()->getNumElements() == 10378 E->getType()->castAs<VectorType>()->getNumElements() && 10379 "All operands must be the same size."); 10380 10381 APValue LHSValue; 10382 APValue RHSValue; 10383 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10384 if (!LHSOK && !Info.noteFailure()) 10385 return false; 10386 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10387 return false; 10388 10389 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10390 return false; 10391 10392 return Success(LHSValue, E); 10393 } 10394 10395 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, 10396 QualType ResultTy, 10397 UnaryOperatorKind Op, 10398 APValue Elt) { 10399 switch (Op) { 10400 case UO_Plus: 10401 // Nothing to do here. 10402 return Elt; 10403 case UO_Minus: 10404 if (Elt.getKind() == APValue::Int) { 10405 Elt.getInt().negate(); 10406 } else { 10407 assert(Elt.getKind() == APValue::Float && 10408 "Vector can only be int or float type"); 10409 Elt.getFloat().changeSign(); 10410 } 10411 return Elt; 10412 case UO_Not: 10413 // This is only valid for integral types anyway, so we don't have to handle 10414 // float here. 10415 assert(Elt.getKind() == APValue::Int && 10416 "Vector operator ~ can only be int"); 10417 Elt.getInt().flipAllBits(); 10418 return Elt; 10419 case UO_LNot: { 10420 if (Elt.getKind() == APValue::Int) { 10421 Elt.getInt() = !Elt.getInt(); 10422 // operator ! on vectors returns -1 for 'truth', so negate it. 10423 Elt.getInt().negate(); 10424 return Elt; 10425 } 10426 assert(Elt.getKind() == APValue::Float && 10427 "Vector can only be int or float type"); 10428 // Float types result in an int of the same size, but -1 for true, or 0 for 10429 // false. 10430 APSInt EltResult{Ctx.getIntWidth(ResultTy), 10431 ResultTy->isUnsignedIntegerType()}; 10432 if (Elt.getFloat().isZero()) 10433 EltResult.setAllBits(); 10434 else 10435 EltResult.clearAllBits(); 10436 10437 return APValue{EltResult}; 10438 } 10439 default: 10440 // FIXME: Implement the rest of the unary operators. 10441 return llvm::None; 10442 } 10443 } 10444 10445 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10446 Expr *SubExpr = E->getSubExpr(); 10447 const auto *VD = SubExpr->getType()->castAs<VectorType>(); 10448 // This result element type differs in the case of negating a floating point 10449 // vector, since the result type is the a vector of the equivilant sized 10450 // integer. 10451 const QualType ResultEltTy = VD->getElementType(); 10452 UnaryOperatorKind Op = E->getOpcode(); 10453 10454 APValue SubExprValue; 10455 if (!Evaluate(SubExprValue, Info, SubExpr)) 10456 return false; 10457 10458 // FIXME: This vector evaluator someday needs to be changed to be LValue 10459 // aware/keep LValue information around, rather than dealing with just vector 10460 // types directly. Until then, we cannot handle cases where the operand to 10461 // these unary operators is an LValue. The only case I've been able to see 10462 // cause this is operator++ assigning to a member expression (only valid in 10463 // altivec compilations) in C mode, so this shouldn't limit us too much. 10464 if (SubExprValue.isLValue()) 10465 return false; 10466 10467 assert(SubExprValue.getVectorLength() == VD->getNumElements() && 10468 "Vector length doesn't match type?"); 10469 10470 SmallVector<APValue, 4> ResultElements; 10471 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { 10472 llvm::Optional<APValue> Elt = handleVectorUnaryOperator( 10473 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); 10474 if (!Elt) 10475 return false; 10476 ResultElements.push_back(*Elt); 10477 } 10478 return Success(APValue(ResultElements.data(), ResultElements.size()), E); 10479 } 10480 10481 //===----------------------------------------------------------------------===// 10482 // Array Evaluation 10483 //===----------------------------------------------------------------------===// 10484 10485 namespace { 10486 class ArrayExprEvaluator 10487 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10488 const LValue &This; 10489 APValue &Result; 10490 public: 10491 10492 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10493 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10494 10495 bool Success(const APValue &V, const Expr *E) { 10496 assert(V.isArray() && "expected array"); 10497 Result = V; 10498 return true; 10499 } 10500 10501 bool ZeroInitialization(const Expr *E) { 10502 const ConstantArrayType *CAT = 10503 Info.Ctx.getAsConstantArrayType(E->getType()); 10504 if (!CAT) { 10505 if (E->getType()->isIncompleteArrayType()) { 10506 // We can be asked to zero-initialize a flexible array member; this 10507 // is represented as an ImplicitValueInitExpr of incomplete array 10508 // type. In this case, the array has zero elements. 10509 Result = APValue(APValue::UninitArray(), 0, 0); 10510 return true; 10511 } 10512 // FIXME: We could handle VLAs here. 10513 return Error(E); 10514 } 10515 10516 Result = APValue(APValue::UninitArray(), 0, 10517 CAT->getSize().getZExtValue()); 10518 if (!Result.hasArrayFiller()) 10519 return true; 10520 10521 // Zero-initialize all elements. 10522 LValue Subobject = This; 10523 Subobject.addArray(Info, E, CAT); 10524 ImplicitValueInitExpr VIE(CAT->getElementType()); 10525 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10526 } 10527 10528 bool VisitCallExpr(const CallExpr *E) { 10529 return handleCallExpr(E, Result, &This); 10530 } 10531 bool VisitInitListExpr(const InitListExpr *E, 10532 QualType AllocType = QualType()); 10533 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10534 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10535 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10536 const LValue &Subobject, 10537 APValue *Value, QualType Type); 10538 bool VisitStringLiteral(const StringLiteral *E, 10539 QualType AllocType = QualType()) { 10540 expandStringLiteral(Info, E, Result, AllocType); 10541 return true; 10542 } 10543 }; 10544 } // end anonymous namespace 10545 10546 static bool EvaluateArray(const Expr *E, const LValue &This, 10547 APValue &Result, EvalInfo &Info) { 10548 assert(!E->isValueDependent()); 10549 assert(E->isPRValue() && E->getType()->isArrayType() && 10550 "not an array prvalue"); 10551 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10552 } 10553 10554 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10555 APValue &Result, const InitListExpr *ILE, 10556 QualType AllocType) { 10557 assert(!ILE->isValueDependent()); 10558 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10559 "not an array prvalue"); 10560 return ArrayExprEvaluator(Info, This, Result) 10561 .VisitInitListExpr(ILE, AllocType); 10562 } 10563 10564 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10565 APValue &Result, 10566 const CXXConstructExpr *CCE, 10567 QualType AllocType) { 10568 assert(!CCE->isValueDependent()); 10569 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10570 "not an array prvalue"); 10571 return ArrayExprEvaluator(Info, This, Result) 10572 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10573 } 10574 10575 // Return true iff the given array filler may depend on the element index. 10576 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10577 // For now, just allow non-class value-initialization and initialization 10578 // lists comprised of them. 10579 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10580 return false; 10581 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10582 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10583 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10584 return true; 10585 } 10586 return false; 10587 } 10588 return true; 10589 } 10590 10591 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10592 QualType AllocType) { 10593 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10594 AllocType.isNull() ? E->getType() : AllocType); 10595 if (!CAT) 10596 return Error(E); 10597 10598 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10599 // an appropriately-typed string literal enclosed in braces. 10600 if (E->isStringLiteralInit()) { 10601 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10602 // FIXME: Support ObjCEncodeExpr here once we support it in 10603 // ArrayExprEvaluator generally. 10604 if (!SL) 10605 return Error(E); 10606 return VisitStringLiteral(SL, AllocType); 10607 } 10608 // Any other transparent list init will need proper handling of the 10609 // AllocType; we can't just recurse to the inner initializer. 10610 assert(!E->isTransparent() && 10611 "transparent array list initialization is not string literal init?"); 10612 10613 bool Success = true; 10614 10615 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10616 "zero-initialized array shouldn't have any initialized elts"); 10617 APValue Filler; 10618 if (Result.isArray() && Result.hasArrayFiller()) 10619 Filler = Result.getArrayFiller(); 10620 10621 unsigned NumEltsToInit = E->getNumInits(); 10622 unsigned NumElts = CAT->getSize().getZExtValue(); 10623 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10624 10625 // If the initializer might depend on the array index, run it for each 10626 // array element. 10627 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10628 NumEltsToInit = NumElts; 10629 10630 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10631 << NumEltsToInit << ".\n"); 10632 10633 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10634 10635 // If the array was previously zero-initialized, preserve the 10636 // zero-initialized values. 10637 if (Filler.hasValue()) { 10638 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10639 Result.getArrayInitializedElt(I) = Filler; 10640 if (Result.hasArrayFiller()) 10641 Result.getArrayFiller() = Filler; 10642 } 10643 10644 LValue Subobject = This; 10645 Subobject.addArray(Info, E, CAT); 10646 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10647 const Expr *Init = 10648 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10649 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10650 Info, Subobject, Init) || 10651 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10652 CAT->getElementType(), 1)) { 10653 if (!Info.noteFailure()) 10654 return false; 10655 Success = false; 10656 } 10657 } 10658 10659 if (!Result.hasArrayFiller()) 10660 return Success; 10661 10662 // If we get here, we have a trivial filler, which we can just evaluate 10663 // once and splat over the rest of the array elements. 10664 assert(FillerExpr && "no array filler for incomplete init list"); 10665 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10666 FillerExpr) && Success; 10667 } 10668 10669 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10670 LValue CommonLV; 10671 if (E->getCommonExpr() && 10672 !Evaluate(Info.CurrentCall->createTemporary( 10673 E->getCommonExpr(), 10674 getStorageType(Info.Ctx, E->getCommonExpr()), 10675 ScopeKind::FullExpression, CommonLV), 10676 Info, E->getCommonExpr()->getSourceExpr())) 10677 return false; 10678 10679 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10680 10681 uint64_t Elements = CAT->getSize().getZExtValue(); 10682 Result = APValue(APValue::UninitArray(), Elements, Elements); 10683 10684 LValue Subobject = This; 10685 Subobject.addArray(Info, E, CAT); 10686 10687 bool Success = true; 10688 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10689 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10690 Info, Subobject, E->getSubExpr()) || 10691 !HandleLValueArrayAdjustment(Info, E, Subobject, 10692 CAT->getElementType(), 1)) { 10693 if (!Info.noteFailure()) 10694 return false; 10695 Success = false; 10696 } 10697 } 10698 10699 return Success; 10700 } 10701 10702 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10703 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10704 } 10705 10706 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10707 const LValue &Subobject, 10708 APValue *Value, 10709 QualType Type) { 10710 bool HadZeroInit = Value->hasValue(); 10711 10712 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10713 unsigned FinalSize = CAT->getSize().getZExtValue(); 10714 10715 // Preserve the array filler if we had prior zero-initialization. 10716 APValue Filler = 10717 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10718 : APValue(); 10719 10720 *Value = APValue(APValue::UninitArray(), 0, FinalSize); 10721 if (FinalSize == 0) 10722 return true; 10723 10724 LValue ArrayElt = Subobject; 10725 ArrayElt.addArray(Info, E, CAT); 10726 // We do the whole initialization in two passes, first for just one element, 10727 // then for the whole array. It's possible we may find out we can't do const 10728 // init in the first pass, in which case we avoid allocating a potentially 10729 // large array. We don't do more passes because expanding array requires 10730 // copying the data, which is wasteful. 10731 for (const unsigned N : {1u, FinalSize}) { 10732 unsigned OldElts = Value->getArrayInitializedElts(); 10733 if (OldElts == N) 10734 break; 10735 10736 // Expand the array to appropriate size. 10737 APValue NewValue(APValue::UninitArray(), N, FinalSize); 10738 for (unsigned I = 0; I < OldElts; ++I) 10739 NewValue.getArrayInitializedElt(I).swap( 10740 Value->getArrayInitializedElt(I)); 10741 Value->swap(NewValue); 10742 10743 if (HadZeroInit) 10744 for (unsigned I = OldElts; I < N; ++I) 10745 Value->getArrayInitializedElt(I) = Filler; 10746 10747 // Initialize the elements. 10748 for (unsigned I = OldElts; I < N; ++I) { 10749 if (!VisitCXXConstructExpr(E, ArrayElt, 10750 &Value->getArrayInitializedElt(I), 10751 CAT->getElementType()) || 10752 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10753 CAT->getElementType(), 1)) 10754 return false; 10755 // When checking for const initilization any diagnostic is considered 10756 // an error. 10757 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && 10758 !Info.keepEvaluatingAfterFailure()) 10759 return false; 10760 } 10761 } 10762 10763 return true; 10764 } 10765 10766 if (!Type->isRecordType()) 10767 return Error(E); 10768 10769 return RecordExprEvaluator(Info, Subobject, *Value) 10770 .VisitCXXConstructExpr(E, Type); 10771 } 10772 10773 //===----------------------------------------------------------------------===// 10774 // Integer Evaluation 10775 // 10776 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10777 // types and back in constant folding. Integer values are thus represented 10778 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10779 //===----------------------------------------------------------------------===// 10780 10781 namespace { 10782 class IntExprEvaluator 10783 : public ExprEvaluatorBase<IntExprEvaluator> { 10784 APValue &Result; 10785 public: 10786 IntExprEvaluator(EvalInfo &info, APValue &result) 10787 : ExprEvaluatorBaseTy(info), Result(result) {} 10788 10789 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10790 assert(E->getType()->isIntegralOrEnumerationType() && 10791 "Invalid evaluation result."); 10792 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10793 "Invalid evaluation result."); 10794 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10795 "Invalid evaluation result."); 10796 Result = APValue(SI); 10797 return true; 10798 } 10799 bool Success(const llvm::APSInt &SI, const Expr *E) { 10800 return Success(SI, E, Result); 10801 } 10802 10803 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10804 assert(E->getType()->isIntegralOrEnumerationType() && 10805 "Invalid evaluation result."); 10806 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10807 "Invalid evaluation result."); 10808 Result = APValue(APSInt(I)); 10809 Result.getInt().setIsUnsigned( 10810 E->getType()->isUnsignedIntegerOrEnumerationType()); 10811 return true; 10812 } 10813 bool Success(const llvm::APInt &I, const Expr *E) { 10814 return Success(I, E, Result); 10815 } 10816 10817 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10818 assert(E->getType()->isIntegralOrEnumerationType() && 10819 "Invalid evaluation result."); 10820 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10821 return true; 10822 } 10823 bool Success(uint64_t Value, const Expr *E) { 10824 return Success(Value, E, Result); 10825 } 10826 10827 bool Success(CharUnits Size, const Expr *E) { 10828 return Success(Size.getQuantity(), E); 10829 } 10830 10831 bool Success(const APValue &V, const Expr *E) { 10832 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10833 Result = V; 10834 return true; 10835 } 10836 return Success(V.getInt(), E); 10837 } 10838 10839 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10840 10841 //===--------------------------------------------------------------------===// 10842 // Visitor Methods 10843 //===--------------------------------------------------------------------===// 10844 10845 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10846 return Success(E->getValue(), E); 10847 } 10848 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10849 return Success(E->getValue(), E); 10850 } 10851 10852 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10853 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10854 if (CheckReferencedDecl(E, E->getDecl())) 10855 return true; 10856 10857 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10858 } 10859 bool VisitMemberExpr(const MemberExpr *E) { 10860 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10861 VisitIgnoredBaseExpression(E->getBase()); 10862 return true; 10863 } 10864 10865 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10866 } 10867 10868 bool VisitCallExpr(const CallExpr *E); 10869 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10870 bool VisitBinaryOperator(const BinaryOperator *E); 10871 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10872 bool VisitUnaryOperator(const UnaryOperator *E); 10873 10874 bool VisitCastExpr(const CastExpr* E); 10875 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10876 10877 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10878 return Success(E->getValue(), E); 10879 } 10880 10881 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10882 return Success(E->getValue(), E); 10883 } 10884 10885 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10886 if (Info.ArrayInitIndex == uint64_t(-1)) { 10887 // We were asked to evaluate this subexpression independent of the 10888 // enclosing ArrayInitLoopExpr. We can't do that. 10889 Info.FFDiag(E); 10890 return false; 10891 } 10892 return Success(Info.ArrayInitIndex, E); 10893 } 10894 10895 // Note, GNU defines __null as an integer, not a pointer. 10896 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10897 return ZeroInitialization(E); 10898 } 10899 10900 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10901 return Success(E->getValue(), E); 10902 } 10903 10904 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10905 return Success(E->getValue(), E); 10906 } 10907 10908 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10909 return Success(E->getValue(), E); 10910 } 10911 10912 bool VisitUnaryReal(const UnaryOperator *E); 10913 bool VisitUnaryImag(const UnaryOperator *E); 10914 10915 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10916 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10917 bool VisitSourceLocExpr(const SourceLocExpr *E); 10918 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10919 bool VisitRequiresExpr(const RequiresExpr *E); 10920 // FIXME: Missing: array subscript of vector, member of vector 10921 }; 10922 10923 class FixedPointExprEvaluator 10924 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10925 APValue &Result; 10926 10927 public: 10928 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10929 : ExprEvaluatorBaseTy(info), Result(result) {} 10930 10931 bool Success(const llvm::APInt &I, const Expr *E) { 10932 return Success( 10933 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10934 } 10935 10936 bool Success(uint64_t Value, const Expr *E) { 10937 return Success( 10938 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10939 } 10940 10941 bool Success(const APValue &V, const Expr *E) { 10942 return Success(V.getFixedPoint(), E); 10943 } 10944 10945 bool Success(const APFixedPoint &V, const Expr *E) { 10946 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10947 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10948 "Invalid evaluation result."); 10949 Result = APValue(V); 10950 return true; 10951 } 10952 10953 //===--------------------------------------------------------------------===// 10954 // Visitor Methods 10955 //===--------------------------------------------------------------------===// 10956 10957 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10958 return Success(E->getValue(), E); 10959 } 10960 10961 bool VisitCastExpr(const CastExpr *E); 10962 bool VisitUnaryOperator(const UnaryOperator *E); 10963 bool VisitBinaryOperator(const BinaryOperator *E); 10964 }; 10965 } // end anonymous namespace 10966 10967 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10968 /// produce either the integer value or a pointer. 10969 /// 10970 /// GCC has a heinous extension which folds casts between pointer types and 10971 /// pointer-sized integral types. We support this by allowing the evaluation of 10972 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10973 /// Some simple arithmetic on such values is supported (they are treated much 10974 /// like char*). 10975 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10976 EvalInfo &Info) { 10977 assert(!E->isValueDependent()); 10978 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 10979 return IntExprEvaluator(Info, Result).Visit(E); 10980 } 10981 10982 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10983 assert(!E->isValueDependent()); 10984 APValue Val; 10985 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10986 return false; 10987 if (!Val.isInt()) { 10988 // FIXME: It would be better to produce the diagnostic for casting 10989 // a pointer to an integer. 10990 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10991 return false; 10992 } 10993 Result = Val.getInt(); 10994 return true; 10995 } 10996 10997 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10998 APValue Evaluated = E->EvaluateInContext( 10999 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 11000 return Success(Evaluated, E); 11001 } 11002 11003 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 11004 EvalInfo &Info) { 11005 assert(!E->isValueDependent()); 11006 if (E->getType()->isFixedPointType()) { 11007 APValue Val; 11008 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 11009 return false; 11010 if (!Val.isFixedPoint()) 11011 return false; 11012 11013 Result = Val.getFixedPoint(); 11014 return true; 11015 } 11016 return false; 11017 } 11018 11019 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 11020 EvalInfo &Info) { 11021 assert(!E->isValueDependent()); 11022 if (E->getType()->isIntegerType()) { 11023 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 11024 APSInt Val; 11025 if (!EvaluateInteger(E, Val, Info)) 11026 return false; 11027 Result = APFixedPoint(Val, FXSema); 11028 return true; 11029 } else if (E->getType()->isFixedPointType()) { 11030 return EvaluateFixedPoint(E, Result, Info); 11031 } 11032 return false; 11033 } 11034 11035 /// Check whether the given declaration can be directly converted to an integral 11036 /// rvalue. If not, no diagnostic is produced; there are other things we can 11037 /// try. 11038 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 11039 // Enums are integer constant exprs. 11040 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 11041 // Check for signedness/width mismatches between E type and ECD value. 11042 bool SameSign = (ECD->getInitVal().isSigned() 11043 == E->getType()->isSignedIntegerOrEnumerationType()); 11044 bool SameWidth = (ECD->getInitVal().getBitWidth() 11045 == Info.Ctx.getIntWidth(E->getType())); 11046 if (SameSign && SameWidth) 11047 return Success(ECD->getInitVal(), E); 11048 else { 11049 // Get rid of mismatch (otherwise Success assertions will fail) 11050 // by computing a new value matching the type of E. 11051 llvm::APSInt Val = ECD->getInitVal(); 11052 if (!SameSign) 11053 Val.setIsSigned(!ECD->getInitVal().isSigned()); 11054 if (!SameWidth) 11055 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 11056 return Success(Val, E); 11057 } 11058 } 11059 return false; 11060 } 11061 11062 /// Values returned by __builtin_classify_type, chosen to match the values 11063 /// produced by GCC's builtin. 11064 enum class GCCTypeClass { 11065 None = -1, 11066 Void = 0, 11067 Integer = 1, 11068 // GCC reserves 2 for character types, but instead classifies them as 11069 // integers. 11070 Enum = 3, 11071 Bool = 4, 11072 Pointer = 5, 11073 // GCC reserves 6 for references, but appears to never use it (because 11074 // expressions never have reference type, presumably). 11075 PointerToDataMember = 7, 11076 RealFloat = 8, 11077 Complex = 9, 11078 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 11079 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 11080 // GCC claims to reserve 11 for pointers to member functions, but *actually* 11081 // uses 12 for that purpose, same as for a class or struct. Maybe it 11082 // internally implements a pointer to member as a struct? Who knows. 11083 PointerToMemberFunction = 12, // Not a bug, see above. 11084 ClassOrStruct = 12, 11085 Union = 13, 11086 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 11087 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 11088 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 11089 // literals. 11090 }; 11091 11092 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11093 /// as GCC. 11094 static GCCTypeClass 11095 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 11096 assert(!T->isDependentType() && "unexpected dependent type"); 11097 11098 QualType CanTy = T.getCanonicalType(); 11099 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 11100 11101 switch (CanTy->getTypeClass()) { 11102 #define TYPE(ID, BASE) 11103 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 11104 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 11105 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 11106 #include "clang/AST/TypeNodes.inc" 11107 case Type::Auto: 11108 case Type::DeducedTemplateSpecialization: 11109 llvm_unreachable("unexpected non-canonical or dependent type"); 11110 11111 case Type::Builtin: 11112 switch (BT->getKind()) { 11113 #define BUILTIN_TYPE(ID, SINGLETON_ID) 11114 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 11115 case BuiltinType::ID: return GCCTypeClass::Integer; 11116 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 11117 case BuiltinType::ID: return GCCTypeClass::RealFloat; 11118 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 11119 case BuiltinType::ID: break; 11120 #include "clang/AST/BuiltinTypes.def" 11121 case BuiltinType::Void: 11122 return GCCTypeClass::Void; 11123 11124 case BuiltinType::Bool: 11125 return GCCTypeClass::Bool; 11126 11127 case BuiltinType::Char_U: 11128 case BuiltinType::UChar: 11129 case BuiltinType::WChar_U: 11130 case BuiltinType::Char8: 11131 case BuiltinType::Char16: 11132 case BuiltinType::Char32: 11133 case BuiltinType::UShort: 11134 case BuiltinType::UInt: 11135 case BuiltinType::ULong: 11136 case BuiltinType::ULongLong: 11137 case BuiltinType::UInt128: 11138 return GCCTypeClass::Integer; 11139 11140 case BuiltinType::UShortAccum: 11141 case BuiltinType::UAccum: 11142 case BuiltinType::ULongAccum: 11143 case BuiltinType::UShortFract: 11144 case BuiltinType::UFract: 11145 case BuiltinType::ULongFract: 11146 case BuiltinType::SatUShortAccum: 11147 case BuiltinType::SatUAccum: 11148 case BuiltinType::SatULongAccum: 11149 case BuiltinType::SatUShortFract: 11150 case BuiltinType::SatUFract: 11151 case BuiltinType::SatULongFract: 11152 return GCCTypeClass::None; 11153 11154 case BuiltinType::NullPtr: 11155 11156 case BuiltinType::ObjCId: 11157 case BuiltinType::ObjCClass: 11158 case BuiltinType::ObjCSel: 11159 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11160 case BuiltinType::Id: 11161 #include "clang/Basic/OpenCLImageTypes.def" 11162 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11163 case BuiltinType::Id: 11164 #include "clang/Basic/OpenCLExtensionTypes.def" 11165 case BuiltinType::OCLSampler: 11166 case BuiltinType::OCLEvent: 11167 case BuiltinType::OCLClkEvent: 11168 case BuiltinType::OCLQueue: 11169 case BuiltinType::OCLReserveID: 11170 #define SVE_TYPE(Name, Id, SingletonId) \ 11171 case BuiltinType::Id: 11172 #include "clang/Basic/AArch64SVEACLETypes.def" 11173 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11174 case BuiltinType::Id: 11175 #include "clang/Basic/PPCTypes.def" 11176 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11177 #include "clang/Basic/RISCVVTypes.def" 11178 return GCCTypeClass::None; 11179 11180 case BuiltinType::Dependent: 11181 llvm_unreachable("unexpected dependent type"); 11182 }; 11183 llvm_unreachable("unexpected placeholder type"); 11184 11185 case Type::Enum: 11186 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11187 11188 case Type::Pointer: 11189 case Type::ConstantArray: 11190 case Type::VariableArray: 11191 case Type::IncompleteArray: 11192 case Type::FunctionNoProto: 11193 case Type::FunctionProto: 11194 return GCCTypeClass::Pointer; 11195 11196 case Type::MemberPointer: 11197 return CanTy->isMemberDataPointerType() 11198 ? GCCTypeClass::PointerToDataMember 11199 : GCCTypeClass::PointerToMemberFunction; 11200 11201 case Type::Complex: 11202 return GCCTypeClass::Complex; 11203 11204 case Type::Record: 11205 return CanTy->isUnionType() ? GCCTypeClass::Union 11206 : GCCTypeClass::ClassOrStruct; 11207 11208 case Type::Atomic: 11209 // GCC classifies _Atomic T the same as T. 11210 return EvaluateBuiltinClassifyType( 11211 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11212 11213 case Type::BlockPointer: 11214 case Type::Vector: 11215 case Type::ExtVector: 11216 case Type::ConstantMatrix: 11217 case Type::ObjCObject: 11218 case Type::ObjCInterface: 11219 case Type::ObjCObjectPointer: 11220 case Type::Pipe: 11221 case Type::BitInt: 11222 // GCC classifies vectors as None. We follow its lead and classify all 11223 // other types that don't fit into the regular classification the same way. 11224 return GCCTypeClass::None; 11225 11226 case Type::LValueReference: 11227 case Type::RValueReference: 11228 llvm_unreachable("invalid type for expression"); 11229 } 11230 11231 llvm_unreachable("unexpected type class"); 11232 } 11233 11234 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11235 /// as GCC. 11236 static GCCTypeClass 11237 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11238 // If no argument was supplied, default to None. This isn't 11239 // ideal, however it is what gcc does. 11240 if (E->getNumArgs() == 0) 11241 return GCCTypeClass::None; 11242 11243 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11244 // being an ICE, but still folds it to a constant using the type of the first 11245 // argument. 11246 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11247 } 11248 11249 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11250 /// __builtin_constant_p when applied to the given pointer. 11251 /// 11252 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11253 /// or it points to the first character of a string literal. 11254 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11255 APValue::LValueBase Base = LV.getLValueBase(); 11256 if (Base.isNull()) { 11257 // A null base is acceptable. 11258 return true; 11259 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11260 if (!isa<StringLiteral>(E)) 11261 return false; 11262 return LV.getLValueOffset().isZero(); 11263 } else if (Base.is<TypeInfoLValue>()) { 11264 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11265 // evaluate to true. 11266 return true; 11267 } else { 11268 // Any other base is not constant enough for GCC. 11269 return false; 11270 } 11271 } 11272 11273 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11274 /// GCC as we can manage. 11275 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11276 // This evaluation is not permitted to have side-effects, so evaluate it in 11277 // a speculative evaluation context. 11278 SpeculativeEvaluationRAII SpeculativeEval(Info); 11279 11280 // Constant-folding is always enabled for the operand of __builtin_constant_p 11281 // (even when the enclosing evaluation context otherwise requires a strict 11282 // language-specific constant expression). 11283 FoldConstant Fold(Info, true); 11284 11285 QualType ArgType = Arg->getType(); 11286 11287 // __builtin_constant_p always has one operand. The rules which gcc follows 11288 // are not precisely documented, but are as follows: 11289 // 11290 // - If the operand is of integral, floating, complex or enumeration type, 11291 // and can be folded to a known value of that type, it returns 1. 11292 // - If the operand can be folded to a pointer to the first character 11293 // of a string literal (or such a pointer cast to an integral type) 11294 // or to a null pointer or an integer cast to a pointer, it returns 1. 11295 // 11296 // Otherwise, it returns 0. 11297 // 11298 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11299 // its support for this did not work prior to GCC 9 and is not yet well 11300 // understood. 11301 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11302 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11303 ArgType->isNullPtrType()) { 11304 APValue V; 11305 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11306 Fold.keepDiagnostics(); 11307 return false; 11308 } 11309 11310 // For a pointer (possibly cast to integer), there are special rules. 11311 if (V.getKind() == APValue::LValue) 11312 return EvaluateBuiltinConstantPForLValue(V); 11313 11314 // Otherwise, any constant value is good enough. 11315 return V.hasValue(); 11316 } 11317 11318 // Anything else isn't considered to be sufficiently constant. 11319 return false; 11320 } 11321 11322 /// Retrieves the "underlying object type" of the given expression, 11323 /// as used by __builtin_object_size. 11324 static QualType getObjectType(APValue::LValueBase B) { 11325 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11326 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11327 return VD->getType(); 11328 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11329 if (isa<CompoundLiteralExpr>(E)) 11330 return E->getType(); 11331 } else if (B.is<TypeInfoLValue>()) { 11332 return B.getTypeInfoType(); 11333 } else if (B.is<DynamicAllocLValue>()) { 11334 return B.getDynamicAllocType(); 11335 } 11336 11337 return QualType(); 11338 } 11339 11340 /// A more selective version of E->IgnoreParenCasts for 11341 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11342 /// to change the type of E. 11343 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11344 /// 11345 /// Always returns an RValue with a pointer representation. 11346 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11347 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11348 11349 auto *NoParens = E->IgnoreParens(); 11350 auto *Cast = dyn_cast<CastExpr>(NoParens); 11351 if (Cast == nullptr) 11352 return NoParens; 11353 11354 // We only conservatively allow a few kinds of casts, because this code is 11355 // inherently a simple solution that seeks to support the common case. 11356 auto CastKind = Cast->getCastKind(); 11357 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11358 CastKind != CK_AddressSpaceConversion) 11359 return NoParens; 11360 11361 auto *SubExpr = Cast->getSubExpr(); 11362 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11363 return NoParens; 11364 return ignorePointerCastsAndParens(SubExpr); 11365 } 11366 11367 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11368 /// record layout. e.g. 11369 /// struct { struct { int a, b; } fst, snd; } obj; 11370 /// obj.fst // no 11371 /// obj.snd // yes 11372 /// obj.fst.a // no 11373 /// obj.fst.b // no 11374 /// obj.snd.a // no 11375 /// obj.snd.b // yes 11376 /// 11377 /// Please note: this function is specialized for how __builtin_object_size 11378 /// views "objects". 11379 /// 11380 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11381 /// correct result, it will always return true. 11382 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11383 assert(!LVal.Designator.Invalid); 11384 11385 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11386 const RecordDecl *Parent = FD->getParent(); 11387 Invalid = Parent->isInvalidDecl(); 11388 if (Invalid || Parent->isUnion()) 11389 return true; 11390 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11391 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11392 }; 11393 11394 auto &Base = LVal.getLValueBase(); 11395 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11396 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11397 bool Invalid; 11398 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11399 return Invalid; 11400 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11401 for (auto *FD : IFD->chain()) { 11402 bool Invalid; 11403 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11404 return Invalid; 11405 } 11406 } 11407 } 11408 11409 unsigned I = 0; 11410 QualType BaseType = getType(Base); 11411 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11412 // If we don't know the array bound, conservatively assume we're looking at 11413 // the final array element. 11414 ++I; 11415 if (BaseType->isIncompleteArrayType()) 11416 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11417 else 11418 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11419 } 11420 11421 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11422 const auto &Entry = LVal.Designator.Entries[I]; 11423 if (BaseType->isArrayType()) { 11424 // Because __builtin_object_size treats arrays as objects, we can ignore 11425 // the index iff this is the last array in the Designator. 11426 if (I + 1 == E) 11427 return true; 11428 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11429 uint64_t Index = Entry.getAsArrayIndex(); 11430 if (Index + 1 != CAT->getSize()) 11431 return false; 11432 BaseType = CAT->getElementType(); 11433 } else if (BaseType->isAnyComplexType()) { 11434 const auto *CT = BaseType->castAs<ComplexType>(); 11435 uint64_t Index = Entry.getAsArrayIndex(); 11436 if (Index != 1) 11437 return false; 11438 BaseType = CT->getElementType(); 11439 } else if (auto *FD = getAsField(Entry)) { 11440 bool Invalid; 11441 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11442 return Invalid; 11443 BaseType = FD->getType(); 11444 } else { 11445 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11446 return false; 11447 } 11448 } 11449 return true; 11450 } 11451 11452 /// Tests to see if the LValue has a user-specified designator (that isn't 11453 /// necessarily valid). Note that this always returns 'true' if the LValue has 11454 /// an unsized array as its first designator entry, because there's currently no 11455 /// way to tell if the user typed *foo or foo[0]. 11456 static bool refersToCompleteObject(const LValue &LVal) { 11457 if (LVal.Designator.Invalid) 11458 return false; 11459 11460 if (!LVal.Designator.Entries.empty()) 11461 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11462 11463 if (!LVal.InvalidBase) 11464 return true; 11465 11466 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11467 // the LValueBase. 11468 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11469 return !E || !isa<MemberExpr>(E); 11470 } 11471 11472 /// Attempts to detect a user writing into a piece of memory that's impossible 11473 /// to figure out the size of by just using types. 11474 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11475 const SubobjectDesignator &Designator = LVal.Designator; 11476 // Notes: 11477 // - Users can only write off of the end when we have an invalid base. Invalid 11478 // bases imply we don't know where the memory came from. 11479 // - We used to be a bit more aggressive here; we'd only be conservative if 11480 // the array at the end was flexible, or if it had 0 or 1 elements. This 11481 // broke some common standard library extensions (PR30346), but was 11482 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11483 // with some sort of list. OTOH, it seems that GCC is always 11484 // conservative with the last element in structs (if it's an array), so our 11485 // current behavior is more compatible than an explicit list approach would 11486 // be. 11487 return LVal.InvalidBase && 11488 Designator.Entries.size() == Designator.MostDerivedPathLength && 11489 Designator.MostDerivedIsArrayElement && 11490 isDesignatorAtObjectEnd(Ctx, LVal); 11491 } 11492 11493 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11494 /// Fails if the conversion would cause loss of precision. 11495 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11496 CharUnits &Result) { 11497 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11498 if (Int.ugt(CharUnitsMax)) 11499 return false; 11500 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11501 return true; 11502 } 11503 11504 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11505 /// determine how many bytes exist from the beginning of the object to either 11506 /// the end of the current subobject, or the end of the object itself, depending 11507 /// on what the LValue looks like + the value of Type. 11508 /// 11509 /// If this returns false, the value of Result is undefined. 11510 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11511 unsigned Type, const LValue &LVal, 11512 CharUnits &EndOffset) { 11513 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11514 11515 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11516 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11517 return false; 11518 return HandleSizeof(Info, ExprLoc, Ty, Result); 11519 }; 11520 11521 // We want to evaluate the size of the entire object. This is a valid fallback 11522 // for when Type=1 and the designator is invalid, because we're asked for an 11523 // upper-bound. 11524 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11525 // Type=3 wants a lower bound, so we can't fall back to this. 11526 if (Type == 3 && !DetermineForCompleteObject) 11527 return false; 11528 11529 llvm::APInt APEndOffset; 11530 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11531 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11532 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11533 11534 if (LVal.InvalidBase) 11535 return false; 11536 11537 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11538 return CheckedHandleSizeof(BaseTy, EndOffset); 11539 } 11540 11541 // We want to evaluate the size of a subobject. 11542 const SubobjectDesignator &Designator = LVal.Designator; 11543 11544 // The following is a moderately common idiom in C: 11545 // 11546 // struct Foo { int a; char c[1]; }; 11547 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11548 // strcpy(&F->c[0], Bar); 11549 // 11550 // In order to not break too much legacy code, we need to support it. 11551 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11552 // If we can resolve this to an alloc_size call, we can hand that back, 11553 // because we know for certain how many bytes there are to write to. 11554 llvm::APInt APEndOffset; 11555 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11556 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11557 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11558 11559 // If we cannot determine the size of the initial allocation, then we can't 11560 // given an accurate upper-bound. However, we are still able to give 11561 // conservative lower-bounds for Type=3. 11562 if (Type == 1) 11563 return false; 11564 } 11565 11566 CharUnits BytesPerElem; 11567 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11568 return false; 11569 11570 // According to the GCC documentation, we want the size of the subobject 11571 // denoted by the pointer. But that's not quite right -- what we actually 11572 // want is the size of the immediately-enclosing array, if there is one. 11573 int64_t ElemsRemaining; 11574 if (Designator.MostDerivedIsArrayElement && 11575 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11576 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11577 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11578 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11579 } else { 11580 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11581 } 11582 11583 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11584 return true; 11585 } 11586 11587 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11588 /// returns true and stores the result in @p Size. 11589 /// 11590 /// If @p WasError is non-null, this will report whether the failure to evaluate 11591 /// is to be treated as an Error in IntExprEvaluator. 11592 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11593 EvalInfo &Info, uint64_t &Size) { 11594 // Determine the denoted object. 11595 LValue LVal; 11596 { 11597 // The operand of __builtin_object_size is never evaluated for side-effects. 11598 // If there are any, but we can determine the pointed-to object anyway, then 11599 // ignore the side-effects. 11600 SpeculativeEvaluationRAII SpeculativeEval(Info); 11601 IgnoreSideEffectsRAII Fold(Info); 11602 11603 if (E->isGLValue()) { 11604 // It's possible for us to be given GLValues if we're called via 11605 // Expr::tryEvaluateObjectSize. 11606 APValue RVal; 11607 if (!EvaluateAsRValue(Info, E, RVal)) 11608 return false; 11609 LVal.setFrom(Info.Ctx, RVal); 11610 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11611 /*InvalidBaseOK=*/true)) 11612 return false; 11613 } 11614 11615 // If we point to before the start of the object, there are no accessible 11616 // bytes. 11617 if (LVal.getLValueOffset().isNegative()) { 11618 Size = 0; 11619 return true; 11620 } 11621 11622 CharUnits EndOffset; 11623 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11624 return false; 11625 11626 // If we've fallen outside of the end offset, just pretend there's nothing to 11627 // write to/read from. 11628 if (EndOffset <= LVal.getLValueOffset()) 11629 Size = 0; 11630 else 11631 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11632 return true; 11633 } 11634 11635 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11636 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11637 return VisitBuiltinCallExpr(E, BuiltinOp); 11638 11639 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11640 } 11641 11642 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11643 APValue &Val, APSInt &Alignment) { 11644 QualType SrcTy = E->getArg(0)->getType(); 11645 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11646 return false; 11647 // Even though we are evaluating integer expressions we could get a pointer 11648 // argument for the __builtin_is_aligned() case. 11649 if (SrcTy->isPointerType()) { 11650 LValue Ptr; 11651 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11652 return false; 11653 Ptr.moveInto(Val); 11654 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11655 Info.FFDiag(E->getArg(0)); 11656 return false; 11657 } else { 11658 APSInt SrcInt; 11659 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11660 return false; 11661 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11662 "Bit widths must be the same"); 11663 Val = APValue(SrcInt); 11664 } 11665 assert(Val.hasValue()); 11666 return true; 11667 } 11668 11669 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11670 unsigned BuiltinOp) { 11671 switch (BuiltinOp) { 11672 default: 11673 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11674 11675 case Builtin::BI__builtin_dynamic_object_size: 11676 case Builtin::BI__builtin_object_size: { 11677 // The type was checked when we built the expression. 11678 unsigned Type = 11679 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11680 assert(Type <= 3 && "unexpected type"); 11681 11682 uint64_t Size; 11683 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11684 return Success(Size, E); 11685 11686 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11687 return Success((Type & 2) ? 0 : -1, E); 11688 11689 // Expression had no side effects, but we couldn't statically determine the 11690 // size of the referenced object. 11691 switch (Info.EvalMode) { 11692 case EvalInfo::EM_ConstantExpression: 11693 case EvalInfo::EM_ConstantFold: 11694 case EvalInfo::EM_IgnoreSideEffects: 11695 // Leave it to IR generation. 11696 return Error(E); 11697 case EvalInfo::EM_ConstantExpressionUnevaluated: 11698 // Reduce it to a constant now. 11699 return Success((Type & 2) ? 0 : -1, E); 11700 } 11701 11702 llvm_unreachable("unexpected EvalMode"); 11703 } 11704 11705 case Builtin::BI__builtin_os_log_format_buffer_size: { 11706 analyze_os_log::OSLogBufferLayout Layout; 11707 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11708 return Success(Layout.size().getQuantity(), E); 11709 } 11710 11711 case Builtin::BI__builtin_is_aligned: { 11712 APValue Src; 11713 APSInt Alignment; 11714 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11715 return false; 11716 if (Src.isLValue()) { 11717 // If we evaluated a pointer, check the minimum known alignment. 11718 LValue Ptr; 11719 Ptr.setFrom(Info.Ctx, Src); 11720 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11721 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11722 // We can return true if the known alignment at the computed offset is 11723 // greater than the requested alignment. 11724 assert(PtrAlign.isPowerOfTwo()); 11725 assert(Alignment.isPowerOf2()); 11726 if (PtrAlign.getQuantity() >= Alignment) 11727 return Success(1, E); 11728 // If the alignment is not known to be sufficient, some cases could still 11729 // be aligned at run time. However, if the requested alignment is less or 11730 // equal to the base alignment and the offset is not aligned, we know that 11731 // the run-time value can never be aligned. 11732 if (BaseAlignment.getQuantity() >= Alignment && 11733 PtrAlign.getQuantity() < Alignment) 11734 return Success(0, E); 11735 // Otherwise we can't infer whether the value is sufficiently aligned. 11736 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11737 // in cases where we can't fully evaluate the pointer. 11738 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11739 << Alignment; 11740 return false; 11741 } 11742 assert(Src.isInt()); 11743 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11744 } 11745 case Builtin::BI__builtin_align_up: { 11746 APValue Src; 11747 APSInt Alignment; 11748 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11749 return false; 11750 if (!Src.isInt()) 11751 return Error(E); 11752 APSInt AlignedVal = 11753 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11754 Src.getInt().isUnsigned()); 11755 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11756 return Success(AlignedVal, E); 11757 } 11758 case Builtin::BI__builtin_align_down: { 11759 APValue Src; 11760 APSInt Alignment; 11761 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11762 return false; 11763 if (!Src.isInt()) 11764 return Error(E); 11765 APSInt AlignedVal = 11766 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11767 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11768 return Success(AlignedVal, E); 11769 } 11770 11771 case Builtin::BI__builtin_bitreverse8: 11772 case Builtin::BI__builtin_bitreverse16: 11773 case Builtin::BI__builtin_bitreverse32: 11774 case Builtin::BI__builtin_bitreverse64: { 11775 APSInt Val; 11776 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11777 return false; 11778 11779 return Success(Val.reverseBits(), E); 11780 } 11781 11782 case Builtin::BI__builtin_bswap16: 11783 case Builtin::BI__builtin_bswap32: 11784 case Builtin::BI__builtin_bswap64: { 11785 APSInt Val; 11786 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11787 return false; 11788 11789 return Success(Val.byteSwap(), E); 11790 } 11791 11792 case Builtin::BI__builtin_classify_type: 11793 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11794 11795 case Builtin::BI__builtin_clrsb: 11796 case Builtin::BI__builtin_clrsbl: 11797 case Builtin::BI__builtin_clrsbll: { 11798 APSInt Val; 11799 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11800 return false; 11801 11802 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11803 } 11804 11805 case Builtin::BI__builtin_clz: 11806 case Builtin::BI__builtin_clzl: 11807 case Builtin::BI__builtin_clzll: 11808 case Builtin::BI__builtin_clzs: { 11809 APSInt Val; 11810 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11811 return false; 11812 if (!Val) 11813 return Error(E); 11814 11815 return Success(Val.countLeadingZeros(), E); 11816 } 11817 11818 case Builtin::BI__builtin_constant_p: { 11819 const Expr *Arg = E->getArg(0); 11820 if (EvaluateBuiltinConstantP(Info, Arg)) 11821 return Success(true, E); 11822 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11823 // Outside a constant context, eagerly evaluate to false in the presence 11824 // of side-effects in order to avoid -Wunsequenced false-positives in 11825 // a branch on __builtin_constant_p(expr). 11826 return Success(false, E); 11827 } 11828 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11829 return false; 11830 } 11831 11832 case Builtin::BI__builtin_is_constant_evaluated: { 11833 const auto *Callee = Info.CurrentCall->getCallee(); 11834 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11835 (Info.CallStackDepth == 1 || 11836 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11837 Callee->getIdentifier() && 11838 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11839 // FIXME: Find a better way to avoid duplicated diagnostics. 11840 if (Info.EvalStatus.Diag) 11841 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11842 : Info.CurrentCall->CallLoc, 11843 diag::warn_is_constant_evaluated_always_true_constexpr) 11844 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11845 : "std::is_constant_evaluated"); 11846 } 11847 11848 return Success(Info.InConstantContext, E); 11849 } 11850 11851 case Builtin::BI__builtin_ctz: 11852 case Builtin::BI__builtin_ctzl: 11853 case Builtin::BI__builtin_ctzll: 11854 case Builtin::BI__builtin_ctzs: { 11855 APSInt Val; 11856 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11857 return false; 11858 if (!Val) 11859 return Error(E); 11860 11861 return Success(Val.countTrailingZeros(), E); 11862 } 11863 11864 case Builtin::BI__builtin_eh_return_data_regno: { 11865 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11866 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11867 return Success(Operand, E); 11868 } 11869 11870 case Builtin::BI__builtin_expect: 11871 case Builtin::BI__builtin_expect_with_probability: 11872 return Visit(E->getArg(0)); 11873 11874 case Builtin::BI__builtin_ffs: 11875 case Builtin::BI__builtin_ffsl: 11876 case Builtin::BI__builtin_ffsll: { 11877 APSInt Val; 11878 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11879 return false; 11880 11881 unsigned N = Val.countTrailingZeros(); 11882 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11883 } 11884 11885 case Builtin::BI__builtin_fpclassify: { 11886 APFloat Val(0.0); 11887 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11888 return false; 11889 unsigned Arg; 11890 switch (Val.getCategory()) { 11891 case APFloat::fcNaN: Arg = 0; break; 11892 case APFloat::fcInfinity: Arg = 1; break; 11893 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11894 case APFloat::fcZero: Arg = 4; break; 11895 } 11896 return Visit(E->getArg(Arg)); 11897 } 11898 11899 case Builtin::BI__builtin_isinf_sign: { 11900 APFloat Val(0.0); 11901 return EvaluateFloat(E->getArg(0), Val, Info) && 11902 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11903 } 11904 11905 case Builtin::BI__builtin_isinf: { 11906 APFloat Val(0.0); 11907 return EvaluateFloat(E->getArg(0), Val, Info) && 11908 Success(Val.isInfinity() ? 1 : 0, E); 11909 } 11910 11911 case Builtin::BI__builtin_isfinite: { 11912 APFloat Val(0.0); 11913 return EvaluateFloat(E->getArg(0), Val, Info) && 11914 Success(Val.isFinite() ? 1 : 0, E); 11915 } 11916 11917 case Builtin::BI__builtin_isnan: { 11918 APFloat Val(0.0); 11919 return EvaluateFloat(E->getArg(0), Val, Info) && 11920 Success(Val.isNaN() ? 1 : 0, E); 11921 } 11922 11923 case Builtin::BI__builtin_isnormal: { 11924 APFloat Val(0.0); 11925 return EvaluateFloat(E->getArg(0), Val, Info) && 11926 Success(Val.isNormal() ? 1 : 0, E); 11927 } 11928 11929 case Builtin::BI__builtin_parity: 11930 case Builtin::BI__builtin_parityl: 11931 case Builtin::BI__builtin_parityll: { 11932 APSInt Val; 11933 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11934 return false; 11935 11936 return Success(Val.countPopulation() % 2, E); 11937 } 11938 11939 case Builtin::BI__builtin_popcount: 11940 case Builtin::BI__builtin_popcountl: 11941 case Builtin::BI__builtin_popcountll: { 11942 APSInt Val; 11943 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11944 return false; 11945 11946 return Success(Val.countPopulation(), E); 11947 } 11948 11949 case Builtin::BI__builtin_rotateleft8: 11950 case Builtin::BI__builtin_rotateleft16: 11951 case Builtin::BI__builtin_rotateleft32: 11952 case Builtin::BI__builtin_rotateleft64: 11953 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11954 case Builtin::BI_rotl16: 11955 case Builtin::BI_rotl: 11956 case Builtin::BI_lrotl: 11957 case Builtin::BI_rotl64: { 11958 APSInt Val, Amt; 11959 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11960 !EvaluateInteger(E->getArg(1), Amt, Info)) 11961 return false; 11962 11963 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11964 } 11965 11966 case Builtin::BI__builtin_rotateright8: 11967 case Builtin::BI__builtin_rotateright16: 11968 case Builtin::BI__builtin_rotateright32: 11969 case Builtin::BI__builtin_rotateright64: 11970 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11971 case Builtin::BI_rotr16: 11972 case Builtin::BI_rotr: 11973 case Builtin::BI_lrotr: 11974 case Builtin::BI_rotr64: { 11975 APSInt Val, Amt; 11976 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11977 !EvaluateInteger(E->getArg(1), Amt, Info)) 11978 return false; 11979 11980 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11981 } 11982 11983 case Builtin::BIstrlen: 11984 case Builtin::BIwcslen: 11985 // A call to strlen is not a constant expression. 11986 if (Info.getLangOpts().CPlusPlus11) 11987 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11988 << /*isConstexpr*/0 << /*isConstructor*/0 11989 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11990 else 11991 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11992 LLVM_FALLTHROUGH; 11993 case Builtin::BI__builtin_strlen: 11994 case Builtin::BI__builtin_wcslen: { 11995 // As an extension, we support __builtin_strlen() as a constant expression, 11996 // and support folding strlen() to a constant. 11997 uint64_t StrLen; 11998 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 11999 return Success(StrLen, E); 12000 return false; 12001 } 12002 12003 case Builtin::BIstrcmp: 12004 case Builtin::BIwcscmp: 12005 case Builtin::BIstrncmp: 12006 case Builtin::BIwcsncmp: 12007 case Builtin::BImemcmp: 12008 case Builtin::BIbcmp: 12009 case Builtin::BIwmemcmp: 12010 // A call to strlen is not a constant expression. 12011 if (Info.getLangOpts().CPlusPlus11) 12012 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12013 << /*isConstexpr*/0 << /*isConstructor*/0 12014 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 12015 else 12016 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12017 LLVM_FALLTHROUGH; 12018 case Builtin::BI__builtin_strcmp: 12019 case Builtin::BI__builtin_wcscmp: 12020 case Builtin::BI__builtin_strncmp: 12021 case Builtin::BI__builtin_wcsncmp: 12022 case Builtin::BI__builtin_memcmp: 12023 case Builtin::BI__builtin_bcmp: 12024 case Builtin::BI__builtin_wmemcmp: { 12025 LValue String1, String2; 12026 if (!EvaluatePointer(E->getArg(0), String1, Info) || 12027 !EvaluatePointer(E->getArg(1), String2, Info)) 12028 return false; 12029 12030 uint64_t MaxLength = uint64_t(-1); 12031 if (BuiltinOp != Builtin::BIstrcmp && 12032 BuiltinOp != Builtin::BIwcscmp && 12033 BuiltinOp != Builtin::BI__builtin_strcmp && 12034 BuiltinOp != Builtin::BI__builtin_wcscmp) { 12035 APSInt N; 12036 if (!EvaluateInteger(E->getArg(2), N, Info)) 12037 return false; 12038 MaxLength = N.getExtValue(); 12039 } 12040 12041 // Empty substrings compare equal by definition. 12042 if (MaxLength == 0u) 12043 return Success(0, E); 12044 12045 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12046 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12047 String1.Designator.Invalid || String2.Designator.Invalid) 12048 return false; 12049 12050 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 12051 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 12052 12053 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 12054 BuiltinOp == Builtin::BIbcmp || 12055 BuiltinOp == Builtin::BI__builtin_memcmp || 12056 BuiltinOp == Builtin::BI__builtin_bcmp; 12057 12058 assert(IsRawByte || 12059 (Info.Ctx.hasSameUnqualifiedType( 12060 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 12061 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 12062 12063 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 12064 // 'char8_t', but no other types. 12065 if (IsRawByte && 12066 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 12067 // FIXME: Consider using our bit_cast implementation to support this. 12068 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 12069 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 12070 << CharTy1 << CharTy2; 12071 return false; 12072 } 12073 12074 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 12075 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 12076 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 12077 Char1.isInt() && Char2.isInt(); 12078 }; 12079 const auto &AdvanceElems = [&] { 12080 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 12081 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 12082 }; 12083 12084 bool StopAtNull = 12085 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 12086 BuiltinOp != Builtin::BIwmemcmp && 12087 BuiltinOp != Builtin::BI__builtin_memcmp && 12088 BuiltinOp != Builtin::BI__builtin_bcmp && 12089 BuiltinOp != Builtin::BI__builtin_wmemcmp); 12090 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 12091 BuiltinOp == Builtin::BIwcsncmp || 12092 BuiltinOp == Builtin::BIwmemcmp || 12093 BuiltinOp == Builtin::BI__builtin_wcscmp || 12094 BuiltinOp == Builtin::BI__builtin_wcsncmp || 12095 BuiltinOp == Builtin::BI__builtin_wmemcmp; 12096 12097 for (; MaxLength; --MaxLength) { 12098 APValue Char1, Char2; 12099 if (!ReadCurElems(Char1, Char2)) 12100 return false; 12101 if (Char1.getInt().ne(Char2.getInt())) { 12102 if (IsWide) // wmemcmp compares with wchar_t signedness. 12103 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 12104 // memcmp always compares unsigned chars. 12105 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 12106 } 12107 if (StopAtNull && !Char1.getInt()) 12108 return Success(0, E); 12109 assert(!(StopAtNull && !Char2.getInt())); 12110 if (!AdvanceElems()) 12111 return false; 12112 } 12113 // We hit the strncmp / memcmp limit. 12114 return Success(0, E); 12115 } 12116 12117 case Builtin::BI__atomic_always_lock_free: 12118 case Builtin::BI__atomic_is_lock_free: 12119 case Builtin::BI__c11_atomic_is_lock_free: { 12120 APSInt SizeVal; 12121 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 12122 return false; 12123 12124 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12125 // of two less than or equal to the maximum inline atomic width, we know it 12126 // is lock-free. If the size isn't a power of two, or greater than the 12127 // maximum alignment where we promote atomics, we know it is not lock-free 12128 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12129 // the answer can only be determined at runtime; for example, 16-byte 12130 // atomics have lock-free implementations on some, but not all, 12131 // x86-64 processors. 12132 12133 // Check power-of-two. 12134 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12135 if (Size.isPowerOfTwo()) { 12136 // Check against inlining width. 12137 unsigned InlineWidthBits = 12138 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12139 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12140 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12141 Size == CharUnits::One() || 12142 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12143 Expr::NPC_NeverValueDependent)) 12144 // OK, we will inline appropriately-aligned operations of this size, 12145 // and _Atomic(T) is appropriately-aligned. 12146 return Success(1, E); 12147 12148 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12149 castAs<PointerType>()->getPointeeType(); 12150 if (!PointeeType->isIncompleteType() && 12151 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12152 // OK, we will inline operations on this object. 12153 return Success(1, E); 12154 } 12155 } 12156 } 12157 12158 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12159 Success(0, E) : Error(E); 12160 } 12161 case Builtin::BI__builtin_add_overflow: 12162 case Builtin::BI__builtin_sub_overflow: 12163 case Builtin::BI__builtin_mul_overflow: 12164 case Builtin::BI__builtin_sadd_overflow: 12165 case Builtin::BI__builtin_uadd_overflow: 12166 case Builtin::BI__builtin_uaddl_overflow: 12167 case Builtin::BI__builtin_uaddll_overflow: 12168 case Builtin::BI__builtin_usub_overflow: 12169 case Builtin::BI__builtin_usubl_overflow: 12170 case Builtin::BI__builtin_usubll_overflow: 12171 case Builtin::BI__builtin_umul_overflow: 12172 case Builtin::BI__builtin_umull_overflow: 12173 case Builtin::BI__builtin_umulll_overflow: 12174 case Builtin::BI__builtin_saddl_overflow: 12175 case Builtin::BI__builtin_saddll_overflow: 12176 case Builtin::BI__builtin_ssub_overflow: 12177 case Builtin::BI__builtin_ssubl_overflow: 12178 case Builtin::BI__builtin_ssubll_overflow: 12179 case Builtin::BI__builtin_smul_overflow: 12180 case Builtin::BI__builtin_smull_overflow: 12181 case Builtin::BI__builtin_smulll_overflow: { 12182 LValue ResultLValue; 12183 APSInt LHS, RHS; 12184 12185 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12186 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12187 !EvaluateInteger(E->getArg(1), RHS, Info) || 12188 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12189 return false; 12190 12191 APSInt Result; 12192 bool DidOverflow = false; 12193 12194 // If the types don't have to match, enlarge all 3 to the largest of them. 12195 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12196 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12197 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12198 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12199 ResultType->isSignedIntegerOrEnumerationType(); 12200 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12201 ResultType->isSignedIntegerOrEnumerationType(); 12202 uint64_t LHSSize = LHS.getBitWidth(); 12203 uint64_t RHSSize = RHS.getBitWidth(); 12204 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12205 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12206 12207 // Add an additional bit if the signedness isn't uniformly agreed to. We 12208 // could do this ONLY if there is a signed and an unsigned that both have 12209 // MaxBits, but the code to check that is pretty nasty. The issue will be 12210 // caught in the shrink-to-result later anyway. 12211 if (IsSigned && !AllSigned) 12212 ++MaxBits; 12213 12214 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12215 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12216 Result = APSInt(MaxBits, !IsSigned); 12217 } 12218 12219 // Find largest int. 12220 switch (BuiltinOp) { 12221 default: 12222 llvm_unreachable("Invalid value for BuiltinOp"); 12223 case Builtin::BI__builtin_add_overflow: 12224 case Builtin::BI__builtin_sadd_overflow: 12225 case Builtin::BI__builtin_saddl_overflow: 12226 case Builtin::BI__builtin_saddll_overflow: 12227 case Builtin::BI__builtin_uadd_overflow: 12228 case Builtin::BI__builtin_uaddl_overflow: 12229 case Builtin::BI__builtin_uaddll_overflow: 12230 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12231 : LHS.uadd_ov(RHS, DidOverflow); 12232 break; 12233 case Builtin::BI__builtin_sub_overflow: 12234 case Builtin::BI__builtin_ssub_overflow: 12235 case Builtin::BI__builtin_ssubl_overflow: 12236 case Builtin::BI__builtin_ssubll_overflow: 12237 case Builtin::BI__builtin_usub_overflow: 12238 case Builtin::BI__builtin_usubl_overflow: 12239 case Builtin::BI__builtin_usubll_overflow: 12240 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12241 : LHS.usub_ov(RHS, DidOverflow); 12242 break; 12243 case Builtin::BI__builtin_mul_overflow: 12244 case Builtin::BI__builtin_smul_overflow: 12245 case Builtin::BI__builtin_smull_overflow: 12246 case Builtin::BI__builtin_smulll_overflow: 12247 case Builtin::BI__builtin_umul_overflow: 12248 case Builtin::BI__builtin_umull_overflow: 12249 case Builtin::BI__builtin_umulll_overflow: 12250 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12251 : LHS.umul_ov(RHS, DidOverflow); 12252 break; 12253 } 12254 12255 // In the case where multiple sizes are allowed, truncate and see if 12256 // the values are the same. 12257 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12258 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12259 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12260 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12261 // since it will give us the behavior of a TruncOrSelf in the case where 12262 // its parameter <= its size. We previously set Result to be at least the 12263 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12264 // will work exactly like TruncOrSelf. 12265 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12266 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12267 12268 if (!APSInt::isSameValue(Temp, Result)) 12269 DidOverflow = true; 12270 Result = Temp; 12271 } 12272 12273 APValue APV{Result}; 12274 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12275 return false; 12276 return Success(DidOverflow, E); 12277 } 12278 } 12279 } 12280 12281 /// Determine whether this is a pointer past the end of the complete 12282 /// object referred to by the lvalue. 12283 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12284 const LValue &LV) { 12285 // A null pointer can be viewed as being "past the end" but we don't 12286 // choose to look at it that way here. 12287 if (!LV.getLValueBase()) 12288 return false; 12289 12290 // If the designator is valid and refers to a subobject, we're not pointing 12291 // past the end. 12292 if (!LV.getLValueDesignator().Invalid && 12293 !LV.getLValueDesignator().isOnePastTheEnd()) 12294 return false; 12295 12296 // A pointer to an incomplete type might be past-the-end if the type's size is 12297 // zero. We cannot tell because the type is incomplete. 12298 QualType Ty = getType(LV.getLValueBase()); 12299 if (Ty->isIncompleteType()) 12300 return true; 12301 12302 // We're a past-the-end pointer if we point to the byte after the object, 12303 // no matter what our type or path is. 12304 auto Size = Ctx.getTypeSizeInChars(Ty); 12305 return LV.getLValueOffset() == Size; 12306 } 12307 12308 namespace { 12309 12310 /// Data recursive integer evaluator of certain binary operators. 12311 /// 12312 /// We use a data recursive algorithm for binary operators so that we are able 12313 /// to handle extreme cases of chained binary operators without causing stack 12314 /// overflow. 12315 class DataRecursiveIntBinOpEvaluator { 12316 struct EvalResult { 12317 APValue Val; 12318 bool Failed; 12319 12320 EvalResult() : Failed(false) { } 12321 12322 void swap(EvalResult &RHS) { 12323 Val.swap(RHS.Val); 12324 Failed = RHS.Failed; 12325 RHS.Failed = false; 12326 } 12327 }; 12328 12329 struct Job { 12330 const Expr *E; 12331 EvalResult LHSResult; // meaningful only for binary operator expression. 12332 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12333 12334 Job() = default; 12335 Job(Job &&) = default; 12336 12337 void startSpeculativeEval(EvalInfo &Info) { 12338 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12339 } 12340 12341 private: 12342 SpeculativeEvaluationRAII SpecEvalRAII; 12343 }; 12344 12345 SmallVector<Job, 16> Queue; 12346 12347 IntExprEvaluator &IntEval; 12348 EvalInfo &Info; 12349 APValue &FinalResult; 12350 12351 public: 12352 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12353 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12354 12355 /// True if \param E is a binary operator that we are going to handle 12356 /// data recursively. 12357 /// We handle binary operators that are comma, logical, or that have operands 12358 /// with integral or enumeration type. 12359 static bool shouldEnqueue(const BinaryOperator *E) { 12360 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12361 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12362 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12363 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12364 } 12365 12366 bool Traverse(const BinaryOperator *E) { 12367 enqueue(E); 12368 EvalResult PrevResult; 12369 while (!Queue.empty()) 12370 process(PrevResult); 12371 12372 if (PrevResult.Failed) return false; 12373 12374 FinalResult.swap(PrevResult.Val); 12375 return true; 12376 } 12377 12378 private: 12379 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12380 return IntEval.Success(Value, E, Result); 12381 } 12382 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12383 return IntEval.Success(Value, E, Result); 12384 } 12385 bool Error(const Expr *E) { 12386 return IntEval.Error(E); 12387 } 12388 bool Error(const Expr *E, diag::kind D) { 12389 return IntEval.Error(E, D); 12390 } 12391 12392 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12393 return Info.CCEDiag(E, D); 12394 } 12395 12396 // Returns true if visiting the RHS is necessary, false otherwise. 12397 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12398 bool &SuppressRHSDiags); 12399 12400 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12401 const BinaryOperator *E, APValue &Result); 12402 12403 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12404 Result.Failed = !Evaluate(Result.Val, Info, E); 12405 if (Result.Failed) 12406 Result.Val = APValue(); 12407 } 12408 12409 void process(EvalResult &Result); 12410 12411 void enqueue(const Expr *E) { 12412 E = E->IgnoreParens(); 12413 Queue.resize(Queue.size()+1); 12414 Queue.back().E = E; 12415 Queue.back().Kind = Job::AnyExprKind; 12416 } 12417 }; 12418 12419 } 12420 12421 bool DataRecursiveIntBinOpEvaluator:: 12422 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12423 bool &SuppressRHSDiags) { 12424 if (E->getOpcode() == BO_Comma) { 12425 // Ignore LHS but note if we could not evaluate it. 12426 if (LHSResult.Failed) 12427 return Info.noteSideEffect(); 12428 return true; 12429 } 12430 12431 if (E->isLogicalOp()) { 12432 bool LHSAsBool; 12433 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12434 // We were able to evaluate the LHS, see if we can get away with not 12435 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12436 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12437 Success(LHSAsBool, E, LHSResult.Val); 12438 return false; // Ignore RHS 12439 } 12440 } else { 12441 LHSResult.Failed = true; 12442 12443 // Since we weren't able to evaluate the left hand side, it 12444 // might have had side effects. 12445 if (!Info.noteSideEffect()) 12446 return false; 12447 12448 // We can't evaluate the LHS; however, sometimes the result 12449 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12450 // Don't ignore RHS and suppress diagnostics from this arm. 12451 SuppressRHSDiags = true; 12452 } 12453 12454 return true; 12455 } 12456 12457 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12458 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12459 12460 if (LHSResult.Failed && !Info.noteFailure()) 12461 return false; // Ignore RHS; 12462 12463 return true; 12464 } 12465 12466 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12467 bool IsSub) { 12468 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12469 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12470 // offsets. 12471 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12472 CharUnits &Offset = LVal.getLValueOffset(); 12473 uint64_t Offset64 = Offset.getQuantity(); 12474 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12475 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12476 : Offset64 + Index64); 12477 } 12478 12479 bool DataRecursiveIntBinOpEvaluator:: 12480 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12481 const BinaryOperator *E, APValue &Result) { 12482 if (E->getOpcode() == BO_Comma) { 12483 if (RHSResult.Failed) 12484 return false; 12485 Result = RHSResult.Val; 12486 return true; 12487 } 12488 12489 if (E->isLogicalOp()) { 12490 bool lhsResult, rhsResult; 12491 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12492 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12493 12494 if (LHSIsOK) { 12495 if (RHSIsOK) { 12496 if (E->getOpcode() == BO_LOr) 12497 return Success(lhsResult || rhsResult, E, Result); 12498 else 12499 return Success(lhsResult && rhsResult, E, Result); 12500 } 12501 } else { 12502 if (RHSIsOK) { 12503 // We can't evaluate the LHS; however, sometimes the result 12504 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12505 if (rhsResult == (E->getOpcode() == BO_LOr)) 12506 return Success(rhsResult, E, Result); 12507 } 12508 } 12509 12510 return false; 12511 } 12512 12513 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12514 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12515 12516 if (LHSResult.Failed || RHSResult.Failed) 12517 return false; 12518 12519 const APValue &LHSVal = LHSResult.Val; 12520 const APValue &RHSVal = RHSResult.Val; 12521 12522 // Handle cases like (unsigned long)&a + 4. 12523 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12524 Result = LHSVal; 12525 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12526 return true; 12527 } 12528 12529 // Handle cases like 4 + (unsigned long)&a 12530 if (E->getOpcode() == BO_Add && 12531 RHSVal.isLValue() && LHSVal.isInt()) { 12532 Result = RHSVal; 12533 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12534 return true; 12535 } 12536 12537 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12538 // Handle (intptr_t)&&A - (intptr_t)&&B. 12539 if (!LHSVal.getLValueOffset().isZero() || 12540 !RHSVal.getLValueOffset().isZero()) 12541 return false; 12542 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12543 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12544 if (!LHSExpr || !RHSExpr) 12545 return false; 12546 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12547 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12548 if (!LHSAddrExpr || !RHSAddrExpr) 12549 return false; 12550 // Make sure both labels come from the same function. 12551 if (LHSAddrExpr->getLabel()->getDeclContext() != 12552 RHSAddrExpr->getLabel()->getDeclContext()) 12553 return false; 12554 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12555 return true; 12556 } 12557 12558 // All the remaining cases expect both operands to be an integer 12559 if (!LHSVal.isInt() || !RHSVal.isInt()) 12560 return Error(E); 12561 12562 // Set up the width and signedness manually, in case it can't be deduced 12563 // from the operation we're performing. 12564 // FIXME: Don't do this in the cases where we can deduce it. 12565 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12566 E->getType()->isUnsignedIntegerOrEnumerationType()); 12567 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12568 RHSVal.getInt(), Value)) 12569 return false; 12570 return Success(Value, E, Result); 12571 } 12572 12573 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12574 Job &job = Queue.back(); 12575 12576 switch (job.Kind) { 12577 case Job::AnyExprKind: { 12578 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12579 if (shouldEnqueue(Bop)) { 12580 job.Kind = Job::BinOpKind; 12581 enqueue(Bop->getLHS()); 12582 return; 12583 } 12584 } 12585 12586 EvaluateExpr(job.E, Result); 12587 Queue.pop_back(); 12588 return; 12589 } 12590 12591 case Job::BinOpKind: { 12592 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12593 bool SuppressRHSDiags = false; 12594 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12595 Queue.pop_back(); 12596 return; 12597 } 12598 if (SuppressRHSDiags) 12599 job.startSpeculativeEval(Info); 12600 job.LHSResult.swap(Result); 12601 job.Kind = Job::BinOpVisitedLHSKind; 12602 enqueue(Bop->getRHS()); 12603 return; 12604 } 12605 12606 case Job::BinOpVisitedLHSKind: { 12607 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12608 EvalResult RHS; 12609 RHS.swap(Result); 12610 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12611 Queue.pop_back(); 12612 return; 12613 } 12614 } 12615 12616 llvm_unreachable("Invalid Job::Kind!"); 12617 } 12618 12619 namespace { 12620 enum class CmpResult { 12621 Unequal, 12622 Less, 12623 Equal, 12624 Greater, 12625 Unordered, 12626 }; 12627 } 12628 12629 template <class SuccessCB, class AfterCB> 12630 static bool 12631 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12632 SuccessCB &&Success, AfterCB &&DoAfter) { 12633 assert(!E->isValueDependent()); 12634 assert(E->isComparisonOp() && "expected comparison operator"); 12635 assert((E->getOpcode() == BO_Cmp || 12636 E->getType()->isIntegralOrEnumerationType()) && 12637 "unsupported binary expression evaluation"); 12638 auto Error = [&](const Expr *E) { 12639 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12640 return false; 12641 }; 12642 12643 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12644 bool IsEquality = E->isEqualityOp(); 12645 12646 QualType LHSTy = E->getLHS()->getType(); 12647 QualType RHSTy = E->getRHS()->getType(); 12648 12649 if (LHSTy->isIntegralOrEnumerationType() && 12650 RHSTy->isIntegralOrEnumerationType()) { 12651 APSInt LHS, RHS; 12652 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12653 if (!LHSOK && !Info.noteFailure()) 12654 return false; 12655 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12656 return false; 12657 if (LHS < RHS) 12658 return Success(CmpResult::Less, E); 12659 if (LHS > RHS) 12660 return Success(CmpResult::Greater, E); 12661 return Success(CmpResult::Equal, E); 12662 } 12663 12664 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12665 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12666 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12667 12668 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12669 if (!LHSOK && !Info.noteFailure()) 12670 return false; 12671 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12672 return false; 12673 if (LHSFX < RHSFX) 12674 return Success(CmpResult::Less, E); 12675 if (LHSFX > RHSFX) 12676 return Success(CmpResult::Greater, E); 12677 return Success(CmpResult::Equal, E); 12678 } 12679 12680 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12681 ComplexValue LHS, RHS; 12682 bool LHSOK; 12683 if (E->isAssignmentOp()) { 12684 LValue LV; 12685 EvaluateLValue(E->getLHS(), LV, Info); 12686 LHSOK = false; 12687 } else if (LHSTy->isRealFloatingType()) { 12688 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12689 if (LHSOK) { 12690 LHS.makeComplexFloat(); 12691 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12692 } 12693 } else { 12694 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12695 } 12696 if (!LHSOK && !Info.noteFailure()) 12697 return false; 12698 12699 if (E->getRHS()->getType()->isRealFloatingType()) { 12700 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12701 return false; 12702 RHS.makeComplexFloat(); 12703 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12704 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12705 return false; 12706 12707 if (LHS.isComplexFloat()) { 12708 APFloat::cmpResult CR_r = 12709 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12710 APFloat::cmpResult CR_i = 12711 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12712 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12713 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12714 } else { 12715 assert(IsEquality && "invalid complex comparison"); 12716 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12717 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12718 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12719 } 12720 } 12721 12722 if (LHSTy->isRealFloatingType() && 12723 RHSTy->isRealFloatingType()) { 12724 APFloat RHS(0.0), LHS(0.0); 12725 12726 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12727 if (!LHSOK && !Info.noteFailure()) 12728 return false; 12729 12730 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12731 return false; 12732 12733 assert(E->isComparisonOp() && "Invalid binary operator!"); 12734 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12735 if (!Info.InConstantContext && 12736 APFloatCmpResult == APFloat::cmpUnordered && 12737 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12738 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12739 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12740 return false; 12741 } 12742 auto GetCmpRes = [&]() { 12743 switch (APFloatCmpResult) { 12744 case APFloat::cmpEqual: 12745 return CmpResult::Equal; 12746 case APFloat::cmpLessThan: 12747 return CmpResult::Less; 12748 case APFloat::cmpGreaterThan: 12749 return CmpResult::Greater; 12750 case APFloat::cmpUnordered: 12751 return CmpResult::Unordered; 12752 } 12753 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12754 }; 12755 return Success(GetCmpRes(), E); 12756 } 12757 12758 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12759 LValue LHSValue, RHSValue; 12760 12761 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12762 if (!LHSOK && !Info.noteFailure()) 12763 return false; 12764 12765 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12766 return false; 12767 12768 // Reject differing bases from the normal codepath; we special-case 12769 // comparisons to null. 12770 if (!HasSameBase(LHSValue, RHSValue)) { 12771 // Inequalities and subtractions between unrelated pointers have 12772 // unspecified or undefined behavior. 12773 if (!IsEquality) { 12774 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12775 return false; 12776 } 12777 // A constant address may compare equal to the address of a symbol. 12778 // The one exception is that address of an object cannot compare equal 12779 // to a null pointer constant. 12780 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12781 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12782 return Error(E); 12783 // It's implementation-defined whether distinct literals will have 12784 // distinct addresses. In clang, the result of such a comparison is 12785 // unspecified, so it is not a constant expression. However, we do know 12786 // that the address of a literal will be non-null. 12787 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12788 LHSValue.Base && RHSValue.Base) 12789 return Error(E); 12790 // We can't tell whether weak symbols will end up pointing to the same 12791 // object. 12792 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12793 return Error(E); 12794 // We can't compare the address of the start of one object with the 12795 // past-the-end address of another object, per C++ DR1652. 12796 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12797 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12798 (RHSValue.Base && RHSValue.Offset.isZero() && 12799 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12800 return Error(E); 12801 // We can't tell whether an object is at the same address as another 12802 // zero sized object. 12803 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12804 (LHSValue.Base && isZeroSized(RHSValue))) 12805 return Error(E); 12806 return Success(CmpResult::Unequal, E); 12807 } 12808 12809 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12810 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12811 12812 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12813 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12814 12815 // C++11 [expr.rel]p3: 12816 // Pointers to void (after pointer conversions) can be compared, with a 12817 // result defined as follows: If both pointers represent the same 12818 // address or are both the null pointer value, the result is true if the 12819 // operator is <= or >= and false otherwise; otherwise the result is 12820 // unspecified. 12821 // We interpret this as applying to pointers to *cv* void. 12822 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12823 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12824 12825 // C++11 [expr.rel]p2: 12826 // - If two pointers point to non-static data members of the same object, 12827 // or to subobjects or array elements fo such members, recursively, the 12828 // pointer to the later declared member compares greater provided the 12829 // two members have the same access control and provided their class is 12830 // not a union. 12831 // [...] 12832 // - Otherwise pointer comparisons are unspecified. 12833 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12834 bool WasArrayIndex; 12835 unsigned Mismatch = FindDesignatorMismatch( 12836 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12837 // At the point where the designators diverge, the comparison has a 12838 // specified value if: 12839 // - we are comparing array indices 12840 // - we are comparing fields of a union, or fields with the same access 12841 // Otherwise, the result is unspecified and thus the comparison is not a 12842 // constant expression. 12843 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12844 Mismatch < RHSDesignator.Entries.size()) { 12845 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12846 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12847 if (!LF && !RF) 12848 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12849 else if (!LF) 12850 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12851 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12852 << RF->getParent() << RF; 12853 else if (!RF) 12854 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12855 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12856 << LF->getParent() << LF; 12857 else if (!LF->getParent()->isUnion() && 12858 LF->getAccess() != RF->getAccess()) 12859 Info.CCEDiag(E, 12860 diag::note_constexpr_pointer_comparison_differing_access) 12861 << LF << LF->getAccess() << RF << RF->getAccess() 12862 << LF->getParent(); 12863 } 12864 } 12865 12866 // The comparison here must be unsigned, and performed with the same 12867 // width as the pointer. 12868 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12869 uint64_t CompareLHS = LHSOffset.getQuantity(); 12870 uint64_t CompareRHS = RHSOffset.getQuantity(); 12871 assert(PtrSize <= 64 && "Unexpected pointer width"); 12872 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12873 CompareLHS &= Mask; 12874 CompareRHS &= Mask; 12875 12876 // If there is a base and this is a relational operator, we can only 12877 // compare pointers within the object in question; otherwise, the result 12878 // depends on where the object is located in memory. 12879 if (!LHSValue.Base.isNull() && IsRelational) { 12880 QualType BaseTy = getType(LHSValue.Base); 12881 if (BaseTy->isIncompleteType()) 12882 return Error(E); 12883 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12884 uint64_t OffsetLimit = Size.getQuantity(); 12885 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12886 return Error(E); 12887 } 12888 12889 if (CompareLHS < CompareRHS) 12890 return Success(CmpResult::Less, E); 12891 if (CompareLHS > CompareRHS) 12892 return Success(CmpResult::Greater, E); 12893 return Success(CmpResult::Equal, E); 12894 } 12895 12896 if (LHSTy->isMemberPointerType()) { 12897 assert(IsEquality && "unexpected member pointer operation"); 12898 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12899 12900 MemberPtr LHSValue, RHSValue; 12901 12902 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12903 if (!LHSOK && !Info.noteFailure()) 12904 return false; 12905 12906 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12907 return false; 12908 12909 // C++11 [expr.eq]p2: 12910 // If both operands are null, they compare equal. Otherwise if only one is 12911 // null, they compare unequal. 12912 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12913 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12914 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12915 } 12916 12917 // Otherwise if either is a pointer to a virtual member function, the 12918 // result is unspecified. 12919 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12920 if (MD->isVirtual()) 12921 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12922 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12923 if (MD->isVirtual()) 12924 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12925 12926 // Otherwise they compare equal if and only if they would refer to the 12927 // same member of the same most derived object or the same subobject if 12928 // they were dereferenced with a hypothetical object of the associated 12929 // class type. 12930 bool Equal = LHSValue == RHSValue; 12931 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12932 } 12933 12934 if (LHSTy->isNullPtrType()) { 12935 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12936 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12937 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12938 // are compared, the result is true of the operator is <=, >= or ==, and 12939 // false otherwise. 12940 return Success(CmpResult::Equal, E); 12941 } 12942 12943 return DoAfter(); 12944 } 12945 12946 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12947 if (!CheckLiteralType(Info, E)) 12948 return false; 12949 12950 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12951 ComparisonCategoryResult CCR; 12952 switch (CR) { 12953 case CmpResult::Unequal: 12954 llvm_unreachable("should never produce Unequal for three-way comparison"); 12955 case CmpResult::Less: 12956 CCR = ComparisonCategoryResult::Less; 12957 break; 12958 case CmpResult::Equal: 12959 CCR = ComparisonCategoryResult::Equal; 12960 break; 12961 case CmpResult::Greater: 12962 CCR = ComparisonCategoryResult::Greater; 12963 break; 12964 case CmpResult::Unordered: 12965 CCR = ComparisonCategoryResult::Unordered; 12966 break; 12967 } 12968 // Evaluation succeeded. Lookup the information for the comparison category 12969 // type and fetch the VarDecl for the result. 12970 const ComparisonCategoryInfo &CmpInfo = 12971 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12972 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12973 // Check and evaluate the result as a constant expression. 12974 LValue LV; 12975 LV.set(VD); 12976 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12977 return false; 12978 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12979 ConstantExprKind::Normal); 12980 }; 12981 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12982 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12983 }); 12984 } 12985 12986 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12987 // We don't support assignment in C. C++ assignments don't get here because 12988 // assignment is an lvalue in C++. 12989 if (E->isAssignmentOp()) { 12990 Error(E); 12991 if (!Info.noteFailure()) 12992 return false; 12993 } 12994 12995 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12996 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12997 12998 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12999 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 13000 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 13001 13002 if (E->isComparisonOp()) { 13003 // Evaluate builtin binary comparisons by evaluating them as three-way 13004 // comparisons and then translating the result. 13005 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13006 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 13007 "should only produce Unequal for equality comparisons"); 13008 bool IsEqual = CR == CmpResult::Equal, 13009 IsLess = CR == CmpResult::Less, 13010 IsGreater = CR == CmpResult::Greater; 13011 auto Op = E->getOpcode(); 13012 switch (Op) { 13013 default: 13014 llvm_unreachable("unsupported binary operator"); 13015 case BO_EQ: 13016 case BO_NE: 13017 return Success(IsEqual == (Op == BO_EQ), E); 13018 case BO_LT: 13019 return Success(IsLess, E); 13020 case BO_GT: 13021 return Success(IsGreater, E); 13022 case BO_LE: 13023 return Success(IsEqual || IsLess, E); 13024 case BO_GE: 13025 return Success(IsEqual || IsGreater, E); 13026 } 13027 }; 13028 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13029 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13030 }); 13031 } 13032 13033 QualType LHSTy = E->getLHS()->getType(); 13034 QualType RHSTy = E->getRHS()->getType(); 13035 13036 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 13037 E->getOpcode() == BO_Sub) { 13038 LValue LHSValue, RHSValue; 13039 13040 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13041 if (!LHSOK && !Info.noteFailure()) 13042 return false; 13043 13044 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13045 return false; 13046 13047 // Reject differing bases from the normal codepath; we special-case 13048 // comparisons to null. 13049 if (!HasSameBase(LHSValue, RHSValue)) { 13050 // Handle &&A - &&B. 13051 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 13052 return Error(E); 13053 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 13054 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 13055 if (!LHSExpr || !RHSExpr) 13056 return Error(E); 13057 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13058 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13059 if (!LHSAddrExpr || !RHSAddrExpr) 13060 return Error(E); 13061 // Make sure both labels come from the same function. 13062 if (LHSAddrExpr->getLabel()->getDeclContext() != 13063 RHSAddrExpr->getLabel()->getDeclContext()) 13064 return Error(E); 13065 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 13066 } 13067 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13068 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13069 13070 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13071 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13072 13073 // C++11 [expr.add]p6: 13074 // Unless both pointers point to elements of the same array object, or 13075 // one past the last element of the array object, the behavior is 13076 // undefined. 13077 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 13078 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 13079 RHSDesignator)) 13080 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 13081 13082 QualType Type = E->getLHS()->getType(); 13083 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 13084 13085 CharUnits ElementSize; 13086 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 13087 return false; 13088 13089 // As an extension, a type may have zero size (empty struct or union in 13090 // C, array of zero length). Pointer subtraction in such cases has 13091 // undefined behavior, so is not constant. 13092 if (ElementSize.isZero()) { 13093 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 13094 << ElementType; 13095 return false; 13096 } 13097 13098 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 13099 // and produce incorrect results when it overflows. Such behavior 13100 // appears to be non-conforming, but is common, so perhaps we should 13101 // assume the standard intended for such cases to be undefined behavior 13102 // and check for them. 13103 13104 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 13105 // overflow in the final conversion to ptrdiff_t. 13106 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 13107 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 13108 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 13109 false); 13110 APSInt TrueResult = (LHS - RHS) / ElemSize; 13111 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 13112 13113 if (Result.extend(65) != TrueResult && 13114 !HandleOverflow(Info, E, TrueResult, E->getType())) 13115 return false; 13116 return Success(Result, E); 13117 } 13118 13119 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13120 } 13121 13122 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 13123 /// a result as the expression's type. 13124 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13125 const UnaryExprOrTypeTraitExpr *E) { 13126 switch(E->getKind()) { 13127 case UETT_PreferredAlignOf: 13128 case UETT_AlignOf: { 13129 if (E->isArgumentType()) 13130 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13131 E); 13132 else 13133 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13134 E); 13135 } 13136 13137 case UETT_VecStep: { 13138 QualType Ty = E->getTypeOfArgument(); 13139 13140 if (Ty->isVectorType()) { 13141 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13142 13143 // The vec_step built-in functions that take a 3-component 13144 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13145 if (n == 3) 13146 n = 4; 13147 13148 return Success(n, E); 13149 } else 13150 return Success(1, E); 13151 } 13152 13153 case UETT_SizeOf: { 13154 QualType SrcTy = E->getTypeOfArgument(); 13155 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13156 // the result is the size of the referenced type." 13157 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13158 SrcTy = Ref->getPointeeType(); 13159 13160 CharUnits Sizeof; 13161 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13162 return false; 13163 return Success(Sizeof, E); 13164 } 13165 case UETT_OpenMPRequiredSimdAlign: 13166 assert(E->isArgumentType()); 13167 return Success( 13168 Info.Ctx.toCharUnitsFromBits( 13169 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13170 .getQuantity(), 13171 E); 13172 } 13173 13174 llvm_unreachable("unknown expr/type trait"); 13175 } 13176 13177 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13178 CharUnits Result; 13179 unsigned n = OOE->getNumComponents(); 13180 if (n == 0) 13181 return Error(OOE); 13182 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13183 for (unsigned i = 0; i != n; ++i) { 13184 OffsetOfNode ON = OOE->getComponent(i); 13185 switch (ON.getKind()) { 13186 case OffsetOfNode::Array: { 13187 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13188 APSInt IdxResult; 13189 if (!EvaluateInteger(Idx, IdxResult, Info)) 13190 return false; 13191 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13192 if (!AT) 13193 return Error(OOE); 13194 CurrentType = AT->getElementType(); 13195 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13196 Result += IdxResult.getSExtValue() * ElementSize; 13197 break; 13198 } 13199 13200 case OffsetOfNode::Field: { 13201 FieldDecl *MemberDecl = ON.getField(); 13202 const RecordType *RT = CurrentType->getAs<RecordType>(); 13203 if (!RT) 13204 return Error(OOE); 13205 RecordDecl *RD = RT->getDecl(); 13206 if (RD->isInvalidDecl()) return false; 13207 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13208 unsigned i = MemberDecl->getFieldIndex(); 13209 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13210 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13211 CurrentType = MemberDecl->getType().getNonReferenceType(); 13212 break; 13213 } 13214 13215 case OffsetOfNode::Identifier: 13216 llvm_unreachable("dependent __builtin_offsetof"); 13217 13218 case OffsetOfNode::Base: { 13219 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13220 if (BaseSpec->isVirtual()) 13221 return Error(OOE); 13222 13223 // Find the layout of the class whose base we are looking into. 13224 const RecordType *RT = CurrentType->getAs<RecordType>(); 13225 if (!RT) 13226 return Error(OOE); 13227 RecordDecl *RD = RT->getDecl(); 13228 if (RD->isInvalidDecl()) return false; 13229 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13230 13231 // Find the base class itself. 13232 CurrentType = BaseSpec->getType(); 13233 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13234 if (!BaseRT) 13235 return Error(OOE); 13236 13237 // Add the offset to the base. 13238 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13239 break; 13240 } 13241 } 13242 } 13243 return Success(Result, OOE); 13244 } 13245 13246 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13247 switch (E->getOpcode()) { 13248 default: 13249 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13250 // See C99 6.6p3. 13251 return Error(E); 13252 case UO_Extension: 13253 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13254 // If so, we could clear the diagnostic ID. 13255 return Visit(E->getSubExpr()); 13256 case UO_Plus: 13257 // The result is just the value. 13258 return Visit(E->getSubExpr()); 13259 case UO_Minus: { 13260 if (!Visit(E->getSubExpr())) 13261 return false; 13262 if (!Result.isInt()) return Error(E); 13263 const APSInt &Value = Result.getInt(); 13264 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13265 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13266 E->getType())) 13267 return false; 13268 return Success(-Value, E); 13269 } 13270 case UO_Not: { 13271 if (!Visit(E->getSubExpr())) 13272 return false; 13273 if (!Result.isInt()) return Error(E); 13274 return Success(~Result.getInt(), E); 13275 } 13276 case UO_LNot: { 13277 bool bres; 13278 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13279 return false; 13280 return Success(!bres, E); 13281 } 13282 } 13283 } 13284 13285 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13286 /// result type is integer. 13287 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13288 const Expr *SubExpr = E->getSubExpr(); 13289 QualType DestType = E->getType(); 13290 QualType SrcType = SubExpr->getType(); 13291 13292 switch (E->getCastKind()) { 13293 case CK_BaseToDerived: 13294 case CK_DerivedToBase: 13295 case CK_UncheckedDerivedToBase: 13296 case CK_Dynamic: 13297 case CK_ToUnion: 13298 case CK_ArrayToPointerDecay: 13299 case CK_FunctionToPointerDecay: 13300 case CK_NullToPointer: 13301 case CK_NullToMemberPointer: 13302 case CK_BaseToDerivedMemberPointer: 13303 case CK_DerivedToBaseMemberPointer: 13304 case CK_ReinterpretMemberPointer: 13305 case CK_ConstructorConversion: 13306 case CK_IntegralToPointer: 13307 case CK_ToVoid: 13308 case CK_VectorSplat: 13309 case CK_IntegralToFloating: 13310 case CK_FloatingCast: 13311 case CK_CPointerToObjCPointerCast: 13312 case CK_BlockPointerToObjCPointerCast: 13313 case CK_AnyPointerToBlockPointerCast: 13314 case CK_ObjCObjectLValueCast: 13315 case CK_FloatingRealToComplex: 13316 case CK_FloatingComplexToReal: 13317 case CK_FloatingComplexCast: 13318 case CK_FloatingComplexToIntegralComplex: 13319 case CK_IntegralRealToComplex: 13320 case CK_IntegralComplexCast: 13321 case CK_IntegralComplexToFloatingComplex: 13322 case CK_BuiltinFnToFnPtr: 13323 case CK_ZeroToOCLOpaqueType: 13324 case CK_NonAtomicToAtomic: 13325 case CK_AddressSpaceConversion: 13326 case CK_IntToOCLSampler: 13327 case CK_FloatingToFixedPoint: 13328 case CK_FixedPointToFloating: 13329 case CK_FixedPointCast: 13330 case CK_IntegralToFixedPoint: 13331 case CK_MatrixCast: 13332 llvm_unreachable("invalid cast kind for integral value"); 13333 13334 case CK_BitCast: 13335 case CK_Dependent: 13336 case CK_LValueBitCast: 13337 case CK_ARCProduceObject: 13338 case CK_ARCConsumeObject: 13339 case CK_ARCReclaimReturnedObject: 13340 case CK_ARCExtendBlockObject: 13341 case CK_CopyAndAutoreleaseBlockObject: 13342 return Error(E); 13343 13344 case CK_UserDefinedConversion: 13345 case CK_LValueToRValue: 13346 case CK_AtomicToNonAtomic: 13347 case CK_NoOp: 13348 case CK_LValueToRValueBitCast: 13349 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13350 13351 case CK_MemberPointerToBoolean: 13352 case CK_PointerToBoolean: 13353 case CK_IntegralToBoolean: 13354 case CK_FloatingToBoolean: 13355 case CK_BooleanToSignedIntegral: 13356 case CK_FloatingComplexToBoolean: 13357 case CK_IntegralComplexToBoolean: { 13358 bool BoolResult; 13359 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13360 return false; 13361 uint64_t IntResult = BoolResult; 13362 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13363 IntResult = (uint64_t)-1; 13364 return Success(IntResult, E); 13365 } 13366 13367 case CK_FixedPointToIntegral: { 13368 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13369 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13370 return false; 13371 bool Overflowed; 13372 llvm::APSInt Result = Src.convertToInt( 13373 Info.Ctx.getIntWidth(DestType), 13374 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13375 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13376 return false; 13377 return Success(Result, E); 13378 } 13379 13380 case CK_FixedPointToBoolean: { 13381 // Unsigned padding does not affect this. 13382 APValue Val; 13383 if (!Evaluate(Val, Info, SubExpr)) 13384 return false; 13385 return Success(Val.getFixedPoint().getBoolValue(), E); 13386 } 13387 13388 case CK_IntegralCast: { 13389 if (!Visit(SubExpr)) 13390 return false; 13391 13392 if (!Result.isInt()) { 13393 // Allow casts of address-of-label differences if they are no-ops 13394 // or narrowing. (The narrowing case isn't actually guaranteed to 13395 // be constant-evaluatable except in some narrow cases which are hard 13396 // to detect here. We let it through on the assumption the user knows 13397 // what they are doing.) 13398 if (Result.isAddrLabelDiff()) 13399 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13400 // Only allow casts of lvalues if they are lossless. 13401 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13402 } 13403 13404 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13405 Result.getInt()), E); 13406 } 13407 13408 case CK_PointerToIntegral: { 13409 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13410 13411 LValue LV; 13412 if (!EvaluatePointer(SubExpr, LV, Info)) 13413 return false; 13414 13415 if (LV.getLValueBase()) { 13416 // Only allow based lvalue casts if they are lossless. 13417 // FIXME: Allow a larger integer size than the pointer size, and allow 13418 // narrowing back down to pointer width in subsequent integral casts. 13419 // FIXME: Check integer type's active bits, not its type size. 13420 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13421 return Error(E); 13422 13423 LV.Designator.setInvalid(); 13424 LV.moveInto(Result); 13425 return true; 13426 } 13427 13428 APSInt AsInt; 13429 APValue V; 13430 LV.moveInto(V); 13431 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13432 llvm_unreachable("Can't cast this!"); 13433 13434 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13435 } 13436 13437 case CK_IntegralComplexToReal: { 13438 ComplexValue C; 13439 if (!EvaluateComplex(SubExpr, C, Info)) 13440 return false; 13441 return Success(C.getComplexIntReal(), E); 13442 } 13443 13444 case CK_FloatingToIntegral: { 13445 APFloat F(0.0); 13446 if (!EvaluateFloat(SubExpr, F, Info)) 13447 return false; 13448 13449 APSInt Value; 13450 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13451 return false; 13452 return Success(Value, E); 13453 } 13454 } 13455 13456 llvm_unreachable("unknown cast resulting in integral value"); 13457 } 13458 13459 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13460 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13461 ComplexValue LV; 13462 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13463 return false; 13464 if (!LV.isComplexInt()) 13465 return Error(E); 13466 return Success(LV.getComplexIntReal(), E); 13467 } 13468 13469 return Visit(E->getSubExpr()); 13470 } 13471 13472 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13473 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13474 ComplexValue LV; 13475 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13476 return false; 13477 if (!LV.isComplexInt()) 13478 return Error(E); 13479 return Success(LV.getComplexIntImag(), E); 13480 } 13481 13482 VisitIgnoredValue(E->getSubExpr()); 13483 return Success(0, E); 13484 } 13485 13486 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13487 return Success(E->getPackLength(), E); 13488 } 13489 13490 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13491 return Success(E->getValue(), E); 13492 } 13493 13494 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13495 const ConceptSpecializationExpr *E) { 13496 return Success(E->isSatisfied(), E); 13497 } 13498 13499 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13500 return Success(E->isSatisfied(), E); 13501 } 13502 13503 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13504 switch (E->getOpcode()) { 13505 default: 13506 // Invalid unary operators 13507 return Error(E); 13508 case UO_Plus: 13509 // The result is just the value. 13510 return Visit(E->getSubExpr()); 13511 case UO_Minus: { 13512 if (!Visit(E->getSubExpr())) return false; 13513 if (!Result.isFixedPoint()) 13514 return Error(E); 13515 bool Overflowed; 13516 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13517 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13518 return false; 13519 return Success(Negated, E); 13520 } 13521 case UO_LNot: { 13522 bool bres; 13523 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13524 return false; 13525 return Success(!bres, E); 13526 } 13527 } 13528 } 13529 13530 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13531 const Expr *SubExpr = E->getSubExpr(); 13532 QualType DestType = E->getType(); 13533 assert(DestType->isFixedPointType() && 13534 "Expected destination type to be a fixed point type"); 13535 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13536 13537 switch (E->getCastKind()) { 13538 case CK_FixedPointCast: { 13539 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13540 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13541 return false; 13542 bool Overflowed; 13543 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13544 if (Overflowed) { 13545 if (Info.checkingForUndefinedBehavior()) 13546 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13547 diag::warn_fixedpoint_constant_overflow) 13548 << Result.toString() << E->getType(); 13549 if (!HandleOverflow(Info, E, Result, E->getType())) 13550 return false; 13551 } 13552 return Success(Result, E); 13553 } 13554 case CK_IntegralToFixedPoint: { 13555 APSInt Src; 13556 if (!EvaluateInteger(SubExpr, Src, Info)) 13557 return false; 13558 13559 bool Overflowed; 13560 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13561 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13562 13563 if (Overflowed) { 13564 if (Info.checkingForUndefinedBehavior()) 13565 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13566 diag::warn_fixedpoint_constant_overflow) 13567 << IntResult.toString() << E->getType(); 13568 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13569 return false; 13570 } 13571 13572 return Success(IntResult, E); 13573 } 13574 case CK_FloatingToFixedPoint: { 13575 APFloat Src(0.0); 13576 if (!EvaluateFloat(SubExpr, Src, Info)) 13577 return false; 13578 13579 bool Overflowed; 13580 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13581 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13582 13583 if (Overflowed) { 13584 if (Info.checkingForUndefinedBehavior()) 13585 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13586 diag::warn_fixedpoint_constant_overflow) 13587 << Result.toString() << E->getType(); 13588 if (!HandleOverflow(Info, E, Result, E->getType())) 13589 return false; 13590 } 13591 13592 return Success(Result, E); 13593 } 13594 case CK_NoOp: 13595 case CK_LValueToRValue: 13596 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13597 default: 13598 return Error(E); 13599 } 13600 } 13601 13602 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13603 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13604 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13605 13606 const Expr *LHS = E->getLHS(); 13607 const Expr *RHS = E->getRHS(); 13608 FixedPointSemantics ResultFXSema = 13609 Info.Ctx.getFixedPointSemantics(E->getType()); 13610 13611 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13612 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13613 return false; 13614 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13615 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13616 return false; 13617 13618 bool OpOverflow = false, ConversionOverflow = false; 13619 APFixedPoint Result(LHSFX.getSemantics()); 13620 switch (E->getOpcode()) { 13621 case BO_Add: { 13622 Result = LHSFX.add(RHSFX, &OpOverflow) 13623 .convert(ResultFXSema, &ConversionOverflow); 13624 break; 13625 } 13626 case BO_Sub: { 13627 Result = LHSFX.sub(RHSFX, &OpOverflow) 13628 .convert(ResultFXSema, &ConversionOverflow); 13629 break; 13630 } 13631 case BO_Mul: { 13632 Result = LHSFX.mul(RHSFX, &OpOverflow) 13633 .convert(ResultFXSema, &ConversionOverflow); 13634 break; 13635 } 13636 case BO_Div: { 13637 if (RHSFX.getValue() == 0) { 13638 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13639 return false; 13640 } 13641 Result = LHSFX.div(RHSFX, &OpOverflow) 13642 .convert(ResultFXSema, &ConversionOverflow); 13643 break; 13644 } 13645 case BO_Shl: 13646 case BO_Shr: { 13647 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13648 llvm::APSInt RHSVal = RHSFX.getValue(); 13649 13650 unsigned ShiftBW = 13651 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13652 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13653 // Embedded-C 4.1.6.2.2: 13654 // The right operand must be nonnegative and less than the total number 13655 // of (nonpadding) bits of the fixed-point operand ... 13656 if (RHSVal.isNegative()) 13657 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13658 else if (Amt != RHSVal) 13659 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13660 << RHSVal << E->getType() << ShiftBW; 13661 13662 if (E->getOpcode() == BO_Shl) 13663 Result = LHSFX.shl(Amt, &OpOverflow); 13664 else 13665 Result = LHSFX.shr(Amt, &OpOverflow); 13666 break; 13667 } 13668 default: 13669 return false; 13670 } 13671 if (OpOverflow || ConversionOverflow) { 13672 if (Info.checkingForUndefinedBehavior()) 13673 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13674 diag::warn_fixedpoint_constant_overflow) 13675 << Result.toString() << E->getType(); 13676 if (!HandleOverflow(Info, E, Result, E->getType())) 13677 return false; 13678 } 13679 return Success(Result, E); 13680 } 13681 13682 //===----------------------------------------------------------------------===// 13683 // Float Evaluation 13684 //===----------------------------------------------------------------------===// 13685 13686 namespace { 13687 class FloatExprEvaluator 13688 : public ExprEvaluatorBase<FloatExprEvaluator> { 13689 APFloat &Result; 13690 public: 13691 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13692 : ExprEvaluatorBaseTy(info), Result(result) {} 13693 13694 bool Success(const APValue &V, const Expr *e) { 13695 Result = V.getFloat(); 13696 return true; 13697 } 13698 13699 bool ZeroInitialization(const Expr *E) { 13700 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13701 return true; 13702 } 13703 13704 bool VisitCallExpr(const CallExpr *E); 13705 13706 bool VisitUnaryOperator(const UnaryOperator *E); 13707 bool VisitBinaryOperator(const BinaryOperator *E); 13708 bool VisitFloatingLiteral(const FloatingLiteral *E); 13709 bool VisitCastExpr(const CastExpr *E); 13710 13711 bool VisitUnaryReal(const UnaryOperator *E); 13712 bool VisitUnaryImag(const UnaryOperator *E); 13713 13714 // FIXME: Missing: array subscript of vector, member of vector 13715 }; 13716 } // end anonymous namespace 13717 13718 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13719 assert(!E->isValueDependent()); 13720 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 13721 return FloatExprEvaluator(Info, Result).Visit(E); 13722 } 13723 13724 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13725 QualType ResultTy, 13726 const Expr *Arg, 13727 bool SNaN, 13728 llvm::APFloat &Result) { 13729 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13730 if (!S) return false; 13731 13732 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13733 13734 llvm::APInt fill; 13735 13736 // Treat empty strings as if they were zero. 13737 if (S->getString().empty()) 13738 fill = llvm::APInt(32, 0); 13739 else if (S->getString().getAsInteger(0, fill)) 13740 return false; 13741 13742 if (Context.getTargetInfo().isNan2008()) { 13743 if (SNaN) 13744 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13745 else 13746 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13747 } else { 13748 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13749 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13750 // a different encoding to what became a standard in 2008, and for pre- 13751 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13752 // sNaN. This is now known as "legacy NaN" encoding. 13753 if (SNaN) 13754 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13755 else 13756 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13757 } 13758 13759 return true; 13760 } 13761 13762 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13763 switch (E->getBuiltinCallee()) { 13764 default: 13765 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13766 13767 case Builtin::BI__builtin_huge_val: 13768 case Builtin::BI__builtin_huge_valf: 13769 case Builtin::BI__builtin_huge_vall: 13770 case Builtin::BI__builtin_huge_valf128: 13771 case Builtin::BI__builtin_inf: 13772 case Builtin::BI__builtin_inff: 13773 case Builtin::BI__builtin_infl: 13774 case Builtin::BI__builtin_inff128: { 13775 const llvm::fltSemantics &Sem = 13776 Info.Ctx.getFloatTypeSemantics(E->getType()); 13777 Result = llvm::APFloat::getInf(Sem); 13778 return true; 13779 } 13780 13781 case Builtin::BI__builtin_nans: 13782 case Builtin::BI__builtin_nansf: 13783 case Builtin::BI__builtin_nansl: 13784 case Builtin::BI__builtin_nansf128: 13785 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13786 true, Result)) 13787 return Error(E); 13788 return true; 13789 13790 case Builtin::BI__builtin_nan: 13791 case Builtin::BI__builtin_nanf: 13792 case Builtin::BI__builtin_nanl: 13793 case Builtin::BI__builtin_nanf128: 13794 // If this is __builtin_nan() turn this into a nan, otherwise we 13795 // can't constant fold it. 13796 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13797 false, Result)) 13798 return Error(E); 13799 return true; 13800 13801 case Builtin::BI__builtin_fabs: 13802 case Builtin::BI__builtin_fabsf: 13803 case Builtin::BI__builtin_fabsl: 13804 case Builtin::BI__builtin_fabsf128: 13805 // The C standard says "fabs raises no floating-point exceptions, 13806 // even if x is a signaling NaN. The returned value is independent of 13807 // the current rounding direction mode." Therefore constant folding can 13808 // proceed without regard to the floating point settings. 13809 // Reference, WG14 N2478 F.10.4.3 13810 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13811 return false; 13812 13813 if (Result.isNegative()) 13814 Result.changeSign(); 13815 return true; 13816 13817 case Builtin::BI__arithmetic_fence: 13818 return EvaluateFloat(E->getArg(0), Result, Info); 13819 13820 // FIXME: Builtin::BI__builtin_powi 13821 // FIXME: Builtin::BI__builtin_powif 13822 // FIXME: Builtin::BI__builtin_powil 13823 13824 case Builtin::BI__builtin_copysign: 13825 case Builtin::BI__builtin_copysignf: 13826 case Builtin::BI__builtin_copysignl: 13827 case Builtin::BI__builtin_copysignf128: { 13828 APFloat RHS(0.); 13829 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13830 !EvaluateFloat(E->getArg(1), RHS, Info)) 13831 return false; 13832 Result.copySign(RHS); 13833 return true; 13834 } 13835 } 13836 } 13837 13838 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13839 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13840 ComplexValue CV; 13841 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13842 return false; 13843 Result = CV.FloatReal; 13844 return true; 13845 } 13846 13847 return Visit(E->getSubExpr()); 13848 } 13849 13850 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13851 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13852 ComplexValue CV; 13853 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13854 return false; 13855 Result = CV.FloatImag; 13856 return true; 13857 } 13858 13859 VisitIgnoredValue(E->getSubExpr()); 13860 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13861 Result = llvm::APFloat::getZero(Sem); 13862 return true; 13863 } 13864 13865 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13866 switch (E->getOpcode()) { 13867 default: return Error(E); 13868 case UO_Plus: 13869 return EvaluateFloat(E->getSubExpr(), Result, Info); 13870 case UO_Minus: 13871 // In C standard, WG14 N2478 F.3 p4 13872 // "the unary - raises no floating point exceptions, 13873 // even if the operand is signalling." 13874 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13875 return false; 13876 Result.changeSign(); 13877 return true; 13878 } 13879 } 13880 13881 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13882 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13883 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13884 13885 APFloat RHS(0.0); 13886 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13887 if (!LHSOK && !Info.noteFailure()) 13888 return false; 13889 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13890 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13891 } 13892 13893 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13894 Result = E->getValue(); 13895 return true; 13896 } 13897 13898 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13899 const Expr* SubExpr = E->getSubExpr(); 13900 13901 switch (E->getCastKind()) { 13902 default: 13903 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13904 13905 case CK_IntegralToFloating: { 13906 APSInt IntResult; 13907 const FPOptions FPO = E->getFPFeaturesInEffect( 13908 Info.Ctx.getLangOpts()); 13909 return EvaluateInteger(SubExpr, IntResult, Info) && 13910 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13911 IntResult, E->getType(), Result); 13912 } 13913 13914 case CK_FixedPointToFloating: { 13915 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13916 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13917 return false; 13918 Result = 13919 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13920 return true; 13921 } 13922 13923 case CK_FloatingCast: { 13924 if (!Visit(SubExpr)) 13925 return false; 13926 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13927 Result); 13928 } 13929 13930 case CK_FloatingComplexToReal: { 13931 ComplexValue V; 13932 if (!EvaluateComplex(SubExpr, V, Info)) 13933 return false; 13934 Result = V.getComplexFloatReal(); 13935 return true; 13936 } 13937 } 13938 } 13939 13940 //===----------------------------------------------------------------------===// 13941 // Complex Evaluation (for float and integer) 13942 //===----------------------------------------------------------------------===// 13943 13944 namespace { 13945 class ComplexExprEvaluator 13946 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13947 ComplexValue &Result; 13948 13949 public: 13950 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13951 : ExprEvaluatorBaseTy(info), Result(Result) {} 13952 13953 bool Success(const APValue &V, const Expr *e) { 13954 Result.setFrom(V); 13955 return true; 13956 } 13957 13958 bool ZeroInitialization(const Expr *E); 13959 13960 //===--------------------------------------------------------------------===// 13961 // Visitor Methods 13962 //===--------------------------------------------------------------------===// 13963 13964 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13965 bool VisitCastExpr(const CastExpr *E); 13966 bool VisitBinaryOperator(const BinaryOperator *E); 13967 bool VisitUnaryOperator(const UnaryOperator *E); 13968 bool VisitInitListExpr(const InitListExpr *E); 13969 bool VisitCallExpr(const CallExpr *E); 13970 }; 13971 } // end anonymous namespace 13972 13973 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13974 EvalInfo &Info) { 13975 assert(!E->isValueDependent()); 13976 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 13977 return ComplexExprEvaluator(Info, Result).Visit(E); 13978 } 13979 13980 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13981 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13982 if (ElemTy->isRealFloatingType()) { 13983 Result.makeComplexFloat(); 13984 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13985 Result.FloatReal = Zero; 13986 Result.FloatImag = Zero; 13987 } else { 13988 Result.makeComplexInt(); 13989 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13990 Result.IntReal = Zero; 13991 Result.IntImag = Zero; 13992 } 13993 return true; 13994 } 13995 13996 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13997 const Expr* SubExpr = E->getSubExpr(); 13998 13999 if (SubExpr->getType()->isRealFloatingType()) { 14000 Result.makeComplexFloat(); 14001 APFloat &Imag = Result.FloatImag; 14002 if (!EvaluateFloat(SubExpr, Imag, Info)) 14003 return false; 14004 14005 Result.FloatReal = APFloat(Imag.getSemantics()); 14006 return true; 14007 } else { 14008 assert(SubExpr->getType()->isIntegerType() && 14009 "Unexpected imaginary literal."); 14010 14011 Result.makeComplexInt(); 14012 APSInt &Imag = Result.IntImag; 14013 if (!EvaluateInteger(SubExpr, Imag, Info)) 14014 return false; 14015 14016 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 14017 return true; 14018 } 14019 } 14020 14021 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 14022 14023 switch (E->getCastKind()) { 14024 case CK_BitCast: 14025 case CK_BaseToDerived: 14026 case CK_DerivedToBase: 14027 case CK_UncheckedDerivedToBase: 14028 case CK_Dynamic: 14029 case CK_ToUnion: 14030 case CK_ArrayToPointerDecay: 14031 case CK_FunctionToPointerDecay: 14032 case CK_NullToPointer: 14033 case CK_NullToMemberPointer: 14034 case CK_BaseToDerivedMemberPointer: 14035 case CK_DerivedToBaseMemberPointer: 14036 case CK_MemberPointerToBoolean: 14037 case CK_ReinterpretMemberPointer: 14038 case CK_ConstructorConversion: 14039 case CK_IntegralToPointer: 14040 case CK_PointerToIntegral: 14041 case CK_PointerToBoolean: 14042 case CK_ToVoid: 14043 case CK_VectorSplat: 14044 case CK_IntegralCast: 14045 case CK_BooleanToSignedIntegral: 14046 case CK_IntegralToBoolean: 14047 case CK_IntegralToFloating: 14048 case CK_FloatingToIntegral: 14049 case CK_FloatingToBoolean: 14050 case CK_FloatingCast: 14051 case CK_CPointerToObjCPointerCast: 14052 case CK_BlockPointerToObjCPointerCast: 14053 case CK_AnyPointerToBlockPointerCast: 14054 case CK_ObjCObjectLValueCast: 14055 case CK_FloatingComplexToReal: 14056 case CK_FloatingComplexToBoolean: 14057 case CK_IntegralComplexToReal: 14058 case CK_IntegralComplexToBoolean: 14059 case CK_ARCProduceObject: 14060 case CK_ARCConsumeObject: 14061 case CK_ARCReclaimReturnedObject: 14062 case CK_ARCExtendBlockObject: 14063 case CK_CopyAndAutoreleaseBlockObject: 14064 case CK_BuiltinFnToFnPtr: 14065 case CK_ZeroToOCLOpaqueType: 14066 case CK_NonAtomicToAtomic: 14067 case CK_AddressSpaceConversion: 14068 case CK_IntToOCLSampler: 14069 case CK_FloatingToFixedPoint: 14070 case CK_FixedPointToFloating: 14071 case CK_FixedPointCast: 14072 case CK_FixedPointToBoolean: 14073 case CK_FixedPointToIntegral: 14074 case CK_IntegralToFixedPoint: 14075 case CK_MatrixCast: 14076 llvm_unreachable("invalid cast kind for complex value"); 14077 14078 case CK_LValueToRValue: 14079 case CK_AtomicToNonAtomic: 14080 case CK_NoOp: 14081 case CK_LValueToRValueBitCast: 14082 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14083 14084 case CK_Dependent: 14085 case CK_LValueBitCast: 14086 case CK_UserDefinedConversion: 14087 return Error(E); 14088 14089 case CK_FloatingRealToComplex: { 14090 APFloat &Real = Result.FloatReal; 14091 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 14092 return false; 14093 14094 Result.makeComplexFloat(); 14095 Result.FloatImag = APFloat(Real.getSemantics()); 14096 return true; 14097 } 14098 14099 case CK_FloatingComplexCast: { 14100 if (!Visit(E->getSubExpr())) 14101 return false; 14102 14103 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14104 QualType From 14105 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14106 14107 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 14108 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 14109 } 14110 14111 case CK_FloatingComplexToIntegralComplex: { 14112 if (!Visit(E->getSubExpr())) 14113 return false; 14114 14115 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14116 QualType From 14117 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14118 Result.makeComplexInt(); 14119 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 14120 To, Result.IntReal) && 14121 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 14122 To, Result.IntImag); 14123 } 14124 14125 case CK_IntegralRealToComplex: { 14126 APSInt &Real = Result.IntReal; 14127 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14128 return false; 14129 14130 Result.makeComplexInt(); 14131 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14132 return true; 14133 } 14134 14135 case CK_IntegralComplexCast: { 14136 if (!Visit(E->getSubExpr())) 14137 return false; 14138 14139 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14140 QualType From 14141 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14142 14143 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14144 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14145 return true; 14146 } 14147 14148 case CK_IntegralComplexToFloatingComplex: { 14149 if (!Visit(E->getSubExpr())) 14150 return false; 14151 14152 const FPOptions FPO = E->getFPFeaturesInEffect( 14153 Info.Ctx.getLangOpts()); 14154 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14155 QualType From 14156 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14157 Result.makeComplexFloat(); 14158 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14159 To, Result.FloatReal) && 14160 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14161 To, Result.FloatImag); 14162 } 14163 } 14164 14165 llvm_unreachable("unknown cast resulting in complex value"); 14166 } 14167 14168 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14169 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14170 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14171 14172 // Track whether the LHS or RHS is real at the type system level. When this is 14173 // the case we can simplify our evaluation strategy. 14174 bool LHSReal = false, RHSReal = false; 14175 14176 bool LHSOK; 14177 if (E->getLHS()->getType()->isRealFloatingType()) { 14178 LHSReal = true; 14179 APFloat &Real = Result.FloatReal; 14180 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14181 if (LHSOK) { 14182 Result.makeComplexFloat(); 14183 Result.FloatImag = APFloat(Real.getSemantics()); 14184 } 14185 } else { 14186 LHSOK = Visit(E->getLHS()); 14187 } 14188 if (!LHSOK && !Info.noteFailure()) 14189 return false; 14190 14191 ComplexValue RHS; 14192 if (E->getRHS()->getType()->isRealFloatingType()) { 14193 RHSReal = true; 14194 APFloat &Real = RHS.FloatReal; 14195 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14196 return false; 14197 RHS.makeComplexFloat(); 14198 RHS.FloatImag = APFloat(Real.getSemantics()); 14199 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14200 return false; 14201 14202 assert(!(LHSReal && RHSReal) && 14203 "Cannot have both operands of a complex operation be real."); 14204 switch (E->getOpcode()) { 14205 default: return Error(E); 14206 case BO_Add: 14207 if (Result.isComplexFloat()) { 14208 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14209 APFloat::rmNearestTiesToEven); 14210 if (LHSReal) 14211 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14212 else if (!RHSReal) 14213 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14214 APFloat::rmNearestTiesToEven); 14215 } else { 14216 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14217 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14218 } 14219 break; 14220 case BO_Sub: 14221 if (Result.isComplexFloat()) { 14222 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14223 APFloat::rmNearestTiesToEven); 14224 if (LHSReal) { 14225 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14226 Result.getComplexFloatImag().changeSign(); 14227 } else if (!RHSReal) { 14228 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14229 APFloat::rmNearestTiesToEven); 14230 } 14231 } else { 14232 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14233 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14234 } 14235 break; 14236 case BO_Mul: 14237 if (Result.isComplexFloat()) { 14238 // This is an implementation of complex multiplication according to the 14239 // constraints laid out in C11 Annex G. The implementation uses the 14240 // following naming scheme: 14241 // (a + ib) * (c + id) 14242 ComplexValue LHS = Result; 14243 APFloat &A = LHS.getComplexFloatReal(); 14244 APFloat &B = LHS.getComplexFloatImag(); 14245 APFloat &C = RHS.getComplexFloatReal(); 14246 APFloat &D = RHS.getComplexFloatImag(); 14247 APFloat &ResR = Result.getComplexFloatReal(); 14248 APFloat &ResI = Result.getComplexFloatImag(); 14249 if (LHSReal) { 14250 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14251 ResR = A * C; 14252 ResI = A * D; 14253 } else if (RHSReal) { 14254 ResR = C * A; 14255 ResI = C * B; 14256 } else { 14257 // In the fully general case, we need to handle NaNs and infinities 14258 // robustly. 14259 APFloat AC = A * C; 14260 APFloat BD = B * D; 14261 APFloat AD = A * D; 14262 APFloat BC = B * C; 14263 ResR = AC - BD; 14264 ResI = AD + BC; 14265 if (ResR.isNaN() && ResI.isNaN()) { 14266 bool Recalc = false; 14267 if (A.isInfinity() || B.isInfinity()) { 14268 A = APFloat::copySign( 14269 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14270 B = APFloat::copySign( 14271 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14272 if (C.isNaN()) 14273 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14274 if (D.isNaN()) 14275 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14276 Recalc = true; 14277 } 14278 if (C.isInfinity() || D.isInfinity()) { 14279 C = APFloat::copySign( 14280 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14281 D = APFloat::copySign( 14282 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14283 if (A.isNaN()) 14284 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14285 if (B.isNaN()) 14286 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14287 Recalc = true; 14288 } 14289 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14290 AD.isInfinity() || BC.isInfinity())) { 14291 if (A.isNaN()) 14292 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14293 if (B.isNaN()) 14294 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14295 if (C.isNaN()) 14296 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14297 if (D.isNaN()) 14298 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14299 Recalc = true; 14300 } 14301 if (Recalc) { 14302 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14303 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14304 } 14305 } 14306 } 14307 } else { 14308 ComplexValue LHS = Result; 14309 Result.getComplexIntReal() = 14310 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14311 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14312 Result.getComplexIntImag() = 14313 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14314 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14315 } 14316 break; 14317 case BO_Div: 14318 if (Result.isComplexFloat()) { 14319 // This is an implementation of complex division according to the 14320 // constraints laid out in C11 Annex G. The implementation uses the 14321 // following naming scheme: 14322 // (a + ib) / (c + id) 14323 ComplexValue LHS = Result; 14324 APFloat &A = LHS.getComplexFloatReal(); 14325 APFloat &B = LHS.getComplexFloatImag(); 14326 APFloat &C = RHS.getComplexFloatReal(); 14327 APFloat &D = RHS.getComplexFloatImag(); 14328 APFloat &ResR = Result.getComplexFloatReal(); 14329 APFloat &ResI = Result.getComplexFloatImag(); 14330 if (RHSReal) { 14331 ResR = A / C; 14332 ResI = B / C; 14333 } else { 14334 if (LHSReal) { 14335 // No real optimizations we can do here, stub out with zero. 14336 B = APFloat::getZero(A.getSemantics()); 14337 } 14338 int DenomLogB = 0; 14339 APFloat MaxCD = maxnum(abs(C), abs(D)); 14340 if (MaxCD.isFinite()) { 14341 DenomLogB = ilogb(MaxCD); 14342 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14343 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14344 } 14345 APFloat Denom = C * C + D * D; 14346 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14347 APFloat::rmNearestTiesToEven); 14348 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14349 APFloat::rmNearestTiesToEven); 14350 if (ResR.isNaN() && ResI.isNaN()) { 14351 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14352 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14353 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14354 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14355 D.isFinite()) { 14356 A = APFloat::copySign( 14357 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14358 B = APFloat::copySign( 14359 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14360 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14361 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14362 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14363 C = APFloat::copySign( 14364 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14365 D = APFloat::copySign( 14366 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14367 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14368 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14369 } 14370 } 14371 } 14372 } else { 14373 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14374 return Error(E, diag::note_expr_divide_by_zero); 14375 14376 ComplexValue LHS = Result; 14377 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14378 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14379 Result.getComplexIntReal() = 14380 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14381 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14382 Result.getComplexIntImag() = 14383 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14384 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14385 } 14386 break; 14387 } 14388 14389 return true; 14390 } 14391 14392 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14393 // Get the operand value into 'Result'. 14394 if (!Visit(E->getSubExpr())) 14395 return false; 14396 14397 switch (E->getOpcode()) { 14398 default: 14399 return Error(E); 14400 case UO_Extension: 14401 return true; 14402 case UO_Plus: 14403 // The result is always just the subexpr. 14404 return true; 14405 case UO_Minus: 14406 if (Result.isComplexFloat()) { 14407 Result.getComplexFloatReal().changeSign(); 14408 Result.getComplexFloatImag().changeSign(); 14409 } 14410 else { 14411 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14412 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14413 } 14414 return true; 14415 case UO_Not: 14416 if (Result.isComplexFloat()) 14417 Result.getComplexFloatImag().changeSign(); 14418 else 14419 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14420 return true; 14421 } 14422 } 14423 14424 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14425 if (E->getNumInits() == 2) { 14426 if (E->getType()->isComplexType()) { 14427 Result.makeComplexFloat(); 14428 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14429 return false; 14430 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14431 return false; 14432 } else { 14433 Result.makeComplexInt(); 14434 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14435 return false; 14436 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14437 return false; 14438 } 14439 return true; 14440 } 14441 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14442 } 14443 14444 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14445 switch (E->getBuiltinCallee()) { 14446 case Builtin::BI__builtin_complex: 14447 Result.makeComplexFloat(); 14448 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14449 return false; 14450 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14451 return false; 14452 return true; 14453 14454 default: 14455 break; 14456 } 14457 14458 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14459 } 14460 14461 //===----------------------------------------------------------------------===// 14462 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14463 // implicit conversion. 14464 //===----------------------------------------------------------------------===// 14465 14466 namespace { 14467 class AtomicExprEvaluator : 14468 public ExprEvaluatorBase<AtomicExprEvaluator> { 14469 const LValue *This; 14470 APValue &Result; 14471 public: 14472 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14473 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14474 14475 bool Success(const APValue &V, const Expr *E) { 14476 Result = V; 14477 return true; 14478 } 14479 14480 bool ZeroInitialization(const Expr *E) { 14481 ImplicitValueInitExpr VIE( 14482 E->getType()->castAs<AtomicType>()->getValueType()); 14483 // For atomic-qualified class (and array) types in C++, initialize the 14484 // _Atomic-wrapped subobject directly, in-place. 14485 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14486 : Evaluate(Result, Info, &VIE); 14487 } 14488 14489 bool VisitCastExpr(const CastExpr *E) { 14490 switch (E->getCastKind()) { 14491 default: 14492 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14493 case CK_NonAtomicToAtomic: 14494 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14495 : Evaluate(Result, Info, E->getSubExpr()); 14496 } 14497 } 14498 }; 14499 } // end anonymous namespace 14500 14501 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14502 EvalInfo &Info) { 14503 assert(!E->isValueDependent()); 14504 assert(E->isPRValue() && E->getType()->isAtomicType()); 14505 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14506 } 14507 14508 //===----------------------------------------------------------------------===// 14509 // Void expression evaluation, primarily for a cast to void on the LHS of a 14510 // comma operator 14511 //===----------------------------------------------------------------------===// 14512 14513 namespace { 14514 class VoidExprEvaluator 14515 : public ExprEvaluatorBase<VoidExprEvaluator> { 14516 public: 14517 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14518 14519 bool Success(const APValue &V, const Expr *e) { return true; } 14520 14521 bool ZeroInitialization(const Expr *E) { return true; } 14522 14523 bool VisitCastExpr(const CastExpr *E) { 14524 switch (E->getCastKind()) { 14525 default: 14526 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14527 case CK_ToVoid: 14528 VisitIgnoredValue(E->getSubExpr()); 14529 return true; 14530 } 14531 } 14532 14533 bool VisitCallExpr(const CallExpr *E) { 14534 switch (E->getBuiltinCallee()) { 14535 case Builtin::BI__assume: 14536 case Builtin::BI__builtin_assume: 14537 // The argument is not evaluated! 14538 return true; 14539 14540 case Builtin::BI__builtin_operator_delete: 14541 return HandleOperatorDeleteCall(Info, E); 14542 14543 default: 14544 break; 14545 } 14546 14547 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14548 } 14549 14550 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14551 }; 14552 } // end anonymous namespace 14553 14554 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14555 // We cannot speculatively evaluate a delete expression. 14556 if (Info.SpeculativeEvaluationDepth) 14557 return false; 14558 14559 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14560 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14561 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14562 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14563 return false; 14564 } 14565 14566 const Expr *Arg = E->getArgument(); 14567 14568 LValue Pointer; 14569 if (!EvaluatePointer(Arg, Pointer, Info)) 14570 return false; 14571 if (Pointer.Designator.Invalid) 14572 return false; 14573 14574 // Deleting a null pointer has no effect. 14575 if (Pointer.isNullPointer()) { 14576 // This is the only case where we need to produce an extension warning: 14577 // the only other way we can succeed is if we find a dynamic allocation, 14578 // and we will have warned when we allocated it in that case. 14579 if (!Info.getLangOpts().CPlusPlus20) 14580 Info.CCEDiag(E, diag::note_constexpr_new); 14581 return true; 14582 } 14583 14584 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14585 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14586 if (!Alloc) 14587 return false; 14588 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14589 14590 // For the non-array case, the designator must be empty if the static type 14591 // does not have a virtual destructor. 14592 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14593 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14594 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14595 << Arg->getType()->getPointeeType() << AllocType; 14596 return false; 14597 } 14598 14599 // For a class type with a virtual destructor, the selected operator delete 14600 // is the one looked up when building the destructor. 14601 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14602 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14603 if (VirtualDelete && 14604 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14605 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14606 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14607 return false; 14608 } 14609 } 14610 14611 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14612 (*Alloc)->Value, AllocType)) 14613 return false; 14614 14615 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14616 // The element was already erased. This means the destructor call also 14617 // deleted the object. 14618 // FIXME: This probably results in undefined behavior before we get this 14619 // far, and should be diagnosed elsewhere first. 14620 Info.FFDiag(E, diag::note_constexpr_double_delete); 14621 return false; 14622 } 14623 14624 return true; 14625 } 14626 14627 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14628 assert(!E->isValueDependent()); 14629 assert(E->isPRValue() && E->getType()->isVoidType()); 14630 return VoidExprEvaluator(Info).Visit(E); 14631 } 14632 14633 //===----------------------------------------------------------------------===// 14634 // Top level Expr::EvaluateAsRValue method. 14635 //===----------------------------------------------------------------------===// 14636 14637 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14638 assert(!E->isValueDependent()); 14639 // In C, function designators are not lvalues, but we evaluate them as if they 14640 // are. 14641 QualType T = E->getType(); 14642 if (E->isGLValue() || T->isFunctionType()) { 14643 LValue LV; 14644 if (!EvaluateLValue(E, LV, Info)) 14645 return false; 14646 LV.moveInto(Result); 14647 } else if (T->isVectorType()) { 14648 if (!EvaluateVector(E, Result, Info)) 14649 return false; 14650 } else if (T->isIntegralOrEnumerationType()) { 14651 if (!IntExprEvaluator(Info, Result).Visit(E)) 14652 return false; 14653 } else if (T->hasPointerRepresentation()) { 14654 LValue LV; 14655 if (!EvaluatePointer(E, LV, Info)) 14656 return false; 14657 LV.moveInto(Result); 14658 } else if (T->isRealFloatingType()) { 14659 llvm::APFloat F(0.0); 14660 if (!EvaluateFloat(E, F, Info)) 14661 return false; 14662 Result = APValue(F); 14663 } else if (T->isAnyComplexType()) { 14664 ComplexValue C; 14665 if (!EvaluateComplex(E, C, Info)) 14666 return false; 14667 C.moveInto(Result); 14668 } else if (T->isFixedPointType()) { 14669 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14670 } else if (T->isMemberPointerType()) { 14671 MemberPtr P; 14672 if (!EvaluateMemberPointer(E, P, Info)) 14673 return false; 14674 P.moveInto(Result); 14675 return true; 14676 } else if (T->isArrayType()) { 14677 LValue LV; 14678 APValue &Value = 14679 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14680 if (!EvaluateArray(E, LV, Value, Info)) 14681 return false; 14682 Result = Value; 14683 } else if (T->isRecordType()) { 14684 LValue LV; 14685 APValue &Value = 14686 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14687 if (!EvaluateRecord(E, LV, Value, Info)) 14688 return false; 14689 Result = Value; 14690 } else if (T->isVoidType()) { 14691 if (!Info.getLangOpts().CPlusPlus11) 14692 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14693 << E->getType(); 14694 if (!EvaluateVoid(E, Info)) 14695 return false; 14696 } else if (T->isAtomicType()) { 14697 QualType Unqual = T.getAtomicUnqualifiedType(); 14698 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14699 LValue LV; 14700 APValue &Value = Info.CurrentCall->createTemporary( 14701 E, Unqual, ScopeKind::FullExpression, LV); 14702 if (!EvaluateAtomic(E, &LV, Value, Info)) 14703 return false; 14704 } else { 14705 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14706 return false; 14707 } 14708 } else if (Info.getLangOpts().CPlusPlus11) { 14709 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14710 return false; 14711 } else { 14712 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14713 return false; 14714 } 14715 14716 return true; 14717 } 14718 14719 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14720 /// cases, the in-place evaluation is essential, since later initializers for 14721 /// an object can indirectly refer to subobjects which were initialized earlier. 14722 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14723 const Expr *E, bool AllowNonLiteralTypes) { 14724 assert(!E->isValueDependent()); 14725 14726 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14727 return false; 14728 14729 if (E->isPRValue()) { 14730 // Evaluate arrays and record types in-place, so that later initializers can 14731 // refer to earlier-initialized members of the object. 14732 QualType T = E->getType(); 14733 if (T->isArrayType()) 14734 return EvaluateArray(E, This, Result, Info); 14735 else if (T->isRecordType()) 14736 return EvaluateRecord(E, This, Result, Info); 14737 else if (T->isAtomicType()) { 14738 QualType Unqual = T.getAtomicUnqualifiedType(); 14739 if (Unqual->isArrayType() || Unqual->isRecordType()) 14740 return EvaluateAtomic(E, &This, Result, Info); 14741 } 14742 } 14743 14744 // For any other type, in-place evaluation is unimportant. 14745 return Evaluate(Result, Info, E); 14746 } 14747 14748 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14749 /// lvalue-to-rvalue cast if it is an lvalue. 14750 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14751 assert(!E->isValueDependent()); 14752 if (Info.EnableNewConstInterp) { 14753 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14754 return false; 14755 } else { 14756 if (E->getType().isNull()) 14757 return false; 14758 14759 if (!CheckLiteralType(Info, E)) 14760 return false; 14761 14762 if (!::Evaluate(Result, Info, E)) 14763 return false; 14764 14765 if (E->isGLValue()) { 14766 LValue LV; 14767 LV.setFrom(Info.Ctx, Result); 14768 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14769 return false; 14770 } 14771 } 14772 14773 // Check this core constant expression is a constant expression. 14774 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14775 ConstantExprKind::Normal) && 14776 CheckMemoryLeaks(Info); 14777 } 14778 14779 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14780 const ASTContext &Ctx, bool &IsConst) { 14781 // Fast-path evaluations of integer literals, since we sometimes see files 14782 // containing vast quantities of these. 14783 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14784 Result.Val = APValue(APSInt(L->getValue(), 14785 L->getType()->isUnsignedIntegerType())); 14786 IsConst = true; 14787 return true; 14788 } 14789 14790 // This case should be rare, but we need to check it before we check on 14791 // the type below. 14792 if (Exp->getType().isNull()) { 14793 IsConst = false; 14794 return true; 14795 } 14796 14797 // FIXME: Evaluating values of large array and record types can cause 14798 // performance problems. Only do so in C++11 for now. 14799 if (Exp->isPRValue() && 14800 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && 14801 !Ctx.getLangOpts().CPlusPlus11) { 14802 IsConst = false; 14803 return true; 14804 } 14805 return false; 14806 } 14807 14808 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14809 Expr::SideEffectsKind SEK) { 14810 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14811 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14812 } 14813 14814 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14815 const ASTContext &Ctx, EvalInfo &Info) { 14816 assert(!E->isValueDependent()); 14817 bool IsConst; 14818 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14819 return IsConst; 14820 14821 return EvaluateAsRValue(Info, E, Result.Val); 14822 } 14823 14824 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14825 const ASTContext &Ctx, 14826 Expr::SideEffectsKind AllowSideEffects, 14827 EvalInfo &Info) { 14828 assert(!E->isValueDependent()); 14829 if (!E->getType()->isIntegralOrEnumerationType()) 14830 return false; 14831 14832 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14833 !ExprResult.Val.isInt() || 14834 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14835 return false; 14836 14837 return true; 14838 } 14839 14840 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14841 const ASTContext &Ctx, 14842 Expr::SideEffectsKind AllowSideEffects, 14843 EvalInfo &Info) { 14844 assert(!E->isValueDependent()); 14845 if (!E->getType()->isFixedPointType()) 14846 return false; 14847 14848 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14849 return false; 14850 14851 if (!ExprResult.Val.isFixedPoint() || 14852 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14853 return false; 14854 14855 return true; 14856 } 14857 14858 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14859 /// any crazy technique (that has nothing to do with language standards) that 14860 /// we want to. If this function returns true, it returns the folded constant 14861 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14862 /// will be applied to the result. 14863 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14864 bool InConstantContext) const { 14865 assert(!isValueDependent() && 14866 "Expression evaluator can't be called on a dependent expression."); 14867 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14868 Info.InConstantContext = InConstantContext; 14869 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14870 } 14871 14872 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14873 bool InConstantContext) const { 14874 assert(!isValueDependent() && 14875 "Expression evaluator can't be called on a dependent expression."); 14876 EvalResult Scratch; 14877 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14878 HandleConversionToBool(Scratch.Val, Result); 14879 } 14880 14881 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14882 SideEffectsKind AllowSideEffects, 14883 bool InConstantContext) const { 14884 assert(!isValueDependent() && 14885 "Expression evaluator can't be called on a dependent expression."); 14886 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14887 Info.InConstantContext = InConstantContext; 14888 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14889 } 14890 14891 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14892 SideEffectsKind AllowSideEffects, 14893 bool InConstantContext) const { 14894 assert(!isValueDependent() && 14895 "Expression evaluator can't be called on a dependent expression."); 14896 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14897 Info.InConstantContext = InConstantContext; 14898 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14899 } 14900 14901 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14902 SideEffectsKind AllowSideEffects, 14903 bool InConstantContext) const { 14904 assert(!isValueDependent() && 14905 "Expression evaluator can't be called on a dependent expression."); 14906 14907 if (!getType()->isRealFloatingType()) 14908 return false; 14909 14910 EvalResult ExprResult; 14911 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14912 !ExprResult.Val.isFloat() || 14913 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14914 return false; 14915 14916 Result = ExprResult.Val.getFloat(); 14917 return true; 14918 } 14919 14920 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14921 bool InConstantContext) const { 14922 assert(!isValueDependent() && 14923 "Expression evaluator can't be called on a dependent expression."); 14924 14925 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14926 Info.InConstantContext = InConstantContext; 14927 LValue LV; 14928 CheckedTemporaries CheckedTemps; 14929 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14930 Result.HasSideEffects || 14931 !CheckLValueConstantExpression(Info, getExprLoc(), 14932 Ctx.getLValueReferenceType(getType()), LV, 14933 ConstantExprKind::Normal, CheckedTemps)) 14934 return false; 14935 14936 LV.moveInto(Result.Val); 14937 return true; 14938 } 14939 14940 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14941 APValue DestroyedValue, QualType Type, 14942 SourceLocation Loc, Expr::EvalStatus &EStatus, 14943 bool IsConstantDestruction) { 14944 EvalInfo Info(Ctx, EStatus, 14945 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14946 : EvalInfo::EM_ConstantFold); 14947 Info.setEvaluatingDecl(Base, DestroyedValue, 14948 EvalInfo::EvaluatingDeclKind::Dtor); 14949 Info.InConstantContext = IsConstantDestruction; 14950 14951 LValue LVal; 14952 LVal.set(Base); 14953 14954 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14955 EStatus.HasSideEffects) 14956 return false; 14957 14958 if (!Info.discardCleanups()) 14959 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14960 14961 return true; 14962 } 14963 14964 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14965 ConstantExprKind Kind) const { 14966 assert(!isValueDependent() && 14967 "Expression evaluator can't be called on a dependent expression."); 14968 14969 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14970 EvalInfo Info(Ctx, Result, EM); 14971 Info.InConstantContext = true; 14972 14973 // The type of the object we're initializing is 'const T' for a class NTTP. 14974 QualType T = getType(); 14975 if (Kind == ConstantExprKind::ClassTemplateArgument) 14976 T.addConst(); 14977 14978 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14979 // represent the result of the evaluation. CheckConstantExpression ensures 14980 // this doesn't escape. 14981 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14982 APValue::LValueBase Base(&BaseMTE); 14983 14984 Info.setEvaluatingDecl(Base, Result.Val); 14985 LValue LVal; 14986 LVal.set(Base); 14987 14988 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14989 return false; 14990 14991 if (!Info.discardCleanups()) 14992 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14993 14994 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14995 Result.Val, Kind)) 14996 return false; 14997 if (!CheckMemoryLeaks(Info)) 14998 return false; 14999 15000 // If this is a class template argument, it's required to have constant 15001 // destruction too. 15002 if (Kind == ConstantExprKind::ClassTemplateArgument && 15003 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 15004 true) || 15005 Result.HasSideEffects)) { 15006 // FIXME: Prefix a note to indicate that the problem is lack of constant 15007 // destruction. 15008 return false; 15009 } 15010 15011 return true; 15012 } 15013 15014 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 15015 const VarDecl *VD, 15016 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15017 assert(!isValueDependent() && 15018 "Expression evaluator can't be called on a dependent expression."); 15019 15020 // FIXME: Evaluating initializers for large array and record types can cause 15021 // performance problems. Only do so in C++11 for now. 15022 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 15023 !Ctx.getLangOpts().CPlusPlus11) 15024 return false; 15025 15026 Expr::EvalStatus EStatus; 15027 EStatus.Diag = &Notes; 15028 15029 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 15030 ? EvalInfo::EM_ConstantExpression 15031 : EvalInfo::EM_ConstantFold); 15032 Info.setEvaluatingDecl(VD, Value); 15033 Info.InConstantContext = true; 15034 15035 SourceLocation DeclLoc = VD->getLocation(); 15036 QualType DeclTy = VD->getType(); 15037 15038 if (Info.EnableNewConstInterp) { 15039 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 15040 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 15041 return false; 15042 } else { 15043 LValue LVal; 15044 LVal.set(VD); 15045 15046 if (!EvaluateInPlace(Value, Info, LVal, this, 15047 /*AllowNonLiteralTypes=*/true) || 15048 EStatus.HasSideEffects) 15049 return false; 15050 15051 // At this point, any lifetime-extended temporaries are completely 15052 // initialized. 15053 Info.performLifetimeExtension(); 15054 15055 if (!Info.discardCleanups()) 15056 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15057 } 15058 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 15059 ConstantExprKind::Normal) && 15060 CheckMemoryLeaks(Info); 15061 } 15062 15063 bool VarDecl::evaluateDestruction( 15064 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15065 Expr::EvalStatus EStatus; 15066 EStatus.Diag = &Notes; 15067 15068 // Only treat the destruction as constant destruction if we formally have 15069 // constant initialization (or are usable in a constant expression). 15070 bool IsConstantDestruction = hasConstantInitialization(); 15071 15072 // Make a copy of the value for the destructor to mutate, if we know it. 15073 // Otherwise, treat the value as default-initialized; if the destructor works 15074 // anyway, then the destruction is constant (and must be essentially empty). 15075 APValue DestroyedValue; 15076 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 15077 DestroyedValue = *getEvaluatedValue(); 15078 else if (!getDefaultInitValue(getType(), DestroyedValue)) 15079 return false; 15080 15081 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 15082 getType(), getLocation(), EStatus, 15083 IsConstantDestruction) || 15084 EStatus.HasSideEffects) 15085 return false; 15086 15087 ensureEvaluatedStmt()->HasConstantDestruction = true; 15088 return true; 15089 } 15090 15091 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 15092 /// constant folded, but discard the result. 15093 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 15094 assert(!isValueDependent() && 15095 "Expression evaluator can't be called on a dependent expression."); 15096 15097 EvalResult Result; 15098 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 15099 !hasUnacceptableSideEffect(Result, SEK); 15100 } 15101 15102 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 15103 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15104 assert(!isValueDependent() && 15105 "Expression evaluator can't be called on a dependent expression."); 15106 15107 EvalResult EVResult; 15108 EVResult.Diag = Diag; 15109 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15110 Info.InConstantContext = true; 15111 15112 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 15113 (void)Result; 15114 assert(Result && "Could not evaluate expression"); 15115 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15116 15117 return EVResult.Val.getInt(); 15118 } 15119 15120 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 15121 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15122 assert(!isValueDependent() && 15123 "Expression evaluator can't be called on a dependent expression."); 15124 15125 EvalResult EVResult; 15126 EVResult.Diag = Diag; 15127 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15128 Info.InConstantContext = true; 15129 Info.CheckingForUndefinedBehavior = true; 15130 15131 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15132 (void)Result; 15133 assert(Result && "Could not evaluate expression"); 15134 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15135 15136 return EVResult.Val.getInt(); 15137 } 15138 15139 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15140 assert(!isValueDependent() && 15141 "Expression evaluator can't be called on a dependent expression."); 15142 15143 bool IsConst; 15144 EvalResult EVResult; 15145 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15146 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15147 Info.CheckingForUndefinedBehavior = true; 15148 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15149 } 15150 } 15151 15152 bool Expr::EvalResult::isGlobalLValue() const { 15153 assert(Val.isLValue()); 15154 return IsGlobalLValue(Val.getLValueBase()); 15155 } 15156 15157 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15158 /// an integer constant expression. 15159 15160 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15161 /// comma, etc 15162 15163 // CheckICE - This function does the fundamental ICE checking: the returned 15164 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15165 // and a (possibly null) SourceLocation indicating the location of the problem. 15166 // 15167 // Note that to reduce code duplication, this helper does no evaluation 15168 // itself; the caller checks whether the expression is evaluatable, and 15169 // in the rare cases where CheckICE actually cares about the evaluated 15170 // value, it calls into Evaluate. 15171 15172 namespace { 15173 15174 enum ICEKind { 15175 /// This expression is an ICE. 15176 IK_ICE, 15177 /// This expression is not an ICE, but if it isn't evaluated, it's 15178 /// a legal subexpression for an ICE. This return value is used to handle 15179 /// the comma operator in C99 mode, and non-constant subexpressions. 15180 IK_ICEIfUnevaluated, 15181 /// This expression is not an ICE, and is not a legal subexpression for one. 15182 IK_NotICE 15183 }; 15184 15185 struct ICEDiag { 15186 ICEKind Kind; 15187 SourceLocation Loc; 15188 15189 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15190 }; 15191 15192 } 15193 15194 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15195 15196 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15197 15198 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15199 Expr::EvalResult EVResult; 15200 Expr::EvalStatus Status; 15201 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15202 15203 Info.InConstantContext = true; 15204 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15205 !EVResult.Val.isInt()) 15206 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15207 15208 return NoDiag(); 15209 } 15210 15211 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15212 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15213 if (!E->getType()->isIntegralOrEnumerationType()) 15214 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15215 15216 switch (E->getStmtClass()) { 15217 #define ABSTRACT_STMT(Node) 15218 #define STMT(Node, Base) case Expr::Node##Class: 15219 #define EXPR(Node, Base) 15220 #include "clang/AST/StmtNodes.inc" 15221 case Expr::PredefinedExprClass: 15222 case Expr::FloatingLiteralClass: 15223 case Expr::ImaginaryLiteralClass: 15224 case Expr::StringLiteralClass: 15225 case Expr::ArraySubscriptExprClass: 15226 case Expr::MatrixSubscriptExprClass: 15227 case Expr::OMPArraySectionExprClass: 15228 case Expr::OMPArrayShapingExprClass: 15229 case Expr::OMPIteratorExprClass: 15230 case Expr::MemberExprClass: 15231 case Expr::CompoundAssignOperatorClass: 15232 case Expr::CompoundLiteralExprClass: 15233 case Expr::ExtVectorElementExprClass: 15234 case Expr::DesignatedInitExprClass: 15235 case Expr::ArrayInitLoopExprClass: 15236 case Expr::ArrayInitIndexExprClass: 15237 case Expr::NoInitExprClass: 15238 case Expr::DesignatedInitUpdateExprClass: 15239 case Expr::ImplicitValueInitExprClass: 15240 case Expr::ParenListExprClass: 15241 case Expr::VAArgExprClass: 15242 case Expr::AddrLabelExprClass: 15243 case Expr::StmtExprClass: 15244 case Expr::CXXMemberCallExprClass: 15245 case Expr::CUDAKernelCallExprClass: 15246 case Expr::CXXAddrspaceCastExprClass: 15247 case Expr::CXXDynamicCastExprClass: 15248 case Expr::CXXTypeidExprClass: 15249 case Expr::CXXUuidofExprClass: 15250 case Expr::MSPropertyRefExprClass: 15251 case Expr::MSPropertySubscriptExprClass: 15252 case Expr::CXXNullPtrLiteralExprClass: 15253 case Expr::UserDefinedLiteralClass: 15254 case Expr::CXXThisExprClass: 15255 case Expr::CXXThrowExprClass: 15256 case Expr::CXXNewExprClass: 15257 case Expr::CXXDeleteExprClass: 15258 case Expr::CXXPseudoDestructorExprClass: 15259 case Expr::UnresolvedLookupExprClass: 15260 case Expr::TypoExprClass: 15261 case Expr::RecoveryExprClass: 15262 case Expr::DependentScopeDeclRefExprClass: 15263 case Expr::CXXConstructExprClass: 15264 case Expr::CXXInheritedCtorInitExprClass: 15265 case Expr::CXXStdInitializerListExprClass: 15266 case Expr::CXXBindTemporaryExprClass: 15267 case Expr::ExprWithCleanupsClass: 15268 case Expr::CXXTemporaryObjectExprClass: 15269 case Expr::CXXUnresolvedConstructExprClass: 15270 case Expr::CXXDependentScopeMemberExprClass: 15271 case Expr::UnresolvedMemberExprClass: 15272 case Expr::ObjCStringLiteralClass: 15273 case Expr::ObjCBoxedExprClass: 15274 case Expr::ObjCArrayLiteralClass: 15275 case Expr::ObjCDictionaryLiteralClass: 15276 case Expr::ObjCEncodeExprClass: 15277 case Expr::ObjCMessageExprClass: 15278 case Expr::ObjCSelectorExprClass: 15279 case Expr::ObjCProtocolExprClass: 15280 case Expr::ObjCIvarRefExprClass: 15281 case Expr::ObjCPropertyRefExprClass: 15282 case Expr::ObjCSubscriptRefExprClass: 15283 case Expr::ObjCIsaExprClass: 15284 case Expr::ObjCAvailabilityCheckExprClass: 15285 case Expr::ShuffleVectorExprClass: 15286 case Expr::ConvertVectorExprClass: 15287 case Expr::BlockExprClass: 15288 case Expr::NoStmtClass: 15289 case Expr::OpaqueValueExprClass: 15290 case Expr::PackExpansionExprClass: 15291 case Expr::SubstNonTypeTemplateParmPackExprClass: 15292 case Expr::FunctionParmPackExprClass: 15293 case Expr::AsTypeExprClass: 15294 case Expr::ObjCIndirectCopyRestoreExprClass: 15295 case Expr::MaterializeTemporaryExprClass: 15296 case Expr::PseudoObjectExprClass: 15297 case Expr::AtomicExprClass: 15298 case Expr::LambdaExprClass: 15299 case Expr::CXXFoldExprClass: 15300 case Expr::CoawaitExprClass: 15301 case Expr::DependentCoawaitExprClass: 15302 case Expr::CoyieldExprClass: 15303 case Expr::SYCLUniqueStableNameExprClass: 15304 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15305 15306 case Expr::InitListExprClass: { 15307 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15308 // form "T x = { a };" is equivalent to "T x = a;". 15309 // Unless we're initializing a reference, T is a scalar as it is known to be 15310 // of integral or enumeration type. 15311 if (E->isPRValue()) 15312 if (cast<InitListExpr>(E)->getNumInits() == 1) 15313 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15314 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15315 } 15316 15317 case Expr::SizeOfPackExprClass: 15318 case Expr::GNUNullExprClass: 15319 case Expr::SourceLocExprClass: 15320 return NoDiag(); 15321 15322 case Expr::SubstNonTypeTemplateParmExprClass: 15323 return 15324 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15325 15326 case Expr::ConstantExprClass: 15327 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15328 15329 case Expr::ParenExprClass: 15330 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15331 case Expr::GenericSelectionExprClass: 15332 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15333 case Expr::IntegerLiteralClass: 15334 case Expr::FixedPointLiteralClass: 15335 case Expr::CharacterLiteralClass: 15336 case Expr::ObjCBoolLiteralExprClass: 15337 case Expr::CXXBoolLiteralExprClass: 15338 case Expr::CXXScalarValueInitExprClass: 15339 case Expr::TypeTraitExprClass: 15340 case Expr::ConceptSpecializationExprClass: 15341 case Expr::RequiresExprClass: 15342 case Expr::ArrayTypeTraitExprClass: 15343 case Expr::ExpressionTraitExprClass: 15344 case Expr::CXXNoexceptExprClass: 15345 return NoDiag(); 15346 case Expr::CallExprClass: 15347 case Expr::CXXOperatorCallExprClass: { 15348 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15349 // constant expressions, but they can never be ICEs because an ICE cannot 15350 // contain an operand of (pointer to) function type. 15351 const CallExpr *CE = cast<CallExpr>(E); 15352 if (CE->getBuiltinCallee()) 15353 return CheckEvalInICE(E, Ctx); 15354 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15355 } 15356 case Expr::CXXRewrittenBinaryOperatorClass: 15357 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15358 Ctx); 15359 case Expr::DeclRefExprClass: { 15360 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15361 if (isa<EnumConstantDecl>(D)) 15362 return NoDiag(); 15363 15364 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15365 // integer variables in constant expressions: 15366 // 15367 // C++ 7.1.5.1p2 15368 // A variable of non-volatile const-qualified integral or enumeration 15369 // type initialized by an ICE can be used in ICEs. 15370 // 15371 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15372 // that mode, use of reference variables should not be allowed. 15373 const VarDecl *VD = dyn_cast<VarDecl>(D); 15374 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15375 !VD->getType()->isReferenceType()) 15376 return NoDiag(); 15377 15378 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15379 } 15380 case Expr::UnaryOperatorClass: { 15381 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15382 switch (Exp->getOpcode()) { 15383 case UO_PostInc: 15384 case UO_PostDec: 15385 case UO_PreInc: 15386 case UO_PreDec: 15387 case UO_AddrOf: 15388 case UO_Deref: 15389 case UO_Coawait: 15390 // C99 6.6/3 allows increment and decrement within unevaluated 15391 // subexpressions of constant expressions, but they can never be ICEs 15392 // because an ICE cannot contain an lvalue operand. 15393 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15394 case UO_Extension: 15395 case UO_LNot: 15396 case UO_Plus: 15397 case UO_Minus: 15398 case UO_Not: 15399 case UO_Real: 15400 case UO_Imag: 15401 return CheckICE(Exp->getSubExpr(), Ctx); 15402 } 15403 llvm_unreachable("invalid unary operator class"); 15404 } 15405 case Expr::OffsetOfExprClass: { 15406 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15407 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15408 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15409 // compliance: we should warn earlier for offsetof expressions with 15410 // array subscripts that aren't ICEs, and if the array subscripts 15411 // are ICEs, the value of the offsetof must be an integer constant. 15412 return CheckEvalInICE(E, Ctx); 15413 } 15414 case Expr::UnaryExprOrTypeTraitExprClass: { 15415 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15416 if ((Exp->getKind() == UETT_SizeOf) && 15417 Exp->getTypeOfArgument()->isVariableArrayType()) 15418 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15419 return NoDiag(); 15420 } 15421 case Expr::BinaryOperatorClass: { 15422 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15423 switch (Exp->getOpcode()) { 15424 case BO_PtrMemD: 15425 case BO_PtrMemI: 15426 case BO_Assign: 15427 case BO_MulAssign: 15428 case BO_DivAssign: 15429 case BO_RemAssign: 15430 case BO_AddAssign: 15431 case BO_SubAssign: 15432 case BO_ShlAssign: 15433 case BO_ShrAssign: 15434 case BO_AndAssign: 15435 case BO_XorAssign: 15436 case BO_OrAssign: 15437 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15438 // constant expressions, but they can never be ICEs because an ICE cannot 15439 // contain an lvalue operand. 15440 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15441 15442 case BO_Mul: 15443 case BO_Div: 15444 case BO_Rem: 15445 case BO_Add: 15446 case BO_Sub: 15447 case BO_Shl: 15448 case BO_Shr: 15449 case BO_LT: 15450 case BO_GT: 15451 case BO_LE: 15452 case BO_GE: 15453 case BO_EQ: 15454 case BO_NE: 15455 case BO_And: 15456 case BO_Xor: 15457 case BO_Or: 15458 case BO_Comma: 15459 case BO_Cmp: { 15460 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15461 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15462 if (Exp->getOpcode() == BO_Div || 15463 Exp->getOpcode() == BO_Rem) { 15464 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15465 // we don't evaluate one. 15466 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15467 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15468 if (REval == 0) 15469 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15470 if (REval.isSigned() && REval.isAllOnes()) { 15471 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15472 if (LEval.isMinSignedValue()) 15473 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15474 } 15475 } 15476 } 15477 if (Exp->getOpcode() == BO_Comma) { 15478 if (Ctx.getLangOpts().C99) { 15479 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15480 // if it isn't evaluated. 15481 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15482 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15483 } else { 15484 // In both C89 and C++, commas in ICEs are illegal. 15485 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15486 } 15487 } 15488 return Worst(LHSResult, RHSResult); 15489 } 15490 case BO_LAnd: 15491 case BO_LOr: { 15492 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15493 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15494 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15495 // Rare case where the RHS has a comma "side-effect"; we need 15496 // to actually check the condition to see whether the side 15497 // with the comma is evaluated. 15498 if ((Exp->getOpcode() == BO_LAnd) != 15499 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15500 return RHSResult; 15501 return NoDiag(); 15502 } 15503 15504 return Worst(LHSResult, RHSResult); 15505 } 15506 } 15507 llvm_unreachable("invalid binary operator kind"); 15508 } 15509 case Expr::ImplicitCastExprClass: 15510 case Expr::CStyleCastExprClass: 15511 case Expr::CXXFunctionalCastExprClass: 15512 case Expr::CXXStaticCastExprClass: 15513 case Expr::CXXReinterpretCastExprClass: 15514 case Expr::CXXConstCastExprClass: 15515 case Expr::ObjCBridgedCastExprClass: { 15516 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15517 if (isa<ExplicitCastExpr>(E)) { 15518 if (const FloatingLiteral *FL 15519 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15520 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15521 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15522 APSInt IgnoredVal(DestWidth, !DestSigned); 15523 bool Ignored; 15524 // If the value does not fit in the destination type, the behavior is 15525 // undefined, so we are not required to treat it as a constant 15526 // expression. 15527 if (FL->getValue().convertToInteger(IgnoredVal, 15528 llvm::APFloat::rmTowardZero, 15529 &Ignored) & APFloat::opInvalidOp) 15530 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15531 return NoDiag(); 15532 } 15533 } 15534 switch (cast<CastExpr>(E)->getCastKind()) { 15535 case CK_LValueToRValue: 15536 case CK_AtomicToNonAtomic: 15537 case CK_NonAtomicToAtomic: 15538 case CK_NoOp: 15539 case CK_IntegralToBoolean: 15540 case CK_IntegralCast: 15541 return CheckICE(SubExpr, Ctx); 15542 default: 15543 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15544 } 15545 } 15546 case Expr::BinaryConditionalOperatorClass: { 15547 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15548 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15549 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15550 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15551 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15552 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15553 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15554 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15555 return FalseResult; 15556 } 15557 case Expr::ConditionalOperatorClass: { 15558 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15559 // If the condition (ignoring parens) is a __builtin_constant_p call, 15560 // then only the true side is actually considered in an integer constant 15561 // expression, and it is fully evaluated. This is an important GNU 15562 // extension. See GCC PR38377 for discussion. 15563 if (const CallExpr *CallCE 15564 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15565 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15566 return CheckEvalInICE(E, Ctx); 15567 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15568 if (CondResult.Kind == IK_NotICE) 15569 return CondResult; 15570 15571 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15572 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15573 15574 if (TrueResult.Kind == IK_NotICE) 15575 return TrueResult; 15576 if (FalseResult.Kind == IK_NotICE) 15577 return FalseResult; 15578 if (CondResult.Kind == IK_ICEIfUnevaluated) 15579 return CondResult; 15580 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15581 return NoDiag(); 15582 // Rare case where the diagnostics depend on which side is evaluated 15583 // Note that if we get here, CondResult is 0, and at least one of 15584 // TrueResult and FalseResult is non-zero. 15585 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15586 return FalseResult; 15587 return TrueResult; 15588 } 15589 case Expr::CXXDefaultArgExprClass: 15590 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15591 case Expr::CXXDefaultInitExprClass: 15592 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15593 case Expr::ChooseExprClass: { 15594 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15595 } 15596 case Expr::BuiltinBitCastExprClass: { 15597 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15598 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15599 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15600 } 15601 } 15602 15603 llvm_unreachable("Invalid StmtClass!"); 15604 } 15605 15606 /// Evaluate an expression as a C++11 integral constant expression. 15607 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15608 const Expr *E, 15609 llvm::APSInt *Value, 15610 SourceLocation *Loc) { 15611 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15612 if (Loc) *Loc = E->getExprLoc(); 15613 return false; 15614 } 15615 15616 APValue Result; 15617 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15618 return false; 15619 15620 if (!Result.isInt()) { 15621 if (Loc) *Loc = E->getExprLoc(); 15622 return false; 15623 } 15624 15625 if (Value) *Value = Result.getInt(); 15626 return true; 15627 } 15628 15629 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15630 SourceLocation *Loc) const { 15631 assert(!isValueDependent() && 15632 "Expression evaluator can't be called on a dependent expression."); 15633 15634 if (Ctx.getLangOpts().CPlusPlus11) 15635 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15636 15637 ICEDiag D = CheckICE(this, Ctx); 15638 if (D.Kind != IK_ICE) { 15639 if (Loc) *Loc = D.Loc; 15640 return false; 15641 } 15642 return true; 15643 } 15644 15645 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15646 SourceLocation *Loc, 15647 bool isEvaluated) const { 15648 if (isValueDependent()) { 15649 // Expression evaluator can't succeed on a dependent expression. 15650 return None; 15651 } 15652 15653 APSInt Value; 15654 15655 if (Ctx.getLangOpts().CPlusPlus11) { 15656 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15657 return Value; 15658 return None; 15659 } 15660 15661 if (!isIntegerConstantExpr(Ctx, Loc)) 15662 return None; 15663 15664 // The only possible side-effects here are due to UB discovered in the 15665 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15666 // required to treat the expression as an ICE, so we produce the folded 15667 // value. 15668 EvalResult ExprResult; 15669 Expr::EvalStatus Status; 15670 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15671 Info.InConstantContext = true; 15672 15673 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15674 llvm_unreachable("ICE cannot be evaluated!"); 15675 15676 return ExprResult.Val.getInt(); 15677 } 15678 15679 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15680 assert(!isValueDependent() && 15681 "Expression evaluator can't be called on a dependent expression."); 15682 15683 return CheckICE(this, Ctx).Kind == IK_ICE; 15684 } 15685 15686 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15687 SourceLocation *Loc) const { 15688 assert(!isValueDependent() && 15689 "Expression evaluator can't be called on a dependent expression."); 15690 15691 // We support this checking in C++98 mode in order to diagnose compatibility 15692 // issues. 15693 assert(Ctx.getLangOpts().CPlusPlus); 15694 15695 // Build evaluation settings. 15696 Expr::EvalStatus Status; 15697 SmallVector<PartialDiagnosticAt, 8> Diags; 15698 Status.Diag = &Diags; 15699 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15700 15701 APValue Scratch; 15702 bool IsConstExpr = 15703 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15704 // FIXME: We don't produce a diagnostic for this, but the callers that 15705 // call us on arbitrary full-expressions should generally not care. 15706 Info.discardCleanups() && !Status.HasSideEffects; 15707 15708 if (!Diags.empty()) { 15709 IsConstExpr = false; 15710 if (Loc) *Loc = Diags[0].first; 15711 } else if (!IsConstExpr) { 15712 // FIXME: This shouldn't happen. 15713 if (Loc) *Loc = getExprLoc(); 15714 } 15715 15716 return IsConstExpr; 15717 } 15718 15719 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15720 const FunctionDecl *Callee, 15721 ArrayRef<const Expr*> Args, 15722 const Expr *This) const { 15723 assert(!isValueDependent() && 15724 "Expression evaluator can't be called on a dependent expression."); 15725 15726 Expr::EvalStatus Status; 15727 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15728 Info.InConstantContext = true; 15729 15730 LValue ThisVal; 15731 const LValue *ThisPtr = nullptr; 15732 if (This) { 15733 #ifndef NDEBUG 15734 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15735 assert(MD && "Don't provide `this` for non-methods."); 15736 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15737 #endif 15738 if (!This->isValueDependent() && 15739 EvaluateObjectArgument(Info, This, ThisVal) && 15740 !Info.EvalStatus.HasSideEffects) 15741 ThisPtr = &ThisVal; 15742 15743 // Ignore any side-effects from a failed evaluation. This is safe because 15744 // they can't interfere with any other argument evaluation. 15745 Info.EvalStatus.HasSideEffects = false; 15746 } 15747 15748 CallRef Call = Info.CurrentCall->createCall(Callee); 15749 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15750 I != E; ++I) { 15751 unsigned Idx = I - Args.begin(); 15752 if (Idx >= Callee->getNumParams()) 15753 break; 15754 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15755 if ((*I)->isValueDependent() || 15756 !EvaluateCallArg(PVD, *I, Call, Info) || 15757 Info.EvalStatus.HasSideEffects) { 15758 // If evaluation fails, throw away the argument entirely. 15759 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15760 *Slot = APValue(); 15761 } 15762 15763 // Ignore any side-effects from a failed evaluation. This is safe because 15764 // they can't interfere with any other argument evaluation. 15765 Info.EvalStatus.HasSideEffects = false; 15766 } 15767 15768 // Parameter cleanups happen in the caller and are not part of this 15769 // evaluation. 15770 Info.discardCleanups(); 15771 Info.EvalStatus.HasSideEffects = false; 15772 15773 // Build fake call to Callee. 15774 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15775 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15776 FullExpressionRAII Scope(Info); 15777 return Evaluate(Value, Info, this) && Scope.destroy() && 15778 !Info.EvalStatus.HasSideEffects; 15779 } 15780 15781 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15782 SmallVectorImpl< 15783 PartialDiagnosticAt> &Diags) { 15784 // FIXME: It would be useful to check constexpr function templates, but at the 15785 // moment the constant expression evaluator cannot cope with the non-rigorous 15786 // ASTs which we build for dependent expressions. 15787 if (FD->isDependentContext()) 15788 return true; 15789 15790 Expr::EvalStatus Status; 15791 Status.Diag = &Diags; 15792 15793 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15794 Info.InConstantContext = true; 15795 Info.CheckingPotentialConstantExpression = true; 15796 15797 // The constexpr VM attempts to compile all methods to bytecode here. 15798 if (Info.EnableNewConstInterp) { 15799 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15800 return Diags.empty(); 15801 } 15802 15803 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15804 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15805 15806 // Fabricate an arbitrary expression on the stack and pretend that it 15807 // is a temporary being used as the 'this' pointer. 15808 LValue This; 15809 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15810 This.set({&VIE, Info.CurrentCall->Index}); 15811 15812 ArrayRef<const Expr*> Args; 15813 15814 APValue Scratch; 15815 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15816 // Evaluate the call as a constant initializer, to allow the construction 15817 // of objects of non-literal types. 15818 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15819 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15820 } else { 15821 SourceLocation Loc = FD->getLocation(); 15822 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15823 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15824 } 15825 15826 return Diags.empty(); 15827 } 15828 15829 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15830 const FunctionDecl *FD, 15831 SmallVectorImpl< 15832 PartialDiagnosticAt> &Diags) { 15833 assert(!E->isValueDependent() && 15834 "Expression evaluator can't be called on a dependent expression."); 15835 15836 Expr::EvalStatus Status; 15837 Status.Diag = &Diags; 15838 15839 EvalInfo Info(FD->getASTContext(), Status, 15840 EvalInfo::EM_ConstantExpressionUnevaluated); 15841 Info.InConstantContext = true; 15842 Info.CheckingPotentialConstantExpression = true; 15843 15844 // Fabricate a call stack frame to give the arguments a plausible cover story. 15845 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15846 15847 APValue ResultScratch; 15848 Evaluate(ResultScratch, Info, E); 15849 return Diags.empty(); 15850 } 15851 15852 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15853 unsigned Type) const { 15854 if (!getType()->isPointerType()) 15855 return false; 15856 15857 Expr::EvalStatus Status; 15858 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15859 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15860 } 15861 15862 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 15863 EvalInfo &Info) { 15864 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 15865 return false; 15866 15867 LValue String; 15868 15869 if (!EvaluatePointer(E, String, Info)) 15870 return false; 15871 15872 QualType CharTy = E->getType()->getPointeeType(); 15873 15874 // Fast path: if it's a string literal, search the string value. 15875 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 15876 String.getLValueBase().dyn_cast<const Expr *>())) { 15877 StringRef Str = S->getBytes(); 15878 int64_t Off = String.Offset.getQuantity(); 15879 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 15880 S->getCharByteWidth() == 1 && 15881 // FIXME: Add fast-path for wchar_t too. 15882 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 15883 Str = Str.substr(Off); 15884 15885 StringRef::size_type Pos = Str.find(0); 15886 if (Pos != StringRef::npos) 15887 Str = Str.substr(0, Pos); 15888 15889 Result = Str.size(); 15890 return true; 15891 } 15892 15893 // Fall through to slow path. 15894 } 15895 15896 // Slow path: scan the bytes of the string looking for the terminating 0. 15897 for (uint64_t Strlen = 0; /**/; ++Strlen) { 15898 APValue Char; 15899 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 15900 !Char.isInt()) 15901 return false; 15902 if (!Char.getInt()) { 15903 Result = Strlen; 15904 return true; 15905 } 15906 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 15907 return false; 15908 } 15909 } 15910 15911 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 15912 Expr::EvalStatus Status; 15913 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15914 return EvaluateBuiltinStrLen(this, Result, Info); 15915 } 15916