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 // ... the address of an unnamed global constant 1982 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D); 1983 } 1984 1985 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1986 return true; 1987 1988 const Expr *E = B.get<const Expr*>(); 1989 switch (E->getStmtClass()) { 1990 default: 1991 return false; 1992 case Expr::CompoundLiteralExprClass: { 1993 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1994 return CLE->isFileScope() && CLE->isLValue(); 1995 } 1996 case Expr::MaterializeTemporaryExprClass: 1997 // A materialized temporary might have been lifetime-extended to static 1998 // storage duration. 1999 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 2000 // A string literal has static storage duration. 2001 case Expr::StringLiteralClass: 2002 case Expr::PredefinedExprClass: 2003 case Expr::ObjCStringLiteralClass: 2004 case Expr::ObjCEncodeExprClass: 2005 return true; 2006 case Expr::ObjCBoxedExprClass: 2007 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2008 case Expr::CallExprClass: 2009 return IsConstantCall(cast<CallExpr>(E)); 2010 // For GCC compatibility, &&label has static storage duration. 2011 case Expr::AddrLabelExprClass: 2012 return true; 2013 // A Block literal expression may be used as the initialization value for 2014 // Block variables at global or local static scope. 2015 case Expr::BlockExprClass: 2016 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2017 // The APValue generated from a __builtin_source_location will be emitted as a 2018 // literal. 2019 case Expr::SourceLocExprClass: 2020 return true; 2021 case Expr::ImplicitValueInitExprClass: 2022 // FIXME: 2023 // We can never form an lvalue with an implicit value initialization as its 2024 // base through expression evaluation, so these only appear in one case: the 2025 // implicit variable declaration we invent when checking whether a constexpr 2026 // constructor can produce a constant expression. We must assume that such 2027 // an expression might be a global lvalue. 2028 return true; 2029 } 2030 } 2031 2032 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2033 return LVal.Base.dyn_cast<const ValueDecl*>(); 2034 } 2035 2036 static bool IsLiteralLValue(const LValue &Value) { 2037 if (Value.getLValueCallIndex()) 2038 return false; 2039 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2040 return E && !isa<MaterializeTemporaryExpr>(E); 2041 } 2042 2043 static bool IsWeakLValue(const LValue &Value) { 2044 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2045 return Decl && Decl->isWeak(); 2046 } 2047 2048 static bool isZeroSized(const LValue &Value) { 2049 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2050 if (Decl && isa<VarDecl>(Decl)) { 2051 QualType Ty = Decl->getType(); 2052 if (Ty->isArrayType()) 2053 return Ty->isIncompleteType() || 2054 Decl->getASTContext().getTypeSize(Ty) == 0; 2055 } 2056 return false; 2057 } 2058 2059 static bool HasSameBase(const LValue &A, const LValue &B) { 2060 if (!A.getLValueBase()) 2061 return !B.getLValueBase(); 2062 if (!B.getLValueBase()) 2063 return false; 2064 2065 if (A.getLValueBase().getOpaqueValue() != 2066 B.getLValueBase().getOpaqueValue()) 2067 return false; 2068 2069 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2070 A.getLValueVersion() == B.getLValueVersion(); 2071 } 2072 2073 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2074 assert(Base && "no location for a null lvalue"); 2075 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2076 2077 // For a parameter, find the corresponding call stack frame (if it still 2078 // exists), and point at the parameter of the function definition we actually 2079 // invoked. 2080 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2081 unsigned Idx = PVD->getFunctionScopeIndex(); 2082 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2083 if (F->Arguments.CallIndex == Base.getCallIndex() && 2084 F->Arguments.Version == Base.getVersion() && F->Callee && 2085 Idx < F->Callee->getNumParams()) { 2086 VD = F->Callee->getParamDecl(Idx); 2087 break; 2088 } 2089 } 2090 } 2091 2092 if (VD) 2093 Info.Note(VD->getLocation(), diag::note_declared_at); 2094 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2095 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2096 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2097 // FIXME: Produce a note for dangling pointers too. 2098 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2099 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2100 diag::note_constexpr_dynamic_alloc_here); 2101 } 2102 // We have no information to show for a typeid(T) object. 2103 } 2104 2105 enum class CheckEvaluationResultKind { 2106 ConstantExpression, 2107 FullyInitialized, 2108 }; 2109 2110 /// Materialized temporaries that we've already checked to determine if they're 2111 /// initializsed by a constant expression. 2112 using CheckedTemporaries = 2113 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2114 2115 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2116 EvalInfo &Info, SourceLocation DiagLoc, 2117 QualType Type, const APValue &Value, 2118 ConstantExprKind Kind, 2119 SourceLocation SubobjectLoc, 2120 CheckedTemporaries &CheckedTemps); 2121 2122 /// Check that this reference or pointer core constant expression is a valid 2123 /// value for an address or reference constant expression. Return true if we 2124 /// can fold this expression, whether or not it's a constant expression. 2125 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2126 QualType Type, const LValue &LVal, 2127 ConstantExprKind Kind, 2128 CheckedTemporaries &CheckedTemps) { 2129 bool IsReferenceType = Type->isReferenceType(); 2130 2131 APValue::LValueBase Base = LVal.getLValueBase(); 2132 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2133 2134 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2135 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2136 2137 // Additional restrictions apply in a template argument. We only enforce the 2138 // C++20 restrictions here; additional syntactic and semantic restrictions 2139 // are applied elsewhere. 2140 if (isTemplateArgument(Kind)) { 2141 int InvalidBaseKind = -1; 2142 StringRef Ident; 2143 if (Base.is<TypeInfoLValue>()) 2144 InvalidBaseKind = 0; 2145 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2146 InvalidBaseKind = 1; 2147 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2148 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2149 InvalidBaseKind = 2; 2150 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2151 InvalidBaseKind = 3; 2152 Ident = PE->getIdentKindName(); 2153 } 2154 2155 if (InvalidBaseKind != -1) { 2156 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2157 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2158 << Ident; 2159 return false; 2160 } 2161 } 2162 2163 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2164 if (FD->isConsteval()) { 2165 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2166 << !Type->isAnyPointerType(); 2167 Info.Note(FD->getLocation(), diag::note_declared_at); 2168 return false; 2169 } 2170 } 2171 2172 // Check that the object is a global. Note that the fake 'this' object we 2173 // manufacture when checking potential constant expressions is conservatively 2174 // assumed to be global here. 2175 if (!IsGlobalLValue(Base)) { 2176 if (Info.getLangOpts().CPlusPlus11) { 2177 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2178 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2179 << IsReferenceType << !Designator.Entries.empty() 2180 << !!VD << VD; 2181 2182 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2183 if (VarD && VarD->isConstexpr()) { 2184 // Non-static local constexpr variables have unintuitive semantics: 2185 // constexpr int a = 1; 2186 // constexpr const int *p = &a; 2187 // ... is invalid because the address of 'a' is not constant. Suggest 2188 // adding a 'static' in this case. 2189 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2190 << VarD 2191 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2192 } else { 2193 NoteLValueLocation(Info, Base); 2194 } 2195 } else { 2196 Info.FFDiag(Loc); 2197 } 2198 // Don't allow references to temporaries to escape. 2199 return false; 2200 } 2201 assert((Info.checkingPotentialConstantExpression() || 2202 LVal.getLValueCallIndex() == 0) && 2203 "have call index for global lvalue"); 2204 2205 if (Base.is<DynamicAllocLValue>()) { 2206 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2207 << IsReferenceType << !Designator.Entries.empty(); 2208 NoteLValueLocation(Info, Base); 2209 return false; 2210 } 2211 2212 if (BaseVD) { 2213 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2214 // Check if this is a thread-local variable. 2215 if (Var->getTLSKind()) 2216 // FIXME: Diagnostic! 2217 return false; 2218 2219 // A dllimport variable never acts like a constant, unless we're 2220 // evaluating a value for use only in name mangling. 2221 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2222 // FIXME: Diagnostic! 2223 return false; 2224 2225 // In CUDA/HIP device compilation, only device side variables have 2226 // constant addresses. 2227 if (Info.getCtx().getLangOpts().CUDA && 2228 Info.getCtx().getLangOpts().CUDAIsDevice && 2229 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) { 2230 if ((!Var->hasAttr<CUDADeviceAttr>() && 2231 !Var->hasAttr<CUDAConstantAttr>() && 2232 !Var->getType()->isCUDADeviceBuiltinSurfaceType() && 2233 !Var->getType()->isCUDADeviceBuiltinTextureType()) || 2234 Var->hasAttr<HIPManagedAttr>()) 2235 return false; 2236 } 2237 } 2238 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2239 // __declspec(dllimport) must be handled very carefully: 2240 // We must never initialize an expression with the thunk in C++. 2241 // Doing otherwise would allow the same id-expression to yield 2242 // different addresses for the same function in different translation 2243 // units. However, this means that we must dynamically initialize the 2244 // expression with the contents of the import address table at runtime. 2245 // 2246 // The C language has no notion of ODR; furthermore, it has no notion of 2247 // dynamic initialization. This means that we are permitted to 2248 // perform initialization with the address of the thunk. 2249 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2250 FD->hasAttr<DLLImportAttr>()) 2251 // FIXME: Diagnostic! 2252 return false; 2253 } 2254 } else if (const auto *MTE = 2255 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2256 if (CheckedTemps.insert(MTE).second) { 2257 QualType TempType = getType(Base); 2258 if (TempType.isDestructedType()) { 2259 Info.FFDiag(MTE->getExprLoc(), 2260 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2261 << TempType; 2262 return false; 2263 } 2264 2265 APValue *V = MTE->getOrCreateValue(false); 2266 assert(V && "evasluation result refers to uninitialised temporary"); 2267 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2268 Info, MTE->getExprLoc(), TempType, *V, 2269 Kind, SourceLocation(), CheckedTemps)) 2270 return false; 2271 } 2272 } 2273 2274 // Allow address constant expressions to be past-the-end pointers. This is 2275 // an extension: the standard requires them to point to an object. 2276 if (!IsReferenceType) 2277 return true; 2278 2279 // A reference constant expression must refer to an object. 2280 if (!Base) { 2281 // FIXME: diagnostic 2282 Info.CCEDiag(Loc); 2283 return true; 2284 } 2285 2286 // Does this refer one past the end of some object? 2287 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2288 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2289 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2290 NoteLValueLocation(Info, Base); 2291 } 2292 2293 return true; 2294 } 2295 2296 /// Member pointers are constant expressions unless they point to a 2297 /// non-virtual dllimport member function. 2298 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2299 SourceLocation Loc, 2300 QualType Type, 2301 const APValue &Value, 2302 ConstantExprKind Kind) { 2303 const ValueDecl *Member = Value.getMemberPointerDecl(); 2304 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2305 if (!FD) 2306 return true; 2307 if (FD->isConsteval()) { 2308 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2309 Info.Note(FD->getLocation(), diag::note_declared_at); 2310 return false; 2311 } 2312 return isForManglingOnly(Kind) || FD->isVirtual() || 2313 !FD->hasAttr<DLLImportAttr>(); 2314 } 2315 2316 /// Check that this core constant expression is of literal type, and if not, 2317 /// produce an appropriate diagnostic. 2318 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2319 const LValue *This = nullptr) { 2320 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2321 return true; 2322 2323 // C++1y: A constant initializer for an object o [...] may also invoke 2324 // constexpr constructors for o and its subobjects even if those objects 2325 // are of non-literal class types. 2326 // 2327 // C++11 missed this detail for aggregates, so classes like this: 2328 // struct foo_t { union { int i; volatile int j; } u; }; 2329 // are not (obviously) initializable like so: 2330 // __attribute__((__require_constant_initialization__)) 2331 // static const foo_t x = {{0}}; 2332 // because "i" is a subobject with non-literal initialization (due to the 2333 // volatile member of the union). See: 2334 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2335 // Therefore, we use the C++1y behavior. 2336 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2337 return true; 2338 2339 // Prvalue constant expressions must be of literal types. 2340 if (Info.getLangOpts().CPlusPlus11) 2341 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2342 << E->getType(); 2343 else 2344 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2345 return false; 2346 } 2347 2348 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2349 EvalInfo &Info, SourceLocation DiagLoc, 2350 QualType Type, const APValue &Value, 2351 ConstantExprKind Kind, 2352 SourceLocation SubobjectLoc, 2353 CheckedTemporaries &CheckedTemps) { 2354 if (!Value.hasValue()) { 2355 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2356 << true << Type; 2357 if (SubobjectLoc.isValid()) 2358 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2359 return false; 2360 } 2361 2362 // We allow _Atomic(T) to be initialized from anything that T can be 2363 // initialized from. 2364 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2365 Type = AT->getValueType(); 2366 2367 // Core issue 1454: For a literal constant expression of array or class type, 2368 // each subobject of its value shall have been initialized by a constant 2369 // expression. 2370 if (Value.isArray()) { 2371 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2372 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2373 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2374 Value.getArrayInitializedElt(I), Kind, 2375 SubobjectLoc, CheckedTemps)) 2376 return false; 2377 } 2378 if (!Value.hasArrayFiller()) 2379 return true; 2380 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2381 Value.getArrayFiller(), Kind, SubobjectLoc, 2382 CheckedTemps); 2383 } 2384 if (Value.isUnion() && Value.getUnionField()) { 2385 return CheckEvaluationResult( 2386 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2387 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2388 CheckedTemps); 2389 } 2390 if (Value.isStruct()) { 2391 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2392 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2393 unsigned BaseIndex = 0; 2394 for (const CXXBaseSpecifier &BS : CD->bases()) { 2395 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2396 Value.getStructBase(BaseIndex), Kind, 2397 BS.getBeginLoc(), CheckedTemps)) 2398 return false; 2399 ++BaseIndex; 2400 } 2401 } 2402 for (const auto *I : RD->fields()) { 2403 if (I->isUnnamedBitfield()) 2404 continue; 2405 2406 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2407 Value.getStructField(I->getFieldIndex()), 2408 Kind, I->getLocation(), CheckedTemps)) 2409 return false; 2410 } 2411 } 2412 2413 if (Value.isLValue() && 2414 CERK == CheckEvaluationResultKind::ConstantExpression) { 2415 LValue LVal; 2416 LVal.setFrom(Info.Ctx, Value); 2417 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2418 CheckedTemps); 2419 } 2420 2421 if (Value.isMemberPointer() && 2422 CERK == CheckEvaluationResultKind::ConstantExpression) 2423 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2424 2425 // Everything else is fine. 2426 return true; 2427 } 2428 2429 /// Check that this core constant expression value is a valid value for a 2430 /// constant expression. If not, report an appropriate diagnostic. Does not 2431 /// check that the expression is of literal type. 2432 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2433 QualType Type, const APValue &Value, 2434 ConstantExprKind Kind) { 2435 // Nothing to check for a constant expression of type 'cv void'. 2436 if (Type->isVoidType()) 2437 return true; 2438 2439 CheckedTemporaries CheckedTemps; 2440 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2441 Info, DiagLoc, Type, Value, Kind, 2442 SourceLocation(), CheckedTemps); 2443 } 2444 2445 /// Check that this evaluated value is fully-initialized and can be loaded by 2446 /// an lvalue-to-rvalue conversion. 2447 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2448 QualType Type, const APValue &Value) { 2449 CheckedTemporaries CheckedTemps; 2450 return CheckEvaluationResult( 2451 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2452 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2453 } 2454 2455 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2456 /// "the allocated storage is deallocated within the evaluation". 2457 static bool CheckMemoryLeaks(EvalInfo &Info) { 2458 if (!Info.HeapAllocs.empty()) { 2459 // We can still fold to a constant despite a compile-time memory leak, 2460 // so long as the heap allocation isn't referenced in the result (we check 2461 // that in CheckConstantExpression). 2462 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2463 diag::note_constexpr_memory_leak) 2464 << unsigned(Info.HeapAllocs.size() - 1); 2465 } 2466 return true; 2467 } 2468 2469 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2470 // A null base expression indicates a null pointer. These are always 2471 // evaluatable, and they are false unless the offset is zero. 2472 if (!Value.getLValueBase()) { 2473 Result = !Value.getLValueOffset().isZero(); 2474 return true; 2475 } 2476 2477 // We have a non-null base. These are generally known to be true, but if it's 2478 // a weak declaration it can be null at runtime. 2479 Result = true; 2480 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2481 return !Decl || !Decl->isWeak(); 2482 } 2483 2484 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2485 switch (Val.getKind()) { 2486 case APValue::None: 2487 case APValue::Indeterminate: 2488 return false; 2489 case APValue::Int: 2490 Result = Val.getInt().getBoolValue(); 2491 return true; 2492 case APValue::FixedPoint: 2493 Result = Val.getFixedPoint().getBoolValue(); 2494 return true; 2495 case APValue::Float: 2496 Result = !Val.getFloat().isZero(); 2497 return true; 2498 case APValue::ComplexInt: 2499 Result = Val.getComplexIntReal().getBoolValue() || 2500 Val.getComplexIntImag().getBoolValue(); 2501 return true; 2502 case APValue::ComplexFloat: 2503 Result = !Val.getComplexFloatReal().isZero() || 2504 !Val.getComplexFloatImag().isZero(); 2505 return true; 2506 case APValue::LValue: 2507 return EvalPointerValueAsBool(Val, Result); 2508 case APValue::MemberPointer: 2509 Result = Val.getMemberPointerDecl(); 2510 return true; 2511 case APValue::Vector: 2512 case APValue::Array: 2513 case APValue::Struct: 2514 case APValue::Union: 2515 case APValue::AddrLabelDiff: 2516 return false; 2517 } 2518 2519 llvm_unreachable("unknown APValue kind"); 2520 } 2521 2522 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2523 EvalInfo &Info) { 2524 assert(!E->isValueDependent()); 2525 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2526 APValue Val; 2527 if (!Evaluate(Val, Info, E)) 2528 return false; 2529 return HandleConversionToBool(Val, Result); 2530 } 2531 2532 template<typename T> 2533 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2534 const T &SrcValue, QualType DestType) { 2535 Info.CCEDiag(E, diag::note_constexpr_overflow) 2536 << SrcValue << DestType; 2537 return Info.noteUndefinedBehavior(); 2538 } 2539 2540 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2541 QualType SrcType, const APFloat &Value, 2542 QualType DestType, APSInt &Result) { 2543 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2544 // Determine whether we are converting to unsigned or signed. 2545 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2546 2547 Result = APSInt(DestWidth, !DestSigned); 2548 bool ignored; 2549 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2550 & APFloat::opInvalidOp) 2551 return HandleOverflow(Info, E, Value, DestType); 2552 return true; 2553 } 2554 2555 /// Get rounding mode used for evaluation of the specified expression. 2556 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2557 /// dynamic. 2558 /// If rounding mode is unknown at compile time, still try to evaluate the 2559 /// expression. If the result is exact, it does not depend on rounding mode. 2560 /// So return "tonearest" mode instead of "dynamic". 2561 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2562 bool &DynamicRM) { 2563 llvm::RoundingMode RM = 2564 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2565 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2566 if (DynamicRM) 2567 RM = llvm::RoundingMode::NearestTiesToEven; 2568 return RM; 2569 } 2570 2571 /// Check if the given evaluation result is allowed for constant evaluation. 2572 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2573 APFloat::opStatus St) { 2574 // In a constant context, assume that any dynamic rounding mode or FP 2575 // exception state matches the default floating-point environment. 2576 if (Info.InConstantContext) 2577 return true; 2578 2579 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2580 if ((St & APFloat::opInexact) && 2581 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2582 // Inexact result means that it depends on rounding mode. If the requested 2583 // mode is dynamic, the evaluation cannot be made in compile time. 2584 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2585 return false; 2586 } 2587 2588 if ((St != APFloat::opOK) && 2589 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2590 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2591 FPO.getAllowFEnvAccess())) { 2592 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2593 return false; 2594 } 2595 2596 if ((St & APFloat::opStatus::opInvalidOp) && 2597 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2598 // There is no usefully definable result. 2599 Info.FFDiag(E); 2600 return false; 2601 } 2602 2603 // FIXME: if: 2604 // - evaluation triggered other FP exception, and 2605 // - exception mode is not "ignore", and 2606 // - the expression being evaluated is not a part of global variable 2607 // initializer, 2608 // the evaluation probably need to be rejected. 2609 return true; 2610 } 2611 2612 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2613 QualType SrcType, QualType DestType, 2614 APFloat &Result) { 2615 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2616 bool DynamicRM; 2617 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2618 APFloat::opStatus St; 2619 APFloat Value = Result; 2620 bool ignored; 2621 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2622 return checkFloatingPointResult(Info, E, St); 2623 } 2624 2625 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2626 QualType DestType, QualType SrcType, 2627 const APSInt &Value) { 2628 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2629 // Figure out if this is a truncate, extend or noop cast. 2630 // If the input is signed, do a sign extend, noop, or truncate. 2631 APSInt Result = Value.extOrTrunc(DestWidth); 2632 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2633 if (DestType->isBooleanType()) 2634 Result = Value.getBoolValue(); 2635 return Result; 2636 } 2637 2638 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2639 const FPOptions FPO, 2640 QualType SrcType, const APSInt &Value, 2641 QualType DestType, APFloat &Result) { 2642 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2643 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2644 APFloat::rmNearestTiesToEven); 2645 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2646 FPO.isFPConstrained()) { 2647 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2648 return false; 2649 } 2650 return true; 2651 } 2652 2653 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2654 APValue &Value, const FieldDecl *FD) { 2655 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2656 2657 if (!Value.isInt()) { 2658 // Trying to store a pointer-cast-to-integer into a bitfield. 2659 // FIXME: In this case, we should provide the diagnostic for casting 2660 // a pointer to an integer. 2661 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2662 Info.FFDiag(E); 2663 return false; 2664 } 2665 2666 APSInt &Int = Value.getInt(); 2667 unsigned OldBitWidth = Int.getBitWidth(); 2668 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2669 if (NewBitWidth < OldBitWidth) 2670 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2671 return true; 2672 } 2673 2674 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2675 llvm::APInt &Res) { 2676 APValue SVal; 2677 if (!Evaluate(SVal, Info, E)) 2678 return false; 2679 if (SVal.isInt()) { 2680 Res = SVal.getInt(); 2681 return true; 2682 } 2683 if (SVal.isFloat()) { 2684 Res = SVal.getFloat().bitcastToAPInt(); 2685 return true; 2686 } 2687 if (SVal.isVector()) { 2688 QualType VecTy = E->getType(); 2689 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2690 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2691 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2692 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2693 Res = llvm::APInt::getZero(VecSize); 2694 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2695 APValue &Elt = SVal.getVectorElt(i); 2696 llvm::APInt EltAsInt; 2697 if (Elt.isInt()) { 2698 EltAsInt = Elt.getInt(); 2699 } else if (Elt.isFloat()) { 2700 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2701 } else { 2702 // Don't try to handle vectors of anything other than int or float 2703 // (not sure if it's possible to hit this case). 2704 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2705 return false; 2706 } 2707 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2708 if (BigEndian) 2709 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2710 else 2711 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2712 } 2713 return true; 2714 } 2715 // Give up if the input isn't an int, float, or vector. For example, we 2716 // reject "(v4i16)(intptr_t)&a". 2717 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2718 return false; 2719 } 2720 2721 /// Perform the given integer operation, which is known to need at most BitWidth 2722 /// bits, and check for overflow in the original type (if that type was not an 2723 /// unsigned type). 2724 template<typename Operation> 2725 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2726 const APSInt &LHS, const APSInt &RHS, 2727 unsigned BitWidth, Operation Op, 2728 APSInt &Result) { 2729 if (LHS.isUnsigned()) { 2730 Result = Op(LHS, RHS); 2731 return true; 2732 } 2733 2734 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2735 Result = Value.trunc(LHS.getBitWidth()); 2736 if (Result.extend(BitWidth) != Value) { 2737 if (Info.checkingForUndefinedBehavior()) 2738 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2739 diag::warn_integer_constant_overflow) 2740 << toString(Result, 10) << E->getType(); 2741 return HandleOverflow(Info, E, Value, E->getType()); 2742 } 2743 return true; 2744 } 2745 2746 /// Perform the given binary integer operation. 2747 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2748 BinaryOperatorKind Opcode, APSInt RHS, 2749 APSInt &Result) { 2750 switch (Opcode) { 2751 default: 2752 Info.FFDiag(E); 2753 return false; 2754 case BO_Mul: 2755 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2756 std::multiplies<APSInt>(), Result); 2757 case BO_Add: 2758 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2759 std::plus<APSInt>(), Result); 2760 case BO_Sub: 2761 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2762 std::minus<APSInt>(), Result); 2763 case BO_And: Result = LHS & RHS; return true; 2764 case BO_Xor: Result = LHS ^ RHS; return true; 2765 case BO_Or: Result = LHS | RHS; return true; 2766 case BO_Div: 2767 case BO_Rem: 2768 if (RHS == 0) { 2769 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2770 return false; 2771 } 2772 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2773 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2774 // this operation and gives the two's complement result. 2775 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && 2776 LHS.isMinSignedValue()) 2777 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2778 E->getType()); 2779 return true; 2780 case BO_Shl: { 2781 if (Info.getLangOpts().OpenCL) 2782 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2783 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2784 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2785 RHS.isUnsigned()); 2786 else if (RHS.isSigned() && RHS.isNegative()) { 2787 // During constant-folding, a negative shift is an opposite shift. Such 2788 // a shift is not a constant expression. 2789 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2790 RHS = -RHS; 2791 goto shift_right; 2792 } 2793 shift_left: 2794 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2795 // the shifted type. 2796 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2797 if (SA != RHS) { 2798 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2799 << RHS << E->getType() << LHS.getBitWidth(); 2800 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2801 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2802 // operand, and must not overflow the corresponding unsigned type. 2803 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2804 // E1 x 2^E2 module 2^N. 2805 if (LHS.isNegative()) 2806 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2807 else if (LHS.countLeadingZeros() < SA) 2808 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2809 } 2810 Result = LHS << SA; 2811 return true; 2812 } 2813 case BO_Shr: { 2814 if (Info.getLangOpts().OpenCL) 2815 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2816 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2817 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2818 RHS.isUnsigned()); 2819 else if (RHS.isSigned() && RHS.isNegative()) { 2820 // During constant-folding, a negative shift is an opposite shift. Such a 2821 // shift is not a constant expression. 2822 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2823 RHS = -RHS; 2824 goto shift_left; 2825 } 2826 shift_right: 2827 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2828 // shifted type. 2829 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2830 if (SA != RHS) 2831 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2832 << RHS << E->getType() << LHS.getBitWidth(); 2833 Result = LHS >> SA; 2834 return true; 2835 } 2836 2837 case BO_LT: Result = LHS < RHS; return true; 2838 case BO_GT: Result = LHS > RHS; return true; 2839 case BO_LE: Result = LHS <= RHS; return true; 2840 case BO_GE: Result = LHS >= RHS; return true; 2841 case BO_EQ: Result = LHS == RHS; return true; 2842 case BO_NE: Result = LHS != RHS; return true; 2843 case BO_Cmp: 2844 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2845 } 2846 } 2847 2848 /// Perform the given binary floating-point operation, in-place, on LHS. 2849 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2850 APFloat &LHS, BinaryOperatorKind Opcode, 2851 const APFloat &RHS) { 2852 bool DynamicRM; 2853 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2854 APFloat::opStatus St; 2855 switch (Opcode) { 2856 default: 2857 Info.FFDiag(E); 2858 return false; 2859 case BO_Mul: 2860 St = LHS.multiply(RHS, RM); 2861 break; 2862 case BO_Add: 2863 St = LHS.add(RHS, RM); 2864 break; 2865 case BO_Sub: 2866 St = LHS.subtract(RHS, RM); 2867 break; 2868 case BO_Div: 2869 // [expr.mul]p4: 2870 // If the second operand of / or % is zero the behavior is undefined. 2871 if (RHS.isZero()) 2872 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2873 St = LHS.divide(RHS, RM); 2874 break; 2875 } 2876 2877 // [expr.pre]p4: 2878 // If during the evaluation of an expression, the result is not 2879 // mathematically defined [...], the behavior is undefined. 2880 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2881 if (LHS.isNaN()) { 2882 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2883 return Info.noteUndefinedBehavior(); 2884 } 2885 2886 return checkFloatingPointResult(Info, E, St); 2887 } 2888 2889 static bool handleLogicalOpForVector(const APInt &LHSValue, 2890 BinaryOperatorKind Opcode, 2891 const APInt &RHSValue, APInt &Result) { 2892 bool LHS = (LHSValue != 0); 2893 bool RHS = (RHSValue != 0); 2894 2895 if (Opcode == BO_LAnd) 2896 Result = LHS && RHS; 2897 else 2898 Result = LHS || RHS; 2899 return true; 2900 } 2901 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2902 BinaryOperatorKind Opcode, 2903 const APFloat &RHSValue, APInt &Result) { 2904 bool LHS = !LHSValue.isZero(); 2905 bool RHS = !RHSValue.isZero(); 2906 2907 if (Opcode == BO_LAnd) 2908 Result = LHS && RHS; 2909 else 2910 Result = LHS || RHS; 2911 return true; 2912 } 2913 2914 static bool handleLogicalOpForVector(const APValue &LHSValue, 2915 BinaryOperatorKind Opcode, 2916 const APValue &RHSValue, APInt &Result) { 2917 // The result is always an int type, however operands match the first. 2918 if (LHSValue.getKind() == APValue::Int) 2919 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2920 RHSValue.getInt(), Result); 2921 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2922 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2923 RHSValue.getFloat(), Result); 2924 } 2925 2926 template <typename APTy> 2927 static bool 2928 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2929 const APTy &RHSValue, APInt &Result) { 2930 switch (Opcode) { 2931 default: 2932 llvm_unreachable("unsupported binary operator"); 2933 case BO_EQ: 2934 Result = (LHSValue == RHSValue); 2935 break; 2936 case BO_NE: 2937 Result = (LHSValue != RHSValue); 2938 break; 2939 case BO_LT: 2940 Result = (LHSValue < RHSValue); 2941 break; 2942 case BO_GT: 2943 Result = (LHSValue > RHSValue); 2944 break; 2945 case BO_LE: 2946 Result = (LHSValue <= RHSValue); 2947 break; 2948 case BO_GE: 2949 Result = (LHSValue >= RHSValue); 2950 break; 2951 } 2952 2953 // The boolean operations on these vector types use an instruction that 2954 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 2955 // to -1 to make sure that we produce the correct value. 2956 Result.negate(); 2957 2958 return true; 2959 } 2960 2961 static bool handleCompareOpForVector(const APValue &LHSValue, 2962 BinaryOperatorKind Opcode, 2963 const APValue &RHSValue, APInt &Result) { 2964 // The result is always an int type, however operands match the first. 2965 if (LHSValue.getKind() == APValue::Int) 2966 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2967 RHSValue.getInt(), Result); 2968 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2969 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2970 RHSValue.getFloat(), Result); 2971 } 2972 2973 // Perform binary operations for vector types, in place on the LHS. 2974 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2975 BinaryOperatorKind Opcode, 2976 APValue &LHSValue, 2977 const APValue &RHSValue) { 2978 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2979 "Operation not supported on vector types"); 2980 2981 const auto *VT = E->getType()->castAs<VectorType>(); 2982 unsigned NumElements = VT->getNumElements(); 2983 QualType EltTy = VT->getElementType(); 2984 2985 // In the cases (typically C as I've observed) where we aren't evaluating 2986 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2987 // just give up. 2988 if (!LHSValue.isVector()) { 2989 assert(LHSValue.isLValue() && 2990 "A vector result that isn't a vector OR uncalculated LValue"); 2991 Info.FFDiag(E); 2992 return false; 2993 } 2994 2995 assert(LHSValue.getVectorLength() == NumElements && 2996 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2997 2998 SmallVector<APValue, 4> ResultElements; 2999 3000 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 3001 APValue LHSElt = LHSValue.getVectorElt(EltNum); 3002 APValue RHSElt = RHSValue.getVectorElt(EltNum); 3003 3004 if (EltTy->isIntegerType()) { 3005 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 3006 EltTy->isUnsignedIntegerType()}; 3007 bool Success = true; 3008 3009 if (BinaryOperator::isLogicalOp(Opcode)) 3010 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3011 else if (BinaryOperator::isComparisonOp(Opcode)) 3012 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3013 else 3014 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 3015 RHSElt.getInt(), EltResult); 3016 3017 if (!Success) { 3018 Info.FFDiag(E); 3019 return false; 3020 } 3021 ResultElements.emplace_back(EltResult); 3022 3023 } else if (EltTy->isFloatingType()) { 3024 assert(LHSElt.getKind() == APValue::Float && 3025 RHSElt.getKind() == APValue::Float && 3026 "Mismatched LHS/RHS/Result Type"); 3027 APFloat LHSFloat = LHSElt.getFloat(); 3028 3029 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3030 RHSElt.getFloat())) { 3031 Info.FFDiag(E); 3032 return false; 3033 } 3034 3035 ResultElements.emplace_back(LHSFloat); 3036 } 3037 } 3038 3039 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3040 return true; 3041 } 3042 3043 /// Cast an lvalue referring to a base subobject to a derived class, by 3044 /// truncating the lvalue's path to the given length. 3045 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3046 const RecordDecl *TruncatedType, 3047 unsigned TruncatedElements) { 3048 SubobjectDesignator &D = Result.Designator; 3049 3050 // Check we actually point to a derived class object. 3051 if (TruncatedElements == D.Entries.size()) 3052 return true; 3053 assert(TruncatedElements >= D.MostDerivedPathLength && 3054 "not casting to a derived class"); 3055 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3056 return false; 3057 3058 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3059 const RecordDecl *RD = TruncatedType; 3060 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3061 if (RD->isInvalidDecl()) return false; 3062 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3063 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3064 if (isVirtualBaseClass(D.Entries[I])) 3065 Result.Offset -= Layout.getVBaseClassOffset(Base); 3066 else 3067 Result.Offset -= Layout.getBaseClassOffset(Base); 3068 RD = Base; 3069 } 3070 D.Entries.resize(TruncatedElements); 3071 return true; 3072 } 3073 3074 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3075 const CXXRecordDecl *Derived, 3076 const CXXRecordDecl *Base, 3077 const ASTRecordLayout *RL = nullptr) { 3078 if (!RL) { 3079 if (Derived->isInvalidDecl()) return false; 3080 RL = &Info.Ctx.getASTRecordLayout(Derived); 3081 } 3082 3083 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3084 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3085 return true; 3086 } 3087 3088 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3089 const CXXRecordDecl *DerivedDecl, 3090 const CXXBaseSpecifier *Base) { 3091 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3092 3093 if (!Base->isVirtual()) 3094 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3095 3096 SubobjectDesignator &D = Obj.Designator; 3097 if (D.Invalid) 3098 return false; 3099 3100 // Extract most-derived object and corresponding type. 3101 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3102 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3103 return false; 3104 3105 // Find the virtual base class. 3106 if (DerivedDecl->isInvalidDecl()) return false; 3107 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3108 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3109 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3110 return true; 3111 } 3112 3113 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3114 QualType Type, LValue &Result) { 3115 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3116 PathE = E->path_end(); 3117 PathI != PathE; ++PathI) { 3118 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3119 *PathI)) 3120 return false; 3121 Type = (*PathI)->getType(); 3122 } 3123 return true; 3124 } 3125 3126 /// Cast an lvalue referring to a derived class to a known base subobject. 3127 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3128 const CXXRecordDecl *DerivedRD, 3129 const CXXRecordDecl *BaseRD) { 3130 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3131 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3132 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3133 llvm_unreachable("Class must be derived from the passed in base class!"); 3134 3135 for (CXXBasePathElement &Elem : Paths.front()) 3136 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3137 return false; 3138 return true; 3139 } 3140 3141 /// Update LVal to refer to the given field, which must be a member of the type 3142 /// currently described by LVal. 3143 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3144 const FieldDecl *FD, 3145 const ASTRecordLayout *RL = nullptr) { 3146 if (!RL) { 3147 if (FD->getParent()->isInvalidDecl()) return false; 3148 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3149 } 3150 3151 unsigned I = FD->getFieldIndex(); 3152 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3153 LVal.addDecl(Info, E, FD); 3154 return true; 3155 } 3156 3157 /// Update LVal to refer to the given indirect field. 3158 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3159 LValue &LVal, 3160 const IndirectFieldDecl *IFD) { 3161 for (const auto *C : IFD->chain()) 3162 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3163 return false; 3164 return true; 3165 } 3166 3167 /// Get the size of the given type in char units. 3168 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3169 QualType Type, CharUnits &Size) { 3170 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3171 // extension. 3172 if (Type->isVoidType() || Type->isFunctionType()) { 3173 Size = CharUnits::One(); 3174 return true; 3175 } 3176 3177 if (Type->isDependentType()) { 3178 Info.FFDiag(Loc); 3179 return false; 3180 } 3181 3182 if (!Type->isConstantSizeType()) { 3183 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3184 // FIXME: Better diagnostic. 3185 Info.FFDiag(Loc); 3186 return false; 3187 } 3188 3189 Size = Info.Ctx.getTypeSizeInChars(Type); 3190 return true; 3191 } 3192 3193 /// Update a pointer value to model pointer arithmetic. 3194 /// \param Info - Information about the ongoing evaluation. 3195 /// \param E - The expression being evaluated, for diagnostic purposes. 3196 /// \param LVal - The pointer value to be updated. 3197 /// \param EltTy - The pointee type represented by LVal. 3198 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3199 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3200 LValue &LVal, QualType EltTy, 3201 APSInt Adjustment) { 3202 CharUnits SizeOfPointee; 3203 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3204 return false; 3205 3206 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3207 return true; 3208 } 3209 3210 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3211 LValue &LVal, QualType EltTy, 3212 int64_t Adjustment) { 3213 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3214 APSInt::get(Adjustment)); 3215 } 3216 3217 /// Update an lvalue to refer to a component of a complex number. 3218 /// \param Info - Information about the ongoing evaluation. 3219 /// \param LVal - The lvalue to be updated. 3220 /// \param EltTy - The complex number's component type. 3221 /// \param Imag - False for the real component, true for the imaginary. 3222 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3223 LValue &LVal, QualType EltTy, 3224 bool Imag) { 3225 if (Imag) { 3226 CharUnits SizeOfComponent; 3227 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3228 return false; 3229 LVal.Offset += SizeOfComponent; 3230 } 3231 LVal.addComplex(Info, E, EltTy, Imag); 3232 return true; 3233 } 3234 3235 /// Try to evaluate the initializer for a variable declaration. 3236 /// 3237 /// \param Info Information about the ongoing evaluation. 3238 /// \param E An expression to be used when printing diagnostics. 3239 /// \param VD The variable whose initializer should be obtained. 3240 /// \param Version The version of the variable within the frame. 3241 /// \param Frame The frame in which the variable was created. Must be null 3242 /// if this variable is not local to the evaluation. 3243 /// \param Result Filled in with a pointer to the value of the variable. 3244 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3245 const VarDecl *VD, CallStackFrame *Frame, 3246 unsigned Version, APValue *&Result) { 3247 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3248 3249 // If this is a local variable, dig out its value. 3250 if (Frame) { 3251 Result = Frame->getTemporary(VD, Version); 3252 if (Result) 3253 return true; 3254 3255 if (!isa<ParmVarDecl>(VD)) { 3256 // Assume variables referenced within a lambda's call operator that were 3257 // not declared within the call operator are captures and during checking 3258 // of a potential constant expression, assume they are unknown constant 3259 // expressions. 3260 assert(isLambdaCallOperator(Frame->Callee) && 3261 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3262 "missing value for local variable"); 3263 if (Info.checkingPotentialConstantExpression()) 3264 return false; 3265 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3266 // still reachable at all? 3267 Info.FFDiag(E->getBeginLoc(), 3268 diag::note_unimplemented_constexpr_lambda_feature_ast) 3269 << "captures not currently allowed"; 3270 return false; 3271 } 3272 } 3273 3274 // If we're currently evaluating the initializer of this declaration, use that 3275 // in-flight value. 3276 if (Info.EvaluatingDecl == Base) { 3277 Result = Info.EvaluatingDeclValue; 3278 return true; 3279 } 3280 3281 if (isa<ParmVarDecl>(VD)) { 3282 // Assume parameters of a potential constant expression are usable in 3283 // constant expressions. 3284 if (!Info.checkingPotentialConstantExpression() || 3285 !Info.CurrentCall->Callee || 3286 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3287 if (Info.getLangOpts().CPlusPlus11) { 3288 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3289 << VD; 3290 NoteLValueLocation(Info, Base); 3291 } else { 3292 Info.FFDiag(E); 3293 } 3294 } 3295 return false; 3296 } 3297 3298 // Dig out the initializer, and use the declaration which it's attached to. 3299 // FIXME: We should eventually check whether the variable has a reachable 3300 // initializing declaration. 3301 const Expr *Init = VD->getAnyInitializer(VD); 3302 if (!Init) { 3303 // Don't diagnose during potential constant expression checking; an 3304 // initializer might be added later. 3305 if (!Info.checkingPotentialConstantExpression()) { 3306 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3307 << VD; 3308 NoteLValueLocation(Info, Base); 3309 } 3310 return false; 3311 } 3312 3313 if (Init->isValueDependent()) { 3314 // The DeclRefExpr is not value-dependent, but the variable it refers to 3315 // has a value-dependent initializer. This should only happen in 3316 // constant-folding cases, where the variable is not actually of a suitable 3317 // type for use in a constant expression (otherwise the DeclRefExpr would 3318 // have been value-dependent too), so diagnose that. 3319 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3320 if (!Info.checkingPotentialConstantExpression()) { 3321 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3322 ? diag::note_constexpr_ltor_non_constexpr 3323 : diag::note_constexpr_ltor_non_integral, 1) 3324 << VD << VD->getType(); 3325 NoteLValueLocation(Info, Base); 3326 } 3327 return false; 3328 } 3329 3330 // Check that we can fold the initializer. In C++, we will have already done 3331 // this in the cases where it matters for conformance. 3332 if (!VD->evaluateValue()) { 3333 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3334 NoteLValueLocation(Info, Base); 3335 return false; 3336 } 3337 3338 // Check that the variable is actually usable in constant expressions. For a 3339 // const integral variable or a reference, we might have a non-constant 3340 // initializer that we can nonetheless evaluate the initializer for. Such 3341 // variables are not usable in constant expressions. In C++98, the 3342 // initializer also syntactically needs to be an ICE. 3343 // 3344 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3345 // expressions here; doing so would regress diagnostics for things like 3346 // reading from a volatile constexpr variable. 3347 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3348 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3349 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3350 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3351 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3352 NoteLValueLocation(Info, Base); 3353 } 3354 3355 // Never use the initializer of a weak variable, not even for constant 3356 // folding. We can't be sure that this is the definition that will be used. 3357 if (VD->isWeak()) { 3358 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3359 NoteLValueLocation(Info, Base); 3360 return false; 3361 } 3362 3363 Result = VD->getEvaluatedValue(); 3364 return true; 3365 } 3366 3367 /// Get the base index of the given base class within an APValue representing 3368 /// the given derived class. 3369 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3370 const CXXRecordDecl *Base) { 3371 Base = Base->getCanonicalDecl(); 3372 unsigned Index = 0; 3373 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3374 E = Derived->bases_end(); I != E; ++I, ++Index) { 3375 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3376 return Index; 3377 } 3378 3379 llvm_unreachable("base class missing from derived class's bases list"); 3380 } 3381 3382 /// Extract the value of a character from a string literal. 3383 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3384 uint64_t Index) { 3385 assert(!isa<SourceLocExpr>(Lit) && 3386 "SourceLocExpr should have already been converted to a StringLiteral"); 3387 3388 // FIXME: Support MakeStringConstant 3389 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3390 std::string Str; 3391 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3392 assert(Index <= Str.size() && "Index too large"); 3393 return APSInt::getUnsigned(Str.c_str()[Index]); 3394 } 3395 3396 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3397 Lit = PE->getFunctionName(); 3398 const StringLiteral *S = cast<StringLiteral>(Lit); 3399 const ConstantArrayType *CAT = 3400 Info.Ctx.getAsConstantArrayType(S->getType()); 3401 assert(CAT && "string literal isn't an array"); 3402 QualType CharType = CAT->getElementType(); 3403 assert(CharType->isIntegerType() && "unexpected character type"); 3404 3405 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3406 CharType->isUnsignedIntegerType()); 3407 if (Index < S->getLength()) 3408 Value = S->getCodeUnit(Index); 3409 return Value; 3410 } 3411 3412 // Expand a string literal into an array of characters. 3413 // 3414 // FIXME: This is inefficient; we should probably introduce something similar 3415 // to the LLVM ConstantDataArray to make this cheaper. 3416 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3417 APValue &Result, 3418 QualType AllocType = QualType()) { 3419 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3420 AllocType.isNull() ? S->getType() : AllocType); 3421 assert(CAT && "string literal isn't an array"); 3422 QualType CharType = CAT->getElementType(); 3423 assert(CharType->isIntegerType() && "unexpected character type"); 3424 3425 unsigned Elts = CAT->getSize().getZExtValue(); 3426 Result = APValue(APValue::UninitArray(), 3427 std::min(S->getLength(), Elts), Elts); 3428 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3429 CharType->isUnsignedIntegerType()); 3430 if (Result.hasArrayFiller()) 3431 Result.getArrayFiller() = APValue(Value); 3432 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3433 Value = S->getCodeUnit(I); 3434 Result.getArrayInitializedElt(I) = APValue(Value); 3435 } 3436 } 3437 3438 // Expand an array so that it has more than Index filled elements. 3439 static void expandArray(APValue &Array, unsigned Index) { 3440 unsigned Size = Array.getArraySize(); 3441 assert(Index < Size); 3442 3443 // Always at least double the number of elements for which we store a value. 3444 unsigned OldElts = Array.getArrayInitializedElts(); 3445 unsigned NewElts = std::max(Index+1, OldElts * 2); 3446 NewElts = std::min(Size, std::max(NewElts, 8u)); 3447 3448 // Copy the data across. 3449 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3450 for (unsigned I = 0; I != OldElts; ++I) 3451 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3452 for (unsigned I = OldElts; I != NewElts; ++I) 3453 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3454 if (NewValue.hasArrayFiller()) 3455 NewValue.getArrayFiller() = Array.getArrayFiller(); 3456 Array.swap(NewValue); 3457 } 3458 3459 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3460 /// conversion. If it's of class type, we may assume that the copy operation 3461 /// is trivial. Note that this is never true for a union type with fields 3462 /// (because the copy always "reads" the active member) and always true for 3463 /// a non-class type. 3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3465 static bool isReadByLvalueToRvalueConversion(QualType T) { 3466 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3467 return !RD || isReadByLvalueToRvalueConversion(RD); 3468 } 3469 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3470 // FIXME: A trivial copy of a union copies the object representation, even if 3471 // the union is empty. 3472 if (RD->isUnion()) 3473 return !RD->field_empty(); 3474 if (RD->isEmpty()) 3475 return false; 3476 3477 for (auto *Field : RD->fields()) 3478 if (!Field->isUnnamedBitfield() && 3479 isReadByLvalueToRvalueConversion(Field->getType())) 3480 return true; 3481 3482 for (auto &BaseSpec : RD->bases()) 3483 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3484 return true; 3485 3486 return false; 3487 } 3488 3489 /// Diagnose an attempt to read from any unreadable field within the specified 3490 /// type, which might be a class type. 3491 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3492 QualType T) { 3493 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3494 if (!RD) 3495 return false; 3496 3497 if (!RD->hasMutableFields()) 3498 return false; 3499 3500 for (auto *Field : RD->fields()) { 3501 // If we're actually going to read this field in some way, then it can't 3502 // be mutable. If we're in a union, then assigning to a mutable field 3503 // (even an empty one) can change the active member, so that's not OK. 3504 // FIXME: Add core issue number for the union case. 3505 if (Field->isMutable() && 3506 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3507 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3508 Info.Note(Field->getLocation(), diag::note_declared_at); 3509 return true; 3510 } 3511 3512 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3513 return true; 3514 } 3515 3516 for (auto &BaseSpec : RD->bases()) 3517 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3518 return true; 3519 3520 // All mutable fields were empty, and thus not actually read. 3521 return false; 3522 } 3523 3524 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3525 APValue::LValueBase Base, 3526 bool MutableSubobject = false) { 3527 // A temporary or transient heap allocation we created. 3528 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3529 return true; 3530 3531 switch (Info.IsEvaluatingDecl) { 3532 case EvalInfo::EvaluatingDeclKind::None: 3533 return false; 3534 3535 case EvalInfo::EvaluatingDeclKind::Ctor: 3536 // The variable whose initializer we're evaluating. 3537 if (Info.EvaluatingDecl == Base) 3538 return true; 3539 3540 // A temporary lifetime-extended by the variable whose initializer we're 3541 // evaluating. 3542 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3543 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3544 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3545 return false; 3546 3547 case EvalInfo::EvaluatingDeclKind::Dtor: 3548 // C++2a [expr.const]p6: 3549 // [during constant destruction] the lifetime of a and its non-mutable 3550 // subobjects (but not its mutable subobjects) [are] considered to start 3551 // within e. 3552 if (MutableSubobject || Base != Info.EvaluatingDecl) 3553 return false; 3554 // FIXME: We can meaningfully extend this to cover non-const objects, but 3555 // we will need special handling: we should be able to access only 3556 // subobjects of such objects that are themselves declared const. 3557 QualType T = getType(Base); 3558 return T.isConstQualified() || T->isReferenceType(); 3559 } 3560 3561 llvm_unreachable("unknown evaluating decl kind"); 3562 } 3563 3564 namespace { 3565 /// A handle to a complete object (an object that is not a subobject of 3566 /// another object). 3567 struct CompleteObject { 3568 /// The identity of the object. 3569 APValue::LValueBase Base; 3570 /// The value of the complete object. 3571 APValue *Value; 3572 /// The type of the complete object. 3573 QualType Type; 3574 3575 CompleteObject() : Value(nullptr) {} 3576 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3577 : Base(Base), Value(Value), Type(Type) {} 3578 3579 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3580 // If this isn't a "real" access (eg, if it's just accessing the type 3581 // info), allow it. We assume the type doesn't change dynamically for 3582 // subobjects of constexpr objects (even though we'd hit UB here if it 3583 // did). FIXME: Is this right? 3584 if (!isAnyAccess(AK)) 3585 return true; 3586 3587 // In C++14 onwards, it is permitted to read a mutable member whose 3588 // lifetime began within the evaluation. 3589 // FIXME: Should we also allow this in C++11? 3590 if (!Info.getLangOpts().CPlusPlus14) 3591 return false; 3592 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3593 } 3594 3595 explicit operator bool() const { return !Type.isNull(); } 3596 }; 3597 } // end anonymous namespace 3598 3599 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3600 bool IsMutable = false) { 3601 // C++ [basic.type.qualifier]p1: 3602 // - A const object is an object of type const T or a non-mutable subobject 3603 // of a const object. 3604 if (ObjType.isConstQualified() && !IsMutable) 3605 SubobjType.addConst(); 3606 // - A volatile object is an object of type const T or a subobject of a 3607 // volatile object. 3608 if (ObjType.isVolatileQualified()) 3609 SubobjType.addVolatile(); 3610 return SubobjType; 3611 } 3612 3613 /// Find the designated sub-object of an rvalue. 3614 template<typename SubobjectHandler> 3615 typename SubobjectHandler::result_type 3616 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3617 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3618 if (Sub.Invalid) 3619 // A diagnostic will have already been produced. 3620 return handler.failed(); 3621 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3622 if (Info.getLangOpts().CPlusPlus11) 3623 Info.FFDiag(E, Sub.isOnePastTheEnd() 3624 ? diag::note_constexpr_access_past_end 3625 : diag::note_constexpr_access_unsized_array) 3626 << handler.AccessKind; 3627 else 3628 Info.FFDiag(E); 3629 return handler.failed(); 3630 } 3631 3632 APValue *O = Obj.Value; 3633 QualType ObjType = Obj.Type; 3634 const FieldDecl *LastField = nullptr; 3635 const FieldDecl *VolatileField = nullptr; 3636 3637 // Walk the designator's path to find the subobject. 3638 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3639 // Reading an indeterminate value is undefined, but assigning over one is OK. 3640 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3641 (O->isIndeterminate() && 3642 !isValidIndeterminateAccess(handler.AccessKind))) { 3643 if (!Info.checkingPotentialConstantExpression()) 3644 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3645 << handler.AccessKind << O->isIndeterminate(); 3646 return handler.failed(); 3647 } 3648 3649 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3650 // const and volatile semantics are not applied on an object under 3651 // {con,de}struction. 3652 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3653 ObjType->isRecordType() && 3654 Info.isEvaluatingCtorDtor( 3655 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3656 Sub.Entries.begin() + I)) != 3657 ConstructionPhase::None) { 3658 ObjType = Info.Ctx.getCanonicalType(ObjType); 3659 ObjType.removeLocalConst(); 3660 ObjType.removeLocalVolatile(); 3661 } 3662 3663 // If this is our last pass, check that the final object type is OK. 3664 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3665 // Accesses to volatile objects are prohibited. 3666 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3667 if (Info.getLangOpts().CPlusPlus) { 3668 int DiagKind; 3669 SourceLocation Loc; 3670 const NamedDecl *Decl = nullptr; 3671 if (VolatileField) { 3672 DiagKind = 2; 3673 Loc = VolatileField->getLocation(); 3674 Decl = VolatileField; 3675 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3676 DiagKind = 1; 3677 Loc = VD->getLocation(); 3678 Decl = VD; 3679 } else { 3680 DiagKind = 0; 3681 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3682 Loc = E->getExprLoc(); 3683 } 3684 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3685 << handler.AccessKind << DiagKind << Decl; 3686 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3687 } else { 3688 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3689 } 3690 return handler.failed(); 3691 } 3692 3693 // If we are reading an object of class type, there may still be more 3694 // things we need to check: if there are any mutable subobjects, we 3695 // cannot perform this read. (This only happens when performing a trivial 3696 // copy or assignment.) 3697 if (ObjType->isRecordType() && 3698 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3699 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3700 return handler.failed(); 3701 } 3702 3703 if (I == N) { 3704 if (!handler.found(*O, ObjType)) 3705 return false; 3706 3707 // If we modified a bit-field, truncate it to the right width. 3708 if (isModification(handler.AccessKind) && 3709 LastField && LastField->isBitField() && 3710 !truncateBitfieldValue(Info, E, *O, LastField)) 3711 return false; 3712 3713 return true; 3714 } 3715 3716 LastField = nullptr; 3717 if (ObjType->isArrayType()) { 3718 // Next subobject is an array element. 3719 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3720 assert(CAT && "vla in literal type?"); 3721 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3722 if (CAT->getSize().ule(Index)) { 3723 // Note, it should not be possible to form a pointer with a valid 3724 // designator which points more than one past the end of the array. 3725 if (Info.getLangOpts().CPlusPlus11) 3726 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3727 << handler.AccessKind; 3728 else 3729 Info.FFDiag(E); 3730 return handler.failed(); 3731 } 3732 3733 ObjType = CAT->getElementType(); 3734 3735 if (O->getArrayInitializedElts() > Index) 3736 O = &O->getArrayInitializedElt(Index); 3737 else if (!isRead(handler.AccessKind)) { 3738 expandArray(*O, Index); 3739 O = &O->getArrayInitializedElt(Index); 3740 } else 3741 O = &O->getArrayFiller(); 3742 } else if (ObjType->isAnyComplexType()) { 3743 // Next subobject is a complex number. 3744 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3745 if (Index > 1) { 3746 if (Info.getLangOpts().CPlusPlus11) 3747 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3748 << handler.AccessKind; 3749 else 3750 Info.FFDiag(E); 3751 return handler.failed(); 3752 } 3753 3754 ObjType = getSubobjectType( 3755 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3756 3757 assert(I == N - 1 && "extracting subobject of scalar?"); 3758 if (O->isComplexInt()) { 3759 return handler.found(Index ? O->getComplexIntImag() 3760 : O->getComplexIntReal(), ObjType); 3761 } else { 3762 assert(O->isComplexFloat()); 3763 return handler.found(Index ? O->getComplexFloatImag() 3764 : O->getComplexFloatReal(), ObjType); 3765 } 3766 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3767 if (Field->isMutable() && 3768 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3769 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3770 << handler.AccessKind << Field; 3771 Info.Note(Field->getLocation(), diag::note_declared_at); 3772 return handler.failed(); 3773 } 3774 3775 // Next subobject is a class, struct or union field. 3776 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3777 if (RD->isUnion()) { 3778 const FieldDecl *UnionField = O->getUnionField(); 3779 if (!UnionField || 3780 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3781 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3782 // Placement new onto an inactive union member makes it active. 3783 O->setUnion(Field, APValue()); 3784 } else { 3785 // FIXME: If O->getUnionValue() is absent, report that there's no 3786 // active union member rather than reporting the prior active union 3787 // member. We'll need to fix nullptr_t to not use APValue() as its 3788 // representation first. 3789 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3790 << handler.AccessKind << Field << !UnionField << UnionField; 3791 return handler.failed(); 3792 } 3793 } 3794 O = &O->getUnionValue(); 3795 } else 3796 O = &O->getStructField(Field->getFieldIndex()); 3797 3798 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3799 LastField = Field; 3800 if (Field->getType().isVolatileQualified()) 3801 VolatileField = Field; 3802 } else { 3803 // Next subobject is a base class. 3804 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3805 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3806 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3807 3808 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3809 } 3810 } 3811 } 3812 3813 namespace { 3814 struct ExtractSubobjectHandler { 3815 EvalInfo &Info; 3816 const Expr *E; 3817 APValue &Result; 3818 const AccessKinds AccessKind; 3819 3820 typedef bool result_type; 3821 bool failed() { return false; } 3822 bool found(APValue &Subobj, QualType SubobjType) { 3823 Result = Subobj; 3824 if (AccessKind == AK_ReadObjectRepresentation) 3825 return true; 3826 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3827 } 3828 bool found(APSInt &Value, QualType SubobjType) { 3829 Result = APValue(Value); 3830 return true; 3831 } 3832 bool found(APFloat &Value, QualType SubobjType) { 3833 Result = APValue(Value); 3834 return true; 3835 } 3836 }; 3837 } // end anonymous namespace 3838 3839 /// Extract the designated sub-object of an rvalue. 3840 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3841 const CompleteObject &Obj, 3842 const SubobjectDesignator &Sub, APValue &Result, 3843 AccessKinds AK = AK_Read) { 3844 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3845 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3846 return findSubobject(Info, E, Obj, Sub, Handler); 3847 } 3848 3849 namespace { 3850 struct ModifySubobjectHandler { 3851 EvalInfo &Info; 3852 APValue &NewVal; 3853 const Expr *E; 3854 3855 typedef bool result_type; 3856 static const AccessKinds AccessKind = AK_Assign; 3857 3858 bool checkConst(QualType QT) { 3859 // Assigning to a const object has undefined behavior. 3860 if (QT.isConstQualified()) { 3861 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3862 return false; 3863 } 3864 return true; 3865 } 3866 3867 bool failed() { return false; } 3868 bool found(APValue &Subobj, QualType SubobjType) { 3869 if (!checkConst(SubobjType)) 3870 return false; 3871 // We've been given ownership of NewVal, so just swap it in. 3872 Subobj.swap(NewVal); 3873 return true; 3874 } 3875 bool found(APSInt &Value, QualType SubobjType) { 3876 if (!checkConst(SubobjType)) 3877 return false; 3878 if (!NewVal.isInt()) { 3879 // Maybe trying to write a cast pointer value into a complex? 3880 Info.FFDiag(E); 3881 return false; 3882 } 3883 Value = NewVal.getInt(); 3884 return true; 3885 } 3886 bool found(APFloat &Value, QualType SubobjType) { 3887 if (!checkConst(SubobjType)) 3888 return false; 3889 Value = NewVal.getFloat(); 3890 return true; 3891 } 3892 }; 3893 } // end anonymous namespace 3894 3895 const AccessKinds ModifySubobjectHandler::AccessKind; 3896 3897 /// Update the designated sub-object of an rvalue to the given value. 3898 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3899 const CompleteObject &Obj, 3900 const SubobjectDesignator &Sub, 3901 APValue &NewVal) { 3902 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3903 return findSubobject(Info, E, Obj, Sub, Handler); 3904 } 3905 3906 /// Find the position where two subobject designators diverge, or equivalently 3907 /// the length of the common initial subsequence. 3908 static unsigned FindDesignatorMismatch(QualType ObjType, 3909 const SubobjectDesignator &A, 3910 const SubobjectDesignator &B, 3911 bool &WasArrayIndex) { 3912 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3913 for (/**/; I != N; ++I) { 3914 if (!ObjType.isNull() && 3915 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3916 // Next subobject is an array element. 3917 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3918 WasArrayIndex = true; 3919 return I; 3920 } 3921 if (ObjType->isAnyComplexType()) 3922 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3923 else 3924 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3925 } else { 3926 if (A.Entries[I].getAsBaseOrMember() != 3927 B.Entries[I].getAsBaseOrMember()) { 3928 WasArrayIndex = false; 3929 return I; 3930 } 3931 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3932 // Next subobject is a field. 3933 ObjType = FD->getType(); 3934 else 3935 // Next subobject is a base class. 3936 ObjType = QualType(); 3937 } 3938 } 3939 WasArrayIndex = false; 3940 return I; 3941 } 3942 3943 /// Determine whether the given subobject designators refer to elements of the 3944 /// same array object. 3945 static bool AreElementsOfSameArray(QualType ObjType, 3946 const SubobjectDesignator &A, 3947 const SubobjectDesignator &B) { 3948 if (A.Entries.size() != B.Entries.size()) 3949 return false; 3950 3951 bool IsArray = A.MostDerivedIsArrayElement; 3952 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3953 // A is a subobject of the array element. 3954 return false; 3955 3956 // If A (and B) designates an array element, the last entry will be the array 3957 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3958 // of length 1' case, and the entire path must match. 3959 bool WasArrayIndex; 3960 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3961 return CommonLength >= A.Entries.size() - IsArray; 3962 } 3963 3964 /// Find the complete object to which an LValue refers. 3965 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3966 AccessKinds AK, const LValue &LVal, 3967 QualType LValType) { 3968 if (LVal.InvalidBase) { 3969 Info.FFDiag(E); 3970 return CompleteObject(); 3971 } 3972 3973 if (!LVal.Base) { 3974 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3975 return CompleteObject(); 3976 } 3977 3978 CallStackFrame *Frame = nullptr; 3979 unsigned Depth = 0; 3980 if (LVal.getLValueCallIndex()) { 3981 std::tie(Frame, Depth) = 3982 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3983 if (!Frame) { 3984 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3985 << AK << LVal.Base.is<const ValueDecl*>(); 3986 NoteLValueLocation(Info, LVal.Base); 3987 return CompleteObject(); 3988 } 3989 } 3990 3991 bool IsAccess = isAnyAccess(AK); 3992 3993 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3994 // is not a constant expression (even if the object is non-volatile). We also 3995 // apply this rule to C++98, in order to conform to the expected 'volatile' 3996 // semantics. 3997 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3998 if (Info.getLangOpts().CPlusPlus) 3999 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 4000 << AK << LValType; 4001 else 4002 Info.FFDiag(E); 4003 return CompleteObject(); 4004 } 4005 4006 // Compute value storage location and type of base object. 4007 APValue *BaseVal = nullptr; 4008 QualType BaseType = getType(LVal.Base); 4009 4010 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 4011 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4012 // This is the object whose initializer we're evaluating, so its lifetime 4013 // started in the current evaluation. 4014 BaseVal = Info.EvaluatingDeclValue; 4015 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4016 // Allow reading from a GUID declaration. 4017 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4018 if (isModification(AK)) { 4019 // All the remaining cases do not permit modification of the object. 4020 Info.FFDiag(E, diag::note_constexpr_modify_global); 4021 return CompleteObject(); 4022 } 4023 APValue &V = GD->getAsAPValue(); 4024 if (V.isAbsent()) { 4025 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4026 << GD->getType(); 4027 return CompleteObject(); 4028 } 4029 return CompleteObject(LVal.Base, &V, GD->getType()); 4030 } 4031 4032 // Allow reading the APValue from an UnnamedGlobalConstantDecl. 4033 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) { 4034 if (isModification(AK)) { 4035 Info.FFDiag(E, diag::note_constexpr_modify_global); 4036 return CompleteObject(); 4037 } 4038 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()), 4039 GCD->getType()); 4040 } 4041 4042 // Allow reading from template parameter objects. 4043 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4044 if (isModification(AK)) { 4045 Info.FFDiag(E, diag::note_constexpr_modify_global); 4046 return CompleteObject(); 4047 } 4048 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4049 TPO->getType()); 4050 } 4051 4052 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4053 // In C++11, constexpr, non-volatile variables initialized with constant 4054 // expressions are constant expressions too. Inside constexpr functions, 4055 // parameters are constant expressions even if they're non-const. 4056 // In C++1y, objects local to a constant expression (those with a Frame) are 4057 // both readable and writable inside constant expressions. 4058 // In C, such things can also be folded, although they are not ICEs. 4059 const VarDecl *VD = dyn_cast<VarDecl>(D); 4060 if (VD) { 4061 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4062 VD = VDef; 4063 } 4064 if (!VD || VD->isInvalidDecl()) { 4065 Info.FFDiag(E); 4066 return CompleteObject(); 4067 } 4068 4069 bool IsConstant = BaseType.isConstant(Info.Ctx); 4070 4071 // Unless we're looking at a local variable or argument in a constexpr call, 4072 // the variable we're reading must be const. 4073 if (!Frame) { 4074 if (IsAccess && isa<ParmVarDecl>(VD)) { 4075 // Access of a parameter that's not associated with a frame isn't going 4076 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4077 // suitable diagnostic. 4078 } else if (Info.getLangOpts().CPlusPlus14 && 4079 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4080 // OK, we can read and modify an object if we're in the process of 4081 // evaluating its initializer, because its lifetime began in this 4082 // evaluation. 4083 } else if (isModification(AK)) { 4084 // All the remaining cases do not permit modification of the object. 4085 Info.FFDiag(E, diag::note_constexpr_modify_global); 4086 return CompleteObject(); 4087 } else if (VD->isConstexpr()) { 4088 // OK, we can read this variable. 4089 } else if (BaseType->isIntegralOrEnumerationType()) { 4090 if (!IsConstant) { 4091 if (!IsAccess) 4092 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4093 if (Info.getLangOpts().CPlusPlus) { 4094 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4095 Info.Note(VD->getLocation(), diag::note_declared_at); 4096 } else { 4097 Info.FFDiag(E); 4098 } 4099 return CompleteObject(); 4100 } 4101 } else if (!IsAccess) { 4102 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4103 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4104 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4105 // This variable might end up being constexpr. Don't diagnose it yet. 4106 } else if (IsConstant) { 4107 // Keep evaluating to see what we can do. In particular, we support 4108 // folding of const floating-point types, in order to make static const 4109 // data members of such types (supported as an extension) more useful. 4110 if (Info.getLangOpts().CPlusPlus) { 4111 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4112 ? diag::note_constexpr_ltor_non_constexpr 4113 : diag::note_constexpr_ltor_non_integral, 1) 4114 << VD << BaseType; 4115 Info.Note(VD->getLocation(), diag::note_declared_at); 4116 } else { 4117 Info.CCEDiag(E); 4118 } 4119 } else { 4120 // Never allow reading a non-const value. 4121 if (Info.getLangOpts().CPlusPlus) { 4122 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4123 ? diag::note_constexpr_ltor_non_constexpr 4124 : diag::note_constexpr_ltor_non_integral, 1) 4125 << VD << BaseType; 4126 Info.Note(VD->getLocation(), diag::note_declared_at); 4127 } else { 4128 Info.FFDiag(E); 4129 } 4130 return CompleteObject(); 4131 } 4132 } 4133 4134 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4135 return CompleteObject(); 4136 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4137 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4138 if (!Alloc) { 4139 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4140 return CompleteObject(); 4141 } 4142 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4143 LVal.Base.getDynamicAllocType()); 4144 } else { 4145 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4146 4147 if (!Frame) { 4148 if (const MaterializeTemporaryExpr *MTE = 4149 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4150 assert(MTE->getStorageDuration() == SD_Static && 4151 "should have a frame for a non-global materialized temporary"); 4152 4153 // C++20 [expr.const]p4: [DR2126] 4154 // An object or reference is usable in constant expressions if it is 4155 // - a temporary object of non-volatile const-qualified literal type 4156 // whose lifetime is extended to that of a variable that is usable 4157 // in constant expressions 4158 // 4159 // C++20 [expr.const]p5: 4160 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4161 // - a non-volatile glvalue that refers to an object that is usable 4162 // in constant expressions, or 4163 // - a non-volatile glvalue of literal type that refers to a 4164 // non-volatile object whose lifetime began within the evaluation 4165 // of E; 4166 // 4167 // C++11 misses the 'began within the evaluation of e' check and 4168 // instead allows all temporaries, including things like: 4169 // int &&r = 1; 4170 // int x = ++r; 4171 // constexpr int k = r; 4172 // Therefore we use the C++14-onwards rules in C++11 too. 4173 // 4174 // Note that temporaries whose lifetimes began while evaluating a 4175 // variable's constructor are not usable while evaluating the 4176 // corresponding destructor, not even if they're of const-qualified 4177 // types. 4178 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4179 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4180 if (!IsAccess) 4181 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4182 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4183 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4184 return CompleteObject(); 4185 } 4186 4187 BaseVal = MTE->getOrCreateValue(false); 4188 assert(BaseVal && "got reference to unevaluated temporary"); 4189 } else { 4190 if (!IsAccess) 4191 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4192 APValue Val; 4193 LVal.moveInto(Val); 4194 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4195 << AK 4196 << Val.getAsString(Info.Ctx, 4197 Info.Ctx.getLValueReferenceType(LValType)); 4198 NoteLValueLocation(Info, LVal.Base); 4199 return CompleteObject(); 4200 } 4201 } else { 4202 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4203 assert(BaseVal && "missing value for temporary"); 4204 } 4205 } 4206 4207 // In C++14, we can't safely access any mutable state when we might be 4208 // evaluating after an unmodeled side effect. Parameters are modeled as state 4209 // in the caller, but aren't visible once the call returns, so they can be 4210 // modified in a speculatively-evaluated call. 4211 // 4212 // FIXME: Not all local state is mutable. Allow local constant subobjects 4213 // to be read here (but take care with 'mutable' fields). 4214 unsigned VisibleDepth = Depth; 4215 if (llvm::isa_and_nonnull<ParmVarDecl>( 4216 LVal.Base.dyn_cast<const ValueDecl *>())) 4217 ++VisibleDepth; 4218 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4219 Info.EvalStatus.HasSideEffects) || 4220 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4221 return CompleteObject(); 4222 4223 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4224 } 4225 4226 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4227 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4228 /// glvalue referred to by an entity of reference type. 4229 /// 4230 /// \param Info - Information about the ongoing evaluation. 4231 /// \param Conv - The expression for which we are performing the conversion. 4232 /// Used for diagnostics. 4233 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4234 /// case of a non-class type). 4235 /// \param LVal - The glvalue on which we are attempting to perform this action. 4236 /// \param RVal - The produced value will be placed here. 4237 /// \param WantObjectRepresentation - If true, we're looking for the object 4238 /// representation rather than the value, and in particular, 4239 /// there is no requirement that the result be fully initialized. 4240 static bool 4241 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4242 const LValue &LVal, APValue &RVal, 4243 bool WantObjectRepresentation = false) { 4244 if (LVal.Designator.Invalid) 4245 return false; 4246 4247 // Check for special cases where there is no existing APValue to look at. 4248 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4249 4250 AccessKinds AK = 4251 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4252 4253 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4254 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4255 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4256 // initializer until now for such expressions. Such an expression can't be 4257 // an ICE in C, so this only matters for fold. 4258 if (Type.isVolatileQualified()) { 4259 Info.FFDiag(Conv); 4260 return false; 4261 } 4262 4263 APValue Lit; 4264 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4265 return false; 4266 4267 // According to GCC info page: 4268 // 4269 // 6.28 Compound Literals 4270 // 4271 // As an optimization, G++ sometimes gives array compound literals longer 4272 // lifetimes: when the array either appears outside a function or has a 4273 // const-qualified type. If foo and its initializer had elements of type 4274 // char *const rather than char *, or if foo were a global variable, the 4275 // array would have static storage duration. But it is probably safest 4276 // just to avoid the use of array compound literals in C++ code. 4277 // 4278 // Obey that rule by checking constness for converted array types. 4279 4280 QualType CLETy = CLE->getType(); 4281 if (CLETy->isArrayType() && !Type->isArrayType()) { 4282 if (!CLETy.isConstant(Info.Ctx)) { 4283 Info.FFDiag(Conv); 4284 Info.Note(CLE->getExprLoc(), diag::note_declared_at); 4285 return false; 4286 } 4287 } 4288 4289 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4290 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4291 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4292 // Special-case character extraction so we don't have to construct an 4293 // APValue for the whole string. 4294 assert(LVal.Designator.Entries.size() <= 1 && 4295 "Can only read characters from string literals"); 4296 if (LVal.Designator.Entries.empty()) { 4297 // Fail for now for LValue to RValue conversion of an array. 4298 // (This shouldn't show up in C/C++, but it could be triggered by a 4299 // weird EvaluateAsRValue call from a tool.) 4300 Info.FFDiag(Conv); 4301 return false; 4302 } 4303 if (LVal.Designator.isOnePastTheEnd()) { 4304 if (Info.getLangOpts().CPlusPlus11) 4305 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4306 else 4307 Info.FFDiag(Conv); 4308 return false; 4309 } 4310 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4311 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4312 return true; 4313 } 4314 } 4315 4316 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4317 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4318 } 4319 4320 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4321 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4322 QualType LValType, APValue &Val) { 4323 if (LVal.Designator.Invalid) 4324 return false; 4325 4326 if (!Info.getLangOpts().CPlusPlus14) { 4327 Info.FFDiag(E); 4328 return false; 4329 } 4330 4331 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4332 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4333 } 4334 4335 namespace { 4336 struct CompoundAssignSubobjectHandler { 4337 EvalInfo &Info; 4338 const CompoundAssignOperator *E; 4339 QualType PromotedLHSType; 4340 BinaryOperatorKind Opcode; 4341 const APValue &RHS; 4342 4343 static const AccessKinds AccessKind = AK_Assign; 4344 4345 typedef bool result_type; 4346 4347 bool checkConst(QualType QT) { 4348 // Assigning to a const object has undefined behavior. 4349 if (QT.isConstQualified()) { 4350 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4351 return false; 4352 } 4353 return true; 4354 } 4355 4356 bool failed() { return false; } 4357 bool found(APValue &Subobj, QualType SubobjType) { 4358 switch (Subobj.getKind()) { 4359 case APValue::Int: 4360 return found(Subobj.getInt(), SubobjType); 4361 case APValue::Float: 4362 return found(Subobj.getFloat(), SubobjType); 4363 case APValue::ComplexInt: 4364 case APValue::ComplexFloat: 4365 // FIXME: Implement complex compound assignment. 4366 Info.FFDiag(E); 4367 return false; 4368 case APValue::LValue: 4369 return foundPointer(Subobj, SubobjType); 4370 case APValue::Vector: 4371 return foundVector(Subobj, SubobjType); 4372 default: 4373 // FIXME: can this happen? 4374 Info.FFDiag(E); 4375 return false; 4376 } 4377 } 4378 4379 bool foundVector(APValue &Value, QualType SubobjType) { 4380 if (!checkConst(SubobjType)) 4381 return false; 4382 4383 if (!SubobjType->isVectorType()) { 4384 Info.FFDiag(E); 4385 return false; 4386 } 4387 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4388 } 4389 4390 bool found(APSInt &Value, QualType SubobjType) { 4391 if (!checkConst(SubobjType)) 4392 return false; 4393 4394 if (!SubobjType->isIntegerType()) { 4395 // We don't support compound assignment on integer-cast-to-pointer 4396 // values. 4397 Info.FFDiag(E); 4398 return false; 4399 } 4400 4401 if (RHS.isInt()) { 4402 APSInt LHS = 4403 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4404 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4405 return false; 4406 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4407 return true; 4408 } else if (RHS.isFloat()) { 4409 const FPOptions FPO = E->getFPFeaturesInEffect( 4410 Info.Ctx.getLangOpts()); 4411 APFloat FValue(0.0); 4412 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4413 PromotedLHSType, FValue) && 4414 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4415 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4416 Value); 4417 } 4418 4419 Info.FFDiag(E); 4420 return false; 4421 } 4422 bool found(APFloat &Value, QualType SubobjType) { 4423 return checkConst(SubobjType) && 4424 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4425 Value) && 4426 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4427 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4428 } 4429 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4430 if (!checkConst(SubobjType)) 4431 return false; 4432 4433 QualType PointeeType; 4434 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4435 PointeeType = PT->getPointeeType(); 4436 4437 if (PointeeType.isNull() || !RHS.isInt() || 4438 (Opcode != BO_Add && Opcode != BO_Sub)) { 4439 Info.FFDiag(E); 4440 return false; 4441 } 4442 4443 APSInt Offset = RHS.getInt(); 4444 if (Opcode == BO_Sub) 4445 negateAsSigned(Offset); 4446 4447 LValue LVal; 4448 LVal.setFrom(Info.Ctx, Subobj); 4449 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4450 return false; 4451 LVal.moveInto(Subobj); 4452 return true; 4453 } 4454 }; 4455 } // end anonymous namespace 4456 4457 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4458 4459 /// Perform a compound assignment of LVal <op>= RVal. 4460 static bool handleCompoundAssignment(EvalInfo &Info, 4461 const CompoundAssignOperator *E, 4462 const LValue &LVal, QualType LValType, 4463 QualType PromotedLValType, 4464 BinaryOperatorKind Opcode, 4465 const APValue &RVal) { 4466 if (LVal.Designator.Invalid) 4467 return false; 4468 4469 if (!Info.getLangOpts().CPlusPlus14) { 4470 Info.FFDiag(E); 4471 return false; 4472 } 4473 4474 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4475 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4476 RVal }; 4477 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4478 } 4479 4480 namespace { 4481 struct IncDecSubobjectHandler { 4482 EvalInfo &Info; 4483 const UnaryOperator *E; 4484 AccessKinds AccessKind; 4485 APValue *Old; 4486 4487 typedef bool result_type; 4488 4489 bool checkConst(QualType QT) { 4490 // Assigning to a const object has undefined behavior. 4491 if (QT.isConstQualified()) { 4492 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4493 return false; 4494 } 4495 return true; 4496 } 4497 4498 bool failed() { return false; } 4499 bool found(APValue &Subobj, QualType SubobjType) { 4500 // Stash the old value. Also clear Old, so we don't clobber it later 4501 // if we're post-incrementing a complex. 4502 if (Old) { 4503 *Old = Subobj; 4504 Old = nullptr; 4505 } 4506 4507 switch (Subobj.getKind()) { 4508 case APValue::Int: 4509 return found(Subobj.getInt(), SubobjType); 4510 case APValue::Float: 4511 return found(Subobj.getFloat(), SubobjType); 4512 case APValue::ComplexInt: 4513 return found(Subobj.getComplexIntReal(), 4514 SubobjType->castAs<ComplexType>()->getElementType() 4515 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4516 case APValue::ComplexFloat: 4517 return found(Subobj.getComplexFloatReal(), 4518 SubobjType->castAs<ComplexType>()->getElementType() 4519 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4520 case APValue::LValue: 4521 return foundPointer(Subobj, SubobjType); 4522 default: 4523 // FIXME: can this happen? 4524 Info.FFDiag(E); 4525 return false; 4526 } 4527 } 4528 bool found(APSInt &Value, QualType SubobjType) { 4529 if (!checkConst(SubobjType)) 4530 return false; 4531 4532 if (!SubobjType->isIntegerType()) { 4533 // We don't support increment / decrement on integer-cast-to-pointer 4534 // values. 4535 Info.FFDiag(E); 4536 return false; 4537 } 4538 4539 if (Old) *Old = APValue(Value); 4540 4541 // bool arithmetic promotes to int, and the conversion back to bool 4542 // doesn't reduce mod 2^n, so special-case it. 4543 if (SubobjType->isBooleanType()) { 4544 if (AccessKind == AK_Increment) 4545 Value = 1; 4546 else 4547 Value = !Value; 4548 return true; 4549 } 4550 4551 bool WasNegative = Value.isNegative(); 4552 if (AccessKind == AK_Increment) { 4553 ++Value; 4554 4555 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4556 APSInt ActualValue(Value, /*IsUnsigned*/true); 4557 return HandleOverflow(Info, E, ActualValue, SubobjType); 4558 } 4559 } else { 4560 --Value; 4561 4562 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4563 unsigned BitWidth = Value.getBitWidth(); 4564 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4565 ActualValue.setBit(BitWidth); 4566 return HandleOverflow(Info, E, ActualValue, SubobjType); 4567 } 4568 } 4569 return true; 4570 } 4571 bool found(APFloat &Value, QualType SubobjType) { 4572 if (!checkConst(SubobjType)) 4573 return false; 4574 4575 if (Old) *Old = APValue(Value); 4576 4577 APFloat One(Value.getSemantics(), 1); 4578 if (AccessKind == AK_Increment) 4579 Value.add(One, APFloat::rmNearestTiesToEven); 4580 else 4581 Value.subtract(One, APFloat::rmNearestTiesToEven); 4582 return true; 4583 } 4584 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4585 if (!checkConst(SubobjType)) 4586 return false; 4587 4588 QualType PointeeType; 4589 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4590 PointeeType = PT->getPointeeType(); 4591 else { 4592 Info.FFDiag(E); 4593 return false; 4594 } 4595 4596 LValue LVal; 4597 LVal.setFrom(Info.Ctx, Subobj); 4598 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4599 AccessKind == AK_Increment ? 1 : -1)) 4600 return false; 4601 LVal.moveInto(Subobj); 4602 return true; 4603 } 4604 }; 4605 } // end anonymous namespace 4606 4607 /// Perform an increment or decrement on LVal. 4608 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4609 QualType LValType, bool IsIncrement, APValue *Old) { 4610 if (LVal.Designator.Invalid) 4611 return false; 4612 4613 if (!Info.getLangOpts().CPlusPlus14) { 4614 Info.FFDiag(E); 4615 return false; 4616 } 4617 4618 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4619 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4620 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4621 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4622 } 4623 4624 /// Build an lvalue for the object argument of a member function call. 4625 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4626 LValue &This) { 4627 if (Object->getType()->isPointerType() && Object->isPRValue()) 4628 return EvaluatePointer(Object, This, Info); 4629 4630 if (Object->isGLValue()) 4631 return EvaluateLValue(Object, This, Info); 4632 4633 if (Object->getType()->isLiteralType(Info.Ctx)) 4634 return EvaluateTemporary(Object, This, Info); 4635 4636 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4637 return false; 4638 } 4639 4640 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4641 /// lvalue referring to the result. 4642 /// 4643 /// \param Info - Information about the ongoing evaluation. 4644 /// \param LV - An lvalue referring to the base of the member pointer. 4645 /// \param RHS - The member pointer expression. 4646 /// \param IncludeMember - Specifies whether the member itself is included in 4647 /// the resulting LValue subobject designator. This is not possible when 4648 /// creating a bound member function. 4649 /// \return The field or method declaration to which the member pointer refers, 4650 /// or 0 if evaluation fails. 4651 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4652 QualType LVType, 4653 LValue &LV, 4654 const Expr *RHS, 4655 bool IncludeMember = true) { 4656 MemberPtr MemPtr; 4657 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4658 return nullptr; 4659 4660 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4661 // member value, the behavior is undefined. 4662 if (!MemPtr.getDecl()) { 4663 // FIXME: Specific diagnostic. 4664 Info.FFDiag(RHS); 4665 return nullptr; 4666 } 4667 4668 if (MemPtr.isDerivedMember()) { 4669 // This is a member of some derived class. Truncate LV appropriately. 4670 // The end of the derived-to-base path for the base object must match the 4671 // derived-to-base path for the member pointer. 4672 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4673 LV.Designator.Entries.size()) { 4674 Info.FFDiag(RHS); 4675 return nullptr; 4676 } 4677 unsigned PathLengthToMember = 4678 LV.Designator.Entries.size() - MemPtr.Path.size(); 4679 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4680 const CXXRecordDecl *LVDecl = getAsBaseClass( 4681 LV.Designator.Entries[PathLengthToMember + I]); 4682 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4683 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4684 Info.FFDiag(RHS); 4685 return nullptr; 4686 } 4687 } 4688 4689 // Truncate the lvalue to the appropriate derived class. 4690 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4691 PathLengthToMember)) 4692 return nullptr; 4693 } else if (!MemPtr.Path.empty()) { 4694 // Extend the LValue path with the member pointer's path. 4695 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4696 MemPtr.Path.size() + IncludeMember); 4697 4698 // Walk down to the appropriate base class. 4699 if (const PointerType *PT = LVType->getAs<PointerType>()) 4700 LVType = PT->getPointeeType(); 4701 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4702 assert(RD && "member pointer access on non-class-type expression"); 4703 // The first class in the path is that of the lvalue. 4704 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4705 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4706 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4707 return nullptr; 4708 RD = Base; 4709 } 4710 // Finally cast to the class containing the member. 4711 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4712 MemPtr.getContainingRecord())) 4713 return nullptr; 4714 } 4715 4716 // Add the member. Note that we cannot build bound member functions here. 4717 if (IncludeMember) { 4718 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4719 if (!HandleLValueMember(Info, RHS, LV, FD)) 4720 return nullptr; 4721 } else if (const IndirectFieldDecl *IFD = 4722 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4723 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4724 return nullptr; 4725 } else { 4726 llvm_unreachable("can't construct reference to bound member function"); 4727 } 4728 } 4729 4730 return MemPtr.getDecl(); 4731 } 4732 4733 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4734 const BinaryOperator *BO, 4735 LValue &LV, 4736 bool IncludeMember = true) { 4737 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4738 4739 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4740 if (Info.noteFailure()) { 4741 MemberPtr MemPtr; 4742 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4743 } 4744 return nullptr; 4745 } 4746 4747 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4748 BO->getRHS(), IncludeMember); 4749 } 4750 4751 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4752 /// the provided lvalue, which currently refers to the base object. 4753 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4754 LValue &Result) { 4755 SubobjectDesignator &D = Result.Designator; 4756 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4757 return false; 4758 4759 QualType TargetQT = E->getType(); 4760 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4761 TargetQT = PT->getPointeeType(); 4762 4763 // Check this cast lands within the final derived-to-base subobject path. 4764 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4765 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4766 << D.MostDerivedType << TargetQT; 4767 return false; 4768 } 4769 4770 // Check the type of the final cast. We don't need to check the path, 4771 // since a cast can only be formed if the path is unique. 4772 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4773 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4774 const CXXRecordDecl *FinalType; 4775 if (NewEntriesSize == D.MostDerivedPathLength) 4776 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4777 else 4778 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4779 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4780 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4781 << D.MostDerivedType << TargetQT; 4782 return false; 4783 } 4784 4785 // Truncate the lvalue to the appropriate derived class. 4786 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4787 } 4788 4789 /// Get the value to use for a default-initialized object of type T. 4790 /// Return false if it encounters something invalid. 4791 static bool getDefaultInitValue(QualType T, APValue &Result) { 4792 bool Success = true; 4793 if (auto *RD = T->getAsCXXRecordDecl()) { 4794 if (RD->isInvalidDecl()) { 4795 Result = APValue(); 4796 return false; 4797 } 4798 if (RD->isUnion()) { 4799 Result = APValue((const FieldDecl *)nullptr); 4800 return true; 4801 } 4802 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4803 std::distance(RD->field_begin(), RD->field_end())); 4804 4805 unsigned Index = 0; 4806 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4807 End = RD->bases_end(); 4808 I != End; ++I, ++Index) 4809 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4810 4811 for (const auto *I : RD->fields()) { 4812 if (I->isUnnamedBitfield()) 4813 continue; 4814 Success &= getDefaultInitValue(I->getType(), 4815 Result.getStructField(I->getFieldIndex())); 4816 } 4817 return Success; 4818 } 4819 4820 if (auto *AT = 4821 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4822 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4823 if (Result.hasArrayFiller()) 4824 Success &= 4825 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4826 4827 return Success; 4828 } 4829 4830 Result = APValue::IndeterminateValue(); 4831 return true; 4832 } 4833 4834 namespace { 4835 enum EvalStmtResult { 4836 /// Evaluation failed. 4837 ESR_Failed, 4838 /// Hit a 'return' statement. 4839 ESR_Returned, 4840 /// Evaluation succeeded. 4841 ESR_Succeeded, 4842 /// Hit a 'continue' statement. 4843 ESR_Continue, 4844 /// Hit a 'break' statement. 4845 ESR_Break, 4846 /// Still scanning for 'case' or 'default' statement. 4847 ESR_CaseNotFound 4848 }; 4849 } 4850 4851 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4852 // We don't need to evaluate the initializer for a static local. 4853 if (!VD->hasLocalStorage()) 4854 return true; 4855 4856 LValue Result; 4857 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4858 ScopeKind::Block, Result); 4859 4860 const Expr *InitE = VD->getInit(); 4861 if (!InitE) { 4862 if (VD->getType()->isDependentType()) 4863 return Info.noteSideEffect(); 4864 return getDefaultInitValue(VD->getType(), Val); 4865 } 4866 if (InitE->isValueDependent()) 4867 return false; 4868 4869 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4870 // Wipe out any partially-computed value, to allow tracking that this 4871 // evaluation failed. 4872 Val = APValue(); 4873 return false; 4874 } 4875 4876 return true; 4877 } 4878 4879 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4880 bool OK = true; 4881 4882 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4883 OK &= EvaluateVarDecl(Info, VD); 4884 4885 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4886 for (auto *BD : DD->bindings()) 4887 if (auto *VD = BD->getHoldingVar()) 4888 OK &= EvaluateDecl(Info, VD); 4889 4890 return OK; 4891 } 4892 4893 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4894 assert(E->isValueDependent()); 4895 if (Info.noteSideEffect()) 4896 return true; 4897 assert(E->containsErrors() && "valid value-dependent expression should never " 4898 "reach invalid code path."); 4899 return false; 4900 } 4901 4902 /// Evaluate a condition (either a variable declaration or an expression). 4903 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4904 const Expr *Cond, bool &Result) { 4905 if (Cond->isValueDependent()) 4906 return false; 4907 FullExpressionRAII Scope(Info); 4908 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4909 return false; 4910 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4911 return false; 4912 return Scope.destroy(); 4913 } 4914 4915 namespace { 4916 /// A location where the result (returned value) of evaluating a 4917 /// statement should be stored. 4918 struct StmtResult { 4919 /// The APValue that should be filled in with the returned value. 4920 APValue &Value; 4921 /// The location containing the result, if any (used to support RVO). 4922 const LValue *Slot; 4923 }; 4924 4925 struct TempVersionRAII { 4926 CallStackFrame &Frame; 4927 4928 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4929 Frame.pushTempVersion(); 4930 } 4931 4932 ~TempVersionRAII() { 4933 Frame.popTempVersion(); 4934 } 4935 }; 4936 4937 } 4938 4939 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4940 const Stmt *S, 4941 const SwitchCase *SC = nullptr); 4942 4943 /// Evaluate the body of a loop, and translate the result as appropriate. 4944 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4945 const Stmt *Body, 4946 const SwitchCase *Case = nullptr) { 4947 BlockScopeRAII Scope(Info); 4948 4949 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4950 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4951 ESR = ESR_Failed; 4952 4953 switch (ESR) { 4954 case ESR_Break: 4955 return ESR_Succeeded; 4956 case ESR_Succeeded: 4957 case ESR_Continue: 4958 return ESR_Continue; 4959 case ESR_Failed: 4960 case ESR_Returned: 4961 case ESR_CaseNotFound: 4962 return ESR; 4963 } 4964 llvm_unreachable("Invalid EvalStmtResult!"); 4965 } 4966 4967 /// Evaluate a switch statement. 4968 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4969 const SwitchStmt *SS) { 4970 BlockScopeRAII Scope(Info); 4971 4972 // Evaluate the switch condition. 4973 APSInt Value; 4974 { 4975 if (const Stmt *Init = SS->getInit()) { 4976 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4977 if (ESR != ESR_Succeeded) { 4978 if (ESR != ESR_Failed && !Scope.destroy()) 4979 ESR = ESR_Failed; 4980 return ESR; 4981 } 4982 } 4983 4984 FullExpressionRAII CondScope(Info); 4985 if (SS->getConditionVariable() && 4986 !EvaluateDecl(Info, SS->getConditionVariable())) 4987 return ESR_Failed; 4988 if (SS->getCond()->isValueDependent()) { 4989 if (!EvaluateDependentExpr(SS->getCond(), Info)) 4990 return ESR_Failed; 4991 } else { 4992 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4993 return ESR_Failed; 4994 } 4995 if (!CondScope.destroy()) 4996 return ESR_Failed; 4997 } 4998 4999 // Find the switch case corresponding to the value of the condition. 5000 // FIXME: Cache this lookup. 5001 const SwitchCase *Found = nullptr; 5002 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 5003 SC = SC->getNextSwitchCase()) { 5004 if (isa<DefaultStmt>(SC)) { 5005 Found = SC; 5006 continue; 5007 } 5008 5009 const CaseStmt *CS = cast<CaseStmt>(SC); 5010 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 5011 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 5012 : LHS; 5013 if (LHS <= Value && Value <= RHS) { 5014 Found = SC; 5015 break; 5016 } 5017 } 5018 5019 if (!Found) 5020 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5021 5022 // Search the switch body for the switch case and evaluate it from there. 5023 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 5024 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 5025 return ESR_Failed; 5026 5027 switch (ESR) { 5028 case ESR_Break: 5029 return ESR_Succeeded; 5030 case ESR_Succeeded: 5031 case ESR_Continue: 5032 case ESR_Failed: 5033 case ESR_Returned: 5034 return ESR; 5035 case ESR_CaseNotFound: 5036 // This can only happen if the switch case is nested within a statement 5037 // expression. We have no intention of supporting that. 5038 Info.FFDiag(Found->getBeginLoc(), 5039 diag::note_constexpr_stmt_expr_unsupported); 5040 return ESR_Failed; 5041 } 5042 llvm_unreachable("Invalid EvalStmtResult!"); 5043 } 5044 5045 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) { 5046 // An expression E is a core constant expression unless the evaluation of E 5047 // would evaluate one of the following: [C++2b] - a control flow that passes 5048 // through a declaration of a variable with static or thread storage duration. 5049 if (VD->isLocalVarDecl() && VD->isStaticLocal()) { 5050 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local) 5051 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD; 5052 return false; 5053 } 5054 return true; 5055 } 5056 5057 // Evaluate a statement. 5058 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 5059 const Stmt *S, const SwitchCase *Case) { 5060 if (!Info.nextStep(S)) 5061 return ESR_Failed; 5062 5063 // If we're hunting down a 'case' or 'default' label, recurse through 5064 // substatements until we hit the label. 5065 if (Case) { 5066 switch (S->getStmtClass()) { 5067 case Stmt::CompoundStmtClass: 5068 // FIXME: Precompute which substatement of a compound statement we 5069 // would jump to, and go straight there rather than performing a 5070 // linear scan each time. 5071 case Stmt::LabelStmtClass: 5072 case Stmt::AttributedStmtClass: 5073 case Stmt::DoStmtClass: 5074 break; 5075 5076 case Stmt::CaseStmtClass: 5077 case Stmt::DefaultStmtClass: 5078 if (Case == S) 5079 Case = nullptr; 5080 break; 5081 5082 case Stmt::IfStmtClass: { 5083 // FIXME: Precompute which side of an 'if' we would jump to, and go 5084 // straight there rather than scanning both sides. 5085 const IfStmt *IS = cast<IfStmt>(S); 5086 5087 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5088 // preceded by our switch label. 5089 BlockScopeRAII Scope(Info); 5090 5091 // Step into the init statement in case it brings an (uninitialized) 5092 // variable into scope. 5093 if (const Stmt *Init = IS->getInit()) { 5094 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5095 if (ESR != ESR_CaseNotFound) { 5096 assert(ESR != ESR_Succeeded); 5097 return ESR; 5098 } 5099 } 5100 5101 // Condition variable must be initialized if it exists. 5102 // FIXME: We can skip evaluating the body if there's a condition 5103 // variable, as there can't be any case labels within it. 5104 // (The same is true for 'for' statements.) 5105 5106 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5107 if (ESR == ESR_Failed) 5108 return ESR; 5109 if (ESR != ESR_CaseNotFound) 5110 return Scope.destroy() ? ESR : ESR_Failed; 5111 if (!IS->getElse()) 5112 return ESR_CaseNotFound; 5113 5114 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5115 if (ESR == ESR_Failed) 5116 return ESR; 5117 if (ESR != ESR_CaseNotFound) 5118 return Scope.destroy() ? ESR : ESR_Failed; 5119 return ESR_CaseNotFound; 5120 } 5121 5122 case Stmt::WhileStmtClass: { 5123 EvalStmtResult ESR = 5124 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5125 if (ESR != ESR_Continue) 5126 return ESR; 5127 break; 5128 } 5129 5130 case Stmt::ForStmtClass: { 5131 const ForStmt *FS = cast<ForStmt>(S); 5132 BlockScopeRAII Scope(Info); 5133 5134 // Step into the init statement in case it brings an (uninitialized) 5135 // variable into scope. 5136 if (const Stmt *Init = FS->getInit()) { 5137 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5138 if (ESR != ESR_CaseNotFound) { 5139 assert(ESR != ESR_Succeeded); 5140 return ESR; 5141 } 5142 } 5143 5144 EvalStmtResult ESR = 5145 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5146 if (ESR != ESR_Continue) 5147 return ESR; 5148 if (const auto *Inc = FS->getInc()) { 5149 if (Inc->isValueDependent()) { 5150 if (!EvaluateDependentExpr(Inc, Info)) 5151 return ESR_Failed; 5152 } else { 5153 FullExpressionRAII IncScope(Info); 5154 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5155 return ESR_Failed; 5156 } 5157 } 5158 break; 5159 } 5160 5161 case Stmt::DeclStmtClass: { 5162 // Start the lifetime of any uninitialized variables we encounter. They 5163 // might be used by the selected branch of the switch. 5164 const DeclStmt *DS = cast<DeclStmt>(S); 5165 for (const auto *D : DS->decls()) { 5166 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5167 if (!CheckLocalVariableDeclaration(Info, VD)) 5168 return ESR_Failed; 5169 if (VD->hasLocalStorage() && !VD->getInit()) 5170 if (!EvaluateVarDecl(Info, VD)) 5171 return ESR_Failed; 5172 // FIXME: If the variable has initialization that can't be jumped 5173 // over, bail out of any immediately-surrounding compound-statement 5174 // too. There can't be any case labels here. 5175 } 5176 } 5177 return ESR_CaseNotFound; 5178 } 5179 5180 default: 5181 return ESR_CaseNotFound; 5182 } 5183 } 5184 5185 switch (S->getStmtClass()) { 5186 default: 5187 if (const Expr *E = dyn_cast<Expr>(S)) { 5188 if (E->isValueDependent()) { 5189 if (!EvaluateDependentExpr(E, Info)) 5190 return ESR_Failed; 5191 } else { 5192 // Don't bother evaluating beyond an expression-statement which couldn't 5193 // be evaluated. 5194 // FIXME: Do we need the FullExpressionRAII object here? 5195 // VisitExprWithCleanups should create one when necessary. 5196 FullExpressionRAII Scope(Info); 5197 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5198 return ESR_Failed; 5199 } 5200 return ESR_Succeeded; 5201 } 5202 5203 Info.FFDiag(S->getBeginLoc()); 5204 return ESR_Failed; 5205 5206 case Stmt::NullStmtClass: 5207 return ESR_Succeeded; 5208 5209 case Stmt::DeclStmtClass: { 5210 const DeclStmt *DS = cast<DeclStmt>(S); 5211 for (const auto *D : DS->decls()) { 5212 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 5213 if (VD && !CheckLocalVariableDeclaration(Info, VD)) 5214 return ESR_Failed; 5215 // Each declaration initialization is its own full-expression. 5216 FullExpressionRAII Scope(Info); 5217 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5218 return ESR_Failed; 5219 if (!Scope.destroy()) 5220 return ESR_Failed; 5221 } 5222 return ESR_Succeeded; 5223 } 5224 5225 case Stmt::ReturnStmtClass: { 5226 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5227 FullExpressionRAII Scope(Info); 5228 if (RetExpr && RetExpr->isValueDependent()) { 5229 EvaluateDependentExpr(RetExpr, Info); 5230 // We know we returned, but we don't know what the value is. 5231 return ESR_Failed; 5232 } 5233 if (RetExpr && 5234 !(Result.Slot 5235 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5236 : Evaluate(Result.Value, Info, RetExpr))) 5237 return ESR_Failed; 5238 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5239 } 5240 5241 case Stmt::CompoundStmtClass: { 5242 BlockScopeRAII Scope(Info); 5243 5244 const CompoundStmt *CS = cast<CompoundStmt>(S); 5245 for (const auto *BI : CS->body()) { 5246 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5247 if (ESR == ESR_Succeeded) 5248 Case = nullptr; 5249 else if (ESR != ESR_CaseNotFound) { 5250 if (ESR != ESR_Failed && !Scope.destroy()) 5251 return ESR_Failed; 5252 return ESR; 5253 } 5254 } 5255 if (Case) 5256 return ESR_CaseNotFound; 5257 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5258 } 5259 5260 case Stmt::IfStmtClass: { 5261 const IfStmt *IS = cast<IfStmt>(S); 5262 5263 // Evaluate the condition, as either a var decl or as an expression. 5264 BlockScopeRAII Scope(Info); 5265 if (const Stmt *Init = IS->getInit()) { 5266 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5267 if (ESR != ESR_Succeeded) { 5268 if (ESR != ESR_Failed && !Scope.destroy()) 5269 return ESR_Failed; 5270 return ESR; 5271 } 5272 } 5273 bool Cond; 5274 if (IS->isConsteval()) 5275 Cond = IS->isNonNegatedConsteval(); 5276 else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5277 Cond)) 5278 return ESR_Failed; 5279 5280 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5281 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5282 if (ESR != ESR_Succeeded) { 5283 if (ESR != ESR_Failed && !Scope.destroy()) 5284 return ESR_Failed; 5285 return ESR; 5286 } 5287 } 5288 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5289 } 5290 5291 case Stmt::WhileStmtClass: { 5292 const WhileStmt *WS = cast<WhileStmt>(S); 5293 while (true) { 5294 BlockScopeRAII Scope(Info); 5295 bool Continue; 5296 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5297 Continue)) 5298 return ESR_Failed; 5299 if (!Continue) 5300 break; 5301 5302 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5303 if (ESR != ESR_Continue) { 5304 if (ESR != ESR_Failed && !Scope.destroy()) 5305 return ESR_Failed; 5306 return ESR; 5307 } 5308 if (!Scope.destroy()) 5309 return ESR_Failed; 5310 } 5311 return ESR_Succeeded; 5312 } 5313 5314 case Stmt::DoStmtClass: { 5315 const DoStmt *DS = cast<DoStmt>(S); 5316 bool Continue; 5317 do { 5318 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5319 if (ESR != ESR_Continue) 5320 return ESR; 5321 Case = nullptr; 5322 5323 if (DS->getCond()->isValueDependent()) { 5324 EvaluateDependentExpr(DS->getCond(), Info); 5325 // Bailout as we don't know whether to keep going or terminate the loop. 5326 return ESR_Failed; 5327 } 5328 FullExpressionRAII CondScope(Info); 5329 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5330 !CondScope.destroy()) 5331 return ESR_Failed; 5332 } while (Continue); 5333 return ESR_Succeeded; 5334 } 5335 5336 case Stmt::ForStmtClass: { 5337 const ForStmt *FS = cast<ForStmt>(S); 5338 BlockScopeRAII ForScope(Info); 5339 if (FS->getInit()) { 5340 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5341 if (ESR != ESR_Succeeded) { 5342 if (ESR != ESR_Failed && !ForScope.destroy()) 5343 return ESR_Failed; 5344 return ESR; 5345 } 5346 } 5347 while (true) { 5348 BlockScopeRAII IterScope(Info); 5349 bool Continue = true; 5350 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5351 FS->getCond(), Continue)) 5352 return ESR_Failed; 5353 if (!Continue) 5354 break; 5355 5356 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5357 if (ESR != ESR_Continue) { 5358 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5359 return ESR_Failed; 5360 return ESR; 5361 } 5362 5363 if (const auto *Inc = FS->getInc()) { 5364 if (Inc->isValueDependent()) { 5365 if (!EvaluateDependentExpr(Inc, Info)) 5366 return ESR_Failed; 5367 } else { 5368 FullExpressionRAII IncScope(Info); 5369 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5370 return ESR_Failed; 5371 } 5372 } 5373 5374 if (!IterScope.destroy()) 5375 return ESR_Failed; 5376 } 5377 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5378 } 5379 5380 case Stmt::CXXForRangeStmtClass: { 5381 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5382 BlockScopeRAII Scope(Info); 5383 5384 // Evaluate the init-statement if present. 5385 if (FS->getInit()) { 5386 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5387 if (ESR != ESR_Succeeded) { 5388 if (ESR != ESR_Failed && !Scope.destroy()) 5389 return ESR_Failed; 5390 return ESR; 5391 } 5392 } 5393 5394 // Initialize the __range variable. 5395 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5396 if (ESR != ESR_Succeeded) { 5397 if (ESR != ESR_Failed && !Scope.destroy()) 5398 return ESR_Failed; 5399 return ESR; 5400 } 5401 5402 // In error-recovery cases it's possible to get here even if we failed to 5403 // synthesize the __begin and __end variables. 5404 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5405 return ESR_Failed; 5406 5407 // Create the __begin and __end iterators. 5408 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5409 if (ESR != ESR_Succeeded) { 5410 if (ESR != ESR_Failed && !Scope.destroy()) 5411 return ESR_Failed; 5412 return ESR; 5413 } 5414 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5415 if (ESR != ESR_Succeeded) { 5416 if (ESR != ESR_Failed && !Scope.destroy()) 5417 return ESR_Failed; 5418 return ESR; 5419 } 5420 5421 while (true) { 5422 // Condition: __begin != __end. 5423 { 5424 if (FS->getCond()->isValueDependent()) { 5425 EvaluateDependentExpr(FS->getCond(), Info); 5426 // We don't know whether to keep going or terminate the loop. 5427 return ESR_Failed; 5428 } 5429 bool Continue = true; 5430 FullExpressionRAII CondExpr(Info); 5431 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5432 return ESR_Failed; 5433 if (!Continue) 5434 break; 5435 } 5436 5437 // User's variable declaration, initialized by *__begin. 5438 BlockScopeRAII InnerScope(Info); 5439 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5440 if (ESR != ESR_Succeeded) { 5441 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5442 return ESR_Failed; 5443 return ESR; 5444 } 5445 5446 // Loop body. 5447 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5448 if (ESR != ESR_Continue) { 5449 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5450 return ESR_Failed; 5451 return ESR; 5452 } 5453 if (FS->getInc()->isValueDependent()) { 5454 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5455 return ESR_Failed; 5456 } else { 5457 // Increment: ++__begin 5458 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5459 return ESR_Failed; 5460 } 5461 5462 if (!InnerScope.destroy()) 5463 return ESR_Failed; 5464 } 5465 5466 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5467 } 5468 5469 case Stmt::SwitchStmtClass: 5470 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5471 5472 case Stmt::ContinueStmtClass: 5473 return ESR_Continue; 5474 5475 case Stmt::BreakStmtClass: 5476 return ESR_Break; 5477 5478 case Stmt::LabelStmtClass: 5479 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5480 5481 case Stmt::AttributedStmtClass: 5482 // As a general principle, C++11 attributes can be ignored without 5483 // any semantic impact. 5484 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5485 Case); 5486 5487 case Stmt::CaseStmtClass: 5488 case Stmt::DefaultStmtClass: 5489 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5490 case Stmt::CXXTryStmtClass: 5491 // Evaluate try blocks by evaluating all sub statements. 5492 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5493 } 5494 } 5495 5496 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5497 /// default constructor. If so, we'll fold it whether or not it's marked as 5498 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5499 /// so we need special handling. 5500 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5501 const CXXConstructorDecl *CD, 5502 bool IsValueInitialization) { 5503 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5504 return false; 5505 5506 // Value-initialization does not call a trivial default constructor, so such a 5507 // call is a core constant expression whether or not the constructor is 5508 // constexpr. 5509 if (!CD->isConstexpr() && !IsValueInitialization) { 5510 if (Info.getLangOpts().CPlusPlus11) { 5511 // FIXME: If DiagDecl is an implicitly-declared special member function, 5512 // we should be much more explicit about why it's not constexpr. 5513 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5514 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5515 Info.Note(CD->getLocation(), diag::note_declared_at); 5516 } else { 5517 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5518 } 5519 } 5520 return true; 5521 } 5522 5523 /// CheckConstexprFunction - Check that a function can be called in a constant 5524 /// expression. 5525 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5526 const FunctionDecl *Declaration, 5527 const FunctionDecl *Definition, 5528 const Stmt *Body) { 5529 // Potential constant expressions can contain calls to declared, but not yet 5530 // defined, constexpr functions. 5531 if (Info.checkingPotentialConstantExpression() && !Definition && 5532 Declaration->isConstexpr()) 5533 return false; 5534 5535 // Bail out if the function declaration itself is invalid. We will 5536 // have produced a relevant diagnostic while parsing it, so just 5537 // note the problematic sub-expression. 5538 if (Declaration->isInvalidDecl()) { 5539 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5540 return false; 5541 } 5542 5543 // DR1872: An instantiated virtual constexpr function can't be called in a 5544 // constant expression (prior to C++20). We can still constant-fold such a 5545 // call. 5546 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5547 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5548 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5549 5550 if (Definition && Definition->isInvalidDecl()) { 5551 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5552 return false; 5553 } 5554 5555 // Can we evaluate this function call? 5556 if (Definition && Definition->isConstexpr() && Body) 5557 return true; 5558 5559 if (Info.getLangOpts().CPlusPlus11) { 5560 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5561 5562 // If this function is not constexpr because it is an inherited 5563 // non-constexpr constructor, diagnose that directly. 5564 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5565 if (CD && CD->isInheritingConstructor()) { 5566 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5567 if (!Inherited->isConstexpr()) 5568 DiagDecl = CD = Inherited; 5569 } 5570 5571 // FIXME: If DiagDecl is an implicitly-declared special member function 5572 // or an inheriting constructor, we should be much more explicit about why 5573 // it's not constexpr. 5574 if (CD && CD->isInheritingConstructor()) 5575 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5576 << CD->getInheritedConstructor().getConstructor()->getParent(); 5577 else 5578 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5579 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5580 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5581 } else { 5582 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5583 } 5584 return false; 5585 } 5586 5587 namespace { 5588 struct CheckDynamicTypeHandler { 5589 AccessKinds AccessKind; 5590 typedef bool result_type; 5591 bool failed() { return false; } 5592 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5593 bool found(APSInt &Value, QualType SubobjType) { return true; } 5594 bool found(APFloat &Value, QualType SubobjType) { return true; } 5595 }; 5596 } // end anonymous namespace 5597 5598 /// Check that we can access the notional vptr of an object / determine its 5599 /// dynamic type. 5600 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5601 AccessKinds AK, bool Polymorphic) { 5602 if (This.Designator.Invalid) 5603 return false; 5604 5605 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5606 5607 if (!Obj) 5608 return false; 5609 5610 if (!Obj.Value) { 5611 // The object is not usable in constant expressions, so we can't inspect 5612 // its value to see if it's in-lifetime or what the active union members 5613 // are. We can still check for a one-past-the-end lvalue. 5614 if (This.Designator.isOnePastTheEnd() || 5615 This.Designator.isMostDerivedAnUnsizedArray()) { 5616 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5617 ? diag::note_constexpr_access_past_end 5618 : diag::note_constexpr_access_unsized_array) 5619 << AK; 5620 return false; 5621 } else if (Polymorphic) { 5622 // Conservatively refuse to perform a polymorphic operation if we would 5623 // not be able to read a notional 'vptr' value. 5624 APValue Val; 5625 This.moveInto(Val); 5626 QualType StarThisType = 5627 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5628 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5629 << AK << Val.getAsString(Info.Ctx, StarThisType); 5630 return false; 5631 } 5632 return true; 5633 } 5634 5635 CheckDynamicTypeHandler Handler{AK}; 5636 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5637 } 5638 5639 /// Check that the pointee of the 'this' pointer in a member function call is 5640 /// either within its lifetime or in its period of construction or destruction. 5641 static bool 5642 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5643 const LValue &This, 5644 const CXXMethodDecl *NamedMember) { 5645 return checkDynamicType( 5646 Info, E, This, 5647 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5648 } 5649 5650 struct DynamicType { 5651 /// The dynamic class type of the object. 5652 const CXXRecordDecl *Type; 5653 /// The corresponding path length in the lvalue. 5654 unsigned PathLength; 5655 }; 5656 5657 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5658 unsigned PathLength) { 5659 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5660 Designator.Entries.size() && "invalid path length"); 5661 return (PathLength == Designator.MostDerivedPathLength) 5662 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5663 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5664 } 5665 5666 /// Determine the dynamic type of an object. 5667 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5668 LValue &This, AccessKinds AK) { 5669 // If we don't have an lvalue denoting an object of class type, there is no 5670 // meaningful dynamic type. (We consider objects of non-class type to have no 5671 // dynamic type.) 5672 if (!checkDynamicType(Info, E, This, AK, true)) 5673 return None; 5674 5675 // Refuse to compute a dynamic type in the presence of virtual bases. This 5676 // shouldn't happen other than in constant-folding situations, since literal 5677 // types can't have virtual bases. 5678 // 5679 // Note that consumers of DynamicType assume that the type has no virtual 5680 // bases, and will need modifications if this restriction is relaxed. 5681 const CXXRecordDecl *Class = 5682 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5683 if (!Class || Class->getNumVBases()) { 5684 Info.FFDiag(E); 5685 return None; 5686 } 5687 5688 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5689 // binary search here instead. But the overwhelmingly common case is that 5690 // we're not in the middle of a constructor, so it probably doesn't matter 5691 // in practice. 5692 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5693 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5694 PathLength <= Path.size(); ++PathLength) { 5695 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5696 Path.slice(0, PathLength))) { 5697 case ConstructionPhase::Bases: 5698 case ConstructionPhase::DestroyingBases: 5699 // We're constructing or destroying a base class. This is not the dynamic 5700 // type. 5701 break; 5702 5703 case ConstructionPhase::None: 5704 case ConstructionPhase::AfterBases: 5705 case ConstructionPhase::AfterFields: 5706 case ConstructionPhase::Destroying: 5707 // We've finished constructing the base classes and not yet started 5708 // destroying them again, so this is the dynamic type. 5709 return DynamicType{getBaseClassType(This.Designator, PathLength), 5710 PathLength}; 5711 } 5712 } 5713 5714 // CWG issue 1517: we're constructing a base class of the object described by 5715 // 'This', so that object has not yet begun its period of construction and 5716 // any polymorphic operation on it results in undefined behavior. 5717 Info.FFDiag(E); 5718 return None; 5719 } 5720 5721 /// Perform virtual dispatch. 5722 static const CXXMethodDecl *HandleVirtualDispatch( 5723 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5724 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5725 Optional<DynamicType> DynType = ComputeDynamicType( 5726 Info, E, This, 5727 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5728 if (!DynType) 5729 return nullptr; 5730 5731 // Find the final overrider. It must be declared in one of the classes on the 5732 // path from the dynamic type to the static type. 5733 // FIXME: If we ever allow literal types to have virtual base classes, that 5734 // won't be true. 5735 const CXXMethodDecl *Callee = Found; 5736 unsigned PathLength = DynType->PathLength; 5737 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5738 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5739 const CXXMethodDecl *Overrider = 5740 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5741 if (Overrider) { 5742 Callee = Overrider; 5743 break; 5744 } 5745 } 5746 5747 // C++2a [class.abstract]p6: 5748 // the effect of making a virtual call to a pure virtual function [...] is 5749 // undefined 5750 if (Callee->isPure()) { 5751 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5752 Info.Note(Callee->getLocation(), diag::note_declared_at); 5753 return nullptr; 5754 } 5755 5756 // If necessary, walk the rest of the path to determine the sequence of 5757 // covariant adjustment steps to apply. 5758 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5759 Found->getReturnType())) { 5760 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5761 for (unsigned CovariantPathLength = PathLength + 1; 5762 CovariantPathLength != This.Designator.Entries.size(); 5763 ++CovariantPathLength) { 5764 const CXXRecordDecl *NextClass = 5765 getBaseClassType(This.Designator, CovariantPathLength); 5766 const CXXMethodDecl *Next = 5767 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5768 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5769 Next->getReturnType(), CovariantAdjustmentPath.back())) 5770 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5771 } 5772 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5773 CovariantAdjustmentPath.back())) 5774 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5775 } 5776 5777 // Perform 'this' adjustment. 5778 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5779 return nullptr; 5780 5781 return Callee; 5782 } 5783 5784 /// Perform the adjustment from a value returned by a virtual function to 5785 /// a value of the statically expected type, which may be a pointer or 5786 /// reference to a base class of the returned type. 5787 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5788 APValue &Result, 5789 ArrayRef<QualType> Path) { 5790 assert(Result.isLValue() && 5791 "unexpected kind of APValue for covariant return"); 5792 if (Result.isNullPointer()) 5793 return true; 5794 5795 LValue LVal; 5796 LVal.setFrom(Info.Ctx, Result); 5797 5798 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5799 for (unsigned I = 1; I != Path.size(); ++I) { 5800 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5801 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5802 if (OldClass != NewClass && 5803 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5804 return false; 5805 OldClass = NewClass; 5806 } 5807 5808 LVal.moveInto(Result); 5809 return true; 5810 } 5811 5812 /// Determine whether \p Base, which is known to be a direct base class of 5813 /// \p Derived, is a public base class. 5814 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5815 const CXXRecordDecl *Base) { 5816 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5817 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5818 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5819 return BaseSpec.getAccessSpecifier() == AS_public; 5820 } 5821 llvm_unreachable("Base is not a direct base of Derived"); 5822 } 5823 5824 /// Apply the given dynamic cast operation on the provided lvalue. 5825 /// 5826 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5827 /// to find a suitable target subobject. 5828 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5829 LValue &Ptr) { 5830 // We can't do anything with a non-symbolic pointer value. 5831 SubobjectDesignator &D = Ptr.Designator; 5832 if (D.Invalid) 5833 return false; 5834 5835 // C++ [expr.dynamic.cast]p6: 5836 // If v is a null pointer value, the result is a null pointer value. 5837 if (Ptr.isNullPointer() && !E->isGLValue()) 5838 return true; 5839 5840 // For all the other cases, we need the pointer to point to an object within 5841 // its lifetime / period of construction / destruction, and we need to know 5842 // its dynamic type. 5843 Optional<DynamicType> DynType = 5844 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5845 if (!DynType) 5846 return false; 5847 5848 // C++ [expr.dynamic.cast]p7: 5849 // If T is "pointer to cv void", then the result is a pointer to the most 5850 // derived object 5851 if (E->getType()->isVoidPointerType()) 5852 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5853 5854 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5855 assert(C && "dynamic_cast target is not void pointer nor class"); 5856 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5857 5858 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5859 // C++ [expr.dynamic.cast]p9: 5860 if (!E->isGLValue()) { 5861 // The value of a failed cast to pointer type is the null pointer value 5862 // of the required result type. 5863 Ptr.setNull(Info.Ctx, E->getType()); 5864 return true; 5865 } 5866 5867 // A failed cast to reference type throws [...] std::bad_cast. 5868 unsigned DiagKind; 5869 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5870 DynType->Type->isDerivedFrom(C))) 5871 DiagKind = 0; 5872 else if (!Paths || Paths->begin() == Paths->end()) 5873 DiagKind = 1; 5874 else if (Paths->isAmbiguous(CQT)) 5875 DiagKind = 2; 5876 else { 5877 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5878 DiagKind = 3; 5879 } 5880 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5881 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5882 << Info.Ctx.getRecordType(DynType->Type) 5883 << E->getType().getUnqualifiedType(); 5884 return false; 5885 }; 5886 5887 // Runtime check, phase 1: 5888 // Walk from the base subobject towards the derived object looking for the 5889 // target type. 5890 for (int PathLength = Ptr.Designator.Entries.size(); 5891 PathLength >= (int)DynType->PathLength; --PathLength) { 5892 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5893 if (declaresSameEntity(Class, C)) 5894 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5895 // We can only walk across public inheritance edges. 5896 if (PathLength > (int)DynType->PathLength && 5897 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5898 Class)) 5899 return RuntimeCheckFailed(nullptr); 5900 } 5901 5902 // Runtime check, phase 2: 5903 // Search the dynamic type for an unambiguous public base of type C. 5904 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5905 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5906 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5907 Paths.front().Access == AS_public) { 5908 // Downcast to the dynamic type... 5909 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5910 return false; 5911 // ... then upcast to the chosen base class subobject. 5912 for (CXXBasePathElement &Elem : Paths.front()) 5913 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5914 return false; 5915 return true; 5916 } 5917 5918 // Otherwise, the runtime check fails. 5919 return RuntimeCheckFailed(&Paths); 5920 } 5921 5922 namespace { 5923 struct StartLifetimeOfUnionMemberHandler { 5924 EvalInfo &Info; 5925 const Expr *LHSExpr; 5926 const FieldDecl *Field; 5927 bool DuringInit; 5928 bool Failed = false; 5929 static const AccessKinds AccessKind = AK_Assign; 5930 5931 typedef bool result_type; 5932 bool failed() { return Failed; } 5933 bool found(APValue &Subobj, QualType SubobjType) { 5934 // We are supposed to perform no initialization but begin the lifetime of 5935 // the object. We interpret that as meaning to do what default 5936 // initialization of the object would do if all constructors involved were 5937 // trivial: 5938 // * All base, non-variant member, and array element subobjects' lifetimes 5939 // begin 5940 // * No variant members' lifetimes begin 5941 // * All scalar subobjects whose lifetimes begin have indeterminate values 5942 assert(SubobjType->isUnionType()); 5943 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5944 // This union member is already active. If it's also in-lifetime, there's 5945 // nothing to do. 5946 if (Subobj.getUnionValue().hasValue()) 5947 return true; 5948 } else if (DuringInit) { 5949 // We're currently in the process of initializing a different union 5950 // member. If we carried on, that initialization would attempt to 5951 // store to an inactive union member, resulting in undefined behavior. 5952 Info.FFDiag(LHSExpr, 5953 diag::note_constexpr_union_member_change_during_init); 5954 return false; 5955 } 5956 APValue Result; 5957 Failed = !getDefaultInitValue(Field->getType(), Result); 5958 Subobj.setUnion(Field, Result); 5959 return true; 5960 } 5961 bool found(APSInt &Value, QualType SubobjType) { 5962 llvm_unreachable("wrong value kind for union object"); 5963 } 5964 bool found(APFloat &Value, QualType SubobjType) { 5965 llvm_unreachable("wrong value kind for union object"); 5966 } 5967 }; 5968 } // end anonymous namespace 5969 5970 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5971 5972 /// Handle a builtin simple-assignment or a call to a trivial assignment 5973 /// operator whose left-hand side might involve a union member access. If it 5974 /// does, implicitly start the lifetime of any accessed union elements per 5975 /// C++20 [class.union]5. 5976 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5977 const LValue &LHS) { 5978 if (LHS.InvalidBase || LHS.Designator.Invalid) 5979 return false; 5980 5981 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5982 // C++ [class.union]p5: 5983 // define the set S(E) of subexpressions of E as follows: 5984 unsigned PathLength = LHS.Designator.Entries.size(); 5985 for (const Expr *E = LHSExpr; E != nullptr;) { 5986 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5987 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5988 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5989 // Note that we can't implicitly start the lifetime of a reference, 5990 // so we don't need to proceed any further if we reach one. 5991 if (!FD || FD->getType()->isReferenceType()) 5992 break; 5993 5994 // ... and also contains A.B if B names a union member ... 5995 if (FD->getParent()->isUnion()) { 5996 // ... of a non-class, non-array type, or of a class type with a 5997 // trivial default constructor that is not deleted, or an array of 5998 // such types. 5999 auto *RD = 6000 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 6001 if (!RD || RD->hasTrivialDefaultConstructor()) 6002 UnionPathLengths.push_back({PathLength - 1, FD}); 6003 } 6004 6005 E = ME->getBase(); 6006 --PathLength; 6007 assert(declaresSameEntity(FD, 6008 LHS.Designator.Entries[PathLength] 6009 .getAsBaseOrMember().getPointer())); 6010 6011 // -- If E is of the form A[B] and is interpreted as a built-in array 6012 // subscripting operator, S(E) is [S(the array operand, if any)]. 6013 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 6014 // Step over an ArrayToPointerDecay implicit cast. 6015 auto *Base = ASE->getBase()->IgnoreImplicit(); 6016 if (!Base->getType()->isArrayType()) 6017 break; 6018 6019 E = Base; 6020 --PathLength; 6021 6022 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6023 // Step over a derived-to-base conversion. 6024 E = ICE->getSubExpr(); 6025 if (ICE->getCastKind() == CK_NoOp) 6026 continue; 6027 if (ICE->getCastKind() != CK_DerivedToBase && 6028 ICE->getCastKind() != CK_UncheckedDerivedToBase) 6029 break; 6030 // Walk path backwards as we walk up from the base to the derived class. 6031 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 6032 --PathLength; 6033 (void)Elt; 6034 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 6035 LHS.Designator.Entries[PathLength] 6036 .getAsBaseOrMember().getPointer())); 6037 } 6038 6039 // -- Otherwise, S(E) is empty. 6040 } else { 6041 break; 6042 } 6043 } 6044 6045 // Common case: no unions' lifetimes are started. 6046 if (UnionPathLengths.empty()) 6047 return true; 6048 6049 // if modification of X [would access an inactive union member], an object 6050 // of the type of X is implicitly created 6051 CompleteObject Obj = 6052 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 6053 if (!Obj) 6054 return false; 6055 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 6056 llvm::reverse(UnionPathLengths)) { 6057 // Form a designator for the union object. 6058 SubobjectDesignator D = LHS.Designator; 6059 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 6060 6061 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 6062 ConstructionPhase::AfterBases; 6063 StartLifetimeOfUnionMemberHandler StartLifetime{ 6064 Info, LHSExpr, LengthAndField.second, DuringInit}; 6065 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 6066 return false; 6067 } 6068 6069 return true; 6070 } 6071 6072 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 6073 CallRef Call, EvalInfo &Info, 6074 bool NonNull = false) { 6075 LValue LV; 6076 // Create the parameter slot and register its destruction. For a vararg 6077 // argument, create a temporary. 6078 // FIXME: For calling conventions that destroy parameters in the callee, 6079 // should we consider performing destruction when the function returns 6080 // instead? 6081 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6082 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6083 ScopeKind::Call, LV); 6084 if (!EvaluateInPlace(V, Info, LV, Arg)) 6085 return false; 6086 6087 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6088 // undefined behavior, so is non-constant. 6089 if (NonNull && V.isLValue() && V.isNullPointer()) { 6090 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6091 return false; 6092 } 6093 6094 return true; 6095 } 6096 6097 /// Evaluate the arguments to a function call. 6098 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6099 EvalInfo &Info, const FunctionDecl *Callee, 6100 bool RightToLeft = false) { 6101 bool Success = true; 6102 llvm::SmallBitVector ForbiddenNullArgs; 6103 if (Callee->hasAttr<NonNullAttr>()) { 6104 ForbiddenNullArgs.resize(Args.size()); 6105 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6106 if (!Attr->args_size()) { 6107 ForbiddenNullArgs.set(); 6108 break; 6109 } else 6110 for (auto Idx : Attr->args()) { 6111 unsigned ASTIdx = Idx.getASTIndex(); 6112 if (ASTIdx >= Args.size()) 6113 continue; 6114 ForbiddenNullArgs[ASTIdx] = true; 6115 } 6116 } 6117 } 6118 for (unsigned I = 0; I < Args.size(); I++) { 6119 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6120 const ParmVarDecl *PVD = 6121 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6122 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6123 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6124 // If we're checking for a potential constant expression, evaluate all 6125 // initializers even if some of them fail. 6126 if (!Info.noteFailure()) 6127 return false; 6128 Success = false; 6129 } 6130 } 6131 return Success; 6132 } 6133 6134 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6135 /// constructor or assignment operator. 6136 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6137 const Expr *E, APValue &Result, 6138 bool CopyObjectRepresentation) { 6139 // Find the reference argument. 6140 CallStackFrame *Frame = Info.CurrentCall; 6141 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6142 if (!RefValue) { 6143 Info.FFDiag(E); 6144 return false; 6145 } 6146 6147 // Copy out the contents of the RHS object. 6148 LValue RefLValue; 6149 RefLValue.setFrom(Info.Ctx, *RefValue); 6150 return handleLValueToRValueConversion( 6151 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6152 CopyObjectRepresentation); 6153 } 6154 6155 /// Evaluate a function call. 6156 static bool HandleFunctionCall(SourceLocation CallLoc, 6157 const FunctionDecl *Callee, const LValue *This, 6158 ArrayRef<const Expr *> Args, CallRef Call, 6159 const Stmt *Body, EvalInfo &Info, 6160 APValue &Result, const LValue *ResultSlot) { 6161 if (!Info.CheckCallLimit(CallLoc)) 6162 return false; 6163 6164 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6165 6166 // For a trivial copy or move assignment, perform an APValue copy. This is 6167 // essential for unions, where the operations performed by the assignment 6168 // operator cannot be represented as statements. 6169 // 6170 // Skip this for non-union classes with no fields; in that case, the defaulted 6171 // copy/move does not actually read the object. 6172 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6173 if (MD && MD->isDefaulted() && 6174 (MD->getParent()->isUnion() || 6175 (MD->isTrivial() && 6176 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6177 assert(This && 6178 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6179 APValue RHSValue; 6180 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6181 MD->getParent()->isUnion())) 6182 return false; 6183 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6184 RHSValue)) 6185 return false; 6186 This->moveInto(Result); 6187 return true; 6188 } else if (MD && isLambdaCallOperator(MD)) { 6189 // We're in a lambda; determine the lambda capture field maps unless we're 6190 // just constexpr checking a lambda's call operator. constexpr checking is 6191 // done before the captures have been added to the closure object (unless 6192 // we're inferring constexpr-ness), so we don't have access to them in this 6193 // case. But since we don't need the captures to constexpr check, we can 6194 // just ignore them. 6195 if (!Info.checkingPotentialConstantExpression()) 6196 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6197 Frame.LambdaThisCaptureField); 6198 } 6199 6200 StmtResult Ret = {Result, ResultSlot}; 6201 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6202 if (ESR == ESR_Succeeded) { 6203 if (Callee->getReturnType()->isVoidType()) 6204 return true; 6205 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6206 } 6207 return ESR == ESR_Returned; 6208 } 6209 6210 /// Evaluate a constructor call. 6211 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6212 CallRef Call, 6213 const CXXConstructorDecl *Definition, 6214 EvalInfo &Info, APValue &Result) { 6215 SourceLocation CallLoc = E->getExprLoc(); 6216 if (!Info.CheckCallLimit(CallLoc)) 6217 return false; 6218 6219 const CXXRecordDecl *RD = Definition->getParent(); 6220 if (RD->getNumVBases()) { 6221 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6222 return false; 6223 } 6224 6225 EvalInfo::EvaluatingConstructorRAII EvalObj( 6226 Info, 6227 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6228 RD->getNumBases()); 6229 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6230 6231 // FIXME: Creating an APValue just to hold a nonexistent return value is 6232 // wasteful. 6233 APValue RetVal; 6234 StmtResult Ret = {RetVal, nullptr}; 6235 6236 // If it's a delegating constructor, delegate. 6237 if (Definition->isDelegatingConstructor()) { 6238 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6239 if ((*I)->getInit()->isValueDependent()) { 6240 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6241 return false; 6242 } else { 6243 FullExpressionRAII InitScope(Info); 6244 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6245 !InitScope.destroy()) 6246 return false; 6247 } 6248 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6249 } 6250 6251 // For a trivial copy or move constructor, perform an APValue copy. This is 6252 // essential for unions (or classes with anonymous union members), where the 6253 // operations performed by the constructor cannot be represented by 6254 // ctor-initializers. 6255 // 6256 // Skip this for empty non-union classes; we should not perform an 6257 // lvalue-to-rvalue conversion on them because their copy constructor does not 6258 // actually read them. 6259 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6260 (Definition->getParent()->isUnion() || 6261 (Definition->isTrivial() && 6262 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6263 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6264 Definition->getParent()->isUnion()); 6265 } 6266 6267 // Reserve space for the struct members. 6268 if (!Result.hasValue()) { 6269 if (!RD->isUnion()) 6270 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6271 std::distance(RD->field_begin(), RD->field_end())); 6272 else 6273 // A union starts with no active member. 6274 Result = APValue((const FieldDecl*)nullptr); 6275 } 6276 6277 if (RD->isInvalidDecl()) return false; 6278 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6279 6280 // A scope for temporaries lifetime-extended by reference members. 6281 BlockScopeRAII LifetimeExtendedScope(Info); 6282 6283 bool Success = true; 6284 unsigned BasesSeen = 0; 6285 #ifndef NDEBUG 6286 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6287 #endif 6288 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6289 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6290 // We might be initializing the same field again if this is an indirect 6291 // field initialization. 6292 if (FieldIt == RD->field_end() || 6293 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6294 assert(Indirect && "fields out of order?"); 6295 return; 6296 } 6297 6298 // Default-initialize any fields with no explicit initializer. 6299 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6300 assert(FieldIt != RD->field_end() && "missing field?"); 6301 if (!FieldIt->isUnnamedBitfield()) 6302 Success &= getDefaultInitValue( 6303 FieldIt->getType(), 6304 Result.getStructField(FieldIt->getFieldIndex())); 6305 } 6306 ++FieldIt; 6307 }; 6308 for (const auto *I : Definition->inits()) { 6309 LValue Subobject = This; 6310 LValue SubobjectParent = This; 6311 APValue *Value = &Result; 6312 6313 // Determine the subobject to initialize. 6314 FieldDecl *FD = nullptr; 6315 if (I->isBaseInitializer()) { 6316 QualType BaseType(I->getBaseClass(), 0); 6317 #ifndef NDEBUG 6318 // Non-virtual base classes are initialized in the order in the class 6319 // definition. We have already checked for virtual base classes. 6320 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6321 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6322 "base class initializers not in expected order"); 6323 ++BaseIt; 6324 #endif 6325 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6326 BaseType->getAsCXXRecordDecl(), &Layout)) 6327 return false; 6328 Value = &Result.getStructBase(BasesSeen++); 6329 } else if ((FD = I->getMember())) { 6330 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6331 return false; 6332 if (RD->isUnion()) { 6333 Result = APValue(FD); 6334 Value = &Result.getUnionValue(); 6335 } else { 6336 SkipToField(FD, false); 6337 Value = &Result.getStructField(FD->getFieldIndex()); 6338 } 6339 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6340 // Walk the indirect field decl's chain to find the object to initialize, 6341 // and make sure we've initialized every step along it. 6342 auto IndirectFieldChain = IFD->chain(); 6343 for (auto *C : IndirectFieldChain) { 6344 FD = cast<FieldDecl>(C); 6345 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6346 // Switch the union field if it differs. This happens if we had 6347 // preceding zero-initialization, and we're now initializing a union 6348 // subobject other than the first. 6349 // FIXME: In this case, the values of the other subobjects are 6350 // specified, since zero-initialization sets all padding bits to zero. 6351 if (!Value->hasValue() || 6352 (Value->isUnion() && Value->getUnionField() != FD)) { 6353 if (CD->isUnion()) 6354 *Value = APValue(FD); 6355 else 6356 // FIXME: This immediately starts the lifetime of all members of 6357 // an anonymous struct. It would be preferable to strictly start 6358 // member lifetime in initialization order. 6359 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6360 } 6361 // Store Subobject as its parent before updating it for the last element 6362 // in the chain. 6363 if (C == IndirectFieldChain.back()) 6364 SubobjectParent = Subobject; 6365 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6366 return false; 6367 if (CD->isUnion()) 6368 Value = &Value->getUnionValue(); 6369 else { 6370 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6371 SkipToField(FD, true); 6372 Value = &Value->getStructField(FD->getFieldIndex()); 6373 } 6374 } 6375 } else { 6376 llvm_unreachable("unknown base initializer kind"); 6377 } 6378 6379 // Need to override This for implicit field initializers as in this case 6380 // This refers to innermost anonymous struct/union containing initializer, 6381 // not to currently constructed class. 6382 const Expr *Init = I->getInit(); 6383 if (Init->isValueDependent()) { 6384 if (!EvaluateDependentExpr(Init, Info)) 6385 return false; 6386 } else { 6387 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6388 isa<CXXDefaultInitExpr>(Init)); 6389 FullExpressionRAII InitScope(Info); 6390 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6391 (FD && FD->isBitField() && 6392 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6393 // If we're checking for a potential constant expression, evaluate all 6394 // initializers even if some of them fail. 6395 if (!Info.noteFailure()) 6396 return false; 6397 Success = false; 6398 } 6399 } 6400 6401 // This is the point at which the dynamic type of the object becomes this 6402 // class type. 6403 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6404 EvalObj.finishedConstructingBases(); 6405 } 6406 6407 // Default-initialize any remaining fields. 6408 if (!RD->isUnion()) { 6409 for (; FieldIt != RD->field_end(); ++FieldIt) { 6410 if (!FieldIt->isUnnamedBitfield()) 6411 Success &= getDefaultInitValue( 6412 FieldIt->getType(), 6413 Result.getStructField(FieldIt->getFieldIndex())); 6414 } 6415 } 6416 6417 EvalObj.finishedConstructingFields(); 6418 6419 return Success && 6420 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6421 LifetimeExtendedScope.destroy(); 6422 } 6423 6424 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6425 ArrayRef<const Expr*> Args, 6426 const CXXConstructorDecl *Definition, 6427 EvalInfo &Info, APValue &Result) { 6428 CallScopeRAII CallScope(Info); 6429 CallRef Call = Info.CurrentCall->createCall(Definition); 6430 if (!EvaluateArgs(Args, Call, Info, Definition)) 6431 return false; 6432 6433 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6434 CallScope.destroy(); 6435 } 6436 6437 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6438 const LValue &This, APValue &Value, 6439 QualType T) { 6440 // Objects can only be destroyed while they're within their lifetimes. 6441 // FIXME: We have no representation for whether an object of type nullptr_t 6442 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6443 // as indeterminate instead? 6444 if (Value.isAbsent() && !T->isNullPtrType()) { 6445 APValue Printable; 6446 This.moveInto(Printable); 6447 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6448 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6449 return false; 6450 } 6451 6452 // Invent an expression for location purposes. 6453 // FIXME: We shouldn't need to do this. 6454 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6455 6456 // For arrays, destroy elements right-to-left. 6457 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6458 uint64_t Size = CAT->getSize().getZExtValue(); 6459 QualType ElemT = CAT->getElementType(); 6460 6461 LValue ElemLV = This; 6462 ElemLV.addArray(Info, &LocE, CAT); 6463 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6464 return false; 6465 6466 // Ensure that we have actual array elements available to destroy; the 6467 // destructors might mutate the value, so we can't run them on the array 6468 // filler. 6469 if (Size && Size > Value.getArrayInitializedElts()) 6470 expandArray(Value, Value.getArraySize() - 1); 6471 6472 for (; Size != 0; --Size) { 6473 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6474 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6475 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6476 return false; 6477 } 6478 6479 // End the lifetime of this array now. 6480 Value = APValue(); 6481 return true; 6482 } 6483 6484 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6485 if (!RD) { 6486 if (T.isDestructedType()) { 6487 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6488 return false; 6489 } 6490 6491 Value = APValue(); 6492 return true; 6493 } 6494 6495 if (RD->getNumVBases()) { 6496 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6497 return false; 6498 } 6499 6500 const CXXDestructorDecl *DD = RD->getDestructor(); 6501 if (!DD && !RD->hasTrivialDestructor()) { 6502 Info.FFDiag(CallLoc); 6503 return false; 6504 } 6505 6506 if (!DD || DD->isTrivial() || 6507 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6508 // A trivial destructor just ends the lifetime of the object. Check for 6509 // this case before checking for a body, because we might not bother 6510 // building a body for a trivial destructor. Note that it doesn't matter 6511 // whether the destructor is constexpr in this case; all trivial 6512 // destructors are constexpr. 6513 // 6514 // If an anonymous union would be destroyed, some enclosing destructor must 6515 // have been explicitly defined, and the anonymous union destruction should 6516 // have no effect. 6517 Value = APValue(); 6518 return true; 6519 } 6520 6521 if (!Info.CheckCallLimit(CallLoc)) 6522 return false; 6523 6524 const FunctionDecl *Definition = nullptr; 6525 const Stmt *Body = DD->getBody(Definition); 6526 6527 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6528 return false; 6529 6530 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6531 6532 // We're now in the period of destruction of this object. 6533 unsigned BasesLeft = RD->getNumBases(); 6534 EvalInfo::EvaluatingDestructorRAII EvalObj( 6535 Info, 6536 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6537 if (!EvalObj.DidInsert) { 6538 // C++2a [class.dtor]p19: 6539 // the behavior is undefined if the destructor is invoked for an object 6540 // whose lifetime has ended 6541 // (Note that formally the lifetime ends when the period of destruction 6542 // begins, even though certain uses of the object remain valid until the 6543 // period of destruction ends.) 6544 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6545 return false; 6546 } 6547 6548 // FIXME: Creating an APValue just to hold a nonexistent return value is 6549 // wasteful. 6550 APValue RetVal; 6551 StmtResult Ret = {RetVal, nullptr}; 6552 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6553 return false; 6554 6555 // A union destructor does not implicitly destroy its members. 6556 if (RD->isUnion()) 6557 return true; 6558 6559 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6560 6561 // We don't have a good way to iterate fields in reverse, so collect all the 6562 // fields first and then walk them backwards. 6563 SmallVector<FieldDecl*, 16> Fields(RD->fields()); 6564 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6565 if (FD->isUnnamedBitfield()) 6566 continue; 6567 6568 LValue Subobject = This; 6569 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6570 return false; 6571 6572 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6573 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6574 FD->getType())) 6575 return false; 6576 } 6577 6578 if (BasesLeft != 0) 6579 EvalObj.startedDestroyingBases(); 6580 6581 // Destroy base classes in reverse order. 6582 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6583 --BasesLeft; 6584 6585 QualType BaseType = Base.getType(); 6586 LValue Subobject = This; 6587 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6588 BaseType->getAsCXXRecordDecl(), &Layout)) 6589 return false; 6590 6591 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6592 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6593 BaseType)) 6594 return false; 6595 } 6596 assert(BasesLeft == 0 && "NumBases was wrong?"); 6597 6598 // The period of destruction ends now. The object is gone. 6599 Value = APValue(); 6600 return true; 6601 } 6602 6603 namespace { 6604 struct DestroyObjectHandler { 6605 EvalInfo &Info; 6606 const Expr *E; 6607 const LValue &This; 6608 const AccessKinds AccessKind; 6609 6610 typedef bool result_type; 6611 bool failed() { return false; } 6612 bool found(APValue &Subobj, QualType SubobjType) { 6613 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6614 SubobjType); 6615 } 6616 bool found(APSInt &Value, QualType SubobjType) { 6617 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6618 return false; 6619 } 6620 bool found(APFloat &Value, QualType SubobjType) { 6621 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6622 return false; 6623 } 6624 }; 6625 } 6626 6627 /// Perform a destructor or pseudo-destructor call on the given object, which 6628 /// might in general not be a complete object. 6629 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6630 const LValue &This, QualType ThisType) { 6631 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6632 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6633 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6634 } 6635 6636 /// Destroy and end the lifetime of the given complete object. 6637 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6638 APValue::LValueBase LVBase, APValue &Value, 6639 QualType T) { 6640 // If we've had an unmodeled side-effect, we can't rely on mutable state 6641 // (such as the object we're about to destroy) being correct. 6642 if (Info.EvalStatus.HasSideEffects) 6643 return false; 6644 6645 LValue LV; 6646 LV.set({LVBase}); 6647 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6648 } 6649 6650 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6651 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6652 LValue &Result) { 6653 if (Info.checkingPotentialConstantExpression() || 6654 Info.SpeculativeEvaluationDepth) 6655 return false; 6656 6657 // This is permitted only within a call to std::allocator<T>::allocate. 6658 auto Caller = Info.getStdAllocatorCaller("allocate"); 6659 if (!Caller) { 6660 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6661 ? diag::note_constexpr_new_untyped 6662 : diag::note_constexpr_new); 6663 return false; 6664 } 6665 6666 QualType ElemType = Caller.ElemType; 6667 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6668 Info.FFDiag(E->getExprLoc(), 6669 diag::note_constexpr_new_not_complete_object_type) 6670 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6671 return false; 6672 } 6673 6674 APSInt ByteSize; 6675 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6676 return false; 6677 bool IsNothrow = false; 6678 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6679 EvaluateIgnoredValue(Info, E->getArg(I)); 6680 IsNothrow |= E->getType()->isNothrowT(); 6681 } 6682 6683 CharUnits ElemSize; 6684 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6685 return false; 6686 APInt Size, Remainder; 6687 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6688 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6689 if (Remainder != 0) { 6690 // This likely indicates a bug in the implementation of 'std::allocator'. 6691 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6692 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6693 return false; 6694 } 6695 6696 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6697 if (IsNothrow) { 6698 Result.setNull(Info.Ctx, E->getType()); 6699 return true; 6700 } 6701 6702 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6703 return false; 6704 } 6705 6706 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6707 ArrayType::Normal, 0); 6708 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6709 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6710 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6711 return true; 6712 } 6713 6714 static bool hasVirtualDestructor(QualType T) { 6715 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6716 if (CXXDestructorDecl *DD = RD->getDestructor()) 6717 return DD->isVirtual(); 6718 return false; 6719 } 6720 6721 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6722 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6723 if (CXXDestructorDecl *DD = RD->getDestructor()) 6724 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6725 return nullptr; 6726 } 6727 6728 /// Check that the given object is a suitable pointer to a heap allocation that 6729 /// still exists and is of the right kind for the purpose of a deletion. 6730 /// 6731 /// On success, returns the heap allocation to deallocate. On failure, produces 6732 /// a diagnostic and returns None. 6733 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6734 const LValue &Pointer, 6735 DynAlloc::Kind DeallocKind) { 6736 auto PointerAsString = [&] { 6737 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6738 }; 6739 6740 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6741 if (!DA) { 6742 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6743 << PointerAsString(); 6744 if (Pointer.Base) 6745 NoteLValueLocation(Info, Pointer.Base); 6746 return None; 6747 } 6748 6749 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6750 if (!Alloc) { 6751 Info.FFDiag(E, diag::note_constexpr_double_delete); 6752 return None; 6753 } 6754 6755 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6756 if (DeallocKind != (*Alloc)->getKind()) { 6757 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6758 << DeallocKind << (*Alloc)->getKind() << AllocType; 6759 NoteLValueLocation(Info, Pointer.Base); 6760 return None; 6761 } 6762 6763 bool Subobject = false; 6764 if (DeallocKind == DynAlloc::New) { 6765 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6766 Pointer.Designator.isOnePastTheEnd(); 6767 } else { 6768 Subobject = Pointer.Designator.Entries.size() != 1 || 6769 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6770 } 6771 if (Subobject) { 6772 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6773 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6774 return None; 6775 } 6776 6777 return Alloc; 6778 } 6779 6780 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6781 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6782 if (Info.checkingPotentialConstantExpression() || 6783 Info.SpeculativeEvaluationDepth) 6784 return false; 6785 6786 // This is permitted only within a call to std::allocator<T>::deallocate. 6787 if (!Info.getStdAllocatorCaller("deallocate")) { 6788 Info.FFDiag(E->getExprLoc()); 6789 return true; 6790 } 6791 6792 LValue Pointer; 6793 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6794 return false; 6795 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6796 EvaluateIgnoredValue(Info, E->getArg(I)); 6797 6798 if (Pointer.Designator.Invalid) 6799 return false; 6800 6801 // Deleting a null pointer would have no effect, but it's not permitted by 6802 // std::allocator<T>::deallocate's contract. 6803 if (Pointer.isNullPointer()) { 6804 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6805 return true; 6806 } 6807 6808 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6809 return false; 6810 6811 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6812 return true; 6813 } 6814 6815 //===----------------------------------------------------------------------===// 6816 // Generic Evaluation 6817 //===----------------------------------------------------------------------===// 6818 namespace { 6819 6820 class BitCastBuffer { 6821 // FIXME: We're going to need bit-level granularity when we support 6822 // bit-fields. 6823 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6824 // we don't support a host or target where that is the case. Still, we should 6825 // use a more generic type in case we ever do. 6826 SmallVector<Optional<unsigned char>, 32> Bytes; 6827 6828 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6829 "Need at least 8 bit unsigned char"); 6830 6831 bool TargetIsLittleEndian; 6832 6833 public: 6834 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6835 : Bytes(Width.getQuantity()), 6836 TargetIsLittleEndian(TargetIsLittleEndian) {} 6837 6838 LLVM_NODISCARD 6839 bool readObject(CharUnits Offset, CharUnits Width, 6840 SmallVectorImpl<unsigned char> &Output) const { 6841 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6842 // If a byte of an integer is uninitialized, then the whole integer is 6843 // uninitialized. 6844 if (!Bytes[I.getQuantity()]) 6845 return false; 6846 Output.push_back(*Bytes[I.getQuantity()]); 6847 } 6848 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6849 std::reverse(Output.begin(), Output.end()); 6850 return true; 6851 } 6852 6853 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6854 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6855 std::reverse(Input.begin(), Input.end()); 6856 6857 size_t Index = 0; 6858 for (unsigned char Byte : Input) { 6859 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6860 Bytes[Offset.getQuantity() + Index] = Byte; 6861 ++Index; 6862 } 6863 } 6864 6865 size_t size() { return Bytes.size(); } 6866 }; 6867 6868 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6869 /// target would represent the value at runtime. 6870 class APValueToBufferConverter { 6871 EvalInfo &Info; 6872 BitCastBuffer Buffer; 6873 const CastExpr *BCE; 6874 6875 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6876 const CastExpr *BCE) 6877 : Info(Info), 6878 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6879 BCE(BCE) {} 6880 6881 bool visit(const APValue &Val, QualType Ty) { 6882 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6883 } 6884 6885 // Write out Val with type Ty into Buffer starting at Offset. 6886 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6887 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6888 6889 // As a special case, nullptr_t has an indeterminate value. 6890 if (Ty->isNullPtrType()) 6891 return true; 6892 6893 // Dig through Src to find the byte at SrcOffset. 6894 switch (Val.getKind()) { 6895 case APValue::Indeterminate: 6896 case APValue::None: 6897 return true; 6898 6899 case APValue::Int: 6900 return visitInt(Val.getInt(), Ty, Offset); 6901 case APValue::Float: 6902 return visitFloat(Val.getFloat(), Ty, Offset); 6903 case APValue::Array: 6904 return visitArray(Val, Ty, Offset); 6905 case APValue::Struct: 6906 return visitRecord(Val, Ty, Offset); 6907 6908 case APValue::ComplexInt: 6909 case APValue::ComplexFloat: 6910 case APValue::Vector: 6911 case APValue::FixedPoint: 6912 // FIXME: We should support these. 6913 6914 case APValue::Union: 6915 case APValue::MemberPointer: 6916 case APValue::AddrLabelDiff: { 6917 Info.FFDiag(BCE->getBeginLoc(), 6918 diag::note_constexpr_bit_cast_unsupported_type) 6919 << Ty; 6920 return false; 6921 } 6922 6923 case APValue::LValue: 6924 llvm_unreachable("LValue subobject in bit_cast?"); 6925 } 6926 llvm_unreachable("Unhandled APValue::ValueKind"); 6927 } 6928 6929 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6930 const RecordDecl *RD = Ty->getAsRecordDecl(); 6931 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6932 6933 // Visit the base classes. 6934 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6935 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6936 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6937 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6938 6939 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6940 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6941 return false; 6942 } 6943 } 6944 6945 // Visit the fields. 6946 unsigned FieldIdx = 0; 6947 for (FieldDecl *FD : RD->fields()) { 6948 if (FD->isBitField()) { 6949 Info.FFDiag(BCE->getBeginLoc(), 6950 diag::note_constexpr_bit_cast_unsupported_bitfield); 6951 return false; 6952 } 6953 6954 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6955 6956 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6957 "only bit-fields can have sub-char alignment"); 6958 CharUnits FieldOffset = 6959 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6960 QualType FieldTy = FD->getType(); 6961 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6962 return false; 6963 ++FieldIdx; 6964 } 6965 6966 return true; 6967 } 6968 6969 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6970 const auto *CAT = 6971 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6972 if (!CAT) 6973 return false; 6974 6975 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6976 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6977 unsigned ArraySize = Val.getArraySize(); 6978 // First, initialize the initialized elements. 6979 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6980 const APValue &SubObj = Val.getArrayInitializedElt(I); 6981 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6982 return false; 6983 } 6984 6985 // Next, initialize the rest of the array using the filler. 6986 if (Val.hasArrayFiller()) { 6987 const APValue &Filler = Val.getArrayFiller(); 6988 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6989 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6990 return false; 6991 } 6992 } 6993 6994 return true; 6995 } 6996 6997 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6998 APSInt AdjustedVal = Val; 6999 unsigned Width = AdjustedVal.getBitWidth(); 7000 if (Ty->isBooleanType()) { 7001 Width = Info.Ctx.getTypeSize(Ty); 7002 AdjustedVal = AdjustedVal.extend(Width); 7003 } 7004 7005 SmallVector<unsigned char, 8> Bytes(Width / 8); 7006 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 7007 Buffer.writeObject(Offset, Bytes); 7008 return true; 7009 } 7010 7011 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 7012 APSInt AsInt(Val.bitcastToAPInt()); 7013 return visitInt(AsInt, Ty, Offset); 7014 } 7015 7016 public: 7017 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 7018 const CastExpr *BCE) { 7019 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 7020 APValueToBufferConverter Converter(Info, DstSize, BCE); 7021 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 7022 return None; 7023 return Converter.Buffer; 7024 } 7025 }; 7026 7027 /// Write an BitCastBuffer into an APValue. 7028 class BufferToAPValueConverter { 7029 EvalInfo &Info; 7030 const BitCastBuffer &Buffer; 7031 const CastExpr *BCE; 7032 7033 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 7034 const CastExpr *BCE) 7035 : Info(Info), Buffer(Buffer), BCE(BCE) {} 7036 7037 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 7038 // with an invalid type, so anything left is a deficiency on our part (FIXME). 7039 // Ideally this will be unreachable. 7040 llvm::NoneType unsupportedType(QualType Ty) { 7041 Info.FFDiag(BCE->getBeginLoc(), 7042 diag::note_constexpr_bit_cast_unsupported_type) 7043 << Ty; 7044 return None; 7045 } 7046 7047 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 7048 Info.FFDiag(BCE->getBeginLoc(), 7049 diag::note_constexpr_bit_cast_unrepresentable_value) 7050 << Ty << toString(Val, /*Radix=*/10); 7051 return None; 7052 } 7053 7054 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 7055 const EnumType *EnumSugar = nullptr) { 7056 if (T->isNullPtrType()) { 7057 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 7058 return APValue((Expr *)nullptr, 7059 /*Offset=*/CharUnits::fromQuantity(NullValue), 7060 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 7061 } 7062 7063 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 7064 7065 // Work around floating point types that contain unused padding bytes. This 7066 // is really just `long double` on x86, which is the only fundamental type 7067 // with padding bytes. 7068 if (T->isRealFloatingType()) { 7069 const llvm::fltSemantics &Semantics = 7070 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7071 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 7072 assert(NumBits % 8 == 0); 7073 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 7074 if (NumBytes != SizeOf) 7075 SizeOf = NumBytes; 7076 } 7077 7078 SmallVector<uint8_t, 8> Bytes; 7079 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7080 // If this is std::byte or unsigned char, then its okay to store an 7081 // indeterminate value. 7082 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7083 bool IsUChar = 7084 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7085 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7086 if (!IsStdByte && !IsUChar) { 7087 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7088 Info.FFDiag(BCE->getExprLoc(), 7089 diag::note_constexpr_bit_cast_indet_dest) 7090 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7091 return None; 7092 } 7093 7094 return APValue::IndeterminateValue(); 7095 } 7096 7097 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7098 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7099 7100 if (T->isIntegralOrEnumerationType()) { 7101 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7102 7103 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7104 if (IntWidth != Val.getBitWidth()) { 7105 APSInt Truncated = Val.trunc(IntWidth); 7106 if (Truncated.extend(Val.getBitWidth()) != Val) 7107 return unrepresentableValue(QualType(T, 0), Val); 7108 Val = Truncated; 7109 } 7110 7111 return APValue(Val); 7112 } 7113 7114 if (T->isRealFloatingType()) { 7115 const llvm::fltSemantics &Semantics = 7116 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7117 return APValue(APFloat(Semantics, Val)); 7118 } 7119 7120 return unsupportedType(QualType(T, 0)); 7121 } 7122 7123 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7124 const RecordDecl *RD = RTy->getAsRecordDecl(); 7125 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7126 7127 unsigned NumBases = 0; 7128 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7129 NumBases = CXXRD->getNumBases(); 7130 7131 APValue ResultVal(APValue::UninitStruct(), NumBases, 7132 std::distance(RD->field_begin(), RD->field_end())); 7133 7134 // Visit the base classes. 7135 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7136 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7137 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7138 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7139 if (BaseDecl->isEmpty() || 7140 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7141 continue; 7142 7143 Optional<APValue> SubObj = visitType( 7144 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7145 if (!SubObj) 7146 return None; 7147 ResultVal.getStructBase(I) = *SubObj; 7148 } 7149 } 7150 7151 // Visit the fields. 7152 unsigned FieldIdx = 0; 7153 for (FieldDecl *FD : RD->fields()) { 7154 // FIXME: We don't currently support bit-fields. A lot of the logic for 7155 // this is in CodeGen, so we need to factor it around. 7156 if (FD->isBitField()) { 7157 Info.FFDiag(BCE->getBeginLoc(), 7158 diag::note_constexpr_bit_cast_unsupported_bitfield); 7159 return None; 7160 } 7161 7162 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7163 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7164 7165 CharUnits FieldOffset = 7166 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7167 Offset; 7168 QualType FieldTy = FD->getType(); 7169 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7170 if (!SubObj) 7171 return None; 7172 ResultVal.getStructField(FieldIdx) = *SubObj; 7173 ++FieldIdx; 7174 } 7175 7176 return ResultVal; 7177 } 7178 7179 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7180 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7181 assert(!RepresentationType.isNull() && 7182 "enum forward decl should be caught by Sema"); 7183 const auto *AsBuiltin = 7184 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7185 // Recurse into the underlying type. Treat std::byte transparently as 7186 // unsigned char. 7187 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7188 } 7189 7190 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7191 size_t Size = Ty->getSize().getLimitedValue(); 7192 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7193 7194 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7195 for (size_t I = 0; I != Size; ++I) { 7196 Optional<APValue> ElementValue = 7197 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7198 if (!ElementValue) 7199 return None; 7200 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7201 } 7202 7203 return ArrayValue; 7204 } 7205 7206 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7207 return unsupportedType(QualType(Ty, 0)); 7208 } 7209 7210 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7211 QualType Can = Ty.getCanonicalType(); 7212 7213 switch (Can->getTypeClass()) { 7214 #define TYPE(Class, Base) \ 7215 case Type::Class: \ 7216 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7217 #define ABSTRACT_TYPE(Class, Base) 7218 #define NON_CANONICAL_TYPE(Class, Base) \ 7219 case Type::Class: \ 7220 llvm_unreachable("non-canonical type should be impossible!"); 7221 #define DEPENDENT_TYPE(Class, Base) \ 7222 case Type::Class: \ 7223 llvm_unreachable( \ 7224 "dependent types aren't supported in the constant evaluator!"); 7225 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7226 case Type::Class: \ 7227 llvm_unreachable("either dependent or not canonical!"); 7228 #include "clang/AST/TypeNodes.inc" 7229 } 7230 llvm_unreachable("Unhandled Type::TypeClass"); 7231 } 7232 7233 public: 7234 // Pull out a full value of type DstType. 7235 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7236 const CastExpr *BCE) { 7237 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7238 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7239 } 7240 }; 7241 7242 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7243 QualType Ty, EvalInfo *Info, 7244 const ASTContext &Ctx, 7245 bool CheckingDest) { 7246 Ty = Ty.getCanonicalType(); 7247 7248 auto diag = [&](int Reason) { 7249 if (Info) 7250 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7251 << CheckingDest << (Reason == 4) << Reason; 7252 return false; 7253 }; 7254 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7255 if (Info) 7256 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7257 << NoteTy << Construct << Ty; 7258 return false; 7259 }; 7260 7261 if (Ty->isUnionType()) 7262 return diag(0); 7263 if (Ty->isPointerType()) 7264 return diag(1); 7265 if (Ty->isMemberPointerType()) 7266 return diag(2); 7267 if (Ty.isVolatileQualified()) 7268 return diag(3); 7269 7270 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7271 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7272 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7273 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7274 CheckingDest)) 7275 return note(1, BS.getType(), BS.getBeginLoc()); 7276 } 7277 for (FieldDecl *FD : Record->fields()) { 7278 if (FD->getType()->isReferenceType()) 7279 return diag(4); 7280 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7281 CheckingDest)) 7282 return note(0, FD->getType(), FD->getBeginLoc()); 7283 } 7284 } 7285 7286 if (Ty->isArrayType() && 7287 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7288 Info, Ctx, CheckingDest)) 7289 return false; 7290 7291 return true; 7292 } 7293 7294 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7295 const ASTContext &Ctx, 7296 const CastExpr *BCE) { 7297 bool DestOK = checkBitCastConstexprEligibilityType( 7298 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7299 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7300 BCE->getBeginLoc(), 7301 BCE->getSubExpr()->getType(), Info, Ctx, false); 7302 return SourceOK; 7303 } 7304 7305 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7306 APValue &SourceValue, 7307 const CastExpr *BCE) { 7308 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7309 "no host or target supports non 8-bit chars"); 7310 assert(SourceValue.isLValue() && 7311 "LValueToRValueBitcast requires an lvalue operand!"); 7312 7313 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7314 return false; 7315 7316 LValue SourceLValue; 7317 APValue SourceRValue; 7318 SourceLValue.setFrom(Info.Ctx, SourceValue); 7319 if (!handleLValueToRValueConversion( 7320 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7321 SourceRValue, /*WantObjectRepresentation=*/true)) 7322 return false; 7323 7324 // Read out SourceValue into a char buffer. 7325 Optional<BitCastBuffer> Buffer = 7326 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7327 if (!Buffer) 7328 return false; 7329 7330 // Write out the buffer into a new APValue. 7331 Optional<APValue> MaybeDestValue = 7332 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7333 if (!MaybeDestValue) 7334 return false; 7335 7336 DestValue = std::move(*MaybeDestValue); 7337 return true; 7338 } 7339 7340 template <class Derived> 7341 class ExprEvaluatorBase 7342 : public ConstStmtVisitor<Derived, bool> { 7343 private: 7344 Derived &getDerived() { return static_cast<Derived&>(*this); } 7345 bool DerivedSuccess(const APValue &V, const Expr *E) { 7346 return getDerived().Success(V, E); 7347 } 7348 bool DerivedZeroInitialization(const Expr *E) { 7349 return getDerived().ZeroInitialization(E); 7350 } 7351 7352 // Check whether a conditional operator with a non-constant condition is a 7353 // potential constant expression. If neither arm is a potential constant 7354 // expression, then the conditional operator is not either. 7355 template<typename ConditionalOperator> 7356 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7357 assert(Info.checkingPotentialConstantExpression()); 7358 7359 // Speculatively evaluate both arms. 7360 SmallVector<PartialDiagnosticAt, 8> Diag; 7361 { 7362 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7363 StmtVisitorTy::Visit(E->getFalseExpr()); 7364 if (Diag.empty()) 7365 return; 7366 } 7367 7368 { 7369 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7370 Diag.clear(); 7371 StmtVisitorTy::Visit(E->getTrueExpr()); 7372 if (Diag.empty()) 7373 return; 7374 } 7375 7376 Error(E, diag::note_constexpr_conditional_never_const); 7377 } 7378 7379 7380 template<typename ConditionalOperator> 7381 bool HandleConditionalOperator(const ConditionalOperator *E) { 7382 bool BoolResult; 7383 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7384 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7385 CheckPotentialConstantConditional(E); 7386 return false; 7387 } 7388 if (Info.noteFailure()) { 7389 StmtVisitorTy::Visit(E->getTrueExpr()); 7390 StmtVisitorTy::Visit(E->getFalseExpr()); 7391 } 7392 return false; 7393 } 7394 7395 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7396 return StmtVisitorTy::Visit(EvalExpr); 7397 } 7398 7399 protected: 7400 EvalInfo &Info; 7401 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7402 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7403 7404 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7405 return Info.CCEDiag(E, D); 7406 } 7407 7408 bool ZeroInitialization(const Expr *E) { return Error(E); } 7409 7410 public: 7411 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7412 7413 EvalInfo &getEvalInfo() { return Info; } 7414 7415 /// Report an evaluation error. This should only be called when an error is 7416 /// first discovered. When propagating an error, just return false. 7417 bool Error(const Expr *E, diag::kind D) { 7418 Info.FFDiag(E, D); 7419 return false; 7420 } 7421 bool Error(const Expr *E) { 7422 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7423 } 7424 7425 bool VisitStmt(const Stmt *) { 7426 llvm_unreachable("Expression evaluator should not be called on stmts"); 7427 } 7428 bool VisitExpr(const Expr *E) { 7429 return Error(E); 7430 } 7431 7432 bool VisitConstantExpr(const ConstantExpr *E) { 7433 if (E->hasAPValueResult()) 7434 return DerivedSuccess(E->getAPValueResult(), E); 7435 7436 return StmtVisitorTy::Visit(E->getSubExpr()); 7437 } 7438 7439 bool VisitParenExpr(const ParenExpr *E) 7440 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7441 bool VisitUnaryExtension(const UnaryOperator *E) 7442 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7443 bool VisitUnaryPlus(const UnaryOperator *E) 7444 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7445 bool VisitChooseExpr(const ChooseExpr *E) 7446 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7447 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7448 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7449 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7450 { return StmtVisitorTy::Visit(E->getReplacement()); } 7451 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7452 TempVersionRAII RAII(*Info.CurrentCall); 7453 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7454 return StmtVisitorTy::Visit(E->getExpr()); 7455 } 7456 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7457 TempVersionRAII RAII(*Info.CurrentCall); 7458 // The initializer may not have been parsed yet, or might be erroneous. 7459 if (!E->getExpr()) 7460 return Error(E); 7461 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7462 return StmtVisitorTy::Visit(E->getExpr()); 7463 } 7464 7465 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7466 FullExpressionRAII Scope(Info); 7467 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7468 } 7469 7470 // Temporaries are registered when created, so we don't care about 7471 // CXXBindTemporaryExpr. 7472 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7473 return StmtVisitorTy::Visit(E->getSubExpr()); 7474 } 7475 7476 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7477 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7478 return static_cast<Derived*>(this)->VisitCastExpr(E); 7479 } 7480 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7481 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7482 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7483 return static_cast<Derived*>(this)->VisitCastExpr(E); 7484 } 7485 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7486 return static_cast<Derived*>(this)->VisitCastExpr(E); 7487 } 7488 7489 bool VisitBinaryOperator(const BinaryOperator *E) { 7490 switch (E->getOpcode()) { 7491 default: 7492 return Error(E); 7493 7494 case BO_Comma: 7495 VisitIgnoredValue(E->getLHS()); 7496 return StmtVisitorTy::Visit(E->getRHS()); 7497 7498 case BO_PtrMemD: 7499 case BO_PtrMemI: { 7500 LValue Obj; 7501 if (!HandleMemberPointerAccess(Info, E, Obj)) 7502 return false; 7503 APValue Result; 7504 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7505 return false; 7506 return DerivedSuccess(Result, E); 7507 } 7508 } 7509 } 7510 7511 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7512 return StmtVisitorTy::Visit(E->getSemanticForm()); 7513 } 7514 7515 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7516 // Evaluate and cache the common expression. We treat it as a temporary, 7517 // even though it's not quite the same thing. 7518 LValue CommonLV; 7519 if (!Evaluate(Info.CurrentCall->createTemporary( 7520 E->getOpaqueValue(), 7521 getStorageType(Info.Ctx, E->getOpaqueValue()), 7522 ScopeKind::FullExpression, CommonLV), 7523 Info, E->getCommon())) 7524 return false; 7525 7526 return HandleConditionalOperator(E); 7527 } 7528 7529 bool VisitConditionalOperator(const ConditionalOperator *E) { 7530 bool IsBcpCall = false; 7531 // If the condition (ignoring parens) is a __builtin_constant_p call, 7532 // the result is a constant expression if it can be folded without 7533 // side-effects. This is an important GNU extension. See GCC PR38377 7534 // for discussion. 7535 if (const CallExpr *CallCE = 7536 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7537 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7538 IsBcpCall = true; 7539 7540 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7541 // constant expression; we can't check whether it's potentially foldable. 7542 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7543 // it would return 'false' in this mode. 7544 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7545 return false; 7546 7547 FoldConstant Fold(Info, IsBcpCall); 7548 if (!HandleConditionalOperator(E)) { 7549 Fold.keepDiagnostics(); 7550 return false; 7551 } 7552 7553 return true; 7554 } 7555 7556 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7557 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7558 return DerivedSuccess(*Value, E); 7559 7560 const Expr *Source = E->getSourceExpr(); 7561 if (!Source) 7562 return Error(E); 7563 if (Source == E) { 7564 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7565 return Error(E); 7566 } 7567 return StmtVisitorTy::Visit(Source); 7568 } 7569 7570 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7571 for (const Expr *SemE : E->semantics()) { 7572 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7573 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7574 // result expression: there could be two different LValues that would 7575 // refer to the same object in that case, and we can't model that. 7576 if (SemE == E->getResultExpr()) 7577 return Error(E); 7578 7579 // Unique OVEs get evaluated if and when we encounter them when 7580 // emitting the rest of the semantic form, rather than eagerly. 7581 if (OVE->isUnique()) 7582 continue; 7583 7584 LValue LV; 7585 if (!Evaluate(Info.CurrentCall->createTemporary( 7586 OVE, getStorageType(Info.Ctx, OVE), 7587 ScopeKind::FullExpression, LV), 7588 Info, OVE->getSourceExpr())) 7589 return false; 7590 } else if (SemE == E->getResultExpr()) { 7591 if (!StmtVisitorTy::Visit(SemE)) 7592 return false; 7593 } else { 7594 if (!EvaluateIgnoredValue(Info, SemE)) 7595 return false; 7596 } 7597 } 7598 return true; 7599 } 7600 7601 bool VisitCallExpr(const CallExpr *E) { 7602 APValue Result; 7603 if (!handleCallExpr(E, Result, nullptr)) 7604 return false; 7605 return DerivedSuccess(Result, E); 7606 } 7607 7608 bool handleCallExpr(const CallExpr *E, APValue &Result, 7609 const LValue *ResultSlot) { 7610 CallScopeRAII CallScope(Info); 7611 7612 const Expr *Callee = E->getCallee()->IgnoreParens(); 7613 QualType CalleeType = Callee->getType(); 7614 7615 const FunctionDecl *FD = nullptr; 7616 LValue *This = nullptr, ThisVal; 7617 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7618 bool HasQualifier = false; 7619 7620 CallRef Call; 7621 7622 // Extract function decl and 'this' pointer from the callee. 7623 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7624 const CXXMethodDecl *Member = nullptr; 7625 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7626 // Explicit bound member calls, such as x.f() or p->g(); 7627 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7628 return false; 7629 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7630 if (!Member) 7631 return Error(Callee); 7632 This = &ThisVal; 7633 HasQualifier = ME->hasQualifier(); 7634 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7635 // Indirect bound member calls ('.*' or '->*'). 7636 const ValueDecl *D = 7637 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7638 if (!D) 7639 return false; 7640 Member = dyn_cast<CXXMethodDecl>(D); 7641 if (!Member) 7642 return Error(Callee); 7643 This = &ThisVal; 7644 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7645 if (!Info.getLangOpts().CPlusPlus20) 7646 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7647 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7648 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7649 } else 7650 return Error(Callee); 7651 FD = Member; 7652 } else if (CalleeType->isFunctionPointerType()) { 7653 LValue CalleeLV; 7654 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7655 return false; 7656 7657 if (!CalleeLV.getLValueOffset().isZero()) 7658 return Error(Callee); 7659 FD = dyn_cast_or_null<FunctionDecl>( 7660 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7661 if (!FD) 7662 return Error(Callee); 7663 // Don't call function pointers which have been cast to some other type. 7664 // Per DR (no number yet), the caller and callee can differ in noexcept. 7665 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7666 CalleeType->getPointeeType(), FD->getType())) { 7667 return Error(E); 7668 } 7669 7670 // For an (overloaded) assignment expression, evaluate the RHS before the 7671 // LHS. 7672 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7673 if (OCE && OCE->isAssignmentOp()) { 7674 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7675 Call = Info.CurrentCall->createCall(FD); 7676 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7677 Info, FD, /*RightToLeft=*/true)) 7678 return false; 7679 } 7680 7681 // Overloaded operator calls to member functions are represented as normal 7682 // calls with '*this' as the first argument. 7683 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7684 if (MD && !MD->isStatic()) { 7685 // FIXME: When selecting an implicit conversion for an overloaded 7686 // operator delete, we sometimes try to evaluate calls to conversion 7687 // operators without a 'this' parameter! 7688 if (Args.empty()) 7689 return Error(E); 7690 7691 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7692 return false; 7693 This = &ThisVal; 7694 7695 // If this is syntactically a simple assignment using a trivial 7696 // assignment operator, start the lifetimes of union members as needed, 7697 // per C++20 [class.union]5. 7698 if (Info.getLangOpts().CPlusPlus20 && OCE && 7699 OCE->getOperator() == OO_Equal && MD->isTrivial() && 7700 !HandleUnionActiveMemberChange(Info, Args[0], ThisVal)) 7701 return false; 7702 7703 Args = Args.slice(1); 7704 } else if (MD && MD->isLambdaStaticInvoker()) { 7705 // Map the static invoker for the lambda back to the call operator. 7706 // Conveniently, we don't have to slice out the 'this' argument (as is 7707 // being done for the non-static case), since a static member function 7708 // doesn't have an implicit argument passed in. 7709 const CXXRecordDecl *ClosureClass = MD->getParent(); 7710 assert( 7711 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7712 "Number of captures must be zero for conversion to function-ptr"); 7713 7714 const CXXMethodDecl *LambdaCallOp = 7715 ClosureClass->getLambdaCallOperator(); 7716 7717 // Set 'FD', the function that will be called below, to the call 7718 // operator. If the closure object represents a generic lambda, find 7719 // the corresponding specialization of the call operator. 7720 7721 if (ClosureClass->isGenericLambda()) { 7722 assert(MD->isFunctionTemplateSpecialization() && 7723 "A generic lambda's static-invoker function must be a " 7724 "template specialization"); 7725 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7726 FunctionTemplateDecl *CallOpTemplate = 7727 LambdaCallOp->getDescribedFunctionTemplate(); 7728 void *InsertPos = nullptr; 7729 FunctionDecl *CorrespondingCallOpSpecialization = 7730 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7731 assert(CorrespondingCallOpSpecialization && 7732 "We must always have a function call operator specialization " 7733 "that corresponds to our static invoker specialization"); 7734 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7735 } else 7736 FD = LambdaCallOp; 7737 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7738 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7739 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7740 LValue Ptr; 7741 if (!HandleOperatorNewCall(Info, E, Ptr)) 7742 return false; 7743 Ptr.moveInto(Result); 7744 return CallScope.destroy(); 7745 } else { 7746 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7747 } 7748 } 7749 } else 7750 return Error(E); 7751 7752 // Evaluate the arguments now if we've not already done so. 7753 if (!Call) { 7754 Call = Info.CurrentCall->createCall(FD); 7755 if (!EvaluateArgs(Args, Call, Info, FD)) 7756 return false; 7757 } 7758 7759 SmallVector<QualType, 4> CovariantAdjustmentPath; 7760 if (This) { 7761 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7762 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7763 // Perform virtual dispatch, if necessary. 7764 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7765 CovariantAdjustmentPath); 7766 if (!FD) 7767 return false; 7768 } else { 7769 // Check that the 'this' pointer points to an object of the right type. 7770 // FIXME: If this is an assignment operator call, we may need to change 7771 // the active union member before we check this. 7772 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7773 return false; 7774 } 7775 } 7776 7777 // Destructor calls are different enough that they have their own codepath. 7778 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7779 assert(This && "no 'this' pointer for destructor call"); 7780 return HandleDestruction(Info, E, *This, 7781 Info.Ctx.getRecordType(DD->getParent())) && 7782 CallScope.destroy(); 7783 } 7784 7785 const FunctionDecl *Definition = nullptr; 7786 Stmt *Body = FD->getBody(Definition); 7787 7788 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7789 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7790 Body, Info, Result, ResultSlot)) 7791 return false; 7792 7793 if (!CovariantAdjustmentPath.empty() && 7794 !HandleCovariantReturnAdjustment(Info, E, Result, 7795 CovariantAdjustmentPath)) 7796 return false; 7797 7798 return CallScope.destroy(); 7799 } 7800 7801 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7802 return StmtVisitorTy::Visit(E->getInitializer()); 7803 } 7804 bool VisitInitListExpr(const InitListExpr *E) { 7805 if (E->getNumInits() == 0) 7806 return DerivedZeroInitialization(E); 7807 if (E->getNumInits() == 1) 7808 return StmtVisitorTy::Visit(E->getInit(0)); 7809 return Error(E); 7810 } 7811 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7812 return DerivedZeroInitialization(E); 7813 } 7814 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7815 return DerivedZeroInitialization(E); 7816 } 7817 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7818 return DerivedZeroInitialization(E); 7819 } 7820 7821 /// A member expression where the object is a prvalue is itself a prvalue. 7822 bool VisitMemberExpr(const MemberExpr *E) { 7823 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7824 "missing temporary materialization conversion"); 7825 assert(!E->isArrow() && "missing call to bound member function?"); 7826 7827 APValue Val; 7828 if (!Evaluate(Val, Info, E->getBase())) 7829 return false; 7830 7831 QualType BaseTy = E->getBase()->getType(); 7832 7833 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7834 if (!FD) return Error(E); 7835 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7836 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7837 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7838 7839 // Note: there is no lvalue base here. But this case should only ever 7840 // happen in C or in C++98, where we cannot be evaluating a constexpr 7841 // constructor, which is the only case the base matters. 7842 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7843 SubobjectDesignator Designator(BaseTy); 7844 Designator.addDeclUnchecked(FD); 7845 7846 APValue Result; 7847 return extractSubobject(Info, E, Obj, Designator, Result) && 7848 DerivedSuccess(Result, E); 7849 } 7850 7851 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7852 APValue Val; 7853 if (!Evaluate(Val, Info, E->getBase())) 7854 return false; 7855 7856 if (Val.isVector()) { 7857 SmallVector<uint32_t, 4> Indices; 7858 E->getEncodedElementAccess(Indices); 7859 if (Indices.size() == 1) { 7860 // Return scalar. 7861 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7862 } else { 7863 // Construct new APValue vector. 7864 SmallVector<APValue, 4> Elts; 7865 for (unsigned I = 0; I < Indices.size(); ++I) { 7866 Elts.push_back(Val.getVectorElt(Indices[I])); 7867 } 7868 APValue VecResult(Elts.data(), Indices.size()); 7869 return DerivedSuccess(VecResult, E); 7870 } 7871 } 7872 7873 return false; 7874 } 7875 7876 bool VisitCastExpr(const CastExpr *E) { 7877 switch (E->getCastKind()) { 7878 default: 7879 break; 7880 7881 case CK_AtomicToNonAtomic: { 7882 APValue AtomicVal; 7883 // This does not need to be done in place even for class/array types: 7884 // atomic-to-non-atomic conversion implies copying the object 7885 // representation. 7886 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7887 return false; 7888 return DerivedSuccess(AtomicVal, E); 7889 } 7890 7891 case CK_NoOp: 7892 case CK_UserDefinedConversion: 7893 return StmtVisitorTy::Visit(E->getSubExpr()); 7894 7895 case CK_LValueToRValue: { 7896 LValue LVal; 7897 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7898 return false; 7899 APValue RVal; 7900 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7901 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7902 LVal, RVal)) 7903 return false; 7904 return DerivedSuccess(RVal, E); 7905 } 7906 case CK_LValueToRValueBitCast: { 7907 APValue DestValue, SourceValue; 7908 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7909 return false; 7910 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7911 return false; 7912 return DerivedSuccess(DestValue, E); 7913 } 7914 7915 case CK_AddressSpaceConversion: { 7916 APValue Value; 7917 if (!Evaluate(Value, Info, E->getSubExpr())) 7918 return false; 7919 return DerivedSuccess(Value, E); 7920 } 7921 } 7922 7923 return Error(E); 7924 } 7925 7926 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7927 return VisitUnaryPostIncDec(UO); 7928 } 7929 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7930 return VisitUnaryPostIncDec(UO); 7931 } 7932 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7933 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7934 return Error(UO); 7935 7936 LValue LVal; 7937 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7938 return false; 7939 APValue RVal; 7940 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7941 UO->isIncrementOp(), &RVal)) 7942 return false; 7943 return DerivedSuccess(RVal, UO); 7944 } 7945 7946 bool VisitStmtExpr(const StmtExpr *E) { 7947 // We will have checked the full-expressions inside the statement expression 7948 // when they were completed, and don't need to check them again now. 7949 llvm::SaveAndRestore<bool> NotCheckingForUB( 7950 Info.CheckingForUndefinedBehavior, false); 7951 7952 const CompoundStmt *CS = E->getSubStmt(); 7953 if (CS->body_empty()) 7954 return true; 7955 7956 BlockScopeRAII Scope(Info); 7957 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7958 BE = CS->body_end(); 7959 /**/; ++BI) { 7960 if (BI + 1 == BE) { 7961 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7962 if (!FinalExpr) { 7963 Info.FFDiag((*BI)->getBeginLoc(), 7964 diag::note_constexpr_stmt_expr_unsupported); 7965 return false; 7966 } 7967 return this->Visit(FinalExpr) && Scope.destroy(); 7968 } 7969 7970 APValue ReturnValue; 7971 StmtResult Result = { ReturnValue, nullptr }; 7972 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7973 if (ESR != ESR_Succeeded) { 7974 // FIXME: If the statement-expression terminated due to 'return', 7975 // 'break', or 'continue', it would be nice to propagate that to 7976 // the outer statement evaluation rather than bailing out. 7977 if (ESR != ESR_Failed) 7978 Info.FFDiag((*BI)->getBeginLoc(), 7979 diag::note_constexpr_stmt_expr_unsupported); 7980 return false; 7981 } 7982 } 7983 7984 llvm_unreachable("Return from function from the loop above."); 7985 } 7986 7987 /// Visit a value which is evaluated, but whose value is ignored. 7988 void VisitIgnoredValue(const Expr *E) { 7989 EvaluateIgnoredValue(Info, E); 7990 } 7991 7992 /// Potentially visit a MemberExpr's base expression. 7993 void VisitIgnoredBaseExpression(const Expr *E) { 7994 // While MSVC doesn't evaluate the base expression, it does diagnose the 7995 // presence of side-effecting behavior. 7996 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7997 return; 7998 VisitIgnoredValue(E); 7999 } 8000 }; 8001 8002 } // namespace 8003 8004 //===----------------------------------------------------------------------===// 8005 // Common base class for lvalue and temporary evaluation. 8006 //===----------------------------------------------------------------------===// 8007 namespace { 8008 template<class Derived> 8009 class LValueExprEvaluatorBase 8010 : public ExprEvaluatorBase<Derived> { 8011 protected: 8012 LValue &Result; 8013 bool InvalidBaseOK; 8014 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 8015 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 8016 8017 bool Success(APValue::LValueBase B) { 8018 Result.set(B); 8019 return true; 8020 } 8021 8022 bool evaluatePointer(const Expr *E, LValue &Result) { 8023 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 8024 } 8025 8026 public: 8027 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 8028 : ExprEvaluatorBaseTy(Info), Result(Result), 8029 InvalidBaseOK(InvalidBaseOK) {} 8030 8031 bool Success(const APValue &V, const Expr *E) { 8032 Result.setFrom(this->Info.Ctx, V); 8033 return true; 8034 } 8035 8036 bool VisitMemberExpr(const MemberExpr *E) { 8037 // Handle non-static data members. 8038 QualType BaseTy; 8039 bool EvalOK; 8040 if (E->isArrow()) { 8041 EvalOK = evaluatePointer(E->getBase(), Result); 8042 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 8043 } else if (E->getBase()->isPRValue()) { 8044 assert(E->getBase()->getType()->isRecordType()); 8045 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 8046 BaseTy = E->getBase()->getType(); 8047 } else { 8048 EvalOK = this->Visit(E->getBase()); 8049 BaseTy = E->getBase()->getType(); 8050 } 8051 if (!EvalOK) { 8052 if (!InvalidBaseOK) 8053 return false; 8054 Result.setInvalid(E); 8055 return true; 8056 } 8057 8058 const ValueDecl *MD = E->getMemberDecl(); 8059 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 8060 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 8061 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 8062 (void)BaseTy; 8063 if (!HandleLValueMember(this->Info, E, Result, FD)) 8064 return false; 8065 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 8066 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 8067 return false; 8068 } else 8069 return this->Error(E); 8070 8071 if (MD->getType()->isReferenceType()) { 8072 APValue RefValue; 8073 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 8074 RefValue)) 8075 return false; 8076 return Success(RefValue, E); 8077 } 8078 return true; 8079 } 8080 8081 bool VisitBinaryOperator(const BinaryOperator *E) { 8082 switch (E->getOpcode()) { 8083 default: 8084 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8085 8086 case BO_PtrMemD: 8087 case BO_PtrMemI: 8088 return HandleMemberPointerAccess(this->Info, E, Result); 8089 } 8090 } 8091 8092 bool VisitCastExpr(const CastExpr *E) { 8093 switch (E->getCastKind()) { 8094 default: 8095 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8096 8097 case CK_DerivedToBase: 8098 case CK_UncheckedDerivedToBase: 8099 if (!this->Visit(E->getSubExpr())) 8100 return false; 8101 8102 // Now figure out the necessary offset to add to the base LV to get from 8103 // the derived class to the base class. 8104 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8105 Result); 8106 } 8107 } 8108 }; 8109 } 8110 8111 //===----------------------------------------------------------------------===// 8112 // LValue Evaluation 8113 // 8114 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8115 // function designators (in C), decl references to void objects (in C), and 8116 // temporaries (if building with -Wno-address-of-temporary). 8117 // 8118 // LValue evaluation produces values comprising a base expression of one of the 8119 // following types: 8120 // - Declarations 8121 // * VarDecl 8122 // * FunctionDecl 8123 // - Literals 8124 // * CompoundLiteralExpr in C (and in global scope in C++) 8125 // * StringLiteral 8126 // * PredefinedExpr 8127 // * ObjCStringLiteralExpr 8128 // * ObjCEncodeExpr 8129 // * AddrLabelExpr 8130 // * BlockExpr 8131 // * CallExpr for a MakeStringConstant builtin 8132 // - typeid(T) expressions, as TypeInfoLValues 8133 // - Locals and temporaries 8134 // * MaterializeTemporaryExpr 8135 // * Any Expr, with a CallIndex indicating the function in which the temporary 8136 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8137 // from the AST (FIXME). 8138 // * A MaterializeTemporaryExpr that has static storage duration, with no 8139 // CallIndex, for a lifetime-extended temporary. 8140 // * The ConstantExpr that is currently being evaluated during evaluation of an 8141 // immediate invocation. 8142 // plus an offset in bytes. 8143 //===----------------------------------------------------------------------===// 8144 namespace { 8145 class LValueExprEvaluator 8146 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8147 public: 8148 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8149 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8150 8151 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8152 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8153 8154 bool VisitCallExpr(const CallExpr *E); 8155 bool VisitDeclRefExpr(const DeclRefExpr *E); 8156 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8157 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8158 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8159 bool VisitMemberExpr(const MemberExpr *E); 8160 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8161 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8162 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8163 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8164 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8165 bool VisitUnaryDeref(const UnaryOperator *E); 8166 bool VisitUnaryReal(const UnaryOperator *E); 8167 bool VisitUnaryImag(const UnaryOperator *E); 8168 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8169 return VisitUnaryPreIncDec(UO); 8170 } 8171 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8172 return VisitUnaryPreIncDec(UO); 8173 } 8174 bool VisitBinAssign(const BinaryOperator *BO); 8175 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8176 8177 bool VisitCastExpr(const CastExpr *E) { 8178 switch (E->getCastKind()) { 8179 default: 8180 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8181 8182 case CK_LValueBitCast: 8183 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8184 if (!Visit(E->getSubExpr())) 8185 return false; 8186 Result.Designator.setInvalid(); 8187 return true; 8188 8189 case CK_BaseToDerived: 8190 if (!Visit(E->getSubExpr())) 8191 return false; 8192 return HandleBaseToDerivedCast(Info, E, Result); 8193 8194 case CK_Dynamic: 8195 if (!Visit(E->getSubExpr())) 8196 return false; 8197 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8198 } 8199 } 8200 }; 8201 } // end anonymous namespace 8202 8203 /// Evaluate an expression as an lvalue. This can be legitimately called on 8204 /// expressions which are not glvalues, in three cases: 8205 /// * function designators in C, and 8206 /// * "extern void" objects 8207 /// * @selector() expressions in Objective-C 8208 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8209 bool InvalidBaseOK) { 8210 assert(!E->isValueDependent()); 8211 assert(E->isGLValue() || E->getType()->isFunctionType() || 8212 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8213 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8214 } 8215 8216 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8217 const NamedDecl *D = E->getDecl(); 8218 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl, 8219 UnnamedGlobalConstantDecl>(D)) 8220 return Success(cast<ValueDecl>(D)); 8221 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8222 return VisitVarDecl(E, VD); 8223 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8224 return Visit(BD->getBinding()); 8225 return Error(E); 8226 } 8227 8228 8229 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8230 8231 // If we are within a lambda's call operator, check whether the 'VD' referred 8232 // to within 'E' actually represents a lambda-capture that maps to a 8233 // data-member/field within the closure object, and if so, evaluate to the 8234 // field or what the field refers to. 8235 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8236 isa<DeclRefExpr>(E) && 8237 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8238 // We don't always have a complete capture-map when checking or inferring if 8239 // the function call operator meets the requirements of a constexpr function 8240 // - but we don't need to evaluate the captures to determine constexprness 8241 // (dcl.constexpr C++17). 8242 if (Info.checkingPotentialConstantExpression()) 8243 return false; 8244 8245 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8246 // Start with 'Result' referring to the complete closure object... 8247 Result = *Info.CurrentCall->This; 8248 // ... then update it to refer to the field of the closure object 8249 // that represents the capture. 8250 if (!HandleLValueMember(Info, E, Result, FD)) 8251 return false; 8252 // And if the field is of reference type, update 'Result' to refer to what 8253 // the field refers to. 8254 if (FD->getType()->isReferenceType()) { 8255 APValue RVal; 8256 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8257 RVal)) 8258 return false; 8259 Result.setFrom(Info.Ctx, RVal); 8260 } 8261 return true; 8262 } 8263 } 8264 8265 CallStackFrame *Frame = nullptr; 8266 unsigned Version = 0; 8267 if (VD->hasLocalStorage()) { 8268 // Only if a local variable was declared in the function currently being 8269 // evaluated, do we expect to be able to find its value in the current 8270 // frame. (Otherwise it was likely declared in an enclosing context and 8271 // could either have a valid evaluatable value (for e.g. a constexpr 8272 // variable) or be ill-formed (and trigger an appropriate evaluation 8273 // diagnostic)). 8274 CallStackFrame *CurrFrame = Info.CurrentCall; 8275 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8276 // Function parameters are stored in some caller's frame. (Usually the 8277 // immediate caller, but for an inherited constructor they may be more 8278 // distant.) 8279 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8280 if (CurrFrame->Arguments) { 8281 VD = CurrFrame->Arguments.getOrigParam(PVD); 8282 Frame = 8283 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8284 Version = CurrFrame->Arguments.Version; 8285 } 8286 } else { 8287 Frame = CurrFrame; 8288 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8289 } 8290 } 8291 } 8292 8293 if (!VD->getType()->isReferenceType()) { 8294 if (Frame) { 8295 Result.set({VD, Frame->Index, Version}); 8296 return true; 8297 } 8298 return Success(VD); 8299 } 8300 8301 if (!Info.getLangOpts().CPlusPlus11) { 8302 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8303 << VD << VD->getType(); 8304 Info.Note(VD->getLocation(), diag::note_declared_at); 8305 } 8306 8307 APValue *V; 8308 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8309 return false; 8310 if (!V->hasValue()) { 8311 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8312 // adjust the diagnostic to say that. 8313 if (!Info.checkingPotentialConstantExpression()) 8314 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8315 return false; 8316 } 8317 return Success(*V, E); 8318 } 8319 8320 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) { 8321 switch (E->getBuiltinCallee()) { 8322 case Builtin::BIas_const: 8323 case Builtin::BIforward: 8324 case Builtin::BImove: 8325 case Builtin::BImove_if_noexcept: 8326 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr()) 8327 return Visit(E->getArg(0)); 8328 break; 8329 } 8330 8331 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8332 } 8333 8334 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8335 const MaterializeTemporaryExpr *E) { 8336 // Walk through the expression to find the materialized temporary itself. 8337 SmallVector<const Expr *, 2> CommaLHSs; 8338 SmallVector<SubobjectAdjustment, 2> Adjustments; 8339 const Expr *Inner = 8340 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8341 8342 // If we passed any comma operators, evaluate their LHSs. 8343 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8344 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8345 return false; 8346 8347 // A materialized temporary with static storage duration can appear within the 8348 // result of a constant expression evaluation, so we need to preserve its 8349 // value for use outside this evaluation. 8350 APValue *Value; 8351 if (E->getStorageDuration() == SD_Static) { 8352 // FIXME: What about SD_Thread? 8353 Value = E->getOrCreateValue(true); 8354 *Value = APValue(); 8355 Result.set(E); 8356 } else { 8357 Value = &Info.CurrentCall->createTemporary( 8358 E, E->getType(), 8359 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8360 : ScopeKind::Block, 8361 Result); 8362 } 8363 8364 QualType Type = Inner->getType(); 8365 8366 // Materialize the temporary itself. 8367 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8368 *Value = APValue(); 8369 return false; 8370 } 8371 8372 // Adjust our lvalue to refer to the desired subobject. 8373 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8374 --I; 8375 switch (Adjustments[I].Kind) { 8376 case SubobjectAdjustment::DerivedToBaseAdjustment: 8377 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8378 Type, Result)) 8379 return false; 8380 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8381 break; 8382 8383 case SubobjectAdjustment::FieldAdjustment: 8384 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8385 return false; 8386 Type = Adjustments[I].Field->getType(); 8387 break; 8388 8389 case SubobjectAdjustment::MemberPointerAdjustment: 8390 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8391 Adjustments[I].Ptr.RHS)) 8392 return false; 8393 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8394 break; 8395 } 8396 } 8397 8398 return true; 8399 } 8400 8401 bool 8402 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8403 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8404 "lvalue compound literal in c++?"); 8405 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8406 // only see this when folding in C, so there's no standard to follow here. 8407 return Success(E); 8408 } 8409 8410 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8411 TypeInfoLValue TypeInfo; 8412 8413 if (!E->isPotentiallyEvaluated()) { 8414 if (E->isTypeOperand()) 8415 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8416 else 8417 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8418 } else { 8419 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8420 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8421 << E->getExprOperand()->getType() 8422 << E->getExprOperand()->getSourceRange(); 8423 } 8424 8425 if (!Visit(E->getExprOperand())) 8426 return false; 8427 8428 Optional<DynamicType> DynType = 8429 ComputeDynamicType(Info, E, Result, AK_TypeId); 8430 if (!DynType) 8431 return false; 8432 8433 TypeInfo = 8434 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8435 } 8436 8437 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8438 } 8439 8440 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8441 return Success(E->getGuidDecl()); 8442 } 8443 8444 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8445 // Handle static data members. 8446 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8447 VisitIgnoredBaseExpression(E->getBase()); 8448 return VisitVarDecl(E, VD); 8449 } 8450 8451 // Handle static member functions. 8452 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8453 if (MD->isStatic()) { 8454 VisitIgnoredBaseExpression(E->getBase()); 8455 return Success(MD); 8456 } 8457 } 8458 8459 // Handle non-static data members. 8460 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8461 } 8462 8463 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8464 // FIXME: Deal with vectors as array subscript bases. 8465 if (E->getBase()->getType()->isVectorType() || 8466 E->getBase()->getType()->isVLSTBuiltinType()) 8467 return Error(E); 8468 8469 APSInt Index; 8470 bool Success = true; 8471 8472 // C++17's rules require us to evaluate the LHS first, regardless of which 8473 // side is the base. 8474 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8475 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8476 : !EvaluateInteger(SubExpr, Index, Info)) { 8477 if (!Info.noteFailure()) 8478 return false; 8479 Success = false; 8480 } 8481 } 8482 8483 return Success && 8484 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8485 } 8486 8487 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8488 return evaluatePointer(E->getSubExpr(), Result); 8489 } 8490 8491 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8492 if (!Visit(E->getSubExpr())) 8493 return false; 8494 // __real is a no-op on scalar lvalues. 8495 if (E->getSubExpr()->getType()->isAnyComplexType()) 8496 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8497 return true; 8498 } 8499 8500 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8501 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8502 "lvalue __imag__ on scalar?"); 8503 if (!Visit(E->getSubExpr())) 8504 return false; 8505 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8506 return true; 8507 } 8508 8509 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8510 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8511 return Error(UO); 8512 8513 if (!this->Visit(UO->getSubExpr())) 8514 return false; 8515 8516 return handleIncDec( 8517 this->Info, UO, Result, UO->getSubExpr()->getType(), 8518 UO->isIncrementOp(), nullptr); 8519 } 8520 8521 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8522 const CompoundAssignOperator *CAO) { 8523 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8524 return Error(CAO); 8525 8526 bool Success = true; 8527 8528 // C++17 onwards require that we evaluate the RHS first. 8529 APValue RHS; 8530 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8531 if (!Info.noteFailure()) 8532 return false; 8533 Success = false; 8534 } 8535 8536 // The overall lvalue result is the result of evaluating the LHS. 8537 if (!this->Visit(CAO->getLHS()) || !Success) 8538 return false; 8539 8540 return handleCompoundAssignment( 8541 this->Info, CAO, 8542 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8543 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8544 } 8545 8546 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8547 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8548 return Error(E); 8549 8550 bool Success = true; 8551 8552 // C++17 onwards require that we evaluate the RHS first. 8553 APValue NewVal; 8554 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8555 if (!Info.noteFailure()) 8556 return false; 8557 Success = false; 8558 } 8559 8560 if (!this->Visit(E->getLHS()) || !Success) 8561 return false; 8562 8563 if (Info.getLangOpts().CPlusPlus20 && 8564 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8565 return false; 8566 8567 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8568 NewVal); 8569 } 8570 8571 //===----------------------------------------------------------------------===// 8572 // Pointer Evaluation 8573 //===----------------------------------------------------------------------===// 8574 8575 /// Attempts to compute the number of bytes available at the pointer 8576 /// returned by a function with the alloc_size attribute. Returns true if we 8577 /// were successful. Places an unsigned number into `Result`. 8578 /// 8579 /// This expects the given CallExpr to be a call to a function with an 8580 /// alloc_size attribute. 8581 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8582 const CallExpr *Call, 8583 llvm::APInt &Result) { 8584 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8585 8586 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8587 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8588 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8589 if (Call->getNumArgs() <= SizeArgNo) 8590 return false; 8591 8592 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8593 Expr::EvalResult ExprResult; 8594 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8595 return false; 8596 Into = ExprResult.Val.getInt(); 8597 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8598 return false; 8599 Into = Into.zext(BitsInSizeT); 8600 return true; 8601 }; 8602 8603 APSInt SizeOfElem; 8604 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8605 return false; 8606 8607 if (!AllocSize->getNumElemsParam().isValid()) { 8608 Result = std::move(SizeOfElem); 8609 return true; 8610 } 8611 8612 APSInt NumberOfElems; 8613 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8614 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8615 return false; 8616 8617 bool Overflow; 8618 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8619 if (Overflow) 8620 return false; 8621 8622 Result = std::move(BytesAvailable); 8623 return true; 8624 } 8625 8626 /// Convenience function. LVal's base must be a call to an alloc_size 8627 /// function. 8628 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8629 const LValue &LVal, 8630 llvm::APInt &Result) { 8631 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8632 "Can't get the size of a non alloc_size function"); 8633 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8634 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8635 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8636 } 8637 8638 /// Attempts to evaluate the given LValueBase as the result of a call to 8639 /// a function with the alloc_size attribute. If it was possible to do so, this 8640 /// function will return true, make Result's Base point to said function call, 8641 /// and mark Result's Base as invalid. 8642 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8643 LValue &Result) { 8644 if (Base.isNull()) 8645 return false; 8646 8647 // Because we do no form of static analysis, we only support const variables. 8648 // 8649 // Additionally, we can't support parameters, nor can we support static 8650 // variables (in the latter case, use-before-assign isn't UB; in the former, 8651 // we have no clue what they'll be assigned to). 8652 const auto *VD = 8653 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8654 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8655 return false; 8656 8657 const Expr *Init = VD->getAnyInitializer(); 8658 if (!Init || Init->getType().isNull()) 8659 return false; 8660 8661 const Expr *E = Init->IgnoreParens(); 8662 if (!tryUnwrapAllocSizeCall(E)) 8663 return false; 8664 8665 // Store E instead of E unwrapped so that the type of the LValue's base is 8666 // what the user wanted. 8667 Result.setInvalid(E); 8668 8669 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8670 Result.addUnsizedArray(Info, E, Pointee); 8671 return true; 8672 } 8673 8674 namespace { 8675 class PointerExprEvaluator 8676 : public ExprEvaluatorBase<PointerExprEvaluator> { 8677 LValue &Result; 8678 bool InvalidBaseOK; 8679 8680 bool Success(const Expr *E) { 8681 Result.set(E); 8682 return true; 8683 } 8684 8685 bool evaluateLValue(const Expr *E, LValue &Result) { 8686 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8687 } 8688 8689 bool evaluatePointer(const Expr *E, LValue &Result) { 8690 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8691 } 8692 8693 bool visitNonBuiltinCallExpr(const CallExpr *E); 8694 public: 8695 8696 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8697 : ExprEvaluatorBaseTy(info), Result(Result), 8698 InvalidBaseOK(InvalidBaseOK) {} 8699 8700 bool Success(const APValue &V, const Expr *E) { 8701 Result.setFrom(Info.Ctx, V); 8702 return true; 8703 } 8704 bool ZeroInitialization(const Expr *E) { 8705 Result.setNull(Info.Ctx, E->getType()); 8706 return true; 8707 } 8708 8709 bool VisitBinaryOperator(const BinaryOperator *E); 8710 bool VisitCastExpr(const CastExpr* E); 8711 bool VisitUnaryAddrOf(const UnaryOperator *E); 8712 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8713 { return Success(E); } 8714 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8715 if (E->isExpressibleAsConstantInitializer()) 8716 return Success(E); 8717 if (Info.noteFailure()) 8718 EvaluateIgnoredValue(Info, E->getSubExpr()); 8719 return Error(E); 8720 } 8721 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8722 { return Success(E); } 8723 bool VisitCallExpr(const CallExpr *E); 8724 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8725 bool VisitBlockExpr(const BlockExpr *E) { 8726 if (!E->getBlockDecl()->hasCaptures()) 8727 return Success(E); 8728 return Error(E); 8729 } 8730 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8731 // Can't look at 'this' when checking a potential constant expression. 8732 if (Info.checkingPotentialConstantExpression()) 8733 return false; 8734 if (!Info.CurrentCall->This) { 8735 if (Info.getLangOpts().CPlusPlus11) 8736 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8737 else 8738 Info.FFDiag(E); 8739 return false; 8740 } 8741 Result = *Info.CurrentCall->This; 8742 // If we are inside a lambda's call operator, the 'this' expression refers 8743 // to the enclosing '*this' object (either by value or reference) which is 8744 // either copied into the closure object's field that represents the '*this' 8745 // or refers to '*this'. 8746 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8747 // Ensure we actually have captured 'this'. (an error will have 8748 // been previously reported if not). 8749 if (!Info.CurrentCall->LambdaThisCaptureField) 8750 return false; 8751 8752 // Update 'Result' to refer to the data member/field of the closure object 8753 // that represents the '*this' capture. 8754 if (!HandleLValueMember(Info, E, Result, 8755 Info.CurrentCall->LambdaThisCaptureField)) 8756 return false; 8757 // If we captured '*this' by reference, replace the field with its referent. 8758 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8759 ->isPointerType()) { 8760 APValue RVal; 8761 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8762 RVal)) 8763 return false; 8764 8765 Result.setFrom(Info.Ctx, RVal); 8766 } 8767 } 8768 return true; 8769 } 8770 8771 bool VisitCXXNewExpr(const CXXNewExpr *E); 8772 8773 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8774 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?"); 8775 APValue LValResult = E->EvaluateInContext( 8776 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8777 Result.setFrom(Info.Ctx, LValResult); 8778 return true; 8779 } 8780 8781 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8782 std::string ResultStr = E->ComputeName(Info.Ctx); 8783 8784 QualType CharTy = Info.Ctx.CharTy.withConst(); 8785 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8786 ResultStr.size() + 1); 8787 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8788 ArrayType::Normal, 0); 8789 8790 StringLiteral *SL = 8791 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, 8792 /*Pascal*/ false, ArrayTy, E->getLocation()); 8793 8794 evaluateLValue(SL, Result); 8795 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8796 return true; 8797 } 8798 8799 // FIXME: Missing: @protocol, @selector 8800 }; 8801 } // end anonymous namespace 8802 8803 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8804 bool InvalidBaseOK) { 8805 assert(!E->isValueDependent()); 8806 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8807 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8808 } 8809 8810 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8811 if (E->getOpcode() != BO_Add && 8812 E->getOpcode() != BO_Sub) 8813 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8814 8815 const Expr *PExp = E->getLHS(); 8816 const Expr *IExp = E->getRHS(); 8817 if (IExp->getType()->isPointerType()) 8818 std::swap(PExp, IExp); 8819 8820 bool EvalPtrOK = evaluatePointer(PExp, Result); 8821 if (!EvalPtrOK && !Info.noteFailure()) 8822 return false; 8823 8824 llvm::APSInt Offset; 8825 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8826 return false; 8827 8828 if (E->getOpcode() == BO_Sub) 8829 negateAsSigned(Offset); 8830 8831 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8832 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8833 } 8834 8835 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8836 return evaluateLValue(E->getSubExpr(), Result); 8837 } 8838 8839 // Is the provided decl 'std::source_location::current'? 8840 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) { 8841 if (!FD) 8842 return false; 8843 const IdentifierInfo *FnII = FD->getIdentifier(); 8844 if (!FnII || !FnII->isStr("current")) 8845 return false; 8846 8847 const auto *RD = dyn_cast<RecordDecl>(FD->getParent()); 8848 if (!RD) 8849 return false; 8850 8851 const IdentifierInfo *ClassII = RD->getIdentifier(); 8852 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location"); 8853 } 8854 8855 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8856 const Expr *SubExpr = E->getSubExpr(); 8857 8858 switch (E->getCastKind()) { 8859 default: 8860 break; 8861 case CK_BitCast: 8862 case CK_CPointerToObjCPointerCast: 8863 case CK_BlockPointerToObjCPointerCast: 8864 case CK_AnyPointerToBlockPointerCast: 8865 case CK_AddressSpaceConversion: 8866 if (!Visit(SubExpr)) 8867 return false; 8868 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8869 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8870 // also static_casts, but we disallow them as a resolution to DR1312. 8871 if (!E->getType()->isVoidPointerType()) { 8872 // In some circumstances, we permit casting from void* to cv1 T*, when the 8873 // actual pointee object is actually a cv2 T. 8874 bool VoidPtrCastMaybeOK = 8875 !Result.InvalidBase && !Result.Designator.Invalid && 8876 !Result.IsNullPtr && 8877 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8878 E->getType()->getPointeeType()); 8879 // 1. We'll allow it in std::allocator::allocate, and anything which that 8880 // calls. 8881 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s 8882 // <source_location> header. Fixed in GCC 12 and later (2022-04-??). 8883 // We'll allow it in the body of std::source_location::current. GCC's 8884 // implementation had a parameter of type `void*`, and casts from 8885 // that back to `const __impl*` in its body. 8886 if (VoidPtrCastMaybeOK && 8887 (Info.getStdAllocatorCaller("allocate") || 8888 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) { 8889 // Permitted. 8890 } else { 8891 Result.Designator.setInvalid(); 8892 if (SubExpr->getType()->isVoidPointerType()) 8893 CCEDiag(E, diag::note_constexpr_invalid_cast) 8894 << 3 << SubExpr->getType(); 8895 else 8896 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8897 } 8898 } 8899 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8900 ZeroInitialization(E); 8901 return true; 8902 8903 case CK_DerivedToBase: 8904 case CK_UncheckedDerivedToBase: 8905 if (!evaluatePointer(E->getSubExpr(), Result)) 8906 return false; 8907 if (!Result.Base && Result.Offset.isZero()) 8908 return true; 8909 8910 // Now figure out the necessary offset to add to the base LV to get from 8911 // the derived class to the base class. 8912 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8913 castAs<PointerType>()->getPointeeType(), 8914 Result); 8915 8916 case CK_BaseToDerived: 8917 if (!Visit(E->getSubExpr())) 8918 return false; 8919 if (!Result.Base && Result.Offset.isZero()) 8920 return true; 8921 return HandleBaseToDerivedCast(Info, E, Result); 8922 8923 case CK_Dynamic: 8924 if (!Visit(E->getSubExpr())) 8925 return false; 8926 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8927 8928 case CK_NullToPointer: 8929 VisitIgnoredValue(E->getSubExpr()); 8930 return ZeroInitialization(E); 8931 8932 case CK_IntegralToPointer: { 8933 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8934 8935 APValue Value; 8936 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8937 break; 8938 8939 if (Value.isInt()) { 8940 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8941 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8942 Result.Base = (Expr*)nullptr; 8943 Result.InvalidBase = false; 8944 Result.Offset = CharUnits::fromQuantity(N); 8945 Result.Designator.setInvalid(); 8946 Result.IsNullPtr = false; 8947 return true; 8948 } else { 8949 // Cast is of an lvalue, no need to change value. 8950 Result.setFrom(Info.Ctx, Value); 8951 return true; 8952 } 8953 } 8954 8955 case CK_ArrayToPointerDecay: { 8956 if (SubExpr->isGLValue()) { 8957 if (!evaluateLValue(SubExpr, Result)) 8958 return false; 8959 } else { 8960 APValue &Value = Info.CurrentCall->createTemporary( 8961 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8962 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8963 return false; 8964 } 8965 // The result is a pointer to the first element of the array. 8966 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8967 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8968 Result.addArray(Info, E, CAT); 8969 else 8970 Result.addUnsizedArray(Info, E, AT->getElementType()); 8971 return true; 8972 } 8973 8974 case CK_FunctionToPointerDecay: 8975 return evaluateLValue(SubExpr, Result); 8976 8977 case CK_LValueToRValue: { 8978 LValue LVal; 8979 if (!evaluateLValue(E->getSubExpr(), LVal)) 8980 return false; 8981 8982 APValue RVal; 8983 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8984 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8985 LVal, RVal)) 8986 return InvalidBaseOK && 8987 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8988 return Success(RVal, E); 8989 } 8990 } 8991 8992 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8993 } 8994 8995 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8996 UnaryExprOrTypeTrait ExprKind) { 8997 // C++ [expr.alignof]p3: 8998 // When alignof is applied to a reference type, the result is the 8999 // alignment of the referenced type. 9000 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 9001 T = Ref->getPointeeType(); 9002 9003 if (T.getQualifiers().hasUnaligned()) 9004 return CharUnits::One(); 9005 9006 const bool AlignOfReturnsPreferred = 9007 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 9008 9009 // __alignof is defined to return the preferred alignment. 9010 // Before 8, clang returned the preferred alignment for alignof and _Alignof 9011 // as well. 9012 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 9013 return Info.Ctx.toCharUnitsFromBits( 9014 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 9015 // alignof and _Alignof are defined to return the ABI alignment. 9016 else if (ExprKind == UETT_AlignOf) 9017 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 9018 else 9019 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 9020 } 9021 9022 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 9023 UnaryExprOrTypeTrait ExprKind) { 9024 E = E->IgnoreParens(); 9025 9026 // The kinds of expressions that we have special-case logic here for 9027 // should be kept up to date with the special checks for those 9028 // expressions in Sema. 9029 9030 // alignof decl is always accepted, even if it doesn't make sense: we default 9031 // to 1 in those cases. 9032 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9033 return Info.Ctx.getDeclAlign(DRE->getDecl(), 9034 /*RefAsPointee*/true); 9035 9036 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 9037 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 9038 /*RefAsPointee*/true); 9039 9040 return GetAlignOfType(Info, E->getType(), ExprKind); 9041 } 9042 9043 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 9044 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 9045 return Info.Ctx.getDeclAlign(VD); 9046 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 9047 return GetAlignOfExpr(Info, E, UETT_AlignOf); 9048 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 9049 } 9050 9051 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 9052 /// __builtin_is_aligned and __builtin_assume_aligned. 9053 static bool getAlignmentArgument(const Expr *E, QualType ForType, 9054 EvalInfo &Info, APSInt &Alignment) { 9055 if (!EvaluateInteger(E, Alignment, Info)) 9056 return false; 9057 if (Alignment < 0 || !Alignment.isPowerOf2()) { 9058 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 9059 return false; 9060 } 9061 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 9062 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 9063 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 9064 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 9065 << MaxValue << ForType << Alignment; 9066 return false; 9067 } 9068 // Ensure both alignment and source value have the same bit width so that we 9069 // don't assert when computing the resulting value. 9070 APSInt ExtAlignment = 9071 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 9072 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 9073 "Alignment should not be changed by ext/trunc"); 9074 Alignment = ExtAlignment; 9075 assert(Alignment.getBitWidth() == SrcWidth); 9076 return true; 9077 } 9078 9079 // To be clear: this happily visits unsupported builtins. Better name welcomed. 9080 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 9081 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 9082 return true; 9083 9084 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 9085 return false; 9086 9087 Result.setInvalid(E); 9088 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 9089 Result.addUnsizedArray(Info, E, PointeeTy); 9090 return true; 9091 } 9092 9093 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 9094 if (IsConstantCall(E)) 9095 return Success(E); 9096 9097 if (unsigned BuiltinOp = E->getBuiltinCallee()) 9098 return VisitBuiltinCallExpr(E, BuiltinOp); 9099 9100 return visitNonBuiltinCallExpr(E); 9101 } 9102 9103 // Determine if T is a character type for which we guarantee that 9104 // sizeof(T) == 1. 9105 static bool isOneByteCharacterType(QualType T) { 9106 return T->isCharType() || T->isChar8Type(); 9107 } 9108 9109 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9110 unsigned BuiltinOp) { 9111 switch (BuiltinOp) { 9112 case Builtin::BIaddressof: 9113 case Builtin::BI__addressof: 9114 case Builtin::BI__builtin_addressof: 9115 return evaluateLValue(E->getArg(0), Result); 9116 case Builtin::BI__builtin_assume_aligned: { 9117 // We need to be very careful here because: if the pointer does not have the 9118 // asserted alignment, then the behavior is undefined, and undefined 9119 // behavior is non-constant. 9120 if (!evaluatePointer(E->getArg(0), Result)) 9121 return false; 9122 9123 LValue OffsetResult(Result); 9124 APSInt Alignment; 9125 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9126 Alignment)) 9127 return false; 9128 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 9129 9130 if (E->getNumArgs() > 2) { 9131 APSInt Offset; 9132 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9133 return false; 9134 9135 int64_t AdditionalOffset = -Offset.getZExtValue(); 9136 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9137 } 9138 9139 // If there is a base object, then it must have the correct alignment. 9140 if (OffsetResult.Base) { 9141 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9142 9143 if (BaseAlignment < Align) { 9144 Result.Designator.setInvalid(); 9145 // FIXME: Add support to Diagnostic for long / long long. 9146 CCEDiag(E->getArg(0), 9147 diag::note_constexpr_baa_insufficient_alignment) << 0 9148 << (unsigned)BaseAlignment.getQuantity() 9149 << (unsigned)Align.getQuantity(); 9150 return false; 9151 } 9152 } 9153 9154 // The offset must also have the correct alignment. 9155 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9156 Result.Designator.setInvalid(); 9157 9158 (OffsetResult.Base 9159 ? CCEDiag(E->getArg(0), 9160 diag::note_constexpr_baa_insufficient_alignment) << 1 9161 : CCEDiag(E->getArg(0), 9162 diag::note_constexpr_baa_value_insufficient_alignment)) 9163 << (int)OffsetResult.Offset.getQuantity() 9164 << (unsigned)Align.getQuantity(); 9165 return false; 9166 } 9167 9168 return true; 9169 } 9170 case Builtin::BI__builtin_align_up: 9171 case Builtin::BI__builtin_align_down: { 9172 if (!evaluatePointer(E->getArg(0), Result)) 9173 return false; 9174 APSInt Alignment; 9175 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9176 Alignment)) 9177 return false; 9178 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9179 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9180 // For align_up/align_down, we can return the same value if the alignment 9181 // is known to be greater or equal to the requested value. 9182 if (PtrAlign.getQuantity() >= Alignment) 9183 return true; 9184 9185 // The alignment could be greater than the minimum at run-time, so we cannot 9186 // infer much about the resulting pointer value. One case is possible: 9187 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9188 // can infer the correct index if the requested alignment is smaller than 9189 // the base alignment so we can perform the computation on the offset. 9190 if (BaseAlignment.getQuantity() >= Alignment) { 9191 assert(Alignment.getBitWidth() <= 64 && 9192 "Cannot handle > 64-bit address-space"); 9193 uint64_t Alignment64 = Alignment.getZExtValue(); 9194 CharUnits NewOffset = CharUnits::fromQuantity( 9195 BuiltinOp == Builtin::BI__builtin_align_down 9196 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9197 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9198 Result.adjustOffset(NewOffset - Result.Offset); 9199 // TODO: diagnose out-of-bounds values/only allow for arrays? 9200 return true; 9201 } 9202 // Otherwise, we cannot constant-evaluate the result. 9203 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9204 << Alignment; 9205 return false; 9206 } 9207 case Builtin::BI__builtin_operator_new: 9208 return HandleOperatorNewCall(Info, E, Result); 9209 case Builtin::BI__builtin_launder: 9210 return evaluatePointer(E->getArg(0), Result); 9211 case Builtin::BIstrchr: 9212 case Builtin::BIwcschr: 9213 case Builtin::BImemchr: 9214 case Builtin::BIwmemchr: 9215 if (Info.getLangOpts().CPlusPlus11) 9216 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9217 << /*isConstexpr*/0 << /*isConstructor*/0 9218 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9219 else 9220 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9221 LLVM_FALLTHROUGH; 9222 case Builtin::BI__builtin_strchr: 9223 case Builtin::BI__builtin_wcschr: 9224 case Builtin::BI__builtin_memchr: 9225 case Builtin::BI__builtin_char_memchr: 9226 case Builtin::BI__builtin_wmemchr: { 9227 if (!Visit(E->getArg(0))) 9228 return false; 9229 APSInt Desired; 9230 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9231 return false; 9232 uint64_t MaxLength = uint64_t(-1); 9233 if (BuiltinOp != Builtin::BIstrchr && 9234 BuiltinOp != Builtin::BIwcschr && 9235 BuiltinOp != Builtin::BI__builtin_strchr && 9236 BuiltinOp != Builtin::BI__builtin_wcschr) { 9237 APSInt N; 9238 if (!EvaluateInteger(E->getArg(2), N, Info)) 9239 return false; 9240 MaxLength = N.getExtValue(); 9241 } 9242 // We cannot find the value if there are no candidates to match against. 9243 if (MaxLength == 0u) 9244 return ZeroInitialization(E); 9245 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9246 Result.Designator.Invalid) 9247 return false; 9248 QualType CharTy = Result.Designator.getType(Info.Ctx); 9249 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9250 BuiltinOp == Builtin::BI__builtin_memchr; 9251 assert(IsRawByte || 9252 Info.Ctx.hasSameUnqualifiedType( 9253 CharTy, E->getArg(0)->getType()->getPointeeType())); 9254 // Pointers to const void may point to objects of incomplete type. 9255 if (IsRawByte && CharTy->isIncompleteType()) { 9256 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9257 return false; 9258 } 9259 // Give up on byte-oriented matching against multibyte elements. 9260 // FIXME: We can compare the bytes in the correct order. 9261 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9262 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9263 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9264 << CharTy; 9265 return false; 9266 } 9267 // Figure out what value we're actually looking for (after converting to 9268 // the corresponding unsigned type if necessary). 9269 uint64_t DesiredVal; 9270 bool StopAtNull = false; 9271 switch (BuiltinOp) { 9272 case Builtin::BIstrchr: 9273 case Builtin::BI__builtin_strchr: 9274 // strchr compares directly to the passed integer, and therefore 9275 // always fails if given an int that is not a char. 9276 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9277 E->getArg(1)->getType(), 9278 Desired), 9279 Desired)) 9280 return ZeroInitialization(E); 9281 StopAtNull = true; 9282 LLVM_FALLTHROUGH; 9283 case Builtin::BImemchr: 9284 case Builtin::BI__builtin_memchr: 9285 case Builtin::BI__builtin_char_memchr: 9286 // memchr compares by converting both sides to unsigned char. That's also 9287 // correct for strchr if we get this far (to cope with plain char being 9288 // unsigned in the strchr case). 9289 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9290 break; 9291 9292 case Builtin::BIwcschr: 9293 case Builtin::BI__builtin_wcschr: 9294 StopAtNull = true; 9295 LLVM_FALLTHROUGH; 9296 case Builtin::BIwmemchr: 9297 case Builtin::BI__builtin_wmemchr: 9298 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9299 DesiredVal = Desired.getZExtValue(); 9300 break; 9301 } 9302 9303 for (; MaxLength; --MaxLength) { 9304 APValue Char; 9305 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9306 !Char.isInt()) 9307 return false; 9308 if (Char.getInt().getZExtValue() == DesiredVal) 9309 return true; 9310 if (StopAtNull && !Char.getInt()) 9311 break; 9312 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9313 return false; 9314 } 9315 // Not found: return nullptr. 9316 return ZeroInitialization(E); 9317 } 9318 9319 case Builtin::BImemcpy: 9320 case Builtin::BImemmove: 9321 case Builtin::BIwmemcpy: 9322 case Builtin::BIwmemmove: 9323 if (Info.getLangOpts().CPlusPlus11) 9324 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9325 << /*isConstexpr*/0 << /*isConstructor*/0 9326 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9327 else 9328 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9329 LLVM_FALLTHROUGH; 9330 case Builtin::BI__builtin_memcpy: 9331 case Builtin::BI__builtin_memmove: 9332 case Builtin::BI__builtin_wmemcpy: 9333 case Builtin::BI__builtin_wmemmove: { 9334 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9335 BuiltinOp == Builtin::BIwmemmove || 9336 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9337 BuiltinOp == Builtin::BI__builtin_wmemmove; 9338 bool Move = BuiltinOp == Builtin::BImemmove || 9339 BuiltinOp == Builtin::BIwmemmove || 9340 BuiltinOp == Builtin::BI__builtin_memmove || 9341 BuiltinOp == Builtin::BI__builtin_wmemmove; 9342 9343 // The result of mem* is the first argument. 9344 if (!Visit(E->getArg(0))) 9345 return false; 9346 LValue Dest = Result; 9347 9348 LValue Src; 9349 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9350 return false; 9351 9352 APSInt N; 9353 if (!EvaluateInteger(E->getArg(2), N, Info)) 9354 return false; 9355 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9356 9357 // If the size is zero, we treat this as always being a valid no-op. 9358 // (Even if one of the src and dest pointers is null.) 9359 if (!N) 9360 return true; 9361 9362 // Otherwise, if either of the operands is null, we can't proceed. Don't 9363 // try to determine the type of the copied objects, because there aren't 9364 // any. 9365 if (!Src.Base || !Dest.Base) { 9366 APValue Val; 9367 (!Src.Base ? Src : Dest).moveInto(Val); 9368 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9369 << Move << WChar << !!Src.Base 9370 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9371 return false; 9372 } 9373 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9374 return false; 9375 9376 // We require that Src and Dest are both pointers to arrays of 9377 // trivially-copyable type. (For the wide version, the designator will be 9378 // invalid if the designated object is not a wchar_t.) 9379 QualType T = Dest.Designator.getType(Info.Ctx); 9380 QualType SrcT = Src.Designator.getType(Info.Ctx); 9381 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9382 // FIXME: Consider using our bit_cast implementation to support this. 9383 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9384 return false; 9385 } 9386 if (T->isIncompleteType()) { 9387 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9388 return false; 9389 } 9390 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9391 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9392 return false; 9393 } 9394 9395 // Figure out how many T's we're copying. 9396 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9397 if (!WChar) { 9398 uint64_t Remainder; 9399 llvm::APInt OrigN = N; 9400 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9401 if (Remainder) { 9402 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9403 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9404 << (unsigned)TSize; 9405 return false; 9406 } 9407 } 9408 9409 // Check that the copying will remain within the arrays, just so that we 9410 // can give a more meaningful diagnostic. This implicitly also checks that 9411 // N fits into 64 bits. 9412 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9413 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9414 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9415 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9416 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9417 << toString(N, 10, /*Signed*/false); 9418 return false; 9419 } 9420 uint64_t NElems = N.getZExtValue(); 9421 uint64_t NBytes = NElems * TSize; 9422 9423 // Check for overlap. 9424 int Direction = 1; 9425 if (HasSameBase(Src, Dest)) { 9426 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9427 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9428 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9429 // Dest is inside the source region. 9430 if (!Move) { 9431 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9432 return false; 9433 } 9434 // For memmove and friends, copy backwards. 9435 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9436 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9437 return false; 9438 Direction = -1; 9439 } else if (!Move && SrcOffset >= DestOffset && 9440 SrcOffset - DestOffset < NBytes) { 9441 // Src is inside the destination region for memcpy: invalid. 9442 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9443 return false; 9444 } 9445 } 9446 9447 while (true) { 9448 APValue Val; 9449 // FIXME: Set WantObjectRepresentation to true if we're copying a 9450 // char-like type? 9451 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9452 !handleAssignment(Info, E, Dest, T, Val)) 9453 return false; 9454 // Do not iterate past the last element; if we're copying backwards, that 9455 // might take us off the start of the array. 9456 if (--NElems == 0) 9457 return true; 9458 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9459 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9460 return false; 9461 } 9462 } 9463 9464 default: 9465 break; 9466 } 9467 9468 return visitNonBuiltinCallExpr(E); 9469 } 9470 9471 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9472 APValue &Result, const InitListExpr *ILE, 9473 QualType AllocType); 9474 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9475 APValue &Result, 9476 const CXXConstructExpr *CCE, 9477 QualType AllocType); 9478 9479 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9480 if (!Info.getLangOpts().CPlusPlus20) 9481 Info.CCEDiag(E, diag::note_constexpr_new); 9482 9483 // We cannot speculatively evaluate a delete expression. 9484 if (Info.SpeculativeEvaluationDepth) 9485 return false; 9486 9487 FunctionDecl *OperatorNew = E->getOperatorNew(); 9488 9489 bool IsNothrow = false; 9490 bool IsPlacement = false; 9491 if (OperatorNew->isReservedGlobalPlacementOperator() && 9492 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9493 // FIXME Support array placement new. 9494 assert(E->getNumPlacementArgs() == 1); 9495 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9496 return false; 9497 if (Result.Designator.Invalid) 9498 return false; 9499 IsPlacement = true; 9500 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9501 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9502 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9503 return false; 9504 } else if (E->getNumPlacementArgs()) { 9505 // The only new-placement list we support is of the form (std::nothrow). 9506 // 9507 // FIXME: There is no restriction on this, but it's not clear that any 9508 // other form makes any sense. We get here for cases such as: 9509 // 9510 // new (std::align_val_t{N}) X(int) 9511 // 9512 // (which should presumably be valid only if N is a multiple of 9513 // alignof(int), and in any case can't be deallocated unless N is 9514 // alignof(X) and X has new-extended alignment). 9515 if (E->getNumPlacementArgs() != 1 || 9516 !E->getPlacementArg(0)->getType()->isNothrowT()) 9517 return Error(E, diag::note_constexpr_new_placement); 9518 9519 LValue Nothrow; 9520 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9521 return false; 9522 IsNothrow = true; 9523 } 9524 9525 const Expr *Init = E->getInitializer(); 9526 const InitListExpr *ResizedArrayILE = nullptr; 9527 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9528 bool ValueInit = false; 9529 9530 QualType AllocType = E->getAllocatedType(); 9531 if (Optional<const Expr *> ArraySize = E->getArraySize()) { 9532 const Expr *Stripped = *ArraySize; 9533 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9534 Stripped = ICE->getSubExpr()) 9535 if (ICE->getCastKind() != CK_NoOp && 9536 ICE->getCastKind() != CK_IntegralCast) 9537 break; 9538 9539 llvm::APSInt ArrayBound; 9540 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9541 return false; 9542 9543 // C++ [expr.new]p9: 9544 // The expression is erroneous if: 9545 // -- [...] its value before converting to size_t [or] applying the 9546 // second standard conversion sequence is less than zero 9547 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9548 if (IsNothrow) 9549 return ZeroInitialization(E); 9550 9551 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9552 << ArrayBound << (*ArraySize)->getSourceRange(); 9553 return false; 9554 } 9555 9556 // -- its value is such that the size of the allocated object would 9557 // exceed the implementation-defined limit 9558 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9559 ArrayBound) > 9560 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9561 if (IsNothrow) 9562 return ZeroInitialization(E); 9563 9564 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9565 << ArrayBound << (*ArraySize)->getSourceRange(); 9566 return false; 9567 } 9568 9569 // -- the new-initializer is a braced-init-list and the number of 9570 // array elements for which initializers are provided [...] 9571 // exceeds the number of elements to initialize 9572 if (!Init) { 9573 // No initialization is performed. 9574 } else if (isa<CXXScalarValueInitExpr>(Init) || 9575 isa<ImplicitValueInitExpr>(Init)) { 9576 ValueInit = true; 9577 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9578 ResizedArrayCCE = CCE; 9579 } else { 9580 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9581 assert(CAT && "unexpected type for array initializer"); 9582 9583 unsigned Bits = 9584 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9585 llvm::APInt InitBound = CAT->getSize().zext(Bits); 9586 llvm::APInt AllocBound = ArrayBound.zext(Bits); 9587 if (InitBound.ugt(AllocBound)) { 9588 if (IsNothrow) 9589 return ZeroInitialization(E); 9590 9591 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9592 << toString(AllocBound, 10, /*Signed=*/false) 9593 << toString(InitBound, 10, /*Signed=*/false) 9594 << (*ArraySize)->getSourceRange(); 9595 return false; 9596 } 9597 9598 // If the sizes differ, we must have an initializer list, and we need 9599 // special handling for this case when we initialize. 9600 if (InitBound != AllocBound) 9601 ResizedArrayILE = cast<InitListExpr>(Init); 9602 } 9603 9604 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9605 ArrayType::Normal, 0); 9606 } else { 9607 assert(!AllocType->isArrayType() && 9608 "array allocation with non-array new"); 9609 } 9610 9611 APValue *Val; 9612 if (IsPlacement) { 9613 AccessKinds AK = AK_Construct; 9614 struct FindObjectHandler { 9615 EvalInfo &Info; 9616 const Expr *E; 9617 QualType AllocType; 9618 const AccessKinds AccessKind; 9619 APValue *Value; 9620 9621 typedef bool result_type; 9622 bool failed() { return false; } 9623 bool found(APValue &Subobj, QualType SubobjType) { 9624 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9625 // old name of the object to be used to name the new object. 9626 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9627 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9628 SubobjType << AllocType; 9629 return false; 9630 } 9631 Value = &Subobj; 9632 return true; 9633 } 9634 bool found(APSInt &Value, QualType SubobjType) { 9635 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9636 return false; 9637 } 9638 bool found(APFloat &Value, QualType SubobjType) { 9639 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9640 return false; 9641 } 9642 } Handler = {Info, E, AllocType, AK, nullptr}; 9643 9644 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9645 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9646 return false; 9647 9648 Val = Handler.Value; 9649 9650 // [basic.life]p1: 9651 // The lifetime of an object o of type T ends when [...] the storage 9652 // which the object occupies is [...] reused by an object that is not 9653 // nested within o (6.6.2). 9654 *Val = APValue(); 9655 } else { 9656 // Perform the allocation and obtain a pointer to the resulting object. 9657 Val = Info.createHeapAlloc(E, AllocType, Result); 9658 if (!Val) 9659 return false; 9660 } 9661 9662 if (ValueInit) { 9663 ImplicitValueInitExpr VIE(AllocType); 9664 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9665 return false; 9666 } else if (ResizedArrayILE) { 9667 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9668 AllocType)) 9669 return false; 9670 } else if (ResizedArrayCCE) { 9671 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9672 AllocType)) 9673 return false; 9674 } else if (Init) { 9675 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9676 return false; 9677 } else if (!getDefaultInitValue(AllocType, *Val)) { 9678 return false; 9679 } 9680 9681 // Array new returns a pointer to the first element, not a pointer to the 9682 // array. 9683 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9684 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9685 9686 return true; 9687 } 9688 //===----------------------------------------------------------------------===// 9689 // Member Pointer Evaluation 9690 //===----------------------------------------------------------------------===// 9691 9692 namespace { 9693 class MemberPointerExprEvaluator 9694 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9695 MemberPtr &Result; 9696 9697 bool Success(const ValueDecl *D) { 9698 Result = MemberPtr(D); 9699 return true; 9700 } 9701 public: 9702 9703 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9704 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9705 9706 bool Success(const APValue &V, const Expr *E) { 9707 Result.setFrom(V); 9708 return true; 9709 } 9710 bool ZeroInitialization(const Expr *E) { 9711 return Success((const ValueDecl*)nullptr); 9712 } 9713 9714 bool VisitCastExpr(const CastExpr *E); 9715 bool VisitUnaryAddrOf(const UnaryOperator *E); 9716 }; 9717 } // end anonymous namespace 9718 9719 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9720 EvalInfo &Info) { 9721 assert(!E->isValueDependent()); 9722 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9723 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9724 } 9725 9726 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9727 switch (E->getCastKind()) { 9728 default: 9729 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9730 9731 case CK_NullToMemberPointer: 9732 VisitIgnoredValue(E->getSubExpr()); 9733 return ZeroInitialization(E); 9734 9735 case CK_BaseToDerivedMemberPointer: { 9736 if (!Visit(E->getSubExpr())) 9737 return false; 9738 if (E->path_empty()) 9739 return true; 9740 // Base-to-derived member pointer casts store the path in derived-to-base 9741 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9742 // the wrong end of the derived->base arc, so stagger the path by one class. 9743 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9744 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9745 PathI != PathE; ++PathI) { 9746 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9747 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9748 if (!Result.castToDerived(Derived)) 9749 return Error(E); 9750 } 9751 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9752 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9753 return Error(E); 9754 return true; 9755 } 9756 9757 case CK_DerivedToBaseMemberPointer: 9758 if (!Visit(E->getSubExpr())) 9759 return false; 9760 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9761 PathE = E->path_end(); PathI != PathE; ++PathI) { 9762 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9763 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9764 if (!Result.castToBase(Base)) 9765 return Error(E); 9766 } 9767 return true; 9768 } 9769 } 9770 9771 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9772 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9773 // member can be formed. 9774 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9775 } 9776 9777 //===----------------------------------------------------------------------===// 9778 // Record Evaluation 9779 //===----------------------------------------------------------------------===// 9780 9781 namespace { 9782 class RecordExprEvaluator 9783 : public ExprEvaluatorBase<RecordExprEvaluator> { 9784 const LValue &This; 9785 APValue &Result; 9786 public: 9787 9788 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9789 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9790 9791 bool Success(const APValue &V, const Expr *E) { 9792 Result = V; 9793 return true; 9794 } 9795 bool ZeroInitialization(const Expr *E) { 9796 return ZeroInitialization(E, E->getType()); 9797 } 9798 bool ZeroInitialization(const Expr *E, QualType T); 9799 9800 bool VisitCallExpr(const CallExpr *E) { 9801 return handleCallExpr(E, Result, &This); 9802 } 9803 bool VisitCastExpr(const CastExpr *E); 9804 bool VisitInitListExpr(const InitListExpr *E); 9805 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9806 return VisitCXXConstructExpr(E, E->getType()); 9807 } 9808 bool VisitLambdaExpr(const LambdaExpr *E); 9809 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9810 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9811 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9812 bool VisitBinCmp(const BinaryOperator *E); 9813 }; 9814 } 9815 9816 /// Perform zero-initialization on an object of non-union class type. 9817 /// C++11 [dcl.init]p5: 9818 /// To zero-initialize an object or reference of type T means: 9819 /// [...] 9820 /// -- if T is a (possibly cv-qualified) non-union class type, 9821 /// each non-static data member and each base-class subobject is 9822 /// zero-initialized 9823 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9824 const RecordDecl *RD, 9825 const LValue &This, APValue &Result) { 9826 assert(!RD->isUnion() && "Expected non-union class type"); 9827 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9828 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9829 std::distance(RD->field_begin(), RD->field_end())); 9830 9831 if (RD->isInvalidDecl()) return false; 9832 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9833 9834 if (CD) { 9835 unsigned Index = 0; 9836 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9837 End = CD->bases_end(); I != End; ++I, ++Index) { 9838 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9839 LValue Subobject = This; 9840 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9841 return false; 9842 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9843 Result.getStructBase(Index))) 9844 return false; 9845 } 9846 } 9847 9848 for (const auto *I : RD->fields()) { 9849 // -- if T is a reference type, no initialization is performed. 9850 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9851 continue; 9852 9853 LValue Subobject = This; 9854 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9855 return false; 9856 9857 ImplicitValueInitExpr VIE(I->getType()); 9858 if (!EvaluateInPlace( 9859 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9860 return false; 9861 } 9862 9863 return true; 9864 } 9865 9866 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9867 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9868 if (RD->isInvalidDecl()) return false; 9869 if (RD->isUnion()) { 9870 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9871 // object's first non-static named data member is zero-initialized 9872 RecordDecl::field_iterator I = RD->field_begin(); 9873 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9874 ++I; 9875 if (I == RD->field_end()) { 9876 Result = APValue((const FieldDecl*)nullptr); 9877 return true; 9878 } 9879 9880 LValue Subobject = This; 9881 if (!HandleLValueMember(Info, E, Subobject, *I)) 9882 return false; 9883 Result = APValue(*I); 9884 ImplicitValueInitExpr VIE(I->getType()); 9885 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9886 } 9887 9888 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9889 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9890 return false; 9891 } 9892 9893 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9894 } 9895 9896 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9897 switch (E->getCastKind()) { 9898 default: 9899 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9900 9901 case CK_ConstructorConversion: 9902 return Visit(E->getSubExpr()); 9903 9904 case CK_DerivedToBase: 9905 case CK_UncheckedDerivedToBase: { 9906 APValue DerivedObject; 9907 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9908 return false; 9909 if (!DerivedObject.isStruct()) 9910 return Error(E->getSubExpr()); 9911 9912 // Derived-to-base rvalue conversion: just slice off the derived part. 9913 APValue *Value = &DerivedObject; 9914 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9915 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9916 PathE = E->path_end(); PathI != PathE; ++PathI) { 9917 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9918 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9919 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9920 RD = Base; 9921 } 9922 Result = *Value; 9923 return true; 9924 } 9925 } 9926 } 9927 9928 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9929 if (E->isTransparent()) 9930 return Visit(E->getInit(0)); 9931 9932 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9933 if (RD->isInvalidDecl()) return false; 9934 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9935 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9936 9937 EvalInfo::EvaluatingConstructorRAII EvalObj( 9938 Info, 9939 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9940 CXXRD && CXXRD->getNumBases()); 9941 9942 if (RD->isUnion()) { 9943 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9944 Result = APValue(Field); 9945 if (!Field) 9946 return true; 9947 9948 // If the initializer list for a union does not contain any elements, the 9949 // first element of the union is value-initialized. 9950 // FIXME: The element should be initialized from an initializer list. 9951 // Is this difference ever observable for initializer lists which 9952 // we don't build? 9953 ImplicitValueInitExpr VIE(Field->getType()); 9954 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9955 9956 LValue Subobject = This; 9957 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9958 return false; 9959 9960 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9961 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9962 isa<CXXDefaultInitExpr>(InitExpr)); 9963 9964 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9965 if (Field->isBitField()) 9966 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9967 Field); 9968 return true; 9969 } 9970 9971 return false; 9972 } 9973 9974 if (!Result.hasValue()) 9975 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9976 std::distance(RD->field_begin(), RD->field_end())); 9977 unsigned ElementNo = 0; 9978 bool Success = true; 9979 9980 // Initialize base classes. 9981 if (CXXRD && CXXRD->getNumBases()) { 9982 for (const auto &Base : CXXRD->bases()) { 9983 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9984 const Expr *Init = E->getInit(ElementNo); 9985 9986 LValue Subobject = This; 9987 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9988 return false; 9989 9990 APValue &FieldVal = Result.getStructBase(ElementNo); 9991 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9992 if (!Info.noteFailure()) 9993 return false; 9994 Success = false; 9995 } 9996 ++ElementNo; 9997 } 9998 9999 EvalObj.finishedConstructingBases(); 10000 } 10001 10002 // Initialize members. 10003 for (const auto *Field : RD->fields()) { 10004 // Anonymous bit-fields are not considered members of the class for 10005 // purposes of aggregate initialization. 10006 if (Field->isUnnamedBitfield()) 10007 continue; 10008 10009 LValue Subobject = This; 10010 10011 bool HaveInit = ElementNo < E->getNumInits(); 10012 10013 // FIXME: Diagnostics here should point to the end of the initializer 10014 // list, not the start. 10015 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 10016 Subobject, Field, &Layout)) 10017 return false; 10018 10019 // Perform an implicit value-initialization for members beyond the end of 10020 // the initializer list. 10021 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 10022 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 10023 10024 if (Field->getType()->isIncompleteArrayType()) { 10025 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) { 10026 if (!CAT->getSize().isZero()) { 10027 // Bail out for now. This might sort of "work", but the rest of the 10028 // code isn't really prepared to handle it. 10029 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array); 10030 return false; 10031 } 10032 } 10033 } 10034 10035 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 10036 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 10037 isa<CXXDefaultInitExpr>(Init)); 10038 10039 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10040 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 10041 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 10042 FieldVal, Field))) { 10043 if (!Info.noteFailure()) 10044 return false; 10045 Success = false; 10046 } 10047 } 10048 10049 EvalObj.finishedConstructingFields(); 10050 10051 return Success; 10052 } 10053 10054 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10055 QualType T) { 10056 // Note that E's type is not necessarily the type of our class here; we might 10057 // be initializing an array element instead. 10058 const CXXConstructorDecl *FD = E->getConstructor(); 10059 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 10060 10061 bool ZeroInit = E->requiresZeroInitialization(); 10062 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 10063 // If we've already performed zero-initialization, we're already done. 10064 if (Result.hasValue()) 10065 return true; 10066 10067 if (ZeroInit) 10068 return ZeroInitialization(E, T); 10069 10070 return getDefaultInitValue(T, Result); 10071 } 10072 10073 const FunctionDecl *Definition = nullptr; 10074 auto Body = FD->getBody(Definition); 10075 10076 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10077 return false; 10078 10079 // Avoid materializing a temporary for an elidable copy/move constructor. 10080 if (E->isElidable() && !ZeroInit) { 10081 // FIXME: This only handles the simplest case, where the source object 10082 // is passed directly as the first argument to the constructor. 10083 // This should also handle stepping though implicit casts and 10084 // and conversion sequences which involve two steps, with a 10085 // conversion operator followed by a converting constructor. 10086 const Expr *SrcObj = E->getArg(0); 10087 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 10088 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 10089 if (const MaterializeTemporaryExpr *ME = 10090 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 10091 return Visit(ME->getSubExpr()); 10092 } 10093 10094 if (ZeroInit && !ZeroInitialization(E, T)) 10095 return false; 10096 10097 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 10098 return HandleConstructorCall(E, This, Args, 10099 cast<CXXConstructorDecl>(Definition), Info, 10100 Result); 10101 } 10102 10103 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 10104 const CXXInheritedCtorInitExpr *E) { 10105 if (!Info.CurrentCall) { 10106 assert(Info.checkingPotentialConstantExpression()); 10107 return false; 10108 } 10109 10110 const CXXConstructorDecl *FD = E->getConstructor(); 10111 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 10112 return false; 10113 10114 const FunctionDecl *Definition = nullptr; 10115 auto Body = FD->getBody(Definition); 10116 10117 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10118 return false; 10119 10120 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 10121 cast<CXXConstructorDecl>(Definition), Info, 10122 Result); 10123 } 10124 10125 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 10126 const CXXStdInitializerListExpr *E) { 10127 const ConstantArrayType *ArrayType = 10128 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 10129 10130 LValue Array; 10131 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 10132 return false; 10133 10134 // Get a pointer to the first element of the array. 10135 Array.addArray(Info, E, ArrayType); 10136 10137 auto InvalidType = [&] { 10138 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 10139 << E->getType(); 10140 return false; 10141 }; 10142 10143 // FIXME: Perform the checks on the field types in SemaInit. 10144 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10145 RecordDecl::field_iterator Field = Record->field_begin(); 10146 if (Field == Record->field_end()) 10147 return InvalidType(); 10148 10149 // Start pointer. 10150 if (!Field->getType()->isPointerType() || 10151 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10152 ArrayType->getElementType())) 10153 return InvalidType(); 10154 10155 // FIXME: What if the initializer_list type has base classes, etc? 10156 Result = APValue(APValue::UninitStruct(), 0, 2); 10157 Array.moveInto(Result.getStructField(0)); 10158 10159 if (++Field == Record->field_end()) 10160 return InvalidType(); 10161 10162 if (Field->getType()->isPointerType() && 10163 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10164 ArrayType->getElementType())) { 10165 // End pointer. 10166 if (!HandleLValueArrayAdjustment(Info, E, Array, 10167 ArrayType->getElementType(), 10168 ArrayType->getSize().getZExtValue())) 10169 return false; 10170 Array.moveInto(Result.getStructField(1)); 10171 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10172 // Length. 10173 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10174 else 10175 return InvalidType(); 10176 10177 if (++Field != Record->field_end()) 10178 return InvalidType(); 10179 10180 return true; 10181 } 10182 10183 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10184 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10185 if (ClosureClass->isInvalidDecl()) 10186 return false; 10187 10188 const size_t NumFields = 10189 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10190 10191 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10192 E->capture_init_end()) && 10193 "The number of lambda capture initializers should equal the number of " 10194 "fields within the closure type"); 10195 10196 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10197 // Iterate through all the lambda's closure object's fields and initialize 10198 // them. 10199 auto *CaptureInitIt = E->capture_init_begin(); 10200 bool Success = true; 10201 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10202 for (const auto *Field : ClosureClass->fields()) { 10203 assert(CaptureInitIt != E->capture_init_end()); 10204 // Get the initializer for this field 10205 Expr *const CurFieldInit = *CaptureInitIt++; 10206 10207 // If there is no initializer, either this is a VLA or an error has 10208 // occurred. 10209 if (!CurFieldInit) 10210 return Error(E); 10211 10212 LValue Subobject = This; 10213 10214 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10215 return false; 10216 10217 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10218 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10219 if (!Info.keepEvaluatingAfterFailure()) 10220 return false; 10221 Success = false; 10222 } 10223 } 10224 return Success; 10225 } 10226 10227 static bool EvaluateRecord(const Expr *E, const LValue &This, 10228 APValue &Result, EvalInfo &Info) { 10229 assert(!E->isValueDependent()); 10230 assert(E->isPRValue() && E->getType()->isRecordType() && 10231 "can't evaluate expression as a record rvalue"); 10232 return RecordExprEvaluator(Info, This, Result).Visit(E); 10233 } 10234 10235 //===----------------------------------------------------------------------===// 10236 // Temporary Evaluation 10237 // 10238 // Temporaries are represented in the AST as rvalues, but generally behave like 10239 // lvalues. The full-object of which the temporary is a subobject is implicitly 10240 // materialized so that a reference can bind to it. 10241 //===----------------------------------------------------------------------===// 10242 namespace { 10243 class TemporaryExprEvaluator 10244 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10245 public: 10246 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10247 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10248 10249 /// Visit an expression which constructs the value of this temporary. 10250 bool VisitConstructExpr(const Expr *E) { 10251 APValue &Value = Info.CurrentCall->createTemporary( 10252 E, E->getType(), ScopeKind::FullExpression, Result); 10253 return EvaluateInPlace(Value, Info, Result, E); 10254 } 10255 10256 bool VisitCastExpr(const CastExpr *E) { 10257 switch (E->getCastKind()) { 10258 default: 10259 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10260 10261 case CK_ConstructorConversion: 10262 return VisitConstructExpr(E->getSubExpr()); 10263 } 10264 } 10265 bool VisitInitListExpr(const InitListExpr *E) { 10266 return VisitConstructExpr(E); 10267 } 10268 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10269 return VisitConstructExpr(E); 10270 } 10271 bool VisitCallExpr(const CallExpr *E) { 10272 return VisitConstructExpr(E); 10273 } 10274 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10275 return VisitConstructExpr(E); 10276 } 10277 bool VisitLambdaExpr(const LambdaExpr *E) { 10278 return VisitConstructExpr(E); 10279 } 10280 }; 10281 } // end anonymous namespace 10282 10283 /// Evaluate an expression of record type as a temporary. 10284 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10285 assert(!E->isValueDependent()); 10286 assert(E->isPRValue() && E->getType()->isRecordType()); 10287 return TemporaryExprEvaluator(Info, Result).Visit(E); 10288 } 10289 10290 //===----------------------------------------------------------------------===// 10291 // Vector Evaluation 10292 //===----------------------------------------------------------------------===// 10293 10294 namespace { 10295 class VectorExprEvaluator 10296 : public ExprEvaluatorBase<VectorExprEvaluator> { 10297 APValue &Result; 10298 public: 10299 10300 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10301 : ExprEvaluatorBaseTy(info), Result(Result) {} 10302 10303 bool Success(ArrayRef<APValue> V, const Expr *E) { 10304 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10305 // FIXME: remove this APValue copy. 10306 Result = APValue(V.data(), V.size()); 10307 return true; 10308 } 10309 bool Success(const APValue &V, const Expr *E) { 10310 assert(V.isVector()); 10311 Result = V; 10312 return true; 10313 } 10314 bool ZeroInitialization(const Expr *E); 10315 10316 bool VisitUnaryReal(const UnaryOperator *E) 10317 { return Visit(E->getSubExpr()); } 10318 bool VisitCastExpr(const CastExpr* E); 10319 bool VisitInitListExpr(const InitListExpr *E); 10320 bool VisitUnaryImag(const UnaryOperator *E); 10321 bool VisitBinaryOperator(const BinaryOperator *E); 10322 bool VisitUnaryOperator(const UnaryOperator *E); 10323 // FIXME: Missing: conditional operator (for GNU 10324 // conditional select), shufflevector, ExtVectorElementExpr 10325 }; 10326 } // end anonymous namespace 10327 10328 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10329 assert(E->isPRValue() && E->getType()->isVectorType() && 10330 "not a vector prvalue"); 10331 return VectorExprEvaluator(Info, Result).Visit(E); 10332 } 10333 10334 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10335 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10336 unsigned NElts = VTy->getNumElements(); 10337 10338 const Expr *SE = E->getSubExpr(); 10339 QualType SETy = SE->getType(); 10340 10341 switch (E->getCastKind()) { 10342 case CK_VectorSplat: { 10343 APValue Val = APValue(); 10344 if (SETy->isIntegerType()) { 10345 APSInt IntResult; 10346 if (!EvaluateInteger(SE, IntResult, Info)) 10347 return false; 10348 Val = APValue(std::move(IntResult)); 10349 } else if (SETy->isRealFloatingType()) { 10350 APFloat FloatResult(0.0); 10351 if (!EvaluateFloat(SE, FloatResult, Info)) 10352 return false; 10353 Val = APValue(std::move(FloatResult)); 10354 } else { 10355 return Error(E); 10356 } 10357 10358 // Splat and create vector APValue. 10359 SmallVector<APValue, 4> Elts(NElts, Val); 10360 return Success(Elts, E); 10361 } 10362 case CK_BitCast: { 10363 // Evaluate the operand into an APInt we can extract from. 10364 llvm::APInt SValInt; 10365 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10366 return false; 10367 // Extract the elements 10368 QualType EltTy = VTy->getElementType(); 10369 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10370 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10371 SmallVector<APValue, 4> Elts; 10372 if (EltTy->isRealFloatingType()) { 10373 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10374 unsigned FloatEltSize = EltSize; 10375 if (&Sem == &APFloat::x87DoubleExtended()) 10376 FloatEltSize = 80; 10377 for (unsigned i = 0; i < NElts; i++) { 10378 llvm::APInt Elt; 10379 if (BigEndian) 10380 Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize); 10381 else 10382 Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize); 10383 Elts.push_back(APValue(APFloat(Sem, Elt))); 10384 } 10385 } else if (EltTy->isIntegerType()) { 10386 for (unsigned i = 0; i < NElts; i++) { 10387 llvm::APInt Elt; 10388 if (BigEndian) 10389 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10390 else 10391 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10392 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10393 } 10394 } else { 10395 return Error(E); 10396 } 10397 return Success(Elts, E); 10398 } 10399 default: 10400 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10401 } 10402 } 10403 10404 bool 10405 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10406 const VectorType *VT = E->getType()->castAs<VectorType>(); 10407 unsigned NumInits = E->getNumInits(); 10408 unsigned NumElements = VT->getNumElements(); 10409 10410 QualType EltTy = VT->getElementType(); 10411 SmallVector<APValue, 4> Elements; 10412 10413 // The number of initializers can be less than the number of 10414 // vector elements. For OpenCL, this can be due to nested vector 10415 // initialization. For GCC compatibility, missing trailing elements 10416 // should be initialized with zeroes. 10417 unsigned CountInits = 0, CountElts = 0; 10418 while (CountElts < NumElements) { 10419 // Handle nested vector initialization. 10420 if (CountInits < NumInits 10421 && E->getInit(CountInits)->getType()->isVectorType()) { 10422 APValue v; 10423 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10424 return Error(E); 10425 unsigned vlen = v.getVectorLength(); 10426 for (unsigned j = 0; j < vlen; j++) 10427 Elements.push_back(v.getVectorElt(j)); 10428 CountElts += vlen; 10429 } else if (EltTy->isIntegerType()) { 10430 llvm::APSInt sInt(32); 10431 if (CountInits < NumInits) { 10432 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10433 return false; 10434 } else // trailing integer zero. 10435 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10436 Elements.push_back(APValue(sInt)); 10437 CountElts++; 10438 } else { 10439 llvm::APFloat f(0.0); 10440 if (CountInits < NumInits) { 10441 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10442 return false; 10443 } else // trailing float zero. 10444 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10445 Elements.push_back(APValue(f)); 10446 CountElts++; 10447 } 10448 CountInits++; 10449 } 10450 return Success(Elements, E); 10451 } 10452 10453 bool 10454 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10455 const auto *VT = E->getType()->castAs<VectorType>(); 10456 QualType EltTy = VT->getElementType(); 10457 APValue ZeroElement; 10458 if (EltTy->isIntegerType()) 10459 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10460 else 10461 ZeroElement = 10462 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10463 10464 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10465 return Success(Elements, E); 10466 } 10467 10468 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10469 VisitIgnoredValue(E->getSubExpr()); 10470 return ZeroInitialization(E); 10471 } 10472 10473 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10474 BinaryOperatorKind Op = E->getOpcode(); 10475 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10476 "Operation not supported on vector types"); 10477 10478 if (Op == BO_Comma) 10479 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10480 10481 Expr *LHS = E->getLHS(); 10482 Expr *RHS = E->getRHS(); 10483 10484 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10485 "Must both be vector types"); 10486 // Checking JUST the types are the same would be fine, except shifts don't 10487 // need to have their types be the same (since you always shift by an int). 10488 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10489 E->getType()->castAs<VectorType>()->getNumElements() && 10490 RHS->getType()->castAs<VectorType>()->getNumElements() == 10491 E->getType()->castAs<VectorType>()->getNumElements() && 10492 "All operands must be the same size."); 10493 10494 APValue LHSValue; 10495 APValue RHSValue; 10496 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10497 if (!LHSOK && !Info.noteFailure()) 10498 return false; 10499 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10500 return false; 10501 10502 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10503 return false; 10504 10505 return Success(LHSValue, E); 10506 } 10507 10508 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, 10509 QualType ResultTy, 10510 UnaryOperatorKind Op, 10511 APValue Elt) { 10512 switch (Op) { 10513 case UO_Plus: 10514 // Nothing to do here. 10515 return Elt; 10516 case UO_Minus: 10517 if (Elt.getKind() == APValue::Int) { 10518 Elt.getInt().negate(); 10519 } else { 10520 assert(Elt.getKind() == APValue::Float && 10521 "Vector can only be int or float type"); 10522 Elt.getFloat().changeSign(); 10523 } 10524 return Elt; 10525 case UO_Not: 10526 // This is only valid for integral types anyway, so we don't have to handle 10527 // float here. 10528 assert(Elt.getKind() == APValue::Int && 10529 "Vector operator ~ can only be int"); 10530 Elt.getInt().flipAllBits(); 10531 return Elt; 10532 case UO_LNot: { 10533 if (Elt.getKind() == APValue::Int) { 10534 Elt.getInt() = !Elt.getInt(); 10535 // operator ! on vectors returns -1 for 'truth', so negate it. 10536 Elt.getInt().negate(); 10537 return Elt; 10538 } 10539 assert(Elt.getKind() == APValue::Float && 10540 "Vector can only be int or float type"); 10541 // Float types result in an int of the same size, but -1 for true, or 0 for 10542 // false. 10543 APSInt EltResult{Ctx.getIntWidth(ResultTy), 10544 ResultTy->isUnsignedIntegerType()}; 10545 if (Elt.getFloat().isZero()) 10546 EltResult.setAllBits(); 10547 else 10548 EltResult.clearAllBits(); 10549 10550 return APValue{EltResult}; 10551 } 10552 default: 10553 // FIXME: Implement the rest of the unary operators. 10554 return llvm::None; 10555 } 10556 } 10557 10558 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10559 Expr *SubExpr = E->getSubExpr(); 10560 const auto *VD = SubExpr->getType()->castAs<VectorType>(); 10561 // This result element type differs in the case of negating a floating point 10562 // vector, since the result type is the a vector of the equivilant sized 10563 // integer. 10564 const QualType ResultEltTy = VD->getElementType(); 10565 UnaryOperatorKind Op = E->getOpcode(); 10566 10567 APValue SubExprValue; 10568 if (!Evaluate(SubExprValue, Info, SubExpr)) 10569 return false; 10570 10571 // FIXME: This vector evaluator someday needs to be changed to be LValue 10572 // aware/keep LValue information around, rather than dealing with just vector 10573 // types directly. Until then, we cannot handle cases where the operand to 10574 // these unary operators is an LValue. The only case I've been able to see 10575 // cause this is operator++ assigning to a member expression (only valid in 10576 // altivec compilations) in C mode, so this shouldn't limit us too much. 10577 if (SubExprValue.isLValue()) 10578 return false; 10579 10580 assert(SubExprValue.getVectorLength() == VD->getNumElements() && 10581 "Vector length doesn't match type?"); 10582 10583 SmallVector<APValue, 4> ResultElements; 10584 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { 10585 llvm::Optional<APValue> Elt = handleVectorUnaryOperator( 10586 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); 10587 if (!Elt) 10588 return false; 10589 ResultElements.push_back(*Elt); 10590 } 10591 return Success(APValue(ResultElements.data(), ResultElements.size()), E); 10592 } 10593 10594 //===----------------------------------------------------------------------===// 10595 // Array Evaluation 10596 //===----------------------------------------------------------------------===// 10597 10598 namespace { 10599 class ArrayExprEvaluator 10600 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10601 const LValue &This; 10602 APValue &Result; 10603 public: 10604 10605 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10606 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10607 10608 bool Success(const APValue &V, const Expr *E) { 10609 assert(V.isArray() && "expected array"); 10610 Result = V; 10611 return true; 10612 } 10613 10614 bool ZeroInitialization(const Expr *E) { 10615 const ConstantArrayType *CAT = 10616 Info.Ctx.getAsConstantArrayType(E->getType()); 10617 if (!CAT) { 10618 if (E->getType()->isIncompleteArrayType()) { 10619 // We can be asked to zero-initialize a flexible array member; this 10620 // is represented as an ImplicitValueInitExpr of incomplete array 10621 // type. In this case, the array has zero elements. 10622 Result = APValue(APValue::UninitArray(), 0, 0); 10623 return true; 10624 } 10625 // FIXME: We could handle VLAs here. 10626 return Error(E); 10627 } 10628 10629 Result = APValue(APValue::UninitArray(), 0, 10630 CAT->getSize().getZExtValue()); 10631 if (!Result.hasArrayFiller()) 10632 return true; 10633 10634 // Zero-initialize all elements. 10635 LValue Subobject = This; 10636 Subobject.addArray(Info, E, CAT); 10637 ImplicitValueInitExpr VIE(CAT->getElementType()); 10638 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10639 } 10640 10641 bool VisitCallExpr(const CallExpr *E) { 10642 return handleCallExpr(E, Result, &This); 10643 } 10644 bool VisitInitListExpr(const InitListExpr *E, 10645 QualType AllocType = QualType()); 10646 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10647 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10648 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10649 const LValue &Subobject, 10650 APValue *Value, QualType Type); 10651 bool VisitStringLiteral(const StringLiteral *E, 10652 QualType AllocType = QualType()) { 10653 expandStringLiteral(Info, E, Result, AllocType); 10654 return true; 10655 } 10656 }; 10657 } // end anonymous namespace 10658 10659 static bool EvaluateArray(const Expr *E, const LValue &This, 10660 APValue &Result, EvalInfo &Info) { 10661 assert(!E->isValueDependent()); 10662 assert(E->isPRValue() && E->getType()->isArrayType() && 10663 "not an array prvalue"); 10664 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10665 } 10666 10667 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10668 APValue &Result, const InitListExpr *ILE, 10669 QualType AllocType) { 10670 assert(!ILE->isValueDependent()); 10671 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10672 "not an array prvalue"); 10673 return ArrayExprEvaluator(Info, This, Result) 10674 .VisitInitListExpr(ILE, AllocType); 10675 } 10676 10677 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10678 APValue &Result, 10679 const CXXConstructExpr *CCE, 10680 QualType AllocType) { 10681 assert(!CCE->isValueDependent()); 10682 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10683 "not an array prvalue"); 10684 return ArrayExprEvaluator(Info, This, Result) 10685 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10686 } 10687 10688 // Return true iff the given array filler may depend on the element index. 10689 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10690 // For now, just allow non-class value-initialization and initialization 10691 // lists comprised of them. 10692 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10693 return false; 10694 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10695 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10696 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10697 return true; 10698 } 10699 return false; 10700 } 10701 return true; 10702 } 10703 10704 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10705 QualType AllocType) { 10706 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10707 AllocType.isNull() ? E->getType() : AllocType); 10708 if (!CAT) 10709 return Error(E); 10710 10711 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10712 // an appropriately-typed string literal enclosed in braces. 10713 if (E->isStringLiteralInit()) { 10714 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10715 // FIXME: Support ObjCEncodeExpr here once we support it in 10716 // ArrayExprEvaluator generally. 10717 if (!SL) 10718 return Error(E); 10719 return VisitStringLiteral(SL, AllocType); 10720 } 10721 // Any other transparent list init will need proper handling of the 10722 // AllocType; we can't just recurse to the inner initializer. 10723 assert(!E->isTransparent() && 10724 "transparent array list initialization is not string literal init?"); 10725 10726 bool Success = true; 10727 10728 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10729 "zero-initialized array shouldn't have any initialized elts"); 10730 APValue Filler; 10731 if (Result.isArray() && Result.hasArrayFiller()) 10732 Filler = Result.getArrayFiller(); 10733 10734 unsigned NumEltsToInit = E->getNumInits(); 10735 unsigned NumElts = CAT->getSize().getZExtValue(); 10736 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10737 10738 // If the initializer might depend on the array index, run it for each 10739 // array element. 10740 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10741 NumEltsToInit = NumElts; 10742 10743 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10744 << NumEltsToInit << ".\n"); 10745 10746 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10747 10748 // If the array was previously zero-initialized, preserve the 10749 // zero-initialized values. 10750 if (Filler.hasValue()) { 10751 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10752 Result.getArrayInitializedElt(I) = Filler; 10753 if (Result.hasArrayFiller()) 10754 Result.getArrayFiller() = Filler; 10755 } 10756 10757 LValue Subobject = This; 10758 Subobject.addArray(Info, E, CAT); 10759 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10760 const Expr *Init = 10761 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10762 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10763 Info, Subobject, Init) || 10764 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10765 CAT->getElementType(), 1)) { 10766 if (!Info.noteFailure()) 10767 return false; 10768 Success = false; 10769 } 10770 } 10771 10772 if (!Result.hasArrayFiller()) 10773 return Success; 10774 10775 // If we get here, we have a trivial filler, which we can just evaluate 10776 // once and splat over the rest of the array elements. 10777 assert(FillerExpr && "no array filler for incomplete init list"); 10778 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10779 FillerExpr) && Success; 10780 } 10781 10782 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10783 LValue CommonLV; 10784 if (E->getCommonExpr() && 10785 !Evaluate(Info.CurrentCall->createTemporary( 10786 E->getCommonExpr(), 10787 getStorageType(Info.Ctx, E->getCommonExpr()), 10788 ScopeKind::FullExpression, CommonLV), 10789 Info, E->getCommonExpr()->getSourceExpr())) 10790 return false; 10791 10792 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10793 10794 uint64_t Elements = CAT->getSize().getZExtValue(); 10795 Result = APValue(APValue::UninitArray(), Elements, Elements); 10796 10797 LValue Subobject = This; 10798 Subobject.addArray(Info, E, CAT); 10799 10800 bool Success = true; 10801 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10802 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10803 Info, Subobject, E->getSubExpr()) || 10804 !HandleLValueArrayAdjustment(Info, E, Subobject, 10805 CAT->getElementType(), 1)) { 10806 if (!Info.noteFailure()) 10807 return false; 10808 Success = false; 10809 } 10810 } 10811 10812 return Success; 10813 } 10814 10815 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10816 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10817 } 10818 10819 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10820 const LValue &Subobject, 10821 APValue *Value, 10822 QualType Type) { 10823 bool HadZeroInit = Value->hasValue(); 10824 10825 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10826 unsigned FinalSize = CAT->getSize().getZExtValue(); 10827 10828 // Preserve the array filler if we had prior zero-initialization. 10829 APValue Filler = 10830 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10831 : APValue(); 10832 10833 *Value = APValue(APValue::UninitArray(), 0, FinalSize); 10834 if (FinalSize == 0) 10835 return true; 10836 10837 LValue ArrayElt = Subobject; 10838 ArrayElt.addArray(Info, E, CAT); 10839 // We do the whole initialization in two passes, first for just one element, 10840 // then for the whole array. It's possible we may find out we can't do const 10841 // init in the first pass, in which case we avoid allocating a potentially 10842 // large array. We don't do more passes because expanding array requires 10843 // copying the data, which is wasteful. 10844 for (const unsigned N : {1u, FinalSize}) { 10845 unsigned OldElts = Value->getArrayInitializedElts(); 10846 if (OldElts == N) 10847 break; 10848 10849 // Expand the array to appropriate size. 10850 APValue NewValue(APValue::UninitArray(), N, FinalSize); 10851 for (unsigned I = 0; I < OldElts; ++I) 10852 NewValue.getArrayInitializedElt(I).swap( 10853 Value->getArrayInitializedElt(I)); 10854 Value->swap(NewValue); 10855 10856 if (HadZeroInit) 10857 for (unsigned I = OldElts; I < N; ++I) 10858 Value->getArrayInitializedElt(I) = Filler; 10859 10860 // Initialize the elements. 10861 for (unsigned I = OldElts; I < N; ++I) { 10862 if (!VisitCXXConstructExpr(E, ArrayElt, 10863 &Value->getArrayInitializedElt(I), 10864 CAT->getElementType()) || 10865 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10866 CAT->getElementType(), 1)) 10867 return false; 10868 // When checking for const initilization any diagnostic is considered 10869 // an error. 10870 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && 10871 !Info.keepEvaluatingAfterFailure()) 10872 return false; 10873 } 10874 } 10875 10876 return true; 10877 } 10878 10879 if (!Type->isRecordType()) 10880 return Error(E); 10881 10882 return RecordExprEvaluator(Info, Subobject, *Value) 10883 .VisitCXXConstructExpr(E, Type); 10884 } 10885 10886 //===----------------------------------------------------------------------===// 10887 // Integer Evaluation 10888 // 10889 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10890 // types and back in constant folding. Integer values are thus represented 10891 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10892 //===----------------------------------------------------------------------===// 10893 10894 namespace { 10895 class IntExprEvaluator 10896 : public ExprEvaluatorBase<IntExprEvaluator> { 10897 APValue &Result; 10898 public: 10899 IntExprEvaluator(EvalInfo &info, APValue &result) 10900 : ExprEvaluatorBaseTy(info), Result(result) {} 10901 10902 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10903 assert(E->getType()->isIntegralOrEnumerationType() && 10904 "Invalid evaluation result."); 10905 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10906 "Invalid evaluation result."); 10907 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10908 "Invalid evaluation result."); 10909 Result = APValue(SI); 10910 return true; 10911 } 10912 bool Success(const llvm::APSInt &SI, const Expr *E) { 10913 return Success(SI, E, Result); 10914 } 10915 10916 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10917 assert(E->getType()->isIntegralOrEnumerationType() && 10918 "Invalid evaluation result."); 10919 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10920 "Invalid evaluation result."); 10921 Result = APValue(APSInt(I)); 10922 Result.getInt().setIsUnsigned( 10923 E->getType()->isUnsignedIntegerOrEnumerationType()); 10924 return true; 10925 } 10926 bool Success(const llvm::APInt &I, const Expr *E) { 10927 return Success(I, E, Result); 10928 } 10929 10930 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10931 assert(E->getType()->isIntegralOrEnumerationType() && 10932 "Invalid evaluation result."); 10933 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10934 return true; 10935 } 10936 bool Success(uint64_t Value, const Expr *E) { 10937 return Success(Value, E, Result); 10938 } 10939 10940 bool Success(CharUnits Size, const Expr *E) { 10941 return Success(Size.getQuantity(), E); 10942 } 10943 10944 bool Success(const APValue &V, const Expr *E) { 10945 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10946 Result = V; 10947 return true; 10948 } 10949 return Success(V.getInt(), E); 10950 } 10951 10952 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10953 10954 //===--------------------------------------------------------------------===// 10955 // Visitor Methods 10956 //===--------------------------------------------------------------------===// 10957 10958 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10959 return Success(E->getValue(), E); 10960 } 10961 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10962 return Success(E->getValue(), E); 10963 } 10964 10965 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10966 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10967 if (CheckReferencedDecl(E, E->getDecl())) 10968 return true; 10969 10970 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10971 } 10972 bool VisitMemberExpr(const MemberExpr *E) { 10973 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10974 VisitIgnoredBaseExpression(E->getBase()); 10975 return true; 10976 } 10977 10978 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10979 } 10980 10981 bool VisitCallExpr(const CallExpr *E); 10982 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10983 bool VisitBinaryOperator(const BinaryOperator *E); 10984 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10985 bool VisitUnaryOperator(const UnaryOperator *E); 10986 10987 bool VisitCastExpr(const CastExpr* E); 10988 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10989 10990 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10991 return Success(E->getValue(), E); 10992 } 10993 10994 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10995 return Success(E->getValue(), E); 10996 } 10997 10998 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10999 if (Info.ArrayInitIndex == uint64_t(-1)) { 11000 // We were asked to evaluate this subexpression independent of the 11001 // enclosing ArrayInitLoopExpr. We can't do that. 11002 Info.FFDiag(E); 11003 return false; 11004 } 11005 return Success(Info.ArrayInitIndex, E); 11006 } 11007 11008 // Note, GNU defines __null as an integer, not a pointer. 11009 bool VisitGNUNullExpr(const GNUNullExpr *E) { 11010 return ZeroInitialization(E); 11011 } 11012 11013 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 11014 return Success(E->getValue(), E); 11015 } 11016 11017 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 11018 return Success(E->getValue(), E); 11019 } 11020 11021 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 11022 return Success(E->getValue(), E); 11023 } 11024 11025 bool VisitUnaryReal(const UnaryOperator *E); 11026 bool VisitUnaryImag(const UnaryOperator *E); 11027 11028 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 11029 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 11030 bool VisitSourceLocExpr(const SourceLocExpr *E); 11031 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 11032 bool VisitRequiresExpr(const RequiresExpr *E); 11033 // FIXME: Missing: array subscript of vector, member of vector 11034 }; 11035 11036 class FixedPointExprEvaluator 11037 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 11038 APValue &Result; 11039 11040 public: 11041 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 11042 : ExprEvaluatorBaseTy(info), Result(result) {} 11043 11044 bool Success(const llvm::APInt &I, const Expr *E) { 11045 return Success( 11046 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11047 } 11048 11049 bool Success(uint64_t Value, const Expr *E) { 11050 return Success( 11051 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11052 } 11053 11054 bool Success(const APValue &V, const Expr *E) { 11055 return Success(V.getFixedPoint(), E); 11056 } 11057 11058 bool Success(const APFixedPoint &V, const Expr *E) { 11059 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 11060 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 11061 "Invalid evaluation result."); 11062 Result = APValue(V); 11063 return true; 11064 } 11065 11066 //===--------------------------------------------------------------------===// 11067 // Visitor Methods 11068 //===--------------------------------------------------------------------===// 11069 11070 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 11071 return Success(E->getValue(), E); 11072 } 11073 11074 bool VisitCastExpr(const CastExpr *E); 11075 bool VisitUnaryOperator(const UnaryOperator *E); 11076 bool VisitBinaryOperator(const BinaryOperator *E); 11077 }; 11078 } // end anonymous namespace 11079 11080 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 11081 /// produce either the integer value or a pointer. 11082 /// 11083 /// GCC has a heinous extension which folds casts between pointer types and 11084 /// pointer-sized integral types. We support this by allowing the evaluation of 11085 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 11086 /// Some simple arithmetic on such values is supported (they are treated much 11087 /// like char*). 11088 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 11089 EvalInfo &Info) { 11090 assert(!E->isValueDependent()); 11091 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 11092 return IntExprEvaluator(Info, Result).Visit(E); 11093 } 11094 11095 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 11096 assert(!E->isValueDependent()); 11097 APValue Val; 11098 if (!EvaluateIntegerOrLValue(E, Val, Info)) 11099 return false; 11100 if (!Val.isInt()) { 11101 // FIXME: It would be better to produce the diagnostic for casting 11102 // a pointer to an integer. 11103 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11104 return false; 11105 } 11106 Result = Val.getInt(); 11107 return true; 11108 } 11109 11110 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 11111 APValue Evaluated = E->EvaluateInContext( 11112 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 11113 return Success(Evaluated, E); 11114 } 11115 11116 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 11117 EvalInfo &Info) { 11118 assert(!E->isValueDependent()); 11119 if (E->getType()->isFixedPointType()) { 11120 APValue Val; 11121 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 11122 return false; 11123 if (!Val.isFixedPoint()) 11124 return false; 11125 11126 Result = Val.getFixedPoint(); 11127 return true; 11128 } 11129 return false; 11130 } 11131 11132 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 11133 EvalInfo &Info) { 11134 assert(!E->isValueDependent()); 11135 if (E->getType()->isIntegerType()) { 11136 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 11137 APSInt Val; 11138 if (!EvaluateInteger(E, Val, Info)) 11139 return false; 11140 Result = APFixedPoint(Val, FXSema); 11141 return true; 11142 } else if (E->getType()->isFixedPointType()) { 11143 return EvaluateFixedPoint(E, Result, Info); 11144 } 11145 return false; 11146 } 11147 11148 /// Check whether the given declaration can be directly converted to an integral 11149 /// rvalue. If not, no diagnostic is produced; there are other things we can 11150 /// try. 11151 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 11152 // Enums are integer constant exprs. 11153 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 11154 // Check for signedness/width mismatches between E type and ECD value. 11155 bool SameSign = (ECD->getInitVal().isSigned() 11156 == E->getType()->isSignedIntegerOrEnumerationType()); 11157 bool SameWidth = (ECD->getInitVal().getBitWidth() 11158 == Info.Ctx.getIntWidth(E->getType())); 11159 if (SameSign && SameWidth) 11160 return Success(ECD->getInitVal(), E); 11161 else { 11162 // Get rid of mismatch (otherwise Success assertions will fail) 11163 // by computing a new value matching the type of E. 11164 llvm::APSInt Val = ECD->getInitVal(); 11165 if (!SameSign) 11166 Val.setIsSigned(!ECD->getInitVal().isSigned()); 11167 if (!SameWidth) 11168 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 11169 return Success(Val, E); 11170 } 11171 } 11172 return false; 11173 } 11174 11175 /// Values returned by __builtin_classify_type, chosen to match the values 11176 /// produced by GCC's builtin. 11177 enum class GCCTypeClass { 11178 None = -1, 11179 Void = 0, 11180 Integer = 1, 11181 // GCC reserves 2 for character types, but instead classifies them as 11182 // integers. 11183 Enum = 3, 11184 Bool = 4, 11185 Pointer = 5, 11186 // GCC reserves 6 for references, but appears to never use it (because 11187 // expressions never have reference type, presumably). 11188 PointerToDataMember = 7, 11189 RealFloat = 8, 11190 Complex = 9, 11191 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 11192 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 11193 // GCC claims to reserve 11 for pointers to member functions, but *actually* 11194 // uses 12 for that purpose, same as for a class or struct. Maybe it 11195 // internally implements a pointer to member as a struct? Who knows. 11196 PointerToMemberFunction = 12, // Not a bug, see above. 11197 ClassOrStruct = 12, 11198 Union = 13, 11199 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 11200 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 11201 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 11202 // literals. 11203 }; 11204 11205 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11206 /// as GCC. 11207 static GCCTypeClass 11208 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 11209 assert(!T->isDependentType() && "unexpected dependent type"); 11210 11211 QualType CanTy = T.getCanonicalType(); 11212 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 11213 11214 switch (CanTy->getTypeClass()) { 11215 #define TYPE(ID, BASE) 11216 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 11217 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 11218 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 11219 #include "clang/AST/TypeNodes.inc" 11220 case Type::Auto: 11221 case Type::DeducedTemplateSpecialization: 11222 llvm_unreachable("unexpected non-canonical or dependent type"); 11223 11224 case Type::Builtin: 11225 switch (BT->getKind()) { 11226 #define BUILTIN_TYPE(ID, SINGLETON_ID) 11227 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 11228 case BuiltinType::ID: return GCCTypeClass::Integer; 11229 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 11230 case BuiltinType::ID: return GCCTypeClass::RealFloat; 11231 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 11232 case BuiltinType::ID: break; 11233 #include "clang/AST/BuiltinTypes.def" 11234 case BuiltinType::Void: 11235 return GCCTypeClass::Void; 11236 11237 case BuiltinType::Bool: 11238 return GCCTypeClass::Bool; 11239 11240 case BuiltinType::Char_U: 11241 case BuiltinType::UChar: 11242 case BuiltinType::WChar_U: 11243 case BuiltinType::Char8: 11244 case BuiltinType::Char16: 11245 case BuiltinType::Char32: 11246 case BuiltinType::UShort: 11247 case BuiltinType::UInt: 11248 case BuiltinType::ULong: 11249 case BuiltinType::ULongLong: 11250 case BuiltinType::UInt128: 11251 return GCCTypeClass::Integer; 11252 11253 case BuiltinType::UShortAccum: 11254 case BuiltinType::UAccum: 11255 case BuiltinType::ULongAccum: 11256 case BuiltinType::UShortFract: 11257 case BuiltinType::UFract: 11258 case BuiltinType::ULongFract: 11259 case BuiltinType::SatUShortAccum: 11260 case BuiltinType::SatUAccum: 11261 case BuiltinType::SatULongAccum: 11262 case BuiltinType::SatUShortFract: 11263 case BuiltinType::SatUFract: 11264 case BuiltinType::SatULongFract: 11265 return GCCTypeClass::None; 11266 11267 case BuiltinType::NullPtr: 11268 11269 case BuiltinType::ObjCId: 11270 case BuiltinType::ObjCClass: 11271 case BuiltinType::ObjCSel: 11272 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11273 case BuiltinType::Id: 11274 #include "clang/Basic/OpenCLImageTypes.def" 11275 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11276 case BuiltinType::Id: 11277 #include "clang/Basic/OpenCLExtensionTypes.def" 11278 case BuiltinType::OCLSampler: 11279 case BuiltinType::OCLEvent: 11280 case BuiltinType::OCLClkEvent: 11281 case BuiltinType::OCLQueue: 11282 case BuiltinType::OCLReserveID: 11283 #define SVE_TYPE(Name, Id, SingletonId) \ 11284 case BuiltinType::Id: 11285 #include "clang/Basic/AArch64SVEACLETypes.def" 11286 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11287 case BuiltinType::Id: 11288 #include "clang/Basic/PPCTypes.def" 11289 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11290 #include "clang/Basic/RISCVVTypes.def" 11291 return GCCTypeClass::None; 11292 11293 case BuiltinType::Dependent: 11294 llvm_unreachable("unexpected dependent type"); 11295 }; 11296 llvm_unreachable("unexpected placeholder type"); 11297 11298 case Type::Enum: 11299 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11300 11301 case Type::Pointer: 11302 case Type::ConstantArray: 11303 case Type::VariableArray: 11304 case Type::IncompleteArray: 11305 case Type::FunctionNoProto: 11306 case Type::FunctionProto: 11307 return GCCTypeClass::Pointer; 11308 11309 case Type::MemberPointer: 11310 return CanTy->isMemberDataPointerType() 11311 ? GCCTypeClass::PointerToDataMember 11312 : GCCTypeClass::PointerToMemberFunction; 11313 11314 case Type::Complex: 11315 return GCCTypeClass::Complex; 11316 11317 case Type::Record: 11318 return CanTy->isUnionType() ? GCCTypeClass::Union 11319 : GCCTypeClass::ClassOrStruct; 11320 11321 case Type::Atomic: 11322 // GCC classifies _Atomic T the same as T. 11323 return EvaluateBuiltinClassifyType( 11324 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11325 11326 case Type::BlockPointer: 11327 case Type::Vector: 11328 case Type::ExtVector: 11329 case Type::ConstantMatrix: 11330 case Type::ObjCObject: 11331 case Type::ObjCInterface: 11332 case Type::ObjCObjectPointer: 11333 case Type::Pipe: 11334 case Type::BitInt: 11335 // GCC classifies vectors as None. We follow its lead and classify all 11336 // other types that don't fit into the regular classification the same way. 11337 return GCCTypeClass::None; 11338 11339 case Type::LValueReference: 11340 case Type::RValueReference: 11341 llvm_unreachable("invalid type for expression"); 11342 } 11343 11344 llvm_unreachable("unexpected type class"); 11345 } 11346 11347 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11348 /// as GCC. 11349 static GCCTypeClass 11350 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11351 // If no argument was supplied, default to None. This isn't 11352 // ideal, however it is what gcc does. 11353 if (E->getNumArgs() == 0) 11354 return GCCTypeClass::None; 11355 11356 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11357 // being an ICE, but still folds it to a constant using the type of the first 11358 // argument. 11359 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11360 } 11361 11362 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11363 /// __builtin_constant_p when applied to the given pointer. 11364 /// 11365 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11366 /// or it points to the first character of a string literal. 11367 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11368 APValue::LValueBase Base = LV.getLValueBase(); 11369 if (Base.isNull()) { 11370 // A null base is acceptable. 11371 return true; 11372 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11373 if (!isa<StringLiteral>(E)) 11374 return false; 11375 return LV.getLValueOffset().isZero(); 11376 } else if (Base.is<TypeInfoLValue>()) { 11377 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11378 // evaluate to true. 11379 return true; 11380 } else { 11381 // Any other base is not constant enough for GCC. 11382 return false; 11383 } 11384 } 11385 11386 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11387 /// GCC as we can manage. 11388 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11389 // This evaluation is not permitted to have side-effects, so evaluate it in 11390 // a speculative evaluation context. 11391 SpeculativeEvaluationRAII SpeculativeEval(Info); 11392 11393 // Constant-folding is always enabled for the operand of __builtin_constant_p 11394 // (even when the enclosing evaluation context otherwise requires a strict 11395 // language-specific constant expression). 11396 FoldConstant Fold(Info, true); 11397 11398 QualType ArgType = Arg->getType(); 11399 11400 // __builtin_constant_p always has one operand. The rules which gcc follows 11401 // are not precisely documented, but are as follows: 11402 // 11403 // - If the operand is of integral, floating, complex or enumeration type, 11404 // and can be folded to a known value of that type, it returns 1. 11405 // - If the operand can be folded to a pointer to the first character 11406 // of a string literal (or such a pointer cast to an integral type) 11407 // or to a null pointer or an integer cast to a pointer, it returns 1. 11408 // 11409 // Otherwise, it returns 0. 11410 // 11411 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11412 // its support for this did not work prior to GCC 9 and is not yet well 11413 // understood. 11414 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11415 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11416 ArgType->isNullPtrType()) { 11417 APValue V; 11418 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11419 Fold.keepDiagnostics(); 11420 return false; 11421 } 11422 11423 // For a pointer (possibly cast to integer), there are special rules. 11424 if (V.getKind() == APValue::LValue) 11425 return EvaluateBuiltinConstantPForLValue(V); 11426 11427 // Otherwise, any constant value is good enough. 11428 return V.hasValue(); 11429 } 11430 11431 // Anything else isn't considered to be sufficiently constant. 11432 return false; 11433 } 11434 11435 /// Retrieves the "underlying object type" of the given expression, 11436 /// as used by __builtin_object_size. 11437 static QualType getObjectType(APValue::LValueBase B) { 11438 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11439 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11440 return VD->getType(); 11441 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11442 if (isa<CompoundLiteralExpr>(E)) 11443 return E->getType(); 11444 } else if (B.is<TypeInfoLValue>()) { 11445 return B.getTypeInfoType(); 11446 } else if (B.is<DynamicAllocLValue>()) { 11447 return B.getDynamicAllocType(); 11448 } 11449 11450 return QualType(); 11451 } 11452 11453 /// A more selective version of E->IgnoreParenCasts for 11454 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11455 /// to change the type of E. 11456 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11457 /// 11458 /// Always returns an RValue with a pointer representation. 11459 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11460 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11461 11462 auto *NoParens = E->IgnoreParens(); 11463 auto *Cast = dyn_cast<CastExpr>(NoParens); 11464 if (Cast == nullptr) 11465 return NoParens; 11466 11467 // We only conservatively allow a few kinds of casts, because this code is 11468 // inherently a simple solution that seeks to support the common case. 11469 auto CastKind = Cast->getCastKind(); 11470 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11471 CastKind != CK_AddressSpaceConversion) 11472 return NoParens; 11473 11474 auto *SubExpr = Cast->getSubExpr(); 11475 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11476 return NoParens; 11477 return ignorePointerCastsAndParens(SubExpr); 11478 } 11479 11480 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11481 /// record layout. e.g. 11482 /// struct { struct { int a, b; } fst, snd; } obj; 11483 /// obj.fst // no 11484 /// obj.snd // yes 11485 /// obj.fst.a // no 11486 /// obj.fst.b // no 11487 /// obj.snd.a // no 11488 /// obj.snd.b // yes 11489 /// 11490 /// Please note: this function is specialized for how __builtin_object_size 11491 /// views "objects". 11492 /// 11493 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11494 /// correct result, it will always return true. 11495 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11496 assert(!LVal.Designator.Invalid); 11497 11498 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11499 const RecordDecl *Parent = FD->getParent(); 11500 Invalid = Parent->isInvalidDecl(); 11501 if (Invalid || Parent->isUnion()) 11502 return true; 11503 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11504 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11505 }; 11506 11507 auto &Base = LVal.getLValueBase(); 11508 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11509 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11510 bool Invalid; 11511 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11512 return Invalid; 11513 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11514 for (auto *FD : IFD->chain()) { 11515 bool Invalid; 11516 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11517 return Invalid; 11518 } 11519 } 11520 } 11521 11522 unsigned I = 0; 11523 QualType BaseType = getType(Base); 11524 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11525 // If we don't know the array bound, conservatively assume we're looking at 11526 // the final array element. 11527 ++I; 11528 if (BaseType->isIncompleteArrayType()) 11529 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11530 else 11531 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11532 } 11533 11534 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11535 const auto &Entry = LVal.Designator.Entries[I]; 11536 if (BaseType->isArrayType()) { 11537 // Because __builtin_object_size treats arrays as objects, we can ignore 11538 // the index iff this is the last array in the Designator. 11539 if (I + 1 == E) 11540 return true; 11541 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11542 uint64_t Index = Entry.getAsArrayIndex(); 11543 if (Index + 1 != CAT->getSize()) 11544 return false; 11545 BaseType = CAT->getElementType(); 11546 } else if (BaseType->isAnyComplexType()) { 11547 const auto *CT = BaseType->castAs<ComplexType>(); 11548 uint64_t Index = Entry.getAsArrayIndex(); 11549 if (Index != 1) 11550 return false; 11551 BaseType = CT->getElementType(); 11552 } else if (auto *FD = getAsField(Entry)) { 11553 bool Invalid; 11554 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11555 return Invalid; 11556 BaseType = FD->getType(); 11557 } else { 11558 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11559 return false; 11560 } 11561 } 11562 return true; 11563 } 11564 11565 /// Tests to see if the LValue has a user-specified designator (that isn't 11566 /// necessarily valid). Note that this always returns 'true' if the LValue has 11567 /// an unsized array as its first designator entry, because there's currently no 11568 /// way to tell if the user typed *foo or foo[0]. 11569 static bool refersToCompleteObject(const LValue &LVal) { 11570 if (LVal.Designator.Invalid) 11571 return false; 11572 11573 if (!LVal.Designator.Entries.empty()) 11574 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11575 11576 if (!LVal.InvalidBase) 11577 return true; 11578 11579 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11580 // the LValueBase. 11581 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11582 return !E || !isa<MemberExpr>(E); 11583 } 11584 11585 /// Attempts to detect a user writing into a piece of memory that's impossible 11586 /// to figure out the size of by just using types. 11587 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11588 const SubobjectDesignator &Designator = LVal.Designator; 11589 // Notes: 11590 // - Users can only write off of the end when we have an invalid base. Invalid 11591 // bases imply we don't know where the memory came from. 11592 // - We used to be a bit more aggressive here; we'd only be conservative if 11593 // the array at the end was flexible, or if it had 0 or 1 elements. This 11594 // broke some common standard library extensions (PR30346), but was 11595 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11596 // with some sort of list. OTOH, it seems that GCC is always 11597 // conservative with the last element in structs (if it's an array), so our 11598 // current behavior is more compatible than an explicit list approach would 11599 // be. 11600 return LVal.InvalidBase && 11601 Designator.Entries.size() == Designator.MostDerivedPathLength && 11602 Designator.MostDerivedIsArrayElement && 11603 isDesignatorAtObjectEnd(Ctx, LVal); 11604 } 11605 11606 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11607 /// Fails if the conversion would cause loss of precision. 11608 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11609 CharUnits &Result) { 11610 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11611 if (Int.ugt(CharUnitsMax)) 11612 return false; 11613 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11614 return true; 11615 } 11616 11617 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11618 /// determine how many bytes exist from the beginning of the object to either 11619 /// the end of the current subobject, or the end of the object itself, depending 11620 /// on what the LValue looks like + the value of Type. 11621 /// 11622 /// If this returns false, the value of Result is undefined. 11623 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11624 unsigned Type, const LValue &LVal, 11625 CharUnits &EndOffset) { 11626 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11627 11628 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11629 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11630 return false; 11631 return HandleSizeof(Info, ExprLoc, Ty, Result); 11632 }; 11633 11634 // We want to evaluate the size of the entire object. This is a valid fallback 11635 // for when Type=1 and the designator is invalid, because we're asked for an 11636 // upper-bound. 11637 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11638 // Type=3 wants a lower bound, so we can't fall back to this. 11639 if (Type == 3 && !DetermineForCompleteObject) 11640 return false; 11641 11642 llvm::APInt APEndOffset; 11643 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11644 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11645 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11646 11647 if (LVal.InvalidBase) 11648 return false; 11649 11650 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11651 return CheckedHandleSizeof(BaseTy, EndOffset); 11652 } 11653 11654 // We want to evaluate the size of a subobject. 11655 const SubobjectDesignator &Designator = LVal.Designator; 11656 11657 // The following is a moderately common idiom in C: 11658 // 11659 // struct Foo { int a; char c[1]; }; 11660 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11661 // strcpy(&F->c[0], Bar); 11662 // 11663 // In order to not break too much legacy code, we need to support it. 11664 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11665 // If we can resolve this to an alloc_size call, we can hand that back, 11666 // because we know for certain how many bytes there are to write to. 11667 llvm::APInt APEndOffset; 11668 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11669 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11670 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11671 11672 // If we cannot determine the size of the initial allocation, then we can't 11673 // given an accurate upper-bound. However, we are still able to give 11674 // conservative lower-bounds for Type=3. 11675 if (Type == 1) 11676 return false; 11677 } 11678 11679 CharUnits BytesPerElem; 11680 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11681 return false; 11682 11683 // According to the GCC documentation, we want the size of the subobject 11684 // denoted by the pointer. But that's not quite right -- what we actually 11685 // want is the size of the immediately-enclosing array, if there is one. 11686 int64_t ElemsRemaining; 11687 if (Designator.MostDerivedIsArrayElement && 11688 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11689 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11690 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11691 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11692 } else { 11693 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11694 } 11695 11696 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11697 return true; 11698 } 11699 11700 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11701 /// returns true and stores the result in @p Size. 11702 /// 11703 /// If @p WasError is non-null, this will report whether the failure to evaluate 11704 /// is to be treated as an Error in IntExprEvaluator. 11705 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11706 EvalInfo &Info, uint64_t &Size) { 11707 // Determine the denoted object. 11708 LValue LVal; 11709 { 11710 // The operand of __builtin_object_size is never evaluated for side-effects. 11711 // If there are any, but we can determine the pointed-to object anyway, then 11712 // ignore the side-effects. 11713 SpeculativeEvaluationRAII SpeculativeEval(Info); 11714 IgnoreSideEffectsRAII Fold(Info); 11715 11716 if (E->isGLValue()) { 11717 // It's possible for us to be given GLValues if we're called via 11718 // Expr::tryEvaluateObjectSize. 11719 APValue RVal; 11720 if (!EvaluateAsRValue(Info, E, RVal)) 11721 return false; 11722 LVal.setFrom(Info.Ctx, RVal); 11723 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11724 /*InvalidBaseOK=*/true)) 11725 return false; 11726 } 11727 11728 // If we point to before the start of the object, there are no accessible 11729 // bytes. 11730 if (LVal.getLValueOffset().isNegative()) { 11731 Size = 0; 11732 return true; 11733 } 11734 11735 CharUnits EndOffset; 11736 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11737 return false; 11738 11739 // If we've fallen outside of the end offset, just pretend there's nothing to 11740 // write to/read from. 11741 if (EndOffset <= LVal.getLValueOffset()) 11742 Size = 0; 11743 else 11744 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11745 return true; 11746 } 11747 11748 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11749 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11750 return VisitBuiltinCallExpr(E, BuiltinOp); 11751 11752 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11753 } 11754 11755 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11756 APValue &Val, APSInt &Alignment) { 11757 QualType SrcTy = E->getArg(0)->getType(); 11758 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11759 return false; 11760 // Even though we are evaluating integer expressions we could get a pointer 11761 // argument for the __builtin_is_aligned() case. 11762 if (SrcTy->isPointerType()) { 11763 LValue Ptr; 11764 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11765 return false; 11766 Ptr.moveInto(Val); 11767 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11768 Info.FFDiag(E->getArg(0)); 11769 return false; 11770 } else { 11771 APSInt SrcInt; 11772 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11773 return false; 11774 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11775 "Bit widths must be the same"); 11776 Val = APValue(SrcInt); 11777 } 11778 assert(Val.hasValue()); 11779 return true; 11780 } 11781 11782 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11783 unsigned BuiltinOp) { 11784 switch (BuiltinOp) { 11785 default: 11786 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11787 11788 case Builtin::BI__builtin_dynamic_object_size: 11789 case Builtin::BI__builtin_object_size: { 11790 // The type was checked when we built the expression. 11791 unsigned Type = 11792 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11793 assert(Type <= 3 && "unexpected type"); 11794 11795 uint64_t Size; 11796 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11797 return Success(Size, E); 11798 11799 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11800 return Success((Type & 2) ? 0 : -1, E); 11801 11802 // Expression had no side effects, but we couldn't statically determine the 11803 // size of the referenced object. 11804 switch (Info.EvalMode) { 11805 case EvalInfo::EM_ConstantExpression: 11806 case EvalInfo::EM_ConstantFold: 11807 case EvalInfo::EM_IgnoreSideEffects: 11808 // Leave it to IR generation. 11809 return Error(E); 11810 case EvalInfo::EM_ConstantExpressionUnevaluated: 11811 // Reduce it to a constant now. 11812 return Success((Type & 2) ? 0 : -1, E); 11813 } 11814 11815 llvm_unreachable("unexpected EvalMode"); 11816 } 11817 11818 case Builtin::BI__builtin_os_log_format_buffer_size: { 11819 analyze_os_log::OSLogBufferLayout Layout; 11820 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11821 return Success(Layout.size().getQuantity(), E); 11822 } 11823 11824 case Builtin::BI__builtin_is_aligned: { 11825 APValue Src; 11826 APSInt Alignment; 11827 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11828 return false; 11829 if (Src.isLValue()) { 11830 // If we evaluated a pointer, check the minimum known alignment. 11831 LValue Ptr; 11832 Ptr.setFrom(Info.Ctx, Src); 11833 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11834 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11835 // We can return true if the known alignment at the computed offset is 11836 // greater than the requested alignment. 11837 assert(PtrAlign.isPowerOfTwo()); 11838 assert(Alignment.isPowerOf2()); 11839 if (PtrAlign.getQuantity() >= Alignment) 11840 return Success(1, E); 11841 // If the alignment is not known to be sufficient, some cases could still 11842 // be aligned at run time. However, if the requested alignment is less or 11843 // equal to the base alignment and the offset is not aligned, we know that 11844 // the run-time value can never be aligned. 11845 if (BaseAlignment.getQuantity() >= Alignment && 11846 PtrAlign.getQuantity() < Alignment) 11847 return Success(0, E); 11848 // Otherwise we can't infer whether the value is sufficiently aligned. 11849 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11850 // in cases where we can't fully evaluate the pointer. 11851 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11852 << Alignment; 11853 return false; 11854 } 11855 assert(Src.isInt()); 11856 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11857 } 11858 case Builtin::BI__builtin_align_up: { 11859 APValue Src; 11860 APSInt Alignment; 11861 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11862 return false; 11863 if (!Src.isInt()) 11864 return Error(E); 11865 APSInt AlignedVal = 11866 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11867 Src.getInt().isUnsigned()); 11868 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11869 return Success(AlignedVal, E); 11870 } 11871 case Builtin::BI__builtin_align_down: { 11872 APValue Src; 11873 APSInt Alignment; 11874 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11875 return false; 11876 if (!Src.isInt()) 11877 return Error(E); 11878 APSInt AlignedVal = 11879 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11880 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11881 return Success(AlignedVal, E); 11882 } 11883 11884 case Builtin::BI__builtin_bitreverse8: 11885 case Builtin::BI__builtin_bitreverse16: 11886 case Builtin::BI__builtin_bitreverse32: 11887 case Builtin::BI__builtin_bitreverse64: { 11888 APSInt Val; 11889 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11890 return false; 11891 11892 return Success(Val.reverseBits(), E); 11893 } 11894 11895 case Builtin::BI__builtin_bswap16: 11896 case Builtin::BI__builtin_bswap32: 11897 case Builtin::BI__builtin_bswap64: { 11898 APSInt Val; 11899 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11900 return false; 11901 11902 return Success(Val.byteSwap(), E); 11903 } 11904 11905 case Builtin::BI__builtin_classify_type: 11906 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11907 11908 case Builtin::BI__builtin_clrsb: 11909 case Builtin::BI__builtin_clrsbl: 11910 case Builtin::BI__builtin_clrsbll: { 11911 APSInt Val; 11912 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11913 return false; 11914 11915 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11916 } 11917 11918 case Builtin::BI__builtin_clz: 11919 case Builtin::BI__builtin_clzl: 11920 case Builtin::BI__builtin_clzll: 11921 case Builtin::BI__builtin_clzs: { 11922 APSInt Val; 11923 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11924 return false; 11925 if (!Val) 11926 return Error(E); 11927 11928 return Success(Val.countLeadingZeros(), E); 11929 } 11930 11931 case Builtin::BI__builtin_constant_p: { 11932 const Expr *Arg = E->getArg(0); 11933 if (EvaluateBuiltinConstantP(Info, Arg)) 11934 return Success(true, E); 11935 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11936 // Outside a constant context, eagerly evaluate to false in the presence 11937 // of side-effects in order to avoid -Wunsequenced false-positives in 11938 // a branch on __builtin_constant_p(expr). 11939 return Success(false, E); 11940 } 11941 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11942 return false; 11943 } 11944 11945 case Builtin::BI__builtin_is_constant_evaluated: { 11946 const auto *Callee = Info.CurrentCall->getCallee(); 11947 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11948 (Info.CallStackDepth == 1 || 11949 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11950 Callee->getIdentifier() && 11951 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11952 // FIXME: Find a better way to avoid duplicated diagnostics. 11953 if (Info.EvalStatus.Diag) 11954 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11955 : Info.CurrentCall->CallLoc, 11956 diag::warn_is_constant_evaluated_always_true_constexpr) 11957 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11958 : "std::is_constant_evaluated"); 11959 } 11960 11961 return Success(Info.InConstantContext, E); 11962 } 11963 11964 case Builtin::BI__builtin_ctz: 11965 case Builtin::BI__builtin_ctzl: 11966 case Builtin::BI__builtin_ctzll: 11967 case Builtin::BI__builtin_ctzs: { 11968 APSInt Val; 11969 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11970 return false; 11971 if (!Val) 11972 return Error(E); 11973 11974 return Success(Val.countTrailingZeros(), E); 11975 } 11976 11977 case Builtin::BI__builtin_eh_return_data_regno: { 11978 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11979 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11980 return Success(Operand, E); 11981 } 11982 11983 case Builtin::BI__builtin_expect: 11984 case Builtin::BI__builtin_expect_with_probability: 11985 return Visit(E->getArg(0)); 11986 11987 case Builtin::BI__builtin_ffs: 11988 case Builtin::BI__builtin_ffsl: 11989 case Builtin::BI__builtin_ffsll: { 11990 APSInt Val; 11991 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11992 return false; 11993 11994 unsigned N = Val.countTrailingZeros(); 11995 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11996 } 11997 11998 case Builtin::BI__builtin_fpclassify: { 11999 APFloat Val(0.0); 12000 if (!EvaluateFloat(E->getArg(5), Val, Info)) 12001 return false; 12002 unsigned Arg; 12003 switch (Val.getCategory()) { 12004 case APFloat::fcNaN: Arg = 0; break; 12005 case APFloat::fcInfinity: Arg = 1; break; 12006 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 12007 case APFloat::fcZero: Arg = 4; break; 12008 } 12009 return Visit(E->getArg(Arg)); 12010 } 12011 12012 case Builtin::BI__builtin_isinf_sign: { 12013 APFloat Val(0.0); 12014 return EvaluateFloat(E->getArg(0), Val, Info) && 12015 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 12016 } 12017 12018 case Builtin::BI__builtin_isinf: { 12019 APFloat Val(0.0); 12020 return EvaluateFloat(E->getArg(0), Val, Info) && 12021 Success(Val.isInfinity() ? 1 : 0, E); 12022 } 12023 12024 case Builtin::BI__builtin_isfinite: { 12025 APFloat Val(0.0); 12026 return EvaluateFloat(E->getArg(0), Val, Info) && 12027 Success(Val.isFinite() ? 1 : 0, E); 12028 } 12029 12030 case Builtin::BI__builtin_isnan: { 12031 APFloat Val(0.0); 12032 return EvaluateFloat(E->getArg(0), Val, Info) && 12033 Success(Val.isNaN() ? 1 : 0, E); 12034 } 12035 12036 case Builtin::BI__builtin_isnormal: { 12037 APFloat Val(0.0); 12038 return EvaluateFloat(E->getArg(0), Val, Info) && 12039 Success(Val.isNormal() ? 1 : 0, E); 12040 } 12041 12042 case Builtin::BI__builtin_parity: 12043 case Builtin::BI__builtin_parityl: 12044 case Builtin::BI__builtin_parityll: { 12045 APSInt Val; 12046 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12047 return false; 12048 12049 return Success(Val.countPopulation() % 2, E); 12050 } 12051 12052 case Builtin::BI__builtin_popcount: 12053 case Builtin::BI__builtin_popcountl: 12054 case Builtin::BI__builtin_popcountll: { 12055 APSInt Val; 12056 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12057 return false; 12058 12059 return Success(Val.countPopulation(), E); 12060 } 12061 12062 case Builtin::BI__builtin_rotateleft8: 12063 case Builtin::BI__builtin_rotateleft16: 12064 case Builtin::BI__builtin_rotateleft32: 12065 case Builtin::BI__builtin_rotateleft64: 12066 case Builtin::BI_rotl8: // Microsoft variants of rotate right 12067 case Builtin::BI_rotl16: 12068 case Builtin::BI_rotl: 12069 case Builtin::BI_lrotl: 12070 case Builtin::BI_rotl64: { 12071 APSInt Val, Amt; 12072 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12073 !EvaluateInteger(E->getArg(1), Amt, Info)) 12074 return false; 12075 12076 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 12077 } 12078 12079 case Builtin::BI__builtin_rotateright8: 12080 case Builtin::BI__builtin_rotateright16: 12081 case Builtin::BI__builtin_rotateright32: 12082 case Builtin::BI__builtin_rotateright64: 12083 case Builtin::BI_rotr8: // Microsoft variants of rotate right 12084 case Builtin::BI_rotr16: 12085 case Builtin::BI_rotr: 12086 case Builtin::BI_lrotr: 12087 case Builtin::BI_rotr64: { 12088 APSInt Val, Amt; 12089 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12090 !EvaluateInteger(E->getArg(1), Amt, Info)) 12091 return false; 12092 12093 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 12094 } 12095 12096 case Builtin::BIstrlen: 12097 case Builtin::BIwcslen: 12098 // A call to strlen is not a constant expression. 12099 if (Info.getLangOpts().CPlusPlus11) 12100 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12101 << /*isConstexpr*/0 << /*isConstructor*/0 12102 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 12103 else 12104 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12105 LLVM_FALLTHROUGH; 12106 case Builtin::BI__builtin_strlen: 12107 case Builtin::BI__builtin_wcslen: { 12108 // As an extension, we support __builtin_strlen() as a constant expression, 12109 // and support folding strlen() to a constant. 12110 uint64_t StrLen; 12111 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 12112 return Success(StrLen, E); 12113 return false; 12114 } 12115 12116 case Builtin::BIstrcmp: 12117 case Builtin::BIwcscmp: 12118 case Builtin::BIstrncmp: 12119 case Builtin::BIwcsncmp: 12120 case Builtin::BImemcmp: 12121 case Builtin::BIbcmp: 12122 case Builtin::BIwmemcmp: 12123 // A call to strlen is not a constant expression. 12124 if (Info.getLangOpts().CPlusPlus11) 12125 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12126 << /*isConstexpr*/0 << /*isConstructor*/0 12127 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 12128 else 12129 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12130 LLVM_FALLTHROUGH; 12131 case Builtin::BI__builtin_strcmp: 12132 case Builtin::BI__builtin_wcscmp: 12133 case Builtin::BI__builtin_strncmp: 12134 case Builtin::BI__builtin_wcsncmp: 12135 case Builtin::BI__builtin_memcmp: 12136 case Builtin::BI__builtin_bcmp: 12137 case Builtin::BI__builtin_wmemcmp: { 12138 LValue String1, String2; 12139 if (!EvaluatePointer(E->getArg(0), String1, Info) || 12140 !EvaluatePointer(E->getArg(1), String2, Info)) 12141 return false; 12142 12143 uint64_t MaxLength = uint64_t(-1); 12144 if (BuiltinOp != Builtin::BIstrcmp && 12145 BuiltinOp != Builtin::BIwcscmp && 12146 BuiltinOp != Builtin::BI__builtin_strcmp && 12147 BuiltinOp != Builtin::BI__builtin_wcscmp) { 12148 APSInt N; 12149 if (!EvaluateInteger(E->getArg(2), N, Info)) 12150 return false; 12151 MaxLength = N.getExtValue(); 12152 } 12153 12154 // Empty substrings compare equal by definition. 12155 if (MaxLength == 0u) 12156 return Success(0, E); 12157 12158 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12159 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12160 String1.Designator.Invalid || String2.Designator.Invalid) 12161 return false; 12162 12163 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 12164 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 12165 12166 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 12167 BuiltinOp == Builtin::BIbcmp || 12168 BuiltinOp == Builtin::BI__builtin_memcmp || 12169 BuiltinOp == Builtin::BI__builtin_bcmp; 12170 12171 assert(IsRawByte || 12172 (Info.Ctx.hasSameUnqualifiedType( 12173 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 12174 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 12175 12176 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 12177 // 'char8_t', but no other types. 12178 if (IsRawByte && 12179 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 12180 // FIXME: Consider using our bit_cast implementation to support this. 12181 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 12182 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 12183 << CharTy1 << CharTy2; 12184 return false; 12185 } 12186 12187 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 12188 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 12189 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 12190 Char1.isInt() && Char2.isInt(); 12191 }; 12192 const auto &AdvanceElems = [&] { 12193 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 12194 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 12195 }; 12196 12197 bool StopAtNull = 12198 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 12199 BuiltinOp != Builtin::BIwmemcmp && 12200 BuiltinOp != Builtin::BI__builtin_memcmp && 12201 BuiltinOp != Builtin::BI__builtin_bcmp && 12202 BuiltinOp != Builtin::BI__builtin_wmemcmp); 12203 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 12204 BuiltinOp == Builtin::BIwcsncmp || 12205 BuiltinOp == Builtin::BIwmemcmp || 12206 BuiltinOp == Builtin::BI__builtin_wcscmp || 12207 BuiltinOp == Builtin::BI__builtin_wcsncmp || 12208 BuiltinOp == Builtin::BI__builtin_wmemcmp; 12209 12210 for (; MaxLength; --MaxLength) { 12211 APValue Char1, Char2; 12212 if (!ReadCurElems(Char1, Char2)) 12213 return false; 12214 if (Char1.getInt().ne(Char2.getInt())) { 12215 if (IsWide) // wmemcmp compares with wchar_t signedness. 12216 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 12217 // memcmp always compares unsigned chars. 12218 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 12219 } 12220 if (StopAtNull && !Char1.getInt()) 12221 return Success(0, E); 12222 assert(!(StopAtNull && !Char2.getInt())); 12223 if (!AdvanceElems()) 12224 return false; 12225 } 12226 // We hit the strncmp / memcmp limit. 12227 return Success(0, E); 12228 } 12229 12230 case Builtin::BI__atomic_always_lock_free: 12231 case Builtin::BI__atomic_is_lock_free: 12232 case Builtin::BI__c11_atomic_is_lock_free: { 12233 APSInt SizeVal; 12234 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 12235 return false; 12236 12237 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12238 // of two less than or equal to the maximum inline atomic width, we know it 12239 // is lock-free. If the size isn't a power of two, or greater than the 12240 // maximum alignment where we promote atomics, we know it is not lock-free 12241 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12242 // the answer can only be determined at runtime; for example, 16-byte 12243 // atomics have lock-free implementations on some, but not all, 12244 // x86-64 processors. 12245 12246 // Check power-of-two. 12247 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12248 if (Size.isPowerOfTwo()) { 12249 // Check against inlining width. 12250 unsigned InlineWidthBits = 12251 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12252 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12253 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12254 Size == CharUnits::One() || 12255 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12256 Expr::NPC_NeverValueDependent)) 12257 // OK, we will inline appropriately-aligned operations of this size, 12258 // and _Atomic(T) is appropriately-aligned. 12259 return Success(1, E); 12260 12261 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12262 castAs<PointerType>()->getPointeeType(); 12263 if (!PointeeType->isIncompleteType() && 12264 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12265 // OK, we will inline operations on this object. 12266 return Success(1, E); 12267 } 12268 } 12269 } 12270 12271 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12272 Success(0, E) : Error(E); 12273 } 12274 case Builtin::BI__builtin_add_overflow: 12275 case Builtin::BI__builtin_sub_overflow: 12276 case Builtin::BI__builtin_mul_overflow: 12277 case Builtin::BI__builtin_sadd_overflow: 12278 case Builtin::BI__builtin_uadd_overflow: 12279 case Builtin::BI__builtin_uaddl_overflow: 12280 case Builtin::BI__builtin_uaddll_overflow: 12281 case Builtin::BI__builtin_usub_overflow: 12282 case Builtin::BI__builtin_usubl_overflow: 12283 case Builtin::BI__builtin_usubll_overflow: 12284 case Builtin::BI__builtin_umul_overflow: 12285 case Builtin::BI__builtin_umull_overflow: 12286 case Builtin::BI__builtin_umulll_overflow: 12287 case Builtin::BI__builtin_saddl_overflow: 12288 case Builtin::BI__builtin_saddll_overflow: 12289 case Builtin::BI__builtin_ssub_overflow: 12290 case Builtin::BI__builtin_ssubl_overflow: 12291 case Builtin::BI__builtin_ssubll_overflow: 12292 case Builtin::BI__builtin_smul_overflow: 12293 case Builtin::BI__builtin_smull_overflow: 12294 case Builtin::BI__builtin_smulll_overflow: { 12295 LValue ResultLValue; 12296 APSInt LHS, RHS; 12297 12298 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12299 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12300 !EvaluateInteger(E->getArg(1), RHS, Info) || 12301 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12302 return false; 12303 12304 APSInt Result; 12305 bool DidOverflow = false; 12306 12307 // If the types don't have to match, enlarge all 3 to the largest of them. 12308 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12309 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12310 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12311 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12312 ResultType->isSignedIntegerOrEnumerationType(); 12313 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12314 ResultType->isSignedIntegerOrEnumerationType(); 12315 uint64_t LHSSize = LHS.getBitWidth(); 12316 uint64_t RHSSize = RHS.getBitWidth(); 12317 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12318 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12319 12320 // Add an additional bit if the signedness isn't uniformly agreed to. We 12321 // could do this ONLY if there is a signed and an unsigned that both have 12322 // MaxBits, but the code to check that is pretty nasty. The issue will be 12323 // caught in the shrink-to-result later anyway. 12324 if (IsSigned && !AllSigned) 12325 ++MaxBits; 12326 12327 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12328 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12329 Result = APSInt(MaxBits, !IsSigned); 12330 } 12331 12332 // Find largest int. 12333 switch (BuiltinOp) { 12334 default: 12335 llvm_unreachable("Invalid value for BuiltinOp"); 12336 case Builtin::BI__builtin_add_overflow: 12337 case Builtin::BI__builtin_sadd_overflow: 12338 case Builtin::BI__builtin_saddl_overflow: 12339 case Builtin::BI__builtin_saddll_overflow: 12340 case Builtin::BI__builtin_uadd_overflow: 12341 case Builtin::BI__builtin_uaddl_overflow: 12342 case Builtin::BI__builtin_uaddll_overflow: 12343 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12344 : LHS.uadd_ov(RHS, DidOverflow); 12345 break; 12346 case Builtin::BI__builtin_sub_overflow: 12347 case Builtin::BI__builtin_ssub_overflow: 12348 case Builtin::BI__builtin_ssubl_overflow: 12349 case Builtin::BI__builtin_ssubll_overflow: 12350 case Builtin::BI__builtin_usub_overflow: 12351 case Builtin::BI__builtin_usubl_overflow: 12352 case Builtin::BI__builtin_usubll_overflow: 12353 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12354 : LHS.usub_ov(RHS, DidOverflow); 12355 break; 12356 case Builtin::BI__builtin_mul_overflow: 12357 case Builtin::BI__builtin_smul_overflow: 12358 case Builtin::BI__builtin_smull_overflow: 12359 case Builtin::BI__builtin_smulll_overflow: 12360 case Builtin::BI__builtin_umul_overflow: 12361 case Builtin::BI__builtin_umull_overflow: 12362 case Builtin::BI__builtin_umulll_overflow: 12363 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12364 : LHS.umul_ov(RHS, DidOverflow); 12365 break; 12366 } 12367 12368 // In the case where multiple sizes are allowed, truncate and see if 12369 // the values are the same. 12370 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12371 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12372 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12373 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12374 // since it will give us the behavior of a TruncOrSelf in the case where 12375 // its parameter <= its size. We previously set Result to be at least the 12376 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12377 // will work exactly like TruncOrSelf. 12378 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12379 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12380 12381 if (!APSInt::isSameValue(Temp, Result)) 12382 DidOverflow = true; 12383 Result = Temp; 12384 } 12385 12386 APValue APV{Result}; 12387 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12388 return false; 12389 return Success(DidOverflow, E); 12390 } 12391 } 12392 } 12393 12394 /// Determine whether this is a pointer past the end of the complete 12395 /// object referred to by the lvalue. 12396 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12397 const LValue &LV) { 12398 // A null pointer can be viewed as being "past the end" but we don't 12399 // choose to look at it that way here. 12400 if (!LV.getLValueBase()) 12401 return false; 12402 12403 // If the designator is valid and refers to a subobject, we're not pointing 12404 // past the end. 12405 if (!LV.getLValueDesignator().Invalid && 12406 !LV.getLValueDesignator().isOnePastTheEnd()) 12407 return false; 12408 12409 // A pointer to an incomplete type might be past-the-end if the type's size is 12410 // zero. We cannot tell because the type is incomplete. 12411 QualType Ty = getType(LV.getLValueBase()); 12412 if (Ty->isIncompleteType()) 12413 return true; 12414 12415 // We're a past-the-end pointer if we point to the byte after the object, 12416 // no matter what our type or path is. 12417 auto Size = Ctx.getTypeSizeInChars(Ty); 12418 return LV.getLValueOffset() == Size; 12419 } 12420 12421 namespace { 12422 12423 /// Data recursive integer evaluator of certain binary operators. 12424 /// 12425 /// We use a data recursive algorithm for binary operators so that we are able 12426 /// to handle extreme cases of chained binary operators without causing stack 12427 /// overflow. 12428 class DataRecursiveIntBinOpEvaluator { 12429 struct EvalResult { 12430 APValue Val; 12431 bool Failed; 12432 12433 EvalResult() : Failed(false) { } 12434 12435 void swap(EvalResult &RHS) { 12436 Val.swap(RHS.Val); 12437 Failed = RHS.Failed; 12438 RHS.Failed = false; 12439 } 12440 }; 12441 12442 struct Job { 12443 const Expr *E; 12444 EvalResult LHSResult; // meaningful only for binary operator expression. 12445 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12446 12447 Job() = default; 12448 Job(Job &&) = default; 12449 12450 void startSpeculativeEval(EvalInfo &Info) { 12451 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12452 } 12453 12454 private: 12455 SpeculativeEvaluationRAII SpecEvalRAII; 12456 }; 12457 12458 SmallVector<Job, 16> Queue; 12459 12460 IntExprEvaluator &IntEval; 12461 EvalInfo &Info; 12462 APValue &FinalResult; 12463 12464 public: 12465 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12466 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12467 12468 /// True if \param E is a binary operator that we are going to handle 12469 /// data recursively. 12470 /// We handle binary operators that are comma, logical, or that have operands 12471 /// with integral or enumeration type. 12472 static bool shouldEnqueue(const BinaryOperator *E) { 12473 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12474 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12475 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12476 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12477 } 12478 12479 bool Traverse(const BinaryOperator *E) { 12480 enqueue(E); 12481 EvalResult PrevResult; 12482 while (!Queue.empty()) 12483 process(PrevResult); 12484 12485 if (PrevResult.Failed) return false; 12486 12487 FinalResult.swap(PrevResult.Val); 12488 return true; 12489 } 12490 12491 private: 12492 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12493 return IntEval.Success(Value, E, Result); 12494 } 12495 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12496 return IntEval.Success(Value, E, Result); 12497 } 12498 bool Error(const Expr *E) { 12499 return IntEval.Error(E); 12500 } 12501 bool Error(const Expr *E, diag::kind D) { 12502 return IntEval.Error(E, D); 12503 } 12504 12505 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12506 return Info.CCEDiag(E, D); 12507 } 12508 12509 // Returns true if visiting the RHS is necessary, false otherwise. 12510 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12511 bool &SuppressRHSDiags); 12512 12513 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12514 const BinaryOperator *E, APValue &Result); 12515 12516 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12517 Result.Failed = !Evaluate(Result.Val, Info, E); 12518 if (Result.Failed) 12519 Result.Val = APValue(); 12520 } 12521 12522 void process(EvalResult &Result); 12523 12524 void enqueue(const Expr *E) { 12525 E = E->IgnoreParens(); 12526 Queue.resize(Queue.size()+1); 12527 Queue.back().E = E; 12528 Queue.back().Kind = Job::AnyExprKind; 12529 } 12530 }; 12531 12532 } 12533 12534 bool DataRecursiveIntBinOpEvaluator:: 12535 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12536 bool &SuppressRHSDiags) { 12537 if (E->getOpcode() == BO_Comma) { 12538 // Ignore LHS but note if we could not evaluate it. 12539 if (LHSResult.Failed) 12540 return Info.noteSideEffect(); 12541 return true; 12542 } 12543 12544 if (E->isLogicalOp()) { 12545 bool LHSAsBool; 12546 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12547 // We were able to evaluate the LHS, see if we can get away with not 12548 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12549 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12550 Success(LHSAsBool, E, LHSResult.Val); 12551 return false; // Ignore RHS 12552 } 12553 } else { 12554 LHSResult.Failed = true; 12555 12556 // Since we weren't able to evaluate the left hand side, it 12557 // might have had side effects. 12558 if (!Info.noteSideEffect()) 12559 return false; 12560 12561 // We can't evaluate the LHS; however, sometimes the result 12562 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12563 // Don't ignore RHS and suppress diagnostics from this arm. 12564 SuppressRHSDiags = true; 12565 } 12566 12567 return true; 12568 } 12569 12570 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12571 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12572 12573 if (LHSResult.Failed && !Info.noteFailure()) 12574 return false; // Ignore RHS; 12575 12576 return true; 12577 } 12578 12579 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12580 bool IsSub) { 12581 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12582 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12583 // offsets. 12584 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12585 CharUnits &Offset = LVal.getLValueOffset(); 12586 uint64_t Offset64 = Offset.getQuantity(); 12587 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12588 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12589 : Offset64 + Index64); 12590 } 12591 12592 bool DataRecursiveIntBinOpEvaluator:: 12593 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12594 const BinaryOperator *E, APValue &Result) { 12595 if (E->getOpcode() == BO_Comma) { 12596 if (RHSResult.Failed) 12597 return false; 12598 Result = RHSResult.Val; 12599 return true; 12600 } 12601 12602 if (E->isLogicalOp()) { 12603 bool lhsResult, rhsResult; 12604 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12605 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12606 12607 if (LHSIsOK) { 12608 if (RHSIsOK) { 12609 if (E->getOpcode() == BO_LOr) 12610 return Success(lhsResult || rhsResult, E, Result); 12611 else 12612 return Success(lhsResult && rhsResult, E, Result); 12613 } 12614 } else { 12615 if (RHSIsOK) { 12616 // We can't evaluate the LHS; however, sometimes the result 12617 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12618 if (rhsResult == (E->getOpcode() == BO_LOr)) 12619 return Success(rhsResult, E, Result); 12620 } 12621 } 12622 12623 return false; 12624 } 12625 12626 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12627 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12628 12629 if (LHSResult.Failed || RHSResult.Failed) 12630 return false; 12631 12632 const APValue &LHSVal = LHSResult.Val; 12633 const APValue &RHSVal = RHSResult.Val; 12634 12635 // Handle cases like (unsigned long)&a + 4. 12636 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12637 Result = LHSVal; 12638 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12639 return true; 12640 } 12641 12642 // Handle cases like 4 + (unsigned long)&a 12643 if (E->getOpcode() == BO_Add && 12644 RHSVal.isLValue() && LHSVal.isInt()) { 12645 Result = RHSVal; 12646 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12647 return true; 12648 } 12649 12650 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12651 // Handle (intptr_t)&&A - (intptr_t)&&B. 12652 if (!LHSVal.getLValueOffset().isZero() || 12653 !RHSVal.getLValueOffset().isZero()) 12654 return false; 12655 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12656 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12657 if (!LHSExpr || !RHSExpr) 12658 return false; 12659 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12660 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12661 if (!LHSAddrExpr || !RHSAddrExpr) 12662 return false; 12663 // Make sure both labels come from the same function. 12664 if (LHSAddrExpr->getLabel()->getDeclContext() != 12665 RHSAddrExpr->getLabel()->getDeclContext()) 12666 return false; 12667 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12668 return true; 12669 } 12670 12671 // All the remaining cases expect both operands to be an integer 12672 if (!LHSVal.isInt() || !RHSVal.isInt()) 12673 return Error(E); 12674 12675 // Set up the width and signedness manually, in case it can't be deduced 12676 // from the operation we're performing. 12677 // FIXME: Don't do this in the cases where we can deduce it. 12678 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12679 E->getType()->isUnsignedIntegerOrEnumerationType()); 12680 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12681 RHSVal.getInt(), Value)) 12682 return false; 12683 return Success(Value, E, Result); 12684 } 12685 12686 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12687 Job &job = Queue.back(); 12688 12689 switch (job.Kind) { 12690 case Job::AnyExprKind: { 12691 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12692 if (shouldEnqueue(Bop)) { 12693 job.Kind = Job::BinOpKind; 12694 enqueue(Bop->getLHS()); 12695 return; 12696 } 12697 } 12698 12699 EvaluateExpr(job.E, Result); 12700 Queue.pop_back(); 12701 return; 12702 } 12703 12704 case Job::BinOpKind: { 12705 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12706 bool SuppressRHSDiags = false; 12707 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12708 Queue.pop_back(); 12709 return; 12710 } 12711 if (SuppressRHSDiags) 12712 job.startSpeculativeEval(Info); 12713 job.LHSResult.swap(Result); 12714 job.Kind = Job::BinOpVisitedLHSKind; 12715 enqueue(Bop->getRHS()); 12716 return; 12717 } 12718 12719 case Job::BinOpVisitedLHSKind: { 12720 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12721 EvalResult RHS; 12722 RHS.swap(Result); 12723 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12724 Queue.pop_back(); 12725 return; 12726 } 12727 } 12728 12729 llvm_unreachable("Invalid Job::Kind!"); 12730 } 12731 12732 namespace { 12733 enum class CmpResult { 12734 Unequal, 12735 Less, 12736 Equal, 12737 Greater, 12738 Unordered, 12739 }; 12740 } 12741 12742 template <class SuccessCB, class AfterCB> 12743 static bool 12744 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12745 SuccessCB &&Success, AfterCB &&DoAfter) { 12746 assert(!E->isValueDependent()); 12747 assert(E->isComparisonOp() && "expected comparison operator"); 12748 assert((E->getOpcode() == BO_Cmp || 12749 E->getType()->isIntegralOrEnumerationType()) && 12750 "unsupported binary expression evaluation"); 12751 auto Error = [&](const Expr *E) { 12752 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12753 return false; 12754 }; 12755 12756 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12757 bool IsEquality = E->isEqualityOp(); 12758 12759 QualType LHSTy = E->getLHS()->getType(); 12760 QualType RHSTy = E->getRHS()->getType(); 12761 12762 if (LHSTy->isIntegralOrEnumerationType() && 12763 RHSTy->isIntegralOrEnumerationType()) { 12764 APSInt LHS, RHS; 12765 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12766 if (!LHSOK && !Info.noteFailure()) 12767 return false; 12768 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12769 return false; 12770 if (LHS < RHS) 12771 return Success(CmpResult::Less, E); 12772 if (LHS > RHS) 12773 return Success(CmpResult::Greater, E); 12774 return Success(CmpResult::Equal, E); 12775 } 12776 12777 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12778 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12779 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12780 12781 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12782 if (!LHSOK && !Info.noteFailure()) 12783 return false; 12784 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12785 return false; 12786 if (LHSFX < RHSFX) 12787 return Success(CmpResult::Less, E); 12788 if (LHSFX > RHSFX) 12789 return Success(CmpResult::Greater, E); 12790 return Success(CmpResult::Equal, E); 12791 } 12792 12793 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12794 ComplexValue LHS, RHS; 12795 bool LHSOK; 12796 if (E->isAssignmentOp()) { 12797 LValue LV; 12798 EvaluateLValue(E->getLHS(), LV, Info); 12799 LHSOK = false; 12800 } else if (LHSTy->isRealFloatingType()) { 12801 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12802 if (LHSOK) { 12803 LHS.makeComplexFloat(); 12804 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12805 } 12806 } else { 12807 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12808 } 12809 if (!LHSOK && !Info.noteFailure()) 12810 return false; 12811 12812 if (E->getRHS()->getType()->isRealFloatingType()) { 12813 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12814 return false; 12815 RHS.makeComplexFloat(); 12816 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12817 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12818 return false; 12819 12820 if (LHS.isComplexFloat()) { 12821 APFloat::cmpResult CR_r = 12822 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12823 APFloat::cmpResult CR_i = 12824 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12825 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12826 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12827 } else { 12828 assert(IsEquality && "invalid complex comparison"); 12829 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12830 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12831 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12832 } 12833 } 12834 12835 if (LHSTy->isRealFloatingType() && 12836 RHSTy->isRealFloatingType()) { 12837 APFloat RHS(0.0), LHS(0.0); 12838 12839 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12840 if (!LHSOK && !Info.noteFailure()) 12841 return false; 12842 12843 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12844 return false; 12845 12846 assert(E->isComparisonOp() && "Invalid binary operator!"); 12847 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12848 if (!Info.InConstantContext && 12849 APFloatCmpResult == APFloat::cmpUnordered && 12850 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12851 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12852 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12853 return false; 12854 } 12855 auto GetCmpRes = [&]() { 12856 switch (APFloatCmpResult) { 12857 case APFloat::cmpEqual: 12858 return CmpResult::Equal; 12859 case APFloat::cmpLessThan: 12860 return CmpResult::Less; 12861 case APFloat::cmpGreaterThan: 12862 return CmpResult::Greater; 12863 case APFloat::cmpUnordered: 12864 return CmpResult::Unordered; 12865 } 12866 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12867 }; 12868 return Success(GetCmpRes(), E); 12869 } 12870 12871 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12872 LValue LHSValue, RHSValue; 12873 12874 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12875 if (!LHSOK && !Info.noteFailure()) 12876 return false; 12877 12878 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12879 return false; 12880 12881 // Reject differing bases from the normal codepath; we special-case 12882 // comparisons to null. 12883 if (!HasSameBase(LHSValue, RHSValue)) { 12884 // Inequalities and subtractions between unrelated pointers have 12885 // unspecified or undefined behavior. 12886 if (!IsEquality) { 12887 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12888 return false; 12889 } 12890 // A constant address may compare equal to the address of a symbol. 12891 // The one exception is that address of an object cannot compare equal 12892 // to a null pointer constant. 12893 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12894 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12895 return Error(E); 12896 // It's implementation-defined whether distinct literals will have 12897 // distinct addresses. In clang, the result of such a comparison is 12898 // unspecified, so it is not a constant expression. However, we do know 12899 // that the address of a literal will be non-null. 12900 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12901 LHSValue.Base && RHSValue.Base) 12902 return Error(E); 12903 // We can't tell whether weak symbols will end up pointing to the same 12904 // object. 12905 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12906 return Error(E); 12907 // We can't compare the address of the start of one object with the 12908 // past-the-end address of another object, per C++ DR1652. 12909 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12910 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12911 (RHSValue.Base && RHSValue.Offset.isZero() && 12912 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12913 return Error(E); 12914 // We can't tell whether an object is at the same address as another 12915 // zero sized object. 12916 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12917 (LHSValue.Base && isZeroSized(RHSValue))) 12918 return Error(E); 12919 return Success(CmpResult::Unequal, E); 12920 } 12921 12922 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12923 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12924 12925 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12926 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12927 12928 // C++11 [expr.rel]p3: 12929 // Pointers to void (after pointer conversions) can be compared, with a 12930 // result defined as follows: If both pointers represent the same 12931 // address or are both the null pointer value, the result is true if the 12932 // operator is <= or >= and false otherwise; otherwise the result is 12933 // unspecified. 12934 // We interpret this as applying to pointers to *cv* void. 12935 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12936 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12937 12938 // C++11 [expr.rel]p2: 12939 // - If two pointers point to non-static data members of the same object, 12940 // or to subobjects or array elements fo such members, recursively, the 12941 // pointer to the later declared member compares greater provided the 12942 // two members have the same access control and provided their class is 12943 // not a union. 12944 // [...] 12945 // - Otherwise pointer comparisons are unspecified. 12946 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12947 bool WasArrayIndex; 12948 unsigned Mismatch = FindDesignatorMismatch( 12949 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12950 // At the point where the designators diverge, the comparison has a 12951 // specified value if: 12952 // - we are comparing array indices 12953 // - we are comparing fields of a union, or fields with the same access 12954 // Otherwise, the result is unspecified and thus the comparison is not a 12955 // constant expression. 12956 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12957 Mismatch < RHSDesignator.Entries.size()) { 12958 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12959 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12960 if (!LF && !RF) 12961 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12962 else if (!LF) 12963 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12964 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12965 << RF->getParent() << RF; 12966 else if (!RF) 12967 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12968 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12969 << LF->getParent() << LF; 12970 else if (!LF->getParent()->isUnion() && 12971 LF->getAccess() != RF->getAccess()) 12972 Info.CCEDiag(E, 12973 diag::note_constexpr_pointer_comparison_differing_access) 12974 << LF << LF->getAccess() << RF << RF->getAccess() 12975 << LF->getParent(); 12976 } 12977 } 12978 12979 // The comparison here must be unsigned, and performed with the same 12980 // width as the pointer. 12981 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12982 uint64_t CompareLHS = LHSOffset.getQuantity(); 12983 uint64_t CompareRHS = RHSOffset.getQuantity(); 12984 assert(PtrSize <= 64 && "Unexpected pointer width"); 12985 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12986 CompareLHS &= Mask; 12987 CompareRHS &= Mask; 12988 12989 // If there is a base and this is a relational operator, we can only 12990 // compare pointers within the object in question; otherwise, the result 12991 // depends on where the object is located in memory. 12992 if (!LHSValue.Base.isNull() && IsRelational) { 12993 QualType BaseTy = getType(LHSValue.Base); 12994 if (BaseTy->isIncompleteType()) 12995 return Error(E); 12996 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12997 uint64_t OffsetLimit = Size.getQuantity(); 12998 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12999 return Error(E); 13000 } 13001 13002 if (CompareLHS < CompareRHS) 13003 return Success(CmpResult::Less, E); 13004 if (CompareLHS > CompareRHS) 13005 return Success(CmpResult::Greater, E); 13006 return Success(CmpResult::Equal, E); 13007 } 13008 13009 if (LHSTy->isMemberPointerType()) { 13010 assert(IsEquality && "unexpected member pointer operation"); 13011 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 13012 13013 MemberPtr LHSValue, RHSValue; 13014 13015 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 13016 if (!LHSOK && !Info.noteFailure()) 13017 return false; 13018 13019 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13020 return false; 13021 13022 // C++11 [expr.eq]p2: 13023 // If both operands are null, they compare equal. Otherwise if only one is 13024 // null, they compare unequal. 13025 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 13026 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 13027 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 13028 } 13029 13030 // Otherwise if either is a pointer to a virtual member function, the 13031 // result is unspecified. 13032 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 13033 if (MD->isVirtual()) 13034 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 13035 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 13036 if (MD->isVirtual()) 13037 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 13038 13039 // Otherwise they compare equal if and only if they would refer to the 13040 // same member of the same most derived object or the same subobject if 13041 // they were dereferenced with a hypothetical object of the associated 13042 // class type. 13043 bool Equal = LHSValue == RHSValue; 13044 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 13045 } 13046 13047 if (LHSTy->isNullPtrType()) { 13048 assert(E->isComparisonOp() && "unexpected nullptr operation"); 13049 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 13050 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 13051 // are compared, the result is true of the operator is <=, >= or ==, and 13052 // false otherwise. 13053 return Success(CmpResult::Equal, E); 13054 } 13055 13056 return DoAfter(); 13057 } 13058 13059 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 13060 if (!CheckLiteralType(Info, E)) 13061 return false; 13062 13063 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13064 ComparisonCategoryResult CCR; 13065 switch (CR) { 13066 case CmpResult::Unequal: 13067 llvm_unreachable("should never produce Unequal for three-way comparison"); 13068 case CmpResult::Less: 13069 CCR = ComparisonCategoryResult::Less; 13070 break; 13071 case CmpResult::Equal: 13072 CCR = ComparisonCategoryResult::Equal; 13073 break; 13074 case CmpResult::Greater: 13075 CCR = ComparisonCategoryResult::Greater; 13076 break; 13077 case CmpResult::Unordered: 13078 CCR = ComparisonCategoryResult::Unordered; 13079 break; 13080 } 13081 // Evaluation succeeded. Lookup the information for the comparison category 13082 // type and fetch the VarDecl for the result. 13083 const ComparisonCategoryInfo &CmpInfo = 13084 Info.Ctx.CompCategories.getInfoForType(E->getType()); 13085 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 13086 // Check and evaluate the result as a constant expression. 13087 LValue LV; 13088 LV.set(VD); 13089 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 13090 return false; 13091 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 13092 ConstantExprKind::Normal); 13093 }; 13094 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13095 return ExprEvaluatorBaseTy::VisitBinCmp(E); 13096 }); 13097 } 13098 13099 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13100 // We don't support assignment in C. C++ assignments don't get here because 13101 // assignment is an lvalue in C++. 13102 if (E->isAssignmentOp()) { 13103 Error(E); 13104 if (!Info.noteFailure()) 13105 return false; 13106 } 13107 13108 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 13109 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 13110 13111 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 13112 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 13113 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 13114 13115 if (E->isComparisonOp()) { 13116 // Evaluate builtin binary comparisons by evaluating them as three-way 13117 // comparisons and then translating the result. 13118 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13119 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 13120 "should only produce Unequal for equality comparisons"); 13121 bool IsEqual = CR == CmpResult::Equal, 13122 IsLess = CR == CmpResult::Less, 13123 IsGreater = CR == CmpResult::Greater; 13124 auto Op = E->getOpcode(); 13125 switch (Op) { 13126 default: 13127 llvm_unreachable("unsupported binary operator"); 13128 case BO_EQ: 13129 case BO_NE: 13130 return Success(IsEqual == (Op == BO_EQ), E); 13131 case BO_LT: 13132 return Success(IsLess, E); 13133 case BO_GT: 13134 return Success(IsGreater, E); 13135 case BO_LE: 13136 return Success(IsEqual || IsLess, E); 13137 case BO_GE: 13138 return Success(IsEqual || IsGreater, E); 13139 } 13140 }; 13141 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13142 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13143 }); 13144 } 13145 13146 QualType LHSTy = E->getLHS()->getType(); 13147 QualType RHSTy = E->getRHS()->getType(); 13148 13149 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 13150 E->getOpcode() == BO_Sub) { 13151 LValue LHSValue, RHSValue; 13152 13153 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13154 if (!LHSOK && !Info.noteFailure()) 13155 return false; 13156 13157 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13158 return false; 13159 13160 // Reject differing bases from the normal codepath; we special-case 13161 // comparisons to null. 13162 if (!HasSameBase(LHSValue, RHSValue)) { 13163 // Handle &&A - &&B. 13164 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 13165 return Error(E); 13166 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 13167 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 13168 if (!LHSExpr || !RHSExpr) 13169 return Error(E); 13170 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13171 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13172 if (!LHSAddrExpr || !RHSAddrExpr) 13173 return Error(E); 13174 // Make sure both labels come from the same function. 13175 if (LHSAddrExpr->getLabel()->getDeclContext() != 13176 RHSAddrExpr->getLabel()->getDeclContext()) 13177 return Error(E); 13178 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 13179 } 13180 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13181 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13182 13183 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13184 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13185 13186 // C++11 [expr.add]p6: 13187 // Unless both pointers point to elements of the same array object, or 13188 // one past the last element of the array object, the behavior is 13189 // undefined. 13190 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 13191 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 13192 RHSDesignator)) 13193 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 13194 13195 QualType Type = E->getLHS()->getType(); 13196 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 13197 13198 CharUnits ElementSize; 13199 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 13200 return false; 13201 13202 // As an extension, a type may have zero size (empty struct or union in 13203 // C, array of zero length). Pointer subtraction in such cases has 13204 // undefined behavior, so is not constant. 13205 if (ElementSize.isZero()) { 13206 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 13207 << ElementType; 13208 return false; 13209 } 13210 13211 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 13212 // and produce incorrect results when it overflows. Such behavior 13213 // appears to be non-conforming, but is common, so perhaps we should 13214 // assume the standard intended for such cases to be undefined behavior 13215 // and check for them. 13216 13217 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 13218 // overflow in the final conversion to ptrdiff_t. 13219 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 13220 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 13221 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 13222 false); 13223 APSInt TrueResult = (LHS - RHS) / ElemSize; 13224 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 13225 13226 if (Result.extend(65) != TrueResult && 13227 !HandleOverflow(Info, E, TrueResult, E->getType())) 13228 return false; 13229 return Success(Result, E); 13230 } 13231 13232 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13233 } 13234 13235 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 13236 /// a result as the expression's type. 13237 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13238 const UnaryExprOrTypeTraitExpr *E) { 13239 switch(E->getKind()) { 13240 case UETT_PreferredAlignOf: 13241 case UETT_AlignOf: { 13242 if (E->isArgumentType()) 13243 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13244 E); 13245 else 13246 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13247 E); 13248 } 13249 13250 case UETT_VecStep: { 13251 QualType Ty = E->getTypeOfArgument(); 13252 13253 if (Ty->isVectorType()) { 13254 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13255 13256 // The vec_step built-in functions that take a 3-component 13257 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13258 if (n == 3) 13259 n = 4; 13260 13261 return Success(n, E); 13262 } else 13263 return Success(1, E); 13264 } 13265 13266 case UETT_SizeOf: { 13267 QualType SrcTy = E->getTypeOfArgument(); 13268 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13269 // the result is the size of the referenced type." 13270 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13271 SrcTy = Ref->getPointeeType(); 13272 13273 CharUnits Sizeof; 13274 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13275 return false; 13276 return Success(Sizeof, E); 13277 } 13278 case UETT_OpenMPRequiredSimdAlign: 13279 assert(E->isArgumentType()); 13280 return Success( 13281 Info.Ctx.toCharUnitsFromBits( 13282 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13283 .getQuantity(), 13284 E); 13285 } 13286 13287 llvm_unreachable("unknown expr/type trait"); 13288 } 13289 13290 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13291 CharUnits Result; 13292 unsigned n = OOE->getNumComponents(); 13293 if (n == 0) 13294 return Error(OOE); 13295 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13296 for (unsigned i = 0; i != n; ++i) { 13297 OffsetOfNode ON = OOE->getComponent(i); 13298 switch (ON.getKind()) { 13299 case OffsetOfNode::Array: { 13300 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13301 APSInt IdxResult; 13302 if (!EvaluateInteger(Idx, IdxResult, Info)) 13303 return false; 13304 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13305 if (!AT) 13306 return Error(OOE); 13307 CurrentType = AT->getElementType(); 13308 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13309 Result += IdxResult.getSExtValue() * ElementSize; 13310 break; 13311 } 13312 13313 case OffsetOfNode::Field: { 13314 FieldDecl *MemberDecl = ON.getField(); 13315 const RecordType *RT = CurrentType->getAs<RecordType>(); 13316 if (!RT) 13317 return Error(OOE); 13318 RecordDecl *RD = RT->getDecl(); 13319 if (RD->isInvalidDecl()) return false; 13320 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13321 unsigned i = MemberDecl->getFieldIndex(); 13322 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13323 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13324 CurrentType = MemberDecl->getType().getNonReferenceType(); 13325 break; 13326 } 13327 13328 case OffsetOfNode::Identifier: 13329 llvm_unreachable("dependent __builtin_offsetof"); 13330 13331 case OffsetOfNode::Base: { 13332 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13333 if (BaseSpec->isVirtual()) 13334 return Error(OOE); 13335 13336 // Find the layout of the class whose base we are looking into. 13337 const RecordType *RT = CurrentType->getAs<RecordType>(); 13338 if (!RT) 13339 return Error(OOE); 13340 RecordDecl *RD = RT->getDecl(); 13341 if (RD->isInvalidDecl()) return false; 13342 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13343 13344 // Find the base class itself. 13345 CurrentType = BaseSpec->getType(); 13346 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13347 if (!BaseRT) 13348 return Error(OOE); 13349 13350 // Add the offset to the base. 13351 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13352 break; 13353 } 13354 } 13355 } 13356 return Success(Result, OOE); 13357 } 13358 13359 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13360 switch (E->getOpcode()) { 13361 default: 13362 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13363 // See C99 6.6p3. 13364 return Error(E); 13365 case UO_Extension: 13366 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13367 // If so, we could clear the diagnostic ID. 13368 return Visit(E->getSubExpr()); 13369 case UO_Plus: 13370 // The result is just the value. 13371 return Visit(E->getSubExpr()); 13372 case UO_Minus: { 13373 if (!Visit(E->getSubExpr())) 13374 return false; 13375 if (!Result.isInt()) return Error(E); 13376 const APSInt &Value = Result.getInt(); 13377 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13378 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13379 E->getType())) 13380 return false; 13381 return Success(-Value, E); 13382 } 13383 case UO_Not: { 13384 if (!Visit(E->getSubExpr())) 13385 return false; 13386 if (!Result.isInt()) return Error(E); 13387 return Success(~Result.getInt(), E); 13388 } 13389 case UO_LNot: { 13390 bool bres; 13391 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13392 return false; 13393 return Success(!bres, E); 13394 } 13395 } 13396 } 13397 13398 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13399 /// result type is integer. 13400 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13401 const Expr *SubExpr = E->getSubExpr(); 13402 QualType DestType = E->getType(); 13403 QualType SrcType = SubExpr->getType(); 13404 13405 switch (E->getCastKind()) { 13406 case CK_BaseToDerived: 13407 case CK_DerivedToBase: 13408 case CK_UncheckedDerivedToBase: 13409 case CK_Dynamic: 13410 case CK_ToUnion: 13411 case CK_ArrayToPointerDecay: 13412 case CK_FunctionToPointerDecay: 13413 case CK_NullToPointer: 13414 case CK_NullToMemberPointer: 13415 case CK_BaseToDerivedMemberPointer: 13416 case CK_DerivedToBaseMemberPointer: 13417 case CK_ReinterpretMemberPointer: 13418 case CK_ConstructorConversion: 13419 case CK_IntegralToPointer: 13420 case CK_ToVoid: 13421 case CK_VectorSplat: 13422 case CK_IntegralToFloating: 13423 case CK_FloatingCast: 13424 case CK_CPointerToObjCPointerCast: 13425 case CK_BlockPointerToObjCPointerCast: 13426 case CK_AnyPointerToBlockPointerCast: 13427 case CK_ObjCObjectLValueCast: 13428 case CK_FloatingRealToComplex: 13429 case CK_FloatingComplexToReal: 13430 case CK_FloatingComplexCast: 13431 case CK_FloatingComplexToIntegralComplex: 13432 case CK_IntegralRealToComplex: 13433 case CK_IntegralComplexCast: 13434 case CK_IntegralComplexToFloatingComplex: 13435 case CK_BuiltinFnToFnPtr: 13436 case CK_ZeroToOCLOpaqueType: 13437 case CK_NonAtomicToAtomic: 13438 case CK_AddressSpaceConversion: 13439 case CK_IntToOCLSampler: 13440 case CK_FloatingToFixedPoint: 13441 case CK_FixedPointToFloating: 13442 case CK_FixedPointCast: 13443 case CK_IntegralToFixedPoint: 13444 case CK_MatrixCast: 13445 llvm_unreachable("invalid cast kind for integral value"); 13446 13447 case CK_BitCast: 13448 case CK_Dependent: 13449 case CK_LValueBitCast: 13450 case CK_ARCProduceObject: 13451 case CK_ARCConsumeObject: 13452 case CK_ARCReclaimReturnedObject: 13453 case CK_ARCExtendBlockObject: 13454 case CK_CopyAndAutoreleaseBlockObject: 13455 return Error(E); 13456 13457 case CK_UserDefinedConversion: 13458 case CK_LValueToRValue: 13459 case CK_AtomicToNonAtomic: 13460 case CK_NoOp: 13461 case CK_LValueToRValueBitCast: 13462 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13463 13464 case CK_MemberPointerToBoolean: 13465 case CK_PointerToBoolean: 13466 case CK_IntegralToBoolean: 13467 case CK_FloatingToBoolean: 13468 case CK_BooleanToSignedIntegral: 13469 case CK_FloatingComplexToBoolean: 13470 case CK_IntegralComplexToBoolean: { 13471 bool BoolResult; 13472 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13473 return false; 13474 uint64_t IntResult = BoolResult; 13475 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13476 IntResult = (uint64_t)-1; 13477 return Success(IntResult, E); 13478 } 13479 13480 case CK_FixedPointToIntegral: { 13481 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13482 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13483 return false; 13484 bool Overflowed; 13485 llvm::APSInt Result = Src.convertToInt( 13486 Info.Ctx.getIntWidth(DestType), 13487 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13488 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13489 return false; 13490 return Success(Result, E); 13491 } 13492 13493 case CK_FixedPointToBoolean: { 13494 // Unsigned padding does not affect this. 13495 APValue Val; 13496 if (!Evaluate(Val, Info, SubExpr)) 13497 return false; 13498 return Success(Val.getFixedPoint().getBoolValue(), E); 13499 } 13500 13501 case CK_IntegralCast: { 13502 if (!Visit(SubExpr)) 13503 return false; 13504 13505 if (!Result.isInt()) { 13506 // Allow casts of address-of-label differences if they are no-ops 13507 // or narrowing. (The narrowing case isn't actually guaranteed to 13508 // be constant-evaluatable except in some narrow cases which are hard 13509 // to detect here. We let it through on the assumption the user knows 13510 // what they are doing.) 13511 if (Result.isAddrLabelDiff()) 13512 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13513 // Only allow casts of lvalues if they are lossless. 13514 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13515 } 13516 13517 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13518 Result.getInt()), E); 13519 } 13520 13521 case CK_PointerToIntegral: { 13522 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13523 13524 LValue LV; 13525 if (!EvaluatePointer(SubExpr, LV, Info)) 13526 return false; 13527 13528 if (LV.getLValueBase()) { 13529 // Only allow based lvalue casts if they are lossless. 13530 // FIXME: Allow a larger integer size than the pointer size, and allow 13531 // narrowing back down to pointer width in subsequent integral casts. 13532 // FIXME: Check integer type's active bits, not its type size. 13533 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13534 return Error(E); 13535 13536 LV.Designator.setInvalid(); 13537 LV.moveInto(Result); 13538 return true; 13539 } 13540 13541 APSInt AsInt; 13542 APValue V; 13543 LV.moveInto(V); 13544 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13545 llvm_unreachable("Can't cast this!"); 13546 13547 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13548 } 13549 13550 case CK_IntegralComplexToReal: { 13551 ComplexValue C; 13552 if (!EvaluateComplex(SubExpr, C, Info)) 13553 return false; 13554 return Success(C.getComplexIntReal(), E); 13555 } 13556 13557 case CK_FloatingToIntegral: { 13558 APFloat F(0.0); 13559 if (!EvaluateFloat(SubExpr, F, Info)) 13560 return false; 13561 13562 APSInt Value; 13563 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13564 return false; 13565 return Success(Value, E); 13566 } 13567 } 13568 13569 llvm_unreachable("unknown cast resulting in integral value"); 13570 } 13571 13572 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13573 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13574 ComplexValue LV; 13575 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13576 return false; 13577 if (!LV.isComplexInt()) 13578 return Error(E); 13579 return Success(LV.getComplexIntReal(), E); 13580 } 13581 13582 return Visit(E->getSubExpr()); 13583 } 13584 13585 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13586 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13587 ComplexValue LV; 13588 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13589 return false; 13590 if (!LV.isComplexInt()) 13591 return Error(E); 13592 return Success(LV.getComplexIntImag(), E); 13593 } 13594 13595 VisitIgnoredValue(E->getSubExpr()); 13596 return Success(0, E); 13597 } 13598 13599 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13600 return Success(E->getPackLength(), E); 13601 } 13602 13603 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13604 return Success(E->getValue(), E); 13605 } 13606 13607 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13608 const ConceptSpecializationExpr *E) { 13609 return Success(E->isSatisfied(), E); 13610 } 13611 13612 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13613 return Success(E->isSatisfied(), E); 13614 } 13615 13616 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13617 switch (E->getOpcode()) { 13618 default: 13619 // Invalid unary operators 13620 return Error(E); 13621 case UO_Plus: 13622 // The result is just the value. 13623 return Visit(E->getSubExpr()); 13624 case UO_Minus: { 13625 if (!Visit(E->getSubExpr())) return false; 13626 if (!Result.isFixedPoint()) 13627 return Error(E); 13628 bool Overflowed; 13629 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13630 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13631 return false; 13632 return Success(Negated, E); 13633 } 13634 case UO_LNot: { 13635 bool bres; 13636 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13637 return false; 13638 return Success(!bres, E); 13639 } 13640 } 13641 } 13642 13643 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13644 const Expr *SubExpr = E->getSubExpr(); 13645 QualType DestType = E->getType(); 13646 assert(DestType->isFixedPointType() && 13647 "Expected destination type to be a fixed point type"); 13648 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13649 13650 switch (E->getCastKind()) { 13651 case CK_FixedPointCast: { 13652 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13653 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13654 return false; 13655 bool Overflowed; 13656 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13657 if (Overflowed) { 13658 if (Info.checkingForUndefinedBehavior()) 13659 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13660 diag::warn_fixedpoint_constant_overflow) 13661 << Result.toString() << E->getType(); 13662 if (!HandleOverflow(Info, E, Result, E->getType())) 13663 return false; 13664 } 13665 return Success(Result, E); 13666 } 13667 case CK_IntegralToFixedPoint: { 13668 APSInt Src; 13669 if (!EvaluateInteger(SubExpr, Src, Info)) 13670 return false; 13671 13672 bool Overflowed; 13673 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13674 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13675 13676 if (Overflowed) { 13677 if (Info.checkingForUndefinedBehavior()) 13678 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13679 diag::warn_fixedpoint_constant_overflow) 13680 << IntResult.toString() << E->getType(); 13681 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13682 return false; 13683 } 13684 13685 return Success(IntResult, E); 13686 } 13687 case CK_FloatingToFixedPoint: { 13688 APFloat Src(0.0); 13689 if (!EvaluateFloat(SubExpr, Src, Info)) 13690 return false; 13691 13692 bool Overflowed; 13693 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13694 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13695 13696 if (Overflowed) { 13697 if (Info.checkingForUndefinedBehavior()) 13698 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13699 diag::warn_fixedpoint_constant_overflow) 13700 << Result.toString() << E->getType(); 13701 if (!HandleOverflow(Info, E, Result, E->getType())) 13702 return false; 13703 } 13704 13705 return Success(Result, E); 13706 } 13707 case CK_NoOp: 13708 case CK_LValueToRValue: 13709 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13710 default: 13711 return Error(E); 13712 } 13713 } 13714 13715 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13716 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13717 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13718 13719 const Expr *LHS = E->getLHS(); 13720 const Expr *RHS = E->getRHS(); 13721 FixedPointSemantics ResultFXSema = 13722 Info.Ctx.getFixedPointSemantics(E->getType()); 13723 13724 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13725 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13726 return false; 13727 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13728 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13729 return false; 13730 13731 bool OpOverflow = false, ConversionOverflow = false; 13732 APFixedPoint Result(LHSFX.getSemantics()); 13733 switch (E->getOpcode()) { 13734 case BO_Add: { 13735 Result = LHSFX.add(RHSFX, &OpOverflow) 13736 .convert(ResultFXSema, &ConversionOverflow); 13737 break; 13738 } 13739 case BO_Sub: { 13740 Result = LHSFX.sub(RHSFX, &OpOverflow) 13741 .convert(ResultFXSema, &ConversionOverflow); 13742 break; 13743 } 13744 case BO_Mul: { 13745 Result = LHSFX.mul(RHSFX, &OpOverflow) 13746 .convert(ResultFXSema, &ConversionOverflow); 13747 break; 13748 } 13749 case BO_Div: { 13750 if (RHSFX.getValue() == 0) { 13751 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13752 return false; 13753 } 13754 Result = LHSFX.div(RHSFX, &OpOverflow) 13755 .convert(ResultFXSema, &ConversionOverflow); 13756 break; 13757 } 13758 case BO_Shl: 13759 case BO_Shr: { 13760 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13761 llvm::APSInt RHSVal = RHSFX.getValue(); 13762 13763 unsigned ShiftBW = 13764 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13765 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13766 // Embedded-C 4.1.6.2.2: 13767 // The right operand must be nonnegative and less than the total number 13768 // of (nonpadding) bits of the fixed-point operand ... 13769 if (RHSVal.isNegative()) 13770 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13771 else if (Amt != RHSVal) 13772 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13773 << RHSVal << E->getType() << ShiftBW; 13774 13775 if (E->getOpcode() == BO_Shl) 13776 Result = LHSFX.shl(Amt, &OpOverflow); 13777 else 13778 Result = LHSFX.shr(Amt, &OpOverflow); 13779 break; 13780 } 13781 default: 13782 return false; 13783 } 13784 if (OpOverflow || ConversionOverflow) { 13785 if (Info.checkingForUndefinedBehavior()) 13786 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13787 diag::warn_fixedpoint_constant_overflow) 13788 << Result.toString() << E->getType(); 13789 if (!HandleOverflow(Info, E, Result, E->getType())) 13790 return false; 13791 } 13792 return Success(Result, E); 13793 } 13794 13795 //===----------------------------------------------------------------------===// 13796 // Float Evaluation 13797 //===----------------------------------------------------------------------===// 13798 13799 namespace { 13800 class FloatExprEvaluator 13801 : public ExprEvaluatorBase<FloatExprEvaluator> { 13802 APFloat &Result; 13803 public: 13804 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13805 : ExprEvaluatorBaseTy(info), Result(result) {} 13806 13807 bool Success(const APValue &V, const Expr *e) { 13808 Result = V.getFloat(); 13809 return true; 13810 } 13811 13812 bool ZeroInitialization(const Expr *E) { 13813 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13814 return true; 13815 } 13816 13817 bool VisitCallExpr(const CallExpr *E); 13818 13819 bool VisitUnaryOperator(const UnaryOperator *E); 13820 bool VisitBinaryOperator(const BinaryOperator *E); 13821 bool VisitFloatingLiteral(const FloatingLiteral *E); 13822 bool VisitCastExpr(const CastExpr *E); 13823 13824 bool VisitUnaryReal(const UnaryOperator *E); 13825 bool VisitUnaryImag(const UnaryOperator *E); 13826 13827 // FIXME: Missing: array subscript of vector, member of vector 13828 }; 13829 } // end anonymous namespace 13830 13831 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13832 assert(!E->isValueDependent()); 13833 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 13834 return FloatExprEvaluator(Info, Result).Visit(E); 13835 } 13836 13837 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13838 QualType ResultTy, 13839 const Expr *Arg, 13840 bool SNaN, 13841 llvm::APFloat &Result) { 13842 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13843 if (!S) return false; 13844 13845 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13846 13847 llvm::APInt fill; 13848 13849 // Treat empty strings as if they were zero. 13850 if (S->getString().empty()) 13851 fill = llvm::APInt(32, 0); 13852 else if (S->getString().getAsInteger(0, fill)) 13853 return false; 13854 13855 if (Context.getTargetInfo().isNan2008()) { 13856 if (SNaN) 13857 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13858 else 13859 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13860 } else { 13861 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13862 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13863 // a different encoding to what became a standard in 2008, and for pre- 13864 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13865 // sNaN. This is now known as "legacy NaN" encoding. 13866 if (SNaN) 13867 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13868 else 13869 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13870 } 13871 13872 return true; 13873 } 13874 13875 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13876 switch (E->getBuiltinCallee()) { 13877 default: 13878 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13879 13880 case Builtin::BI__builtin_huge_val: 13881 case Builtin::BI__builtin_huge_valf: 13882 case Builtin::BI__builtin_huge_vall: 13883 case Builtin::BI__builtin_huge_valf16: 13884 case Builtin::BI__builtin_huge_valf128: 13885 case Builtin::BI__builtin_inf: 13886 case Builtin::BI__builtin_inff: 13887 case Builtin::BI__builtin_infl: 13888 case Builtin::BI__builtin_inff16: 13889 case Builtin::BI__builtin_inff128: { 13890 const llvm::fltSemantics &Sem = 13891 Info.Ctx.getFloatTypeSemantics(E->getType()); 13892 Result = llvm::APFloat::getInf(Sem); 13893 return true; 13894 } 13895 13896 case Builtin::BI__builtin_nans: 13897 case Builtin::BI__builtin_nansf: 13898 case Builtin::BI__builtin_nansl: 13899 case Builtin::BI__builtin_nansf16: 13900 case Builtin::BI__builtin_nansf128: 13901 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13902 true, Result)) 13903 return Error(E); 13904 return true; 13905 13906 case Builtin::BI__builtin_nan: 13907 case Builtin::BI__builtin_nanf: 13908 case Builtin::BI__builtin_nanl: 13909 case Builtin::BI__builtin_nanf16: 13910 case Builtin::BI__builtin_nanf128: 13911 // If this is __builtin_nan() turn this into a nan, otherwise we 13912 // can't constant fold it. 13913 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13914 false, Result)) 13915 return Error(E); 13916 return true; 13917 13918 case Builtin::BI__builtin_fabs: 13919 case Builtin::BI__builtin_fabsf: 13920 case Builtin::BI__builtin_fabsl: 13921 case Builtin::BI__builtin_fabsf128: 13922 // The C standard says "fabs raises no floating-point exceptions, 13923 // even if x is a signaling NaN. The returned value is independent of 13924 // the current rounding direction mode." Therefore constant folding can 13925 // proceed without regard to the floating point settings. 13926 // Reference, WG14 N2478 F.10.4.3 13927 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13928 return false; 13929 13930 if (Result.isNegative()) 13931 Result.changeSign(); 13932 return true; 13933 13934 case Builtin::BI__arithmetic_fence: 13935 return EvaluateFloat(E->getArg(0), Result, Info); 13936 13937 // FIXME: Builtin::BI__builtin_powi 13938 // FIXME: Builtin::BI__builtin_powif 13939 // FIXME: Builtin::BI__builtin_powil 13940 13941 case Builtin::BI__builtin_copysign: 13942 case Builtin::BI__builtin_copysignf: 13943 case Builtin::BI__builtin_copysignl: 13944 case Builtin::BI__builtin_copysignf128: { 13945 APFloat RHS(0.); 13946 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13947 !EvaluateFloat(E->getArg(1), RHS, Info)) 13948 return false; 13949 Result.copySign(RHS); 13950 return true; 13951 } 13952 } 13953 } 13954 13955 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13956 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13957 ComplexValue CV; 13958 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13959 return false; 13960 Result = CV.FloatReal; 13961 return true; 13962 } 13963 13964 return Visit(E->getSubExpr()); 13965 } 13966 13967 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13968 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13969 ComplexValue CV; 13970 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13971 return false; 13972 Result = CV.FloatImag; 13973 return true; 13974 } 13975 13976 VisitIgnoredValue(E->getSubExpr()); 13977 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13978 Result = llvm::APFloat::getZero(Sem); 13979 return true; 13980 } 13981 13982 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13983 switch (E->getOpcode()) { 13984 default: return Error(E); 13985 case UO_Plus: 13986 return EvaluateFloat(E->getSubExpr(), Result, Info); 13987 case UO_Minus: 13988 // In C standard, WG14 N2478 F.3 p4 13989 // "the unary - raises no floating point exceptions, 13990 // even if the operand is signalling." 13991 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13992 return false; 13993 Result.changeSign(); 13994 return true; 13995 } 13996 } 13997 13998 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13999 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14000 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14001 14002 APFloat RHS(0.0); 14003 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 14004 if (!LHSOK && !Info.noteFailure()) 14005 return false; 14006 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 14007 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 14008 } 14009 14010 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 14011 Result = E->getValue(); 14012 return true; 14013 } 14014 14015 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 14016 const Expr* SubExpr = E->getSubExpr(); 14017 14018 switch (E->getCastKind()) { 14019 default: 14020 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14021 14022 case CK_IntegralToFloating: { 14023 APSInt IntResult; 14024 const FPOptions FPO = E->getFPFeaturesInEffect( 14025 Info.Ctx.getLangOpts()); 14026 return EvaluateInteger(SubExpr, IntResult, Info) && 14027 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 14028 IntResult, E->getType(), Result); 14029 } 14030 14031 case CK_FixedPointToFloating: { 14032 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 14033 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 14034 return false; 14035 Result = 14036 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 14037 return true; 14038 } 14039 14040 case CK_FloatingCast: { 14041 if (!Visit(SubExpr)) 14042 return false; 14043 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 14044 Result); 14045 } 14046 14047 case CK_FloatingComplexToReal: { 14048 ComplexValue V; 14049 if (!EvaluateComplex(SubExpr, V, Info)) 14050 return false; 14051 Result = V.getComplexFloatReal(); 14052 return true; 14053 } 14054 } 14055 } 14056 14057 //===----------------------------------------------------------------------===// 14058 // Complex Evaluation (for float and integer) 14059 //===----------------------------------------------------------------------===// 14060 14061 namespace { 14062 class ComplexExprEvaluator 14063 : public ExprEvaluatorBase<ComplexExprEvaluator> { 14064 ComplexValue &Result; 14065 14066 public: 14067 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 14068 : ExprEvaluatorBaseTy(info), Result(Result) {} 14069 14070 bool Success(const APValue &V, const Expr *e) { 14071 Result.setFrom(V); 14072 return true; 14073 } 14074 14075 bool ZeroInitialization(const Expr *E); 14076 14077 //===--------------------------------------------------------------------===// 14078 // Visitor Methods 14079 //===--------------------------------------------------------------------===// 14080 14081 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 14082 bool VisitCastExpr(const CastExpr *E); 14083 bool VisitBinaryOperator(const BinaryOperator *E); 14084 bool VisitUnaryOperator(const UnaryOperator *E); 14085 bool VisitInitListExpr(const InitListExpr *E); 14086 bool VisitCallExpr(const CallExpr *E); 14087 }; 14088 } // end anonymous namespace 14089 14090 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 14091 EvalInfo &Info) { 14092 assert(!E->isValueDependent()); 14093 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 14094 return ComplexExprEvaluator(Info, Result).Visit(E); 14095 } 14096 14097 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 14098 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 14099 if (ElemTy->isRealFloatingType()) { 14100 Result.makeComplexFloat(); 14101 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 14102 Result.FloatReal = Zero; 14103 Result.FloatImag = Zero; 14104 } else { 14105 Result.makeComplexInt(); 14106 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 14107 Result.IntReal = Zero; 14108 Result.IntImag = Zero; 14109 } 14110 return true; 14111 } 14112 14113 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 14114 const Expr* SubExpr = E->getSubExpr(); 14115 14116 if (SubExpr->getType()->isRealFloatingType()) { 14117 Result.makeComplexFloat(); 14118 APFloat &Imag = Result.FloatImag; 14119 if (!EvaluateFloat(SubExpr, Imag, Info)) 14120 return false; 14121 14122 Result.FloatReal = APFloat(Imag.getSemantics()); 14123 return true; 14124 } else { 14125 assert(SubExpr->getType()->isIntegerType() && 14126 "Unexpected imaginary literal."); 14127 14128 Result.makeComplexInt(); 14129 APSInt &Imag = Result.IntImag; 14130 if (!EvaluateInteger(SubExpr, Imag, Info)) 14131 return false; 14132 14133 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 14134 return true; 14135 } 14136 } 14137 14138 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 14139 14140 switch (E->getCastKind()) { 14141 case CK_BitCast: 14142 case CK_BaseToDerived: 14143 case CK_DerivedToBase: 14144 case CK_UncheckedDerivedToBase: 14145 case CK_Dynamic: 14146 case CK_ToUnion: 14147 case CK_ArrayToPointerDecay: 14148 case CK_FunctionToPointerDecay: 14149 case CK_NullToPointer: 14150 case CK_NullToMemberPointer: 14151 case CK_BaseToDerivedMemberPointer: 14152 case CK_DerivedToBaseMemberPointer: 14153 case CK_MemberPointerToBoolean: 14154 case CK_ReinterpretMemberPointer: 14155 case CK_ConstructorConversion: 14156 case CK_IntegralToPointer: 14157 case CK_PointerToIntegral: 14158 case CK_PointerToBoolean: 14159 case CK_ToVoid: 14160 case CK_VectorSplat: 14161 case CK_IntegralCast: 14162 case CK_BooleanToSignedIntegral: 14163 case CK_IntegralToBoolean: 14164 case CK_IntegralToFloating: 14165 case CK_FloatingToIntegral: 14166 case CK_FloatingToBoolean: 14167 case CK_FloatingCast: 14168 case CK_CPointerToObjCPointerCast: 14169 case CK_BlockPointerToObjCPointerCast: 14170 case CK_AnyPointerToBlockPointerCast: 14171 case CK_ObjCObjectLValueCast: 14172 case CK_FloatingComplexToReal: 14173 case CK_FloatingComplexToBoolean: 14174 case CK_IntegralComplexToReal: 14175 case CK_IntegralComplexToBoolean: 14176 case CK_ARCProduceObject: 14177 case CK_ARCConsumeObject: 14178 case CK_ARCReclaimReturnedObject: 14179 case CK_ARCExtendBlockObject: 14180 case CK_CopyAndAutoreleaseBlockObject: 14181 case CK_BuiltinFnToFnPtr: 14182 case CK_ZeroToOCLOpaqueType: 14183 case CK_NonAtomicToAtomic: 14184 case CK_AddressSpaceConversion: 14185 case CK_IntToOCLSampler: 14186 case CK_FloatingToFixedPoint: 14187 case CK_FixedPointToFloating: 14188 case CK_FixedPointCast: 14189 case CK_FixedPointToBoolean: 14190 case CK_FixedPointToIntegral: 14191 case CK_IntegralToFixedPoint: 14192 case CK_MatrixCast: 14193 llvm_unreachable("invalid cast kind for complex value"); 14194 14195 case CK_LValueToRValue: 14196 case CK_AtomicToNonAtomic: 14197 case CK_NoOp: 14198 case CK_LValueToRValueBitCast: 14199 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14200 14201 case CK_Dependent: 14202 case CK_LValueBitCast: 14203 case CK_UserDefinedConversion: 14204 return Error(E); 14205 14206 case CK_FloatingRealToComplex: { 14207 APFloat &Real = Result.FloatReal; 14208 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 14209 return false; 14210 14211 Result.makeComplexFloat(); 14212 Result.FloatImag = APFloat(Real.getSemantics()); 14213 return true; 14214 } 14215 14216 case CK_FloatingComplexCast: { 14217 if (!Visit(E->getSubExpr())) 14218 return false; 14219 14220 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14221 QualType From 14222 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14223 14224 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 14225 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 14226 } 14227 14228 case CK_FloatingComplexToIntegralComplex: { 14229 if (!Visit(E->getSubExpr())) 14230 return false; 14231 14232 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14233 QualType From 14234 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14235 Result.makeComplexInt(); 14236 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 14237 To, Result.IntReal) && 14238 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 14239 To, Result.IntImag); 14240 } 14241 14242 case CK_IntegralRealToComplex: { 14243 APSInt &Real = Result.IntReal; 14244 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14245 return false; 14246 14247 Result.makeComplexInt(); 14248 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14249 return true; 14250 } 14251 14252 case CK_IntegralComplexCast: { 14253 if (!Visit(E->getSubExpr())) 14254 return false; 14255 14256 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14257 QualType From 14258 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14259 14260 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14261 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14262 return true; 14263 } 14264 14265 case CK_IntegralComplexToFloatingComplex: { 14266 if (!Visit(E->getSubExpr())) 14267 return false; 14268 14269 const FPOptions FPO = E->getFPFeaturesInEffect( 14270 Info.Ctx.getLangOpts()); 14271 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14272 QualType From 14273 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14274 Result.makeComplexFloat(); 14275 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14276 To, Result.FloatReal) && 14277 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14278 To, Result.FloatImag); 14279 } 14280 } 14281 14282 llvm_unreachable("unknown cast resulting in complex value"); 14283 } 14284 14285 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14286 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14287 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14288 14289 // Track whether the LHS or RHS is real at the type system level. When this is 14290 // the case we can simplify our evaluation strategy. 14291 bool LHSReal = false, RHSReal = false; 14292 14293 bool LHSOK; 14294 if (E->getLHS()->getType()->isRealFloatingType()) { 14295 LHSReal = true; 14296 APFloat &Real = Result.FloatReal; 14297 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14298 if (LHSOK) { 14299 Result.makeComplexFloat(); 14300 Result.FloatImag = APFloat(Real.getSemantics()); 14301 } 14302 } else { 14303 LHSOK = Visit(E->getLHS()); 14304 } 14305 if (!LHSOK && !Info.noteFailure()) 14306 return false; 14307 14308 ComplexValue RHS; 14309 if (E->getRHS()->getType()->isRealFloatingType()) { 14310 RHSReal = true; 14311 APFloat &Real = RHS.FloatReal; 14312 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14313 return false; 14314 RHS.makeComplexFloat(); 14315 RHS.FloatImag = APFloat(Real.getSemantics()); 14316 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14317 return false; 14318 14319 assert(!(LHSReal && RHSReal) && 14320 "Cannot have both operands of a complex operation be real."); 14321 switch (E->getOpcode()) { 14322 default: return Error(E); 14323 case BO_Add: 14324 if (Result.isComplexFloat()) { 14325 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14326 APFloat::rmNearestTiesToEven); 14327 if (LHSReal) 14328 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14329 else if (!RHSReal) 14330 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14331 APFloat::rmNearestTiesToEven); 14332 } else { 14333 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14334 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14335 } 14336 break; 14337 case BO_Sub: 14338 if (Result.isComplexFloat()) { 14339 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14340 APFloat::rmNearestTiesToEven); 14341 if (LHSReal) { 14342 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14343 Result.getComplexFloatImag().changeSign(); 14344 } else if (!RHSReal) { 14345 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14346 APFloat::rmNearestTiesToEven); 14347 } 14348 } else { 14349 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14350 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14351 } 14352 break; 14353 case BO_Mul: 14354 if (Result.isComplexFloat()) { 14355 // This is an implementation of complex multiplication according to the 14356 // constraints laid out in C11 Annex G. The implementation uses the 14357 // following naming scheme: 14358 // (a + ib) * (c + id) 14359 ComplexValue LHS = Result; 14360 APFloat &A = LHS.getComplexFloatReal(); 14361 APFloat &B = LHS.getComplexFloatImag(); 14362 APFloat &C = RHS.getComplexFloatReal(); 14363 APFloat &D = RHS.getComplexFloatImag(); 14364 APFloat &ResR = Result.getComplexFloatReal(); 14365 APFloat &ResI = Result.getComplexFloatImag(); 14366 if (LHSReal) { 14367 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14368 ResR = A * C; 14369 ResI = A * D; 14370 } else if (RHSReal) { 14371 ResR = C * A; 14372 ResI = C * B; 14373 } else { 14374 // In the fully general case, we need to handle NaNs and infinities 14375 // robustly. 14376 APFloat AC = A * C; 14377 APFloat BD = B * D; 14378 APFloat AD = A * D; 14379 APFloat BC = B * C; 14380 ResR = AC - BD; 14381 ResI = AD + BC; 14382 if (ResR.isNaN() && ResI.isNaN()) { 14383 bool Recalc = false; 14384 if (A.isInfinity() || B.isInfinity()) { 14385 A = APFloat::copySign( 14386 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14387 B = APFloat::copySign( 14388 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14389 if (C.isNaN()) 14390 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14391 if (D.isNaN()) 14392 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14393 Recalc = true; 14394 } 14395 if (C.isInfinity() || D.isInfinity()) { 14396 C = APFloat::copySign( 14397 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14398 D = APFloat::copySign( 14399 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14400 if (A.isNaN()) 14401 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14402 if (B.isNaN()) 14403 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14404 Recalc = true; 14405 } 14406 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14407 AD.isInfinity() || BC.isInfinity())) { 14408 if (A.isNaN()) 14409 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14410 if (B.isNaN()) 14411 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14412 if (C.isNaN()) 14413 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14414 if (D.isNaN()) 14415 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14416 Recalc = true; 14417 } 14418 if (Recalc) { 14419 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14420 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14421 } 14422 } 14423 } 14424 } else { 14425 ComplexValue LHS = Result; 14426 Result.getComplexIntReal() = 14427 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14428 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14429 Result.getComplexIntImag() = 14430 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14431 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14432 } 14433 break; 14434 case BO_Div: 14435 if (Result.isComplexFloat()) { 14436 // This is an implementation of complex division according to the 14437 // constraints laid out in C11 Annex G. The implementation uses the 14438 // following naming scheme: 14439 // (a + ib) / (c + id) 14440 ComplexValue LHS = Result; 14441 APFloat &A = LHS.getComplexFloatReal(); 14442 APFloat &B = LHS.getComplexFloatImag(); 14443 APFloat &C = RHS.getComplexFloatReal(); 14444 APFloat &D = RHS.getComplexFloatImag(); 14445 APFloat &ResR = Result.getComplexFloatReal(); 14446 APFloat &ResI = Result.getComplexFloatImag(); 14447 if (RHSReal) { 14448 ResR = A / C; 14449 ResI = B / C; 14450 } else { 14451 if (LHSReal) { 14452 // No real optimizations we can do here, stub out with zero. 14453 B = APFloat::getZero(A.getSemantics()); 14454 } 14455 int DenomLogB = 0; 14456 APFloat MaxCD = maxnum(abs(C), abs(D)); 14457 if (MaxCD.isFinite()) { 14458 DenomLogB = ilogb(MaxCD); 14459 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14460 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14461 } 14462 APFloat Denom = C * C + D * D; 14463 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14464 APFloat::rmNearestTiesToEven); 14465 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14466 APFloat::rmNearestTiesToEven); 14467 if (ResR.isNaN() && ResI.isNaN()) { 14468 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14469 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14470 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14471 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14472 D.isFinite()) { 14473 A = APFloat::copySign( 14474 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14475 B = APFloat::copySign( 14476 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14477 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14478 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14479 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14480 C = APFloat::copySign( 14481 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14482 D = APFloat::copySign( 14483 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14484 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14485 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14486 } 14487 } 14488 } 14489 } else { 14490 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14491 return Error(E, diag::note_expr_divide_by_zero); 14492 14493 ComplexValue LHS = Result; 14494 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14495 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14496 Result.getComplexIntReal() = 14497 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14498 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14499 Result.getComplexIntImag() = 14500 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14501 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14502 } 14503 break; 14504 } 14505 14506 return true; 14507 } 14508 14509 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14510 // Get the operand value into 'Result'. 14511 if (!Visit(E->getSubExpr())) 14512 return false; 14513 14514 switch (E->getOpcode()) { 14515 default: 14516 return Error(E); 14517 case UO_Extension: 14518 return true; 14519 case UO_Plus: 14520 // The result is always just the subexpr. 14521 return true; 14522 case UO_Minus: 14523 if (Result.isComplexFloat()) { 14524 Result.getComplexFloatReal().changeSign(); 14525 Result.getComplexFloatImag().changeSign(); 14526 } 14527 else { 14528 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14529 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14530 } 14531 return true; 14532 case UO_Not: 14533 if (Result.isComplexFloat()) 14534 Result.getComplexFloatImag().changeSign(); 14535 else 14536 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14537 return true; 14538 } 14539 } 14540 14541 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14542 if (E->getNumInits() == 2) { 14543 if (E->getType()->isComplexType()) { 14544 Result.makeComplexFloat(); 14545 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14546 return false; 14547 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14548 return false; 14549 } else { 14550 Result.makeComplexInt(); 14551 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14552 return false; 14553 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14554 return false; 14555 } 14556 return true; 14557 } 14558 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14559 } 14560 14561 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14562 switch (E->getBuiltinCallee()) { 14563 case Builtin::BI__builtin_complex: 14564 Result.makeComplexFloat(); 14565 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14566 return false; 14567 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14568 return false; 14569 return true; 14570 14571 default: 14572 break; 14573 } 14574 14575 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14576 } 14577 14578 //===----------------------------------------------------------------------===// 14579 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14580 // implicit conversion. 14581 //===----------------------------------------------------------------------===// 14582 14583 namespace { 14584 class AtomicExprEvaluator : 14585 public ExprEvaluatorBase<AtomicExprEvaluator> { 14586 const LValue *This; 14587 APValue &Result; 14588 public: 14589 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14590 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14591 14592 bool Success(const APValue &V, const Expr *E) { 14593 Result = V; 14594 return true; 14595 } 14596 14597 bool ZeroInitialization(const Expr *E) { 14598 ImplicitValueInitExpr VIE( 14599 E->getType()->castAs<AtomicType>()->getValueType()); 14600 // For atomic-qualified class (and array) types in C++, initialize the 14601 // _Atomic-wrapped subobject directly, in-place. 14602 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14603 : Evaluate(Result, Info, &VIE); 14604 } 14605 14606 bool VisitCastExpr(const CastExpr *E) { 14607 switch (E->getCastKind()) { 14608 default: 14609 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14610 case CK_NonAtomicToAtomic: 14611 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14612 : Evaluate(Result, Info, E->getSubExpr()); 14613 } 14614 } 14615 }; 14616 } // end anonymous namespace 14617 14618 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14619 EvalInfo &Info) { 14620 assert(!E->isValueDependent()); 14621 assert(E->isPRValue() && E->getType()->isAtomicType()); 14622 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14623 } 14624 14625 //===----------------------------------------------------------------------===// 14626 // Void expression evaluation, primarily for a cast to void on the LHS of a 14627 // comma operator 14628 //===----------------------------------------------------------------------===// 14629 14630 namespace { 14631 class VoidExprEvaluator 14632 : public ExprEvaluatorBase<VoidExprEvaluator> { 14633 public: 14634 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14635 14636 bool Success(const APValue &V, const Expr *e) { return true; } 14637 14638 bool ZeroInitialization(const Expr *E) { return true; } 14639 14640 bool VisitCastExpr(const CastExpr *E) { 14641 switch (E->getCastKind()) { 14642 default: 14643 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14644 case CK_ToVoid: 14645 VisitIgnoredValue(E->getSubExpr()); 14646 return true; 14647 } 14648 } 14649 14650 bool VisitCallExpr(const CallExpr *E) { 14651 switch (E->getBuiltinCallee()) { 14652 case Builtin::BI__assume: 14653 case Builtin::BI__builtin_assume: 14654 // The argument is not evaluated! 14655 return true; 14656 14657 case Builtin::BI__builtin_operator_delete: 14658 return HandleOperatorDeleteCall(Info, E); 14659 14660 default: 14661 break; 14662 } 14663 14664 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14665 } 14666 14667 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14668 }; 14669 } // end anonymous namespace 14670 14671 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14672 // We cannot speculatively evaluate a delete expression. 14673 if (Info.SpeculativeEvaluationDepth) 14674 return false; 14675 14676 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14677 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14678 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14679 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14680 return false; 14681 } 14682 14683 const Expr *Arg = E->getArgument(); 14684 14685 LValue Pointer; 14686 if (!EvaluatePointer(Arg, Pointer, Info)) 14687 return false; 14688 if (Pointer.Designator.Invalid) 14689 return false; 14690 14691 // Deleting a null pointer has no effect. 14692 if (Pointer.isNullPointer()) { 14693 // This is the only case where we need to produce an extension warning: 14694 // the only other way we can succeed is if we find a dynamic allocation, 14695 // and we will have warned when we allocated it in that case. 14696 if (!Info.getLangOpts().CPlusPlus20) 14697 Info.CCEDiag(E, diag::note_constexpr_new); 14698 return true; 14699 } 14700 14701 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14702 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14703 if (!Alloc) 14704 return false; 14705 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14706 14707 // For the non-array case, the designator must be empty if the static type 14708 // does not have a virtual destructor. 14709 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14710 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14711 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14712 << Arg->getType()->getPointeeType() << AllocType; 14713 return false; 14714 } 14715 14716 // For a class type with a virtual destructor, the selected operator delete 14717 // is the one looked up when building the destructor. 14718 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14719 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14720 if (VirtualDelete && 14721 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14722 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14723 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14724 return false; 14725 } 14726 } 14727 14728 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14729 (*Alloc)->Value, AllocType)) 14730 return false; 14731 14732 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14733 // The element was already erased. This means the destructor call also 14734 // deleted the object. 14735 // FIXME: This probably results in undefined behavior before we get this 14736 // far, and should be diagnosed elsewhere first. 14737 Info.FFDiag(E, diag::note_constexpr_double_delete); 14738 return false; 14739 } 14740 14741 return true; 14742 } 14743 14744 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14745 assert(!E->isValueDependent()); 14746 assert(E->isPRValue() && E->getType()->isVoidType()); 14747 return VoidExprEvaluator(Info).Visit(E); 14748 } 14749 14750 //===----------------------------------------------------------------------===// 14751 // Top level Expr::EvaluateAsRValue method. 14752 //===----------------------------------------------------------------------===// 14753 14754 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14755 assert(!E->isValueDependent()); 14756 // In C, function designators are not lvalues, but we evaluate them as if they 14757 // are. 14758 QualType T = E->getType(); 14759 if (E->isGLValue() || T->isFunctionType()) { 14760 LValue LV; 14761 if (!EvaluateLValue(E, LV, Info)) 14762 return false; 14763 LV.moveInto(Result); 14764 } else if (T->isVectorType()) { 14765 if (!EvaluateVector(E, Result, Info)) 14766 return false; 14767 } else if (T->isIntegralOrEnumerationType()) { 14768 if (!IntExprEvaluator(Info, Result).Visit(E)) 14769 return false; 14770 } else if (T->hasPointerRepresentation()) { 14771 LValue LV; 14772 if (!EvaluatePointer(E, LV, Info)) 14773 return false; 14774 LV.moveInto(Result); 14775 } else if (T->isRealFloatingType()) { 14776 llvm::APFloat F(0.0); 14777 if (!EvaluateFloat(E, F, Info)) 14778 return false; 14779 Result = APValue(F); 14780 } else if (T->isAnyComplexType()) { 14781 ComplexValue C; 14782 if (!EvaluateComplex(E, C, Info)) 14783 return false; 14784 C.moveInto(Result); 14785 } else if (T->isFixedPointType()) { 14786 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14787 } else if (T->isMemberPointerType()) { 14788 MemberPtr P; 14789 if (!EvaluateMemberPointer(E, P, Info)) 14790 return false; 14791 P.moveInto(Result); 14792 return true; 14793 } else if (T->isArrayType()) { 14794 LValue LV; 14795 APValue &Value = 14796 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14797 if (!EvaluateArray(E, LV, Value, Info)) 14798 return false; 14799 Result = Value; 14800 } else if (T->isRecordType()) { 14801 LValue LV; 14802 APValue &Value = 14803 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14804 if (!EvaluateRecord(E, LV, Value, Info)) 14805 return false; 14806 Result = Value; 14807 } else if (T->isVoidType()) { 14808 if (!Info.getLangOpts().CPlusPlus11) 14809 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14810 << E->getType(); 14811 if (!EvaluateVoid(E, Info)) 14812 return false; 14813 } else if (T->isAtomicType()) { 14814 QualType Unqual = T.getAtomicUnqualifiedType(); 14815 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14816 LValue LV; 14817 APValue &Value = Info.CurrentCall->createTemporary( 14818 E, Unqual, ScopeKind::FullExpression, LV); 14819 if (!EvaluateAtomic(E, &LV, Value, Info)) 14820 return false; 14821 } else { 14822 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14823 return false; 14824 } 14825 } else if (Info.getLangOpts().CPlusPlus11) { 14826 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14827 return false; 14828 } else { 14829 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14830 return false; 14831 } 14832 14833 return true; 14834 } 14835 14836 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14837 /// cases, the in-place evaluation is essential, since later initializers for 14838 /// an object can indirectly refer to subobjects which were initialized earlier. 14839 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14840 const Expr *E, bool AllowNonLiteralTypes) { 14841 assert(!E->isValueDependent()); 14842 14843 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14844 return false; 14845 14846 if (E->isPRValue()) { 14847 // Evaluate arrays and record types in-place, so that later initializers can 14848 // refer to earlier-initialized members of the object. 14849 QualType T = E->getType(); 14850 if (T->isArrayType()) 14851 return EvaluateArray(E, This, Result, Info); 14852 else if (T->isRecordType()) 14853 return EvaluateRecord(E, This, Result, Info); 14854 else if (T->isAtomicType()) { 14855 QualType Unqual = T.getAtomicUnqualifiedType(); 14856 if (Unqual->isArrayType() || Unqual->isRecordType()) 14857 return EvaluateAtomic(E, &This, Result, Info); 14858 } 14859 } 14860 14861 // For any other type, in-place evaluation is unimportant. 14862 return Evaluate(Result, Info, E); 14863 } 14864 14865 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14866 /// lvalue-to-rvalue cast if it is an lvalue. 14867 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14868 assert(!E->isValueDependent()); 14869 if (Info.EnableNewConstInterp) { 14870 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14871 return false; 14872 } else { 14873 if (E->getType().isNull()) 14874 return false; 14875 14876 if (!CheckLiteralType(Info, E)) 14877 return false; 14878 14879 if (!::Evaluate(Result, Info, E)) 14880 return false; 14881 14882 if (E->isGLValue()) { 14883 LValue LV; 14884 LV.setFrom(Info.Ctx, Result); 14885 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14886 return false; 14887 } 14888 } 14889 14890 // Check this core constant expression is a constant expression. 14891 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14892 ConstantExprKind::Normal) && 14893 CheckMemoryLeaks(Info); 14894 } 14895 14896 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14897 const ASTContext &Ctx, bool &IsConst) { 14898 // Fast-path evaluations of integer literals, since we sometimes see files 14899 // containing vast quantities of these. 14900 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14901 Result.Val = APValue(APSInt(L->getValue(), 14902 L->getType()->isUnsignedIntegerType())); 14903 IsConst = true; 14904 return true; 14905 } 14906 14907 // This case should be rare, but we need to check it before we check on 14908 // the type below. 14909 if (Exp->getType().isNull()) { 14910 IsConst = false; 14911 return true; 14912 } 14913 14914 // FIXME: Evaluating values of large array and record types can cause 14915 // performance problems. Only do so in C++11 for now. 14916 if (Exp->isPRValue() && 14917 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && 14918 !Ctx.getLangOpts().CPlusPlus11) { 14919 IsConst = false; 14920 return true; 14921 } 14922 return false; 14923 } 14924 14925 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14926 Expr::SideEffectsKind SEK) { 14927 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14928 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14929 } 14930 14931 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14932 const ASTContext &Ctx, EvalInfo &Info) { 14933 assert(!E->isValueDependent()); 14934 bool IsConst; 14935 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14936 return IsConst; 14937 14938 return EvaluateAsRValue(Info, E, Result.Val); 14939 } 14940 14941 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14942 const ASTContext &Ctx, 14943 Expr::SideEffectsKind AllowSideEffects, 14944 EvalInfo &Info) { 14945 assert(!E->isValueDependent()); 14946 if (!E->getType()->isIntegralOrEnumerationType()) 14947 return false; 14948 14949 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14950 !ExprResult.Val.isInt() || 14951 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14952 return false; 14953 14954 return true; 14955 } 14956 14957 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14958 const ASTContext &Ctx, 14959 Expr::SideEffectsKind AllowSideEffects, 14960 EvalInfo &Info) { 14961 assert(!E->isValueDependent()); 14962 if (!E->getType()->isFixedPointType()) 14963 return false; 14964 14965 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14966 return false; 14967 14968 if (!ExprResult.Val.isFixedPoint() || 14969 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14970 return false; 14971 14972 return true; 14973 } 14974 14975 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14976 /// any crazy technique (that has nothing to do with language standards) that 14977 /// we want to. If this function returns true, it returns the folded constant 14978 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14979 /// will be applied to the result. 14980 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14981 bool InConstantContext) const { 14982 assert(!isValueDependent() && 14983 "Expression evaluator can't be called on a dependent expression."); 14984 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14985 Info.InConstantContext = InConstantContext; 14986 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14987 } 14988 14989 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14990 bool InConstantContext) const { 14991 assert(!isValueDependent() && 14992 "Expression evaluator can't be called on a dependent expression."); 14993 EvalResult Scratch; 14994 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14995 HandleConversionToBool(Scratch.Val, Result); 14996 } 14997 14998 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14999 SideEffectsKind AllowSideEffects, 15000 bool InConstantContext) const { 15001 assert(!isValueDependent() && 15002 "Expression evaluator can't be called on a dependent expression."); 15003 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15004 Info.InConstantContext = InConstantContext; 15005 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 15006 } 15007 15008 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 15009 SideEffectsKind AllowSideEffects, 15010 bool InConstantContext) const { 15011 assert(!isValueDependent() && 15012 "Expression evaluator can't be called on a dependent expression."); 15013 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15014 Info.InConstantContext = InConstantContext; 15015 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 15016 } 15017 15018 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 15019 SideEffectsKind AllowSideEffects, 15020 bool InConstantContext) const { 15021 assert(!isValueDependent() && 15022 "Expression evaluator can't be called on a dependent expression."); 15023 15024 if (!getType()->isRealFloatingType()) 15025 return false; 15026 15027 EvalResult ExprResult; 15028 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 15029 !ExprResult.Val.isFloat() || 15030 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15031 return false; 15032 15033 Result = ExprResult.Val.getFloat(); 15034 return true; 15035 } 15036 15037 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 15038 bool InConstantContext) const { 15039 assert(!isValueDependent() && 15040 "Expression evaluator can't be called on a dependent expression."); 15041 15042 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 15043 Info.InConstantContext = InConstantContext; 15044 LValue LV; 15045 CheckedTemporaries CheckedTemps; 15046 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 15047 Result.HasSideEffects || 15048 !CheckLValueConstantExpression(Info, getExprLoc(), 15049 Ctx.getLValueReferenceType(getType()), LV, 15050 ConstantExprKind::Normal, CheckedTemps)) 15051 return false; 15052 15053 LV.moveInto(Result.Val); 15054 return true; 15055 } 15056 15057 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 15058 APValue DestroyedValue, QualType Type, 15059 SourceLocation Loc, Expr::EvalStatus &EStatus, 15060 bool IsConstantDestruction) { 15061 EvalInfo Info(Ctx, EStatus, 15062 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 15063 : EvalInfo::EM_ConstantFold); 15064 Info.setEvaluatingDecl(Base, DestroyedValue, 15065 EvalInfo::EvaluatingDeclKind::Dtor); 15066 Info.InConstantContext = IsConstantDestruction; 15067 15068 LValue LVal; 15069 LVal.set(Base); 15070 15071 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 15072 EStatus.HasSideEffects) 15073 return false; 15074 15075 if (!Info.discardCleanups()) 15076 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15077 15078 return true; 15079 } 15080 15081 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 15082 ConstantExprKind Kind) const { 15083 assert(!isValueDependent() && 15084 "Expression evaluator can't be called on a dependent expression."); 15085 15086 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 15087 EvalInfo Info(Ctx, Result, EM); 15088 Info.InConstantContext = true; 15089 15090 // The type of the object we're initializing is 'const T' for a class NTTP. 15091 QualType T = getType(); 15092 if (Kind == ConstantExprKind::ClassTemplateArgument) 15093 T.addConst(); 15094 15095 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 15096 // represent the result of the evaluation. CheckConstantExpression ensures 15097 // this doesn't escape. 15098 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 15099 APValue::LValueBase Base(&BaseMTE); 15100 15101 Info.setEvaluatingDecl(Base, Result.Val); 15102 LValue LVal; 15103 LVal.set(Base); 15104 15105 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 15106 return false; 15107 15108 if (!Info.discardCleanups()) 15109 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15110 15111 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 15112 Result.Val, Kind)) 15113 return false; 15114 if (!CheckMemoryLeaks(Info)) 15115 return false; 15116 15117 // If this is a class template argument, it's required to have constant 15118 // destruction too. 15119 if (Kind == ConstantExprKind::ClassTemplateArgument && 15120 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 15121 true) || 15122 Result.HasSideEffects)) { 15123 // FIXME: Prefix a note to indicate that the problem is lack of constant 15124 // destruction. 15125 return false; 15126 } 15127 15128 return true; 15129 } 15130 15131 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 15132 const VarDecl *VD, 15133 SmallVectorImpl<PartialDiagnosticAt> &Notes, 15134 bool IsConstantInitialization) const { 15135 assert(!isValueDependent() && 15136 "Expression evaluator can't be called on a dependent expression."); 15137 15138 // FIXME: Evaluating initializers for large array and record types can cause 15139 // performance problems. Only do so in C++11 for now. 15140 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 15141 !Ctx.getLangOpts().CPlusPlus11) 15142 return false; 15143 15144 Expr::EvalStatus EStatus; 15145 EStatus.Diag = &Notes; 15146 15147 EvalInfo Info(Ctx, EStatus, 15148 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 15149 ? EvalInfo::EM_ConstantExpression 15150 : EvalInfo::EM_ConstantFold); 15151 Info.setEvaluatingDecl(VD, Value); 15152 Info.InConstantContext = IsConstantInitialization; 15153 15154 SourceLocation DeclLoc = VD->getLocation(); 15155 QualType DeclTy = VD->getType(); 15156 15157 if (Info.EnableNewConstInterp) { 15158 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 15159 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 15160 return false; 15161 } else { 15162 LValue LVal; 15163 LVal.set(VD); 15164 15165 if (!EvaluateInPlace(Value, Info, LVal, this, 15166 /*AllowNonLiteralTypes=*/true) || 15167 EStatus.HasSideEffects) 15168 return false; 15169 15170 // At this point, any lifetime-extended temporaries are completely 15171 // initialized. 15172 Info.performLifetimeExtension(); 15173 15174 if (!Info.discardCleanups()) 15175 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15176 } 15177 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 15178 ConstantExprKind::Normal) && 15179 CheckMemoryLeaks(Info); 15180 } 15181 15182 bool VarDecl::evaluateDestruction( 15183 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15184 Expr::EvalStatus EStatus; 15185 EStatus.Diag = &Notes; 15186 15187 // Only treat the destruction as constant destruction if we formally have 15188 // constant initialization (or are usable in a constant expression). 15189 bool IsConstantDestruction = hasConstantInitialization(); 15190 15191 // Make a copy of the value for the destructor to mutate, if we know it. 15192 // Otherwise, treat the value as default-initialized; if the destructor works 15193 // anyway, then the destruction is constant (and must be essentially empty). 15194 APValue DestroyedValue; 15195 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 15196 DestroyedValue = *getEvaluatedValue(); 15197 else if (!getDefaultInitValue(getType(), DestroyedValue)) 15198 return false; 15199 15200 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 15201 getType(), getLocation(), EStatus, 15202 IsConstantDestruction) || 15203 EStatus.HasSideEffects) 15204 return false; 15205 15206 ensureEvaluatedStmt()->HasConstantDestruction = true; 15207 return true; 15208 } 15209 15210 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 15211 /// constant folded, but discard the result. 15212 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 15213 assert(!isValueDependent() && 15214 "Expression evaluator can't be called on a dependent expression."); 15215 15216 EvalResult Result; 15217 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 15218 !hasUnacceptableSideEffect(Result, SEK); 15219 } 15220 15221 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 15222 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15223 assert(!isValueDependent() && 15224 "Expression evaluator can't be called on a dependent expression."); 15225 15226 EvalResult EVResult; 15227 EVResult.Diag = Diag; 15228 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15229 Info.InConstantContext = true; 15230 15231 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 15232 (void)Result; 15233 assert(Result && "Could not evaluate expression"); 15234 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15235 15236 return EVResult.Val.getInt(); 15237 } 15238 15239 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 15240 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15241 assert(!isValueDependent() && 15242 "Expression evaluator can't be called on a dependent expression."); 15243 15244 EvalResult EVResult; 15245 EVResult.Diag = Diag; 15246 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15247 Info.InConstantContext = true; 15248 Info.CheckingForUndefinedBehavior = true; 15249 15250 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15251 (void)Result; 15252 assert(Result && "Could not evaluate expression"); 15253 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15254 15255 return EVResult.Val.getInt(); 15256 } 15257 15258 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15259 assert(!isValueDependent() && 15260 "Expression evaluator can't be called on a dependent expression."); 15261 15262 bool IsConst; 15263 EvalResult EVResult; 15264 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15265 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15266 Info.CheckingForUndefinedBehavior = true; 15267 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15268 } 15269 } 15270 15271 bool Expr::EvalResult::isGlobalLValue() const { 15272 assert(Val.isLValue()); 15273 return IsGlobalLValue(Val.getLValueBase()); 15274 } 15275 15276 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15277 /// an integer constant expression. 15278 15279 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15280 /// comma, etc 15281 15282 // CheckICE - This function does the fundamental ICE checking: the returned 15283 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15284 // and a (possibly null) SourceLocation indicating the location of the problem. 15285 // 15286 // Note that to reduce code duplication, this helper does no evaluation 15287 // itself; the caller checks whether the expression is evaluatable, and 15288 // in the rare cases where CheckICE actually cares about the evaluated 15289 // value, it calls into Evaluate. 15290 15291 namespace { 15292 15293 enum ICEKind { 15294 /// This expression is an ICE. 15295 IK_ICE, 15296 /// This expression is not an ICE, but if it isn't evaluated, it's 15297 /// a legal subexpression for an ICE. This return value is used to handle 15298 /// the comma operator in C99 mode, and non-constant subexpressions. 15299 IK_ICEIfUnevaluated, 15300 /// This expression is not an ICE, and is not a legal subexpression for one. 15301 IK_NotICE 15302 }; 15303 15304 struct ICEDiag { 15305 ICEKind Kind; 15306 SourceLocation Loc; 15307 15308 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15309 }; 15310 15311 } 15312 15313 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15314 15315 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15316 15317 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15318 Expr::EvalResult EVResult; 15319 Expr::EvalStatus Status; 15320 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15321 15322 Info.InConstantContext = true; 15323 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15324 !EVResult.Val.isInt()) 15325 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15326 15327 return NoDiag(); 15328 } 15329 15330 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15331 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15332 if (!E->getType()->isIntegralOrEnumerationType()) 15333 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15334 15335 switch (E->getStmtClass()) { 15336 #define ABSTRACT_STMT(Node) 15337 #define STMT(Node, Base) case Expr::Node##Class: 15338 #define EXPR(Node, Base) 15339 #include "clang/AST/StmtNodes.inc" 15340 case Expr::PredefinedExprClass: 15341 case Expr::FloatingLiteralClass: 15342 case Expr::ImaginaryLiteralClass: 15343 case Expr::StringLiteralClass: 15344 case Expr::ArraySubscriptExprClass: 15345 case Expr::MatrixSubscriptExprClass: 15346 case Expr::OMPArraySectionExprClass: 15347 case Expr::OMPArrayShapingExprClass: 15348 case Expr::OMPIteratorExprClass: 15349 case Expr::MemberExprClass: 15350 case Expr::CompoundAssignOperatorClass: 15351 case Expr::CompoundLiteralExprClass: 15352 case Expr::ExtVectorElementExprClass: 15353 case Expr::DesignatedInitExprClass: 15354 case Expr::ArrayInitLoopExprClass: 15355 case Expr::ArrayInitIndexExprClass: 15356 case Expr::NoInitExprClass: 15357 case Expr::DesignatedInitUpdateExprClass: 15358 case Expr::ImplicitValueInitExprClass: 15359 case Expr::ParenListExprClass: 15360 case Expr::VAArgExprClass: 15361 case Expr::AddrLabelExprClass: 15362 case Expr::StmtExprClass: 15363 case Expr::CXXMemberCallExprClass: 15364 case Expr::CUDAKernelCallExprClass: 15365 case Expr::CXXAddrspaceCastExprClass: 15366 case Expr::CXXDynamicCastExprClass: 15367 case Expr::CXXTypeidExprClass: 15368 case Expr::CXXUuidofExprClass: 15369 case Expr::MSPropertyRefExprClass: 15370 case Expr::MSPropertySubscriptExprClass: 15371 case Expr::CXXNullPtrLiteralExprClass: 15372 case Expr::UserDefinedLiteralClass: 15373 case Expr::CXXThisExprClass: 15374 case Expr::CXXThrowExprClass: 15375 case Expr::CXXNewExprClass: 15376 case Expr::CXXDeleteExprClass: 15377 case Expr::CXXPseudoDestructorExprClass: 15378 case Expr::UnresolvedLookupExprClass: 15379 case Expr::TypoExprClass: 15380 case Expr::RecoveryExprClass: 15381 case Expr::DependentScopeDeclRefExprClass: 15382 case Expr::CXXConstructExprClass: 15383 case Expr::CXXInheritedCtorInitExprClass: 15384 case Expr::CXXStdInitializerListExprClass: 15385 case Expr::CXXBindTemporaryExprClass: 15386 case Expr::ExprWithCleanupsClass: 15387 case Expr::CXXTemporaryObjectExprClass: 15388 case Expr::CXXUnresolvedConstructExprClass: 15389 case Expr::CXXDependentScopeMemberExprClass: 15390 case Expr::UnresolvedMemberExprClass: 15391 case Expr::ObjCStringLiteralClass: 15392 case Expr::ObjCBoxedExprClass: 15393 case Expr::ObjCArrayLiteralClass: 15394 case Expr::ObjCDictionaryLiteralClass: 15395 case Expr::ObjCEncodeExprClass: 15396 case Expr::ObjCMessageExprClass: 15397 case Expr::ObjCSelectorExprClass: 15398 case Expr::ObjCProtocolExprClass: 15399 case Expr::ObjCIvarRefExprClass: 15400 case Expr::ObjCPropertyRefExprClass: 15401 case Expr::ObjCSubscriptRefExprClass: 15402 case Expr::ObjCIsaExprClass: 15403 case Expr::ObjCAvailabilityCheckExprClass: 15404 case Expr::ShuffleVectorExprClass: 15405 case Expr::ConvertVectorExprClass: 15406 case Expr::BlockExprClass: 15407 case Expr::NoStmtClass: 15408 case Expr::OpaqueValueExprClass: 15409 case Expr::PackExpansionExprClass: 15410 case Expr::SubstNonTypeTemplateParmPackExprClass: 15411 case Expr::FunctionParmPackExprClass: 15412 case Expr::AsTypeExprClass: 15413 case Expr::ObjCIndirectCopyRestoreExprClass: 15414 case Expr::MaterializeTemporaryExprClass: 15415 case Expr::PseudoObjectExprClass: 15416 case Expr::AtomicExprClass: 15417 case Expr::LambdaExprClass: 15418 case Expr::CXXFoldExprClass: 15419 case Expr::CoawaitExprClass: 15420 case Expr::DependentCoawaitExprClass: 15421 case Expr::CoyieldExprClass: 15422 case Expr::SYCLUniqueStableNameExprClass: 15423 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15424 15425 case Expr::InitListExprClass: { 15426 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15427 // form "T x = { a };" is equivalent to "T x = a;". 15428 // Unless we're initializing a reference, T is a scalar as it is known to be 15429 // of integral or enumeration type. 15430 if (E->isPRValue()) 15431 if (cast<InitListExpr>(E)->getNumInits() == 1) 15432 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15433 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15434 } 15435 15436 case Expr::SizeOfPackExprClass: 15437 case Expr::GNUNullExprClass: 15438 case Expr::SourceLocExprClass: 15439 return NoDiag(); 15440 15441 case Expr::SubstNonTypeTemplateParmExprClass: 15442 return 15443 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15444 15445 case Expr::ConstantExprClass: 15446 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15447 15448 case Expr::ParenExprClass: 15449 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15450 case Expr::GenericSelectionExprClass: 15451 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15452 case Expr::IntegerLiteralClass: 15453 case Expr::FixedPointLiteralClass: 15454 case Expr::CharacterLiteralClass: 15455 case Expr::ObjCBoolLiteralExprClass: 15456 case Expr::CXXBoolLiteralExprClass: 15457 case Expr::CXXScalarValueInitExprClass: 15458 case Expr::TypeTraitExprClass: 15459 case Expr::ConceptSpecializationExprClass: 15460 case Expr::RequiresExprClass: 15461 case Expr::ArrayTypeTraitExprClass: 15462 case Expr::ExpressionTraitExprClass: 15463 case Expr::CXXNoexceptExprClass: 15464 return NoDiag(); 15465 case Expr::CallExprClass: 15466 case Expr::CXXOperatorCallExprClass: { 15467 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15468 // constant expressions, but they can never be ICEs because an ICE cannot 15469 // contain an operand of (pointer to) function type. 15470 const CallExpr *CE = cast<CallExpr>(E); 15471 if (CE->getBuiltinCallee()) 15472 return CheckEvalInICE(E, Ctx); 15473 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15474 } 15475 case Expr::CXXRewrittenBinaryOperatorClass: 15476 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15477 Ctx); 15478 case Expr::DeclRefExprClass: { 15479 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15480 if (isa<EnumConstantDecl>(D)) 15481 return NoDiag(); 15482 15483 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15484 // integer variables in constant expressions: 15485 // 15486 // C++ 7.1.5.1p2 15487 // A variable of non-volatile const-qualified integral or enumeration 15488 // type initialized by an ICE can be used in ICEs. 15489 // 15490 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15491 // that mode, use of reference variables should not be allowed. 15492 const VarDecl *VD = dyn_cast<VarDecl>(D); 15493 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15494 !VD->getType()->isReferenceType()) 15495 return NoDiag(); 15496 15497 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15498 } 15499 case Expr::UnaryOperatorClass: { 15500 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15501 switch (Exp->getOpcode()) { 15502 case UO_PostInc: 15503 case UO_PostDec: 15504 case UO_PreInc: 15505 case UO_PreDec: 15506 case UO_AddrOf: 15507 case UO_Deref: 15508 case UO_Coawait: 15509 // C99 6.6/3 allows increment and decrement within unevaluated 15510 // subexpressions of constant expressions, but they can never be ICEs 15511 // because an ICE cannot contain an lvalue operand. 15512 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15513 case UO_Extension: 15514 case UO_LNot: 15515 case UO_Plus: 15516 case UO_Minus: 15517 case UO_Not: 15518 case UO_Real: 15519 case UO_Imag: 15520 return CheckICE(Exp->getSubExpr(), Ctx); 15521 } 15522 llvm_unreachable("invalid unary operator class"); 15523 } 15524 case Expr::OffsetOfExprClass: { 15525 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15526 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15527 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15528 // compliance: we should warn earlier for offsetof expressions with 15529 // array subscripts that aren't ICEs, and if the array subscripts 15530 // are ICEs, the value of the offsetof must be an integer constant. 15531 return CheckEvalInICE(E, Ctx); 15532 } 15533 case Expr::UnaryExprOrTypeTraitExprClass: { 15534 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15535 if ((Exp->getKind() == UETT_SizeOf) && 15536 Exp->getTypeOfArgument()->isVariableArrayType()) 15537 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15538 return NoDiag(); 15539 } 15540 case Expr::BinaryOperatorClass: { 15541 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15542 switch (Exp->getOpcode()) { 15543 case BO_PtrMemD: 15544 case BO_PtrMemI: 15545 case BO_Assign: 15546 case BO_MulAssign: 15547 case BO_DivAssign: 15548 case BO_RemAssign: 15549 case BO_AddAssign: 15550 case BO_SubAssign: 15551 case BO_ShlAssign: 15552 case BO_ShrAssign: 15553 case BO_AndAssign: 15554 case BO_XorAssign: 15555 case BO_OrAssign: 15556 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15557 // constant expressions, but they can never be ICEs because an ICE cannot 15558 // contain an lvalue operand. 15559 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15560 15561 case BO_Mul: 15562 case BO_Div: 15563 case BO_Rem: 15564 case BO_Add: 15565 case BO_Sub: 15566 case BO_Shl: 15567 case BO_Shr: 15568 case BO_LT: 15569 case BO_GT: 15570 case BO_LE: 15571 case BO_GE: 15572 case BO_EQ: 15573 case BO_NE: 15574 case BO_And: 15575 case BO_Xor: 15576 case BO_Or: 15577 case BO_Comma: 15578 case BO_Cmp: { 15579 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15580 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15581 if (Exp->getOpcode() == BO_Div || 15582 Exp->getOpcode() == BO_Rem) { 15583 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15584 // we don't evaluate one. 15585 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15586 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15587 if (REval == 0) 15588 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15589 if (REval.isSigned() && REval.isAllOnes()) { 15590 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15591 if (LEval.isMinSignedValue()) 15592 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15593 } 15594 } 15595 } 15596 if (Exp->getOpcode() == BO_Comma) { 15597 if (Ctx.getLangOpts().C99) { 15598 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15599 // if it isn't evaluated. 15600 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15601 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15602 } else { 15603 // In both C89 and C++, commas in ICEs are illegal. 15604 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15605 } 15606 } 15607 return Worst(LHSResult, RHSResult); 15608 } 15609 case BO_LAnd: 15610 case BO_LOr: { 15611 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15612 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15613 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15614 // Rare case where the RHS has a comma "side-effect"; we need 15615 // to actually check the condition to see whether the side 15616 // with the comma is evaluated. 15617 if ((Exp->getOpcode() == BO_LAnd) != 15618 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15619 return RHSResult; 15620 return NoDiag(); 15621 } 15622 15623 return Worst(LHSResult, RHSResult); 15624 } 15625 } 15626 llvm_unreachable("invalid binary operator kind"); 15627 } 15628 case Expr::ImplicitCastExprClass: 15629 case Expr::CStyleCastExprClass: 15630 case Expr::CXXFunctionalCastExprClass: 15631 case Expr::CXXStaticCastExprClass: 15632 case Expr::CXXReinterpretCastExprClass: 15633 case Expr::CXXConstCastExprClass: 15634 case Expr::ObjCBridgedCastExprClass: { 15635 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15636 if (isa<ExplicitCastExpr>(E)) { 15637 if (const FloatingLiteral *FL 15638 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15639 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15640 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15641 APSInt IgnoredVal(DestWidth, !DestSigned); 15642 bool Ignored; 15643 // If the value does not fit in the destination type, the behavior is 15644 // undefined, so we are not required to treat it as a constant 15645 // expression. 15646 if (FL->getValue().convertToInteger(IgnoredVal, 15647 llvm::APFloat::rmTowardZero, 15648 &Ignored) & APFloat::opInvalidOp) 15649 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15650 return NoDiag(); 15651 } 15652 } 15653 switch (cast<CastExpr>(E)->getCastKind()) { 15654 case CK_LValueToRValue: 15655 case CK_AtomicToNonAtomic: 15656 case CK_NonAtomicToAtomic: 15657 case CK_NoOp: 15658 case CK_IntegralToBoolean: 15659 case CK_IntegralCast: 15660 return CheckICE(SubExpr, Ctx); 15661 default: 15662 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15663 } 15664 } 15665 case Expr::BinaryConditionalOperatorClass: { 15666 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15667 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15668 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15669 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15670 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15671 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15672 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15673 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15674 return FalseResult; 15675 } 15676 case Expr::ConditionalOperatorClass: { 15677 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15678 // If the condition (ignoring parens) is a __builtin_constant_p call, 15679 // then only the true side is actually considered in an integer constant 15680 // expression, and it is fully evaluated. This is an important GNU 15681 // extension. See GCC PR38377 for discussion. 15682 if (const CallExpr *CallCE 15683 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15684 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15685 return CheckEvalInICE(E, Ctx); 15686 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15687 if (CondResult.Kind == IK_NotICE) 15688 return CondResult; 15689 15690 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15691 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15692 15693 if (TrueResult.Kind == IK_NotICE) 15694 return TrueResult; 15695 if (FalseResult.Kind == IK_NotICE) 15696 return FalseResult; 15697 if (CondResult.Kind == IK_ICEIfUnevaluated) 15698 return CondResult; 15699 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15700 return NoDiag(); 15701 // Rare case where the diagnostics depend on which side is evaluated 15702 // Note that if we get here, CondResult is 0, and at least one of 15703 // TrueResult and FalseResult is non-zero. 15704 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15705 return FalseResult; 15706 return TrueResult; 15707 } 15708 case Expr::CXXDefaultArgExprClass: 15709 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15710 case Expr::CXXDefaultInitExprClass: 15711 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15712 case Expr::ChooseExprClass: { 15713 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15714 } 15715 case Expr::BuiltinBitCastExprClass: { 15716 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15717 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15718 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15719 } 15720 } 15721 15722 llvm_unreachable("Invalid StmtClass!"); 15723 } 15724 15725 /// Evaluate an expression as a C++11 integral constant expression. 15726 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15727 const Expr *E, 15728 llvm::APSInt *Value, 15729 SourceLocation *Loc) { 15730 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15731 if (Loc) *Loc = E->getExprLoc(); 15732 return false; 15733 } 15734 15735 APValue Result; 15736 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15737 return false; 15738 15739 if (!Result.isInt()) { 15740 if (Loc) *Loc = E->getExprLoc(); 15741 return false; 15742 } 15743 15744 if (Value) *Value = Result.getInt(); 15745 return true; 15746 } 15747 15748 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15749 SourceLocation *Loc) const { 15750 assert(!isValueDependent() && 15751 "Expression evaluator can't be called on a dependent expression."); 15752 15753 if (Ctx.getLangOpts().CPlusPlus11) 15754 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15755 15756 ICEDiag D = CheckICE(this, Ctx); 15757 if (D.Kind != IK_ICE) { 15758 if (Loc) *Loc = D.Loc; 15759 return false; 15760 } 15761 return true; 15762 } 15763 15764 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15765 SourceLocation *Loc, 15766 bool isEvaluated) const { 15767 if (isValueDependent()) { 15768 // Expression evaluator can't succeed on a dependent expression. 15769 return None; 15770 } 15771 15772 APSInt Value; 15773 15774 if (Ctx.getLangOpts().CPlusPlus11) { 15775 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15776 return Value; 15777 return None; 15778 } 15779 15780 if (!isIntegerConstantExpr(Ctx, Loc)) 15781 return None; 15782 15783 // The only possible side-effects here are due to UB discovered in the 15784 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15785 // required to treat the expression as an ICE, so we produce the folded 15786 // value. 15787 EvalResult ExprResult; 15788 Expr::EvalStatus Status; 15789 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15790 Info.InConstantContext = true; 15791 15792 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15793 llvm_unreachable("ICE cannot be evaluated!"); 15794 15795 return ExprResult.Val.getInt(); 15796 } 15797 15798 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15799 assert(!isValueDependent() && 15800 "Expression evaluator can't be called on a dependent expression."); 15801 15802 return CheckICE(this, Ctx).Kind == IK_ICE; 15803 } 15804 15805 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15806 SourceLocation *Loc) const { 15807 assert(!isValueDependent() && 15808 "Expression evaluator can't be called on a dependent expression."); 15809 15810 // We support this checking in C++98 mode in order to diagnose compatibility 15811 // issues. 15812 assert(Ctx.getLangOpts().CPlusPlus); 15813 15814 // Build evaluation settings. 15815 Expr::EvalStatus Status; 15816 SmallVector<PartialDiagnosticAt, 8> Diags; 15817 Status.Diag = &Diags; 15818 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15819 15820 APValue Scratch; 15821 bool IsConstExpr = 15822 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15823 // FIXME: We don't produce a diagnostic for this, but the callers that 15824 // call us on arbitrary full-expressions should generally not care. 15825 Info.discardCleanups() && !Status.HasSideEffects; 15826 15827 if (!Diags.empty()) { 15828 IsConstExpr = false; 15829 if (Loc) *Loc = Diags[0].first; 15830 } else if (!IsConstExpr) { 15831 // FIXME: This shouldn't happen. 15832 if (Loc) *Loc = getExprLoc(); 15833 } 15834 15835 return IsConstExpr; 15836 } 15837 15838 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15839 const FunctionDecl *Callee, 15840 ArrayRef<const Expr*> Args, 15841 const Expr *This) const { 15842 assert(!isValueDependent() && 15843 "Expression evaluator can't be called on a dependent expression."); 15844 15845 Expr::EvalStatus Status; 15846 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15847 Info.InConstantContext = true; 15848 15849 LValue ThisVal; 15850 const LValue *ThisPtr = nullptr; 15851 if (This) { 15852 #ifndef NDEBUG 15853 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15854 assert(MD && "Don't provide `this` for non-methods."); 15855 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15856 #endif 15857 if (!This->isValueDependent() && 15858 EvaluateObjectArgument(Info, This, ThisVal) && 15859 !Info.EvalStatus.HasSideEffects) 15860 ThisPtr = &ThisVal; 15861 15862 // Ignore any side-effects from a failed evaluation. This is safe because 15863 // they can't interfere with any other argument evaluation. 15864 Info.EvalStatus.HasSideEffects = false; 15865 } 15866 15867 CallRef Call = Info.CurrentCall->createCall(Callee); 15868 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15869 I != E; ++I) { 15870 unsigned Idx = I - Args.begin(); 15871 if (Idx >= Callee->getNumParams()) 15872 break; 15873 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15874 if ((*I)->isValueDependent() || 15875 !EvaluateCallArg(PVD, *I, Call, Info) || 15876 Info.EvalStatus.HasSideEffects) { 15877 // If evaluation fails, throw away the argument entirely. 15878 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15879 *Slot = APValue(); 15880 } 15881 15882 // Ignore any side-effects from a failed evaluation. This is safe because 15883 // they can't interfere with any other argument evaluation. 15884 Info.EvalStatus.HasSideEffects = false; 15885 } 15886 15887 // Parameter cleanups happen in the caller and are not part of this 15888 // evaluation. 15889 Info.discardCleanups(); 15890 Info.EvalStatus.HasSideEffects = false; 15891 15892 // Build fake call to Callee. 15893 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15894 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15895 FullExpressionRAII Scope(Info); 15896 return Evaluate(Value, Info, this) && Scope.destroy() && 15897 !Info.EvalStatus.HasSideEffects; 15898 } 15899 15900 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15901 SmallVectorImpl< 15902 PartialDiagnosticAt> &Diags) { 15903 // FIXME: It would be useful to check constexpr function templates, but at the 15904 // moment the constant expression evaluator cannot cope with the non-rigorous 15905 // ASTs which we build for dependent expressions. 15906 if (FD->isDependentContext()) 15907 return true; 15908 15909 Expr::EvalStatus Status; 15910 Status.Diag = &Diags; 15911 15912 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15913 Info.InConstantContext = true; 15914 Info.CheckingPotentialConstantExpression = true; 15915 15916 // The constexpr VM attempts to compile all methods to bytecode here. 15917 if (Info.EnableNewConstInterp) { 15918 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15919 return Diags.empty(); 15920 } 15921 15922 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15923 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15924 15925 // Fabricate an arbitrary expression on the stack and pretend that it 15926 // is a temporary being used as the 'this' pointer. 15927 LValue This; 15928 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15929 This.set({&VIE, Info.CurrentCall->Index}); 15930 15931 ArrayRef<const Expr*> Args; 15932 15933 APValue Scratch; 15934 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15935 // Evaluate the call as a constant initializer, to allow the construction 15936 // of objects of non-literal types. 15937 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15938 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15939 } else { 15940 SourceLocation Loc = FD->getLocation(); 15941 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15942 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15943 } 15944 15945 return Diags.empty(); 15946 } 15947 15948 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15949 const FunctionDecl *FD, 15950 SmallVectorImpl< 15951 PartialDiagnosticAt> &Diags) { 15952 assert(!E->isValueDependent() && 15953 "Expression evaluator can't be called on a dependent expression."); 15954 15955 Expr::EvalStatus Status; 15956 Status.Diag = &Diags; 15957 15958 EvalInfo Info(FD->getASTContext(), Status, 15959 EvalInfo::EM_ConstantExpressionUnevaluated); 15960 Info.InConstantContext = true; 15961 Info.CheckingPotentialConstantExpression = true; 15962 15963 // Fabricate a call stack frame to give the arguments a plausible cover story. 15964 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15965 15966 APValue ResultScratch; 15967 Evaluate(ResultScratch, Info, E); 15968 return Diags.empty(); 15969 } 15970 15971 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15972 unsigned Type) const { 15973 if (!getType()->isPointerType()) 15974 return false; 15975 15976 Expr::EvalStatus Status; 15977 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15978 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15979 } 15980 15981 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 15982 EvalInfo &Info) { 15983 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 15984 return false; 15985 15986 LValue String; 15987 15988 if (!EvaluatePointer(E, String, Info)) 15989 return false; 15990 15991 QualType CharTy = E->getType()->getPointeeType(); 15992 15993 // Fast path: if it's a string literal, search the string value. 15994 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 15995 String.getLValueBase().dyn_cast<const Expr *>())) { 15996 StringRef Str = S->getBytes(); 15997 int64_t Off = String.Offset.getQuantity(); 15998 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 15999 S->getCharByteWidth() == 1 && 16000 // FIXME: Add fast-path for wchar_t too. 16001 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 16002 Str = Str.substr(Off); 16003 16004 StringRef::size_type Pos = Str.find(0); 16005 if (Pos != StringRef::npos) 16006 Str = Str.substr(0, Pos); 16007 16008 Result = Str.size(); 16009 return true; 16010 } 16011 16012 // Fall through to slow path. 16013 } 16014 16015 // Slow path: scan the bytes of the string looking for the terminating 0. 16016 for (uint64_t Strlen = 0; /**/; ++Strlen) { 16017 APValue Char; 16018 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 16019 !Char.isInt()) 16020 return false; 16021 if (!Char.getInt()) { 16022 Result = Strlen; 16023 return true; 16024 } 16025 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 16026 return false; 16027 } 16028 } 16029 16030 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 16031 Expr::EvalStatus Status; 16032 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 16033 return EvaluateBuiltinStrLen(this, Result, Info); 16034 } 16035