1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 return B.getType(); 83 } 84 85 /// Get an LValue path entry, which is known to not be an array index, as a 86 /// field declaration. 87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 89 } 90 /// Get an LValue path entry, which is known to not be an array index, as a 91 /// base class declaration. 92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 94 } 95 /// Determine whether this LValue path entry for a base class names a virtual 96 /// base class. 97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 98 return E.getAsBaseOrMember().getInt(); 99 } 100 101 /// Given an expression, determine the type used to store the result of 102 /// evaluating that expression. 103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 104 if (E->isPRValue()) 105 return E->getType(); 106 return Ctx.getLValueReferenceType(E->getType()); 107 } 108 109 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 111 if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) 112 return DirectCallee->getAttr<AllocSizeAttr>(); 113 if (const Decl *IndirectCallee = CE->getCalleeDecl()) 114 return IndirectCallee->getAttr<AllocSizeAttr>(); 115 return nullptr; 116 } 117 118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 119 /// This will look through a single cast. 120 /// 121 /// Returns null if we couldn't unwrap a function with alloc_size. 122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 123 if (!E->getType()->isPointerType()) 124 return nullptr; 125 126 E = E->IgnoreParens(); 127 // If we're doing a variable assignment from e.g. malloc(N), there will 128 // probably be a cast of some kind. In exotic cases, we might also see a 129 // top-level ExprWithCleanups. Ignore them either way. 130 if (const auto *FE = dyn_cast<FullExpr>(E)) 131 E = FE->getSubExpr()->IgnoreParens(); 132 133 if (const auto *Cast = dyn_cast<CastExpr>(E)) 134 E = Cast->getSubExpr()->IgnoreParens(); 135 136 if (const auto *CE = dyn_cast<CallExpr>(E)) 137 return getAllocSizeAttr(CE) ? CE : nullptr; 138 return nullptr; 139 } 140 141 /// Determines whether or not the given Base contains a call to a function 142 /// with the alloc_size attribute. 143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 144 const auto *E = Base.dyn_cast<const Expr *>(); 145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 146 } 147 148 /// Determines whether the given kind of constant expression is only ever 149 /// used for name mangling. If so, it's permitted to reference things that we 150 /// can't generate code for (in particular, dllimported functions). 151 static bool isForManglingOnly(ConstantExprKind Kind) { 152 switch (Kind) { 153 case ConstantExprKind::Normal: 154 case ConstantExprKind::ClassTemplateArgument: 155 case ConstantExprKind::ImmediateInvocation: 156 // Note that non-type template arguments of class type are emitted as 157 // template parameter objects. 158 return false; 159 160 case ConstantExprKind::NonClassTemplateArgument: 161 return true; 162 } 163 llvm_unreachable("unknown ConstantExprKind"); 164 } 165 166 static bool isTemplateArgument(ConstantExprKind Kind) { 167 switch (Kind) { 168 case ConstantExprKind::Normal: 169 case ConstantExprKind::ImmediateInvocation: 170 return false; 171 172 case ConstantExprKind::ClassTemplateArgument: 173 case ConstantExprKind::NonClassTemplateArgument: 174 return true; 175 } 176 llvm_unreachable("unknown ConstantExprKind"); 177 } 178 179 /// The bound to claim that an array of unknown bound has. 180 /// The value in MostDerivedArraySize is undefined in this case. So, set it 181 /// to an arbitrary value that's likely to loudly break things if it's used. 182 static const uint64_t AssumedSizeForUnsizedArray = 183 std::numeric_limits<uint64_t>::max() / 2; 184 185 /// Determines if an LValue with the given LValueBase will have an unsized 186 /// array in its designator. 187 /// Find the path length and type of the most-derived subobject in the given 188 /// path, and find the size of the containing array, if any. 189 static unsigned 190 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 191 ArrayRef<APValue::LValuePathEntry> Path, 192 uint64_t &ArraySize, QualType &Type, bool &IsArray, 193 bool &FirstEntryIsUnsizedArray) { 194 // This only accepts LValueBases from APValues, and APValues don't support 195 // arrays that lack size info. 196 assert(!isBaseAnAllocSizeCall(Base) && 197 "Unsized arrays shouldn't appear here"); 198 unsigned MostDerivedLength = 0; 199 Type = getType(Base); 200 201 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 202 if (Type->isArrayType()) { 203 const ArrayType *AT = Ctx.getAsArrayType(Type); 204 Type = AT->getElementType(); 205 MostDerivedLength = I + 1; 206 IsArray = true; 207 208 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 209 ArraySize = CAT->getSize().getZExtValue(); 210 } else { 211 assert(I == 0 && "unexpected unsized array designator"); 212 FirstEntryIsUnsizedArray = true; 213 ArraySize = AssumedSizeForUnsizedArray; 214 } 215 } else if (Type->isAnyComplexType()) { 216 const ComplexType *CT = Type->castAs<ComplexType>(); 217 Type = CT->getElementType(); 218 ArraySize = 2; 219 MostDerivedLength = I + 1; 220 IsArray = true; 221 } else if (const FieldDecl *FD = getAsField(Path[I])) { 222 Type = FD->getType(); 223 ArraySize = 0; 224 MostDerivedLength = I + 1; 225 IsArray = false; 226 } else { 227 // Path[I] describes a base class. 228 ArraySize = 0; 229 IsArray = false; 230 } 231 } 232 return MostDerivedLength; 233 } 234 235 /// A path from a glvalue to a subobject of that glvalue. 236 struct SubobjectDesignator { 237 /// True if the subobject was named in a manner not supported by C++11. Such 238 /// lvalues can still be folded, but they are not core constant expressions 239 /// and we cannot perform lvalue-to-rvalue conversions on them. 240 unsigned Invalid : 1; 241 242 /// Is this a pointer one past the end of an object? 243 unsigned IsOnePastTheEnd : 1; 244 245 /// Indicator of whether the first entry is an unsized array. 246 unsigned FirstEntryIsAnUnsizedArray : 1; 247 248 /// Indicator of whether the most-derived object is an array element. 249 unsigned MostDerivedIsArrayElement : 1; 250 251 /// The length of the path to the most-derived object of which this is a 252 /// subobject. 253 unsigned MostDerivedPathLength : 28; 254 255 /// The size of the array of which the most-derived object is an element. 256 /// This will always be 0 if the most-derived object is not an array 257 /// element. 0 is not an indicator of whether or not the most-derived object 258 /// is an array, however, because 0-length arrays are allowed. 259 /// 260 /// If the current array is an unsized array, the value of this is 261 /// undefined. 262 uint64_t MostDerivedArraySize; 263 264 /// The type of the most derived object referred to by this address. 265 QualType MostDerivedType; 266 267 typedef APValue::LValuePathEntry PathEntry; 268 269 /// The entries on the path from the glvalue to the designated subobject. 270 SmallVector<PathEntry, 8> Entries; 271 272 SubobjectDesignator() : Invalid(true) {} 273 274 explicit SubobjectDesignator(QualType T) 275 : Invalid(false), IsOnePastTheEnd(false), 276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 277 MostDerivedPathLength(0), MostDerivedArraySize(0), 278 MostDerivedType(T) {} 279 280 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 281 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 282 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 283 MostDerivedPathLength(0), MostDerivedArraySize(0) { 284 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 285 if (!Invalid) { 286 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 287 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 288 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 289 if (V.getLValueBase()) { 290 bool IsArray = false; 291 bool FirstIsUnsizedArray = false; 292 MostDerivedPathLength = findMostDerivedSubobject( 293 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 294 MostDerivedType, IsArray, FirstIsUnsizedArray); 295 MostDerivedIsArrayElement = IsArray; 296 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 297 } 298 } 299 } 300 301 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 302 unsigned NewLength) { 303 if (Invalid) 304 return; 305 306 assert(Base && "cannot truncate path for null pointer"); 307 assert(NewLength <= Entries.size() && "not a truncation"); 308 309 if (NewLength == Entries.size()) 310 return; 311 Entries.resize(NewLength); 312 313 bool IsArray = false; 314 bool FirstIsUnsizedArray = false; 315 MostDerivedPathLength = findMostDerivedSubobject( 316 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 317 FirstIsUnsizedArray); 318 MostDerivedIsArrayElement = IsArray; 319 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 320 } 321 322 void setInvalid() { 323 Invalid = true; 324 Entries.clear(); 325 } 326 327 /// Determine whether the most derived subobject is an array without a 328 /// known bound. 329 bool isMostDerivedAnUnsizedArray() const { 330 assert(!Invalid && "Calling this makes no sense on invalid designators"); 331 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 332 } 333 334 /// Determine what the most derived array's size is. Results in an assertion 335 /// failure if the most derived array lacks a size. 336 uint64_t getMostDerivedArraySize() const { 337 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 338 return MostDerivedArraySize; 339 } 340 341 /// Determine whether this is a one-past-the-end pointer. 342 bool isOnePastTheEnd() const { 343 assert(!Invalid); 344 if (IsOnePastTheEnd) 345 return true; 346 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 347 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 348 MostDerivedArraySize) 349 return true; 350 return false; 351 } 352 353 /// Get the range of valid index adjustments in the form 354 /// {maximum value that can be subtracted from this pointer, 355 /// maximum value that can be added to this pointer} 356 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 357 if (Invalid || isMostDerivedAnUnsizedArray()) 358 return {0, 0}; 359 360 // [expr.add]p4: For the purposes of these operators, a pointer to a 361 // nonarray object behaves the same as a pointer to the first element of 362 // an array of length one with the type of the object as its element type. 363 bool IsArray = MostDerivedPathLength == Entries.size() && 364 MostDerivedIsArrayElement; 365 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 366 : (uint64_t)IsOnePastTheEnd; 367 uint64_t ArraySize = 368 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 369 return {ArrayIndex, ArraySize - ArrayIndex}; 370 } 371 372 /// Check that this refers to a valid subobject. 373 bool isValidSubobject() const { 374 if (Invalid) 375 return false; 376 return !isOnePastTheEnd(); 377 } 378 /// Check that this refers to a valid subobject, and if not, produce a 379 /// relevant diagnostic and set the designator as invalid. 380 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 381 382 /// Get the type of the designated object. 383 QualType getType(ASTContext &Ctx) const { 384 assert(!Invalid && "invalid designator has no subobject type"); 385 return MostDerivedPathLength == Entries.size() 386 ? MostDerivedType 387 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 388 } 389 390 /// Update this designator to refer to the first element within this array. 391 void addArrayUnchecked(const ConstantArrayType *CAT) { 392 Entries.push_back(PathEntry::ArrayIndex(0)); 393 394 // This is a most-derived object. 395 MostDerivedType = CAT->getElementType(); 396 MostDerivedIsArrayElement = true; 397 MostDerivedArraySize = CAT->getSize().getZExtValue(); 398 MostDerivedPathLength = Entries.size(); 399 } 400 /// Update this designator to refer to the first element within the array of 401 /// elements of type T. This is an array of unknown size. 402 void addUnsizedArrayUnchecked(QualType ElemTy) { 403 Entries.push_back(PathEntry::ArrayIndex(0)); 404 405 MostDerivedType = ElemTy; 406 MostDerivedIsArrayElement = true; 407 // The value in MostDerivedArraySize is undefined in this case. So, set it 408 // to an arbitrary value that's likely to loudly break things if it's 409 // used. 410 MostDerivedArraySize = AssumedSizeForUnsizedArray; 411 MostDerivedPathLength = Entries.size(); 412 } 413 /// Update this designator to refer to the given base or member of this 414 /// object. 415 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 416 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 417 418 // If this isn't a base class, it's a new most-derived object. 419 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 420 MostDerivedType = FD->getType(); 421 MostDerivedIsArrayElement = false; 422 MostDerivedArraySize = 0; 423 MostDerivedPathLength = Entries.size(); 424 } 425 } 426 /// Update this designator to refer to the given complex component. 427 void addComplexUnchecked(QualType EltTy, bool Imag) { 428 Entries.push_back(PathEntry::ArrayIndex(Imag)); 429 430 // This is technically a most-derived object, though in practice this 431 // is unlikely to matter. 432 MostDerivedType = EltTy; 433 MostDerivedIsArrayElement = true; 434 MostDerivedArraySize = 2; 435 MostDerivedPathLength = Entries.size(); 436 } 437 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 438 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 439 const APSInt &N); 440 /// Add N to the address of this subobject. 441 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 442 if (Invalid || !N) return; 443 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 444 if (isMostDerivedAnUnsizedArray()) { 445 diagnoseUnsizedArrayPointerArithmetic(Info, E); 446 // Can't verify -- trust that the user is doing the right thing (or if 447 // not, trust that the caller will catch the bad behavior). 448 // FIXME: Should we reject if this overflows, at least? 449 Entries.back() = PathEntry::ArrayIndex( 450 Entries.back().getAsArrayIndex() + TruncatedN); 451 return; 452 } 453 454 // [expr.add]p4: For the purposes of these operators, a pointer to a 455 // nonarray object behaves the same as a pointer to the first element of 456 // an array of length one with the type of the object as its element type. 457 bool IsArray = MostDerivedPathLength == Entries.size() && 458 MostDerivedIsArrayElement; 459 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 460 : (uint64_t)IsOnePastTheEnd; 461 uint64_t ArraySize = 462 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 463 464 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 465 // Calculate the actual index in a wide enough type, so we can include 466 // it in the note. 467 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 468 (llvm::APInt&)N += ArrayIndex; 469 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 470 diagnosePointerArithmetic(Info, E, N); 471 setInvalid(); 472 return; 473 } 474 475 ArrayIndex += TruncatedN; 476 assert(ArrayIndex <= ArraySize && 477 "bounds check succeeded for out-of-bounds index"); 478 479 if (IsArray) 480 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 481 else 482 IsOnePastTheEnd = (ArrayIndex != 0); 483 } 484 }; 485 486 /// A scope at the end of which an object can need to be destroyed. 487 enum class ScopeKind { 488 Block, 489 FullExpression, 490 Call 491 }; 492 493 /// A reference to a particular call and its arguments. 494 struct CallRef { 495 CallRef() : OrigCallee(), CallIndex(0), Version() {} 496 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 497 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 498 499 explicit operator bool() const { return OrigCallee; } 500 501 /// Get the parameter that the caller initialized, corresponding to the 502 /// given parameter in the callee. 503 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 504 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 505 : PVD; 506 } 507 508 /// The callee at the point where the arguments were evaluated. This might 509 /// be different from the actual callee (a different redeclaration, or a 510 /// virtual override), but this function's parameters are the ones that 511 /// appear in the parameter map. 512 const FunctionDecl *OrigCallee; 513 /// The call index of the frame that holds the argument values. 514 unsigned CallIndex; 515 /// The version of the parameters corresponding to this call. 516 unsigned Version; 517 }; 518 519 /// A stack frame in the constexpr call stack. 520 class CallStackFrame : public interp::Frame { 521 public: 522 EvalInfo &Info; 523 524 /// Parent - The caller of this stack frame. 525 CallStackFrame *Caller; 526 527 /// Callee - The function which was called. 528 const FunctionDecl *Callee; 529 530 /// This - The binding for the this pointer in this call, if any. 531 const LValue *This; 532 533 /// Information on how to find the arguments to this call. Our arguments 534 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 535 /// key and this value as the version. 536 CallRef Arguments; 537 538 /// Source location information about the default argument or default 539 /// initializer expression we're evaluating, if any. 540 CurrentSourceLocExprScope CurSourceLocExprScope; 541 542 // Note that we intentionally use std::map here so that references to 543 // values are stable. 544 typedef std::pair<const void *, unsigned> MapKeyTy; 545 typedef std::map<MapKeyTy, APValue> MapTy; 546 /// Temporaries - Temporary lvalues materialized within this stack frame. 547 MapTy Temporaries; 548 549 /// CallLoc - The location of the call expression for this call. 550 SourceLocation CallLoc; 551 552 /// Index - The call index of this call. 553 unsigned Index; 554 555 /// The stack of integers for tracking version numbers for temporaries. 556 SmallVector<unsigned, 2> TempVersionStack = {1}; 557 unsigned CurTempVersion = TempVersionStack.back(); 558 559 unsigned getTempVersion() const { return TempVersionStack.back(); } 560 561 void pushTempVersion() { 562 TempVersionStack.push_back(++CurTempVersion); 563 } 564 565 void popTempVersion() { 566 TempVersionStack.pop_back(); 567 } 568 569 CallRef createCall(const FunctionDecl *Callee) { 570 return {Callee, Index, ++CurTempVersion}; 571 } 572 573 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 574 // on the overall stack usage of deeply-recursing constexpr evaluations. 575 // (We should cache this map rather than recomputing it repeatedly.) 576 // But let's try this and see how it goes; we can look into caching the map 577 // as a later change. 578 579 /// LambdaCaptureFields - Mapping from captured variables/this to 580 /// corresponding data members in the closure class. 581 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 582 FieldDecl *LambdaThisCaptureField; 583 584 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 585 const FunctionDecl *Callee, const LValue *This, 586 CallRef Arguments); 587 ~CallStackFrame(); 588 589 // Return the temporary for Key whose version number is Version. 590 APValue *getTemporary(const void *Key, unsigned Version) { 591 MapKeyTy KV(Key, Version); 592 auto LB = Temporaries.lower_bound(KV); 593 if (LB != Temporaries.end() && LB->first == KV) 594 return &LB->second; 595 // Pair (Key,Version) wasn't found in the map. Check that no elements 596 // in the map have 'Key' as their key. 597 assert((LB == Temporaries.end() || LB->first.first != Key) && 598 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 599 "Element with key 'Key' found in map"); 600 return nullptr; 601 } 602 603 // Return the current temporary for Key in the map. 604 APValue *getCurrentTemporary(const void *Key) { 605 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 606 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 607 return &std::prev(UB)->second; 608 return nullptr; 609 } 610 611 // Return the version number of the current temporary for Key. 612 unsigned getCurrentTemporaryVersion(const void *Key) const { 613 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 614 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 615 return std::prev(UB)->first.second; 616 return 0; 617 } 618 619 /// Allocate storage for an object of type T in this stack frame. 620 /// Populates LV with a handle to the created object. Key identifies 621 /// the temporary within the stack frame, and must not be reused without 622 /// bumping the temporary version number. 623 template<typename KeyT> 624 APValue &createTemporary(const KeyT *Key, QualType T, 625 ScopeKind Scope, LValue &LV); 626 627 /// Allocate storage for a parameter of a function call made in this frame. 628 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 629 630 void describe(llvm::raw_ostream &OS) override; 631 632 Frame *getCaller() const override { return Caller; } 633 SourceLocation getCallLocation() const override { return CallLoc; } 634 const FunctionDecl *getCallee() const override { return Callee; } 635 636 bool isStdFunction() const { 637 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 638 if (DC->isStdNamespace()) 639 return true; 640 return false; 641 } 642 643 private: 644 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 645 ScopeKind Scope); 646 }; 647 648 /// Temporarily override 'this'. 649 class ThisOverrideRAII { 650 public: 651 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 652 : Frame(Frame), OldThis(Frame.This) { 653 if (Enable) 654 Frame.This = NewThis; 655 } 656 ~ThisOverrideRAII() { 657 Frame.This = OldThis; 658 } 659 private: 660 CallStackFrame &Frame; 661 const LValue *OldThis; 662 }; 663 } 664 665 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 666 const LValue &This, QualType ThisType); 667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 668 APValue::LValueBase LVBase, APValue &Value, 669 QualType T); 670 671 namespace { 672 /// A cleanup, and a flag indicating whether it is lifetime-extended. 673 class Cleanup { 674 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 675 APValue::LValueBase Base; 676 QualType T; 677 678 public: 679 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 680 ScopeKind Scope) 681 : Value(Val, Scope), Base(Base), T(T) {} 682 683 /// Determine whether this cleanup should be performed at the end of the 684 /// given kind of scope. 685 bool isDestroyedAtEndOf(ScopeKind K) const { 686 return (int)Value.getInt() >= (int)K; 687 } 688 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 689 if (RunDestructors) { 690 SourceLocation Loc; 691 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 692 Loc = VD->getLocation(); 693 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 694 Loc = E->getExprLoc(); 695 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 696 } 697 *Value.getPointer() = APValue(); 698 return true; 699 } 700 701 bool hasSideEffect() { 702 return T.isDestructedType(); 703 } 704 }; 705 706 /// A reference to an object whose construction we are currently evaluating. 707 struct ObjectUnderConstruction { 708 APValue::LValueBase Base; 709 ArrayRef<APValue::LValuePathEntry> Path; 710 friend bool operator==(const ObjectUnderConstruction &LHS, 711 const ObjectUnderConstruction &RHS) { 712 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 713 } 714 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 715 return llvm::hash_combine(Obj.Base, Obj.Path); 716 } 717 }; 718 enum class ConstructionPhase { 719 None, 720 Bases, 721 AfterBases, 722 AfterFields, 723 Destroying, 724 DestroyingBases 725 }; 726 } 727 728 namespace llvm { 729 template<> struct DenseMapInfo<ObjectUnderConstruction> { 730 using Base = DenseMapInfo<APValue::LValueBase>; 731 static ObjectUnderConstruction getEmptyKey() { 732 return {Base::getEmptyKey(), {}}; } 733 static ObjectUnderConstruction getTombstoneKey() { 734 return {Base::getTombstoneKey(), {}}; 735 } 736 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 737 return hash_value(Object); 738 } 739 static bool isEqual(const ObjectUnderConstruction &LHS, 740 const ObjectUnderConstruction &RHS) { 741 return LHS == RHS; 742 } 743 }; 744 } 745 746 namespace { 747 /// A dynamically-allocated heap object. 748 struct DynAlloc { 749 /// The value of this heap-allocated object. 750 APValue Value; 751 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 752 /// or a CallExpr (the latter is for direct calls to operator new inside 753 /// std::allocator<T>::allocate). 754 const Expr *AllocExpr = nullptr; 755 756 enum Kind { 757 New, 758 ArrayNew, 759 StdAllocator 760 }; 761 762 /// Get the kind of the allocation. This must match between allocation 763 /// and deallocation. 764 Kind getKind() const { 765 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 766 return NE->isArray() ? ArrayNew : New; 767 assert(isa<CallExpr>(AllocExpr)); 768 return StdAllocator; 769 } 770 }; 771 772 struct DynAllocOrder { 773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 774 return L.getIndex() < R.getIndex(); 775 } 776 }; 777 778 /// EvalInfo - This is a private struct used by the evaluator to capture 779 /// information about a subexpression as it is folded. It retains information 780 /// about the AST context, but also maintains information about the folded 781 /// expression. 782 /// 783 /// If an expression could be evaluated, it is still possible it is not a C 784 /// "integer constant expression" or constant expression. If not, this struct 785 /// captures information about how and why not. 786 /// 787 /// One bit of information passed *into* the request for constant folding 788 /// indicates whether the subexpression is "evaluated" or not according to C 789 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 790 /// evaluate the expression regardless of what the RHS is, but C only allows 791 /// certain things in certain situations. 792 class EvalInfo : public interp::State { 793 public: 794 ASTContext &Ctx; 795 796 /// EvalStatus - Contains information about the evaluation. 797 Expr::EvalStatus &EvalStatus; 798 799 /// CurrentCall - The top of the constexpr call stack. 800 CallStackFrame *CurrentCall; 801 802 /// CallStackDepth - The number of calls in the call stack right now. 803 unsigned CallStackDepth; 804 805 /// NextCallIndex - The next call index to assign. 806 unsigned NextCallIndex; 807 808 /// StepsLeft - The remaining number of evaluation steps we're permitted 809 /// to perform. This is essentially a limit for the number of statements 810 /// we will evaluate. 811 unsigned StepsLeft; 812 813 /// Enable the experimental new constant interpreter. If an expression is 814 /// not supported by the interpreter, an error is triggered. 815 bool EnableNewConstInterp; 816 817 /// BottomFrame - The frame in which evaluation started. This must be 818 /// initialized after CurrentCall and CallStackDepth. 819 CallStackFrame BottomFrame; 820 821 /// A stack of values whose lifetimes end at the end of some surrounding 822 /// evaluation frame. 823 llvm::SmallVector<Cleanup, 16> CleanupStack; 824 825 /// EvaluatingDecl - This is the declaration whose initializer is being 826 /// evaluated, if any. 827 APValue::LValueBase EvaluatingDecl; 828 829 enum class EvaluatingDeclKind { 830 None, 831 /// We're evaluating the construction of EvaluatingDecl. 832 Ctor, 833 /// We're evaluating the destruction of EvaluatingDecl. 834 Dtor, 835 }; 836 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 837 838 /// EvaluatingDeclValue - This is the value being constructed for the 839 /// declaration whose initializer is being evaluated, if any. 840 APValue *EvaluatingDeclValue; 841 842 /// Set of objects that are currently being constructed. 843 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 844 ObjectsUnderConstruction; 845 846 /// Current heap allocations, along with the location where each was 847 /// allocated. We use std::map here because we need stable addresses 848 /// for the stored APValues. 849 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 850 851 /// The number of heap allocations performed so far in this evaluation. 852 unsigned NumHeapAllocs = 0; 853 854 struct EvaluatingConstructorRAII { 855 EvalInfo &EI; 856 ObjectUnderConstruction Object; 857 bool DidInsert; 858 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 859 bool HasBases) 860 : EI(EI), Object(Object) { 861 DidInsert = 862 EI.ObjectsUnderConstruction 863 .insert({Object, HasBases ? ConstructionPhase::Bases 864 : ConstructionPhase::AfterBases}) 865 .second; 866 } 867 void finishedConstructingBases() { 868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 869 } 870 void finishedConstructingFields() { 871 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 872 } 873 ~EvaluatingConstructorRAII() { 874 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 875 } 876 }; 877 878 struct EvaluatingDestructorRAII { 879 EvalInfo &EI; 880 ObjectUnderConstruction Object; 881 bool DidInsert; 882 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 883 : EI(EI), Object(Object) { 884 DidInsert = EI.ObjectsUnderConstruction 885 .insert({Object, ConstructionPhase::Destroying}) 886 .second; 887 } 888 void startedDestroyingBases() { 889 EI.ObjectsUnderConstruction[Object] = 890 ConstructionPhase::DestroyingBases; 891 } 892 ~EvaluatingDestructorRAII() { 893 if (DidInsert) 894 EI.ObjectsUnderConstruction.erase(Object); 895 } 896 }; 897 898 ConstructionPhase 899 isEvaluatingCtorDtor(APValue::LValueBase Base, 900 ArrayRef<APValue::LValuePathEntry> Path) { 901 return ObjectsUnderConstruction.lookup({Base, Path}); 902 } 903 904 /// If we're currently speculatively evaluating, the outermost call stack 905 /// depth at which we can mutate state, otherwise 0. 906 unsigned SpeculativeEvaluationDepth = 0; 907 908 /// The current array initialization index, if we're performing array 909 /// initialization. 910 uint64_t ArrayInitIndex = -1; 911 912 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 913 /// notes attached to it will also be stored, otherwise they will not be. 914 bool HasActiveDiagnostic; 915 916 /// Have we emitted a diagnostic explaining why we couldn't constant 917 /// fold (not just why it's not strictly a constant expression)? 918 bool HasFoldFailureDiagnostic; 919 920 /// Whether or not we're in a context where the front end requires a 921 /// constant value. 922 bool InConstantContext; 923 924 /// Whether we're checking that an expression is a potential constant 925 /// expression. If so, do not fail on constructs that could become constant 926 /// later on (such as a use of an undefined global). 927 bool CheckingPotentialConstantExpression = false; 928 929 /// Whether we're checking for an expression that has undefined behavior. 930 /// If so, we will produce warnings if we encounter an operation that is 931 /// always undefined. 932 /// 933 /// Note that we still need to evaluate the expression normally when this 934 /// is set; this is used when evaluating ICEs in C. 935 bool CheckingForUndefinedBehavior = false; 936 937 enum EvaluationMode { 938 /// Evaluate as a constant expression. Stop if we find that the expression 939 /// is not a constant expression. 940 EM_ConstantExpression, 941 942 /// Evaluate as a constant expression. Stop if we find that the expression 943 /// is not a constant expression. Some expressions can be retried in the 944 /// optimizer if we don't constant fold them here, but in an unevaluated 945 /// context we try to fold them immediately since the optimizer never 946 /// gets a chance to look at it. 947 EM_ConstantExpressionUnevaluated, 948 949 /// Fold the expression to a constant. Stop if we hit a side-effect that 950 /// we can't model. 951 EM_ConstantFold, 952 953 /// Evaluate in any way we know how. Don't worry about side-effects that 954 /// can't be modeled. 955 EM_IgnoreSideEffects, 956 } EvalMode; 957 958 /// Are we checking whether the expression is a potential constant 959 /// expression? 960 bool checkingPotentialConstantExpression() const override { 961 return CheckingPotentialConstantExpression; 962 } 963 964 /// Are we checking an expression for overflow? 965 // FIXME: We should check for any kind of undefined or suspicious behavior 966 // in such constructs, not just overflow. 967 bool checkingForUndefinedBehavior() const override { 968 return CheckingForUndefinedBehavior; 969 } 970 971 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 972 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 973 CallStackDepth(0), NextCallIndex(1), 974 StepsLeft(C.getLangOpts().ConstexprStepLimit), 975 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 976 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 977 EvaluatingDecl((const ValueDecl *)nullptr), 978 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 979 HasFoldFailureDiagnostic(false), InConstantContext(false), 980 EvalMode(Mode) {} 981 982 ~EvalInfo() { 983 discardCleanups(); 984 } 985 986 ASTContext &getCtx() const override { return Ctx; } 987 988 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 989 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 990 EvaluatingDecl = Base; 991 IsEvaluatingDecl = EDK; 992 EvaluatingDeclValue = &Value; 993 } 994 995 bool CheckCallLimit(SourceLocation Loc) { 996 // Don't perform any constexpr calls (other than the call we're checking) 997 // when checking a potential constant expression. 998 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 999 return false; 1000 if (NextCallIndex == 0) { 1001 // NextCallIndex has wrapped around. 1002 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1003 return false; 1004 } 1005 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1006 return true; 1007 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1008 << getLangOpts().ConstexprCallDepth; 1009 return false; 1010 } 1011 1012 std::pair<CallStackFrame *, unsigned> 1013 getCallFrameAndDepth(unsigned CallIndex) { 1014 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1015 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1016 // be null in this loop. 1017 unsigned Depth = CallStackDepth; 1018 CallStackFrame *Frame = CurrentCall; 1019 while (Frame->Index > CallIndex) { 1020 Frame = Frame->Caller; 1021 --Depth; 1022 } 1023 if (Frame->Index == CallIndex) 1024 return {Frame, Depth}; 1025 return {nullptr, 0}; 1026 } 1027 1028 bool nextStep(const Stmt *S) { 1029 if (!StepsLeft) { 1030 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1031 return false; 1032 } 1033 --StepsLeft; 1034 return true; 1035 } 1036 1037 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1038 1039 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1040 Optional<DynAlloc*> Result; 1041 auto It = HeapAllocs.find(DA); 1042 if (It != HeapAllocs.end()) 1043 Result = &It->second; 1044 return Result; 1045 } 1046 1047 /// Get the allocated storage for the given parameter of the given call. 1048 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1049 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1050 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1051 : nullptr; 1052 } 1053 1054 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1055 struct StdAllocatorCaller { 1056 unsigned FrameIndex; 1057 QualType ElemType; 1058 explicit operator bool() const { return FrameIndex != 0; }; 1059 }; 1060 1061 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1062 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1063 Call = Call->Caller) { 1064 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1065 if (!MD) 1066 continue; 1067 const IdentifierInfo *FnII = MD->getIdentifier(); 1068 if (!FnII || !FnII->isStr(FnName)) 1069 continue; 1070 1071 const auto *CTSD = 1072 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1073 if (!CTSD) 1074 continue; 1075 1076 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1077 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1078 if (CTSD->isInStdNamespace() && ClassII && 1079 ClassII->isStr("allocator") && TAL.size() >= 1 && 1080 TAL[0].getKind() == TemplateArgument::Type) 1081 return {Call->Index, TAL[0].getAsType()}; 1082 } 1083 1084 return {}; 1085 } 1086 1087 void performLifetimeExtension() { 1088 // Disable the cleanups for lifetime-extended temporaries. 1089 llvm::erase_if(CleanupStack, [](Cleanup &C) { 1090 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); 1091 }); 1092 } 1093 1094 /// Throw away any remaining cleanups at the end of evaluation. If any 1095 /// cleanups would have had a side-effect, note that as an unmodeled 1096 /// side-effect and return false. Otherwise, return true. 1097 bool discardCleanups() { 1098 for (Cleanup &C : CleanupStack) { 1099 if (C.hasSideEffect() && !noteSideEffect()) { 1100 CleanupStack.clear(); 1101 return false; 1102 } 1103 } 1104 CleanupStack.clear(); 1105 return true; 1106 } 1107 1108 private: 1109 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1110 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1111 1112 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1113 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1114 1115 void setFoldFailureDiagnostic(bool Flag) override { 1116 HasFoldFailureDiagnostic = Flag; 1117 } 1118 1119 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1120 1121 // If we have a prior diagnostic, it will be noting that the expression 1122 // isn't a constant expression. This diagnostic is more important, 1123 // unless we require this evaluation to produce a constant expression. 1124 // 1125 // FIXME: We might want to show both diagnostics to the user in 1126 // EM_ConstantFold mode. 1127 bool hasPriorDiagnostic() override { 1128 if (!EvalStatus.Diag->empty()) { 1129 switch (EvalMode) { 1130 case EM_ConstantFold: 1131 case EM_IgnoreSideEffects: 1132 if (!HasFoldFailureDiagnostic) 1133 break; 1134 // We've already failed to fold something. Keep that diagnostic. 1135 LLVM_FALLTHROUGH; 1136 case EM_ConstantExpression: 1137 case EM_ConstantExpressionUnevaluated: 1138 setActiveDiagnostic(false); 1139 return true; 1140 } 1141 } 1142 return false; 1143 } 1144 1145 unsigned getCallStackDepth() override { return CallStackDepth; } 1146 1147 public: 1148 /// Should we continue evaluation after encountering a side-effect that we 1149 /// couldn't model? 1150 bool keepEvaluatingAfterSideEffect() { 1151 switch (EvalMode) { 1152 case EM_IgnoreSideEffects: 1153 return true; 1154 1155 case EM_ConstantExpression: 1156 case EM_ConstantExpressionUnevaluated: 1157 case EM_ConstantFold: 1158 // By default, assume any side effect might be valid in some other 1159 // evaluation of this expression from a different context. 1160 return checkingPotentialConstantExpression() || 1161 checkingForUndefinedBehavior(); 1162 } 1163 llvm_unreachable("Missed EvalMode case"); 1164 } 1165 1166 /// Note that we have had a side-effect, and determine whether we should 1167 /// keep evaluating. 1168 bool noteSideEffect() { 1169 EvalStatus.HasSideEffects = true; 1170 return keepEvaluatingAfterSideEffect(); 1171 } 1172 1173 /// Should we continue evaluation after encountering undefined behavior? 1174 bool keepEvaluatingAfterUndefinedBehavior() { 1175 switch (EvalMode) { 1176 case EM_IgnoreSideEffects: 1177 case EM_ConstantFold: 1178 return true; 1179 1180 case EM_ConstantExpression: 1181 case EM_ConstantExpressionUnevaluated: 1182 return checkingForUndefinedBehavior(); 1183 } 1184 llvm_unreachable("Missed EvalMode case"); 1185 } 1186 1187 /// Note that we hit something that was technically undefined behavior, but 1188 /// that we can evaluate past it (such as signed overflow or floating-point 1189 /// division by zero.) 1190 bool noteUndefinedBehavior() override { 1191 EvalStatus.HasUndefinedBehavior = true; 1192 return keepEvaluatingAfterUndefinedBehavior(); 1193 } 1194 1195 /// Should we continue evaluation as much as possible after encountering a 1196 /// construct which can't be reduced to a value? 1197 bool keepEvaluatingAfterFailure() const override { 1198 if (!StepsLeft) 1199 return false; 1200 1201 switch (EvalMode) { 1202 case EM_ConstantExpression: 1203 case EM_ConstantExpressionUnevaluated: 1204 case EM_ConstantFold: 1205 case EM_IgnoreSideEffects: 1206 return checkingPotentialConstantExpression() || 1207 checkingForUndefinedBehavior(); 1208 } 1209 llvm_unreachable("Missed EvalMode case"); 1210 } 1211 1212 /// Notes that we failed to evaluate an expression that other expressions 1213 /// directly depend on, and determine if we should keep evaluating. This 1214 /// should only be called if we actually intend to keep evaluating. 1215 /// 1216 /// Call noteSideEffect() instead if we may be able to ignore the value that 1217 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1218 /// 1219 /// (Foo(), 1) // use noteSideEffect 1220 /// (Foo() || true) // use noteSideEffect 1221 /// Foo() + 1 // use noteFailure 1222 LLVM_NODISCARD bool noteFailure() { 1223 // Failure when evaluating some expression often means there is some 1224 // subexpression whose evaluation was skipped. Therefore, (because we 1225 // don't track whether we skipped an expression when unwinding after an 1226 // evaluation failure) every evaluation failure that bubbles up from a 1227 // subexpression implies that a side-effect has potentially happened. We 1228 // skip setting the HasSideEffects flag to true until we decide to 1229 // continue evaluating after that point, which happens here. 1230 bool KeepGoing = keepEvaluatingAfterFailure(); 1231 EvalStatus.HasSideEffects |= KeepGoing; 1232 return KeepGoing; 1233 } 1234 1235 class ArrayInitLoopIndex { 1236 EvalInfo &Info; 1237 uint64_t OuterIndex; 1238 1239 public: 1240 ArrayInitLoopIndex(EvalInfo &Info) 1241 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1242 Info.ArrayInitIndex = 0; 1243 } 1244 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1245 1246 operator uint64_t&() { return Info.ArrayInitIndex; } 1247 }; 1248 }; 1249 1250 /// Object used to treat all foldable expressions as constant expressions. 1251 struct FoldConstant { 1252 EvalInfo &Info; 1253 bool Enabled; 1254 bool HadNoPriorDiags; 1255 EvalInfo::EvaluationMode OldMode; 1256 1257 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1258 : Info(Info), 1259 Enabled(Enabled), 1260 HadNoPriorDiags(Info.EvalStatus.Diag && 1261 Info.EvalStatus.Diag->empty() && 1262 !Info.EvalStatus.HasSideEffects), 1263 OldMode(Info.EvalMode) { 1264 if (Enabled) 1265 Info.EvalMode = EvalInfo::EM_ConstantFold; 1266 } 1267 void keepDiagnostics() { Enabled = false; } 1268 ~FoldConstant() { 1269 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1270 !Info.EvalStatus.HasSideEffects) 1271 Info.EvalStatus.Diag->clear(); 1272 Info.EvalMode = OldMode; 1273 } 1274 }; 1275 1276 /// RAII object used to set the current evaluation mode to ignore 1277 /// side-effects. 1278 struct IgnoreSideEffectsRAII { 1279 EvalInfo &Info; 1280 EvalInfo::EvaluationMode OldMode; 1281 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1282 : Info(Info), OldMode(Info.EvalMode) { 1283 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1284 } 1285 1286 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1287 }; 1288 1289 /// RAII object used to optionally suppress diagnostics and side-effects from 1290 /// a speculative evaluation. 1291 class SpeculativeEvaluationRAII { 1292 EvalInfo *Info = nullptr; 1293 Expr::EvalStatus OldStatus; 1294 unsigned OldSpeculativeEvaluationDepth; 1295 1296 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1297 Info = Other.Info; 1298 OldStatus = Other.OldStatus; 1299 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1300 Other.Info = nullptr; 1301 } 1302 1303 void maybeRestoreState() { 1304 if (!Info) 1305 return; 1306 1307 Info->EvalStatus = OldStatus; 1308 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1309 } 1310 1311 public: 1312 SpeculativeEvaluationRAII() = default; 1313 1314 SpeculativeEvaluationRAII( 1315 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1316 : Info(&Info), OldStatus(Info.EvalStatus), 1317 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1318 Info.EvalStatus.Diag = NewDiag; 1319 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1320 } 1321 1322 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1323 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1324 moveFromAndCancel(std::move(Other)); 1325 } 1326 1327 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1328 maybeRestoreState(); 1329 moveFromAndCancel(std::move(Other)); 1330 return *this; 1331 } 1332 1333 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1334 }; 1335 1336 /// RAII object wrapping a full-expression or block scope, and handling 1337 /// the ending of the lifetime of temporaries created within it. 1338 template<ScopeKind Kind> 1339 class ScopeRAII { 1340 EvalInfo &Info; 1341 unsigned OldStackSize; 1342 public: 1343 ScopeRAII(EvalInfo &Info) 1344 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1345 // Push a new temporary version. This is needed to distinguish between 1346 // temporaries created in different iterations of a loop. 1347 Info.CurrentCall->pushTempVersion(); 1348 } 1349 bool destroy(bool RunDestructors = true) { 1350 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1351 OldStackSize = -1U; 1352 return OK; 1353 } 1354 ~ScopeRAII() { 1355 if (OldStackSize != -1U) 1356 destroy(false); 1357 // Body moved to a static method to encourage the compiler to inline away 1358 // instances of this class. 1359 Info.CurrentCall->popTempVersion(); 1360 } 1361 private: 1362 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1363 unsigned OldStackSize) { 1364 assert(OldStackSize <= Info.CleanupStack.size() && 1365 "running cleanups out of order?"); 1366 1367 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1368 // for a full-expression scope. 1369 bool Success = true; 1370 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1371 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1372 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1373 Success = false; 1374 break; 1375 } 1376 } 1377 } 1378 1379 // Compact any retained cleanups. 1380 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1381 if (Kind != ScopeKind::Block) 1382 NewEnd = 1383 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1384 return C.isDestroyedAtEndOf(Kind); 1385 }); 1386 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1387 return Success; 1388 } 1389 }; 1390 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1391 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1392 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1393 } 1394 1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1396 CheckSubobjectKind CSK) { 1397 if (Invalid) 1398 return false; 1399 if (isOnePastTheEnd()) { 1400 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1401 << CSK; 1402 setInvalid(); 1403 return false; 1404 } 1405 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1406 // must actually be at least one array element; even a VLA cannot have a 1407 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1408 return true; 1409 } 1410 1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1412 const Expr *E) { 1413 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1414 // Do not set the designator as invalid: we can represent this situation, 1415 // and correct handling of __builtin_object_size requires us to do so. 1416 } 1417 1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1419 const Expr *E, 1420 const APSInt &N) { 1421 // If we're complaining, we must be able to statically determine the size of 1422 // the most derived array. 1423 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1424 Info.CCEDiag(E, diag::note_constexpr_array_index) 1425 << N << /*array*/ 0 1426 << static_cast<unsigned>(getMostDerivedArraySize()); 1427 else 1428 Info.CCEDiag(E, diag::note_constexpr_array_index) 1429 << N << /*non-array*/ 1; 1430 setInvalid(); 1431 } 1432 1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1434 const FunctionDecl *Callee, const LValue *This, 1435 CallRef Call) 1436 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1437 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1438 Info.CurrentCall = this; 1439 ++Info.CallStackDepth; 1440 } 1441 1442 CallStackFrame::~CallStackFrame() { 1443 assert(Info.CurrentCall == this && "calls retired out of order"); 1444 --Info.CallStackDepth; 1445 Info.CurrentCall = Caller; 1446 } 1447 1448 static bool isRead(AccessKinds AK) { 1449 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1450 } 1451 1452 static bool isModification(AccessKinds AK) { 1453 switch (AK) { 1454 case AK_Read: 1455 case AK_ReadObjectRepresentation: 1456 case AK_MemberCall: 1457 case AK_DynamicCast: 1458 case AK_TypeId: 1459 return false; 1460 case AK_Assign: 1461 case AK_Increment: 1462 case AK_Decrement: 1463 case AK_Construct: 1464 case AK_Destroy: 1465 return true; 1466 } 1467 llvm_unreachable("unknown access kind"); 1468 } 1469 1470 static bool isAnyAccess(AccessKinds AK) { 1471 return isRead(AK) || isModification(AK); 1472 } 1473 1474 /// Is this an access per the C++ definition? 1475 static bool isFormalAccess(AccessKinds AK) { 1476 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1477 } 1478 1479 /// Is this kind of axcess valid on an indeterminate object value? 1480 static bool isValidIndeterminateAccess(AccessKinds AK) { 1481 switch (AK) { 1482 case AK_Read: 1483 case AK_Increment: 1484 case AK_Decrement: 1485 // These need the object's value. 1486 return false; 1487 1488 case AK_ReadObjectRepresentation: 1489 case AK_Assign: 1490 case AK_Construct: 1491 case AK_Destroy: 1492 // Construction and destruction don't need the value. 1493 return true; 1494 1495 case AK_MemberCall: 1496 case AK_DynamicCast: 1497 case AK_TypeId: 1498 // These aren't really meaningful on scalars. 1499 return true; 1500 } 1501 llvm_unreachable("unknown access kind"); 1502 } 1503 1504 namespace { 1505 struct ComplexValue { 1506 private: 1507 bool IsInt; 1508 1509 public: 1510 APSInt IntReal, IntImag; 1511 APFloat FloatReal, FloatImag; 1512 1513 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1514 1515 void makeComplexFloat() { IsInt = false; } 1516 bool isComplexFloat() const { return !IsInt; } 1517 APFloat &getComplexFloatReal() { return FloatReal; } 1518 APFloat &getComplexFloatImag() { return FloatImag; } 1519 1520 void makeComplexInt() { IsInt = true; } 1521 bool isComplexInt() const { return IsInt; } 1522 APSInt &getComplexIntReal() { return IntReal; } 1523 APSInt &getComplexIntImag() { return IntImag; } 1524 1525 void moveInto(APValue &v) const { 1526 if (isComplexFloat()) 1527 v = APValue(FloatReal, FloatImag); 1528 else 1529 v = APValue(IntReal, IntImag); 1530 } 1531 void setFrom(const APValue &v) { 1532 assert(v.isComplexFloat() || v.isComplexInt()); 1533 if (v.isComplexFloat()) { 1534 makeComplexFloat(); 1535 FloatReal = v.getComplexFloatReal(); 1536 FloatImag = v.getComplexFloatImag(); 1537 } else { 1538 makeComplexInt(); 1539 IntReal = v.getComplexIntReal(); 1540 IntImag = v.getComplexIntImag(); 1541 } 1542 } 1543 }; 1544 1545 struct LValue { 1546 APValue::LValueBase Base; 1547 CharUnits Offset; 1548 SubobjectDesignator Designator; 1549 bool IsNullPtr : 1; 1550 bool InvalidBase : 1; 1551 1552 const APValue::LValueBase getLValueBase() const { return Base; } 1553 CharUnits &getLValueOffset() { return Offset; } 1554 const CharUnits &getLValueOffset() const { return Offset; } 1555 SubobjectDesignator &getLValueDesignator() { return Designator; } 1556 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1557 bool isNullPointer() const { return IsNullPtr;} 1558 1559 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1560 unsigned getLValueVersion() const { return Base.getVersion(); } 1561 1562 void moveInto(APValue &V) const { 1563 if (Designator.Invalid) 1564 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1565 else { 1566 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1567 V = APValue(Base, Offset, Designator.Entries, 1568 Designator.IsOnePastTheEnd, IsNullPtr); 1569 } 1570 } 1571 void setFrom(ASTContext &Ctx, const APValue &V) { 1572 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1573 Base = V.getLValueBase(); 1574 Offset = V.getLValueOffset(); 1575 InvalidBase = false; 1576 Designator = SubobjectDesignator(Ctx, V); 1577 IsNullPtr = V.isNullPointer(); 1578 } 1579 1580 void set(APValue::LValueBase B, bool BInvalid = false) { 1581 #ifndef NDEBUG 1582 // We only allow a few types of invalid bases. Enforce that here. 1583 if (BInvalid) { 1584 const auto *E = B.get<const Expr *>(); 1585 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1586 "Unexpected type of invalid base"); 1587 } 1588 #endif 1589 1590 Base = B; 1591 Offset = CharUnits::fromQuantity(0); 1592 InvalidBase = BInvalid; 1593 Designator = SubobjectDesignator(getType(B)); 1594 IsNullPtr = false; 1595 } 1596 1597 void setNull(ASTContext &Ctx, QualType PointerTy) { 1598 Base = (const ValueDecl *)nullptr; 1599 Offset = 1600 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1601 InvalidBase = false; 1602 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1603 IsNullPtr = true; 1604 } 1605 1606 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1607 set(B, true); 1608 } 1609 1610 std::string toString(ASTContext &Ctx, QualType T) const { 1611 APValue Printable; 1612 moveInto(Printable); 1613 return Printable.getAsString(Ctx, T); 1614 } 1615 1616 private: 1617 // Check that this LValue is not based on a null pointer. If it is, produce 1618 // a diagnostic and mark the designator as invalid. 1619 template <typename GenDiagType> 1620 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1621 if (Designator.Invalid) 1622 return false; 1623 if (IsNullPtr) { 1624 GenDiag(); 1625 Designator.setInvalid(); 1626 return false; 1627 } 1628 return true; 1629 } 1630 1631 public: 1632 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1633 CheckSubobjectKind CSK) { 1634 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1635 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1636 }); 1637 } 1638 1639 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1640 AccessKinds AK) { 1641 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1642 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1643 }); 1644 } 1645 1646 // Check this LValue refers to an object. If not, set the designator to be 1647 // invalid and emit a diagnostic. 1648 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1649 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1650 Designator.checkSubobject(Info, E, CSK); 1651 } 1652 1653 void addDecl(EvalInfo &Info, const Expr *E, 1654 const Decl *D, bool Virtual = false) { 1655 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1656 Designator.addDeclUnchecked(D, Virtual); 1657 } 1658 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1659 if (!Designator.Entries.empty()) { 1660 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1661 Designator.setInvalid(); 1662 return; 1663 } 1664 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1665 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1666 Designator.FirstEntryIsAnUnsizedArray = true; 1667 Designator.addUnsizedArrayUnchecked(ElemTy); 1668 } 1669 } 1670 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1671 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1672 Designator.addArrayUnchecked(CAT); 1673 } 1674 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1675 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1676 Designator.addComplexUnchecked(EltTy, Imag); 1677 } 1678 void clearIsNullPointer() { 1679 IsNullPtr = false; 1680 } 1681 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1682 const APSInt &Index, CharUnits ElementSize) { 1683 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1684 // but we're not required to diagnose it and it's valid in C++.) 1685 if (!Index) 1686 return; 1687 1688 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1689 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1690 // offsets. 1691 uint64_t Offset64 = Offset.getQuantity(); 1692 uint64_t ElemSize64 = ElementSize.getQuantity(); 1693 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1694 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1695 1696 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1697 Designator.adjustIndex(Info, E, Index); 1698 clearIsNullPointer(); 1699 } 1700 void adjustOffset(CharUnits N) { 1701 Offset += N; 1702 if (N.getQuantity()) 1703 clearIsNullPointer(); 1704 } 1705 }; 1706 1707 struct MemberPtr { 1708 MemberPtr() {} 1709 explicit MemberPtr(const ValueDecl *Decl) 1710 : DeclAndIsDerivedMember(Decl, false) {} 1711 1712 /// The member or (direct or indirect) field referred to by this member 1713 /// pointer, or 0 if this is a null member pointer. 1714 const ValueDecl *getDecl() const { 1715 return DeclAndIsDerivedMember.getPointer(); 1716 } 1717 /// Is this actually a member of some type derived from the relevant class? 1718 bool isDerivedMember() const { 1719 return DeclAndIsDerivedMember.getInt(); 1720 } 1721 /// Get the class which the declaration actually lives in. 1722 const CXXRecordDecl *getContainingRecord() const { 1723 return cast<CXXRecordDecl>( 1724 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1725 } 1726 1727 void moveInto(APValue &V) const { 1728 V = APValue(getDecl(), isDerivedMember(), Path); 1729 } 1730 void setFrom(const APValue &V) { 1731 assert(V.isMemberPointer()); 1732 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1733 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1734 Path.clear(); 1735 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1736 Path.insert(Path.end(), P.begin(), P.end()); 1737 } 1738 1739 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1740 /// whether the member is a member of some class derived from the class type 1741 /// of the member pointer. 1742 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1743 /// Path - The path of base/derived classes from the member declaration's 1744 /// class (exclusive) to the class type of the member pointer (inclusive). 1745 SmallVector<const CXXRecordDecl*, 4> Path; 1746 1747 /// Perform a cast towards the class of the Decl (either up or down the 1748 /// hierarchy). 1749 bool castBack(const CXXRecordDecl *Class) { 1750 assert(!Path.empty()); 1751 const CXXRecordDecl *Expected; 1752 if (Path.size() >= 2) 1753 Expected = Path[Path.size() - 2]; 1754 else 1755 Expected = getContainingRecord(); 1756 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1757 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1758 // if B does not contain the original member and is not a base or 1759 // derived class of the class containing the original member, the result 1760 // of the cast is undefined. 1761 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1762 // (D::*). We consider that to be a language defect. 1763 return false; 1764 } 1765 Path.pop_back(); 1766 return true; 1767 } 1768 /// Perform a base-to-derived member pointer cast. 1769 bool castToDerived(const CXXRecordDecl *Derived) { 1770 if (!getDecl()) 1771 return true; 1772 if (!isDerivedMember()) { 1773 Path.push_back(Derived); 1774 return true; 1775 } 1776 if (!castBack(Derived)) 1777 return false; 1778 if (Path.empty()) 1779 DeclAndIsDerivedMember.setInt(false); 1780 return true; 1781 } 1782 /// Perform a derived-to-base member pointer cast. 1783 bool castToBase(const CXXRecordDecl *Base) { 1784 if (!getDecl()) 1785 return true; 1786 if (Path.empty()) 1787 DeclAndIsDerivedMember.setInt(true); 1788 if (isDerivedMember()) { 1789 Path.push_back(Base); 1790 return true; 1791 } 1792 return castBack(Base); 1793 } 1794 }; 1795 1796 /// Compare two member pointers, which are assumed to be of the same type. 1797 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1798 if (!LHS.getDecl() || !RHS.getDecl()) 1799 return !LHS.getDecl() && !RHS.getDecl(); 1800 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1801 return false; 1802 return LHS.Path == RHS.Path; 1803 } 1804 } 1805 1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1808 const LValue &This, const Expr *E, 1809 bool AllowNonLiteralTypes = false); 1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1811 bool InvalidBaseOK = false); 1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1813 bool InvalidBaseOK = false); 1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1815 EvalInfo &Info); 1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1819 EvalInfo &Info); 1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1823 EvalInfo &Info); 1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 1826 EvalInfo &Info); 1827 1828 /// Evaluate an integer or fixed point expression into an APResult. 1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1830 EvalInfo &Info); 1831 1832 /// Evaluate only a fixed point expression into an APResult. 1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1834 EvalInfo &Info); 1835 1836 //===----------------------------------------------------------------------===// 1837 // Misc utilities 1838 //===----------------------------------------------------------------------===// 1839 1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1841 /// preserving its value (by extending by up to one bit as needed). 1842 static void negateAsSigned(APSInt &Int) { 1843 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1844 Int = Int.extend(Int.getBitWidth() + 1); 1845 Int.setIsSigned(true); 1846 } 1847 Int = -Int; 1848 } 1849 1850 template<typename KeyT> 1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1852 ScopeKind Scope, LValue &LV) { 1853 unsigned Version = getTempVersion(); 1854 APValue::LValueBase Base(Key, Index, Version); 1855 LV.set(Base); 1856 return createLocal(Base, Key, T, Scope); 1857 } 1858 1859 /// Allocate storage for a parameter of a function call made in this frame. 1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1861 LValue &LV) { 1862 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1863 APValue::LValueBase Base(PVD, Index, Args.Version); 1864 LV.set(Base); 1865 // We always destroy parameters at the end of the call, even if we'd allow 1866 // them to live to the end of the full-expression at runtime, in order to 1867 // give portable results and match other compilers. 1868 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1869 } 1870 1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1872 QualType T, ScopeKind Scope) { 1873 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1874 unsigned Version = Base.getVersion(); 1875 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1876 assert(Result.isAbsent() && "local created multiple times"); 1877 1878 // If we're creating a local immediately in the operand of a speculative 1879 // evaluation, don't register a cleanup to be run outside the speculative 1880 // evaluation context, since we won't actually be able to initialize this 1881 // object. 1882 if (Index <= Info.SpeculativeEvaluationDepth) { 1883 if (T.isDestructedType()) 1884 Info.noteSideEffect(); 1885 } else { 1886 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1887 } 1888 return Result; 1889 } 1890 1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1892 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1893 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1894 return nullptr; 1895 } 1896 1897 DynamicAllocLValue DA(NumHeapAllocs++); 1898 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1899 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1900 std::forward_as_tuple(DA), std::tuple<>()); 1901 assert(Result.second && "reused a heap alloc index?"); 1902 Result.first->second.AllocExpr = E; 1903 return &Result.first->second.Value; 1904 } 1905 1906 /// Produce a string describing the given constexpr call. 1907 void CallStackFrame::describe(raw_ostream &Out) { 1908 unsigned ArgIndex = 0; 1909 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1910 !isa<CXXConstructorDecl>(Callee) && 1911 cast<CXXMethodDecl>(Callee)->isInstance(); 1912 1913 if (!IsMemberCall) 1914 Out << *Callee << '('; 1915 1916 if (This && IsMemberCall) { 1917 APValue Val; 1918 This->moveInto(Val); 1919 Val.printPretty(Out, Info.Ctx, 1920 This->Designator.MostDerivedType); 1921 // FIXME: Add parens around Val if needed. 1922 Out << "->" << *Callee << '('; 1923 IsMemberCall = false; 1924 } 1925 1926 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1927 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1928 if (ArgIndex > (unsigned)IsMemberCall) 1929 Out << ", "; 1930 1931 const ParmVarDecl *Param = *I; 1932 APValue *V = Info.getParamSlot(Arguments, Param); 1933 if (V) 1934 V->printPretty(Out, Info.Ctx, Param->getType()); 1935 else 1936 Out << "<...>"; 1937 1938 if (ArgIndex == 0 && IsMemberCall) 1939 Out << "->" << *Callee << '('; 1940 } 1941 1942 Out << ')'; 1943 } 1944 1945 /// Evaluate an expression to see if it had side-effects, and discard its 1946 /// result. 1947 /// \return \c true if the caller should keep evaluating. 1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1949 assert(!E->isValueDependent()); 1950 APValue Scratch; 1951 if (!Evaluate(Scratch, Info, E)) 1952 // We don't need the value, but we might have skipped a side effect here. 1953 return Info.noteSideEffect(); 1954 return true; 1955 } 1956 1957 /// Should this call expression be treated as a constant? 1958 static bool IsConstantCall(const CallExpr *E) { 1959 unsigned Builtin = E->getBuiltinCallee(); 1960 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1961 Builtin == Builtin::BI__builtin___NSStringMakeConstantString || 1962 Builtin == Builtin::BI__builtin_function_start); 1963 } 1964 1965 static bool IsGlobalLValue(APValue::LValueBase B) { 1966 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1967 // constant expression of pointer type that evaluates to... 1968 1969 // ... a null pointer value, or a prvalue core constant expression of type 1970 // std::nullptr_t. 1971 if (!B) return true; 1972 1973 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1974 // ... the address of an object with static storage duration, 1975 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1976 return VD->hasGlobalStorage(); 1977 if (isa<TemplateParamObjectDecl>(D)) 1978 return true; 1979 // ... the address of a function, 1980 // ... the address of a GUID [MS extension], 1981 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1982 } 1983 1984 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1985 return true; 1986 1987 const Expr *E = B.get<const Expr*>(); 1988 switch (E->getStmtClass()) { 1989 default: 1990 return false; 1991 case Expr::CompoundLiteralExprClass: { 1992 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1993 return CLE->isFileScope() && CLE->isLValue(); 1994 } 1995 case Expr::MaterializeTemporaryExprClass: 1996 // A materialized temporary might have been lifetime-extended to static 1997 // storage duration. 1998 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1999 // A string literal has static storage duration. 2000 case Expr::StringLiteralClass: 2001 case Expr::PredefinedExprClass: 2002 case Expr::ObjCStringLiteralClass: 2003 case Expr::ObjCEncodeExprClass: 2004 return true; 2005 case Expr::ObjCBoxedExprClass: 2006 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2007 case Expr::CallExprClass: 2008 return IsConstantCall(cast<CallExpr>(E)); 2009 // For GCC compatibility, &&label has static storage duration. 2010 case Expr::AddrLabelExprClass: 2011 return true; 2012 // A Block literal expression may be used as the initialization value for 2013 // Block variables at global or local static scope. 2014 case Expr::BlockExprClass: 2015 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2016 case Expr::ImplicitValueInitExprClass: 2017 // FIXME: 2018 // We can never form an lvalue with an implicit value initialization as its 2019 // base through expression evaluation, so these only appear in one case: the 2020 // implicit variable declaration we invent when checking whether a constexpr 2021 // constructor can produce a constant expression. We must assume that such 2022 // an expression might be a global lvalue. 2023 return true; 2024 } 2025 } 2026 2027 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2028 return LVal.Base.dyn_cast<const ValueDecl*>(); 2029 } 2030 2031 static bool IsLiteralLValue(const LValue &Value) { 2032 if (Value.getLValueCallIndex()) 2033 return false; 2034 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2035 return E && !isa<MaterializeTemporaryExpr>(E); 2036 } 2037 2038 static bool IsWeakLValue(const LValue &Value) { 2039 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2040 return Decl && Decl->isWeak(); 2041 } 2042 2043 static bool isZeroSized(const LValue &Value) { 2044 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2045 if (Decl && isa<VarDecl>(Decl)) { 2046 QualType Ty = Decl->getType(); 2047 if (Ty->isArrayType()) 2048 return Ty->isIncompleteType() || 2049 Decl->getASTContext().getTypeSize(Ty) == 0; 2050 } 2051 return false; 2052 } 2053 2054 static bool HasSameBase(const LValue &A, const LValue &B) { 2055 if (!A.getLValueBase()) 2056 return !B.getLValueBase(); 2057 if (!B.getLValueBase()) 2058 return false; 2059 2060 if (A.getLValueBase().getOpaqueValue() != 2061 B.getLValueBase().getOpaqueValue()) 2062 return false; 2063 2064 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2065 A.getLValueVersion() == B.getLValueVersion(); 2066 } 2067 2068 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2069 assert(Base && "no location for a null lvalue"); 2070 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2071 2072 // For a parameter, find the corresponding call stack frame (if it still 2073 // exists), and point at the parameter of the function definition we actually 2074 // invoked. 2075 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2076 unsigned Idx = PVD->getFunctionScopeIndex(); 2077 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2078 if (F->Arguments.CallIndex == Base.getCallIndex() && 2079 F->Arguments.Version == Base.getVersion() && F->Callee && 2080 Idx < F->Callee->getNumParams()) { 2081 VD = F->Callee->getParamDecl(Idx); 2082 break; 2083 } 2084 } 2085 } 2086 2087 if (VD) 2088 Info.Note(VD->getLocation(), diag::note_declared_at); 2089 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2090 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2091 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2092 // FIXME: Produce a note for dangling pointers too. 2093 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2094 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2095 diag::note_constexpr_dynamic_alloc_here); 2096 } 2097 // We have no information to show for a typeid(T) object. 2098 } 2099 2100 enum class CheckEvaluationResultKind { 2101 ConstantExpression, 2102 FullyInitialized, 2103 }; 2104 2105 /// Materialized temporaries that we've already checked to determine if they're 2106 /// initializsed by a constant expression. 2107 using CheckedTemporaries = 2108 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2109 2110 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2111 EvalInfo &Info, SourceLocation DiagLoc, 2112 QualType Type, const APValue &Value, 2113 ConstantExprKind Kind, 2114 SourceLocation SubobjectLoc, 2115 CheckedTemporaries &CheckedTemps); 2116 2117 /// Check that this reference or pointer core constant expression is a valid 2118 /// value for an address or reference constant expression. Return true if we 2119 /// can fold this expression, whether or not it's a constant expression. 2120 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2121 QualType Type, const LValue &LVal, 2122 ConstantExprKind Kind, 2123 CheckedTemporaries &CheckedTemps) { 2124 bool IsReferenceType = Type->isReferenceType(); 2125 2126 APValue::LValueBase Base = LVal.getLValueBase(); 2127 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2128 2129 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2130 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2131 2132 // Additional restrictions apply in a template argument. We only enforce the 2133 // C++20 restrictions here; additional syntactic and semantic restrictions 2134 // are applied elsewhere. 2135 if (isTemplateArgument(Kind)) { 2136 int InvalidBaseKind = -1; 2137 StringRef Ident; 2138 if (Base.is<TypeInfoLValue>()) 2139 InvalidBaseKind = 0; 2140 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2141 InvalidBaseKind = 1; 2142 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2143 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2144 InvalidBaseKind = 2; 2145 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2146 InvalidBaseKind = 3; 2147 Ident = PE->getIdentKindName(); 2148 } 2149 2150 if (InvalidBaseKind != -1) { 2151 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2152 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2153 << Ident; 2154 return false; 2155 } 2156 } 2157 2158 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2159 if (FD->isConsteval()) { 2160 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2161 << !Type->isAnyPointerType(); 2162 Info.Note(FD->getLocation(), diag::note_declared_at); 2163 return false; 2164 } 2165 } 2166 2167 // Check that the object is a global. Note that the fake 'this' object we 2168 // manufacture when checking potential constant expressions is conservatively 2169 // assumed to be global here. 2170 if (!IsGlobalLValue(Base)) { 2171 if (Info.getLangOpts().CPlusPlus11) { 2172 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2173 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2174 << IsReferenceType << !Designator.Entries.empty() 2175 << !!VD << VD; 2176 2177 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2178 if (VarD && VarD->isConstexpr()) { 2179 // Non-static local constexpr variables have unintuitive semantics: 2180 // constexpr int a = 1; 2181 // constexpr const int *p = &a; 2182 // ... is invalid because the address of 'a' is not constant. Suggest 2183 // adding a 'static' in this case. 2184 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2185 << VarD 2186 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2187 } else { 2188 NoteLValueLocation(Info, Base); 2189 } 2190 } else { 2191 Info.FFDiag(Loc); 2192 } 2193 // Don't allow references to temporaries to escape. 2194 return false; 2195 } 2196 assert((Info.checkingPotentialConstantExpression() || 2197 LVal.getLValueCallIndex() == 0) && 2198 "have call index for global lvalue"); 2199 2200 if (Base.is<DynamicAllocLValue>()) { 2201 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2202 << IsReferenceType << !Designator.Entries.empty(); 2203 NoteLValueLocation(Info, Base); 2204 return false; 2205 } 2206 2207 if (BaseVD) { 2208 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2209 // Check if this is a thread-local variable. 2210 if (Var->getTLSKind()) 2211 // FIXME: Diagnostic! 2212 return false; 2213 2214 // A dllimport variable never acts like a constant, unless we're 2215 // evaluating a value for use only in name mangling. 2216 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2217 // FIXME: Diagnostic! 2218 return false; 2219 2220 // In CUDA/HIP device compilation, only device side variables have 2221 // constant addresses. 2222 if (Info.getCtx().getLangOpts().CUDA && 2223 Info.getCtx().getLangOpts().CUDAIsDevice && 2224 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) { 2225 if ((!Var->hasAttr<CUDADeviceAttr>() && 2226 !Var->hasAttr<CUDAConstantAttr>() && 2227 !Var->getType()->isCUDADeviceBuiltinSurfaceType() && 2228 !Var->getType()->isCUDADeviceBuiltinTextureType()) || 2229 Var->hasAttr<HIPManagedAttr>()) 2230 return false; 2231 } 2232 } 2233 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2234 // __declspec(dllimport) must be handled very carefully: 2235 // We must never initialize an expression with the thunk in C++. 2236 // Doing otherwise would allow the same id-expression to yield 2237 // different addresses for the same function in different translation 2238 // units. However, this means that we must dynamically initialize the 2239 // expression with the contents of the import address table at runtime. 2240 // 2241 // The C language has no notion of ODR; furthermore, it has no notion of 2242 // dynamic initialization. This means that we are permitted to 2243 // perform initialization with the address of the thunk. 2244 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2245 FD->hasAttr<DLLImportAttr>()) 2246 // FIXME: Diagnostic! 2247 return false; 2248 } 2249 } else if (const auto *MTE = 2250 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2251 if (CheckedTemps.insert(MTE).second) { 2252 QualType TempType = getType(Base); 2253 if (TempType.isDestructedType()) { 2254 Info.FFDiag(MTE->getExprLoc(), 2255 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2256 << TempType; 2257 return false; 2258 } 2259 2260 APValue *V = MTE->getOrCreateValue(false); 2261 assert(V && "evasluation result refers to uninitialised temporary"); 2262 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2263 Info, MTE->getExprLoc(), TempType, *V, 2264 Kind, SourceLocation(), CheckedTemps)) 2265 return false; 2266 } 2267 } 2268 2269 // Allow address constant expressions to be past-the-end pointers. This is 2270 // an extension: the standard requires them to point to an object. 2271 if (!IsReferenceType) 2272 return true; 2273 2274 // A reference constant expression must refer to an object. 2275 if (!Base) { 2276 // FIXME: diagnostic 2277 Info.CCEDiag(Loc); 2278 return true; 2279 } 2280 2281 // Does this refer one past the end of some object? 2282 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2283 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2284 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2285 NoteLValueLocation(Info, Base); 2286 } 2287 2288 return true; 2289 } 2290 2291 /// Member pointers are constant expressions unless they point to a 2292 /// non-virtual dllimport member function. 2293 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2294 SourceLocation Loc, 2295 QualType Type, 2296 const APValue &Value, 2297 ConstantExprKind Kind) { 2298 const ValueDecl *Member = Value.getMemberPointerDecl(); 2299 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2300 if (!FD) 2301 return true; 2302 if (FD->isConsteval()) { 2303 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2304 Info.Note(FD->getLocation(), diag::note_declared_at); 2305 return false; 2306 } 2307 return isForManglingOnly(Kind) || FD->isVirtual() || 2308 !FD->hasAttr<DLLImportAttr>(); 2309 } 2310 2311 /// Check that this core constant expression is of literal type, and if not, 2312 /// produce an appropriate diagnostic. 2313 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2314 const LValue *This = nullptr) { 2315 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2316 return true; 2317 2318 // C++1y: A constant initializer for an object o [...] may also invoke 2319 // constexpr constructors for o and its subobjects even if those objects 2320 // are of non-literal class types. 2321 // 2322 // C++11 missed this detail for aggregates, so classes like this: 2323 // struct foo_t { union { int i; volatile int j; } u; }; 2324 // are not (obviously) initializable like so: 2325 // __attribute__((__require_constant_initialization__)) 2326 // static const foo_t x = {{0}}; 2327 // because "i" is a subobject with non-literal initialization (due to the 2328 // volatile member of the union). See: 2329 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2330 // Therefore, we use the C++1y behavior. 2331 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2332 return true; 2333 2334 // Prvalue constant expressions must be of literal types. 2335 if (Info.getLangOpts().CPlusPlus11) 2336 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2337 << E->getType(); 2338 else 2339 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2340 return false; 2341 } 2342 2343 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2344 EvalInfo &Info, SourceLocation DiagLoc, 2345 QualType Type, const APValue &Value, 2346 ConstantExprKind Kind, 2347 SourceLocation SubobjectLoc, 2348 CheckedTemporaries &CheckedTemps) { 2349 if (!Value.hasValue()) { 2350 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2351 << true << Type; 2352 if (SubobjectLoc.isValid()) 2353 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2354 return false; 2355 } 2356 2357 // We allow _Atomic(T) to be initialized from anything that T can be 2358 // initialized from. 2359 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2360 Type = AT->getValueType(); 2361 2362 // Core issue 1454: For a literal constant expression of array or class type, 2363 // each subobject of its value shall have been initialized by a constant 2364 // expression. 2365 if (Value.isArray()) { 2366 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2367 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2368 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2369 Value.getArrayInitializedElt(I), Kind, 2370 SubobjectLoc, CheckedTemps)) 2371 return false; 2372 } 2373 if (!Value.hasArrayFiller()) 2374 return true; 2375 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2376 Value.getArrayFiller(), Kind, SubobjectLoc, 2377 CheckedTemps); 2378 } 2379 if (Value.isUnion() && Value.getUnionField()) { 2380 return CheckEvaluationResult( 2381 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2382 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2383 CheckedTemps); 2384 } 2385 if (Value.isStruct()) { 2386 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2387 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2388 unsigned BaseIndex = 0; 2389 for (const CXXBaseSpecifier &BS : CD->bases()) { 2390 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2391 Value.getStructBase(BaseIndex), Kind, 2392 BS.getBeginLoc(), CheckedTemps)) 2393 return false; 2394 ++BaseIndex; 2395 } 2396 } 2397 for (const auto *I : RD->fields()) { 2398 if (I->isUnnamedBitfield()) 2399 continue; 2400 2401 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2402 Value.getStructField(I->getFieldIndex()), 2403 Kind, I->getLocation(), CheckedTemps)) 2404 return false; 2405 } 2406 } 2407 2408 if (Value.isLValue() && 2409 CERK == CheckEvaluationResultKind::ConstantExpression) { 2410 LValue LVal; 2411 LVal.setFrom(Info.Ctx, Value); 2412 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2413 CheckedTemps); 2414 } 2415 2416 if (Value.isMemberPointer() && 2417 CERK == CheckEvaluationResultKind::ConstantExpression) 2418 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2419 2420 // Everything else is fine. 2421 return true; 2422 } 2423 2424 /// Check that this core constant expression value is a valid value for a 2425 /// constant expression. If not, report an appropriate diagnostic. Does not 2426 /// check that the expression is of literal type. 2427 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2428 QualType Type, const APValue &Value, 2429 ConstantExprKind Kind) { 2430 // Nothing to check for a constant expression of type 'cv void'. 2431 if (Type->isVoidType()) 2432 return true; 2433 2434 CheckedTemporaries CheckedTemps; 2435 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2436 Info, DiagLoc, Type, Value, Kind, 2437 SourceLocation(), CheckedTemps); 2438 } 2439 2440 /// Check that this evaluated value is fully-initialized and can be loaded by 2441 /// an lvalue-to-rvalue conversion. 2442 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2443 QualType Type, const APValue &Value) { 2444 CheckedTemporaries CheckedTemps; 2445 return CheckEvaluationResult( 2446 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2447 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2448 } 2449 2450 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2451 /// "the allocated storage is deallocated within the evaluation". 2452 static bool CheckMemoryLeaks(EvalInfo &Info) { 2453 if (!Info.HeapAllocs.empty()) { 2454 // We can still fold to a constant despite a compile-time memory leak, 2455 // so long as the heap allocation isn't referenced in the result (we check 2456 // that in CheckConstantExpression). 2457 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2458 diag::note_constexpr_memory_leak) 2459 << unsigned(Info.HeapAllocs.size() - 1); 2460 } 2461 return true; 2462 } 2463 2464 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2465 // A null base expression indicates a null pointer. These are always 2466 // evaluatable, and they are false unless the offset is zero. 2467 if (!Value.getLValueBase()) { 2468 Result = !Value.getLValueOffset().isZero(); 2469 return true; 2470 } 2471 2472 // We have a non-null base. These are generally known to be true, but if it's 2473 // a weak declaration it can be null at runtime. 2474 Result = true; 2475 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2476 return !Decl || !Decl->isWeak(); 2477 } 2478 2479 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2480 switch (Val.getKind()) { 2481 case APValue::None: 2482 case APValue::Indeterminate: 2483 return false; 2484 case APValue::Int: 2485 Result = Val.getInt().getBoolValue(); 2486 return true; 2487 case APValue::FixedPoint: 2488 Result = Val.getFixedPoint().getBoolValue(); 2489 return true; 2490 case APValue::Float: 2491 Result = !Val.getFloat().isZero(); 2492 return true; 2493 case APValue::ComplexInt: 2494 Result = Val.getComplexIntReal().getBoolValue() || 2495 Val.getComplexIntImag().getBoolValue(); 2496 return true; 2497 case APValue::ComplexFloat: 2498 Result = !Val.getComplexFloatReal().isZero() || 2499 !Val.getComplexFloatImag().isZero(); 2500 return true; 2501 case APValue::LValue: 2502 return EvalPointerValueAsBool(Val, Result); 2503 case APValue::MemberPointer: 2504 Result = Val.getMemberPointerDecl(); 2505 return true; 2506 case APValue::Vector: 2507 case APValue::Array: 2508 case APValue::Struct: 2509 case APValue::Union: 2510 case APValue::AddrLabelDiff: 2511 return false; 2512 } 2513 2514 llvm_unreachable("unknown APValue kind"); 2515 } 2516 2517 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2518 EvalInfo &Info) { 2519 assert(!E->isValueDependent()); 2520 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2521 APValue Val; 2522 if (!Evaluate(Val, Info, E)) 2523 return false; 2524 return HandleConversionToBool(Val, Result); 2525 } 2526 2527 template<typename T> 2528 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2529 const T &SrcValue, QualType DestType) { 2530 Info.CCEDiag(E, diag::note_constexpr_overflow) 2531 << SrcValue << DestType; 2532 return Info.noteUndefinedBehavior(); 2533 } 2534 2535 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2536 QualType SrcType, const APFloat &Value, 2537 QualType DestType, APSInt &Result) { 2538 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2539 // Determine whether we are converting to unsigned or signed. 2540 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2541 2542 Result = APSInt(DestWidth, !DestSigned); 2543 bool ignored; 2544 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2545 & APFloat::opInvalidOp) 2546 return HandleOverflow(Info, E, Value, DestType); 2547 return true; 2548 } 2549 2550 /// Get rounding mode used for evaluation of the specified expression. 2551 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2552 /// dynamic. 2553 /// If rounding mode is unknown at compile time, still try to evaluate the 2554 /// expression. If the result is exact, it does not depend on rounding mode. 2555 /// So return "tonearest" mode instead of "dynamic". 2556 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2557 bool &DynamicRM) { 2558 llvm::RoundingMode RM = 2559 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2560 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2561 if (DynamicRM) 2562 RM = llvm::RoundingMode::NearestTiesToEven; 2563 return RM; 2564 } 2565 2566 /// Check if the given evaluation result is allowed for constant evaluation. 2567 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2568 APFloat::opStatus St) { 2569 // In a constant context, assume that any dynamic rounding mode or FP 2570 // exception state matches the default floating-point environment. 2571 if (Info.InConstantContext) 2572 return true; 2573 2574 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2575 if ((St & APFloat::opInexact) && 2576 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2577 // Inexact result means that it depends on rounding mode. If the requested 2578 // mode is dynamic, the evaluation cannot be made in compile time. 2579 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2580 return false; 2581 } 2582 2583 if ((St != APFloat::opOK) && 2584 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2585 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2586 FPO.getAllowFEnvAccess())) { 2587 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2588 return false; 2589 } 2590 2591 if ((St & APFloat::opStatus::opInvalidOp) && 2592 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2593 // There is no usefully definable result. 2594 Info.FFDiag(E); 2595 return false; 2596 } 2597 2598 // FIXME: if: 2599 // - evaluation triggered other FP exception, and 2600 // - exception mode is not "ignore", and 2601 // - the expression being evaluated is not a part of global variable 2602 // initializer, 2603 // the evaluation probably need to be rejected. 2604 return true; 2605 } 2606 2607 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2608 QualType SrcType, QualType DestType, 2609 APFloat &Result) { 2610 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2611 bool DynamicRM; 2612 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2613 APFloat::opStatus St; 2614 APFloat Value = Result; 2615 bool ignored; 2616 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2617 return checkFloatingPointResult(Info, E, St); 2618 } 2619 2620 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2621 QualType DestType, QualType SrcType, 2622 const APSInt &Value) { 2623 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2624 // Figure out if this is a truncate, extend or noop cast. 2625 // If the input is signed, do a sign extend, noop, or truncate. 2626 APSInt Result = Value.extOrTrunc(DestWidth); 2627 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2628 if (DestType->isBooleanType()) 2629 Result = Value.getBoolValue(); 2630 return Result; 2631 } 2632 2633 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2634 const FPOptions FPO, 2635 QualType SrcType, const APSInt &Value, 2636 QualType DestType, APFloat &Result) { 2637 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2638 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2639 APFloat::rmNearestTiesToEven); 2640 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2641 FPO.isFPConstrained()) { 2642 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2643 return false; 2644 } 2645 return true; 2646 } 2647 2648 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2649 APValue &Value, const FieldDecl *FD) { 2650 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2651 2652 if (!Value.isInt()) { 2653 // Trying to store a pointer-cast-to-integer into a bitfield. 2654 // FIXME: In this case, we should provide the diagnostic for casting 2655 // a pointer to an integer. 2656 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2657 Info.FFDiag(E); 2658 return false; 2659 } 2660 2661 APSInt &Int = Value.getInt(); 2662 unsigned OldBitWidth = Int.getBitWidth(); 2663 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2664 if (NewBitWidth < OldBitWidth) 2665 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2666 return true; 2667 } 2668 2669 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2670 llvm::APInt &Res) { 2671 APValue SVal; 2672 if (!Evaluate(SVal, Info, E)) 2673 return false; 2674 if (SVal.isInt()) { 2675 Res = SVal.getInt(); 2676 return true; 2677 } 2678 if (SVal.isFloat()) { 2679 Res = SVal.getFloat().bitcastToAPInt(); 2680 return true; 2681 } 2682 if (SVal.isVector()) { 2683 QualType VecTy = E->getType(); 2684 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2685 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2686 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2687 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2688 Res = llvm::APInt::getZero(VecSize); 2689 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2690 APValue &Elt = SVal.getVectorElt(i); 2691 llvm::APInt EltAsInt; 2692 if (Elt.isInt()) { 2693 EltAsInt = Elt.getInt(); 2694 } else if (Elt.isFloat()) { 2695 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2696 } else { 2697 // Don't try to handle vectors of anything other than int or float 2698 // (not sure if it's possible to hit this case). 2699 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2700 return false; 2701 } 2702 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2703 if (BigEndian) 2704 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2705 else 2706 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2707 } 2708 return true; 2709 } 2710 // Give up if the input isn't an int, float, or vector. For example, we 2711 // reject "(v4i16)(intptr_t)&a". 2712 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2713 return false; 2714 } 2715 2716 /// Perform the given integer operation, which is known to need at most BitWidth 2717 /// bits, and check for overflow in the original type (if that type was not an 2718 /// unsigned type). 2719 template<typename Operation> 2720 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2721 const APSInt &LHS, const APSInt &RHS, 2722 unsigned BitWidth, Operation Op, 2723 APSInt &Result) { 2724 if (LHS.isUnsigned()) { 2725 Result = Op(LHS, RHS); 2726 return true; 2727 } 2728 2729 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2730 Result = Value.trunc(LHS.getBitWidth()); 2731 if (Result.extend(BitWidth) != Value) { 2732 if (Info.checkingForUndefinedBehavior()) 2733 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2734 diag::warn_integer_constant_overflow) 2735 << toString(Result, 10) << E->getType(); 2736 return HandleOverflow(Info, E, Value, E->getType()); 2737 } 2738 return true; 2739 } 2740 2741 /// Perform the given binary integer operation. 2742 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2743 BinaryOperatorKind Opcode, APSInt RHS, 2744 APSInt &Result) { 2745 switch (Opcode) { 2746 default: 2747 Info.FFDiag(E); 2748 return false; 2749 case BO_Mul: 2750 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2751 std::multiplies<APSInt>(), Result); 2752 case BO_Add: 2753 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2754 std::plus<APSInt>(), Result); 2755 case BO_Sub: 2756 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2757 std::minus<APSInt>(), Result); 2758 case BO_And: Result = LHS & RHS; return true; 2759 case BO_Xor: Result = LHS ^ RHS; return true; 2760 case BO_Or: Result = LHS | RHS; return true; 2761 case BO_Div: 2762 case BO_Rem: 2763 if (RHS == 0) { 2764 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2765 return false; 2766 } 2767 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2768 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2769 // this operation and gives the two's complement result. 2770 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && 2771 LHS.isMinSignedValue()) 2772 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2773 E->getType()); 2774 return true; 2775 case BO_Shl: { 2776 if (Info.getLangOpts().OpenCL) 2777 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2778 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2779 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2780 RHS.isUnsigned()); 2781 else if (RHS.isSigned() && RHS.isNegative()) { 2782 // During constant-folding, a negative shift is an opposite shift. Such 2783 // a shift is not a constant expression. 2784 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2785 RHS = -RHS; 2786 goto shift_right; 2787 } 2788 shift_left: 2789 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2790 // the shifted type. 2791 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2792 if (SA != RHS) { 2793 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2794 << RHS << E->getType() << LHS.getBitWidth(); 2795 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2796 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2797 // operand, and must not overflow the corresponding unsigned type. 2798 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2799 // E1 x 2^E2 module 2^N. 2800 if (LHS.isNegative()) 2801 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2802 else if (LHS.countLeadingZeros() < SA) 2803 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2804 } 2805 Result = LHS << SA; 2806 return true; 2807 } 2808 case BO_Shr: { 2809 if (Info.getLangOpts().OpenCL) 2810 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2811 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2812 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2813 RHS.isUnsigned()); 2814 else if (RHS.isSigned() && RHS.isNegative()) { 2815 // During constant-folding, a negative shift is an opposite shift. Such a 2816 // shift is not a constant expression. 2817 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2818 RHS = -RHS; 2819 goto shift_left; 2820 } 2821 shift_right: 2822 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2823 // shifted type. 2824 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2825 if (SA != RHS) 2826 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2827 << RHS << E->getType() << LHS.getBitWidth(); 2828 Result = LHS >> SA; 2829 return true; 2830 } 2831 2832 case BO_LT: Result = LHS < RHS; return true; 2833 case BO_GT: Result = LHS > RHS; return true; 2834 case BO_LE: Result = LHS <= RHS; return true; 2835 case BO_GE: Result = LHS >= RHS; return true; 2836 case BO_EQ: Result = LHS == RHS; return true; 2837 case BO_NE: Result = LHS != RHS; return true; 2838 case BO_Cmp: 2839 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2840 } 2841 } 2842 2843 /// Perform the given binary floating-point operation, in-place, on LHS. 2844 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2845 APFloat &LHS, BinaryOperatorKind Opcode, 2846 const APFloat &RHS) { 2847 bool DynamicRM; 2848 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2849 APFloat::opStatus St; 2850 switch (Opcode) { 2851 default: 2852 Info.FFDiag(E); 2853 return false; 2854 case BO_Mul: 2855 St = LHS.multiply(RHS, RM); 2856 break; 2857 case BO_Add: 2858 St = LHS.add(RHS, RM); 2859 break; 2860 case BO_Sub: 2861 St = LHS.subtract(RHS, RM); 2862 break; 2863 case BO_Div: 2864 // [expr.mul]p4: 2865 // If the second operand of / or % is zero the behavior is undefined. 2866 if (RHS.isZero()) 2867 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2868 St = LHS.divide(RHS, RM); 2869 break; 2870 } 2871 2872 // [expr.pre]p4: 2873 // If during the evaluation of an expression, the result is not 2874 // mathematically defined [...], the behavior is undefined. 2875 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2876 if (LHS.isNaN()) { 2877 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2878 return Info.noteUndefinedBehavior(); 2879 } 2880 2881 return checkFloatingPointResult(Info, E, St); 2882 } 2883 2884 static bool handleLogicalOpForVector(const APInt &LHSValue, 2885 BinaryOperatorKind Opcode, 2886 const APInt &RHSValue, APInt &Result) { 2887 bool LHS = (LHSValue != 0); 2888 bool RHS = (RHSValue != 0); 2889 2890 if (Opcode == BO_LAnd) 2891 Result = LHS && RHS; 2892 else 2893 Result = LHS || RHS; 2894 return true; 2895 } 2896 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2897 BinaryOperatorKind Opcode, 2898 const APFloat &RHSValue, APInt &Result) { 2899 bool LHS = !LHSValue.isZero(); 2900 bool RHS = !RHSValue.isZero(); 2901 2902 if (Opcode == BO_LAnd) 2903 Result = LHS && RHS; 2904 else 2905 Result = LHS || RHS; 2906 return true; 2907 } 2908 2909 static bool handleLogicalOpForVector(const APValue &LHSValue, 2910 BinaryOperatorKind Opcode, 2911 const APValue &RHSValue, APInt &Result) { 2912 // The result is always an int type, however operands match the first. 2913 if (LHSValue.getKind() == APValue::Int) 2914 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2915 RHSValue.getInt(), Result); 2916 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2917 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2918 RHSValue.getFloat(), Result); 2919 } 2920 2921 template <typename APTy> 2922 static bool 2923 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2924 const APTy &RHSValue, APInt &Result) { 2925 switch (Opcode) { 2926 default: 2927 llvm_unreachable("unsupported binary operator"); 2928 case BO_EQ: 2929 Result = (LHSValue == RHSValue); 2930 break; 2931 case BO_NE: 2932 Result = (LHSValue != RHSValue); 2933 break; 2934 case BO_LT: 2935 Result = (LHSValue < RHSValue); 2936 break; 2937 case BO_GT: 2938 Result = (LHSValue > RHSValue); 2939 break; 2940 case BO_LE: 2941 Result = (LHSValue <= RHSValue); 2942 break; 2943 case BO_GE: 2944 Result = (LHSValue >= RHSValue); 2945 break; 2946 } 2947 2948 // The boolean operations on these vector types use an instruction that 2949 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 2950 // to -1 to make sure that we produce the correct value. 2951 Result.negate(); 2952 2953 return true; 2954 } 2955 2956 static bool handleCompareOpForVector(const APValue &LHSValue, 2957 BinaryOperatorKind Opcode, 2958 const APValue &RHSValue, APInt &Result) { 2959 // The result is always an int type, however operands match the first. 2960 if (LHSValue.getKind() == APValue::Int) 2961 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2962 RHSValue.getInt(), Result); 2963 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2964 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2965 RHSValue.getFloat(), Result); 2966 } 2967 2968 // Perform binary operations for vector types, in place on the LHS. 2969 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2970 BinaryOperatorKind Opcode, 2971 APValue &LHSValue, 2972 const APValue &RHSValue) { 2973 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2974 "Operation not supported on vector types"); 2975 2976 const auto *VT = E->getType()->castAs<VectorType>(); 2977 unsigned NumElements = VT->getNumElements(); 2978 QualType EltTy = VT->getElementType(); 2979 2980 // In the cases (typically C as I've observed) where we aren't evaluating 2981 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2982 // just give up. 2983 if (!LHSValue.isVector()) { 2984 assert(LHSValue.isLValue() && 2985 "A vector result that isn't a vector OR uncalculated LValue"); 2986 Info.FFDiag(E); 2987 return false; 2988 } 2989 2990 assert(LHSValue.getVectorLength() == NumElements && 2991 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2992 2993 SmallVector<APValue, 4> ResultElements; 2994 2995 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2996 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2997 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2998 2999 if (EltTy->isIntegerType()) { 3000 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 3001 EltTy->isUnsignedIntegerType()}; 3002 bool Success = true; 3003 3004 if (BinaryOperator::isLogicalOp(Opcode)) 3005 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3006 else if (BinaryOperator::isComparisonOp(Opcode)) 3007 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3008 else 3009 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 3010 RHSElt.getInt(), EltResult); 3011 3012 if (!Success) { 3013 Info.FFDiag(E); 3014 return false; 3015 } 3016 ResultElements.emplace_back(EltResult); 3017 3018 } else if (EltTy->isFloatingType()) { 3019 assert(LHSElt.getKind() == APValue::Float && 3020 RHSElt.getKind() == APValue::Float && 3021 "Mismatched LHS/RHS/Result Type"); 3022 APFloat LHSFloat = LHSElt.getFloat(); 3023 3024 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3025 RHSElt.getFloat())) { 3026 Info.FFDiag(E); 3027 return false; 3028 } 3029 3030 ResultElements.emplace_back(LHSFloat); 3031 } 3032 } 3033 3034 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3035 return true; 3036 } 3037 3038 /// Cast an lvalue referring to a base subobject to a derived class, by 3039 /// truncating the lvalue's path to the given length. 3040 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3041 const RecordDecl *TruncatedType, 3042 unsigned TruncatedElements) { 3043 SubobjectDesignator &D = Result.Designator; 3044 3045 // Check we actually point to a derived class object. 3046 if (TruncatedElements == D.Entries.size()) 3047 return true; 3048 assert(TruncatedElements >= D.MostDerivedPathLength && 3049 "not casting to a derived class"); 3050 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3051 return false; 3052 3053 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3054 const RecordDecl *RD = TruncatedType; 3055 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3056 if (RD->isInvalidDecl()) return false; 3057 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3058 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3059 if (isVirtualBaseClass(D.Entries[I])) 3060 Result.Offset -= Layout.getVBaseClassOffset(Base); 3061 else 3062 Result.Offset -= Layout.getBaseClassOffset(Base); 3063 RD = Base; 3064 } 3065 D.Entries.resize(TruncatedElements); 3066 return true; 3067 } 3068 3069 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3070 const CXXRecordDecl *Derived, 3071 const CXXRecordDecl *Base, 3072 const ASTRecordLayout *RL = nullptr) { 3073 if (!RL) { 3074 if (Derived->isInvalidDecl()) return false; 3075 RL = &Info.Ctx.getASTRecordLayout(Derived); 3076 } 3077 3078 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3079 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3080 return true; 3081 } 3082 3083 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3084 const CXXRecordDecl *DerivedDecl, 3085 const CXXBaseSpecifier *Base) { 3086 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3087 3088 if (!Base->isVirtual()) 3089 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3090 3091 SubobjectDesignator &D = Obj.Designator; 3092 if (D.Invalid) 3093 return false; 3094 3095 // Extract most-derived object and corresponding type. 3096 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3097 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3098 return false; 3099 3100 // Find the virtual base class. 3101 if (DerivedDecl->isInvalidDecl()) return false; 3102 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3103 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3104 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3105 return true; 3106 } 3107 3108 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3109 QualType Type, LValue &Result) { 3110 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3111 PathE = E->path_end(); 3112 PathI != PathE; ++PathI) { 3113 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3114 *PathI)) 3115 return false; 3116 Type = (*PathI)->getType(); 3117 } 3118 return true; 3119 } 3120 3121 /// Cast an lvalue referring to a derived class to a known base subobject. 3122 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3123 const CXXRecordDecl *DerivedRD, 3124 const CXXRecordDecl *BaseRD) { 3125 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3126 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3127 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3128 llvm_unreachable("Class must be derived from the passed in base class!"); 3129 3130 for (CXXBasePathElement &Elem : Paths.front()) 3131 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3132 return false; 3133 return true; 3134 } 3135 3136 /// Update LVal to refer to the given field, which must be a member of the type 3137 /// currently described by LVal. 3138 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3139 const FieldDecl *FD, 3140 const ASTRecordLayout *RL = nullptr) { 3141 if (!RL) { 3142 if (FD->getParent()->isInvalidDecl()) return false; 3143 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3144 } 3145 3146 unsigned I = FD->getFieldIndex(); 3147 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3148 LVal.addDecl(Info, E, FD); 3149 return true; 3150 } 3151 3152 /// Update LVal to refer to the given indirect field. 3153 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3154 LValue &LVal, 3155 const IndirectFieldDecl *IFD) { 3156 for (const auto *C : IFD->chain()) 3157 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3158 return false; 3159 return true; 3160 } 3161 3162 /// Get the size of the given type in char units. 3163 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3164 QualType Type, CharUnits &Size) { 3165 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3166 // extension. 3167 if (Type->isVoidType() || Type->isFunctionType()) { 3168 Size = CharUnits::One(); 3169 return true; 3170 } 3171 3172 if (Type->isDependentType()) { 3173 Info.FFDiag(Loc); 3174 return false; 3175 } 3176 3177 if (!Type->isConstantSizeType()) { 3178 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3179 // FIXME: Better diagnostic. 3180 Info.FFDiag(Loc); 3181 return false; 3182 } 3183 3184 Size = Info.Ctx.getTypeSizeInChars(Type); 3185 return true; 3186 } 3187 3188 /// Update a pointer value to model pointer arithmetic. 3189 /// \param Info - Information about the ongoing evaluation. 3190 /// \param E - The expression being evaluated, for diagnostic purposes. 3191 /// \param LVal - The pointer value to be updated. 3192 /// \param EltTy - The pointee type represented by LVal. 3193 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3194 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3195 LValue &LVal, QualType EltTy, 3196 APSInt Adjustment) { 3197 CharUnits SizeOfPointee; 3198 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3199 return false; 3200 3201 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3202 return true; 3203 } 3204 3205 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3206 LValue &LVal, QualType EltTy, 3207 int64_t Adjustment) { 3208 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3209 APSInt::get(Adjustment)); 3210 } 3211 3212 /// Update an lvalue to refer to a component of a complex number. 3213 /// \param Info - Information about the ongoing evaluation. 3214 /// \param LVal - The lvalue to be updated. 3215 /// \param EltTy - The complex number's component type. 3216 /// \param Imag - False for the real component, true for the imaginary. 3217 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3218 LValue &LVal, QualType EltTy, 3219 bool Imag) { 3220 if (Imag) { 3221 CharUnits SizeOfComponent; 3222 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3223 return false; 3224 LVal.Offset += SizeOfComponent; 3225 } 3226 LVal.addComplex(Info, E, EltTy, Imag); 3227 return true; 3228 } 3229 3230 /// Try to evaluate the initializer for a variable declaration. 3231 /// 3232 /// \param Info Information about the ongoing evaluation. 3233 /// \param E An expression to be used when printing diagnostics. 3234 /// \param VD The variable whose initializer should be obtained. 3235 /// \param Version The version of the variable within the frame. 3236 /// \param Frame The frame in which the variable was created. Must be null 3237 /// if this variable is not local to the evaluation. 3238 /// \param Result Filled in with a pointer to the value of the variable. 3239 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3240 const VarDecl *VD, CallStackFrame *Frame, 3241 unsigned Version, APValue *&Result) { 3242 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3243 3244 // If this is a local variable, dig out its value. 3245 if (Frame) { 3246 Result = Frame->getTemporary(VD, Version); 3247 if (Result) 3248 return true; 3249 3250 if (!isa<ParmVarDecl>(VD)) { 3251 // Assume variables referenced within a lambda's call operator that were 3252 // not declared within the call operator are captures and during checking 3253 // of a potential constant expression, assume they are unknown constant 3254 // expressions. 3255 assert(isLambdaCallOperator(Frame->Callee) && 3256 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3257 "missing value for local variable"); 3258 if (Info.checkingPotentialConstantExpression()) 3259 return false; 3260 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3261 // still reachable at all? 3262 Info.FFDiag(E->getBeginLoc(), 3263 diag::note_unimplemented_constexpr_lambda_feature_ast) 3264 << "captures not currently allowed"; 3265 return false; 3266 } 3267 } 3268 3269 // If we're currently evaluating the initializer of this declaration, use that 3270 // in-flight value. 3271 if (Info.EvaluatingDecl == Base) { 3272 Result = Info.EvaluatingDeclValue; 3273 return true; 3274 } 3275 3276 if (isa<ParmVarDecl>(VD)) { 3277 // Assume parameters of a potential constant expression are usable in 3278 // constant expressions. 3279 if (!Info.checkingPotentialConstantExpression() || 3280 !Info.CurrentCall->Callee || 3281 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3282 if (Info.getLangOpts().CPlusPlus11) { 3283 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3284 << VD; 3285 NoteLValueLocation(Info, Base); 3286 } else { 3287 Info.FFDiag(E); 3288 } 3289 } 3290 return false; 3291 } 3292 3293 // Dig out the initializer, and use the declaration which it's attached to. 3294 // FIXME: We should eventually check whether the variable has a reachable 3295 // initializing declaration. 3296 const Expr *Init = VD->getAnyInitializer(VD); 3297 if (!Init) { 3298 // Don't diagnose during potential constant expression checking; an 3299 // initializer might be added later. 3300 if (!Info.checkingPotentialConstantExpression()) { 3301 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3302 << VD; 3303 NoteLValueLocation(Info, Base); 3304 } 3305 return false; 3306 } 3307 3308 if (Init->isValueDependent()) { 3309 // The DeclRefExpr is not value-dependent, but the variable it refers to 3310 // has a value-dependent initializer. This should only happen in 3311 // constant-folding cases, where the variable is not actually of a suitable 3312 // type for use in a constant expression (otherwise the DeclRefExpr would 3313 // have been value-dependent too), so diagnose that. 3314 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3315 if (!Info.checkingPotentialConstantExpression()) { 3316 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3317 ? diag::note_constexpr_ltor_non_constexpr 3318 : diag::note_constexpr_ltor_non_integral, 1) 3319 << VD << VD->getType(); 3320 NoteLValueLocation(Info, Base); 3321 } 3322 return false; 3323 } 3324 3325 // Check that we can fold the initializer. In C++, we will have already done 3326 // this in the cases where it matters for conformance. 3327 if (!VD->evaluateValue()) { 3328 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3329 NoteLValueLocation(Info, Base); 3330 return false; 3331 } 3332 3333 // Check that the variable is actually usable in constant expressions. For a 3334 // const integral variable or a reference, we might have a non-constant 3335 // initializer that we can nonetheless evaluate the initializer for. Such 3336 // variables are not usable in constant expressions. In C++98, the 3337 // initializer also syntactically needs to be an ICE. 3338 // 3339 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3340 // expressions here; doing so would regress diagnostics for things like 3341 // reading from a volatile constexpr variable. 3342 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3343 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3344 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3345 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3346 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3347 NoteLValueLocation(Info, Base); 3348 } 3349 3350 // Never use the initializer of a weak variable, not even for constant 3351 // folding. We can't be sure that this is the definition that will be used. 3352 if (VD->isWeak()) { 3353 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3354 NoteLValueLocation(Info, Base); 3355 return false; 3356 } 3357 3358 Result = VD->getEvaluatedValue(); 3359 return true; 3360 } 3361 3362 /// Get the base index of the given base class within an APValue representing 3363 /// the given derived class. 3364 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3365 const CXXRecordDecl *Base) { 3366 Base = Base->getCanonicalDecl(); 3367 unsigned Index = 0; 3368 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3369 E = Derived->bases_end(); I != E; ++I, ++Index) { 3370 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3371 return Index; 3372 } 3373 3374 llvm_unreachable("base class missing from derived class's bases list"); 3375 } 3376 3377 /// Extract the value of a character from a string literal. 3378 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3379 uint64_t Index) { 3380 assert(!isa<SourceLocExpr>(Lit) && 3381 "SourceLocExpr should have already been converted to a StringLiteral"); 3382 3383 // FIXME: Support MakeStringConstant 3384 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3385 std::string Str; 3386 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3387 assert(Index <= Str.size() && "Index too large"); 3388 return APSInt::getUnsigned(Str.c_str()[Index]); 3389 } 3390 3391 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3392 Lit = PE->getFunctionName(); 3393 const StringLiteral *S = cast<StringLiteral>(Lit); 3394 const ConstantArrayType *CAT = 3395 Info.Ctx.getAsConstantArrayType(S->getType()); 3396 assert(CAT && "string literal isn't an array"); 3397 QualType CharType = CAT->getElementType(); 3398 assert(CharType->isIntegerType() && "unexpected character type"); 3399 3400 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3401 CharType->isUnsignedIntegerType()); 3402 if (Index < S->getLength()) 3403 Value = S->getCodeUnit(Index); 3404 return Value; 3405 } 3406 3407 // Expand a string literal into an array of characters. 3408 // 3409 // FIXME: This is inefficient; we should probably introduce something similar 3410 // to the LLVM ConstantDataArray to make this cheaper. 3411 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3412 APValue &Result, 3413 QualType AllocType = QualType()) { 3414 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3415 AllocType.isNull() ? S->getType() : AllocType); 3416 assert(CAT && "string literal isn't an array"); 3417 QualType CharType = CAT->getElementType(); 3418 assert(CharType->isIntegerType() && "unexpected character type"); 3419 3420 unsigned Elts = CAT->getSize().getZExtValue(); 3421 Result = APValue(APValue::UninitArray(), 3422 std::min(S->getLength(), Elts), Elts); 3423 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3424 CharType->isUnsignedIntegerType()); 3425 if (Result.hasArrayFiller()) 3426 Result.getArrayFiller() = APValue(Value); 3427 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3428 Value = S->getCodeUnit(I); 3429 Result.getArrayInitializedElt(I) = APValue(Value); 3430 } 3431 } 3432 3433 // Expand an array so that it has more than Index filled elements. 3434 static void expandArray(APValue &Array, unsigned Index) { 3435 unsigned Size = Array.getArraySize(); 3436 assert(Index < Size); 3437 3438 // Always at least double the number of elements for which we store a value. 3439 unsigned OldElts = Array.getArrayInitializedElts(); 3440 unsigned NewElts = std::max(Index+1, OldElts * 2); 3441 NewElts = std::min(Size, std::max(NewElts, 8u)); 3442 3443 // Copy the data across. 3444 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3445 for (unsigned I = 0; I != OldElts; ++I) 3446 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3447 for (unsigned I = OldElts; I != NewElts; ++I) 3448 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3449 if (NewValue.hasArrayFiller()) 3450 NewValue.getArrayFiller() = Array.getArrayFiller(); 3451 Array.swap(NewValue); 3452 } 3453 3454 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3455 /// conversion. If it's of class type, we may assume that the copy operation 3456 /// is trivial. Note that this is never true for a union type with fields 3457 /// (because the copy always "reads" the active member) and always true for 3458 /// a non-class type. 3459 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3460 static bool isReadByLvalueToRvalueConversion(QualType T) { 3461 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3462 return !RD || isReadByLvalueToRvalueConversion(RD); 3463 } 3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3465 // FIXME: A trivial copy of a union copies the object representation, even if 3466 // the union is empty. 3467 if (RD->isUnion()) 3468 return !RD->field_empty(); 3469 if (RD->isEmpty()) 3470 return false; 3471 3472 for (auto *Field : RD->fields()) 3473 if (!Field->isUnnamedBitfield() && 3474 isReadByLvalueToRvalueConversion(Field->getType())) 3475 return true; 3476 3477 for (auto &BaseSpec : RD->bases()) 3478 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3479 return true; 3480 3481 return false; 3482 } 3483 3484 /// Diagnose an attempt to read from any unreadable field within the specified 3485 /// type, which might be a class type. 3486 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3487 QualType T) { 3488 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3489 if (!RD) 3490 return false; 3491 3492 if (!RD->hasMutableFields()) 3493 return false; 3494 3495 for (auto *Field : RD->fields()) { 3496 // If we're actually going to read this field in some way, then it can't 3497 // be mutable. If we're in a union, then assigning to a mutable field 3498 // (even an empty one) can change the active member, so that's not OK. 3499 // FIXME: Add core issue number for the union case. 3500 if (Field->isMutable() && 3501 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3502 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3503 Info.Note(Field->getLocation(), diag::note_declared_at); 3504 return true; 3505 } 3506 3507 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3508 return true; 3509 } 3510 3511 for (auto &BaseSpec : RD->bases()) 3512 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3513 return true; 3514 3515 // All mutable fields were empty, and thus not actually read. 3516 return false; 3517 } 3518 3519 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3520 APValue::LValueBase Base, 3521 bool MutableSubobject = false) { 3522 // A temporary or transient heap allocation we created. 3523 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3524 return true; 3525 3526 switch (Info.IsEvaluatingDecl) { 3527 case EvalInfo::EvaluatingDeclKind::None: 3528 return false; 3529 3530 case EvalInfo::EvaluatingDeclKind::Ctor: 3531 // The variable whose initializer we're evaluating. 3532 if (Info.EvaluatingDecl == Base) 3533 return true; 3534 3535 // A temporary lifetime-extended by the variable whose initializer we're 3536 // evaluating. 3537 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3538 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3539 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3540 return false; 3541 3542 case EvalInfo::EvaluatingDeclKind::Dtor: 3543 // C++2a [expr.const]p6: 3544 // [during constant destruction] the lifetime of a and its non-mutable 3545 // subobjects (but not its mutable subobjects) [are] considered to start 3546 // within e. 3547 if (MutableSubobject || Base != Info.EvaluatingDecl) 3548 return false; 3549 // FIXME: We can meaningfully extend this to cover non-const objects, but 3550 // we will need special handling: we should be able to access only 3551 // subobjects of such objects that are themselves declared const. 3552 QualType T = getType(Base); 3553 return T.isConstQualified() || T->isReferenceType(); 3554 } 3555 3556 llvm_unreachable("unknown evaluating decl kind"); 3557 } 3558 3559 namespace { 3560 /// A handle to a complete object (an object that is not a subobject of 3561 /// another object). 3562 struct CompleteObject { 3563 /// The identity of the object. 3564 APValue::LValueBase Base; 3565 /// The value of the complete object. 3566 APValue *Value; 3567 /// The type of the complete object. 3568 QualType Type; 3569 3570 CompleteObject() : Value(nullptr) {} 3571 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3572 : Base(Base), Value(Value), Type(Type) {} 3573 3574 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3575 // If this isn't a "real" access (eg, if it's just accessing the type 3576 // info), allow it. We assume the type doesn't change dynamically for 3577 // subobjects of constexpr objects (even though we'd hit UB here if it 3578 // did). FIXME: Is this right? 3579 if (!isAnyAccess(AK)) 3580 return true; 3581 3582 // In C++14 onwards, it is permitted to read a mutable member whose 3583 // lifetime began within the evaluation. 3584 // FIXME: Should we also allow this in C++11? 3585 if (!Info.getLangOpts().CPlusPlus14) 3586 return false; 3587 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3588 } 3589 3590 explicit operator bool() const { return !Type.isNull(); } 3591 }; 3592 } // end anonymous namespace 3593 3594 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3595 bool IsMutable = false) { 3596 // C++ [basic.type.qualifier]p1: 3597 // - A const object is an object of type const T or a non-mutable subobject 3598 // of a const object. 3599 if (ObjType.isConstQualified() && !IsMutable) 3600 SubobjType.addConst(); 3601 // - A volatile object is an object of type const T or a subobject of a 3602 // volatile object. 3603 if (ObjType.isVolatileQualified()) 3604 SubobjType.addVolatile(); 3605 return SubobjType; 3606 } 3607 3608 /// Find the designated sub-object of an rvalue. 3609 template<typename SubobjectHandler> 3610 typename SubobjectHandler::result_type 3611 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3612 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3613 if (Sub.Invalid) 3614 // A diagnostic will have already been produced. 3615 return handler.failed(); 3616 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3617 if (Info.getLangOpts().CPlusPlus11) 3618 Info.FFDiag(E, Sub.isOnePastTheEnd() 3619 ? diag::note_constexpr_access_past_end 3620 : diag::note_constexpr_access_unsized_array) 3621 << handler.AccessKind; 3622 else 3623 Info.FFDiag(E); 3624 return handler.failed(); 3625 } 3626 3627 APValue *O = Obj.Value; 3628 QualType ObjType = Obj.Type; 3629 const FieldDecl *LastField = nullptr; 3630 const FieldDecl *VolatileField = nullptr; 3631 3632 // Walk the designator's path to find the subobject. 3633 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3634 // Reading an indeterminate value is undefined, but assigning over one is OK. 3635 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3636 (O->isIndeterminate() && 3637 !isValidIndeterminateAccess(handler.AccessKind))) { 3638 if (!Info.checkingPotentialConstantExpression()) 3639 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3640 << handler.AccessKind << O->isIndeterminate(); 3641 return handler.failed(); 3642 } 3643 3644 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3645 // const and volatile semantics are not applied on an object under 3646 // {con,de}struction. 3647 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3648 ObjType->isRecordType() && 3649 Info.isEvaluatingCtorDtor( 3650 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3651 Sub.Entries.begin() + I)) != 3652 ConstructionPhase::None) { 3653 ObjType = Info.Ctx.getCanonicalType(ObjType); 3654 ObjType.removeLocalConst(); 3655 ObjType.removeLocalVolatile(); 3656 } 3657 3658 // If this is our last pass, check that the final object type is OK. 3659 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3660 // Accesses to volatile objects are prohibited. 3661 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3662 if (Info.getLangOpts().CPlusPlus) { 3663 int DiagKind; 3664 SourceLocation Loc; 3665 const NamedDecl *Decl = nullptr; 3666 if (VolatileField) { 3667 DiagKind = 2; 3668 Loc = VolatileField->getLocation(); 3669 Decl = VolatileField; 3670 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3671 DiagKind = 1; 3672 Loc = VD->getLocation(); 3673 Decl = VD; 3674 } else { 3675 DiagKind = 0; 3676 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3677 Loc = E->getExprLoc(); 3678 } 3679 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3680 << handler.AccessKind << DiagKind << Decl; 3681 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3682 } else { 3683 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3684 } 3685 return handler.failed(); 3686 } 3687 3688 // If we are reading an object of class type, there may still be more 3689 // things we need to check: if there are any mutable subobjects, we 3690 // cannot perform this read. (This only happens when performing a trivial 3691 // copy or assignment.) 3692 if (ObjType->isRecordType() && 3693 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3694 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3695 return handler.failed(); 3696 } 3697 3698 if (I == N) { 3699 if (!handler.found(*O, ObjType)) 3700 return false; 3701 3702 // If we modified a bit-field, truncate it to the right width. 3703 if (isModification(handler.AccessKind) && 3704 LastField && LastField->isBitField() && 3705 !truncateBitfieldValue(Info, E, *O, LastField)) 3706 return false; 3707 3708 return true; 3709 } 3710 3711 LastField = nullptr; 3712 if (ObjType->isArrayType()) { 3713 // Next subobject is an array element. 3714 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3715 assert(CAT && "vla in literal type?"); 3716 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3717 if (CAT->getSize().ule(Index)) { 3718 // Note, it should not be possible to form a pointer with a valid 3719 // designator which points more than one past the end of the array. 3720 if (Info.getLangOpts().CPlusPlus11) 3721 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3722 << handler.AccessKind; 3723 else 3724 Info.FFDiag(E); 3725 return handler.failed(); 3726 } 3727 3728 ObjType = CAT->getElementType(); 3729 3730 if (O->getArrayInitializedElts() > Index) 3731 O = &O->getArrayInitializedElt(Index); 3732 else if (!isRead(handler.AccessKind)) { 3733 expandArray(*O, Index); 3734 O = &O->getArrayInitializedElt(Index); 3735 } else 3736 O = &O->getArrayFiller(); 3737 } else if (ObjType->isAnyComplexType()) { 3738 // Next subobject is a complex number. 3739 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3740 if (Index > 1) { 3741 if (Info.getLangOpts().CPlusPlus11) 3742 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3743 << handler.AccessKind; 3744 else 3745 Info.FFDiag(E); 3746 return handler.failed(); 3747 } 3748 3749 ObjType = getSubobjectType( 3750 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3751 3752 assert(I == N - 1 && "extracting subobject of scalar?"); 3753 if (O->isComplexInt()) { 3754 return handler.found(Index ? O->getComplexIntImag() 3755 : O->getComplexIntReal(), ObjType); 3756 } else { 3757 assert(O->isComplexFloat()); 3758 return handler.found(Index ? O->getComplexFloatImag() 3759 : O->getComplexFloatReal(), ObjType); 3760 } 3761 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3762 if (Field->isMutable() && 3763 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3764 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3765 << handler.AccessKind << Field; 3766 Info.Note(Field->getLocation(), diag::note_declared_at); 3767 return handler.failed(); 3768 } 3769 3770 // Next subobject is a class, struct or union field. 3771 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3772 if (RD->isUnion()) { 3773 const FieldDecl *UnionField = O->getUnionField(); 3774 if (!UnionField || 3775 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3776 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3777 // Placement new onto an inactive union member makes it active. 3778 O->setUnion(Field, APValue()); 3779 } else { 3780 // FIXME: If O->getUnionValue() is absent, report that there's no 3781 // active union member rather than reporting the prior active union 3782 // member. We'll need to fix nullptr_t to not use APValue() as its 3783 // representation first. 3784 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3785 << handler.AccessKind << Field << !UnionField << UnionField; 3786 return handler.failed(); 3787 } 3788 } 3789 O = &O->getUnionValue(); 3790 } else 3791 O = &O->getStructField(Field->getFieldIndex()); 3792 3793 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3794 LastField = Field; 3795 if (Field->getType().isVolatileQualified()) 3796 VolatileField = Field; 3797 } else { 3798 // Next subobject is a base class. 3799 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3800 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3801 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3802 3803 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3804 } 3805 } 3806 } 3807 3808 namespace { 3809 struct ExtractSubobjectHandler { 3810 EvalInfo &Info; 3811 const Expr *E; 3812 APValue &Result; 3813 const AccessKinds AccessKind; 3814 3815 typedef bool result_type; 3816 bool failed() { return false; } 3817 bool found(APValue &Subobj, QualType SubobjType) { 3818 Result = Subobj; 3819 if (AccessKind == AK_ReadObjectRepresentation) 3820 return true; 3821 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3822 } 3823 bool found(APSInt &Value, QualType SubobjType) { 3824 Result = APValue(Value); 3825 return true; 3826 } 3827 bool found(APFloat &Value, QualType SubobjType) { 3828 Result = APValue(Value); 3829 return true; 3830 } 3831 }; 3832 } // end anonymous namespace 3833 3834 /// Extract the designated sub-object of an rvalue. 3835 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3836 const CompleteObject &Obj, 3837 const SubobjectDesignator &Sub, APValue &Result, 3838 AccessKinds AK = AK_Read) { 3839 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3840 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3841 return findSubobject(Info, E, Obj, Sub, Handler); 3842 } 3843 3844 namespace { 3845 struct ModifySubobjectHandler { 3846 EvalInfo &Info; 3847 APValue &NewVal; 3848 const Expr *E; 3849 3850 typedef bool result_type; 3851 static const AccessKinds AccessKind = AK_Assign; 3852 3853 bool checkConst(QualType QT) { 3854 // Assigning to a const object has undefined behavior. 3855 if (QT.isConstQualified()) { 3856 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3857 return false; 3858 } 3859 return true; 3860 } 3861 3862 bool failed() { return false; } 3863 bool found(APValue &Subobj, QualType SubobjType) { 3864 if (!checkConst(SubobjType)) 3865 return false; 3866 // We've been given ownership of NewVal, so just swap it in. 3867 Subobj.swap(NewVal); 3868 return true; 3869 } 3870 bool found(APSInt &Value, QualType SubobjType) { 3871 if (!checkConst(SubobjType)) 3872 return false; 3873 if (!NewVal.isInt()) { 3874 // Maybe trying to write a cast pointer value into a complex? 3875 Info.FFDiag(E); 3876 return false; 3877 } 3878 Value = NewVal.getInt(); 3879 return true; 3880 } 3881 bool found(APFloat &Value, QualType SubobjType) { 3882 if (!checkConst(SubobjType)) 3883 return false; 3884 Value = NewVal.getFloat(); 3885 return true; 3886 } 3887 }; 3888 } // end anonymous namespace 3889 3890 const AccessKinds ModifySubobjectHandler::AccessKind; 3891 3892 /// Update the designated sub-object of an rvalue to the given value. 3893 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3894 const CompleteObject &Obj, 3895 const SubobjectDesignator &Sub, 3896 APValue &NewVal) { 3897 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3898 return findSubobject(Info, E, Obj, Sub, Handler); 3899 } 3900 3901 /// Find the position where two subobject designators diverge, or equivalently 3902 /// the length of the common initial subsequence. 3903 static unsigned FindDesignatorMismatch(QualType ObjType, 3904 const SubobjectDesignator &A, 3905 const SubobjectDesignator &B, 3906 bool &WasArrayIndex) { 3907 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3908 for (/**/; I != N; ++I) { 3909 if (!ObjType.isNull() && 3910 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3911 // Next subobject is an array element. 3912 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3913 WasArrayIndex = true; 3914 return I; 3915 } 3916 if (ObjType->isAnyComplexType()) 3917 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3918 else 3919 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3920 } else { 3921 if (A.Entries[I].getAsBaseOrMember() != 3922 B.Entries[I].getAsBaseOrMember()) { 3923 WasArrayIndex = false; 3924 return I; 3925 } 3926 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3927 // Next subobject is a field. 3928 ObjType = FD->getType(); 3929 else 3930 // Next subobject is a base class. 3931 ObjType = QualType(); 3932 } 3933 } 3934 WasArrayIndex = false; 3935 return I; 3936 } 3937 3938 /// Determine whether the given subobject designators refer to elements of the 3939 /// same array object. 3940 static bool AreElementsOfSameArray(QualType ObjType, 3941 const SubobjectDesignator &A, 3942 const SubobjectDesignator &B) { 3943 if (A.Entries.size() != B.Entries.size()) 3944 return false; 3945 3946 bool IsArray = A.MostDerivedIsArrayElement; 3947 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3948 // A is a subobject of the array element. 3949 return false; 3950 3951 // If A (and B) designates an array element, the last entry will be the array 3952 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3953 // of length 1' case, and the entire path must match. 3954 bool WasArrayIndex; 3955 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3956 return CommonLength >= A.Entries.size() - IsArray; 3957 } 3958 3959 /// Find the complete object to which an LValue refers. 3960 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3961 AccessKinds AK, const LValue &LVal, 3962 QualType LValType) { 3963 if (LVal.InvalidBase) { 3964 Info.FFDiag(E); 3965 return CompleteObject(); 3966 } 3967 3968 if (!LVal.Base) { 3969 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3970 return CompleteObject(); 3971 } 3972 3973 CallStackFrame *Frame = nullptr; 3974 unsigned Depth = 0; 3975 if (LVal.getLValueCallIndex()) { 3976 std::tie(Frame, Depth) = 3977 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3978 if (!Frame) { 3979 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3980 << AK << LVal.Base.is<const ValueDecl*>(); 3981 NoteLValueLocation(Info, LVal.Base); 3982 return CompleteObject(); 3983 } 3984 } 3985 3986 bool IsAccess = isAnyAccess(AK); 3987 3988 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3989 // is not a constant expression (even if the object is non-volatile). We also 3990 // apply this rule to C++98, in order to conform to the expected 'volatile' 3991 // semantics. 3992 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3993 if (Info.getLangOpts().CPlusPlus) 3994 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3995 << AK << LValType; 3996 else 3997 Info.FFDiag(E); 3998 return CompleteObject(); 3999 } 4000 4001 // Compute value storage location and type of base object. 4002 APValue *BaseVal = nullptr; 4003 QualType BaseType = getType(LVal.Base); 4004 4005 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 4006 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4007 // This is the object whose initializer we're evaluating, so its lifetime 4008 // started in the current evaluation. 4009 BaseVal = Info.EvaluatingDeclValue; 4010 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4011 // Allow reading from a GUID declaration. 4012 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4013 if (isModification(AK)) { 4014 // All the remaining cases do not permit modification of the object. 4015 Info.FFDiag(E, diag::note_constexpr_modify_global); 4016 return CompleteObject(); 4017 } 4018 APValue &V = GD->getAsAPValue(); 4019 if (V.isAbsent()) { 4020 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4021 << GD->getType(); 4022 return CompleteObject(); 4023 } 4024 return CompleteObject(LVal.Base, &V, GD->getType()); 4025 } 4026 4027 // Allow reading from template parameter objects. 4028 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4029 if (isModification(AK)) { 4030 Info.FFDiag(E, diag::note_constexpr_modify_global); 4031 return CompleteObject(); 4032 } 4033 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4034 TPO->getType()); 4035 } 4036 4037 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4038 // In C++11, constexpr, non-volatile variables initialized with constant 4039 // expressions are constant expressions too. Inside constexpr functions, 4040 // parameters are constant expressions even if they're non-const. 4041 // In C++1y, objects local to a constant expression (those with a Frame) are 4042 // both readable and writable inside constant expressions. 4043 // In C, such things can also be folded, although they are not ICEs. 4044 const VarDecl *VD = dyn_cast<VarDecl>(D); 4045 if (VD) { 4046 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4047 VD = VDef; 4048 } 4049 if (!VD || VD->isInvalidDecl()) { 4050 Info.FFDiag(E); 4051 return CompleteObject(); 4052 } 4053 4054 bool IsConstant = BaseType.isConstant(Info.Ctx); 4055 4056 // Unless we're looking at a local variable or argument in a constexpr call, 4057 // the variable we're reading must be const. 4058 if (!Frame) { 4059 if (IsAccess && isa<ParmVarDecl>(VD)) { 4060 // Access of a parameter that's not associated with a frame isn't going 4061 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4062 // suitable diagnostic. 4063 } else if (Info.getLangOpts().CPlusPlus14 && 4064 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4065 // OK, we can read and modify an object if we're in the process of 4066 // evaluating its initializer, because its lifetime began in this 4067 // evaluation. 4068 } else if (isModification(AK)) { 4069 // All the remaining cases do not permit modification of the object. 4070 Info.FFDiag(E, diag::note_constexpr_modify_global); 4071 return CompleteObject(); 4072 } else if (VD->isConstexpr()) { 4073 // OK, we can read this variable. 4074 } else if (BaseType->isIntegralOrEnumerationType()) { 4075 if (!IsConstant) { 4076 if (!IsAccess) 4077 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4078 if (Info.getLangOpts().CPlusPlus) { 4079 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4080 Info.Note(VD->getLocation(), diag::note_declared_at); 4081 } else { 4082 Info.FFDiag(E); 4083 } 4084 return CompleteObject(); 4085 } 4086 } else if (!IsAccess) { 4087 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4088 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4089 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4090 // This variable might end up being constexpr. Don't diagnose it yet. 4091 } else if (IsConstant) { 4092 // Keep evaluating to see what we can do. In particular, we support 4093 // folding of const floating-point types, in order to make static const 4094 // data members of such types (supported as an extension) more useful. 4095 if (Info.getLangOpts().CPlusPlus) { 4096 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4097 ? diag::note_constexpr_ltor_non_constexpr 4098 : diag::note_constexpr_ltor_non_integral, 1) 4099 << VD << BaseType; 4100 Info.Note(VD->getLocation(), diag::note_declared_at); 4101 } else { 4102 Info.CCEDiag(E); 4103 } 4104 } else { 4105 // Never allow reading a non-const value. 4106 if (Info.getLangOpts().CPlusPlus) { 4107 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4108 ? diag::note_constexpr_ltor_non_constexpr 4109 : diag::note_constexpr_ltor_non_integral, 1) 4110 << VD << BaseType; 4111 Info.Note(VD->getLocation(), diag::note_declared_at); 4112 } else { 4113 Info.FFDiag(E); 4114 } 4115 return CompleteObject(); 4116 } 4117 } 4118 4119 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4120 return CompleteObject(); 4121 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4122 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4123 if (!Alloc) { 4124 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4125 return CompleteObject(); 4126 } 4127 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4128 LVal.Base.getDynamicAllocType()); 4129 } else { 4130 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4131 4132 if (!Frame) { 4133 if (const MaterializeTemporaryExpr *MTE = 4134 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4135 assert(MTE->getStorageDuration() == SD_Static && 4136 "should have a frame for a non-global materialized temporary"); 4137 4138 // C++20 [expr.const]p4: [DR2126] 4139 // An object or reference is usable in constant expressions if it is 4140 // - a temporary object of non-volatile const-qualified literal type 4141 // whose lifetime is extended to that of a variable that is usable 4142 // in constant expressions 4143 // 4144 // C++20 [expr.const]p5: 4145 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4146 // - a non-volatile glvalue that refers to an object that is usable 4147 // in constant expressions, or 4148 // - a non-volatile glvalue of literal type that refers to a 4149 // non-volatile object whose lifetime began within the evaluation 4150 // of E; 4151 // 4152 // C++11 misses the 'began within the evaluation of e' check and 4153 // instead allows all temporaries, including things like: 4154 // int &&r = 1; 4155 // int x = ++r; 4156 // constexpr int k = r; 4157 // Therefore we use the C++14-onwards rules in C++11 too. 4158 // 4159 // Note that temporaries whose lifetimes began while evaluating a 4160 // variable's constructor are not usable while evaluating the 4161 // corresponding destructor, not even if they're of const-qualified 4162 // types. 4163 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4164 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4165 if (!IsAccess) 4166 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4167 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4168 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4169 return CompleteObject(); 4170 } 4171 4172 BaseVal = MTE->getOrCreateValue(false); 4173 assert(BaseVal && "got reference to unevaluated temporary"); 4174 } else { 4175 if (!IsAccess) 4176 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4177 APValue Val; 4178 LVal.moveInto(Val); 4179 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4180 << AK 4181 << Val.getAsString(Info.Ctx, 4182 Info.Ctx.getLValueReferenceType(LValType)); 4183 NoteLValueLocation(Info, LVal.Base); 4184 return CompleteObject(); 4185 } 4186 } else { 4187 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4188 assert(BaseVal && "missing value for temporary"); 4189 } 4190 } 4191 4192 // In C++14, we can't safely access any mutable state when we might be 4193 // evaluating after an unmodeled side effect. Parameters are modeled as state 4194 // in the caller, but aren't visible once the call returns, so they can be 4195 // modified in a speculatively-evaluated call. 4196 // 4197 // FIXME: Not all local state is mutable. Allow local constant subobjects 4198 // to be read here (but take care with 'mutable' fields). 4199 unsigned VisibleDepth = Depth; 4200 if (llvm::isa_and_nonnull<ParmVarDecl>( 4201 LVal.Base.dyn_cast<const ValueDecl *>())) 4202 ++VisibleDepth; 4203 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4204 Info.EvalStatus.HasSideEffects) || 4205 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4206 return CompleteObject(); 4207 4208 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4209 } 4210 4211 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4212 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4213 /// glvalue referred to by an entity of reference type. 4214 /// 4215 /// \param Info - Information about the ongoing evaluation. 4216 /// \param Conv - The expression for which we are performing the conversion. 4217 /// Used for diagnostics. 4218 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4219 /// case of a non-class type). 4220 /// \param LVal - The glvalue on which we are attempting to perform this action. 4221 /// \param RVal - The produced value will be placed here. 4222 /// \param WantObjectRepresentation - If true, we're looking for the object 4223 /// representation rather than the value, and in particular, 4224 /// there is no requirement that the result be fully initialized. 4225 static bool 4226 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4227 const LValue &LVal, APValue &RVal, 4228 bool WantObjectRepresentation = false) { 4229 if (LVal.Designator.Invalid) 4230 return false; 4231 4232 // Check for special cases where there is no existing APValue to look at. 4233 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4234 4235 AccessKinds AK = 4236 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4237 4238 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4239 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4240 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4241 // initializer until now for such expressions. Such an expression can't be 4242 // an ICE in C, so this only matters for fold. 4243 if (Type.isVolatileQualified()) { 4244 Info.FFDiag(Conv); 4245 return false; 4246 } 4247 APValue Lit; 4248 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4249 return false; 4250 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4251 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4252 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4253 // Special-case character extraction so we don't have to construct an 4254 // APValue for the whole string. 4255 assert(LVal.Designator.Entries.size() <= 1 && 4256 "Can only read characters from string literals"); 4257 if (LVal.Designator.Entries.empty()) { 4258 // Fail for now for LValue to RValue conversion of an array. 4259 // (This shouldn't show up in C/C++, but it could be triggered by a 4260 // weird EvaluateAsRValue call from a tool.) 4261 Info.FFDiag(Conv); 4262 return false; 4263 } 4264 if (LVal.Designator.isOnePastTheEnd()) { 4265 if (Info.getLangOpts().CPlusPlus11) 4266 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4267 else 4268 Info.FFDiag(Conv); 4269 return false; 4270 } 4271 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4272 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4273 return true; 4274 } 4275 } 4276 4277 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4278 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4279 } 4280 4281 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4282 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4283 QualType LValType, APValue &Val) { 4284 if (LVal.Designator.Invalid) 4285 return false; 4286 4287 if (!Info.getLangOpts().CPlusPlus14) { 4288 Info.FFDiag(E); 4289 return false; 4290 } 4291 4292 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4293 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4294 } 4295 4296 namespace { 4297 struct CompoundAssignSubobjectHandler { 4298 EvalInfo &Info; 4299 const CompoundAssignOperator *E; 4300 QualType PromotedLHSType; 4301 BinaryOperatorKind Opcode; 4302 const APValue &RHS; 4303 4304 static const AccessKinds AccessKind = AK_Assign; 4305 4306 typedef bool result_type; 4307 4308 bool checkConst(QualType QT) { 4309 // Assigning to a const object has undefined behavior. 4310 if (QT.isConstQualified()) { 4311 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4312 return false; 4313 } 4314 return true; 4315 } 4316 4317 bool failed() { return false; } 4318 bool found(APValue &Subobj, QualType SubobjType) { 4319 switch (Subobj.getKind()) { 4320 case APValue::Int: 4321 return found(Subobj.getInt(), SubobjType); 4322 case APValue::Float: 4323 return found(Subobj.getFloat(), SubobjType); 4324 case APValue::ComplexInt: 4325 case APValue::ComplexFloat: 4326 // FIXME: Implement complex compound assignment. 4327 Info.FFDiag(E); 4328 return false; 4329 case APValue::LValue: 4330 return foundPointer(Subobj, SubobjType); 4331 case APValue::Vector: 4332 return foundVector(Subobj, SubobjType); 4333 default: 4334 // FIXME: can this happen? 4335 Info.FFDiag(E); 4336 return false; 4337 } 4338 } 4339 4340 bool foundVector(APValue &Value, QualType SubobjType) { 4341 if (!checkConst(SubobjType)) 4342 return false; 4343 4344 if (!SubobjType->isVectorType()) { 4345 Info.FFDiag(E); 4346 return false; 4347 } 4348 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4349 } 4350 4351 bool found(APSInt &Value, QualType SubobjType) { 4352 if (!checkConst(SubobjType)) 4353 return false; 4354 4355 if (!SubobjType->isIntegerType()) { 4356 // We don't support compound assignment on integer-cast-to-pointer 4357 // values. 4358 Info.FFDiag(E); 4359 return false; 4360 } 4361 4362 if (RHS.isInt()) { 4363 APSInt LHS = 4364 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4365 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4366 return false; 4367 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4368 return true; 4369 } else if (RHS.isFloat()) { 4370 const FPOptions FPO = E->getFPFeaturesInEffect( 4371 Info.Ctx.getLangOpts()); 4372 APFloat FValue(0.0); 4373 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4374 PromotedLHSType, FValue) && 4375 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4376 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4377 Value); 4378 } 4379 4380 Info.FFDiag(E); 4381 return false; 4382 } 4383 bool found(APFloat &Value, QualType SubobjType) { 4384 return checkConst(SubobjType) && 4385 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4386 Value) && 4387 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4388 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4389 } 4390 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4391 if (!checkConst(SubobjType)) 4392 return false; 4393 4394 QualType PointeeType; 4395 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4396 PointeeType = PT->getPointeeType(); 4397 4398 if (PointeeType.isNull() || !RHS.isInt() || 4399 (Opcode != BO_Add && Opcode != BO_Sub)) { 4400 Info.FFDiag(E); 4401 return false; 4402 } 4403 4404 APSInt Offset = RHS.getInt(); 4405 if (Opcode == BO_Sub) 4406 negateAsSigned(Offset); 4407 4408 LValue LVal; 4409 LVal.setFrom(Info.Ctx, Subobj); 4410 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4411 return false; 4412 LVal.moveInto(Subobj); 4413 return true; 4414 } 4415 }; 4416 } // end anonymous namespace 4417 4418 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4419 4420 /// Perform a compound assignment of LVal <op>= RVal. 4421 static bool handleCompoundAssignment(EvalInfo &Info, 4422 const CompoundAssignOperator *E, 4423 const LValue &LVal, QualType LValType, 4424 QualType PromotedLValType, 4425 BinaryOperatorKind Opcode, 4426 const APValue &RVal) { 4427 if (LVal.Designator.Invalid) 4428 return false; 4429 4430 if (!Info.getLangOpts().CPlusPlus14) { 4431 Info.FFDiag(E); 4432 return false; 4433 } 4434 4435 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4436 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4437 RVal }; 4438 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4439 } 4440 4441 namespace { 4442 struct IncDecSubobjectHandler { 4443 EvalInfo &Info; 4444 const UnaryOperator *E; 4445 AccessKinds AccessKind; 4446 APValue *Old; 4447 4448 typedef bool result_type; 4449 4450 bool checkConst(QualType QT) { 4451 // Assigning to a const object has undefined behavior. 4452 if (QT.isConstQualified()) { 4453 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4454 return false; 4455 } 4456 return true; 4457 } 4458 4459 bool failed() { return false; } 4460 bool found(APValue &Subobj, QualType SubobjType) { 4461 // Stash the old value. Also clear Old, so we don't clobber it later 4462 // if we're post-incrementing a complex. 4463 if (Old) { 4464 *Old = Subobj; 4465 Old = nullptr; 4466 } 4467 4468 switch (Subobj.getKind()) { 4469 case APValue::Int: 4470 return found(Subobj.getInt(), SubobjType); 4471 case APValue::Float: 4472 return found(Subobj.getFloat(), SubobjType); 4473 case APValue::ComplexInt: 4474 return found(Subobj.getComplexIntReal(), 4475 SubobjType->castAs<ComplexType>()->getElementType() 4476 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4477 case APValue::ComplexFloat: 4478 return found(Subobj.getComplexFloatReal(), 4479 SubobjType->castAs<ComplexType>()->getElementType() 4480 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4481 case APValue::LValue: 4482 return foundPointer(Subobj, SubobjType); 4483 default: 4484 // FIXME: can this happen? 4485 Info.FFDiag(E); 4486 return false; 4487 } 4488 } 4489 bool found(APSInt &Value, QualType SubobjType) { 4490 if (!checkConst(SubobjType)) 4491 return false; 4492 4493 if (!SubobjType->isIntegerType()) { 4494 // We don't support increment / decrement on integer-cast-to-pointer 4495 // values. 4496 Info.FFDiag(E); 4497 return false; 4498 } 4499 4500 if (Old) *Old = APValue(Value); 4501 4502 // bool arithmetic promotes to int, and the conversion back to bool 4503 // doesn't reduce mod 2^n, so special-case it. 4504 if (SubobjType->isBooleanType()) { 4505 if (AccessKind == AK_Increment) 4506 Value = 1; 4507 else 4508 Value = !Value; 4509 return true; 4510 } 4511 4512 bool WasNegative = Value.isNegative(); 4513 if (AccessKind == AK_Increment) { 4514 ++Value; 4515 4516 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4517 APSInt ActualValue(Value, /*IsUnsigned*/true); 4518 return HandleOverflow(Info, E, ActualValue, SubobjType); 4519 } 4520 } else { 4521 --Value; 4522 4523 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4524 unsigned BitWidth = Value.getBitWidth(); 4525 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4526 ActualValue.setBit(BitWidth); 4527 return HandleOverflow(Info, E, ActualValue, SubobjType); 4528 } 4529 } 4530 return true; 4531 } 4532 bool found(APFloat &Value, QualType SubobjType) { 4533 if (!checkConst(SubobjType)) 4534 return false; 4535 4536 if (Old) *Old = APValue(Value); 4537 4538 APFloat One(Value.getSemantics(), 1); 4539 if (AccessKind == AK_Increment) 4540 Value.add(One, APFloat::rmNearestTiesToEven); 4541 else 4542 Value.subtract(One, APFloat::rmNearestTiesToEven); 4543 return true; 4544 } 4545 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4546 if (!checkConst(SubobjType)) 4547 return false; 4548 4549 QualType PointeeType; 4550 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4551 PointeeType = PT->getPointeeType(); 4552 else { 4553 Info.FFDiag(E); 4554 return false; 4555 } 4556 4557 LValue LVal; 4558 LVal.setFrom(Info.Ctx, Subobj); 4559 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4560 AccessKind == AK_Increment ? 1 : -1)) 4561 return false; 4562 LVal.moveInto(Subobj); 4563 return true; 4564 } 4565 }; 4566 } // end anonymous namespace 4567 4568 /// Perform an increment or decrement on LVal. 4569 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4570 QualType LValType, bool IsIncrement, APValue *Old) { 4571 if (LVal.Designator.Invalid) 4572 return false; 4573 4574 if (!Info.getLangOpts().CPlusPlus14) { 4575 Info.FFDiag(E); 4576 return false; 4577 } 4578 4579 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4580 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4581 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4582 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4583 } 4584 4585 /// Build an lvalue for the object argument of a member function call. 4586 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4587 LValue &This) { 4588 if (Object->getType()->isPointerType() && Object->isPRValue()) 4589 return EvaluatePointer(Object, This, Info); 4590 4591 if (Object->isGLValue()) 4592 return EvaluateLValue(Object, This, Info); 4593 4594 if (Object->getType()->isLiteralType(Info.Ctx)) 4595 return EvaluateTemporary(Object, This, Info); 4596 4597 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4598 return false; 4599 } 4600 4601 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4602 /// lvalue referring to the result. 4603 /// 4604 /// \param Info - Information about the ongoing evaluation. 4605 /// \param LV - An lvalue referring to the base of the member pointer. 4606 /// \param RHS - The member pointer expression. 4607 /// \param IncludeMember - Specifies whether the member itself is included in 4608 /// the resulting LValue subobject designator. This is not possible when 4609 /// creating a bound member function. 4610 /// \return The field or method declaration to which the member pointer refers, 4611 /// or 0 if evaluation fails. 4612 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4613 QualType LVType, 4614 LValue &LV, 4615 const Expr *RHS, 4616 bool IncludeMember = true) { 4617 MemberPtr MemPtr; 4618 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4619 return nullptr; 4620 4621 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4622 // member value, the behavior is undefined. 4623 if (!MemPtr.getDecl()) { 4624 // FIXME: Specific diagnostic. 4625 Info.FFDiag(RHS); 4626 return nullptr; 4627 } 4628 4629 if (MemPtr.isDerivedMember()) { 4630 // This is a member of some derived class. Truncate LV appropriately. 4631 // The end of the derived-to-base path for the base object must match the 4632 // derived-to-base path for the member pointer. 4633 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4634 LV.Designator.Entries.size()) { 4635 Info.FFDiag(RHS); 4636 return nullptr; 4637 } 4638 unsigned PathLengthToMember = 4639 LV.Designator.Entries.size() - MemPtr.Path.size(); 4640 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4641 const CXXRecordDecl *LVDecl = getAsBaseClass( 4642 LV.Designator.Entries[PathLengthToMember + I]); 4643 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4644 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4645 Info.FFDiag(RHS); 4646 return nullptr; 4647 } 4648 } 4649 4650 // Truncate the lvalue to the appropriate derived class. 4651 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4652 PathLengthToMember)) 4653 return nullptr; 4654 } else if (!MemPtr.Path.empty()) { 4655 // Extend the LValue path with the member pointer's path. 4656 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4657 MemPtr.Path.size() + IncludeMember); 4658 4659 // Walk down to the appropriate base class. 4660 if (const PointerType *PT = LVType->getAs<PointerType>()) 4661 LVType = PT->getPointeeType(); 4662 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4663 assert(RD && "member pointer access on non-class-type expression"); 4664 // The first class in the path is that of the lvalue. 4665 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4666 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4667 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4668 return nullptr; 4669 RD = Base; 4670 } 4671 // Finally cast to the class containing the member. 4672 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4673 MemPtr.getContainingRecord())) 4674 return nullptr; 4675 } 4676 4677 // Add the member. Note that we cannot build bound member functions here. 4678 if (IncludeMember) { 4679 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4680 if (!HandleLValueMember(Info, RHS, LV, FD)) 4681 return nullptr; 4682 } else if (const IndirectFieldDecl *IFD = 4683 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4684 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4685 return nullptr; 4686 } else { 4687 llvm_unreachable("can't construct reference to bound member function"); 4688 } 4689 } 4690 4691 return MemPtr.getDecl(); 4692 } 4693 4694 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4695 const BinaryOperator *BO, 4696 LValue &LV, 4697 bool IncludeMember = true) { 4698 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4699 4700 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4701 if (Info.noteFailure()) { 4702 MemberPtr MemPtr; 4703 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4704 } 4705 return nullptr; 4706 } 4707 4708 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4709 BO->getRHS(), IncludeMember); 4710 } 4711 4712 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4713 /// the provided lvalue, which currently refers to the base object. 4714 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4715 LValue &Result) { 4716 SubobjectDesignator &D = Result.Designator; 4717 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4718 return false; 4719 4720 QualType TargetQT = E->getType(); 4721 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4722 TargetQT = PT->getPointeeType(); 4723 4724 // Check this cast lands within the final derived-to-base subobject path. 4725 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4726 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4727 << D.MostDerivedType << TargetQT; 4728 return false; 4729 } 4730 4731 // Check the type of the final cast. We don't need to check the path, 4732 // since a cast can only be formed if the path is unique. 4733 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4734 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4735 const CXXRecordDecl *FinalType; 4736 if (NewEntriesSize == D.MostDerivedPathLength) 4737 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4738 else 4739 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4740 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4741 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4742 << D.MostDerivedType << TargetQT; 4743 return false; 4744 } 4745 4746 // Truncate the lvalue to the appropriate derived class. 4747 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4748 } 4749 4750 /// Get the value to use for a default-initialized object of type T. 4751 /// Return false if it encounters something invalid. 4752 static bool getDefaultInitValue(QualType T, APValue &Result) { 4753 bool Success = true; 4754 if (auto *RD = T->getAsCXXRecordDecl()) { 4755 if (RD->isInvalidDecl()) { 4756 Result = APValue(); 4757 return false; 4758 } 4759 if (RD->isUnion()) { 4760 Result = APValue((const FieldDecl *)nullptr); 4761 return true; 4762 } 4763 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4764 std::distance(RD->field_begin(), RD->field_end())); 4765 4766 unsigned Index = 0; 4767 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4768 End = RD->bases_end(); 4769 I != End; ++I, ++Index) 4770 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4771 4772 for (const auto *I : RD->fields()) { 4773 if (I->isUnnamedBitfield()) 4774 continue; 4775 Success &= getDefaultInitValue(I->getType(), 4776 Result.getStructField(I->getFieldIndex())); 4777 } 4778 return Success; 4779 } 4780 4781 if (auto *AT = 4782 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4783 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4784 if (Result.hasArrayFiller()) 4785 Success &= 4786 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4787 4788 return Success; 4789 } 4790 4791 Result = APValue::IndeterminateValue(); 4792 return true; 4793 } 4794 4795 namespace { 4796 enum EvalStmtResult { 4797 /// Evaluation failed. 4798 ESR_Failed, 4799 /// Hit a 'return' statement. 4800 ESR_Returned, 4801 /// Evaluation succeeded. 4802 ESR_Succeeded, 4803 /// Hit a 'continue' statement. 4804 ESR_Continue, 4805 /// Hit a 'break' statement. 4806 ESR_Break, 4807 /// Still scanning for 'case' or 'default' statement. 4808 ESR_CaseNotFound 4809 }; 4810 } 4811 4812 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4813 // We don't need to evaluate the initializer for a static local. 4814 if (!VD->hasLocalStorage()) 4815 return true; 4816 4817 LValue Result; 4818 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4819 ScopeKind::Block, Result); 4820 4821 const Expr *InitE = VD->getInit(); 4822 if (!InitE) { 4823 if (VD->getType()->isDependentType()) 4824 return Info.noteSideEffect(); 4825 return getDefaultInitValue(VD->getType(), Val); 4826 } 4827 if (InitE->isValueDependent()) 4828 return false; 4829 4830 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4831 // Wipe out any partially-computed value, to allow tracking that this 4832 // evaluation failed. 4833 Val = APValue(); 4834 return false; 4835 } 4836 4837 return true; 4838 } 4839 4840 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4841 bool OK = true; 4842 4843 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4844 OK &= EvaluateVarDecl(Info, VD); 4845 4846 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4847 for (auto *BD : DD->bindings()) 4848 if (auto *VD = BD->getHoldingVar()) 4849 OK &= EvaluateDecl(Info, VD); 4850 4851 return OK; 4852 } 4853 4854 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4855 assert(E->isValueDependent()); 4856 if (Info.noteSideEffect()) 4857 return true; 4858 assert(E->containsErrors() && "valid value-dependent expression should never " 4859 "reach invalid code path."); 4860 return false; 4861 } 4862 4863 /// Evaluate a condition (either a variable declaration or an expression). 4864 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4865 const Expr *Cond, bool &Result) { 4866 if (Cond->isValueDependent()) 4867 return false; 4868 FullExpressionRAII Scope(Info); 4869 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4870 return false; 4871 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4872 return false; 4873 return Scope.destroy(); 4874 } 4875 4876 namespace { 4877 /// A location where the result (returned value) of evaluating a 4878 /// statement should be stored. 4879 struct StmtResult { 4880 /// The APValue that should be filled in with the returned value. 4881 APValue &Value; 4882 /// The location containing the result, if any (used to support RVO). 4883 const LValue *Slot; 4884 }; 4885 4886 struct TempVersionRAII { 4887 CallStackFrame &Frame; 4888 4889 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4890 Frame.pushTempVersion(); 4891 } 4892 4893 ~TempVersionRAII() { 4894 Frame.popTempVersion(); 4895 } 4896 }; 4897 4898 } 4899 4900 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4901 const Stmt *S, 4902 const SwitchCase *SC = nullptr); 4903 4904 /// Evaluate the body of a loop, and translate the result as appropriate. 4905 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4906 const Stmt *Body, 4907 const SwitchCase *Case = nullptr) { 4908 BlockScopeRAII Scope(Info); 4909 4910 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4911 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4912 ESR = ESR_Failed; 4913 4914 switch (ESR) { 4915 case ESR_Break: 4916 return ESR_Succeeded; 4917 case ESR_Succeeded: 4918 case ESR_Continue: 4919 return ESR_Continue; 4920 case ESR_Failed: 4921 case ESR_Returned: 4922 case ESR_CaseNotFound: 4923 return ESR; 4924 } 4925 llvm_unreachable("Invalid EvalStmtResult!"); 4926 } 4927 4928 /// Evaluate a switch statement. 4929 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4930 const SwitchStmt *SS) { 4931 BlockScopeRAII Scope(Info); 4932 4933 // Evaluate the switch condition. 4934 APSInt Value; 4935 { 4936 if (const Stmt *Init = SS->getInit()) { 4937 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4938 if (ESR != ESR_Succeeded) { 4939 if (ESR != ESR_Failed && !Scope.destroy()) 4940 ESR = ESR_Failed; 4941 return ESR; 4942 } 4943 } 4944 4945 FullExpressionRAII CondScope(Info); 4946 if (SS->getConditionVariable() && 4947 !EvaluateDecl(Info, SS->getConditionVariable())) 4948 return ESR_Failed; 4949 if (SS->getCond()->isValueDependent()) { 4950 if (!EvaluateDependentExpr(SS->getCond(), Info)) 4951 return ESR_Failed; 4952 } else { 4953 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4954 return ESR_Failed; 4955 } 4956 if (!CondScope.destroy()) 4957 return ESR_Failed; 4958 } 4959 4960 // Find the switch case corresponding to the value of the condition. 4961 // FIXME: Cache this lookup. 4962 const SwitchCase *Found = nullptr; 4963 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4964 SC = SC->getNextSwitchCase()) { 4965 if (isa<DefaultStmt>(SC)) { 4966 Found = SC; 4967 continue; 4968 } 4969 4970 const CaseStmt *CS = cast<CaseStmt>(SC); 4971 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4972 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4973 : LHS; 4974 if (LHS <= Value && Value <= RHS) { 4975 Found = SC; 4976 break; 4977 } 4978 } 4979 4980 if (!Found) 4981 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4982 4983 // Search the switch body for the switch case and evaluate it from there. 4984 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4985 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4986 return ESR_Failed; 4987 4988 switch (ESR) { 4989 case ESR_Break: 4990 return ESR_Succeeded; 4991 case ESR_Succeeded: 4992 case ESR_Continue: 4993 case ESR_Failed: 4994 case ESR_Returned: 4995 return ESR; 4996 case ESR_CaseNotFound: 4997 // This can only happen if the switch case is nested within a statement 4998 // expression. We have no intention of supporting that. 4999 Info.FFDiag(Found->getBeginLoc(), 5000 diag::note_constexpr_stmt_expr_unsupported); 5001 return ESR_Failed; 5002 } 5003 llvm_unreachable("Invalid EvalStmtResult!"); 5004 } 5005 5006 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) { 5007 // An expression E is a core constant expression unless the evaluation of E 5008 // would evaluate one of the following: [C++2b] - a control flow that passes 5009 // through a declaration of a variable with static or thread storage duration. 5010 if (VD->isLocalVarDecl() && VD->isStaticLocal()) { 5011 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local) 5012 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD; 5013 return false; 5014 } 5015 return true; 5016 } 5017 5018 // Evaluate a statement. 5019 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 5020 const Stmt *S, const SwitchCase *Case) { 5021 if (!Info.nextStep(S)) 5022 return ESR_Failed; 5023 5024 // If we're hunting down a 'case' or 'default' label, recurse through 5025 // substatements until we hit the label. 5026 if (Case) { 5027 switch (S->getStmtClass()) { 5028 case Stmt::CompoundStmtClass: 5029 // FIXME: Precompute which substatement of a compound statement we 5030 // would jump to, and go straight there rather than performing a 5031 // linear scan each time. 5032 case Stmt::LabelStmtClass: 5033 case Stmt::AttributedStmtClass: 5034 case Stmt::DoStmtClass: 5035 break; 5036 5037 case Stmt::CaseStmtClass: 5038 case Stmt::DefaultStmtClass: 5039 if (Case == S) 5040 Case = nullptr; 5041 break; 5042 5043 case Stmt::IfStmtClass: { 5044 // FIXME: Precompute which side of an 'if' we would jump to, and go 5045 // straight there rather than scanning both sides. 5046 const IfStmt *IS = cast<IfStmt>(S); 5047 5048 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5049 // preceded by our switch label. 5050 BlockScopeRAII Scope(Info); 5051 5052 // Step into the init statement in case it brings an (uninitialized) 5053 // variable into scope. 5054 if (const Stmt *Init = IS->getInit()) { 5055 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5056 if (ESR != ESR_CaseNotFound) { 5057 assert(ESR != ESR_Succeeded); 5058 return ESR; 5059 } 5060 } 5061 5062 // Condition variable must be initialized if it exists. 5063 // FIXME: We can skip evaluating the body if there's a condition 5064 // variable, as there can't be any case labels within it. 5065 // (The same is true for 'for' statements.) 5066 5067 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5068 if (ESR == ESR_Failed) 5069 return ESR; 5070 if (ESR != ESR_CaseNotFound) 5071 return Scope.destroy() ? ESR : ESR_Failed; 5072 if (!IS->getElse()) 5073 return ESR_CaseNotFound; 5074 5075 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5076 if (ESR == ESR_Failed) 5077 return ESR; 5078 if (ESR != ESR_CaseNotFound) 5079 return Scope.destroy() ? ESR : ESR_Failed; 5080 return ESR_CaseNotFound; 5081 } 5082 5083 case Stmt::WhileStmtClass: { 5084 EvalStmtResult ESR = 5085 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5086 if (ESR != ESR_Continue) 5087 return ESR; 5088 break; 5089 } 5090 5091 case Stmt::ForStmtClass: { 5092 const ForStmt *FS = cast<ForStmt>(S); 5093 BlockScopeRAII Scope(Info); 5094 5095 // Step into the init statement in case it brings an (uninitialized) 5096 // variable into scope. 5097 if (const Stmt *Init = FS->getInit()) { 5098 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5099 if (ESR != ESR_CaseNotFound) { 5100 assert(ESR != ESR_Succeeded); 5101 return ESR; 5102 } 5103 } 5104 5105 EvalStmtResult ESR = 5106 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5107 if (ESR != ESR_Continue) 5108 return ESR; 5109 if (const auto *Inc = FS->getInc()) { 5110 if (Inc->isValueDependent()) { 5111 if (!EvaluateDependentExpr(Inc, Info)) 5112 return ESR_Failed; 5113 } else { 5114 FullExpressionRAII IncScope(Info); 5115 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5116 return ESR_Failed; 5117 } 5118 } 5119 break; 5120 } 5121 5122 case Stmt::DeclStmtClass: { 5123 // Start the lifetime of any uninitialized variables we encounter. They 5124 // might be used by the selected branch of the switch. 5125 const DeclStmt *DS = cast<DeclStmt>(S); 5126 for (const auto *D : DS->decls()) { 5127 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5128 if (!CheckLocalVariableDeclaration(Info, VD)) 5129 return ESR_Failed; 5130 if (VD->hasLocalStorage() && !VD->getInit()) 5131 if (!EvaluateVarDecl(Info, VD)) 5132 return ESR_Failed; 5133 // FIXME: If the variable has initialization that can't be jumped 5134 // over, bail out of any immediately-surrounding compound-statement 5135 // too. There can't be any case labels here. 5136 } 5137 } 5138 return ESR_CaseNotFound; 5139 } 5140 5141 default: 5142 return ESR_CaseNotFound; 5143 } 5144 } 5145 5146 switch (S->getStmtClass()) { 5147 default: 5148 if (const Expr *E = dyn_cast<Expr>(S)) { 5149 if (E->isValueDependent()) { 5150 if (!EvaluateDependentExpr(E, Info)) 5151 return ESR_Failed; 5152 } else { 5153 // Don't bother evaluating beyond an expression-statement which couldn't 5154 // be evaluated. 5155 // FIXME: Do we need the FullExpressionRAII object here? 5156 // VisitExprWithCleanups should create one when necessary. 5157 FullExpressionRAII Scope(Info); 5158 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5159 return ESR_Failed; 5160 } 5161 return ESR_Succeeded; 5162 } 5163 5164 Info.FFDiag(S->getBeginLoc()); 5165 return ESR_Failed; 5166 5167 case Stmt::NullStmtClass: 5168 return ESR_Succeeded; 5169 5170 case Stmt::DeclStmtClass: { 5171 const DeclStmt *DS = cast<DeclStmt>(S); 5172 for (const auto *D : DS->decls()) { 5173 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 5174 if (VD && !CheckLocalVariableDeclaration(Info, VD)) 5175 return ESR_Failed; 5176 // Each declaration initialization is its own full-expression. 5177 FullExpressionRAII Scope(Info); 5178 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5179 return ESR_Failed; 5180 if (!Scope.destroy()) 5181 return ESR_Failed; 5182 } 5183 return ESR_Succeeded; 5184 } 5185 5186 case Stmt::ReturnStmtClass: { 5187 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5188 FullExpressionRAII Scope(Info); 5189 if (RetExpr && RetExpr->isValueDependent()) { 5190 EvaluateDependentExpr(RetExpr, Info); 5191 // We know we returned, but we don't know what the value is. 5192 return ESR_Failed; 5193 } 5194 if (RetExpr && 5195 !(Result.Slot 5196 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5197 : Evaluate(Result.Value, Info, RetExpr))) 5198 return ESR_Failed; 5199 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5200 } 5201 5202 case Stmt::CompoundStmtClass: { 5203 BlockScopeRAII Scope(Info); 5204 5205 const CompoundStmt *CS = cast<CompoundStmt>(S); 5206 for (const auto *BI : CS->body()) { 5207 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5208 if (ESR == ESR_Succeeded) 5209 Case = nullptr; 5210 else if (ESR != ESR_CaseNotFound) { 5211 if (ESR != ESR_Failed && !Scope.destroy()) 5212 return ESR_Failed; 5213 return ESR; 5214 } 5215 } 5216 if (Case) 5217 return ESR_CaseNotFound; 5218 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5219 } 5220 5221 case Stmt::IfStmtClass: { 5222 const IfStmt *IS = cast<IfStmt>(S); 5223 5224 // Evaluate the condition, as either a var decl or as an expression. 5225 BlockScopeRAII Scope(Info); 5226 if (const Stmt *Init = IS->getInit()) { 5227 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5228 if (ESR != ESR_Succeeded) { 5229 if (ESR != ESR_Failed && !Scope.destroy()) 5230 return ESR_Failed; 5231 return ESR; 5232 } 5233 } 5234 bool Cond; 5235 if (IS->isConsteval()) 5236 Cond = IS->isNonNegatedConsteval(); 5237 else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5238 Cond)) 5239 return ESR_Failed; 5240 5241 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5242 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5243 if (ESR != ESR_Succeeded) { 5244 if (ESR != ESR_Failed && !Scope.destroy()) 5245 return ESR_Failed; 5246 return ESR; 5247 } 5248 } 5249 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5250 } 5251 5252 case Stmt::WhileStmtClass: { 5253 const WhileStmt *WS = cast<WhileStmt>(S); 5254 while (true) { 5255 BlockScopeRAII Scope(Info); 5256 bool Continue; 5257 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5258 Continue)) 5259 return ESR_Failed; 5260 if (!Continue) 5261 break; 5262 5263 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5264 if (ESR != ESR_Continue) { 5265 if (ESR != ESR_Failed && !Scope.destroy()) 5266 return ESR_Failed; 5267 return ESR; 5268 } 5269 if (!Scope.destroy()) 5270 return ESR_Failed; 5271 } 5272 return ESR_Succeeded; 5273 } 5274 5275 case Stmt::DoStmtClass: { 5276 const DoStmt *DS = cast<DoStmt>(S); 5277 bool Continue; 5278 do { 5279 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5280 if (ESR != ESR_Continue) 5281 return ESR; 5282 Case = nullptr; 5283 5284 if (DS->getCond()->isValueDependent()) { 5285 EvaluateDependentExpr(DS->getCond(), Info); 5286 // Bailout as we don't know whether to keep going or terminate the loop. 5287 return ESR_Failed; 5288 } 5289 FullExpressionRAII CondScope(Info); 5290 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5291 !CondScope.destroy()) 5292 return ESR_Failed; 5293 } while (Continue); 5294 return ESR_Succeeded; 5295 } 5296 5297 case Stmt::ForStmtClass: { 5298 const ForStmt *FS = cast<ForStmt>(S); 5299 BlockScopeRAII ForScope(Info); 5300 if (FS->getInit()) { 5301 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5302 if (ESR != ESR_Succeeded) { 5303 if (ESR != ESR_Failed && !ForScope.destroy()) 5304 return ESR_Failed; 5305 return ESR; 5306 } 5307 } 5308 while (true) { 5309 BlockScopeRAII IterScope(Info); 5310 bool Continue = true; 5311 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5312 FS->getCond(), Continue)) 5313 return ESR_Failed; 5314 if (!Continue) 5315 break; 5316 5317 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5318 if (ESR != ESR_Continue) { 5319 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5320 return ESR_Failed; 5321 return ESR; 5322 } 5323 5324 if (const auto *Inc = FS->getInc()) { 5325 if (Inc->isValueDependent()) { 5326 if (!EvaluateDependentExpr(Inc, Info)) 5327 return ESR_Failed; 5328 } else { 5329 FullExpressionRAII IncScope(Info); 5330 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5331 return ESR_Failed; 5332 } 5333 } 5334 5335 if (!IterScope.destroy()) 5336 return ESR_Failed; 5337 } 5338 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5339 } 5340 5341 case Stmt::CXXForRangeStmtClass: { 5342 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5343 BlockScopeRAII Scope(Info); 5344 5345 // Evaluate the init-statement if present. 5346 if (FS->getInit()) { 5347 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5348 if (ESR != ESR_Succeeded) { 5349 if (ESR != ESR_Failed && !Scope.destroy()) 5350 return ESR_Failed; 5351 return ESR; 5352 } 5353 } 5354 5355 // Initialize the __range variable. 5356 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5357 if (ESR != ESR_Succeeded) { 5358 if (ESR != ESR_Failed && !Scope.destroy()) 5359 return ESR_Failed; 5360 return ESR; 5361 } 5362 5363 // In error-recovery cases it's possible to get here even if we failed to 5364 // synthesize the __begin and __end variables. 5365 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5366 return ESR_Failed; 5367 5368 // Create the __begin and __end iterators. 5369 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5370 if (ESR != ESR_Succeeded) { 5371 if (ESR != ESR_Failed && !Scope.destroy()) 5372 return ESR_Failed; 5373 return ESR; 5374 } 5375 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5376 if (ESR != ESR_Succeeded) { 5377 if (ESR != ESR_Failed && !Scope.destroy()) 5378 return ESR_Failed; 5379 return ESR; 5380 } 5381 5382 while (true) { 5383 // Condition: __begin != __end. 5384 { 5385 if (FS->getCond()->isValueDependent()) { 5386 EvaluateDependentExpr(FS->getCond(), Info); 5387 // We don't know whether to keep going or terminate the loop. 5388 return ESR_Failed; 5389 } 5390 bool Continue = true; 5391 FullExpressionRAII CondExpr(Info); 5392 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5393 return ESR_Failed; 5394 if (!Continue) 5395 break; 5396 } 5397 5398 // User's variable declaration, initialized by *__begin. 5399 BlockScopeRAII InnerScope(Info); 5400 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5401 if (ESR != ESR_Succeeded) { 5402 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5403 return ESR_Failed; 5404 return ESR; 5405 } 5406 5407 // Loop body. 5408 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5409 if (ESR != ESR_Continue) { 5410 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5411 return ESR_Failed; 5412 return ESR; 5413 } 5414 if (FS->getInc()->isValueDependent()) { 5415 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5416 return ESR_Failed; 5417 } else { 5418 // Increment: ++__begin 5419 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5420 return ESR_Failed; 5421 } 5422 5423 if (!InnerScope.destroy()) 5424 return ESR_Failed; 5425 } 5426 5427 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5428 } 5429 5430 case Stmt::SwitchStmtClass: 5431 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5432 5433 case Stmt::ContinueStmtClass: 5434 return ESR_Continue; 5435 5436 case Stmt::BreakStmtClass: 5437 return ESR_Break; 5438 5439 case Stmt::LabelStmtClass: 5440 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5441 5442 case Stmt::AttributedStmtClass: 5443 // As a general principle, C++11 attributes can be ignored without 5444 // any semantic impact. 5445 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5446 Case); 5447 5448 case Stmt::CaseStmtClass: 5449 case Stmt::DefaultStmtClass: 5450 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5451 case Stmt::CXXTryStmtClass: 5452 // Evaluate try blocks by evaluating all sub statements. 5453 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5454 } 5455 } 5456 5457 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5458 /// default constructor. If so, we'll fold it whether or not it's marked as 5459 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5460 /// so we need special handling. 5461 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5462 const CXXConstructorDecl *CD, 5463 bool IsValueInitialization) { 5464 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5465 return false; 5466 5467 // Value-initialization does not call a trivial default constructor, so such a 5468 // call is a core constant expression whether or not the constructor is 5469 // constexpr. 5470 if (!CD->isConstexpr() && !IsValueInitialization) { 5471 if (Info.getLangOpts().CPlusPlus11) { 5472 // FIXME: If DiagDecl is an implicitly-declared special member function, 5473 // we should be much more explicit about why it's not constexpr. 5474 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5475 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5476 Info.Note(CD->getLocation(), diag::note_declared_at); 5477 } else { 5478 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5479 } 5480 } 5481 return true; 5482 } 5483 5484 /// CheckConstexprFunction - Check that a function can be called in a constant 5485 /// expression. 5486 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5487 const FunctionDecl *Declaration, 5488 const FunctionDecl *Definition, 5489 const Stmt *Body) { 5490 // Potential constant expressions can contain calls to declared, but not yet 5491 // defined, constexpr functions. 5492 if (Info.checkingPotentialConstantExpression() && !Definition && 5493 Declaration->isConstexpr()) 5494 return false; 5495 5496 // Bail out if the function declaration itself is invalid. We will 5497 // have produced a relevant diagnostic while parsing it, so just 5498 // note the problematic sub-expression. 5499 if (Declaration->isInvalidDecl()) { 5500 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5501 return false; 5502 } 5503 5504 // DR1872: An instantiated virtual constexpr function can't be called in a 5505 // constant expression (prior to C++20). We can still constant-fold such a 5506 // call. 5507 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5508 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5509 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5510 5511 if (Definition && Definition->isInvalidDecl()) { 5512 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5513 return false; 5514 } 5515 5516 // Can we evaluate this function call? 5517 if (Definition && Definition->isConstexpr() && Body) 5518 return true; 5519 5520 if (Info.getLangOpts().CPlusPlus11) { 5521 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5522 5523 // If this function is not constexpr because it is an inherited 5524 // non-constexpr constructor, diagnose that directly. 5525 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5526 if (CD && CD->isInheritingConstructor()) { 5527 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5528 if (!Inherited->isConstexpr()) 5529 DiagDecl = CD = Inherited; 5530 } 5531 5532 // FIXME: If DiagDecl is an implicitly-declared special member function 5533 // or an inheriting constructor, we should be much more explicit about why 5534 // it's not constexpr. 5535 if (CD && CD->isInheritingConstructor()) 5536 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5537 << CD->getInheritedConstructor().getConstructor()->getParent(); 5538 else 5539 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5540 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5541 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5542 } else { 5543 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5544 } 5545 return false; 5546 } 5547 5548 namespace { 5549 struct CheckDynamicTypeHandler { 5550 AccessKinds AccessKind; 5551 typedef bool result_type; 5552 bool failed() { return false; } 5553 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5554 bool found(APSInt &Value, QualType SubobjType) { return true; } 5555 bool found(APFloat &Value, QualType SubobjType) { return true; } 5556 }; 5557 } // end anonymous namespace 5558 5559 /// Check that we can access the notional vptr of an object / determine its 5560 /// dynamic type. 5561 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5562 AccessKinds AK, bool Polymorphic) { 5563 if (This.Designator.Invalid) 5564 return false; 5565 5566 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5567 5568 if (!Obj) 5569 return false; 5570 5571 if (!Obj.Value) { 5572 // The object is not usable in constant expressions, so we can't inspect 5573 // its value to see if it's in-lifetime or what the active union members 5574 // are. We can still check for a one-past-the-end lvalue. 5575 if (This.Designator.isOnePastTheEnd() || 5576 This.Designator.isMostDerivedAnUnsizedArray()) { 5577 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5578 ? diag::note_constexpr_access_past_end 5579 : diag::note_constexpr_access_unsized_array) 5580 << AK; 5581 return false; 5582 } else if (Polymorphic) { 5583 // Conservatively refuse to perform a polymorphic operation if we would 5584 // not be able to read a notional 'vptr' value. 5585 APValue Val; 5586 This.moveInto(Val); 5587 QualType StarThisType = 5588 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5589 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5590 << AK << Val.getAsString(Info.Ctx, StarThisType); 5591 return false; 5592 } 5593 return true; 5594 } 5595 5596 CheckDynamicTypeHandler Handler{AK}; 5597 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5598 } 5599 5600 /// Check that the pointee of the 'this' pointer in a member function call is 5601 /// either within its lifetime or in its period of construction or destruction. 5602 static bool 5603 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5604 const LValue &This, 5605 const CXXMethodDecl *NamedMember) { 5606 return checkDynamicType( 5607 Info, E, This, 5608 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5609 } 5610 5611 struct DynamicType { 5612 /// The dynamic class type of the object. 5613 const CXXRecordDecl *Type; 5614 /// The corresponding path length in the lvalue. 5615 unsigned PathLength; 5616 }; 5617 5618 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5619 unsigned PathLength) { 5620 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5621 Designator.Entries.size() && "invalid path length"); 5622 return (PathLength == Designator.MostDerivedPathLength) 5623 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5624 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5625 } 5626 5627 /// Determine the dynamic type of an object. 5628 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5629 LValue &This, AccessKinds AK) { 5630 // If we don't have an lvalue denoting an object of class type, there is no 5631 // meaningful dynamic type. (We consider objects of non-class type to have no 5632 // dynamic type.) 5633 if (!checkDynamicType(Info, E, This, AK, true)) 5634 return None; 5635 5636 // Refuse to compute a dynamic type in the presence of virtual bases. This 5637 // shouldn't happen other than in constant-folding situations, since literal 5638 // types can't have virtual bases. 5639 // 5640 // Note that consumers of DynamicType assume that the type has no virtual 5641 // bases, and will need modifications if this restriction is relaxed. 5642 const CXXRecordDecl *Class = 5643 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5644 if (!Class || Class->getNumVBases()) { 5645 Info.FFDiag(E); 5646 return None; 5647 } 5648 5649 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5650 // binary search here instead. But the overwhelmingly common case is that 5651 // we're not in the middle of a constructor, so it probably doesn't matter 5652 // in practice. 5653 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5654 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5655 PathLength <= Path.size(); ++PathLength) { 5656 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5657 Path.slice(0, PathLength))) { 5658 case ConstructionPhase::Bases: 5659 case ConstructionPhase::DestroyingBases: 5660 // We're constructing or destroying a base class. This is not the dynamic 5661 // type. 5662 break; 5663 5664 case ConstructionPhase::None: 5665 case ConstructionPhase::AfterBases: 5666 case ConstructionPhase::AfterFields: 5667 case ConstructionPhase::Destroying: 5668 // We've finished constructing the base classes and not yet started 5669 // destroying them again, so this is the dynamic type. 5670 return DynamicType{getBaseClassType(This.Designator, PathLength), 5671 PathLength}; 5672 } 5673 } 5674 5675 // CWG issue 1517: we're constructing a base class of the object described by 5676 // 'This', so that object has not yet begun its period of construction and 5677 // any polymorphic operation on it results in undefined behavior. 5678 Info.FFDiag(E); 5679 return None; 5680 } 5681 5682 /// Perform virtual dispatch. 5683 static const CXXMethodDecl *HandleVirtualDispatch( 5684 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5685 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5686 Optional<DynamicType> DynType = ComputeDynamicType( 5687 Info, E, This, 5688 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5689 if (!DynType) 5690 return nullptr; 5691 5692 // Find the final overrider. It must be declared in one of the classes on the 5693 // path from the dynamic type to the static type. 5694 // FIXME: If we ever allow literal types to have virtual base classes, that 5695 // won't be true. 5696 const CXXMethodDecl *Callee = Found; 5697 unsigned PathLength = DynType->PathLength; 5698 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5699 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5700 const CXXMethodDecl *Overrider = 5701 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5702 if (Overrider) { 5703 Callee = Overrider; 5704 break; 5705 } 5706 } 5707 5708 // C++2a [class.abstract]p6: 5709 // the effect of making a virtual call to a pure virtual function [...] is 5710 // undefined 5711 if (Callee->isPure()) { 5712 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5713 Info.Note(Callee->getLocation(), diag::note_declared_at); 5714 return nullptr; 5715 } 5716 5717 // If necessary, walk the rest of the path to determine the sequence of 5718 // covariant adjustment steps to apply. 5719 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5720 Found->getReturnType())) { 5721 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5722 for (unsigned CovariantPathLength = PathLength + 1; 5723 CovariantPathLength != This.Designator.Entries.size(); 5724 ++CovariantPathLength) { 5725 const CXXRecordDecl *NextClass = 5726 getBaseClassType(This.Designator, CovariantPathLength); 5727 const CXXMethodDecl *Next = 5728 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5729 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5730 Next->getReturnType(), CovariantAdjustmentPath.back())) 5731 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5732 } 5733 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5734 CovariantAdjustmentPath.back())) 5735 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5736 } 5737 5738 // Perform 'this' adjustment. 5739 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5740 return nullptr; 5741 5742 return Callee; 5743 } 5744 5745 /// Perform the adjustment from a value returned by a virtual function to 5746 /// a value of the statically expected type, which may be a pointer or 5747 /// reference to a base class of the returned type. 5748 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5749 APValue &Result, 5750 ArrayRef<QualType> Path) { 5751 assert(Result.isLValue() && 5752 "unexpected kind of APValue for covariant return"); 5753 if (Result.isNullPointer()) 5754 return true; 5755 5756 LValue LVal; 5757 LVal.setFrom(Info.Ctx, Result); 5758 5759 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5760 for (unsigned I = 1; I != Path.size(); ++I) { 5761 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5762 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5763 if (OldClass != NewClass && 5764 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5765 return false; 5766 OldClass = NewClass; 5767 } 5768 5769 LVal.moveInto(Result); 5770 return true; 5771 } 5772 5773 /// Determine whether \p Base, which is known to be a direct base class of 5774 /// \p Derived, is a public base class. 5775 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5776 const CXXRecordDecl *Base) { 5777 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5778 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5779 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5780 return BaseSpec.getAccessSpecifier() == AS_public; 5781 } 5782 llvm_unreachable("Base is not a direct base of Derived"); 5783 } 5784 5785 /// Apply the given dynamic cast operation on the provided lvalue. 5786 /// 5787 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5788 /// to find a suitable target subobject. 5789 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5790 LValue &Ptr) { 5791 // We can't do anything with a non-symbolic pointer value. 5792 SubobjectDesignator &D = Ptr.Designator; 5793 if (D.Invalid) 5794 return false; 5795 5796 // C++ [expr.dynamic.cast]p6: 5797 // If v is a null pointer value, the result is a null pointer value. 5798 if (Ptr.isNullPointer() && !E->isGLValue()) 5799 return true; 5800 5801 // For all the other cases, we need the pointer to point to an object within 5802 // its lifetime / period of construction / destruction, and we need to know 5803 // its dynamic type. 5804 Optional<DynamicType> DynType = 5805 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5806 if (!DynType) 5807 return false; 5808 5809 // C++ [expr.dynamic.cast]p7: 5810 // If T is "pointer to cv void", then the result is a pointer to the most 5811 // derived object 5812 if (E->getType()->isVoidPointerType()) 5813 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5814 5815 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5816 assert(C && "dynamic_cast target is not void pointer nor class"); 5817 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5818 5819 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5820 // C++ [expr.dynamic.cast]p9: 5821 if (!E->isGLValue()) { 5822 // The value of a failed cast to pointer type is the null pointer value 5823 // of the required result type. 5824 Ptr.setNull(Info.Ctx, E->getType()); 5825 return true; 5826 } 5827 5828 // A failed cast to reference type throws [...] std::bad_cast. 5829 unsigned DiagKind; 5830 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5831 DynType->Type->isDerivedFrom(C))) 5832 DiagKind = 0; 5833 else if (!Paths || Paths->begin() == Paths->end()) 5834 DiagKind = 1; 5835 else if (Paths->isAmbiguous(CQT)) 5836 DiagKind = 2; 5837 else { 5838 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5839 DiagKind = 3; 5840 } 5841 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5842 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5843 << Info.Ctx.getRecordType(DynType->Type) 5844 << E->getType().getUnqualifiedType(); 5845 return false; 5846 }; 5847 5848 // Runtime check, phase 1: 5849 // Walk from the base subobject towards the derived object looking for the 5850 // target type. 5851 for (int PathLength = Ptr.Designator.Entries.size(); 5852 PathLength >= (int)DynType->PathLength; --PathLength) { 5853 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5854 if (declaresSameEntity(Class, C)) 5855 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5856 // We can only walk across public inheritance edges. 5857 if (PathLength > (int)DynType->PathLength && 5858 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5859 Class)) 5860 return RuntimeCheckFailed(nullptr); 5861 } 5862 5863 // Runtime check, phase 2: 5864 // Search the dynamic type for an unambiguous public base of type C. 5865 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5866 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5867 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5868 Paths.front().Access == AS_public) { 5869 // Downcast to the dynamic type... 5870 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5871 return false; 5872 // ... then upcast to the chosen base class subobject. 5873 for (CXXBasePathElement &Elem : Paths.front()) 5874 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5875 return false; 5876 return true; 5877 } 5878 5879 // Otherwise, the runtime check fails. 5880 return RuntimeCheckFailed(&Paths); 5881 } 5882 5883 namespace { 5884 struct StartLifetimeOfUnionMemberHandler { 5885 EvalInfo &Info; 5886 const Expr *LHSExpr; 5887 const FieldDecl *Field; 5888 bool DuringInit; 5889 bool Failed = false; 5890 static const AccessKinds AccessKind = AK_Assign; 5891 5892 typedef bool result_type; 5893 bool failed() { return Failed; } 5894 bool found(APValue &Subobj, QualType SubobjType) { 5895 // We are supposed to perform no initialization but begin the lifetime of 5896 // the object. We interpret that as meaning to do what default 5897 // initialization of the object would do if all constructors involved were 5898 // trivial: 5899 // * All base, non-variant member, and array element subobjects' lifetimes 5900 // begin 5901 // * No variant members' lifetimes begin 5902 // * All scalar subobjects whose lifetimes begin have indeterminate values 5903 assert(SubobjType->isUnionType()); 5904 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5905 // This union member is already active. If it's also in-lifetime, there's 5906 // nothing to do. 5907 if (Subobj.getUnionValue().hasValue()) 5908 return true; 5909 } else if (DuringInit) { 5910 // We're currently in the process of initializing a different union 5911 // member. If we carried on, that initialization would attempt to 5912 // store to an inactive union member, resulting in undefined behavior. 5913 Info.FFDiag(LHSExpr, 5914 diag::note_constexpr_union_member_change_during_init); 5915 return false; 5916 } 5917 APValue Result; 5918 Failed = !getDefaultInitValue(Field->getType(), Result); 5919 Subobj.setUnion(Field, Result); 5920 return true; 5921 } 5922 bool found(APSInt &Value, QualType SubobjType) { 5923 llvm_unreachable("wrong value kind for union object"); 5924 } 5925 bool found(APFloat &Value, QualType SubobjType) { 5926 llvm_unreachable("wrong value kind for union object"); 5927 } 5928 }; 5929 } // end anonymous namespace 5930 5931 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5932 5933 /// Handle a builtin simple-assignment or a call to a trivial assignment 5934 /// operator whose left-hand side might involve a union member access. If it 5935 /// does, implicitly start the lifetime of any accessed union elements per 5936 /// C++20 [class.union]5. 5937 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5938 const LValue &LHS) { 5939 if (LHS.InvalidBase || LHS.Designator.Invalid) 5940 return false; 5941 5942 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5943 // C++ [class.union]p5: 5944 // define the set S(E) of subexpressions of E as follows: 5945 unsigned PathLength = LHS.Designator.Entries.size(); 5946 for (const Expr *E = LHSExpr; E != nullptr;) { 5947 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5948 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5949 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5950 // Note that we can't implicitly start the lifetime of a reference, 5951 // so we don't need to proceed any further if we reach one. 5952 if (!FD || FD->getType()->isReferenceType()) 5953 break; 5954 5955 // ... and also contains A.B if B names a union member ... 5956 if (FD->getParent()->isUnion()) { 5957 // ... of a non-class, non-array type, or of a class type with a 5958 // trivial default constructor that is not deleted, or an array of 5959 // such types. 5960 auto *RD = 5961 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5962 if (!RD || RD->hasTrivialDefaultConstructor()) 5963 UnionPathLengths.push_back({PathLength - 1, FD}); 5964 } 5965 5966 E = ME->getBase(); 5967 --PathLength; 5968 assert(declaresSameEntity(FD, 5969 LHS.Designator.Entries[PathLength] 5970 .getAsBaseOrMember().getPointer())); 5971 5972 // -- If E is of the form A[B] and is interpreted as a built-in array 5973 // subscripting operator, S(E) is [S(the array operand, if any)]. 5974 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5975 // Step over an ArrayToPointerDecay implicit cast. 5976 auto *Base = ASE->getBase()->IgnoreImplicit(); 5977 if (!Base->getType()->isArrayType()) 5978 break; 5979 5980 E = Base; 5981 --PathLength; 5982 5983 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5984 // Step over a derived-to-base conversion. 5985 E = ICE->getSubExpr(); 5986 if (ICE->getCastKind() == CK_NoOp) 5987 continue; 5988 if (ICE->getCastKind() != CK_DerivedToBase && 5989 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5990 break; 5991 // Walk path backwards as we walk up from the base to the derived class. 5992 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5993 --PathLength; 5994 (void)Elt; 5995 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5996 LHS.Designator.Entries[PathLength] 5997 .getAsBaseOrMember().getPointer())); 5998 } 5999 6000 // -- Otherwise, S(E) is empty. 6001 } else { 6002 break; 6003 } 6004 } 6005 6006 // Common case: no unions' lifetimes are started. 6007 if (UnionPathLengths.empty()) 6008 return true; 6009 6010 // if modification of X [would access an inactive union member], an object 6011 // of the type of X is implicitly created 6012 CompleteObject Obj = 6013 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 6014 if (!Obj) 6015 return false; 6016 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 6017 llvm::reverse(UnionPathLengths)) { 6018 // Form a designator for the union object. 6019 SubobjectDesignator D = LHS.Designator; 6020 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 6021 6022 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 6023 ConstructionPhase::AfterBases; 6024 StartLifetimeOfUnionMemberHandler StartLifetime{ 6025 Info, LHSExpr, LengthAndField.second, DuringInit}; 6026 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 6027 return false; 6028 } 6029 6030 return true; 6031 } 6032 6033 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 6034 CallRef Call, EvalInfo &Info, 6035 bool NonNull = false) { 6036 LValue LV; 6037 // Create the parameter slot and register its destruction. For a vararg 6038 // argument, create a temporary. 6039 // FIXME: For calling conventions that destroy parameters in the callee, 6040 // should we consider performing destruction when the function returns 6041 // instead? 6042 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6043 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6044 ScopeKind::Call, LV); 6045 if (!EvaluateInPlace(V, Info, LV, Arg)) 6046 return false; 6047 6048 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6049 // undefined behavior, so is non-constant. 6050 if (NonNull && V.isLValue() && V.isNullPointer()) { 6051 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6052 return false; 6053 } 6054 6055 return true; 6056 } 6057 6058 /// Evaluate the arguments to a function call. 6059 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6060 EvalInfo &Info, const FunctionDecl *Callee, 6061 bool RightToLeft = false) { 6062 bool Success = true; 6063 llvm::SmallBitVector ForbiddenNullArgs; 6064 if (Callee->hasAttr<NonNullAttr>()) { 6065 ForbiddenNullArgs.resize(Args.size()); 6066 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6067 if (!Attr->args_size()) { 6068 ForbiddenNullArgs.set(); 6069 break; 6070 } else 6071 for (auto Idx : Attr->args()) { 6072 unsigned ASTIdx = Idx.getASTIndex(); 6073 if (ASTIdx >= Args.size()) 6074 continue; 6075 ForbiddenNullArgs[ASTIdx] = true; 6076 } 6077 } 6078 } 6079 for (unsigned I = 0; I < Args.size(); I++) { 6080 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6081 const ParmVarDecl *PVD = 6082 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6083 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6084 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6085 // If we're checking for a potential constant expression, evaluate all 6086 // initializers even if some of them fail. 6087 if (!Info.noteFailure()) 6088 return false; 6089 Success = false; 6090 } 6091 } 6092 return Success; 6093 } 6094 6095 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6096 /// constructor or assignment operator. 6097 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6098 const Expr *E, APValue &Result, 6099 bool CopyObjectRepresentation) { 6100 // Find the reference argument. 6101 CallStackFrame *Frame = Info.CurrentCall; 6102 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6103 if (!RefValue) { 6104 Info.FFDiag(E); 6105 return false; 6106 } 6107 6108 // Copy out the contents of the RHS object. 6109 LValue RefLValue; 6110 RefLValue.setFrom(Info.Ctx, *RefValue); 6111 return handleLValueToRValueConversion( 6112 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6113 CopyObjectRepresentation); 6114 } 6115 6116 /// Evaluate a function call. 6117 static bool HandleFunctionCall(SourceLocation CallLoc, 6118 const FunctionDecl *Callee, const LValue *This, 6119 ArrayRef<const Expr *> Args, CallRef Call, 6120 const Stmt *Body, EvalInfo &Info, 6121 APValue &Result, const LValue *ResultSlot) { 6122 if (!Info.CheckCallLimit(CallLoc)) 6123 return false; 6124 6125 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6126 6127 // For a trivial copy or move assignment, perform an APValue copy. This is 6128 // essential for unions, where the operations performed by the assignment 6129 // operator cannot be represented as statements. 6130 // 6131 // Skip this for non-union classes with no fields; in that case, the defaulted 6132 // copy/move does not actually read the object. 6133 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6134 if (MD && MD->isDefaulted() && 6135 (MD->getParent()->isUnion() || 6136 (MD->isTrivial() && 6137 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6138 assert(This && 6139 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6140 APValue RHSValue; 6141 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6142 MD->getParent()->isUnion())) 6143 return false; 6144 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6145 RHSValue)) 6146 return false; 6147 This->moveInto(Result); 6148 return true; 6149 } else if (MD && isLambdaCallOperator(MD)) { 6150 // We're in a lambda; determine the lambda capture field maps unless we're 6151 // just constexpr checking a lambda's call operator. constexpr checking is 6152 // done before the captures have been added to the closure object (unless 6153 // we're inferring constexpr-ness), so we don't have access to them in this 6154 // case. But since we don't need the captures to constexpr check, we can 6155 // just ignore them. 6156 if (!Info.checkingPotentialConstantExpression()) 6157 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6158 Frame.LambdaThisCaptureField); 6159 } 6160 6161 StmtResult Ret = {Result, ResultSlot}; 6162 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6163 if (ESR == ESR_Succeeded) { 6164 if (Callee->getReturnType()->isVoidType()) 6165 return true; 6166 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6167 } 6168 return ESR == ESR_Returned; 6169 } 6170 6171 /// Evaluate a constructor call. 6172 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6173 CallRef Call, 6174 const CXXConstructorDecl *Definition, 6175 EvalInfo &Info, APValue &Result) { 6176 SourceLocation CallLoc = E->getExprLoc(); 6177 if (!Info.CheckCallLimit(CallLoc)) 6178 return false; 6179 6180 const CXXRecordDecl *RD = Definition->getParent(); 6181 if (RD->getNumVBases()) { 6182 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6183 return false; 6184 } 6185 6186 EvalInfo::EvaluatingConstructorRAII EvalObj( 6187 Info, 6188 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6189 RD->getNumBases()); 6190 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6191 6192 // FIXME: Creating an APValue just to hold a nonexistent return value is 6193 // wasteful. 6194 APValue RetVal; 6195 StmtResult Ret = {RetVal, nullptr}; 6196 6197 // If it's a delegating constructor, delegate. 6198 if (Definition->isDelegatingConstructor()) { 6199 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6200 if ((*I)->getInit()->isValueDependent()) { 6201 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6202 return false; 6203 } else { 6204 FullExpressionRAII InitScope(Info); 6205 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6206 !InitScope.destroy()) 6207 return false; 6208 } 6209 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6210 } 6211 6212 // For a trivial copy or move constructor, perform an APValue copy. This is 6213 // essential for unions (or classes with anonymous union members), where the 6214 // operations performed by the constructor cannot be represented by 6215 // ctor-initializers. 6216 // 6217 // Skip this for empty non-union classes; we should not perform an 6218 // lvalue-to-rvalue conversion on them because their copy constructor does not 6219 // actually read them. 6220 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6221 (Definition->getParent()->isUnion() || 6222 (Definition->isTrivial() && 6223 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6224 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6225 Definition->getParent()->isUnion()); 6226 } 6227 6228 // Reserve space for the struct members. 6229 if (!Result.hasValue()) { 6230 if (!RD->isUnion()) 6231 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6232 std::distance(RD->field_begin(), RD->field_end())); 6233 else 6234 // A union starts with no active member. 6235 Result = APValue((const FieldDecl*)nullptr); 6236 } 6237 6238 if (RD->isInvalidDecl()) return false; 6239 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6240 6241 // A scope for temporaries lifetime-extended by reference members. 6242 BlockScopeRAII LifetimeExtendedScope(Info); 6243 6244 bool Success = true; 6245 unsigned BasesSeen = 0; 6246 #ifndef NDEBUG 6247 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6248 #endif 6249 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6250 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6251 // We might be initializing the same field again if this is an indirect 6252 // field initialization. 6253 if (FieldIt == RD->field_end() || 6254 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6255 assert(Indirect && "fields out of order?"); 6256 return; 6257 } 6258 6259 // Default-initialize any fields with no explicit initializer. 6260 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6261 assert(FieldIt != RD->field_end() && "missing field?"); 6262 if (!FieldIt->isUnnamedBitfield()) 6263 Success &= getDefaultInitValue( 6264 FieldIt->getType(), 6265 Result.getStructField(FieldIt->getFieldIndex())); 6266 } 6267 ++FieldIt; 6268 }; 6269 for (const auto *I : Definition->inits()) { 6270 LValue Subobject = This; 6271 LValue SubobjectParent = This; 6272 APValue *Value = &Result; 6273 6274 // Determine the subobject to initialize. 6275 FieldDecl *FD = nullptr; 6276 if (I->isBaseInitializer()) { 6277 QualType BaseType(I->getBaseClass(), 0); 6278 #ifndef NDEBUG 6279 // Non-virtual base classes are initialized in the order in the class 6280 // definition. We have already checked for virtual base classes. 6281 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6282 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6283 "base class initializers not in expected order"); 6284 ++BaseIt; 6285 #endif 6286 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6287 BaseType->getAsCXXRecordDecl(), &Layout)) 6288 return false; 6289 Value = &Result.getStructBase(BasesSeen++); 6290 } else if ((FD = I->getMember())) { 6291 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6292 return false; 6293 if (RD->isUnion()) { 6294 Result = APValue(FD); 6295 Value = &Result.getUnionValue(); 6296 } else { 6297 SkipToField(FD, false); 6298 Value = &Result.getStructField(FD->getFieldIndex()); 6299 } 6300 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6301 // Walk the indirect field decl's chain to find the object to initialize, 6302 // and make sure we've initialized every step along it. 6303 auto IndirectFieldChain = IFD->chain(); 6304 for (auto *C : IndirectFieldChain) { 6305 FD = cast<FieldDecl>(C); 6306 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6307 // Switch the union field if it differs. This happens if we had 6308 // preceding zero-initialization, and we're now initializing a union 6309 // subobject other than the first. 6310 // FIXME: In this case, the values of the other subobjects are 6311 // specified, since zero-initialization sets all padding bits to zero. 6312 if (!Value->hasValue() || 6313 (Value->isUnion() && Value->getUnionField() != FD)) { 6314 if (CD->isUnion()) 6315 *Value = APValue(FD); 6316 else 6317 // FIXME: This immediately starts the lifetime of all members of 6318 // an anonymous struct. It would be preferable to strictly start 6319 // member lifetime in initialization order. 6320 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6321 } 6322 // Store Subobject as its parent before updating it for the last element 6323 // in the chain. 6324 if (C == IndirectFieldChain.back()) 6325 SubobjectParent = Subobject; 6326 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6327 return false; 6328 if (CD->isUnion()) 6329 Value = &Value->getUnionValue(); 6330 else { 6331 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6332 SkipToField(FD, true); 6333 Value = &Value->getStructField(FD->getFieldIndex()); 6334 } 6335 } 6336 } else { 6337 llvm_unreachable("unknown base initializer kind"); 6338 } 6339 6340 // Need to override This for implicit field initializers as in this case 6341 // This refers to innermost anonymous struct/union containing initializer, 6342 // not to currently constructed class. 6343 const Expr *Init = I->getInit(); 6344 if (Init->isValueDependent()) { 6345 if (!EvaluateDependentExpr(Init, Info)) 6346 return false; 6347 } else { 6348 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6349 isa<CXXDefaultInitExpr>(Init)); 6350 FullExpressionRAII InitScope(Info); 6351 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6352 (FD && FD->isBitField() && 6353 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6354 // If we're checking for a potential constant expression, evaluate all 6355 // initializers even if some of them fail. 6356 if (!Info.noteFailure()) 6357 return false; 6358 Success = false; 6359 } 6360 } 6361 6362 // This is the point at which the dynamic type of the object becomes this 6363 // class type. 6364 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6365 EvalObj.finishedConstructingBases(); 6366 } 6367 6368 // Default-initialize any remaining fields. 6369 if (!RD->isUnion()) { 6370 for (; FieldIt != RD->field_end(); ++FieldIt) { 6371 if (!FieldIt->isUnnamedBitfield()) 6372 Success &= getDefaultInitValue( 6373 FieldIt->getType(), 6374 Result.getStructField(FieldIt->getFieldIndex())); 6375 } 6376 } 6377 6378 EvalObj.finishedConstructingFields(); 6379 6380 return Success && 6381 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6382 LifetimeExtendedScope.destroy(); 6383 } 6384 6385 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6386 ArrayRef<const Expr*> Args, 6387 const CXXConstructorDecl *Definition, 6388 EvalInfo &Info, APValue &Result) { 6389 CallScopeRAII CallScope(Info); 6390 CallRef Call = Info.CurrentCall->createCall(Definition); 6391 if (!EvaluateArgs(Args, Call, Info, Definition)) 6392 return false; 6393 6394 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6395 CallScope.destroy(); 6396 } 6397 6398 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6399 const LValue &This, APValue &Value, 6400 QualType T) { 6401 // Objects can only be destroyed while they're within their lifetimes. 6402 // FIXME: We have no representation for whether an object of type nullptr_t 6403 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6404 // as indeterminate instead? 6405 if (Value.isAbsent() && !T->isNullPtrType()) { 6406 APValue Printable; 6407 This.moveInto(Printable); 6408 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6409 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6410 return false; 6411 } 6412 6413 // Invent an expression for location purposes. 6414 // FIXME: We shouldn't need to do this. 6415 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6416 6417 // For arrays, destroy elements right-to-left. 6418 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6419 uint64_t Size = CAT->getSize().getZExtValue(); 6420 QualType ElemT = CAT->getElementType(); 6421 6422 LValue ElemLV = This; 6423 ElemLV.addArray(Info, &LocE, CAT); 6424 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6425 return false; 6426 6427 // Ensure that we have actual array elements available to destroy; the 6428 // destructors might mutate the value, so we can't run them on the array 6429 // filler. 6430 if (Size && Size > Value.getArrayInitializedElts()) 6431 expandArray(Value, Value.getArraySize() - 1); 6432 6433 for (; Size != 0; --Size) { 6434 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6435 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6436 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6437 return false; 6438 } 6439 6440 // End the lifetime of this array now. 6441 Value = APValue(); 6442 return true; 6443 } 6444 6445 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6446 if (!RD) { 6447 if (T.isDestructedType()) { 6448 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6449 return false; 6450 } 6451 6452 Value = APValue(); 6453 return true; 6454 } 6455 6456 if (RD->getNumVBases()) { 6457 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6458 return false; 6459 } 6460 6461 const CXXDestructorDecl *DD = RD->getDestructor(); 6462 if (!DD && !RD->hasTrivialDestructor()) { 6463 Info.FFDiag(CallLoc); 6464 return false; 6465 } 6466 6467 if (!DD || DD->isTrivial() || 6468 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6469 // A trivial destructor just ends the lifetime of the object. Check for 6470 // this case before checking for a body, because we might not bother 6471 // building a body for a trivial destructor. Note that it doesn't matter 6472 // whether the destructor is constexpr in this case; all trivial 6473 // destructors are constexpr. 6474 // 6475 // If an anonymous union would be destroyed, some enclosing destructor must 6476 // have been explicitly defined, and the anonymous union destruction should 6477 // have no effect. 6478 Value = APValue(); 6479 return true; 6480 } 6481 6482 if (!Info.CheckCallLimit(CallLoc)) 6483 return false; 6484 6485 const FunctionDecl *Definition = nullptr; 6486 const Stmt *Body = DD->getBody(Definition); 6487 6488 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6489 return false; 6490 6491 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6492 6493 // We're now in the period of destruction of this object. 6494 unsigned BasesLeft = RD->getNumBases(); 6495 EvalInfo::EvaluatingDestructorRAII EvalObj( 6496 Info, 6497 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6498 if (!EvalObj.DidInsert) { 6499 // C++2a [class.dtor]p19: 6500 // the behavior is undefined if the destructor is invoked for an object 6501 // whose lifetime has ended 6502 // (Note that formally the lifetime ends when the period of destruction 6503 // begins, even though certain uses of the object remain valid until the 6504 // period of destruction ends.) 6505 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6506 return false; 6507 } 6508 6509 // FIXME: Creating an APValue just to hold a nonexistent return value is 6510 // wasteful. 6511 APValue RetVal; 6512 StmtResult Ret = {RetVal, nullptr}; 6513 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6514 return false; 6515 6516 // A union destructor does not implicitly destroy its members. 6517 if (RD->isUnion()) 6518 return true; 6519 6520 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6521 6522 // We don't have a good way to iterate fields in reverse, so collect all the 6523 // fields first and then walk them backwards. 6524 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6525 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6526 if (FD->isUnnamedBitfield()) 6527 continue; 6528 6529 LValue Subobject = This; 6530 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6531 return false; 6532 6533 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6534 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6535 FD->getType())) 6536 return false; 6537 } 6538 6539 if (BasesLeft != 0) 6540 EvalObj.startedDestroyingBases(); 6541 6542 // Destroy base classes in reverse order. 6543 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6544 --BasesLeft; 6545 6546 QualType BaseType = Base.getType(); 6547 LValue Subobject = This; 6548 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6549 BaseType->getAsCXXRecordDecl(), &Layout)) 6550 return false; 6551 6552 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6553 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6554 BaseType)) 6555 return false; 6556 } 6557 assert(BasesLeft == 0 && "NumBases was wrong?"); 6558 6559 // The period of destruction ends now. The object is gone. 6560 Value = APValue(); 6561 return true; 6562 } 6563 6564 namespace { 6565 struct DestroyObjectHandler { 6566 EvalInfo &Info; 6567 const Expr *E; 6568 const LValue &This; 6569 const AccessKinds AccessKind; 6570 6571 typedef bool result_type; 6572 bool failed() { return false; } 6573 bool found(APValue &Subobj, QualType SubobjType) { 6574 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6575 SubobjType); 6576 } 6577 bool found(APSInt &Value, QualType SubobjType) { 6578 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6579 return false; 6580 } 6581 bool found(APFloat &Value, QualType SubobjType) { 6582 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6583 return false; 6584 } 6585 }; 6586 } 6587 6588 /// Perform a destructor or pseudo-destructor call on the given object, which 6589 /// might in general not be a complete object. 6590 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6591 const LValue &This, QualType ThisType) { 6592 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6593 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6594 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6595 } 6596 6597 /// Destroy and end the lifetime of the given complete object. 6598 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6599 APValue::LValueBase LVBase, APValue &Value, 6600 QualType T) { 6601 // If we've had an unmodeled side-effect, we can't rely on mutable state 6602 // (such as the object we're about to destroy) being correct. 6603 if (Info.EvalStatus.HasSideEffects) 6604 return false; 6605 6606 LValue LV; 6607 LV.set({LVBase}); 6608 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6609 } 6610 6611 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6612 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6613 LValue &Result) { 6614 if (Info.checkingPotentialConstantExpression() || 6615 Info.SpeculativeEvaluationDepth) 6616 return false; 6617 6618 // This is permitted only within a call to std::allocator<T>::allocate. 6619 auto Caller = Info.getStdAllocatorCaller("allocate"); 6620 if (!Caller) { 6621 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6622 ? diag::note_constexpr_new_untyped 6623 : diag::note_constexpr_new); 6624 return false; 6625 } 6626 6627 QualType ElemType = Caller.ElemType; 6628 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6629 Info.FFDiag(E->getExprLoc(), 6630 diag::note_constexpr_new_not_complete_object_type) 6631 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6632 return false; 6633 } 6634 6635 APSInt ByteSize; 6636 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6637 return false; 6638 bool IsNothrow = false; 6639 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6640 EvaluateIgnoredValue(Info, E->getArg(I)); 6641 IsNothrow |= E->getType()->isNothrowT(); 6642 } 6643 6644 CharUnits ElemSize; 6645 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6646 return false; 6647 APInt Size, Remainder; 6648 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6649 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6650 if (Remainder != 0) { 6651 // This likely indicates a bug in the implementation of 'std::allocator'. 6652 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6653 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6654 return false; 6655 } 6656 6657 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6658 if (IsNothrow) { 6659 Result.setNull(Info.Ctx, E->getType()); 6660 return true; 6661 } 6662 6663 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6664 return false; 6665 } 6666 6667 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6668 ArrayType::Normal, 0); 6669 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6670 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6671 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6672 return true; 6673 } 6674 6675 static bool hasVirtualDestructor(QualType T) { 6676 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6677 if (CXXDestructorDecl *DD = RD->getDestructor()) 6678 return DD->isVirtual(); 6679 return false; 6680 } 6681 6682 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6683 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6684 if (CXXDestructorDecl *DD = RD->getDestructor()) 6685 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6686 return nullptr; 6687 } 6688 6689 /// Check that the given object is a suitable pointer to a heap allocation that 6690 /// still exists and is of the right kind for the purpose of a deletion. 6691 /// 6692 /// On success, returns the heap allocation to deallocate. On failure, produces 6693 /// a diagnostic and returns None. 6694 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6695 const LValue &Pointer, 6696 DynAlloc::Kind DeallocKind) { 6697 auto PointerAsString = [&] { 6698 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6699 }; 6700 6701 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6702 if (!DA) { 6703 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6704 << PointerAsString(); 6705 if (Pointer.Base) 6706 NoteLValueLocation(Info, Pointer.Base); 6707 return None; 6708 } 6709 6710 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6711 if (!Alloc) { 6712 Info.FFDiag(E, diag::note_constexpr_double_delete); 6713 return None; 6714 } 6715 6716 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6717 if (DeallocKind != (*Alloc)->getKind()) { 6718 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6719 << DeallocKind << (*Alloc)->getKind() << AllocType; 6720 NoteLValueLocation(Info, Pointer.Base); 6721 return None; 6722 } 6723 6724 bool Subobject = false; 6725 if (DeallocKind == DynAlloc::New) { 6726 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6727 Pointer.Designator.isOnePastTheEnd(); 6728 } else { 6729 Subobject = Pointer.Designator.Entries.size() != 1 || 6730 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6731 } 6732 if (Subobject) { 6733 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6734 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6735 return None; 6736 } 6737 6738 return Alloc; 6739 } 6740 6741 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6742 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6743 if (Info.checkingPotentialConstantExpression() || 6744 Info.SpeculativeEvaluationDepth) 6745 return false; 6746 6747 // This is permitted only within a call to std::allocator<T>::deallocate. 6748 if (!Info.getStdAllocatorCaller("deallocate")) { 6749 Info.FFDiag(E->getExprLoc()); 6750 return true; 6751 } 6752 6753 LValue Pointer; 6754 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6755 return false; 6756 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6757 EvaluateIgnoredValue(Info, E->getArg(I)); 6758 6759 if (Pointer.Designator.Invalid) 6760 return false; 6761 6762 // Deleting a null pointer would have no effect, but it's not permitted by 6763 // std::allocator<T>::deallocate's contract. 6764 if (Pointer.isNullPointer()) { 6765 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6766 return true; 6767 } 6768 6769 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6770 return false; 6771 6772 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6773 return true; 6774 } 6775 6776 //===----------------------------------------------------------------------===// 6777 // Generic Evaluation 6778 //===----------------------------------------------------------------------===// 6779 namespace { 6780 6781 class BitCastBuffer { 6782 // FIXME: We're going to need bit-level granularity when we support 6783 // bit-fields. 6784 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6785 // we don't support a host or target where that is the case. Still, we should 6786 // use a more generic type in case we ever do. 6787 SmallVector<Optional<unsigned char>, 32> Bytes; 6788 6789 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6790 "Need at least 8 bit unsigned char"); 6791 6792 bool TargetIsLittleEndian; 6793 6794 public: 6795 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6796 : Bytes(Width.getQuantity()), 6797 TargetIsLittleEndian(TargetIsLittleEndian) {} 6798 6799 LLVM_NODISCARD 6800 bool readObject(CharUnits Offset, CharUnits Width, 6801 SmallVectorImpl<unsigned char> &Output) const { 6802 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6803 // If a byte of an integer is uninitialized, then the whole integer is 6804 // uninitialized. 6805 if (!Bytes[I.getQuantity()]) 6806 return false; 6807 Output.push_back(*Bytes[I.getQuantity()]); 6808 } 6809 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6810 std::reverse(Output.begin(), Output.end()); 6811 return true; 6812 } 6813 6814 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6815 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6816 std::reverse(Input.begin(), Input.end()); 6817 6818 size_t Index = 0; 6819 for (unsigned char Byte : Input) { 6820 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6821 Bytes[Offset.getQuantity() + Index] = Byte; 6822 ++Index; 6823 } 6824 } 6825 6826 size_t size() { return Bytes.size(); } 6827 }; 6828 6829 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6830 /// target would represent the value at runtime. 6831 class APValueToBufferConverter { 6832 EvalInfo &Info; 6833 BitCastBuffer Buffer; 6834 const CastExpr *BCE; 6835 6836 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6837 const CastExpr *BCE) 6838 : Info(Info), 6839 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6840 BCE(BCE) {} 6841 6842 bool visit(const APValue &Val, QualType Ty) { 6843 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6844 } 6845 6846 // Write out Val with type Ty into Buffer starting at Offset. 6847 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6848 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6849 6850 // As a special case, nullptr_t has an indeterminate value. 6851 if (Ty->isNullPtrType()) 6852 return true; 6853 6854 // Dig through Src to find the byte at SrcOffset. 6855 switch (Val.getKind()) { 6856 case APValue::Indeterminate: 6857 case APValue::None: 6858 return true; 6859 6860 case APValue::Int: 6861 return visitInt(Val.getInt(), Ty, Offset); 6862 case APValue::Float: 6863 return visitFloat(Val.getFloat(), Ty, Offset); 6864 case APValue::Array: 6865 return visitArray(Val, Ty, Offset); 6866 case APValue::Struct: 6867 return visitRecord(Val, Ty, Offset); 6868 6869 case APValue::ComplexInt: 6870 case APValue::ComplexFloat: 6871 case APValue::Vector: 6872 case APValue::FixedPoint: 6873 // FIXME: We should support these. 6874 6875 case APValue::Union: 6876 case APValue::MemberPointer: 6877 case APValue::AddrLabelDiff: { 6878 Info.FFDiag(BCE->getBeginLoc(), 6879 diag::note_constexpr_bit_cast_unsupported_type) 6880 << Ty; 6881 return false; 6882 } 6883 6884 case APValue::LValue: 6885 llvm_unreachable("LValue subobject in bit_cast?"); 6886 } 6887 llvm_unreachable("Unhandled APValue::ValueKind"); 6888 } 6889 6890 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6891 const RecordDecl *RD = Ty->getAsRecordDecl(); 6892 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6893 6894 // Visit the base classes. 6895 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6896 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6897 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6898 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6899 6900 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6901 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6902 return false; 6903 } 6904 } 6905 6906 // Visit the fields. 6907 unsigned FieldIdx = 0; 6908 for (FieldDecl *FD : RD->fields()) { 6909 if (FD->isBitField()) { 6910 Info.FFDiag(BCE->getBeginLoc(), 6911 diag::note_constexpr_bit_cast_unsupported_bitfield); 6912 return false; 6913 } 6914 6915 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6916 6917 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6918 "only bit-fields can have sub-char alignment"); 6919 CharUnits FieldOffset = 6920 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6921 QualType FieldTy = FD->getType(); 6922 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6923 return false; 6924 ++FieldIdx; 6925 } 6926 6927 return true; 6928 } 6929 6930 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6931 const auto *CAT = 6932 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6933 if (!CAT) 6934 return false; 6935 6936 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6937 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6938 unsigned ArraySize = Val.getArraySize(); 6939 // First, initialize the initialized elements. 6940 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6941 const APValue &SubObj = Val.getArrayInitializedElt(I); 6942 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6943 return false; 6944 } 6945 6946 // Next, initialize the rest of the array using the filler. 6947 if (Val.hasArrayFiller()) { 6948 const APValue &Filler = Val.getArrayFiller(); 6949 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6950 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6951 return false; 6952 } 6953 } 6954 6955 return true; 6956 } 6957 6958 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6959 APSInt AdjustedVal = Val; 6960 unsigned Width = AdjustedVal.getBitWidth(); 6961 if (Ty->isBooleanType()) { 6962 Width = Info.Ctx.getTypeSize(Ty); 6963 AdjustedVal = AdjustedVal.extend(Width); 6964 } 6965 6966 SmallVector<unsigned char, 8> Bytes(Width / 8); 6967 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6968 Buffer.writeObject(Offset, Bytes); 6969 return true; 6970 } 6971 6972 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6973 APSInt AsInt(Val.bitcastToAPInt()); 6974 return visitInt(AsInt, Ty, Offset); 6975 } 6976 6977 public: 6978 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6979 const CastExpr *BCE) { 6980 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6981 APValueToBufferConverter Converter(Info, DstSize, BCE); 6982 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6983 return None; 6984 return Converter.Buffer; 6985 } 6986 }; 6987 6988 /// Write an BitCastBuffer into an APValue. 6989 class BufferToAPValueConverter { 6990 EvalInfo &Info; 6991 const BitCastBuffer &Buffer; 6992 const CastExpr *BCE; 6993 6994 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6995 const CastExpr *BCE) 6996 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6997 6998 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6999 // with an invalid type, so anything left is a deficiency on our part (FIXME). 7000 // Ideally this will be unreachable. 7001 llvm::NoneType unsupportedType(QualType Ty) { 7002 Info.FFDiag(BCE->getBeginLoc(), 7003 diag::note_constexpr_bit_cast_unsupported_type) 7004 << Ty; 7005 return None; 7006 } 7007 7008 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 7009 Info.FFDiag(BCE->getBeginLoc(), 7010 diag::note_constexpr_bit_cast_unrepresentable_value) 7011 << Ty << toString(Val, /*Radix=*/10); 7012 return None; 7013 } 7014 7015 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 7016 const EnumType *EnumSugar = nullptr) { 7017 if (T->isNullPtrType()) { 7018 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 7019 return APValue((Expr *)nullptr, 7020 /*Offset=*/CharUnits::fromQuantity(NullValue), 7021 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 7022 } 7023 7024 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 7025 7026 // Work around floating point types that contain unused padding bytes. This 7027 // is really just `long double` on x86, which is the only fundamental type 7028 // with padding bytes. 7029 if (T->isRealFloatingType()) { 7030 const llvm::fltSemantics &Semantics = 7031 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7032 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 7033 assert(NumBits % 8 == 0); 7034 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 7035 if (NumBytes != SizeOf) 7036 SizeOf = NumBytes; 7037 } 7038 7039 SmallVector<uint8_t, 8> Bytes; 7040 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7041 // If this is std::byte or unsigned char, then its okay to store an 7042 // indeterminate value. 7043 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7044 bool IsUChar = 7045 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7046 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7047 if (!IsStdByte && !IsUChar) { 7048 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7049 Info.FFDiag(BCE->getExprLoc(), 7050 diag::note_constexpr_bit_cast_indet_dest) 7051 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7052 return None; 7053 } 7054 7055 return APValue::IndeterminateValue(); 7056 } 7057 7058 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7059 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7060 7061 if (T->isIntegralOrEnumerationType()) { 7062 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7063 7064 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7065 if (IntWidth != Val.getBitWidth()) { 7066 APSInt Truncated = Val.trunc(IntWidth); 7067 if (Truncated.extend(Val.getBitWidth()) != Val) 7068 return unrepresentableValue(QualType(T, 0), Val); 7069 Val = Truncated; 7070 } 7071 7072 return APValue(Val); 7073 } 7074 7075 if (T->isRealFloatingType()) { 7076 const llvm::fltSemantics &Semantics = 7077 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7078 return APValue(APFloat(Semantics, Val)); 7079 } 7080 7081 return unsupportedType(QualType(T, 0)); 7082 } 7083 7084 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7085 const RecordDecl *RD = RTy->getAsRecordDecl(); 7086 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7087 7088 unsigned NumBases = 0; 7089 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7090 NumBases = CXXRD->getNumBases(); 7091 7092 APValue ResultVal(APValue::UninitStruct(), NumBases, 7093 std::distance(RD->field_begin(), RD->field_end())); 7094 7095 // Visit the base classes. 7096 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7097 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7098 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7099 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7100 if (BaseDecl->isEmpty() || 7101 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7102 continue; 7103 7104 Optional<APValue> SubObj = visitType( 7105 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7106 if (!SubObj) 7107 return None; 7108 ResultVal.getStructBase(I) = *SubObj; 7109 } 7110 } 7111 7112 // Visit the fields. 7113 unsigned FieldIdx = 0; 7114 for (FieldDecl *FD : RD->fields()) { 7115 // FIXME: We don't currently support bit-fields. A lot of the logic for 7116 // this is in CodeGen, so we need to factor it around. 7117 if (FD->isBitField()) { 7118 Info.FFDiag(BCE->getBeginLoc(), 7119 diag::note_constexpr_bit_cast_unsupported_bitfield); 7120 return None; 7121 } 7122 7123 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7124 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7125 7126 CharUnits FieldOffset = 7127 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7128 Offset; 7129 QualType FieldTy = FD->getType(); 7130 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7131 if (!SubObj) 7132 return None; 7133 ResultVal.getStructField(FieldIdx) = *SubObj; 7134 ++FieldIdx; 7135 } 7136 7137 return ResultVal; 7138 } 7139 7140 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7141 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7142 assert(!RepresentationType.isNull() && 7143 "enum forward decl should be caught by Sema"); 7144 const auto *AsBuiltin = 7145 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7146 // Recurse into the underlying type. Treat std::byte transparently as 7147 // unsigned char. 7148 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7149 } 7150 7151 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7152 size_t Size = Ty->getSize().getLimitedValue(); 7153 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7154 7155 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7156 for (size_t I = 0; I != Size; ++I) { 7157 Optional<APValue> ElementValue = 7158 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7159 if (!ElementValue) 7160 return None; 7161 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7162 } 7163 7164 return ArrayValue; 7165 } 7166 7167 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7168 return unsupportedType(QualType(Ty, 0)); 7169 } 7170 7171 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7172 QualType Can = Ty.getCanonicalType(); 7173 7174 switch (Can->getTypeClass()) { 7175 #define TYPE(Class, Base) \ 7176 case Type::Class: \ 7177 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7178 #define ABSTRACT_TYPE(Class, Base) 7179 #define NON_CANONICAL_TYPE(Class, Base) \ 7180 case Type::Class: \ 7181 llvm_unreachable("non-canonical type should be impossible!"); 7182 #define DEPENDENT_TYPE(Class, Base) \ 7183 case Type::Class: \ 7184 llvm_unreachable( \ 7185 "dependent types aren't supported in the constant evaluator!"); 7186 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7187 case Type::Class: \ 7188 llvm_unreachable("either dependent or not canonical!"); 7189 #include "clang/AST/TypeNodes.inc" 7190 } 7191 llvm_unreachable("Unhandled Type::TypeClass"); 7192 } 7193 7194 public: 7195 // Pull out a full value of type DstType. 7196 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7197 const CastExpr *BCE) { 7198 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7199 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7200 } 7201 }; 7202 7203 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7204 QualType Ty, EvalInfo *Info, 7205 const ASTContext &Ctx, 7206 bool CheckingDest) { 7207 Ty = Ty.getCanonicalType(); 7208 7209 auto diag = [&](int Reason) { 7210 if (Info) 7211 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7212 << CheckingDest << (Reason == 4) << Reason; 7213 return false; 7214 }; 7215 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7216 if (Info) 7217 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7218 << NoteTy << Construct << Ty; 7219 return false; 7220 }; 7221 7222 if (Ty->isUnionType()) 7223 return diag(0); 7224 if (Ty->isPointerType()) 7225 return diag(1); 7226 if (Ty->isMemberPointerType()) 7227 return diag(2); 7228 if (Ty.isVolatileQualified()) 7229 return diag(3); 7230 7231 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7232 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7233 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7234 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7235 CheckingDest)) 7236 return note(1, BS.getType(), BS.getBeginLoc()); 7237 } 7238 for (FieldDecl *FD : Record->fields()) { 7239 if (FD->getType()->isReferenceType()) 7240 return diag(4); 7241 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7242 CheckingDest)) 7243 return note(0, FD->getType(), FD->getBeginLoc()); 7244 } 7245 } 7246 7247 if (Ty->isArrayType() && 7248 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7249 Info, Ctx, CheckingDest)) 7250 return false; 7251 7252 return true; 7253 } 7254 7255 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7256 const ASTContext &Ctx, 7257 const CastExpr *BCE) { 7258 bool DestOK = checkBitCastConstexprEligibilityType( 7259 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7260 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7261 BCE->getBeginLoc(), 7262 BCE->getSubExpr()->getType(), Info, Ctx, false); 7263 return SourceOK; 7264 } 7265 7266 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7267 APValue &SourceValue, 7268 const CastExpr *BCE) { 7269 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7270 "no host or target supports non 8-bit chars"); 7271 assert(SourceValue.isLValue() && 7272 "LValueToRValueBitcast requires an lvalue operand!"); 7273 7274 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7275 return false; 7276 7277 LValue SourceLValue; 7278 APValue SourceRValue; 7279 SourceLValue.setFrom(Info.Ctx, SourceValue); 7280 if (!handleLValueToRValueConversion( 7281 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7282 SourceRValue, /*WantObjectRepresentation=*/true)) 7283 return false; 7284 7285 // Read out SourceValue into a char buffer. 7286 Optional<BitCastBuffer> Buffer = 7287 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7288 if (!Buffer) 7289 return false; 7290 7291 // Write out the buffer into a new APValue. 7292 Optional<APValue> MaybeDestValue = 7293 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7294 if (!MaybeDestValue) 7295 return false; 7296 7297 DestValue = std::move(*MaybeDestValue); 7298 return true; 7299 } 7300 7301 template <class Derived> 7302 class ExprEvaluatorBase 7303 : public ConstStmtVisitor<Derived, bool> { 7304 private: 7305 Derived &getDerived() { return static_cast<Derived&>(*this); } 7306 bool DerivedSuccess(const APValue &V, const Expr *E) { 7307 return getDerived().Success(V, E); 7308 } 7309 bool DerivedZeroInitialization(const Expr *E) { 7310 return getDerived().ZeroInitialization(E); 7311 } 7312 7313 // Check whether a conditional operator with a non-constant condition is a 7314 // potential constant expression. If neither arm is a potential constant 7315 // expression, then the conditional operator is not either. 7316 template<typename ConditionalOperator> 7317 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7318 assert(Info.checkingPotentialConstantExpression()); 7319 7320 // Speculatively evaluate both arms. 7321 SmallVector<PartialDiagnosticAt, 8> Diag; 7322 { 7323 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7324 StmtVisitorTy::Visit(E->getFalseExpr()); 7325 if (Diag.empty()) 7326 return; 7327 } 7328 7329 { 7330 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7331 Diag.clear(); 7332 StmtVisitorTy::Visit(E->getTrueExpr()); 7333 if (Diag.empty()) 7334 return; 7335 } 7336 7337 Error(E, diag::note_constexpr_conditional_never_const); 7338 } 7339 7340 7341 template<typename ConditionalOperator> 7342 bool HandleConditionalOperator(const ConditionalOperator *E) { 7343 bool BoolResult; 7344 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7345 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7346 CheckPotentialConstantConditional(E); 7347 return false; 7348 } 7349 if (Info.noteFailure()) { 7350 StmtVisitorTy::Visit(E->getTrueExpr()); 7351 StmtVisitorTy::Visit(E->getFalseExpr()); 7352 } 7353 return false; 7354 } 7355 7356 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7357 return StmtVisitorTy::Visit(EvalExpr); 7358 } 7359 7360 protected: 7361 EvalInfo &Info; 7362 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7363 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7364 7365 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7366 return Info.CCEDiag(E, D); 7367 } 7368 7369 bool ZeroInitialization(const Expr *E) { return Error(E); } 7370 7371 public: 7372 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7373 7374 EvalInfo &getEvalInfo() { return Info; } 7375 7376 /// Report an evaluation error. This should only be called when an error is 7377 /// first discovered. When propagating an error, just return false. 7378 bool Error(const Expr *E, diag::kind D) { 7379 Info.FFDiag(E, D); 7380 return false; 7381 } 7382 bool Error(const Expr *E) { 7383 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7384 } 7385 7386 bool VisitStmt(const Stmt *) { 7387 llvm_unreachable("Expression evaluator should not be called on stmts"); 7388 } 7389 bool VisitExpr(const Expr *E) { 7390 return Error(E); 7391 } 7392 7393 bool VisitConstantExpr(const ConstantExpr *E) { 7394 if (E->hasAPValueResult()) 7395 return DerivedSuccess(E->getAPValueResult(), E); 7396 7397 return StmtVisitorTy::Visit(E->getSubExpr()); 7398 } 7399 7400 bool VisitParenExpr(const ParenExpr *E) 7401 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7402 bool VisitUnaryExtension(const UnaryOperator *E) 7403 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7404 bool VisitUnaryPlus(const UnaryOperator *E) 7405 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7406 bool VisitChooseExpr(const ChooseExpr *E) 7407 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7408 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7409 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7410 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7411 { return StmtVisitorTy::Visit(E->getReplacement()); } 7412 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7413 TempVersionRAII RAII(*Info.CurrentCall); 7414 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7415 return StmtVisitorTy::Visit(E->getExpr()); 7416 } 7417 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7418 TempVersionRAII RAII(*Info.CurrentCall); 7419 // The initializer may not have been parsed yet, or might be erroneous. 7420 if (!E->getExpr()) 7421 return Error(E); 7422 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7423 return StmtVisitorTy::Visit(E->getExpr()); 7424 } 7425 7426 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7427 FullExpressionRAII Scope(Info); 7428 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7429 } 7430 7431 // Temporaries are registered when created, so we don't care about 7432 // CXXBindTemporaryExpr. 7433 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7434 return StmtVisitorTy::Visit(E->getSubExpr()); 7435 } 7436 7437 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7438 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7439 return static_cast<Derived*>(this)->VisitCastExpr(E); 7440 } 7441 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7442 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7443 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7444 return static_cast<Derived*>(this)->VisitCastExpr(E); 7445 } 7446 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7447 return static_cast<Derived*>(this)->VisitCastExpr(E); 7448 } 7449 7450 bool VisitBinaryOperator(const BinaryOperator *E) { 7451 switch (E->getOpcode()) { 7452 default: 7453 return Error(E); 7454 7455 case BO_Comma: 7456 VisitIgnoredValue(E->getLHS()); 7457 return StmtVisitorTy::Visit(E->getRHS()); 7458 7459 case BO_PtrMemD: 7460 case BO_PtrMemI: { 7461 LValue Obj; 7462 if (!HandleMemberPointerAccess(Info, E, Obj)) 7463 return false; 7464 APValue Result; 7465 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7466 return false; 7467 return DerivedSuccess(Result, E); 7468 } 7469 } 7470 } 7471 7472 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7473 return StmtVisitorTy::Visit(E->getSemanticForm()); 7474 } 7475 7476 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7477 // Evaluate and cache the common expression. We treat it as a temporary, 7478 // even though it's not quite the same thing. 7479 LValue CommonLV; 7480 if (!Evaluate(Info.CurrentCall->createTemporary( 7481 E->getOpaqueValue(), 7482 getStorageType(Info.Ctx, E->getOpaqueValue()), 7483 ScopeKind::FullExpression, CommonLV), 7484 Info, E->getCommon())) 7485 return false; 7486 7487 return HandleConditionalOperator(E); 7488 } 7489 7490 bool VisitConditionalOperator(const ConditionalOperator *E) { 7491 bool IsBcpCall = false; 7492 // If the condition (ignoring parens) is a __builtin_constant_p call, 7493 // the result is a constant expression if it can be folded without 7494 // side-effects. This is an important GNU extension. See GCC PR38377 7495 // for discussion. 7496 if (const CallExpr *CallCE = 7497 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7498 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7499 IsBcpCall = true; 7500 7501 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7502 // constant expression; we can't check whether it's potentially foldable. 7503 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7504 // it would return 'false' in this mode. 7505 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7506 return false; 7507 7508 FoldConstant Fold(Info, IsBcpCall); 7509 if (!HandleConditionalOperator(E)) { 7510 Fold.keepDiagnostics(); 7511 return false; 7512 } 7513 7514 return true; 7515 } 7516 7517 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7518 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7519 return DerivedSuccess(*Value, E); 7520 7521 const Expr *Source = E->getSourceExpr(); 7522 if (!Source) 7523 return Error(E); 7524 if (Source == E) { 7525 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7526 return Error(E); 7527 } 7528 return StmtVisitorTy::Visit(Source); 7529 } 7530 7531 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7532 for (const Expr *SemE : E->semantics()) { 7533 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7534 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7535 // result expression: there could be two different LValues that would 7536 // refer to the same object in that case, and we can't model that. 7537 if (SemE == E->getResultExpr()) 7538 return Error(E); 7539 7540 // Unique OVEs get evaluated if and when we encounter them when 7541 // emitting the rest of the semantic form, rather than eagerly. 7542 if (OVE->isUnique()) 7543 continue; 7544 7545 LValue LV; 7546 if (!Evaluate(Info.CurrentCall->createTemporary( 7547 OVE, getStorageType(Info.Ctx, OVE), 7548 ScopeKind::FullExpression, LV), 7549 Info, OVE->getSourceExpr())) 7550 return false; 7551 } else if (SemE == E->getResultExpr()) { 7552 if (!StmtVisitorTy::Visit(SemE)) 7553 return false; 7554 } else { 7555 if (!EvaluateIgnoredValue(Info, SemE)) 7556 return false; 7557 } 7558 } 7559 return true; 7560 } 7561 7562 bool VisitCallExpr(const CallExpr *E) { 7563 APValue Result; 7564 if (!handleCallExpr(E, Result, nullptr)) 7565 return false; 7566 return DerivedSuccess(Result, E); 7567 } 7568 7569 bool handleCallExpr(const CallExpr *E, APValue &Result, 7570 const LValue *ResultSlot) { 7571 CallScopeRAII CallScope(Info); 7572 7573 const Expr *Callee = E->getCallee()->IgnoreParens(); 7574 QualType CalleeType = Callee->getType(); 7575 7576 const FunctionDecl *FD = nullptr; 7577 LValue *This = nullptr, ThisVal; 7578 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7579 bool HasQualifier = false; 7580 7581 CallRef Call; 7582 7583 // Extract function decl and 'this' pointer from the callee. 7584 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7585 const CXXMethodDecl *Member = nullptr; 7586 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7587 // Explicit bound member calls, such as x.f() or p->g(); 7588 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7589 return false; 7590 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7591 if (!Member) 7592 return Error(Callee); 7593 This = &ThisVal; 7594 HasQualifier = ME->hasQualifier(); 7595 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7596 // Indirect bound member calls ('.*' or '->*'). 7597 const ValueDecl *D = 7598 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7599 if (!D) 7600 return false; 7601 Member = dyn_cast<CXXMethodDecl>(D); 7602 if (!Member) 7603 return Error(Callee); 7604 This = &ThisVal; 7605 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7606 if (!Info.getLangOpts().CPlusPlus20) 7607 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7608 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7609 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7610 } else 7611 return Error(Callee); 7612 FD = Member; 7613 } else if (CalleeType->isFunctionPointerType()) { 7614 LValue CalleeLV; 7615 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7616 return false; 7617 7618 if (!CalleeLV.getLValueOffset().isZero()) 7619 return Error(Callee); 7620 FD = dyn_cast_or_null<FunctionDecl>( 7621 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7622 if (!FD) 7623 return Error(Callee); 7624 // Don't call function pointers which have been cast to some other type. 7625 // Per DR (no number yet), the caller and callee can differ in noexcept. 7626 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7627 CalleeType->getPointeeType(), FD->getType())) { 7628 return Error(E); 7629 } 7630 7631 // For an (overloaded) assignment expression, evaluate the RHS before the 7632 // LHS. 7633 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7634 if (OCE && OCE->isAssignmentOp()) { 7635 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7636 Call = Info.CurrentCall->createCall(FD); 7637 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7638 Info, FD, /*RightToLeft=*/true)) 7639 return false; 7640 } 7641 7642 // Overloaded operator calls to member functions are represented as normal 7643 // calls with '*this' as the first argument. 7644 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7645 if (MD && !MD->isStatic()) { 7646 // FIXME: When selecting an implicit conversion for an overloaded 7647 // operator delete, we sometimes try to evaluate calls to conversion 7648 // operators without a 'this' parameter! 7649 if (Args.empty()) 7650 return Error(E); 7651 7652 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7653 return false; 7654 This = &ThisVal; 7655 7656 // If this is syntactically a simple assignment using a trivial 7657 // assignment operator, start the lifetimes of union members as needed, 7658 // per C++20 [class.union]5. 7659 if (Info.getLangOpts().CPlusPlus20 && OCE && 7660 OCE->getOperator() == OO_Equal && MD->isTrivial() && 7661 !HandleUnionActiveMemberChange(Info, Args[0], ThisVal)) 7662 return false; 7663 7664 Args = Args.slice(1); 7665 } else if (MD && MD->isLambdaStaticInvoker()) { 7666 // Map the static invoker for the lambda back to the call operator. 7667 // Conveniently, we don't have to slice out the 'this' argument (as is 7668 // being done for the non-static case), since a static member function 7669 // doesn't have an implicit argument passed in. 7670 const CXXRecordDecl *ClosureClass = MD->getParent(); 7671 assert( 7672 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7673 "Number of captures must be zero for conversion to function-ptr"); 7674 7675 const CXXMethodDecl *LambdaCallOp = 7676 ClosureClass->getLambdaCallOperator(); 7677 7678 // Set 'FD', the function that will be called below, to the call 7679 // operator. If the closure object represents a generic lambda, find 7680 // the corresponding specialization of the call operator. 7681 7682 if (ClosureClass->isGenericLambda()) { 7683 assert(MD->isFunctionTemplateSpecialization() && 7684 "A generic lambda's static-invoker function must be a " 7685 "template specialization"); 7686 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7687 FunctionTemplateDecl *CallOpTemplate = 7688 LambdaCallOp->getDescribedFunctionTemplate(); 7689 void *InsertPos = nullptr; 7690 FunctionDecl *CorrespondingCallOpSpecialization = 7691 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7692 assert(CorrespondingCallOpSpecialization && 7693 "We must always have a function call operator specialization " 7694 "that corresponds to our static invoker specialization"); 7695 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7696 } else 7697 FD = LambdaCallOp; 7698 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7699 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7700 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7701 LValue Ptr; 7702 if (!HandleOperatorNewCall(Info, E, Ptr)) 7703 return false; 7704 Ptr.moveInto(Result); 7705 return CallScope.destroy(); 7706 } else { 7707 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7708 } 7709 } 7710 } else 7711 return Error(E); 7712 7713 // Evaluate the arguments now if we've not already done so. 7714 if (!Call) { 7715 Call = Info.CurrentCall->createCall(FD); 7716 if (!EvaluateArgs(Args, Call, Info, FD)) 7717 return false; 7718 } 7719 7720 SmallVector<QualType, 4> CovariantAdjustmentPath; 7721 if (This) { 7722 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7723 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7724 // Perform virtual dispatch, if necessary. 7725 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7726 CovariantAdjustmentPath); 7727 if (!FD) 7728 return false; 7729 } else { 7730 // Check that the 'this' pointer points to an object of the right type. 7731 // FIXME: If this is an assignment operator call, we may need to change 7732 // the active union member before we check this. 7733 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7734 return false; 7735 } 7736 } 7737 7738 // Destructor calls are different enough that they have their own codepath. 7739 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7740 assert(This && "no 'this' pointer for destructor call"); 7741 return HandleDestruction(Info, E, *This, 7742 Info.Ctx.getRecordType(DD->getParent())) && 7743 CallScope.destroy(); 7744 } 7745 7746 const FunctionDecl *Definition = nullptr; 7747 Stmt *Body = FD->getBody(Definition); 7748 7749 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7750 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7751 Body, Info, Result, ResultSlot)) 7752 return false; 7753 7754 if (!CovariantAdjustmentPath.empty() && 7755 !HandleCovariantReturnAdjustment(Info, E, Result, 7756 CovariantAdjustmentPath)) 7757 return false; 7758 7759 return CallScope.destroy(); 7760 } 7761 7762 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7763 return StmtVisitorTy::Visit(E->getInitializer()); 7764 } 7765 bool VisitInitListExpr(const InitListExpr *E) { 7766 if (E->getNumInits() == 0) 7767 return DerivedZeroInitialization(E); 7768 if (E->getNumInits() == 1) 7769 return StmtVisitorTy::Visit(E->getInit(0)); 7770 return Error(E); 7771 } 7772 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7773 return DerivedZeroInitialization(E); 7774 } 7775 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7776 return DerivedZeroInitialization(E); 7777 } 7778 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7779 return DerivedZeroInitialization(E); 7780 } 7781 7782 /// A member expression where the object is a prvalue is itself a prvalue. 7783 bool VisitMemberExpr(const MemberExpr *E) { 7784 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7785 "missing temporary materialization conversion"); 7786 assert(!E->isArrow() && "missing call to bound member function?"); 7787 7788 APValue Val; 7789 if (!Evaluate(Val, Info, E->getBase())) 7790 return false; 7791 7792 QualType BaseTy = E->getBase()->getType(); 7793 7794 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7795 if (!FD) return Error(E); 7796 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7797 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7798 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7799 7800 // Note: there is no lvalue base here. But this case should only ever 7801 // happen in C or in C++98, where we cannot be evaluating a constexpr 7802 // constructor, which is the only case the base matters. 7803 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7804 SubobjectDesignator Designator(BaseTy); 7805 Designator.addDeclUnchecked(FD); 7806 7807 APValue Result; 7808 return extractSubobject(Info, E, Obj, Designator, Result) && 7809 DerivedSuccess(Result, E); 7810 } 7811 7812 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7813 APValue Val; 7814 if (!Evaluate(Val, Info, E->getBase())) 7815 return false; 7816 7817 if (Val.isVector()) { 7818 SmallVector<uint32_t, 4> Indices; 7819 E->getEncodedElementAccess(Indices); 7820 if (Indices.size() == 1) { 7821 // Return scalar. 7822 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7823 } else { 7824 // Construct new APValue vector. 7825 SmallVector<APValue, 4> Elts; 7826 for (unsigned I = 0; I < Indices.size(); ++I) { 7827 Elts.push_back(Val.getVectorElt(Indices[I])); 7828 } 7829 APValue VecResult(Elts.data(), Indices.size()); 7830 return DerivedSuccess(VecResult, E); 7831 } 7832 } 7833 7834 return false; 7835 } 7836 7837 bool VisitCastExpr(const CastExpr *E) { 7838 switch (E->getCastKind()) { 7839 default: 7840 break; 7841 7842 case CK_AtomicToNonAtomic: { 7843 APValue AtomicVal; 7844 // This does not need to be done in place even for class/array types: 7845 // atomic-to-non-atomic conversion implies copying the object 7846 // representation. 7847 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7848 return false; 7849 return DerivedSuccess(AtomicVal, E); 7850 } 7851 7852 case CK_NoOp: 7853 case CK_UserDefinedConversion: 7854 return StmtVisitorTy::Visit(E->getSubExpr()); 7855 7856 case CK_LValueToRValue: { 7857 LValue LVal; 7858 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7859 return false; 7860 APValue RVal; 7861 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7862 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7863 LVal, RVal)) 7864 return false; 7865 return DerivedSuccess(RVal, E); 7866 } 7867 case CK_LValueToRValueBitCast: { 7868 APValue DestValue, SourceValue; 7869 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7870 return false; 7871 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7872 return false; 7873 return DerivedSuccess(DestValue, E); 7874 } 7875 7876 case CK_AddressSpaceConversion: { 7877 APValue Value; 7878 if (!Evaluate(Value, Info, E->getSubExpr())) 7879 return false; 7880 return DerivedSuccess(Value, E); 7881 } 7882 } 7883 7884 return Error(E); 7885 } 7886 7887 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7888 return VisitUnaryPostIncDec(UO); 7889 } 7890 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7891 return VisitUnaryPostIncDec(UO); 7892 } 7893 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7894 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7895 return Error(UO); 7896 7897 LValue LVal; 7898 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7899 return false; 7900 APValue RVal; 7901 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7902 UO->isIncrementOp(), &RVal)) 7903 return false; 7904 return DerivedSuccess(RVal, UO); 7905 } 7906 7907 bool VisitStmtExpr(const StmtExpr *E) { 7908 // We will have checked the full-expressions inside the statement expression 7909 // when they were completed, and don't need to check them again now. 7910 llvm::SaveAndRestore<bool> NotCheckingForUB( 7911 Info.CheckingForUndefinedBehavior, false); 7912 7913 const CompoundStmt *CS = E->getSubStmt(); 7914 if (CS->body_empty()) 7915 return true; 7916 7917 BlockScopeRAII Scope(Info); 7918 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7919 BE = CS->body_end(); 7920 /**/; ++BI) { 7921 if (BI + 1 == BE) { 7922 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7923 if (!FinalExpr) { 7924 Info.FFDiag((*BI)->getBeginLoc(), 7925 diag::note_constexpr_stmt_expr_unsupported); 7926 return false; 7927 } 7928 return this->Visit(FinalExpr) && Scope.destroy(); 7929 } 7930 7931 APValue ReturnValue; 7932 StmtResult Result = { ReturnValue, nullptr }; 7933 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7934 if (ESR != ESR_Succeeded) { 7935 // FIXME: If the statement-expression terminated due to 'return', 7936 // 'break', or 'continue', it would be nice to propagate that to 7937 // the outer statement evaluation rather than bailing out. 7938 if (ESR != ESR_Failed) 7939 Info.FFDiag((*BI)->getBeginLoc(), 7940 diag::note_constexpr_stmt_expr_unsupported); 7941 return false; 7942 } 7943 } 7944 7945 llvm_unreachable("Return from function from the loop above."); 7946 } 7947 7948 /// Visit a value which is evaluated, but whose value is ignored. 7949 void VisitIgnoredValue(const Expr *E) { 7950 EvaluateIgnoredValue(Info, E); 7951 } 7952 7953 /// Potentially visit a MemberExpr's base expression. 7954 void VisitIgnoredBaseExpression(const Expr *E) { 7955 // While MSVC doesn't evaluate the base expression, it does diagnose the 7956 // presence of side-effecting behavior. 7957 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7958 return; 7959 VisitIgnoredValue(E); 7960 } 7961 }; 7962 7963 } // namespace 7964 7965 //===----------------------------------------------------------------------===// 7966 // Common base class for lvalue and temporary evaluation. 7967 //===----------------------------------------------------------------------===// 7968 namespace { 7969 template<class Derived> 7970 class LValueExprEvaluatorBase 7971 : public ExprEvaluatorBase<Derived> { 7972 protected: 7973 LValue &Result; 7974 bool InvalidBaseOK; 7975 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7976 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7977 7978 bool Success(APValue::LValueBase B) { 7979 Result.set(B); 7980 return true; 7981 } 7982 7983 bool evaluatePointer(const Expr *E, LValue &Result) { 7984 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7985 } 7986 7987 public: 7988 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7989 : ExprEvaluatorBaseTy(Info), Result(Result), 7990 InvalidBaseOK(InvalidBaseOK) {} 7991 7992 bool Success(const APValue &V, const Expr *E) { 7993 Result.setFrom(this->Info.Ctx, V); 7994 return true; 7995 } 7996 7997 bool VisitMemberExpr(const MemberExpr *E) { 7998 // Handle non-static data members. 7999 QualType BaseTy; 8000 bool EvalOK; 8001 if (E->isArrow()) { 8002 EvalOK = evaluatePointer(E->getBase(), Result); 8003 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 8004 } else if (E->getBase()->isPRValue()) { 8005 assert(E->getBase()->getType()->isRecordType()); 8006 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 8007 BaseTy = E->getBase()->getType(); 8008 } else { 8009 EvalOK = this->Visit(E->getBase()); 8010 BaseTy = E->getBase()->getType(); 8011 } 8012 if (!EvalOK) { 8013 if (!InvalidBaseOK) 8014 return false; 8015 Result.setInvalid(E); 8016 return true; 8017 } 8018 8019 const ValueDecl *MD = E->getMemberDecl(); 8020 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 8021 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 8022 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 8023 (void)BaseTy; 8024 if (!HandleLValueMember(this->Info, E, Result, FD)) 8025 return false; 8026 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 8027 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 8028 return false; 8029 } else 8030 return this->Error(E); 8031 8032 if (MD->getType()->isReferenceType()) { 8033 APValue RefValue; 8034 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 8035 RefValue)) 8036 return false; 8037 return Success(RefValue, E); 8038 } 8039 return true; 8040 } 8041 8042 bool VisitBinaryOperator(const BinaryOperator *E) { 8043 switch (E->getOpcode()) { 8044 default: 8045 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8046 8047 case BO_PtrMemD: 8048 case BO_PtrMemI: 8049 return HandleMemberPointerAccess(this->Info, E, Result); 8050 } 8051 } 8052 8053 bool VisitCastExpr(const CastExpr *E) { 8054 switch (E->getCastKind()) { 8055 default: 8056 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8057 8058 case CK_DerivedToBase: 8059 case CK_UncheckedDerivedToBase: 8060 if (!this->Visit(E->getSubExpr())) 8061 return false; 8062 8063 // Now figure out the necessary offset to add to the base LV to get from 8064 // the derived class to the base class. 8065 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8066 Result); 8067 } 8068 } 8069 }; 8070 } 8071 8072 //===----------------------------------------------------------------------===// 8073 // LValue Evaluation 8074 // 8075 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8076 // function designators (in C), decl references to void objects (in C), and 8077 // temporaries (if building with -Wno-address-of-temporary). 8078 // 8079 // LValue evaluation produces values comprising a base expression of one of the 8080 // following types: 8081 // - Declarations 8082 // * VarDecl 8083 // * FunctionDecl 8084 // - Literals 8085 // * CompoundLiteralExpr in C (and in global scope in C++) 8086 // * StringLiteral 8087 // * PredefinedExpr 8088 // * ObjCStringLiteralExpr 8089 // * ObjCEncodeExpr 8090 // * AddrLabelExpr 8091 // * BlockExpr 8092 // * CallExpr for a MakeStringConstant builtin 8093 // - typeid(T) expressions, as TypeInfoLValues 8094 // - Locals and temporaries 8095 // * MaterializeTemporaryExpr 8096 // * Any Expr, with a CallIndex indicating the function in which the temporary 8097 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8098 // from the AST (FIXME). 8099 // * A MaterializeTemporaryExpr that has static storage duration, with no 8100 // CallIndex, for a lifetime-extended temporary. 8101 // * The ConstantExpr that is currently being evaluated during evaluation of an 8102 // immediate invocation. 8103 // plus an offset in bytes. 8104 //===----------------------------------------------------------------------===// 8105 namespace { 8106 class LValueExprEvaluator 8107 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8108 public: 8109 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8110 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8111 8112 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8113 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8114 8115 bool VisitDeclRefExpr(const DeclRefExpr *E); 8116 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8117 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8118 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8119 bool VisitMemberExpr(const MemberExpr *E); 8120 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8121 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8122 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8123 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8124 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8125 bool VisitUnaryDeref(const UnaryOperator *E); 8126 bool VisitUnaryReal(const UnaryOperator *E); 8127 bool VisitUnaryImag(const UnaryOperator *E); 8128 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8129 return VisitUnaryPreIncDec(UO); 8130 } 8131 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8132 return VisitUnaryPreIncDec(UO); 8133 } 8134 bool VisitBinAssign(const BinaryOperator *BO); 8135 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8136 8137 bool VisitCastExpr(const CastExpr *E) { 8138 switch (E->getCastKind()) { 8139 default: 8140 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8141 8142 case CK_LValueBitCast: 8143 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8144 if (!Visit(E->getSubExpr())) 8145 return false; 8146 Result.Designator.setInvalid(); 8147 return true; 8148 8149 case CK_BaseToDerived: 8150 if (!Visit(E->getSubExpr())) 8151 return false; 8152 return HandleBaseToDerivedCast(Info, E, Result); 8153 8154 case CK_Dynamic: 8155 if (!Visit(E->getSubExpr())) 8156 return false; 8157 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8158 } 8159 } 8160 }; 8161 } // end anonymous namespace 8162 8163 /// Evaluate an expression as an lvalue. This can be legitimately called on 8164 /// expressions which are not glvalues, in three cases: 8165 /// * function designators in C, and 8166 /// * "extern void" objects 8167 /// * @selector() expressions in Objective-C 8168 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8169 bool InvalidBaseOK) { 8170 assert(!E->isValueDependent()); 8171 assert(E->isGLValue() || E->getType()->isFunctionType() || 8172 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8173 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8174 } 8175 8176 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8177 const NamedDecl *D = E->getDecl(); 8178 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8179 return Success(cast<ValueDecl>(D)); 8180 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8181 return VisitVarDecl(E, VD); 8182 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8183 return Visit(BD->getBinding()); 8184 return Error(E); 8185 } 8186 8187 8188 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8189 8190 // If we are within a lambda's call operator, check whether the 'VD' referred 8191 // to within 'E' actually represents a lambda-capture that maps to a 8192 // data-member/field within the closure object, and if so, evaluate to the 8193 // field or what the field refers to. 8194 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8195 isa<DeclRefExpr>(E) && 8196 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8197 // We don't always have a complete capture-map when checking or inferring if 8198 // the function call operator meets the requirements of a constexpr function 8199 // - but we don't need to evaluate the captures to determine constexprness 8200 // (dcl.constexpr C++17). 8201 if (Info.checkingPotentialConstantExpression()) 8202 return false; 8203 8204 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8205 // Start with 'Result' referring to the complete closure object... 8206 Result = *Info.CurrentCall->This; 8207 // ... then update it to refer to the field of the closure object 8208 // that represents the capture. 8209 if (!HandleLValueMember(Info, E, Result, FD)) 8210 return false; 8211 // And if the field is of reference type, update 'Result' to refer to what 8212 // the field refers to. 8213 if (FD->getType()->isReferenceType()) { 8214 APValue RVal; 8215 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8216 RVal)) 8217 return false; 8218 Result.setFrom(Info.Ctx, RVal); 8219 } 8220 return true; 8221 } 8222 } 8223 8224 CallStackFrame *Frame = nullptr; 8225 unsigned Version = 0; 8226 if (VD->hasLocalStorage()) { 8227 // Only if a local variable was declared in the function currently being 8228 // evaluated, do we expect to be able to find its value in the current 8229 // frame. (Otherwise it was likely declared in an enclosing context and 8230 // could either have a valid evaluatable value (for e.g. a constexpr 8231 // variable) or be ill-formed (and trigger an appropriate evaluation 8232 // diagnostic)). 8233 CallStackFrame *CurrFrame = Info.CurrentCall; 8234 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8235 // Function parameters are stored in some caller's frame. (Usually the 8236 // immediate caller, but for an inherited constructor they may be more 8237 // distant.) 8238 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8239 if (CurrFrame->Arguments) { 8240 VD = CurrFrame->Arguments.getOrigParam(PVD); 8241 Frame = 8242 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8243 Version = CurrFrame->Arguments.Version; 8244 } 8245 } else { 8246 Frame = CurrFrame; 8247 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8248 } 8249 } 8250 } 8251 8252 if (!VD->getType()->isReferenceType()) { 8253 if (Frame) { 8254 Result.set({VD, Frame->Index, Version}); 8255 return true; 8256 } 8257 return Success(VD); 8258 } 8259 8260 if (!Info.getLangOpts().CPlusPlus11) { 8261 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8262 << VD << VD->getType(); 8263 Info.Note(VD->getLocation(), diag::note_declared_at); 8264 } 8265 8266 APValue *V; 8267 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8268 return false; 8269 if (!V->hasValue()) { 8270 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8271 // adjust the diagnostic to say that. 8272 if (!Info.checkingPotentialConstantExpression()) 8273 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8274 return false; 8275 } 8276 return Success(*V, E); 8277 } 8278 8279 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8280 const MaterializeTemporaryExpr *E) { 8281 // Walk through the expression to find the materialized temporary itself. 8282 SmallVector<const Expr *, 2> CommaLHSs; 8283 SmallVector<SubobjectAdjustment, 2> Adjustments; 8284 const Expr *Inner = 8285 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8286 8287 // If we passed any comma operators, evaluate their LHSs. 8288 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8289 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8290 return false; 8291 8292 // A materialized temporary with static storage duration can appear within the 8293 // result of a constant expression evaluation, so we need to preserve its 8294 // value for use outside this evaluation. 8295 APValue *Value; 8296 if (E->getStorageDuration() == SD_Static) { 8297 // FIXME: What about SD_Thread? 8298 Value = E->getOrCreateValue(true); 8299 *Value = APValue(); 8300 Result.set(E); 8301 } else { 8302 Value = &Info.CurrentCall->createTemporary( 8303 E, E->getType(), 8304 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8305 : ScopeKind::Block, 8306 Result); 8307 } 8308 8309 QualType Type = Inner->getType(); 8310 8311 // Materialize the temporary itself. 8312 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8313 *Value = APValue(); 8314 return false; 8315 } 8316 8317 // Adjust our lvalue to refer to the desired subobject. 8318 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8319 --I; 8320 switch (Adjustments[I].Kind) { 8321 case SubobjectAdjustment::DerivedToBaseAdjustment: 8322 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8323 Type, Result)) 8324 return false; 8325 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8326 break; 8327 8328 case SubobjectAdjustment::FieldAdjustment: 8329 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8330 return false; 8331 Type = Adjustments[I].Field->getType(); 8332 break; 8333 8334 case SubobjectAdjustment::MemberPointerAdjustment: 8335 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8336 Adjustments[I].Ptr.RHS)) 8337 return false; 8338 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8339 break; 8340 } 8341 } 8342 8343 return true; 8344 } 8345 8346 bool 8347 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8348 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8349 "lvalue compound literal in c++?"); 8350 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8351 // only see this when folding in C, so there's no standard to follow here. 8352 return Success(E); 8353 } 8354 8355 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8356 TypeInfoLValue TypeInfo; 8357 8358 if (!E->isPotentiallyEvaluated()) { 8359 if (E->isTypeOperand()) 8360 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8361 else 8362 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8363 } else { 8364 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8365 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8366 << E->getExprOperand()->getType() 8367 << E->getExprOperand()->getSourceRange(); 8368 } 8369 8370 if (!Visit(E->getExprOperand())) 8371 return false; 8372 8373 Optional<DynamicType> DynType = 8374 ComputeDynamicType(Info, E, Result, AK_TypeId); 8375 if (!DynType) 8376 return false; 8377 8378 TypeInfo = 8379 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8380 } 8381 8382 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8383 } 8384 8385 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8386 return Success(E->getGuidDecl()); 8387 } 8388 8389 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8390 // Handle static data members. 8391 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8392 VisitIgnoredBaseExpression(E->getBase()); 8393 return VisitVarDecl(E, VD); 8394 } 8395 8396 // Handle static member functions. 8397 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8398 if (MD->isStatic()) { 8399 VisitIgnoredBaseExpression(E->getBase()); 8400 return Success(MD); 8401 } 8402 } 8403 8404 // Handle non-static data members. 8405 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8406 } 8407 8408 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8409 // FIXME: Deal with vectors as array subscript bases. 8410 if (E->getBase()->getType()->isVectorType()) 8411 return Error(E); 8412 8413 APSInt Index; 8414 bool Success = true; 8415 8416 // C++17's rules require us to evaluate the LHS first, regardless of which 8417 // side is the base. 8418 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8419 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8420 : !EvaluateInteger(SubExpr, Index, Info)) { 8421 if (!Info.noteFailure()) 8422 return false; 8423 Success = false; 8424 } 8425 } 8426 8427 return Success && 8428 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8429 } 8430 8431 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8432 return evaluatePointer(E->getSubExpr(), Result); 8433 } 8434 8435 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8436 if (!Visit(E->getSubExpr())) 8437 return false; 8438 // __real is a no-op on scalar lvalues. 8439 if (E->getSubExpr()->getType()->isAnyComplexType()) 8440 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8441 return true; 8442 } 8443 8444 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8445 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8446 "lvalue __imag__ on scalar?"); 8447 if (!Visit(E->getSubExpr())) 8448 return false; 8449 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8450 return true; 8451 } 8452 8453 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8454 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8455 return Error(UO); 8456 8457 if (!this->Visit(UO->getSubExpr())) 8458 return false; 8459 8460 return handleIncDec( 8461 this->Info, UO, Result, UO->getSubExpr()->getType(), 8462 UO->isIncrementOp(), nullptr); 8463 } 8464 8465 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8466 const CompoundAssignOperator *CAO) { 8467 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8468 return Error(CAO); 8469 8470 bool Success = true; 8471 8472 // C++17 onwards require that we evaluate the RHS first. 8473 APValue RHS; 8474 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8475 if (!Info.noteFailure()) 8476 return false; 8477 Success = false; 8478 } 8479 8480 // The overall lvalue result is the result of evaluating the LHS. 8481 if (!this->Visit(CAO->getLHS()) || !Success) 8482 return false; 8483 8484 return handleCompoundAssignment( 8485 this->Info, CAO, 8486 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8487 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8488 } 8489 8490 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8491 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8492 return Error(E); 8493 8494 bool Success = true; 8495 8496 // C++17 onwards require that we evaluate the RHS first. 8497 APValue NewVal; 8498 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8499 if (!Info.noteFailure()) 8500 return false; 8501 Success = false; 8502 } 8503 8504 if (!this->Visit(E->getLHS()) || !Success) 8505 return false; 8506 8507 if (Info.getLangOpts().CPlusPlus20 && 8508 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8509 return false; 8510 8511 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8512 NewVal); 8513 } 8514 8515 //===----------------------------------------------------------------------===// 8516 // Pointer Evaluation 8517 //===----------------------------------------------------------------------===// 8518 8519 /// Attempts to compute the number of bytes available at the pointer 8520 /// returned by a function with the alloc_size attribute. Returns true if we 8521 /// were successful. Places an unsigned number into `Result`. 8522 /// 8523 /// This expects the given CallExpr to be a call to a function with an 8524 /// alloc_size attribute. 8525 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8526 const CallExpr *Call, 8527 llvm::APInt &Result) { 8528 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8529 8530 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8531 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8532 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8533 if (Call->getNumArgs() <= SizeArgNo) 8534 return false; 8535 8536 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8537 Expr::EvalResult ExprResult; 8538 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8539 return false; 8540 Into = ExprResult.Val.getInt(); 8541 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8542 return false; 8543 Into = Into.zextOrSelf(BitsInSizeT); 8544 return true; 8545 }; 8546 8547 APSInt SizeOfElem; 8548 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8549 return false; 8550 8551 if (!AllocSize->getNumElemsParam().isValid()) { 8552 Result = std::move(SizeOfElem); 8553 return true; 8554 } 8555 8556 APSInt NumberOfElems; 8557 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8558 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8559 return false; 8560 8561 bool Overflow; 8562 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8563 if (Overflow) 8564 return false; 8565 8566 Result = std::move(BytesAvailable); 8567 return true; 8568 } 8569 8570 /// Convenience function. LVal's base must be a call to an alloc_size 8571 /// function. 8572 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8573 const LValue &LVal, 8574 llvm::APInt &Result) { 8575 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8576 "Can't get the size of a non alloc_size function"); 8577 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8578 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8579 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8580 } 8581 8582 /// Attempts to evaluate the given LValueBase as the result of a call to 8583 /// a function with the alloc_size attribute. If it was possible to do so, this 8584 /// function will return true, make Result's Base point to said function call, 8585 /// and mark Result's Base as invalid. 8586 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8587 LValue &Result) { 8588 if (Base.isNull()) 8589 return false; 8590 8591 // Because we do no form of static analysis, we only support const variables. 8592 // 8593 // Additionally, we can't support parameters, nor can we support static 8594 // variables (in the latter case, use-before-assign isn't UB; in the former, 8595 // we have no clue what they'll be assigned to). 8596 const auto *VD = 8597 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8598 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8599 return false; 8600 8601 const Expr *Init = VD->getAnyInitializer(); 8602 if (!Init) 8603 return false; 8604 8605 const Expr *E = Init->IgnoreParens(); 8606 if (!tryUnwrapAllocSizeCall(E)) 8607 return false; 8608 8609 // Store E instead of E unwrapped so that the type of the LValue's base is 8610 // what the user wanted. 8611 Result.setInvalid(E); 8612 8613 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8614 Result.addUnsizedArray(Info, E, Pointee); 8615 return true; 8616 } 8617 8618 namespace { 8619 class PointerExprEvaluator 8620 : public ExprEvaluatorBase<PointerExprEvaluator> { 8621 LValue &Result; 8622 bool InvalidBaseOK; 8623 8624 bool Success(const Expr *E) { 8625 Result.set(E); 8626 return true; 8627 } 8628 8629 bool evaluateLValue(const Expr *E, LValue &Result) { 8630 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8631 } 8632 8633 bool evaluatePointer(const Expr *E, LValue &Result) { 8634 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8635 } 8636 8637 bool visitNonBuiltinCallExpr(const CallExpr *E); 8638 public: 8639 8640 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8641 : ExprEvaluatorBaseTy(info), Result(Result), 8642 InvalidBaseOK(InvalidBaseOK) {} 8643 8644 bool Success(const APValue &V, const Expr *E) { 8645 Result.setFrom(Info.Ctx, V); 8646 return true; 8647 } 8648 bool ZeroInitialization(const Expr *E) { 8649 Result.setNull(Info.Ctx, E->getType()); 8650 return true; 8651 } 8652 8653 bool VisitBinaryOperator(const BinaryOperator *E); 8654 bool VisitCastExpr(const CastExpr* E); 8655 bool VisitUnaryAddrOf(const UnaryOperator *E); 8656 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8657 { return Success(E); } 8658 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8659 if (E->isExpressibleAsConstantInitializer()) 8660 return Success(E); 8661 if (Info.noteFailure()) 8662 EvaluateIgnoredValue(Info, E->getSubExpr()); 8663 return Error(E); 8664 } 8665 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8666 { return Success(E); } 8667 bool VisitCallExpr(const CallExpr *E); 8668 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8669 bool VisitBlockExpr(const BlockExpr *E) { 8670 if (!E->getBlockDecl()->hasCaptures()) 8671 return Success(E); 8672 return Error(E); 8673 } 8674 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8675 // Can't look at 'this' when checking a potential constant expression. 8676 if (Info.checkingPotentialConstantExpression()) 8677 return false; 8678 if (!Info.CurrentCall->This) { 8679 if (Info.getLangOpts().CPlusPlus11) 8680 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8681 else 8682 Info.FFDiag(E); 8683 return false; 8684 } 8685 Result = *Info.CurrentCall->This; 8686 // If we are inside a lambda's call operator, the 'this' expression refers 8687 // to the enclosing '*this' object (either by value or reference) which is 8688 // either copied into the closure object's field that represents the '*this' 8689 // or refers to '*this'. 8690 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8691 // Ensure we actually have captured 'this'. (an error will have 8692 // been previously reported if not). 8693 if (!Info.CurrentCall->LambdaThisCaptureField) 8694 return false; 8695 8696 // Update 'Result' to refer to the data member/field of the closure object 8697 // that represents the '*this' capture. 8698 if (!HandleLValueMember(Info, E, Result, 8699 Info.CurrentCall->LambdaThisCaptureField)) 8700 return false; 8701 // If we captured '*this' by reference, replace the field with its referent. 8702 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8703 ->isPointerType()) { 8704 APValue RVal; 8705 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8706 RVal)) 8707 return false; 8708 8709 Result.setFrom(Info.Ctx, RVal); 8710 } 8711 } 8712 return true; 8713 } 8714 8715 bool VisitCXXNewExpr(const CXXNewExpr *E); 8716 8717 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8718 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8719 APValue LValResult = E->EvaluateInContext( 8720 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8721 Result.setFrom(Info.Ctx, LValResult); 8722 return true; 8723 } 8724 8725 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8726 std::string ResultStr = E->ComputeName(Info.Ctx); 8727 8728 QualType CharTy = Info.Ctx.CharTy.withConst(); 8729 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8730 ResultStr.size() + 1); 8731 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8732 ArrayType::Normal, 0); 8733 8734 StringLiteral *SL = 8735 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, 8736 /*Pascal*/ false, ArrayTy, E->getLocation()); 8737 8738 evaluateLValue(SL, Result); 8739 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8740 return true; 8741 } 8742 8743 // FIXME: Missing: @protocol, @selector 8744 }; 8745 } // end anonymous namespace 8746 8747 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8748 bool InvalidBaseOK) { 8749 assert(!E->isValueDependent()); 8750 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8751 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8752 } 8753 8754 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8755 if (E->getOpcode() != BO_Add && 8756 E->getOpcode() != BO_Sub) 8757 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8758 8759 const Expr *PExp = E->getLHS(); 8760 const Expr *IExp = E->getRHS(); 8761 if (IExp->getType()->isPointerType()) 8762 std::swap(PExp, IExp); 8763 8764 bool EvalPtrOK = evaluatePointer(PExp, Result); 8765 if (!EvalPtrOK && !Info.noteFailure()) 8766 return false; 8767 8768 llvm::APSInt Offset; 8769 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8770 return false; 8771 8772 if (E->getOpcode() == BO_Sub) 8773 negateAsSigned(Offset); 8774 8775 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8776 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8777 } 8778 8779 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8780 return evaluateLValue(E->getSubExpr(), Result); 8781 } 8782 8783 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8784 const Expr *SubExpr = E->getSubExpr(); 8785 8786 switch (E->getCastKind()) { 8787 default: 8788 break; 8789 case CK_BitCast: 8790 case CK_CPointerToObjCPointerCast: 8791 case CK_BlockPointerToObjCPointerCast: 8792 case CK_AnyPointerToBlockPointerCast: 8793 case CK_AddressSpaceConversion: 8794 if (!Visit(SubExpr)) 8795 return false; 8796 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8797 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8798 // also static_casts, but we disallow them as a resolution to DR1312. 8799 if (!E->getType()->isVoidPointerType()) { 8800 if (!Result.InvalidBase && !Result.Designator.Invalid && 8801 !Result.IsNullPtr && 8802 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8803 E->getType()->getPointeeType()) && 8804 Info.getStdAllocatorCaller("allocate")) { 8805 // Inside a call to std::allocator::allocate and friends, we permit 8806 // casting from void* back to cv1 T* for a pointer that points to a 8807 // cv2 T. 8808 } else { 8809 Result.Designator.setInvalid(); 8810 if (SubExpr->getType()->isVoidPointerType()) 8811 CCEDiag(E, diag::note_constexpr_invalid_cast) 8812 << 3 << SubExpr->getType(); 8813 else 8814 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8815 } 8816 } 8817 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8818 ZeroInitialization(E); 8819 return true; 8820 8821 case CK_DerivedToBase: 8822 case CK_UncheckedDerivedToBase: 8823 if (!evaluatePointer(E->getSubExpr(), Result)) 8824 return false; 8825 if (!Result.Base && Result.Offset.isZero()) 8826 return true; 8827 8828 // Now figure out the necessary offset to add to the base LV to get from 8829 // the derived class to the base class. 8830 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8831 castAs<PointerType>()->getPointeeType(), 8832 Result); 8833 8834 case CK_BaseToDerived: 8835 if (!Visit(E->getSubExpr())) 8836 return false; 8837 if (!Result.Base && Result.Offset.isZero()) 8838 return true; 8839 return HandleBaseToDerivedCast(Info, E, Result); 8840 8841 case CK_Dynamic: 8842 if (!Visit(E->getSubExpr())) 8843 return false; 8844 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8845 8846 case CK_NullToPointer: 8847 VisitIgnoredValue(E->getSubExpr()); 8848 return ZeroInitialization(E); 8849 8850 case CK_IntegralToPointer: { 8851 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8852 8853 APValue Value; 8854 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8855 break; 8856 8857 if (Value.isInt()) { 8858 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8859 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8860 Result.Base = (Expr*)nullptr; 8861 Result.InvalidBase = false; 8862 Result.Offset = CharUnits::fromQuantity(N); 8863 Result.Designator.setInvalid(); 8864 Result.IsNullPtr = false; 8865 return true; 8866 } else { 8867 // Cast is of an lvalue, no need to change value. 8868 Result.setFrom(Info.Ctx, Value); 8869 return true; 8870 } 8871 } 8872 8873 case CK_ArrayToPointerDecay: { 8874 if (SubExpr->isGLValue()) { 8875 if (!evaluateLValue(SubExpr, Result)) 8876 return false; 8877 } else { 8878 APValue &Value = Info.CurrentCall->createTemporary( 8879 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8880 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8881 return false; 8882 } 8883 // The result is a pointer to the first element of the array. 8884 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8885 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8886 Result.addArray(Info, E, CAT); 8887 else 8888 Result.addUnsizedArray(Info, E, AT->getElementType()); 8889 return true; 8890 } 8891 8892 case CK_FunctionToPointerDecay: 8893 return evaluateLValue(SubExpr, Result); 8894 8895 case CK_LValueToRValue: { 8896 LValue LVal; 8897 if (!evaluateLValue(E->getSubExpr(), LVal)) 8898 return false; 8899 8900 APValue RVal; 8901 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8902 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8903 LVal, RVal)) 8904 return InvalidBaseOK && 8905 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8906 return Success(RVal, E); 8907 } 8908 } 8909 8910 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8911 } 8912 8913 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8914 UnaryExprOrTypeTrait ExprKind) { 8915 // C++ [expr.alignof]p3: 8916 // When alignof is applied to a reference type, the result is the 8917 // alignment of the referenced type. 8918 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8919 T = Ref->getPointeeType(); 8920 8921 if (T.getQualifiers().hasUnaligned()) 8922 return CharUnits::One(); 8923 8924 const bool AlignOfReturnsPreferred = 8925 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8926 8927 // __alignof is defined to return the preferred alignment. 8928 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8929 // as well. 8930 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8931 return Info.Ctx.toCharUnitsFromBits( 8932 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8933 // alignof and _Alignof are defined to return the ABI alignment. 8934 else if (ExprKind == UETT_AlignOf) 8935 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8936 else 8937 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8938 } 8939 8940 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8941 UnaryExprOrTypeTrait ExprKind) { 8942 E = E->IgnoreParens(); 8943 8944 // The kinds of expressions that we have special-case logic here for 8945 // should be kept up to date with the special checks for those 8946 // expressions in Sema. 8947 8948 // alignof decl is always accepted, even if it doesn't make sense: we default 8949 // to 1 in those cases. 8950 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8951 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8952 /*RefAsPointee*/true); 8953 8954 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8955 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8956 /*RefAsPointee*/true); 8957 8958 return GetAlignOfType(Info, E->getType(), ExprKind); 8959 } 8960 8961 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8962 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8963 return Info.Ctx.getDeclAlign(VD); 8964 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8965 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8966 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8967 } 8968 8969 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8970 /// __builtin_is_aligned and __builtin_assume_aligned. 8971 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8972 EvalInfo &Info, APSInt &Alignment) { 8973 if (!EvaluateInteger(E, Alignment, Info)) 8974 return false; 8975 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8976 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8977 return false; 8978 } 8979 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8980 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8981 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8982 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8983 << MaxValue << ForType << Alignment; 8984 return false; 8985 } 8986 // Ensure both alignment and source value have the same bit width so that we 8987 // don't assert when computing the resulting value. 8988 APSInt ExtAlignment = 8989 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8990 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8991 "Alignment should not be changed by ext/trunc"); 8992 Alignment = ExtAlignment; 8993 assert(Alignment.getBitWidth() == SrcWidth); 8994 return true; 8995 } 8996 8997 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8998 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8999 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 9000 return true; 9001 9002 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 9003 return false; 9004 9005 Result.setInvalid(E); 9006 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 9007 Result.addUnsizedArray(Info, E, PointeeTy); 9008 return true; 9009 } 9010 9011 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 9012 if (IsConstantCall(E)) 9013 return Success(E); 9014 9015 if (unsigned BuiltinOp = E->getBuiltinCallee()) 9016 return VisitBuiltinCallExpr(E, BuiltinOp); 9017 9018 return visitNonBuiltinCallExpr(E); 9019 } 9020 9021 // Determine if T is a character type for which we guarantee that 9022 // sizeof(T) == 1. 9023 static bool isOneByteCharacterType(QualType T) { 9024 return T->isCharType() || T->isChar8Type(); 9025 } 9026 9027 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9028 unsigned BuiltinOp) { 9029 switch (BuiltinOp) { 9030 case Builtin::BI__builtin_addressof: 9031 return evaluateLValue(E->getArg(0), Result); 9032 case Builtin::BI__builtin_assume_aligned: { 9033 // We need to be very careful here because: if the pointer does not have the 9034 // asserted alignment, then the behavior is undefined, and undefined 9035 // behavior is non-constant. 9036 if (!evaluatePointer(E->getArg(0), Result)) 9037 return false; 9038 9039 LValue OffsetResult(Result); 9040 APSInt Alignment; 9041 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9042 Alignment)) 9043 return false; 9044 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 9045 9046 if (E->getNumArgs() > 2) { 9047 APSInt Offset; 9048 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9049 return false; 9050 9051 int64_t AdditionalOffset = -Offset.getZExtValue(); 9052 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9053 } 9054 9055 // If there is a base object, then it must have the correct alignment. 9056 if (OffsetResult.Base) { 9057 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9058 9059 if (BaseAlignment < Align) { 9060 Result.Designator.setInvalid(); 9061 // FIXME: Add support to Diagnostic for long / long long. 9062 CCEDiag(E->getArg(0), 9063 diag::note_constexpr_baa_insufficient_alignment) << 0 9064 << (unsigned)BaseAlignment.getQuantity() 9065 << (unsigned)Align.getQuantity(); 9066 return false; 9067 } 9068 } 9069 9070 // The offset must also have the correct alignment. 9071 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9072 Result.Designator.setInvalid(); 9073 9074 (OffsetResult.Base 9075 ? CCEDiag(E->getArg(0), 9076 diag::note_constexpr_baa_insufficient_alignment) << 1 9077 : CCEDiag(E->getArg(0), 9078 diag::note_constexpr_baa_value_insufficient_alignment)) 9079 << (int)OffsetResult.Offset.getQuantity() 9080 << (unsigned)Align.getQuantity(); 9081 return false; 9082 } 9083 9084 return true; 9085 } 9086 case Builtin::BI__builtin_align_up: 9087 case Builtin::BI__builtin_align_down: { 9088 if (!evaluatePointer(E->getArg(0), Result)) 9089 return false; 9090 APSInt Alignment; 9091 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9092 Alignment)) 9093 return false; 9094 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9095 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9096 // For align_up/align_down, we can return the same value if the alignment 9097 // is known to be greater or equal to the requested value. 9098 if (PtrAlign.getQuantity() >= Alignment) 9099 return true; 9100 9101 // The alignment could be greater than the minimum at run-time, so we cannot 9102 // infer much about the resulting pointer value. One case is possible: 9103 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9104 // can infer the correct index if the requested alignment is smaller than 9105 // the base alignment so we can perform the computation on the offset. 9106 if (BaseAlignment.getQuantity() >= Alignment) { 9107 assert(Alignment.getBitWidth() <= 64 && 9108 "Cannot handle > 64-bit address-space"); 9109 uint64_t Alignment64 = Alignment.getZExtValue(); 9110 CharUnits NewOffset = CharUnits::fromQuantity( 9111 BuiltinOp == Builtin::BI__builtin_align_down 9112 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9113 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9114 Result.adjustOffset(NewOffset - Result.Offset); 9115 // TODO: diagnose out-of-bounds values/only allow for arrays? 9116 return true; 9117 } 9118 // Otherwise, we cannot constant-evaluate the result. 9119 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9120 << Alignment; 9121 return false; 9122 } 9123 case Builtin::BI__builtin_operator_new: 9124 return HandleOperatorNewCall(Info, E, Result); 9125 case Builtin::BI__builtin_launder: 9126 return evaluatePointer(E->getArg(0), Result); 9127 case Builtin::BIstrchr: 9128 case Builtin::BIwcschr: 9129 case Builtin::BImemchr: 9130 case Builtin::BIwmemchr: 9131 if (Info.getLangOpts().CPlusPlus11) 9132 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9133 << /*isConstexpr*/0 << /*isConstructor*/0 9134 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9135 else 9136 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9137 LLVM_FALLTHROUGH; 9138 case Builtin::BI__builtin_strchr: 9139 case Builtin::BI__builtin_wcschr: 9140 case Builtin::BI__builtin_memchr: 9141 case Builtin::BI__builtin_char_memchr: 9142 case Builtin::BI__builtin_wmemchr: { 9143 if (!Visit(E->getArg(0))) 9144 return false; 9145 APSInt Desired; 9146 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9147 return false; 9148 uint64_t MaxLength = uint64_t(-1); 9149 if (BuiltinOp != Builtin::BIstrchr && 9150 BuiltinOp != Builtin::BIwcschr && 9151 BuiltinOp != Builtin::BI__builtin_strchr && 9152 BuiltinOp != Builtin::BI__builtin_wcschr) { 9153 APSInt N; 9154 if (!EvaluateInteger(E->getArg(2), N, Info)) 9155 return false; 9156 MaxLength = N.getExtValue(); 9157 } 9158 // We cannot find the value if there are no candidates to match against. 9159 if (MaxLength == 0u) 9160 return ZeroInitialization(E); 9161 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9162 Result.Designator.Invalid) 9163 return false; 9164 QualType CharTy = Result.Designator.getType(Info.Ctx); 9165 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9166 BuiltinOp == Builtin::BI__builtin_memchr; 9167 assert(IsRawByte || 9168 Info.Ctx.hasSameUnqualifiedType( 9169 CharTy, E->getArg(0)->getType()->getPointeeType())); 9170 // Pointers to const void may point to objects of incomplete type. 9171 if (IsRawByte && CharTy->isIncompleteType()) { 9172 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9173 return false; 9174 } 9175 // Give up on byte-oriented matching against multibyte elements. 9176 // FIXME: We can compare the bytes in the correct order. 9177 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9178 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9179 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9180 << CharTy; 9181 return false; 9182 } 9183 // Figure out what value we're actually looking for (after converting to 9184 // the corresponding unsigned type if necessary). 9185 uint64_t DesiredVal; 9186 bool StopAtNull = false; 9187 switch (BuiltinOp) { 9188 case Builtin::BIstrchr: 9189 case Builtin::BI__builtin_strchr: 9190 // strchr compares directly to the passed integer, and therefore 9191 // always fails if given an int that is not a char. 9192 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9193 E->getArg(1)->getType(), 9194 Desired), 9195 Desired)) 9196 return ZeroInitialization(E); 9197 StopAtNull = true; 9198 LLVM_FALLTHROUGH; 9199 case Builtin::BImemchr: 9200 case Builtin::BI__builtin_memchr: 9201 case Builtin::BI__builtin_char_memchr: 9202 // memchr compares by converting both sides to unsigned char. That's also 9203 // correct for strchr if we get this far (to cope with plain char being 9204 // unsigned in the strchr case). 9205 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9206 break; 9207 9208 case Builtin::BIwcschr: 9209 case Builtin::BI__builtin_wcschr: 9210 StopAtNull = true; 9211 LLVM_FALLTHROUGH; 9212 case Builtin::BIwmemchr: 9213 case Builtin::BI__builtin_wmemchr: 9214 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9215 DesiredVal = Desired.getZExtValue(); 9216 break; 9217 } 9218 9219 for (; MaxLength; --MaxLength) { 9220 APValue Char; 9221 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9222 !Char.isInt()) 9223 return false; 9224 if (Char.getInt().getZExtValue() == DesiredVal) 9225 return true; 9226 if (StopAtNull && !Char.getInt()) 9227 break; 9228 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9229 return false; 9230 } 9231 // Not found: return nullptr. 9232 return ZeroInitialization(E); 9233 } 9234 9235 case Builtin::BImemcpy: 9236 case Builtin::BImemmove: 9237 case Builtin::BIwmemcpy: 9238 case Builtin::BIwmemmove: 9239 if (Info.getLangOpts().CPlusPlus11) 9240 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9241 << /*isConstexpr*/0 << /*isConstructor*/0 9242 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9243 else 9244 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9245 LLVM_FALLTHROUGH; 9246 case Builtin::BI__builtin_memcpy: 9247 case Builtin::BI__builtin_memmove: 9248 case Builtin::BI__builtin_wmemcpy: 9249 case Builtin::BI__builtin_wmemmove: { 9250 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9251 BuiltinOp == Builtin::BIwmemmove || 9252 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9253 BuiltinOp == Builtin::BI__builtin_wmemmove; 9254 bool Move = BuiltinOp == Builtin::BImemmove || 9255 BuiltinOp == Builtin::BIwmemmove || 9256 BuiltinOp == Builtin::BI__builtin_memmove || 9257 BuiltinOp == Builtin::BI__builtin_wmemmove; 9258 9259 // The result of mem* is the first argument. 9260 if (!Visit(E->getArg(0))) 9261 return false; 9262 LValue Dest = Result; 9263 9264 LValue Src; 9265 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9266 return false; 9267 9268 APSInt N; 9269 if (!EvaluateInteger(E->getArg(2), N, Info)) 9270 return false; 9271 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9272 9273 // If the size is zero, we treat this as always being a valid no-op. 9274 // (Even if one of the src and dest pointers is null.) 9275 if (!N) 9276 return true; 9277 9278 // Otherwise, if either of the operands is null, we can't proceed. Don't 9279 // try to determine the type of the copied objects, because there aren't 9280 // any. 9281 if (!Src.Base || !Dest.Base) { 9282 APValue Val; 9283 (!Src.Base ? Src : Dest).moveInto(Val); 9284 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9285 << Move << WChar << !!Src.Base 9286 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9287 return false; 9288 } 9289 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9290 return false; 9291 9292 // We require that Src and Dest are both pointers to arrays of 9293 // trivially-copyable type. (For the wide version, the designator will be 9294 // invalid if the designated object is not a wchar_t.) 9295 QualType T = Dest.Designator.getType(Info.Ctx); 9296 QualType SrcT = Src.Designator.getType(Info.Ctx); 9297 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9298 // FIXME: Consider using our bit_cast implementation to support this. 9299 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9300 return false; 9301 } 9302 if (T->isIncompleteType()) { 9303 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9304 return false; 9305 } 9306 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9307 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9308 return false; 9309 } 9310 9311 // Figure out how many T's we're copying. 9312 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9313 if (!WChar) { 9314 uint64_t Remainder; 9315 llvm::APInt OrigN = N; 9316 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9317 if (Remainder) { 9318 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9319 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9320 << (unsigned)TSize; 9321 return false; 9322 } 9323 } 9324 9325 // Check that the copying will remain within the arrays, just so that we 9326 // can give a more meaningful diagnostic. This implicitly also checks that 9327 // N fits into 64 bits. 9328 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9329 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9330 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9331 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9332 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9333 << toString(N, 10, /*Signed*/false); 9334 return false; 9335 } 9336 uint64_t NElems = N.getZExtValue(); 9337 uint64_t NBytes = NElems * TSize; 9338 9339 // Check for overlap. 9340 int Direction = 1; 9341 if (HasSameBase(Src, Dest)) { 9342 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9343 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9344 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9345 // Dest is inside the source region. 9346 if (!Move) { 9347 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9348 return false; 9349 } 9350 // For memmove and friends, copy backwards. 9351 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9352 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9353 return false; 9354 Direction = -1; 9355 } else if (!Move && SrcOffset >= DestOffset && 9356 SrcOffset - DestOffset < NBytes) { 9357 // Src is inside the destination region for memcpy: invalid. 9358 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9359 return false; 9360 } 9361 } 9362 9363 while (true) { 9364 APValue Val; 9365 // FIXME: Set WantObjectRepresentation to true if we're copying a 9366 // char-like type? 9367 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9368 !handleAssignment(Info, E, Dest, T, Val)) 9369 return false; 9370 // Do not iterate past the last element; if we're copying backwards, that 9371 // might take us off the start of the array. 9372 if (--NElems == 0) 9373 return true; 9374 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9375 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9376 return false; 9377 } 9378 } 9379 9380 default: 9381 break; 9382 } 9383 9384 return visitNonBuiltinCallExpr(E); 9385 } 9386 9387 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9388 APValue &Result, const InitListExpr *ILE, 9389 QualType AllocType); 9390 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9391 APValue &Result, 9392 const CXXConstructExpr *CCE, 9393 QualType AllocType); 9394 9395 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9396 if (!Info.getLangOpts().CPlusPlus20) 9397 Info.CCEDiag(E, diag::note_constexpr_new); 9398 9399 // We cannot speculatively evaluate a delete expression. 9400 if (Info.SpeculativeEvaluationDepth) 9401 return false; 9402 9403 FunctionDecl *OperatorNew = E->getOperatorNew(); 9404 9405 bool IsNothrow = false; 9406 bool IsPlacement = false; 9407 if (OperatorNew->isReservedGlobalPlacementOperator() && 9408 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9409 // FIXME Support array placement new. 9410 assert(E->getNumPlacementArgs() == 1); 9411 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9412 return false; 9413 if (Result.Designator.Invalid) 9414 return false; 9415 IsPlacement = true; 9416 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9417 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9418 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9419 return false; 9420 } else if (E->getNumPlacementArgs()) { 9421 // The only new-placement list we support is of the form (std::nothrow). 9422 // 9423 // FIXME: There is no restriction on this, but it's not clear that any 9424 // other form makes any sense. We get here for cases such as: 9425 // 9426 // new (std::align_val_t{N}) X(int) 9427 // 9428 // (which should presumably be valid only if N is a multiple of 9429 // alignof(int), and in any case can't be deallocated unless N is 9430 // alignof(X) and X has new-extended alignment). 9431 if (E->getNumPlacementArgs() != 1 || 9432 !E->getPlacementArg(0)->getType()->isNothrowT()) 9433 return Error(E, diag::note_constexpr_new_placement); 9434 9435 LValue Nothrow; 9436 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9437 return false; 9438 IsNothrow = true; 9439 } 9440 9441 const Expr *Init = E->getInitializer(); 9442 const InitListExpr *ResizedArrayILE = nullptr; 9443 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9444 bool ValueInit = false; 9445 9446 QualType AllocType = E->getAllocatedType(); 9447 if (Optional<const Expr *> ArraySize = E->getArraySize()) { 9448 const Expr *Stripped = *ArraySize; 9449 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9450 Stripped = ICE->getSubExpr()) 9451 if (ICE->getCastKind() != CK_NoOp && 9452 ICE->getCastKind() != CK_IntegralCast) 9453 break; 9454 9455 llvm::APSInt ArrayBound; 9456 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9457 return false; 9458 9459 // C++ [expr.new]p9: 9460 // The expression is erroneous if: 9461 // -- [...] its value before converting to size_t [or] applying the 9462 // second standard conversion sequence is less than zero 9463 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9464 if (IsNothrow) 9465 return ZeroInitialization(E); 9466 9467 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9468 << ArrayBound << (*ArraySize)->getSourceRange(); 9469 return false; 9470 } 9471 9472 // -- its value is such that the size of the allocated object would 9473 // exceed the implementation-defined limit 9474 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9475 ArrayBound) > 9476 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9477 if (IsNothrow) 9478 return ZeroInitialization(E); 9479 9480 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9481 << ArrayBound << (*ArraySize)->getSourceRange(); 9482 return false; 9483 } 9484 9485 // -- the new-initializer is a braced-init-list and the number of 9486 // array elements for which initializers are provided [...] 9487 // exceeds the number of elements to initialize 9488 if (!Init) { 9489 // No initialization is performed. 9490 } else if (isa<CXXScalarValueInitExpr>(Init) || 9491 isa<ImplicitValueInitExpr>(Init)) { 9492 ValueInit = true; 9493 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9494 ResizedArrayCCE = CCE; 9495 } else { 9496 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9497 assert(CAT && "unexpected type for array initializer"); 9498 9499 unsigned Bits = 9500 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9501 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9502 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9503 if (InitBound.ugt(AllocBound)) { 9504 if (IsNothrow) 9505 return ZeroInitialization(E); 9506 9507 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9508 << toString(AllocBound, 10, /*Signed=*/false) 9509 << toString(InitBound, 10, /*Signed=*/false) 9510 << (*ArraySize)->getSourceRange(); 9511 return false; 9512 } 9513 9514 // If the sizes differ, we must have an initializer list, and we need 9515 // special handling for this case when we initialize. 9516 if (InitBound != AllocBound) 9517 ResizedArrayILE = cast<InitListExpr>(Init); 9518 } 9519 9520 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9521 ArrayType::Normal, 0); 9522 } else { 9523 assert(!AllocType->isArrayType() && 9524 "array allocation with non-array new"); 9525 } 9526 9527 APValue *Val; 9528 if (IsPlacement) { 9529 AccessKinds AK = AK_Construct; 9530 struct FindObjectHandler { 9531 EvalInfo &Info; 9532 const Expr *E; 9533 QualType AllocType; 9534 const AccessKinds AccessKind; 9535 APValue *Value; 9536 9537 typedef bool result_type; 9538 bool failed() { return false; } 9539 bool found(APValue &Subobj, QualType SubobjType) { 9540 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9541 // old name of the object to be used to name the new object. 9542 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9543 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9544 SubobjType << AllocType; 9545 return false; 9546 } 9547 Value = &Subobj; 9548 return true; 9549 } 9550 bool found(APSInt &Value, QualType SubobjType) { 9551 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9552 return false; 9553 } 9554 bool found(APFloat &Value, QualType SubobjType) { 9555 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9556 return false; 9557 } 9558 } Handler = {Info, E, AllocType, AK, nullptr}; 9559 9560 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9561 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9562 return false; 9563 9564 Val = Handler.Value; 9565 9566 // [basic.life]p1: 9567 // The lifetime of an object o of type T ends when [...] the storage 9568 // which the object occupies is [...] reused by an object that is not 9569 // nested within o (6.6.2). 9570 *Val = APValue(); 9571 } else { 9572 // Perform the allocation and obtain a pointer to the resulting object. 9573 Val = Info.createHeapAlloc(E, AllocType, Result); 9574 if (!Val) 9575 return false; 9576 } 9577 9578 if (ValueInit) { 9579 ImplicitValueInitExpr VIE(AllocType); 9580 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9581 return false; 9582 } else if (ResizedArrayILE) { 9583 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9584 AllocType)) 9585 return false; 9586 } else if (ResizedArrayCCE) { 9587 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9588 AllocType)) 9589 return false; 9590 } else if (Init) { 9591 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9592 return false; 9593 } else if (!getDefaultInitValue(AllocType, *Val)) { 9594 return false; 9595 } 9596 9597 // Array new returns a pointer to the first element, not a pointer to the 9598 // array. 9599 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9600 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9601 9602 return true; 9603 } 9604 //===----------------------------------------------------------------------===// 9605 // Member Pointer Evaluation 9606 //===----------------------------------------------------------------------===// 9607 9608 namespace { 9609 class MemberPointerExprEvaluator 9610 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9611 MemberPtr &Result; 9612 9613 bool Success(const ValueDecl *D) { 9614 Result = MemberPtr(D); 9615 return true; 9616 } 9617 public: 9618 9619 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9620 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9621 9622 bool Success(const APValue &V, const Expr *E) { 9623 Result.setFrom(V); 9624 return true; 9625 } 9626 bool ZeroInitialization(const Expr *E) { 9627 return Success((const ValueDecl*)nullptr); 9628 } 9629 9630 bool VisitCastExpr(const CastExpr *E); 9631 bool VisitUnaryAddrOf(const UnaryOperator *E); 9632 }; 9633 } // end anonymous namespace 9634 9635 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9636 EvalInfo &Info) { 9637 assert(!E->isValueDependent()); 9638 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9639 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9640 } 9641 9642 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9643 switch (E->getCastKind()) { 9644 default: 9645 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9646 9647 case CK_NullToMemberPointer: 9648 VisitIgnoredValue(E->getSubExpr()); 9649 return ZeroInitialization(E); 9650 9651 case CK_BaseToDerivedMemberPointer: { 9652 if (!Visit(E->getSubExpr())) 9653 return false; 9654 if (E->path_empty()) 9655 return true; 9656 // Base-to-derived member pointer casts store the path in derived-to-base 9657 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9658 // the wrong end of the derived->base arc, so stagger the path by one class. 9659 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9660 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9661 PathI != PathE; ++PathI) { 9662 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9663 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9664 if (!Result.castToDerived(Derived)) 9665 return Error(E); 9666 } 9667 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9668 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9669 return Error(E); 9670 return true; 9671 } 9672 9673 case CK_DerivedToBaseMemberPointer: 9674 if (!Visit(E->getSubExpr())) 9675 return false; 9676 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9677 PathE = E->path_end(); PathI != PathE; ++PathI) { 9678 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9679 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9680 if (!Result.castToBase(Base)) 9681 return Error(E); 9682 } 9683 return true; 9684 } 9685 } 9686 9687 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9688 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9689 // member can be formed. 9690 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9691 } 9692 9693 //===----------------------------------------------------------------------===// 9694 // Record Evaluation 9695 //===----------------------------------------------------------------------===// 9696 9697 namespace { 9698 class RecordExprEvaluator 9699 : public ExprEvaluatorBase<RecordExprEvaluator> { 9700 const LValue &This; 9701 APValue &Result; 9702 public: 9703 9704 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9705 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9706 9707 bool Success(const APValue &V, const Expr *E) { 9708 Result = V; 9709 return true; 9710 } 9711 bool ZeroInitialization(const Expr *E) { 9712 return ZeroInitialization(E, E->getType()); 9713 } 9714 bool ZeroInitialization(const Expr *E, QualType T); 9715 9716 bool VisitCallExpr(const CallExpr *E) { 9717 return handleCallExpr(E, Result, &This); 9718 } 9719 bool VisitCastExpr(const CastExpr *E); 9720 bool VisitInitListExpr(const InitListExpr *E); 9721 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9722 return VisitCXXConstructExpr(E, E->getType()); 9723 } 9724 bool VisitLambdaExpr(const LambdaExpr *E); 9725 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9726 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9727 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9728 bool VisitBinCmp(const BinaryOperator *E); 9729 }; 9730 } 9731 9732 /// Perform zero-initialization on an object of non-union class type. 9733 /// C++11 [dcl.init]p5: 9734 /// To zero-initialize an object or reference of type T means: 9735 /// [...] 9736 /// -- if T is a (possibly cv-qualified) non-union class type, 9737 /// each non-static data member and each base-class subobject is 9738 /// zero-initialized 9739 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9740 const RecordDecl *RD, 9741 const LValue &This, APValue &Result) { 9742 assert(!RD->isUnion() && "Expected non-union class type"); 9743 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9744 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9745 std::distance(RD->field_begin(), RD->field_end())); 9746 9747 if (RD->isInvalidDecl()) return false; 9748 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9749 9750 if (CD) { 9751 unsigned Index = 0; 9752 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9753 End = CD->bases_end(); I != End; ++I, ++Index) { 9754 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9755 LValue Subobject = This; 9756 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9757 return false; 9758 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9759 Result.getStructBase(Index))) 9760 return false; 9761 } 9762 } 9763 9764 for (const auto *I : RD->fields()) { 9765 // -- if T is a reference type, no initialization is performed. 9766 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9767 continue; 9768 9769 LValue Subobject = This; 9770 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9771 return false; 9772 9773 ImplicitValueInitExpr VIE(I->getType()); 9774 if (!EvaluateInPlace( 9775 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9776 return false; 9777 } 9778 9779 return true; 9780 } 9781 9782 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9783 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9784 if (RD->isInvalidDecl()) return false; 9785 if (RD->isUnion()) { 9786 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9787 // object's first non-static named data member is zero-initialized 9788 RecordDecl::field_iterator I = RD->field_begin(); 9789 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9790 ++I; 9791 if (I == RD->field_end()) { 9792 Result = APValue((const FieldDecl*)nullptr); 9793 return true; 9794 } 9795 9796 LValue Subobject = This; 9797 if (!HandleLValueMember(Info, E, Subobject, *I)) 9798 return false; 9799 Result = APValue(*I); 9800 ImplicitValueInitExpr VIE(I->getType()); 9801 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9802 } 9803 9804 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9805 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9806 return false; 9807 } 9808 9809 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9810 } 9811 9812 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9813 switch (E->getCastKind()) { 9814 default: 9815 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9816 9817 case CK_ConstructorConversion: 9818 return Visit(E->getSubExpr()); 9819 9820 case CK_DerivedToBase: 9821 case CK_UncheckedDerivedToBase: { 9822 APValue DerivedObject; 9823 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9824 return false; 9825 if (!DerivedObject.isStruct()) 9826 return Error(E->getSubExpr()); 9827 9828 // Derived-to-base rvalue conversion: just slice off the derived part. 9829 APValue *Value = &DerivedObject; 9830 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9831 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9832 PathE = E->path_end(); PathI != PathE; ++PathI) { 9833 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9834 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9835 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9836 RD = Base; 9837 } 9838 Result = *Value; 9839 return true; 9840 } 9841 } 9842 } 9843 9844 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9845 if (E->isTransparent()) 9846 return Visit(E->getInit(0)); 9847 9848 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9849 if (RD->isInvalidDecl()) return false; 9850 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9851 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9852 9853 EvalInfo::EvaluatingConstructorRAII EvalObj( 9854 Info, 9855 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9856 CXXRD && CXXRD->getNumBases()); 9857 9858 if (RD->isUnion()) { 9859 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9860 Result = APValue(Field); 9861 if (!Field) 9862 return true; 9863 9864 // If the initializer list for a union does not contain any elements, the 9865 // first element of the union is value-initialized. 9866 // FIXME: The element should be initialized from an initializer list. 9867 // Is this difference ever observable for initializer lists which 9868 // we don't build? 9869 ImplicitValueInitExpr VIE(Field->getType()); 9870 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9871 9872 LValue Subobject = This; 9873 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9874 return false; 9875 9876 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9877 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9878 isa<CXXDefaultInitExpr>(InitExpr)); 9879 9880 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9881 if (Field->isBitField()) 9882 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9883 Field); 9884 return true; 9885 } 9886 9887 return false; 9888 } 9889 9890 if (!Result.hasValue()) 9891 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9892 std::distance(RD->field_begin(), RD->field_end())); 9893 unsigned ElementNo = 0; 9894 bool Success = true; 9895 9896 // Initialize base classes. 9897 if (CXXRD && CXXRD->getNumBases()) { 9898 for (const auto &Base : CXXRD->bases()) { 9899 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9900 const Expr *Init = E->getInit(ElementNo); 9901 9902 LValue Subobject = This; 9903 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9904 return false; 9905 9906 APValue &FieldVal = Result.getStructBase(ElementNo); 9907 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9908 if (!Info.noteFailure()) 9909 return false; 9910 Success = false; 9911 } 9912 ++ElementNo; 9913 } 9914 9915 EvalObj.finishedConstructingBases(); 9916 } 9917 9918 // Initialize members. 9919 for (const auto *Field : RD->fields()) { 9920 // Anonymous bit-fields are not considered members of the class for 9921 // purposes of aggregate initialization. 9922 if (Field->isUnnamedBitfield()) 9923 continue; 9924 9925 LValue Subobject = This; 9926 9927 bool HaveInit = ElementNo < E->getNumInits(); 9928 9929 // FIXME: Diagnostics here should point to the end of the initializer 9930 // list, not the start. 9931 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9932 Subobject, Field, &Layout)) 9933 return false; 9934 9935 // Perform an implicit value-initialization for members beyond the end of 9936 // the initializer list. 9937 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9938 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9939 9940 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9941 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9942 isa<CXXDefaultInitExpr>(Init)); 9943 9944 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9945 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9946 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9947 FieldVal, Field))) { 9948 if (!Info.noteFailure()) 9949 return false; 9950 Success = false; 9951 } 9952 } 9953 9954 EvalObj.finishedConstructingFields(); 9955 9956 return Success; 9957 } 9958 9959 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9960 QualType T) { 9961 // Note that E's type is not necessarily the type of our class here; we might 9962 // be initializing an array element instead. 9963 const CXXConstructorDecl *FD = E->getConstructor(); 9964 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9965 9966 bool ZeroInit = E->requiresZeroInitialization(); 9967 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9968 // If we've already performed zero-initialization, we're already done. 9969 if (Result.hasValue()) 9970 return true; 9971 9972 if (ZeroInit) 9973 return ZeroInitialization(E, T); 9974 9975 return getDefaultInitValue(T, Result); 9976 } 9977 9978 const FunctionDecl *Definition = nullptr; 9979 auto Body = FD->getBody(Definition); 9980 9981 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9982 return false; 9983 9984 // Avoid materializing a temporary for an elidable copy/move constructor. 9985 if (E->isElidable() && !ZeroInit) { 9986 // FIXME: This only handles the simplest case, where the source object 9987 // is passed directly as the first argument to the constructor. 9988 // This should also handle stepping though implicit casts and 9989 // and conversion sequences which involve two steps, with a 9990 // conversion operator followed by a converting constructor. 9991 const Expr *SrcObj = E->getArg(0); 9992 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 9993 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 9994 if (const MaterializeTemporaryExpr *ME = 9995 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 9996 return Visit(ME->getSubExpr()); 9997 } 9998 9999 if (ZeroInit && !ZeroInitialization(E, T)) 10000 return false; 10001 10002 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 10003 return HandleConstructorCall(E, This, Args, 10004 cast<CXXConstructorDecl>(Definition), Info, 10005 Result); 10006 } 10007 10008 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 10009 const CXXInheritedCtorInitExpr *E) { 10010 if (!Info.CurrentCall) { 10011 assert(Info.checkingPotentialConstantExpression()); 10012 return false; 10013 } 10014 10015 const CXXConstructorDecl *FD = E->getConstructor(); 10016 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 10017 return false; 10018 10019 const FunctionDecl *Definition = nullptr; 10020 auto Body = FD->getBody(Definition); 10021 10022 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10023 return false; 10024 10025 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 10026 cast<CXXConstructorDecl>(Definition), Info, 10027 Result); 10028 } 10029 10030 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 10031 const CXXStdInitializerListExpr *E) { 10032 const ConstantArrayType *ArrayType = 10033 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 10034 10035 LValue Array; 10036 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 10037 return false; 10038 10039 // Get a pointer to the first element of the array. 10040 Array.addArray(Info, E, ArrayType); 10041 10042 auto InvalidType = [&] { 10043 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 10044 << E->getType(); 10045 return false; 10046 }; 10047 10048 // FIXME: Perform the checks on the field types in SemaInit. 10049 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10050 RecordDecl::field_iterator Field = Record->field_begin(); 10051 if (Field == Record->field_end()) 10052 return InvalidType(); 10053 10054 // Start pointer. 10055 if (!Field->getType()->isPointerType() || 10056 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10057 ArrayType->getElementType())) 10058 return InvalidType(); 10059 10060 // FIXME: What if the initializer_list type has base classes, etc? 10061 Result = APValue(APValue::UninitStruct(), 0, 2); 10062 Array.moveInto(Result.getStructField(0)); 10063 10064 if (++Field == Record->field_end()) 10065 return InvalidType(); 10066 10067 if (Field->getType()->isPointerType() && 10068 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10069 ArrayType->getElementType())) { 10070 // End pointer. 10071 if (!HandleLValueArrayAdjustment(Info, E, Array, 10072 ArrayType->getElementType(), 10073 ArrayType->getSize().getZExtValue())) 10074 return false; 10075 Array.moveInto(Result.getStructField(1)); 10076 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10077 // Length. 10078 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10079 else 10080 return InvalidType(); 10081 10082 if (++Field != Record->field_end()) 10083 return InvalidType(); 10084 10085 return true; 10086 } 10087 10088 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10089 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10090 if (ClosureClass->isInvalidDecl()) 10091 return false; 10092 10093 const size_t NumFields = 10094 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10095 10096 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10097 E->capture_init_end()) && 10098 "The number of lambda capture initializers should equal the number of " 10099 "fields within the closure type"); 10100 10101 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10102 // Iterate through all the lambda's closure object's fields and initialize 10103 // them. 10104 auto *CaptureInitIt = E->capture_init_begin(); 10105 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10106 bool Success = true; 10107 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10108 for (const auto *Field : ClosureClass->fields()) { 10109 assert(CaptureInitIt != E->capture_init_end()); 10110 // Get the initializer for this field 10111 Expr *const CurFieldInit = *CaptureInitIt++; 10112 10113 // If there is no initializer, either this is a VLA or an error has 10114 // occurred. 10115 if (!CurFieldInit) 10116 return Error(E); 10117 10118 LValue Subobject = This; 10119 10120 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10121 return false; 10122 10123 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10124 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10125 if (!Info.keepEvaluatingAfterFailure()) 10126 return false; 10127 Success = false; 10128 } 10129 ++CaptureIt; 10130 } 10131 return Success; 10132 } 10133 10134 static bool EvaluateRecord(const Expr *E, const LValue &This, 10135 APValue &Result, EvalInfo &Info) { 10136 assert(!E->isValueDependent()); 10137 assert(E->isPRValue() && E->getType()->isRecordType() && 10138 "can't evaluate expression as a record rvalue"); 10139 return RecordExprEvaluator(Info, This, Result).Visit(E); 10140 } 10141 10142 //===----------------------------------------------------------------------===// 10143 // Temporary Evaluation 10144 // 10145 // Temporaries are represented in the AST as rvalues, but generally behave like 10146 // lvalues. The full-object of which the temporary is a subobject is implicitly 10147 // materialized so that a reference can bind to it. 10148 //===----------------------------------------------------------------------===// 10149 namespace { 10150 class TemporaryExprEvaluator 10151 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10152 public: 10153 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10154 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10155 10156 /// Visit an expression which constructs the value of this temporary. 10157 bool VisitConstructExpr(const Expr *E) { 10158 APValue &Value = Info.CurrentCall->createTemporary( 10159 E, E->getType(), ScopeKind::FullExpression, Result); 10160 return EvaluateInPlace(Value, Info, Result, E); 10161 } 10162 10163 bool VisitCastExpr(const CastExpr *E) { 10164 switch (E->getCastKind()) { 10165 default: 10166 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10167 10168 case CK_ConstructorConversion: 10169 return VisitConstructExpr(E->getSubExpr()); 10170 } 10171 } 10172 bool VisitInitListExpr(const InitListExpr *E) { 10173 return VisitConstructExpr(E); 10174 } 10175 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10176 return VisitConstructExpr(E); 10177 } 10178 bool VisitCallExpr(const CallExpr *E) { 10179 return VisitConstructExpr(E); 10180 } 10181 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10182 return VisitConstructExpr(E); 10183 } 10184 bool VisitLambdaExpr(const LambdaExpr *E) { 10185 return VisitConstructExpr(E); 10186 } 10187 }; 10188 } // end anonymous namespace 10189 10190 /// Evaluate an expression of record type as a temporary. 10191 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10192 assert(!E->isValueDependent()); 10193 assert(E->isPRValue() && E->getType()->isRecordType()); 10194 return TemporaryExprEvaluator(Info, Result).Visit(E); 10195 } 10196 10197 //===----------------------------------------------------------------------===// 10198 // Vector Evaluation 10199 //===----------------------------------------------------------------------===// 10200 10201 namespace { 10202 class VectorExprEvaluator 10203 : public ExprEvaluatorBase<VectorExprEvaluator> { 10204 APValue &Result; 10205 public: 10206 10207 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10208 : ExprEvaluatorBaseTy(info), Result(Result) {} 10209 10210 bool Success(ArrayRef<APValue> V, const Expr *E) { 10211 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10212 // FIXME: remove this APValue copy. 10213 Result = APValue(V.data(), V.size()); 10214 return true; 10215 } 10216 bool Success(const APValue &V, const Expr *E) { 10217 assert(V.isVector()); 10218 Result = V; 10219 return true; 10220 } 10221 bool ZeroInitialization(const Expr *E); 10222 10223 bool VisitUnaryReal(const UnaryOperator *E) 10224 { return Visit(E->getSubExpr()); } 10225 bool VisitCastExpr(const CastExpr* E); 10226 bool VisitInitListExpr(const InitListExpr *E); 10227 bool VisitUnaryImag(const UnaryOperator *E); 10228 bool VisitBinaryOperator(const BinaryOperator *E); 10229 bool VisitUnaryOperator(const UnaryOperator *E); 10230 // FIXME: Missing: conditional operator (for GNU 10231 // conditional select), shufflevector, ExtVectorElementExpr 10232 }; 10233 } // end anonymous namespace 10234 10235 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10236 assert(E->isPRValue() && E->getType()->isVectorType() && 10237 "not a vector prvalue"); 10238 return VectorExprEvaluator(Info, Result).Visit(E); 10239 } 10240 10241 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10242 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10243 unsigned NElts = VTy->getNumElements(); 10244 10245 const Expr *SE = E->getSubExpr(); 10246 QualType SETy = SE->getType(); 10247 10248 switch (E->getCastKind()) { 10249 case CK_VectorSplat: { 10250 APValue Val = APValue(); 10251 if (SETy->isIntegerType()) { 10252 APSInt IntResult; 10253 if (!EvaluateInteger(SE, IntResult, Info)) 10254 return false; 10255 Val = APValue(std::move(IntResult)); 10256 } else if (SETy->isRealFloatingType()) { 10257 APFloat FloatResult(0.0); 10258 if (!EvaluateFloat(SE, FloatResult, Info)) 10259 return false; 10260 Val = APValue(std::move(FloatResult)); 10261 } else { 10262 return Error(E); 10263 } 10264 10265 // Splat and create vector APValue. 10266 SmallVector<APValue, 4> Elts(NElts, Val); 10267 return Success(Elts, E); 10268 } 10269 case CK_BitCast: { 10270 // Evaluate the operand into an APInt we can extract from. 10271 llvm::APInt SValInt; 10272 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10273 return false; 10274 // Extract the elements 10275 QualType EltTy = VTy->getElementType(); 10276 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10277 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10278 SmallVector<APValue, 4> Elts; 10279 if (EltTy->isRealFloatingType()) { 10280 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10281 unsigned FloatEltSize = EltSize; 10282 if (&Sem == &APFloat::x87DoubleExtended()) 10283 FloatEltSize = 80; 10284 for (unsigned i = 0; i < NElts; i++) { 10285 llvm::APInt Elt; 10286 if (BigEndian) 10287 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10288 else 10289 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10290 Elts.push_back(APValue(APFloat(Sem, Elt))); 10291 } 10292 } else if (EltTy->isIntegerType()) { 10293 for (unsigned i = 0; i < NElts; i++) { 10294 llvm::APInt Elt; 10295 if (BigEndian) 10296 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10297 else 10298 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10299 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10300 } 10301 } else { 10302 return Error(E); 10303 } 10304 return Success(Elts, E); 10305 } 10306 default: 10307 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10308 } 10309 } 10310 10311 bool 10312 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10313 const VectorType *VT = E->getType()->castAs<VectorType>(); 10314 unsigned NumInits = E->getNumInits(); 10315 unsigned NumElements = VT->getNumElements(); 10316 10317 QualType EltTy = VT->getElementType(); 10318 SmallVector<APValue, 4> Elements; 10319 10320 // The number of initializers can be less than the number of 10321 // vector elements. For OpenCL, this can be due to nested vector 10322 // initialization. For GCC compatibility, missing trailing elements 10323 // should be initialized with zeroes. 10324 unsigned CountInits = 0, CountElts = 0; 10325 while (CountElts < NumElements) { 10326 // Handle nested vector initialization. 10327 if (CountInits < NumInits 10328 && E->getInit(CountInits)->getType()->isVectorType()) { 10329 APValue v; 10330 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10331 return Error(E); 10332 unsigned vlen = v.getVectorLength(); 10333 for (unsigned j = 0; j < vlen; j++) 10334 Elements.push_back(v.getVectorElt(j)); 10335 CountElts += vlen; 10336 } else if (EltTy->isIntegerType()) { 10337 llvm::APSInt sInt(32); 10338 if (CountInits < NumInits) { 10339 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10340 return false; 10341 } else // trailing integer zero. 10342 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10343 Elements.push_back(APValue(sInt)); 10344 CountElts++; 10345 } else { 10346 llvm::APFloat f(0.0); 10347 if (CountInits < NumInits) { 10348 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10349 return false; 10350 } else // trailing float zero. 10351 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10352 Elements.push_back(APValue(f)); 10353 CountElts++; 10354 } 10355 CountInits++; 10356 } 10357 return Success(Elements, E); 10358 } 10359 10360 bool 10361 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10362 const auto *VT = E->getType()->castAs<VectorType>(); 10363 QualType EltTy = VT->getElementType(); 10364 APValue ZeroElement; 10365 if (EltTy->isIntegerType()) 10366 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10367 else 10368 ZeroElement = 10369 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10370 10371 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10372 return Success(Elements, E); 10373 } 10374 10375 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10376 VisitIgnoredValue(E->getSubExpr()); 10377 return ZeroInitialization(E); 10378 } 10379 10380 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10381 BinaryOperatorKind Op = E->getOpcode(); 10382 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10383 "Operation not supported on vector types"); 10384 10385 if (Op == BO_Comma) 10386 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10387 10388 Expr *LHS = E->getLHS(); 10389 Expr *RHS = E->getRHS(); 10390 10391 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10392 "Must both be vector types"); 10393 // Checking JUST the types are the same would be fine, except shifts don't 10394 // need to have their types be the same (since you always shift by an int). 10395 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10396 E->getType()->castAs<VectorType>()->getNumElements() && 10397 RHS->getType()->castAs<VectorType>()->getNumElements() == 10398 E->getType()->castAs<VectorType>()->getNumElements() && 10399 "All operands must be the same size."); 10400 10401 APValue LHSValue; 10402 APValue RHSValue; 10403 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10404 if (!LHSOK && !Info.noteFailure()) 10405 return false; 10406 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10407 return false; 10408 10409 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10410 return false; 10411 10412 return Success(LHSValue, E); 10413 } 10414 10415 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, 10416 QualType ResultTy, 10417 UnaryOperatorKind Op, 10418 APValue Elt) { 10419 switch (Op) { 10420 case UO_Plus: 10421 // Nothing to do here. 10422 return Elt; 10423 case UO_Minus: 10424 if (Elt.getKind() == APValue::Int) { 10425 Elt.getInt().negate(); 10426 } else { 10427 assert(Elt.getKind() == APValue::Float && 10428 "Vector can only be int or float type"); 10429 Elt.getFloat().changeSign(); 10430 } 10431 return Elt; 10432 case UO_Not: 10433 // This is only valid for integral types anyway, so we don't have to handle 10434 // float here. 10435 assert(Elt.getKind() == APValue::Int && 10436 "Vector operator ~ can only be int"); 10437 Elt.getInt().flipAllBits(); 10438 return Elt; 10439 case UO_LNot: { 10440 if (Elt.getKind() == APValue::Int) { 10441 Elt.getInt() = !Elt.getInt(); 10442 // operator ! on vectors returns -1 for 'truth', so negate it. 10443 Elt.getInt().negate(); 10444 return Elt; 10445 } 10446 assert(Elt.getKind() == APValue::Float && 10447 "Vector can only be int or float type"); 10448 // Float types result in an int of the same size, but -1 for true, or 0 for 10449 // false. 10450 APSInt EltResult{Ctx.getIntWidth(ResultTy), 10451 ResultTy->isUnsignedIntegerType()}; 10452 if (Elt.getFloat().isZero()) 10453 EltResult.setAllBits(); 10454 else 10455 EltResult.clearAllBits(); 10456 10457 return APValue{EltResult}; 10458 } 10459 default: 10460 // FIXME: Implement the rest of the unary operators. 10461 return llvm::None; 10462 } 10463 } 10464 10465 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10466 Expr *SubExpr = E->getSubExpr(); 10467 const auto *VD = SubExpr->getType()->castAs<VectorType>(); 10468 // This result element type differs in the case of negating a floating point 10469 // vector, since the result type is the a vector of the equivilant sized 10470 // integer. 10471 const QualType ResultEltTy = VD->getElementType(); 10472 UnaryOperatorKind Op = E->getOpcode(); 10473 10474 APValue SubExprValue; 10475 if (!Evaluate(SubExprValue, Info, SubExpr)) 10476 return false; 10477 10478 // FIXME: This vector evaluator someday needs to be changed to be LValue 10479 // aware/keep LValue information around, rather than dealing with just vector 10480 // types directly. Until then, we cannot handle cases where the operand to 10481 // these unary operators is an LValue. The only case I've been able to see 10482 // cause this is operator++ assigning to a member expression (only valid in 10483 // altivec compilations) in C mode, so this shouldn't limit us too much. 10484 if (SubExprValue.isLValue()) 10485 return false; 10486 10487 assert(SubExprValue.getVectorLength() == VD->getNumElements() && 10488 "Vector length doesn't match type?"); 10489 10490 SmallVector<APValue, 4> ResultElements; 10491 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { 10492 llvm::Optional<APValue> Elt = handleVectorUnaryOperator( 10493 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); 10494 if (!Elt) 10495 return false; 10496 ResultElements.push_back(*Elt); 10497 } 10498 return Success(APValue(ResultElements.data(), ResultElements.size()), E); 10499 } 10500 10501 //===----------------------------------------------------------------------===// 10502 // Array Evaluation 10503 //===----------------------------------------------------------------------===// 10504 10505 namespace { 10506 class ArrayExprEvaluator 10507 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10508 const LValue &This; 10509 APValue &Result; 10510 public: 10511 10512 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10513 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10514 10515 bool Success(const APValue &V, const Expr *E) { 10516 assert(V.isArray() && "expected array"); 10517 Result = V; 10518 return true; 10519 } 10520 10521 bool ZeroInitialization(const Expr *E) { 10522 const ConstantArrayType *CAT = 10523 Info.Ctx.getAsConstantArrayType(E->getType()); 10524 if (!CAT) { 10525 if (E->getType()->isIncompleteArrayType()) { 10526 // We can be asked to zero-initialize a flexible array member; this 10527 // is represented as an ImplicitValueInitExpr of incomplete array 10528 // type. In this case, the array has zero elements. 10529 Result = APValue(APValue::UninitArray(), 0, 0); 10530 return true; 10531 } 10532 // FIXME: We could handle VLAs here. 10533 return Error(E); 10534 } 10535 10536 Result = APValue(APValue::UninitArray(), 0, 10537 CAT->getSize().getZExtValue()); 10538 if (!Result.hasArrayFiller()) 10539 return true; 10540 10541 // Zero-initialize all elements. 10542 LValue Subobject = This; 10543 Subobject.addArray(Info, E, CAT); 10544 ImplicitValueInitExpr VIE(CAT->getElementType()); 10545 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10546 } 10547 10548 bool VisitCallExpr(const CallExpr *E) { 10549 return handleCallExpr(E, Result, &This); 10550 } 10551 bool VisitInitListExpr(const InitListExpr *E, 10552 QualType AllocType = QualType()); 10553 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10554 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10555 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10556 const LValue &Subobject, 10557 APValue *Value, QualType Type); 10558 bool VisitStringLiteral(const StringLiteral *E, 10559 QualType AllocType = QualType()) { 10560 expandStringLiteral(Info, E, Result, AllocType); 10561 return true; 10562 } 10563 }; 10564 } // end anonymous namespace 10565 10566 static bool EvaluateArray(const Expr *E, const LValue &This, 10567 APValue &Result, EvalInfo &Info) { 10568 assert(!E->isValueDependent()); 10569 assert(E->isPRValue() && E->getType()->isArrayType() && 10570 "not an array prvalue"); 10571 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10572 } 10573 10574 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10575 APValue &Result, const InitListExpr *ILE, 10576 QualType AllocType) { 10577 assert(!ILE->isValueDependent()); 10578 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10579 "not an array prvalue"); 10580 return ArrayExprEvaluator(Info, This, Result) 10581 .VisitInitListExpr(ILE, AllocType); 10582 } 10583 10584 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10585 APValue &Result, 10586 const CXXConstructExpr *CCE, 10587 QualType AllocType) { 10588 assert(!CCE->isValueDependent()); 10589 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10590 "not an array prvalue"); 10591 return ArrayExprEvaluator(Info, This, Result) 10592 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10593 } 10594 10595 // Return true iff the given array filler may depend on the element index. 10596 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10597 // For now, just allow non-class value-initialization and initialization 10598 // lists comprised of them. 10599 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10600 return false; 10601 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10602 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10603 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10604 return true; 10605 } 10606 return false; 10607 } 10608 return true; 10609 } 10610 10611 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10612 QualType AllocType) { 10613 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10614 AllocType.isNull() ? E->getType() : AllocType); 10615 if (!CAT) 10616 return Error(E); 10617 10618 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10619 // an appropriately-typed string literal enclosed in braces. 10620 if (E->isStringLiteralInit()) { 10621 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10622 // FIXME: Support ObjCEncodeExpr here once we support it in 10623 // ArrayExprEvaluator generally. 10624 if (!SL) 10625 return Error(E); 10626 return VisitStringLiteral(SL, AllocType); 10627 } 10628 // Any other transparent list init will need proper handling of the 10629 // AllocType; we can't just recurse to the inner initializer. 10630 assert(!E->isTransparent() && 10631 "transparent array list initialization is not string literal init?"); 10632 10633 bool Success = true; 10634 10635 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10636 "zero-initialized array shouldn't have any initialized elts"); 10637 APValue Filler; 10638 if (Result.isArray() && Result.hasArrayFiller()) 10639 Filler = Result.getArrayFiller(); 10640 10641 unsigned NumEltsToInit = E->getNumInits(); 10642 unsigned NumElts = CAT->getSize().getZExtValue(); 10643 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10644 10645 // If the initializer might depend on the array index, run it for each 10646 // array element. 10647 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10648 NumEltsToInit = NumElts; 10649 10650 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10651 << NumEltsToInit << ".\n"); 10652 10653 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10654 10655 // If the array was previously zero-initialized, preserve the 10656 // zero-initialized values. 10657 if (Filler.hasValue()) { 10658 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10659 Result.getArrayInitializedElt(I) = Filler; 10660 if (Result.hasArrayFiller()) 10661 Result.getArrayFiller() = Filler; 10662 } 10663 10664 LValue Subobject = This; 10665 Subobject.addArray(Info, E, CAT); 10666 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10667 const Expr *Init = 10668 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10669 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10670 Info, Subobject, Init) || 10671 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10672 CAT->getElementType(), 1)) { 10673 if (!Info.noteFailure()) 10674 return false; 10675 Success = false; 10676 } 10677 } 10678 10679 if (!Result.hasArrayFiller()) 10680 return Success; 10681 10682 // If we get here, we have a trivial filler, which we can just evaluate 10683 // once and splat over the rest of the array elements. 10684 assert(FillerExpr && "no array filler for incomplete init list"); 10685 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10686 FillerExpr) && Success; 10687 } 10688 10689 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10690 LValue CommonLV; 10691 if (E->getCommonExpr() && 10692 !Evaluate(Info.CurrentCall->createTemporary( 10693 E->getCommonExpr(), 10694 getStorageType(Info.Ctx, E->getCommonExpr()), 10695 ScopeKind::FullExpression, CommonLV), 10696 Info, E->getCommonExpr()->getSourceExpr())) 10697 return false; 10698 10699 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10700 10701 uint64_t Elements = CAT->getSize().getZExtValue(); 10702 Result = APValue(APValue::UninitArray(), Elements, Elements); 10703 10704 LValue Subobject = This; 10705 Subobject.addArray(Info, E, CAT); 10706 10707 bool Success = true; 10708 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10709 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10710 Info, Subobject, E->getSubExpr()) || 10711 !HandleLValueArrayAdjustment(Info, E, Subobject, 10712 CAT->getElementType(), 1)) { 10713 if (!Info.noteFailure()) 10714 return false; 10715 Success = false; 10716 } 10717 } 10718 10719 return Success; 10720 } 10721 10722 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10723 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10724 } 10725 10726 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10727 const LValue &Subobject, 10728 APValue *Value, 10729 QualType Type) { 10730 bool HadZeroInit = Value->hasValue(); 10731 10732 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10733 unsigned FinalSize = CAT->getSize().getZExtValue(); 10734 10735 // Preserve the array filler if we had prior zero-initialization. 10736 APValue Filler = 10737 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10738 : APValue(); 10739 10740 *Value = APValue(APValue::UninitArray(), 0, FinalSize); 10741 if (FinalSize == 0) 10742 return true; 10743 10744 LValue ArrayElt = Subobject; 10745 ArrayElt.addArray(Info, E, CAT); 10746 // We do the whole initialization in two passes, first for just one element, 10747 // then for the whole array. It's possible we may find out we can't do const 10748 // init in the first pass, in which case we avoid allocating a potentially 10749 // large array. We don't do more passes because expanding array requires 10750 // copying the data, which is wasteful. 10751 for (const unsigned N : {1u, FinalSize}) { 10752 unsigned OldElts = Value->getArrayInitializedElts(); 10753 if (OldElts == N) 10754 break; 10755 10756 // Expand the array to appropriate size. 10757 APValue NewValue(APValue::UninitArray(), N, FinalSize); 10758 for (unsigned I = 0; I < OldElts; ++I) 10759 NewValue.getArrayInitializedElt(I).swap( 10760 Value->getArrayInitializedElt(I)); 10761 Value->swap(NewValue); 10762 10763 if (HadZeroInit) 10764 for (unsigned I = OldElts; I < N; ++I) 10765 Value->getArrayInitializedElt(I) = Filler; 10766 10767 // Initialize the elements. 10768 for (unsigned I = OldElts; I < N; ++I) { 10769 if (!VisitCXXConstructExpr(E, ArrayElt, 10770 &Value->getArrayInitializedElt(I), 10771 CAT->getElementType()) || 10772 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10773 CAT->getElementType(), 1)) 10774 return false; 10775 // When checking for const initilization any diagnostic is considered 10776 // an error. 10777 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && 10778 !Info.keepEvaluatingAfterFailure()) 10779 return false; 10780 } 10781 } 10782 10783 return true; 10784 } 10785 10786 if (!Type->isRecordType()) 10787 return Error(E); 10788 10789 return RecordExprEvaluator(Info, Subobject, *Value) 10790 .VisitCXXConstructExpr(E, Type); 10791 } 10792 10793 //===----------------------------------------------------------------------===// 10794 // Integer Evaluation 10795 // 10796 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10797 // types and back in constant folding. Integer values are thus represented 10798 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10799 //===----------------------------------------------------------------------===// 10800 10801 namespace { 10802 class IntExprEvaluator 10803 : public ExprEvaluatorBase<IntExprEvaluator> { 10804 APValue &Result; 10805 public: 10806 IntExprEvaluator(EvalInfo &info, APValue &result) 10807 : ExprEvaluatorBaseTy(info), Result(result) {} 10808 10809 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10810 assert(E->getType()->isIntegralOrEnumerationType() && 10811 "Invalid evaluation result."); 10812 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10813 "Invalid evaluation result."); 10814 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10815 "Invalid evaluation result."); 10816 Result = APValue(SI); 10817 return true; 10818 } 10819 bool Success(const llvm::APSInt &SI, const Expr *E) { 10820 return Success(SI, E, Result); 10821 } 10822 10823 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10824 assert(E->getType()->isIntegralOrEnumerationType() && 10825 "Invalid evaluation result."); 10826 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10827 "Invalid evaluation result."); 10828 Result = APValue(APSInt(I)); 10829 Result.getInt().setIsUnsigned( 10830 E->getType()->isUnsignedIntegerOrEnumerationType()); 10831 return true; 10832 } 10833 bool Success(const llvm::APInt &I, const Expr *E) { 10834 return Success(I, E, Result); 10835 } 10836 10837 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10838 assert(E->getType()->isIntegralOrEnumerationType() && 10839 "Invalid evaluation result."); 10840 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10841 return true; 10842 } 10843 bool Success(uint64_t Value, const Expr *E) { 10844 return Success(Value, E, Result); 10845 } 10846 10847 bool Success(CharUnits Size, const Expr *E) { 10848 return Success(Size.getQuantity(), E); 10849 } 10850 10851 bool Success(const APValue &V, const Expr *E) { 10852 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10853 Result = V; 10854 return true; 10855 } 10856 return Success(V.getInt(), E); 10857 } 10858 10859 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10860 10861 //===--------------------------------------------------------------------===// 10862 // Visitor Methods 10863 //===--------------------------------------------------------------------===// 10864 10865 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10866 return Success(E->getValue(), E); 10867 } 10868 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10869 return Success(E->getValue(), E); 10870 } 10871 10872 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10873 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10874 if (CheckReferencedDecl(E, E->getDecl())) 10875 return true; 10876 10877 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10878 } 10879 bool VisitMemberExpr(const MemberExpr *E) { 10880 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10881 VisitIgnoredBaseExpression(E->getBase()); 10882 return true; 10883 } 10884 10885 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10886 } 10887 10888 bool VisitCallExpr(const CallExpr *E); 10889 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10890 bool VisitBinaryOperator(const BinaryOperator *E); 10891 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10892 bool VisitUnaryOperator(const UnaryOperator *E); 10893 10894 bool VisitCastExpr(const CastExpr* E); 10895 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10896 10897 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10898 return Success(E->getValue(), E); 10899 } 10900 10901 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10902 return Success(E->getValue(), E); 10903 } 10904 10905 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10906 if (Info.ArrayInitIndex == uint64_t(-1)) { 10907 // We were asked to evaluate this subexpression independent of the 10908 // enclosing ArrayInitLoopExpr. We can't do that. 10909 Info.FFDiag(E); 10910 return false; 10911 } 10912 return Success(Info.ArrayInitIndex, E); 10913 } 10914 10915 // Note, GNU defines __null as an integer, not a pointer. 10916 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10917 return ZeroInitialization(E); 10918 } 10919 10920 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10921 return Success(E->getValue(), E); 10922 } 10923 10924 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10925 return Success(E->getValue(), E); 10926 } 10927 10928 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10929 return Success(E->getValue(), E); 10930 } 10931 10932 bool VisitUnaryReal(const UnaryOperator *E); 10933 bool VisitUnaryImag(const UnaryOperator *E); 10934 10935 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10936 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10937 bool VisitSourceLocExpr(const SourceLocExpr *E); 10938 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10939 bool VisitRequiresExpr(const RequiresExpr *E); 10940 // FIXME: Missing: array subscript of vector, member of vector 10941 }; 10942 10943 class FixedPointExprEvaluator 10944 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10945 APValue &Result; 10946 10947 public: 10948 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10949 : ExprEvaluatorBaseTy(info), Result(result) {} 10950 10951 bool Success(const llvm::APInt &I, const Expr *E) { 10952 return Success( 10953 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10954 } 10955 10956 bool Success(uint64_t Value, const Expr *E) { 10957 return Success( 10958 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10959 } 10960 10961 bool Success(const APValue &V, const Expr *E) { 10962 return Success(V.getFixedPoint(), E); 10963 } 10964 10965 bool Success(const APFixedPoint &V, const Expr *E) { 10966 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10967 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10968 "Invalid evaluation result."); 10969 Result = APValue(V); 10970 return true; 10971 } 10972 10973 //===--------------------------------------------------------------------===// 10974 // Visitor Methods 10975 //===--------------------------------------------------------------------===// 10976 10977 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10978 return Success(E->getValue(), E); 10979 } 10980 10981 bool VisitCastExpr(const CastExpr *E); 10982 bool VisitUnaryOperator(const UnaryOperator *E); 10983 bool VisitBinaryOperator(const BinaryOperator *E); 10984 }; 10985 } // end anonymous namespace 10986 10987 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10988 /// produce either the integer value or a pointer. 10989 /// 10990 /// GCC has a heinous extension which folds casts between pointer types and 10991 /// pointer-sized integral types. We support this by allowing the evaluation of 10992 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10993 /// Some simple arithmetic on such values is supported (they are treated much 10994 /// like char*). 10995 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10996 EvalInfo &Info) { 10997 assert(!E->isValueDependent()); 10998 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 10999 return IntExprEvaluator(Info, Result).Visit(E); 11000 } 11001 11002 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 11003 assert(!E->isValueDependent()); 11004 APValue Val; 11005 if (!EvaluateIntegerOrLValue(E, Val, Info)) 11006 return false; 11007 if (!Val.isInt()) { 11008 // FIXME: It would be better to produce the diagnostic for casting 11009 // a pointer to an integer. 11010 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11011 return false; 11012 } 11013 Result = Val.getInt(); 11014 return true; 11015 } 11016 11017 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 11018 APValue Evaluated = E->EvaluateInContext( 11019 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 11020 return Success(Evaluated, E); 11021 } 11022 11023 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 11024 EvalInfo &Info) { 11025 assert(!E->isValueDependent()); 11026 if (E->getType()->isFixedPointType()) { 11027 APValue Val; 11028 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 11029 return false; 11030 if (!Val.isFixedPoint()) 11031 return false; 11032 11033 Result = Val.getFixedPoint(); 11034 return true; 11035 } 11036 return false; 11037 } 11038 11039 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 11040 EvalInfo &Info) { 11041 assert(!E->isValueDependent()); 11042 if (E->getType()->isIntegerType()) { 11043 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 11044 APSInt Val; 11045 if (!EvaluateInteger(E, Val, Info)) 11046 return false; 11047 Result = APFixedPoint(Val, FXSema); 11048 return true; 11049 } else if (E->getType()->isFixedPointType()) { 11050 return EvaluateFixedPoint(E, Result, Info); 11051 } 11052 return false; 11053 } 11054 11055 /// Check whether the given declaration can be directly converted to an integral 11056 /// rvalue. If not, no diagnostic is produced; there are other things we can 11057 /// try. 11058 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 11059 // Enums are integer constant exprs. 11060 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 11061 // Check for signedness/width mismatches between E type and ECD value. 11062 bool SameSign = (ECD->getInitVal().isSigned() 11063 == E->getType()->isSignedIntegerOrEnumerationType()); 11064 bool SameWidth = (ECD->getInitVal().getBitWidth() 11065 == Info.Ctx.getIntWidth(E->getType())); 11066 if (SameSign && SameWidth) 11067 return Success(ECD->getInitVal(), E); 11068 else { 11069 // Get rid of mismatch (otherwise Success assertions will fail) 11070 // by computing a new value matching the type of E. 11071 llvm::APSInt Val = ECD->getInitVal(); 11072 if (!SameSign) 11073 Val.setIsSigned(!ECD->getInitVal().isSigned()); 11074 if (!SameWidth) 11075 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 11076 return Success(Val, E); 11077 } 11078 } 11079 return false; 11080 } 11081 11082 /// Values returned by __builtin_classify_type, chosen to match the values 11083 /// produced by GCC's builtin. 11084 enum class GCCTypeClass { 11085 None = -1, 11086 Void = 0, 11087 Integer = 1, 11088 // GCC reserves 2 for character types, but instead classifies them as 11089 // integers. 11090 Enum = 3, 11091 Bool = 4, 11092 Pointer = 5, 11093 // GCC reserves 6 for references, but appears to never use it (because 11094 // expressions never have reference type, presumably). 11095 PointerToDataMember = 7, 11096 RealFloat = 8, 11097 Complex = 9, 11098 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 11099 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 11100 // GCC claims to reserve 11 for pointers to member functions, but *actually* 11101 // uses 12 for that purpose, same as for a class or struct. Maybe it 11102 // internally implements a pointer to member as a struct? Who knows. 11103 PointerToMemberFunction = 12, // Not a bug, see above. 11104 ClassOrStruct = 12, 11105 Union = 13, 11106 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 11107 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 11108 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 11109 // literals. 11110 }; 11111 11112 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11113 /// as GCC. 11114 static GCCTypeClass 11115 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 11116 assert(!T->isDependentType() && "unexpected dependent type"); 11117 11118 QualType CanTy = T.getCanonicalType(); 11119 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 11120 11121 switch (CanTy->getTypeClass()) { 11122 #define TYPE(ID, BASE) 11123 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 11124 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 11125 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 11126 #include "clang/AST/TypeNodes.inc" 11127 case Type::Auto: 11128 case Type::DeducedTemplateSpecialization: 11129 llvm_unreachable("unexpected non-canonical or dependent type"); 11130 11131 case Type::Builtin: 11132 switch (BT->getKind()) { 11133 #define BUILTIN_TYPE(ID, SINGLETON_ID) 11134 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 11135 case BuiltinType::ID: return GCCTypeClass::Integer; 11136 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 11137 case BuiltinType::ID: return GCCTypeClass::RealFloat; 11138 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 11139 case BuiltinType::ID: break; 11140 #include "clang/AST/BuiltinTypes.def" 11141 case BuiltinType::Void: 11142 return GCCTypeClass::Void; 11143 11144 case BuiltinType::Bool: 11145 return GCCTypeClass::Bool; 11146 11147 case BuiltinType::Char_U: 11148 case BuiltinType::UChar: 11149 case BuiltinType::WChar_U: 11150 case BuiltinType::Char8: 11151 case BuiltinType::Char16: 11152 case BuiltinType::Char32: 11153 case BuiltinType::UShort: 11154 case BuiltinType::UInt: 11155 case BuiltinType::ULong: 11156 case BuiltinType::ULongLong: 11157 case BuiltinType::UInt128: 11158 return GCCTypeClass::Integer; 11159 11160 case BuiltinType::UShortAccum: 11161 case BuiltinType::UAccum: 11162 case BuiltinType::ULongAccum: 11163 case BuiltinType::UShortFract: 11164 case BuiltinType::UFract: 11165 case BuiltinType::ULongFract: 11166 case BuiltinType::SatUShortAccum: 11167 case BuiltinType::SatUAccum: 11168 case BuiltinType::SatULongAccum: 11169 case BuiltinType::SatUShortFract: 11170 case BuiltinType::SatUFract: 11171 case BuiltinType::SatULongFract: 11172 return GCCTypeClass::None; 11173 11174 case BuiltinType::NullPtr: 11175 11176 case BuiltinType::ObjCId: 11177 case BuiltinType::ObjCClass: 11178 case BuiltinType::ObjCSel: 11179 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11180 case BuiltinType::Id: 11181 #include "clang/Basic/OpenCLImageTypes.def" 11182 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11183 case BuiltinType::Id: 11184 #include "clang/Basic/OpenCLExtensionTypes.def" 11185 case BuiltinType::OCLSampler: 11186 case BuiltinType::OCLEvent: 11187 case BuiltinType::OCLClkEvent: 11188 case BuiltinType::OCLQueue: 11189 case BuiltinType::OCLReserveID: 11190 #define SVE_TYPE(Name, Id, SingletonId) \ 11191 case BuiltinType::Id: 11192 #include "clang/Basic/AArch64SVEACLETypes.def" 11193 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11194 case BuiltinType::Id: 11195 #include "clang/Basic/PPCTypes.def" 11196 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11197 #include "clang/Basic/RISCVVTypes.def" 11198 return GCCTypeClass::None; 11199 11200 case BuiltinType::Dependent: 11201 llvm_unreachable("unexpected dependent type"); 11202 }; 11203 llvm_unreachable("unexpected placeholder type"); 11204 11205 case Type::Enum: 11206 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11207 11208 case Type::Pointer: 11209 case Type::ConstantArray: 11210 case Type::VariableArray: 11211 case Type::IncompleteArray: 11212 case Type::FunctionNoProto: 11213 case Type::FunctionProto: 11214 return GCCTypeClass::Pointer; 11215 11216 case Type::MemberPointer: 11217 return CanTy->isMemberDataPointerType() 11218 ? GCCTypeClass::PointerToDataMember 11219 : GCCTypeClass::PointerToMemberFunction; 11220 11221 case Type::Complex: 11222 return GCCTypeClass::Complex; 11223 11224 case Type::Record: 11225 return CanTy->isUnionType() ? GCCTypeClass::Union 11226 : GCCTypeClass::ClassOrStruct; 11227 11228 case Type::Atomic: 11229 // GCC classifies _Atomic T the same as T. 11230 return EvaluateBuiltinClassifyType( 11231 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11232 11233 case Type::BlockPointer: 11234 case Type::Vector: 11235 case Type::ExtVector: 11236 case Type::ConstantMatrix: 11237 case Type::ObjCObject: 11238 case Type::ObjCInterface: 11239 case Type::ObjCObjectPointer: 11240 case Type::Pipe: 11241 case Type::BitInt: 11242 // GCC classifies vectors as None. We follow its lead and classify all 11243 // other types that don't fit into the regular classification the same way. 11244 return GCCTypeClass::None; 11245 11246 case Type::LValueReference: 11247 case Type::RValueReference: 11248 llvm_unreachable("invalid type for expression"); 11249 } 11250 11251 llvm_unreachable("unexpected type class"); 11252 } 11253 11254 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11255 /// as GCC. 11256 static GCCTypeClass 11257 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11258 // If no argument was supplied, default to None. This isn't 11259 // ideal, however it is what gcc does. 11260 if (E->getNumArgs() == 0) 11261 return GCCTypeClass::None; 11262 11263 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11264 // being an ICE, but still folds it to a constant using the type of the first 11265 // argument. 11266 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11267 } 11268 11269 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11270 /// __builtin_constant_p when applied to the given pointer. 11271 /// 11272 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11273 /// or it points to the first character of a string literal. 11274 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11275 APValue::LValueBase Base = LV.getLValueBase(); 11276 if (Base.isNull()) { 11277 // A null base is acceptable. 11278 return true; 11279 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11280 if (!isa<StringLiteral>(E)) 11281 return false; 11282 return LV.getLValueOffset().isZero(); 11283 } else if (Base.is<TypeInfoLValue>()) { 11284 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11285 // evaluate to true. 11286 return true; 11287 } else { 11288 // Any other base is not constant enough for GCC. 11289 return false; 11290 } 11291 } 11292 11293 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11294 /// GCC as we can manage. 11295 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11296 // This evaluation is not permitted to have side-effects, so evaluate it in 11297 // a speculative evaluation context. 11298 SpeculativeEvaluationRAII SpeculativeEval(Info); 11299 11300 // Constant-folding is always enabled for the operand of __builtin_constant_p 11301 // (even when the enclosing evaluation context otherwise requires a strict 11302 // language-specific constant expression). 11303 FoldConstant Fold(Info, true); 11304 11305 QualType ArgType = Arg->getType(); 11306 11307 // __builtin_constant_p always has one operand. The rules which gcc follows 11308 // are not precisely documented, but are as follows: 11309 // 11310 // - If the operand is of integral, floating, complex or enumeration type, 11311 // and can be folded to a known value of that type, it returns 1. 11312 // - If the operand can be folded to a pointer to the first character 11313 // of a string literal (or such a pointer cast to an integral type) 11314 // or to a null pointer or an integer cast to a pointer, it returns 1. 11315 // 11316 // Otherwise, it returns 0. 11317 // 11318 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11319 // its support for this did not work prior to GCC 9 and is not yet well 11320 // understood. 11321 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11322 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11323 ArgType->isNullPtrType()) { 11324 APValue V; 11325 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11326 Fold.keepDiagnostics(); 11327 return false; 11328 } 11329 11330 // For a pointer (possibly cast to integer), there are special rules. 11331 if (V.getKind() == APValue::LValue) 11332 return EvaluateBuiltinConstantPForLValue(V); 11333 11334 // Otherwise, any constant value is good enough. 11335 return V.hasValue(); 11336 } 11337 11338 // Anything else isn't considered to be sufficiently constant. 11339 return false; 11340 } 11341 11342 /// Retrieves the "underlying object type" of the given expression, 11343 /// as used by __builtin_object_size. 11344 static QualType getObjectType(APValue::LValueBase B) { 11345 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11346 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11347 return VD->getType(); 11348 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11349 if (isa<CompoundLiteralExpr>(E)) 11350 return E->getType(); 11351 } else if (B.is<TypeInfoLValue>()) { 11352 return B.getTypeInfoType(); 11353 } else if (B.is<DynamicAllocLValue>()) { 11354 return B.getDynamicAllocType(); 11355 } 11356 11357 return QualType(); 11358 } 11359 11360 /// A more selective version of E->IgnoreParenCasts for 11361 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11362 /// to change the type of E. 11363 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11364 /// 11365 /// Always returns an RValue with a pointer representation. 11366 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11367 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11368 11369 auto *NoParens = E->IgnoreParens(); 11370 auto *Cast = dyn_cast<CastExpr>(NoParens); 11371 if (Cast == nullptr) 11372 return NoParens; 11373 11374 // We only conservatively allow a few kinds of casts, because this code is 11375 // inherently a simple solution that seeks to support the common case. 11376 auto CastKind = Cast->getCastKind(); 11377 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11378 CastKind != CK_AddressSpaceConversion) 11379 return NoParens; 11380 11381 auto *SubExpr = Cast->getSubExpr(); 11382 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11383 return NoParens; 11384 return ignorePointerCastsAndParens(SubExpr); 11385 } 11386 11387 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11388 /// record layout. e.g. 11389 /// struct { struct { int a, b; } fst, snd; } obj; 11390 /// obj.fst // no 11391 /// obj.snd // yes 11392 /// obj.fst.a // no 11393 /// obj.fst.b // no 11394 /// obj.snd.a // no 11395 /// obj.snd.b // yes 11396 /// 11397 /// Please note: this function is specialized for how __builtin_object_size 11398 /// views "objects". 11399 /// 11400 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11401 /// correct result, it will always return true. 11402 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11403 assert(!LVal.Designator.Invalid); 11404 11405 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11406 const RecordDecl *Parent = FD->getParent(); 11407 Invalid = Parent->isInvalidDecl(); 11408 if (Invalid || Parent->isUnion()) 11409 return true; 11410 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11411 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11412 }; 11413 11414 auto &Base = LVal.getLValueBase(); 11415 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11416 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11417 bool Invalid; 11418 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11419 return Invalid; 11420 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11421 for (auto *FD : IFD->chain()) { 11422 bool Invalid; 11423 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11424 return Invalid; 11425 } 11426 } 11427 } 11428 11429 unsigned I = 0; 11430 QualType BaseType = getType(Base); 11431 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11432 // If we don't know the array bound, conservatively assume we're looking at 11433 // the final array element. 11434 ++I; 11435 if (BaseType->isIncompleteArrayType()) 11436 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11437 else 11438 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11439 } 11440 11441 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11442 const auto &Entry = LVal.Designator.Entries[I]; 11443 if (BaseType->isArrayType()) { 11444 // Because __builtin_object_size treats arrays as objects, we can ignore 11445 // the index iff this is the last array in the Designator. 11446 if (I + 1 == E) 11447 return true; 11448 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11449 uint64_t Index = Entry.getAsArrayIndex(); 11450 if (Index + 1 != CAT->getSize()) 11451 return false; 11452 BaseType = CAT->getElementType(); 11453 } else if (BaseType->isAnyComplexType()) { 11454 const auto *CT = BaseType->castAs<ComplexType>(); 11455 uint64_t Index = Entry.getAsArrayIndex(); 11456 if (Index != 1) 11457 return false; 11458 BaseType = CT->getElementType(); 11459 } else if (auto *FD = getAsField(Entry)) { 11460 bool Invalid; 11461 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11462 return Invalid; 11463 BaseType = FD->getType(); 11464 } else { 11465 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11466 return false; 11467 } 11468 } 11469 return true; 11470 } 11471 11472 /// Tests to see if the LValue has a user-specified designator (that isn't 11473 /// necessarily valid). Note that this always returns 'true' if the LValue has 11474 /// an unsized array as its first designator entry, because there's currently no 11475 /// way to tell if the user typed *foo or foo[0]. 11476 static bool refersToCompleteObject(const LValue &LVal) { 11477 if (LVal.Designator.Invalid) 11478 return false; 11479 11480 if (!LVal.Designator.Entries.empty()) 11481 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11482 11483 if (!LVal.InvalidBase) 11484 return true; 11485 11486 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11487 // the LValueBase. 11488 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11489 return !E || !isa<MemberExpr>(E); 11490 } 11491 11492 /// Attempts to detect a user writing into a piece of memory that's impossible 11493 /// to figure out the size of by just using types. 11494 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11495 const SubobjectDesignator &Designator = LVal.Designator; 11496 // Notes: 11497 // - Users can only write off of the end when we have an invalid base. Invalid 11498 // bases imply we don't know where the memory came from. 11499 // - We used to be a bit more aggressive here; we'd only be conservative if 11500 // the array at the end was flexible, or if it had 0 or 1 elements. This 11501 // broke some common standard library extensions (PR30346), but was 11502 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11503 // with some sort of list. OTOH, it seems that GCC is always 11504 // conservative with the last element in structs (if it's an array), so our 11505 // current behavior is more compatible than an explicit list approach would 11506 // be. 11507 return LVal.InvalidBase && 11508 Designator.Entries.size() == Designator.MostDerivedPathLength && 11509 Designator.MostDerivedIsArrayElement && 11510 isDesignatorAtObjectEnd(Ctx, LVal); 11511 } 11512 11513 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11514 /// Fails if the conversion would cause loss of precision. 11515 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11516 CharUnits &Result) { 11517 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11518 if (Int.ugt(CharUnitsMax)) 11519 return false; 11520 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11521 return true; 11522 } 11523 11524 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11525 /// determine how many bytes exist from the beginning of the object to either 11526 /// the end of the current subobject, or the end of the object itself, depending 11527 /// on what the LValue looks like + the value of Type. 11528 /// 11529 /// If this returns false, the value of Result is undefined. 11530 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11531 unsigned Type, const LValue &LVal, 11532 CharUnits &EndOffset) { 11533 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11534 11535 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11536 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11537 return false; 11538 return HandleSizeof(Info, ExprLoc, Ty, Result); 11539 }; 11540 11541 // We want to evaluate the size of the entire object. This is a valid fallback 11542 // for when Type=1 and the designator is invalid, because we're asked for an 11543 // upper-bound. 11544 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11545 // Type=3 wants a lower bound, so we can't fall back to this. 11546 if (Type == 3 && !DetermineForCompleteObject) 11547 return false; 11548 11549 llvm::APInt APEndOffset; 11550 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11551 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11552 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11553 11554 if (LVal.InvalidBase) 11555 return false; 11556 11557 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11558 return CheckedHandleSizeof(BaseTy, EndOffset); 11559 } 11560 11561 // We want to evaluate the size of a subobject. 11562 const SubobjectDesignator &Designator = LVal.Designator; 11563 11564 // The following is a moderately common idiom in C: 11565 // 11566 // struct Foo { int a; char c[1]; }; 11567 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11568 // strcpy(&F->c[0], Bar); 11569 // 11570 // In order to not break too much legacy code, we need to support it. 11571 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11572 // If we can resolve this to an alloc_size call, we can hand that back, 11573 // because we know for certain how many bytes there are to write to. 11574 llvm::APInt APEndOffset; 11575 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11576 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11577 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11578 11579 // If we cannot determine the size of the initial allocation, then we can't 11580 // given an accurate upper-bound. However, we are still able to give 11581 // conservative lower-bounds for Type=3. 11582 if (Type == 1) 11583 return false; 11584 } 11585 11586 CharUnits BytesPerElem; 11587 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11588 return false; 11589 11590 // According to the GCC documentation, we want the size of the subobject 11591 // denoted by the pointer. But that's not quite right -- what we actually 11592 // want is the size of the immediately-enclosing array, if there is one. 11593 int64_t ElemsRemaining; 11594 if (Designator.MostDerivedIsArrayElement && 11595 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11596 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11597 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11598 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11599 } else { 11600 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11601 } 11602 11603 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11604 return true; 11605 } 11606 11607 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11608 /// returns true and stores the result in @p Size. 11609 /// 11610 /// If @p WasError is non-null, this will report whether the failure to evaluate 11611 /// is to be treated as an Error in IntExprEvaluator. 11612 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11613 EvalInfo &Info, uint64_t &Size) { 11614 // Determine the denoted object. 11615 LValue LVal; 11616 { 11617 // The operand of __builtin_object_size is never evaluated for side-effects. 11618 // If there are any, but we can determine the pointed-to object anyway, then 11619 // ignore the side-effects. 11620 SpeculativeEvaluationRAII SpeculativeEval(Info); 11621 IgnoreSideEffectsRAII Fold(Info); 11622 11623 if (E->isGLValue()) { 11624 // It's possible for us to be given GLValues if we're called via 11625 // Expr::tryEvaluateObjectSize. 11626 APValue RVal; 11627 if (!EvaluateAsRValue(Info, E, RVal)) 11628 return false; 11629 LVal.setFrom(Info.Ctx, RVal); 11630 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11631 /*InvalidBaseOK=*/true)) 11632 return false; 11633 } 11634 11635 // If we point to before the start of the object, there are no accessible 11636 // bytes. 11637 if (LVal.getLValueOffset().isNegative()) { 11638 Size = 0; 11639 return true; 11640 } 11641 11642 CharUnits EndOffset; 11643 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11644 return false; 11645 11646 // If we've fallen outside of the end offset, just pretend there's nothing to 11647 // write to/read from. 11648 if (EndOffset <= LVal.getLValueOffset()) 11649 Size = 0; 11650 else 11651 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11652 return true; 11653 } 11654 11655 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11656 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11657 return VisitBuiltinCallExpr(E, BuiltinOp); 11658 11659 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11660 } 11661 11662 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11663 APValue &Val, APSInt &Alignment) { 11664 QualType SrcTy = E->getArg(0)->getType(); 11665 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11666 return false; 11667 // Even though we are evaluating integer expressions we could get a pointer 11668 // argument for the __builtin_is_aligned() case. 11669 if (SrcTy->isPointerType()) { 11670 LValue Ptr; 11671 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11672 return false; 11673 Ptr.moveInto(Val); 11674 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11675 Info.FFDiag(E->getArg(0)); 11676 return false; 11677 } else { 11678 APSInt SrcInt; 11679 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11680 return false; 11681 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11682 "Bit widths must be the same"); 11683 Val = APValue(SrcInt); 11684 } 11685 assert(Val.hasValue()); 11686 return true; 11687 } 11688 11689 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11690 unsigned BuiltinOp) { 11691 switch (BuiltinOp) { 11692 default: 11693 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11694 11695 case Builtin::BI__builtin_dynamic_object_size: 11696 case Builtin::BI__builtin_object_size: { 11697 // The type was checked when we built the expression. 11698 unsigned Type = 11699 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11700 assert(Type <= 3 && "unexpected type"); 11701 11702 uint64_t Size; 11703 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11704 return Success(Size, E); 11705 11706 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11707 return Success((Type & 2) ? 0 : -1, E); 11708 11709 // Expression had no side effects, but we couldn't statically determine the 11710 // size of the referenced object. 11711 switch (Info.EvalMode) { 11712 case EvalInfo::EM_ConstantExpression: 11713 case EvalInfo::EM_ConstantFold: 11714 case EvalInfo::EM_IgnoreSideEffects: 11715 // Leave it to IR generation. 11716 return Error(E); 11717 case EvalInfo::EM_ConstantExpressionUnevaluated: 11718 // Reduce it to a constant now. 11719 return Success((Type & 2) ? 0 : -1, E); 11720 } 11721 11722 llvm_unreachable("unexpected EvalMode"); 11723 } 11724 11725 case Builtin::BI__builtin_os_log_format_buffer_size: { 11726 analyze_os_log::OSLogBufferLayout Layout; 11727 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11728 return Success(Layout.size().getQuantity(), E); 11729 } 11730 11731 case Builtin::BI__builtin_is_aligned: { 11732 APValue Src; 11733 APSInt Alignment; 11734 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11735 return false; 11736 if (Src.isLValue()) { 11737 // If we evaluated a pointer, check the minimum known alignment. 11738 LValue Ptr; 11739 Ptr.setFrom(Info.Ctx, Src); 11740 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11741 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11742 // We can return true if the known alignment at the computed offset is 11743 // greater than the requested alignment. 11744 assert(PtrAlign.isPowerOfTwo()); 11745 assert(Alignment.isPowerOf2()); 11746 if (PtrAlign.getQuantity() >= Alignment) 11747 return Success(1, E); 11748 // If the alignment is not known to be sufficient, some cases could still 11749 // be aligned at run time. However, if the requested alignment is less or 11750 // equal to the base alignment and the offset is not aligned, we know that 11751 // the run-time value can never be aligned. 11752 if (BaseAlignment.getQuantity() >= Alignment && 11753 PtrAlign.getQuantity() < Alignment) 11754 return Success(0, E); 11755 // Otherwise we can't infer whether the value is sufficiently aligned. 11756 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11757 // in cases where we can't fully evaluate the pointer. 11758 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11759 << Alignment; 11760 return false; 11761 } 11762 assert(Src.isInt()); 11763 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11764 } 11765 case Builtin::BI__builtin_align_up: { 11766 APValue Src; 11767 APSInt Alignment; 11768 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11769 return false; 11770 if (!Src.isInt()) 11771 return Error(E); 11772 APSInt AlignedVal = 11773 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11774 Src.getInt().isUnsigned()); 11775 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11776 return Success(AlignedVal, E); 11777 } 11778 case Builtin::BI__builtin_align_down: { 11779 APValue Src; 11780 APSInt Alignment; 11781 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11782 return false; 11783 if (!Src.isInt()) 11784 return Error(E); 11785 APSInt AlignedVal = 11786 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11787 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11788 return Success(AlignedVal, E); 11789 } 11790 11791 case Builtin::BI__builtin_bitreverse8: 11792 case Builtin::BI__builtin_bitreverse16: 11793 case Builtin::BI__builtin_bitreverse32: 11794 case Builtin::BI__builtin_bitreverse64: { 11795 APSInt Val; 11796 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11797 return false; 11798 11799 return Success(Val.reverseBits(), E); 11800 } 11801 11802 case Builtin::BI__builtin_bswap16: 11803 case Builtin::BI__builtin_bswap32: 11804 case Builtin::BI__builtin_bswap64: { 11805 APSInt Val; 11806 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11807 return false; 11808 11809 return Success(Val.byteSwap(), E); 11810 } 11811 11812 case Builtin::BI__builtin_classify_type: 11813 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11814 11815 case Builtin::BI__builtin_clrsb: 11816 case Builtin::BI__builtin_clrsbl: 11817 case Builtin::BI__builtin_clrsbll: { 11818 APSInt Val; 11819 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11820 return false; 11821 11822 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11823 } 11824 11825 case Builtin::BI__builtin_clz: 11826 case Builtin::BI__builtin_clzl: 11827 case Builtin::BI__builtin_clzll: 11828 case Builtin::BI__builtin_clzs: { 11829 APSInt Val; 11830 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11831 return false; 11832 if (!Val) 11833 return Error(E); 11834 11835 return Success(Val.countLeadingZeros(), E); 11836 } 11837 11838 case Builtin::BI__builtin_constant_p: { 11839 const Expr *Arg = E->getArg(0); 11840 if (EvaluateBuiltinConstantP(Info, Arg)) 11841 return Success(true, E); 11842 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11843 // Outside a constant context, eagerly evaluate to false in the presence 11844 // of side-effects in order to avoid -Wunsequenced false-positives in 11845 // a branch on __builtin_constant_p(expr). 11846 return Success(false, E); 11847 } 11848 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11849 return false; 11850 } 11851 11852 case Builtin::BI__builtin_is_constant_evaluated: { 11853 const auto *Callee = Info.CurrentCall->getCallee(); 11854 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11855 (Info.CallStackDepth == 1 || 11856 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11857 Callee->getIdentifier() && 11858 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11859 // FIXME: Find a better way to avoid duplicated diagnostics. 11860 if (Info.EvalStatus.Diag) 11861 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11862 : Info.CurrentCall->CallLoc, 11863 diag::warn_is_constant_evaluated_always_true_constexpr) 11864 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11865 : "std::is_constant_evaluated"); 11866 } 11867 11868 return Success(Info.InConstantContext, E); 11869 } 11870 11871 case Builtin::BI__builtin_ctz: 11872 case Builtin::BI__builtin_ctzl: 11873 case Builtin::BI__builtin_ctzll: 11874 case Builtin::BI__builtin_ctzs: { 11875 APSInt Val; 11876 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11877 return false; 11878 if (!Val) 11879 return Error(E); 11880 11881 return Success(Val.countTrailingZeros(), E); 11882 } 11883 11884 case Builtin::BI__builtin_eh_return_data_regno: { 11885 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11886 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11887 return Success(Operand, E); 11888 } 11889 11890 case Builtin::BI__builtin_expect: 11891 case Builtin::BI__builtin_expect_with_probability: 11892 return Visit(E->getArg(0)); 11893 11894 case Builtin::BI__builtin_ffs: 11895 case Builtin::BI__builtin_ffsl: 11896 case Builtin::BI__builtin_ffsll: { 11897 APSInt Val; 11898 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11899 return false; 11900 11901 unsigned N = Val.countTrailingZeros(); 11902 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11903 } 11904 11905 case Builtin::BI__builtin_fpclassify: { 11906 APFloat Val(0.0); 11907 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11908 return false; 11909 unsigned Arg; 11910 switch (Val.getCategory()) { 11911 case APFloat::fcNaN: Arg = 0; break; 11912 case APFloat::fcInfinity: Arg = 1; break; 11913 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11914 case APFloat::fcZero: Arg = 4; break; 11915 } 11916 return Visit(E->getArg(Arg)); 11917 } 11918 11919 case Builtin::BI__builtin_isinf_sign: { 11920 APFloat Val(0.0); 11921 return EvaluateFloat(E->getArg(0), Val, Info) && 11922 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11923 } 11924 11925 case Builtin::BI__builtin_isinf: { 11926 APFloat Val(0.0); 11927 return EvaluateFloat(E->getArg(0), Val, Info) && 11928 Success(Val.isInfinity() ? 1 : 0, E); 11929 } 11930 11931 case Builtin::BI__builtin_isfinite: { 11932 APFloat Val(0.0); 11933 return EvaluateFloat(E->getArg(0), Val, Info) && 11934 Success(Val.isFinite() ? 1 : 0, E); 11935 } 11936 11937 case Builtin::BI__builtin_isnan: { 11938 APFloat Val(0.0); 11939 return EvaluateFloat(E->getArg(0), Val, Info) && 11940 Success(Val.isNaN() ? 1 : 0, E); 11941 } 11942 11943 case Builtin::BI__builtin_isnormal: { 11944 APFloat Val(0.0); 11945 return EvaluateFloat(E->getArg(0), Val, Info) && 11946 Success(Val.isNormal() ? 1 : 0, E); 11947 } 11948 11949 case Builtin::BI__builtin_parity: 11950 case Builtin::BI__builtin_parityl: 11951 case Builtin::BI__builtin_parityll: { 11952 APSInt Val; 11953 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11954 return false; 11955 11956 return Success(Val.countPopulation() % 2, E); 11957 } 11958 11959 case Builtin::BI__builtin_popcount: 11960 case Builtin::BI__builtin_popcountl: 11961 case Builtin::BI__builtin_popcountll: { 11962 APSInt Val; 11963 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11964 return false; 11965 11966 return Success(Val.countPopulation(), E); 11967 } 11968 11969 case Builtin::BI__builtin_rotateleft8: 11970 case Builtin::BI__builtin_rotateleft16: 11971 case Builtin::BI__builtin_rotateleft32: 11972 case Builtin::BI__builtin_rotateleft64: 11973 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11974 case Builtin::BI_rotl16: 11975 case Builtin::BI_rotl: 11976 case Builtin::BI_lrotl: 11977 case Builtin::BI_rotl64: { 11978 APSInt Val, Amt; 11979 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11980 !EvaluateInteger(E->getArg(1), Amt, Info)) 11981 return false; 11982 11983 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11984 } 11985 11986 case Builtin::BI__builtin_rotateright8: 11987 case Builtin::BI__builtin_rotateright16: 11988 case Builtin::BI__builtin_rotateright32: 11989 case Builtin::BI__builtin_rotateright64: 11990 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11991 case Builtin::BI_rotr16: 11992 case Builtin::BI_rotr: 11993 case Builtin::BI_lrotr: 11994 case Builtin::BI_rotr64: { 11995 APSInt Val, Amt; 11996 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11997 !EvaluateInteger(E->getArg(1), Amt, Info)) 11998 return false; 11999 12000 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 12001 } 12002 12003 case Builtin::BIstrlen: 12004 case Builtin::BIwcslen: 12005 // A call to strlen is not a constant expression. 12006 if (Info.getLangOpts().CPlusPlus11) 12007 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12008 << /*isConstexpr*/0 << /*isConstructor*/0 12009 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 12010 else 12011 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12012 LLVM_FALLTHROUGH; 12013 case Builtin::BI__builtin_strlen: 12014 case Builtin::BI__builtin_wcslen: { 12015 // As an extension, we support __builtin_strlen() as a constant expression, 12016 // and support folding strlen() to a constant. 12017 uint64_t StrLen; 12018 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 12019 return Success(StrLen, E); 12020 return false; 12021 } 12022 12023 case Builtin::BIstrcmp: 12024 case Builtin::BIwcscmp: 12025 case Builtin::BIstrncmp: 12026 case Builtin::BIwcsncmp: 12027 case Builtin::BImemcmp: 12028 case Builtin::BIbcmp: 12029 case Builtin::BIwmemcmp: 12030 // A call to strlen is not a constant expression. 12031 if (Info.getLangOpts().CPlusPlus11) 12032 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12033 << /*isConstexpr*/0 << /*isConstructor*/0 12034 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 12035 else 12036 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12037 LLVM_FALLTHROUGH; 12038 case Builtin::BI__builtin_strcmp: 12039 case Builtin::BI__builtin_wcscmp: 12040 case Builtin::BI__builtin_strncmp: 12041 case Builtin::BI__builtin_wcsncmp: 12042 case Builtin::BI__builtin_memcmp: 12043 case Builtin::BI__builtin_bcmp: 12044 case Builtin::BI__builtin_wmemcmp: { 12045 LValue String1, String2; 12046 if (!EvaluatePointer(E->getArg(0), String1, Info) || 12047 !EvaluatePointer(E->getArg(1), String2, Info)) 12048 return false; 12049 12050 uint64_t MaxLength = uint64_t(-1); 12051 if (BuiltinOp != Builtin::BIstrcmp && 12052 BuiltinOp != Builtin::BIwcscmp && 12053 BuiltinOp != Builtin::BI__builtin_strcmp && 12054 BuiltinOp != Builtin::BI__builtin_wcscmp) { 12055 APSInt N; 12056 if (!EvaluateInteger(E->getArg(2), N, Info)) 12057 return false; 12058 MaxLength = N.getExtValue(); 12059 } 12060 12061 // Empty substrings compare equal by definition. 12062 if (MaxLength == 0u) 12063 return Success(0, E); 12064 12065 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12066 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12067 String1.Designator.Invalid || String2.Designator.Invalid) 12068 return false; 12069 12070 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 12071 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 12072 12073 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 12074 BuiltinOp == Builtin::BIbcmp || 12075 BuiltinOp == Builtin::BI__builtin_memcmp || 12076 BuiltinOp == Builtin::BI__builtin_bcmp; 12077 12078 assert(IsRawByte || 12079 (Info.Ctx.hasSameUnqualifiedType( 12080 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 12081 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 12082 12083 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 12084 // 'char8_t', but no other types. 12085 if (IsRawByte && 12086 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 12087 // FIXME: Consider using our bit_cast implementation to support this. 12088 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 12089 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 12090 << CharTy1 << CharTy2; 12091 return false; 12092 } 12093 12094 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 12095 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 12096 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 12097 Char1.isInt() && Char2.isInt(); 12098 }; 12099 const auto &AdvanceElems = [&] { 12100 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 12101 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 12102 }; 12103 12104 bool StopAtNull = 12105 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 12106 BuiltinOp != Builtin::BIwmemcmp && 12107 BuiltinOp != Builtin::BI__builtin_memcmp && 12108 BuiltinOp != Builtin::BI__builtin_bcmp && 12109 BuiltinOp != Builtin::BI__builtin_wmemcmp); 12110 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 12111 BuiltinOp == Builtin::BIwcsncmp || 12112 BuiltinOp == Builtin::BIwmemcmp || 12113 BuiltinOp == Builtin::BI__builtin_wcscmp || 12114 BuiltinOp == Builtin::BI__builtin_wcsncmp || 12115 BuiltinOp == Builtin::BI__builtin_wmemcmp; 12116 12117 for (; MaxLength; --MaxLength) { 12118 APValue Char1, Char2; 12119 if (!ReadCurElems(Char1, Char2)) 12120 return false; 12121 if (Char1.getInt().ne(Char2.getInt())) { 12122 if (IsWide) // wmemcmp compares with wchar_t signedness. 12123 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 12124 // memcmp always compares unsigned chars. 12125 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 12126 } 12127 if (StopAtNull && !Char1.getInt()) 12128 return Success(0, E); 12129 assert(!(StopAtNull && !Char2.getInt())); 12130 if (!AdvanceElems()) 12131 return false; 12132 } 12133 // We hit the strncmp / memcmp limit. 12134 return Success(0, E); 12135 } 12136 12137 case Builtin::BI__atomic_always_lock_free: 12138 case Builtin::BI__atomic_is_lock_free: 12139 case Builtin::BI__c11_atomic_is_lock_free: { 12140 APSInt SizeVal; 12141 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 12142 return false; 12143 12144 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12145 // of two less than or equal to the maximum inline atomic width, we know it 12146 // is lock-free. If the size isn't a power of two, or greater than the 12147 // maximum alignment where we promote atomics, we know it is not lock-free 12148 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12149 // the answer can only be determined at runtime; for example, 16-byte 12150 // atomics have lock-free implementations on some, but not all, 12151 // x86-64 processors. 12152 12153 // Check power-of-two. 12154 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12155 if (Size.isPowerOfTwo()) { 12156 // Check against inlining width. 12157 unsigned InlineWidthBits = 12158 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12159 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12160 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12161 Size == CharUnits::One() || 12162 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12163 Expr::NPC_NeverValueDependent)) 12164 // OK, we will inline appropriately-aligned operations of this size, 12165 // and _Atomic(T) is appropriately-aligned. 12166 return Success(1, E); 12167 12168 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12169 castAs<PointerType>()->getPointeeType(); 12170 if (!PointeeType->isIncompleteType() && 12171 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12172 // OK, we will inline operations on this object. 12173 return Success(1, E); 12174 } 12175 } 12176 } 12177 12178 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12179 Success(0, E) : Error(E); 12180 } 12181 case Builtin::BI__builtin_add_overflow: 12182 case Builtin::BI__builtin_sub_overflow: 12183 case Builtin::BI__builtin_mul_overflow: 12184 case Builtin::BI__builtin_sadd_overflow: 12185 case Builtin::BI__builtin_uadd_overflow: 12186 case Builtin::BI__builtin_uaddl_overflow: 12187 case Builtin::BI__builtin_uaddll_overflow: 12188 case Builtin::BI__builtin_usub_overflow: 12189 case Builtin::BI__builtin_usubl_overflow: 12190 case Builtin::BI__builtin_usubll_overflow: 12191 case Builtin::BI__builtin_umul_overflow: 12192 case Builtin::BI__builtin_umull_overflow: 12193 case Builtin::BI__builtin_umulll_overflow: 12194 case Builtin::BI__builtin_saddl_overflow: 12195 case Builtin::BI__builtin_saddll_overflow: 12196 case Builtin::BI__builtin_ssub_overflow: 12197 case Builtin::BI__builtin_ssubl_overflow: 12198 case Builtin::BI__builtin_ssubll_overflow: 12199 case Builtin::BI__builtin_smul_overflow: 12200 case Builtin::BI__builtin_smull_overflow: 12201 case Builtin::BI__builtin_smulll_overflow: { 12202 LValue ResultLValue; 12203 APSInt LHS, RHS; 12204 12205 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12206 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12207 !EvaluateInteger(E->getArg(1), RHS, Info) || 12208 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12209 return false; 12210 12211 APSInt Result; 12212 bool DidOverflow = false; 12213 12214 // If the types don't have to match, enlarge all 3 to the largest of them. 12215 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12216 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12217 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12218 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12219 ResultType->isSignedIntegerOrEnumerationType(); 12220 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12221 ResultType->isSignedIntegerOrEnumerationType(); 12222 uint64_t LHSSize = LHS.getBitWidth(); 12223 uint64_t RHSSize = RHS.getBitWidth(); 12224 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12225 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12226 12227 // Add an additional bit if the signedness isn't uniformly agreed to. We 12228 // could do this ONLY if there is a signed and an unsigned that both have 12229 // MaxBits, but the code to check that is pretty nasty. The issue will be 12230 // caught in the shrink-to-result later anyway. 12231 if (IsSigned && !AllSigned) 12232 ++MaxBits; 12233 12234 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12235 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12236 Result = APSInt(MaxBits, !IsSigned); 12237 } 12238 12239 // Find largest int. 12240 switch (BuiltinOp) { 12241 default: 12242 llvm_unreachable("Invalid value for BuiltinOp"); 12243 case Builtin::BI__builtin_add_overflow: 12244 case Builtin::BI__builtin_sadd_overflow: 12245 case Builtin::BI__builtin_saddl_overflow: 12246 case Builtin::BI__builtin_saddll_overflow: 12247 case Builtin::BI__builtin_uadd_overflow: 12248 case Builtin::BI__builtin_uaddl_overflow: 12249 case Builtin::BI__builtin_uaddll_overflow: 12250 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12251 : LHS.uadd_ov(RHS, DidOverflow); 12252 break; 12253 case Builtin::BI__builtin_sub_overflow: 12254 case Builtin::BI__builtin_ssub_overflow: 12255 case Builtin::BI__builtin_ssubl_overflow: 12256 case Builtin::BI__builtin_ssubll_overflow: 12257 case Builtin::BI__builtin_usub_overflow: 12258 case Builtin::BI__builtin_usubl_overflow: 12259 case Builtin::BI__builtin_usubll_overflow: 12260 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12261 : LHS.usub_ov(RHS, DidOverflow); 12262 break; 12263 case Builtin::BI__builtin_mul_overflow: 12264 case Builtin::BI__builtin_smul_overflow: 12265 case Builtin::BI__builtin_smull_overflow: 12266 case Builtin::BI__builtin_smulll_overflow: 12267 case Builtin::BI__builtin_umul_overflow: 12268 case Builtin::BI__builtin_umull_overflow: 12269 case Builtin::BI__builtin_umulll_overflow: 12270 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12271 : LHS.umul_ov(RHS, DidOverflow); 12272 break; 12273 } 12274 12275 // In the case where multiple sizes are allowed, truncate and see if 12276 // the values are the same. 12277 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12278 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12279 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12280 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12281 // since it will give us the behavior of a TruncOrSelf in the case where 12282 // its parameter <= its size. We previously set Result to be at least the 12283 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12284 // will work exactly like TruncOrSelf. 12285 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12286 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12287 12288 if (!APSInt::isSameValue(Temp, Result)) 12289 DidOverflow = true; 12290 Result = Temp; 12291 } 12292 12293 APValue APV{Result}; 12294 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12295 return false; 12296 return Success(DidOverflow, E); 12297 } 12298 } 12299 } 12300 12301 /// Determine whether this is a pointer past the end of the complete 12302 /// object referred to by the lvalue. 12303 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12304 const LValue &LV) { 12305 // A null pointer can be viewed as being "past the end" but we don't 12306 // choose to look at it that way here. 12307 if (!LV.getLValueBase()) 12308 return false; 12309 12310 // If the designator is valid and refers to a subobject, we're not pointing 12311 // past the end. 12312 if (!LV.getLValueDesignator().Invalid && 12313 !LV.getLValueDesignator().isOnePastTheEnd()) 12314 return false; 12315 12316 // A pointer to an incomplete type might be past-the-end if the type's size is 12317 // zero. We cannot tell because the type is incomplete. 12318 QualType Ty = getType(LV.getLValueBase()); 12319 if (Ty->isIncompleteType()) 12320 return true; 12321 12322 // We're a past-the-end pointer if we point to the byte after the object, 12323 // no matter what our type or path is. 12324 auto Size = Ctx.getTypeSizeInChars(Ty); 12325 return LV.getLValueOffset() == Size; 12326 } 12327 12328 namespace { 12329 12330 /// Data recursive integer evaluator of certain binary operators. 12331 /// 12332 /// We use a data recursive algorithm for binary operators so that we are able 12333 /// to handle extreme cases of chained binary operators without causing stack 12334 /// overflow. 12335 class DataRecursiveIntBinOpEvaluator { 12336 struct EvalResult { 12337 APValue Val; 12338 bool Failed; 12339 12340 EvalResult() : Failed(false) { } 12341 12342 void swap(EvalResult &RHS) { 12343 Val.swap(RHS.Val); 12344 Failed = RHS.Failed; 12345 RHS.Failed = false; 12346 } 12347 }; 12348 12349 struct Job { 12350 const Expr *E; 12351 EvalResult LHSResult; // meaningful only for binary operator expression. 12352 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12353 12354 Job() = default; 12355 Job(Job &&) = default; 12356 12357 void startSpeculativeEval(EvalInfo &Info) { 12358 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12359 } 12360 12361 private: 12362 SpeculativeEvaluationRAII SpecEvalRAII; 12363 }; 12364 12365 SmallVector<Job, 16> Queue; 12366 12367 IntExprEvaluator &IntEval; 12368 EvalInfo &Info; 12369 APValue &FinalResult; 12370 12371 public: 12372 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12373 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12374 12375 /// True if \param E is a binary operator that we are going to handle 12376 /// data recursively. 12377 /// We handle binary operators that are comma, logical, or that have operands 12378 /// with integral or enumeration type. 12379 static bool shouldEnqueue(const BinaryOperator *E) { 12380 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12381 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12382 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12383 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12384 } 12385 12386 bool Traverse(const BinaryOperator *E) { 12387 enqueue(E); 12388 EvalResult PrevResult; 12389 while (!Queue.empty()) 12390 process(PrevResult); 12391 12392 if (PrevResult.Failed) return false; 12393 12394 FinalResult.swap(PrevResult.Val); 12395 return true; 12396 } 12397 12398 private: 12399 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12400 return IntEval.Success(Value, E, Result); 12401 } 12402 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12403 return IntEval.Success(Value, E, Result); 12404 } 12405 bool Error(const Expr *E) { 12406 return IntEval.Error(E); 12407 } 12408 bool Error(const Expr *E, diag::kind D) { 12409 return IntEval.Error(E, D); 12410 } 12411 12412 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12413 return Info.CCEDiag(E, D); 12414 } 12415 12416 // Returns true if visiting the RHS is necessary, false otherwise. 12417 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12418 bool &SuppressRHSDiags); 12419 12420 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12421 const BinaryOperator *E, APValue &Result); 12422 12423 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12424 Result.Failed = !Evaluate(Result.Val, Info, E); 12425 if (Result.Failed) 12426 Result.Val = APValue(); 12427 } 12428 12429 void process(EvalResult &Result); 12430 12431 void enqueue(const Expr *E) { 12432 E = E->IgnoreParens(); 12433 Queue.resize(Queue.size()+1); 12434 Queue.back().E = E; 12435 Queue.back().Kind = Job::AnyExprKind; 12436 } 12437 }; 12438 12439 } 12440 12441 bool DataRecursiveIntBinOpEvaluator:: 12442 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12443 bool &SuppressRHSDiags) { 12444 if (E->getOpcode() == BO_Comma) { 12445 // Ignore LHS but note if we could not evaluate it. 12446 if (LHSResult.Failed) 12447 return Info.noteSideEffect(); 12448 return true; 12449 } 12450 12451 if (E->isLogicalOp()) { 12452 bool LHSAsBool; 12453 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12454 // We were able to evaluate the LHS, see if we can get away with not 12455 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12456 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12457 Success(LHSAsBool, E, LHSResult.Val); 12458 return false; // Ignore RHS 12459 } 12460 } else { 12461 LHSResult.Failed = true; 12462 12463 // Since we weren't able to evaluate the left hand side, it 12464 // might have had side effects. 12465 if (!Info.noteSideEffect()) 12466 return false; 12467 12468 // We can't evaluate the LHS; however, sometimes the result 12469 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12470 // Don't ignore RHS and suppress diagnostics from this arm. 12471 SuppressRHSDiags = true; 12472 } 12473 12474 return true; 12475 } 12476 12477 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12478 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12479 12480 if (LHSResult.Failed && !Info.noteFailure()) 12481 return false; // Ignore RHS; 12482 12483 return true; 12484 } 12485 12486 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12487 bool IsSub) { 12488 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12489 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12490 // offsets. 12491 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12492 CharUnits &Offset = LVal.getLValueOffset(); 12493 uint64_t Offset64 = Offset.getQuantity(); 12494 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12495 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12496 : Offset64 + Index64); 12497 } 12498 12499 bool DataRecursiveIntBinOpEvaluator:: 12500 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12501 const BinaryOperator *E, APValue &Result) { 12502 if (E->getOpcode() == BO_Comma) { 12503 if (RHSResult.Failed) 12504 return false; 12505 Result = RHSResult.Val; 12506 return true; 12507 } 12508 12509 if (E->isLogicalOp()) { 12510 bool lhsResult, rhsResult; 12511 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12512 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12513 12514 if (LHSIsOK) { 12515 if (RHSIsOK) { 12516 if (E->getOpcode() == BO_LOr) 12517 return Success(lhsResult || rhsResult, E, Result); 12518 else 12519 return Success(lhsResult && rhsResult, E, Result); 12520 } 12521 } else { 12522 if (RHSIsOK) { 12523 // We can't evaluate the LHS; however, sometimes the result 12524 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12525 if (rhsResult == (E->getOpcode() == BO_LOr)) 12526 return Success(rhsResult, E, Result); 12527 } 12528 } 12529 12530 return false; 12531 } 12532 12533 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12534 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12535 12536 if (LHSResult.Failed || RHSResult.Failed) 12537 return false; 12538 12539 const APValue &LHSVal = LHSResult.Val; 12540 const APValue &RHSVal = RHSResult.Val; 12541 12542 // Handle cases like (unsigned long)&a + 4. 12543 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12544 Result = LHSVal; 12545 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12546 return true; 12547 } 12548 12549 // Handle cases like 4 + (unsigned long)&a 12550 if (E->getOpcode() == BO_Add && 12551 RHSVal.isLValue() && LHSVal.isInt()) { 12552 Result = RHSVal; 12553 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12554 return true; 12555 } 12556 12557 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12558 // Handle (intptr_t)&&A - (intptr_t)&&B. 12559 if (!LHSVal.getLValueOffset().isZero() || 12560 !RHSVal.getLValueOffset().isZero()) 12561 return false; 12562 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12563 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12564 if (!LHSExpr || !RHSExpr) 12565 return false; 12566 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12567 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12568 if (!LHSAddrExpr || !RHSAddrExpr) 12569 return false; 12570 // Make sure both labels come from the same function. 12571 if (LHSAddrExpr->getLabel()->getDeclContext() != 12572 RHSAddrExpr->getLabel()->getDeclContext()) 12573 return false; 12574 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12575 return true; 12576 } 12577 12578 // All the remaining cases expect both operands to be an integer 12579 if (!LHSVal.isInt() || !RHSVal.isInt()) 12580 return Error(E); 12581 12582 // Set up the width and signedness manually, in case it can't be deduced 12583 // from the operation we're performing. 12584 // FIXME: Don't do this in the cases where we can deduce it. 12585 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12586 E->getType()->isUnsignedIntegerOrEnumerationType()); 12587 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12588 RHSVal.getInt(), Value)) 12589 return false; 12590 return Success(Value, E, Result); 12591 } 12592 12593 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12594 Job &job = Queue.back(); 12595 12596 switch (job.Kind) { 12597 case Job::AnyExprKind: { 12598 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12599 if (shouldEnqueue(Bop)) { 12600 job.Kind = Job::BinOpKind; 12601 enqueue(Bop->getLHS()); 12602 return; 12603 } 12604 } 12605 12606 EvaluateExpr(job.E, Result); 12607 Queue.pop_back(); 12608 return; 12609 } 12610 12611 case Job::BinOpKind: { 12612 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12613 bool SuppressRHSDiags = false; 12614 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12615 Queue.pop_back(); 12616 return; 12617 } 12618 if (SuppressRHSDiags) 12619 job.startSpeculativeEval(Info); 12620 job.LHSResult.swap(Result); 12621 job.Kind = Job::BinOpVisitedLHSKind; 12622 enqueue(Bop->getRHS()); 12623 return; 12624 } 12625 12626 case Job::BinOpVisitedLHSKind: { 12627 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12628 EvalResult RHS; 12629 RHS.swap(Result); 12630 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12631 Queue.pop_back(); 12632 return; 12633 } 12634 } 12635 12636 llvm_unreachable("Invalid Job::Kind!"); 12637 } 12638 12639 namespace { 12640 enum class CmpResult { 12641 Unequal, 12642 Less, 12643 Equal, 12644 Greater, 12645 Unordered, 12646 }; 12647 } 12648 12649 template <class SuccessCB, class AfterCB> 12650 static bool 12651 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12652 SuccessCB &&Success, AfterCB &&DoAfter) { 12653 assert(!E->isValueDependent()); 12654 assert(E->isComparisonOp() && "expected comparison operator"); 12655 assert((E->getOpcode() == BO_Cmp || 12656 E->getType()->isIntegralOrEnumerationType()) && 12657 "unsupported binary expression evaluation"); 12658 auto Error = [&](const Expr *E) { 12659 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12660 return false; 12661 }; 12662 12663 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12664 bool IsEquality = E->isEqualityOp(); 12665 12666 QualType LHSTy = E->getLHS()->getType(); 12667 QualType RHSTy = E->getRHS()->getType(); 12668 12669 if (LHSTy->isIntegralOrEnumerationType() && 12670 RHSTy->isIntegralOrEnumerationType()) { 12671 APSInt LHS, RHS; 12672 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12673 if (!LHSOK && !Info.noteFailure()) 12674 return false; 12675 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12676 return false; 12677 if (LHS < RHS) 12678 return Success(CmpResult::Less, E); 12679 if (LHS > RHS) 12680 return Success(CmpResult::Greater, E); 12681 return Success(CmpResult::Equal, E); 12682 } 12683 12684 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12685 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12686 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12687 12688 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12689 if (!LHSOK && !Info.noteFailure()) 12690 return false; 12691 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12692 return false; 12693 if (LHSFX < RHSFX) 12694 return Success(CmpResult::Less, E); 12695 if (LHSFX > RHSFX) 12696 return Success(CmpResult::Greater, E); 12697 return Success(CmpResult::Equal, E); 12698 } 12699 12700 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12701 ComplexValue LHS, RHS; 12702 bool LHSOK; 12703 if (E->isAssignmentOp()) { 12704 LValue LV; 12705 EvaluateLValue(E->getLHS(), LV, Info); 12706 LHSOK = false; 12707 } else if (LHSTy->isRealFloatingType()) { 12708 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12709 if (LHSOK) { 12710 LHS.makeComplexFloat(); 12711 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12712 } 12713 } else { 12714 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12715 } 12716 if (!LHSOK && !Info.noteFailure()) 12717 return false; 12718 12719 if (E->getRHS()->getType()->isRealFloatingType()) { 12720 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12721 return false; 12722 RHS.makeComplexFloat(); 12723 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12724 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12725 return false; 12726 12727 if (LHS.isComplexFloat()) { 12728 APFloat::cmpResult CR_r = 12729 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12730 APFloat::cmpResult CR_i = 12731 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12732 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12733 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12734 } else { 12735 assert(IsEquality && "invalid complex comparison"); 12736 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12737 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12738 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12739 } 12740 } 12741 12742 if (LHSTy->isRealFloatingType() && 12743 RHSTy->isRealFloatingType()) { 12744 APFloat RHS(0.0), LHS(0.0); 12745 12746 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12747 if (!LHSOK && !Info.noteFailure()) 12748 return false; 12749 12750 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12751 return false; 12752 12753 assert(E->isComparisonOp() && "Invalid binary operator!"); 12754 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12755 if (!Info.InConstantContext && 12756 APFloatCmpResult == APFloat::cmpUnordered && 12757 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12758 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12759 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12760 return false; 12761 } 12762 auto GetCmpRes = [&]() { 12763 switch (APFloatCmpResult) { 12764 case APFloat::cmpEqual: 12765 return CmpResult::Equal; 12766 case APFloat::cmpLessThan: 12767 return CmpResult::Less; 12768 case APFloat::cmpGreaterThan: 12769 return CmpResult::Greater; 12770 case APFloat::cmpUnordered: 12771 return CmpResult::Unordered; 12772 } 12773 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12774 }; 12775 return Success(GetCmpRes(), E); 12776 } 12777 12778 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12779 LValue LHSValue, RHSValue; 12780 12781 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12782 if (!LHSOK && !Info.noteFailure()) 12783 return false; 12784 12785 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12786 return false; 12787 12788 // Reject differing bases from the normal codepath; we special-case 12789 // comparisons to null. 12790 if (!HasSameBase(LHSValue, RHSValue)) { 12791 // Inequalities and subtractions between unrelated pointers have 12792 // unspecified or undefined behavior. 12793 if (!IsEquality) { 12794 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12795 return false; 12796 } 12797 // A constant address may compare equal to the address of a symbol. 12798 // The one exception is that address of an object cannot compare equal 12799 // to a null pointer constant. 12800 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12801 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12802 return Error(E); 12803 // It's implementation-defined whether distinct literals will have 12804 // distinct addresses. In clang, the result of such a comparison is 12805 // unspecified, so it is not a constant expression. However, we do know 12806 // that the address of a literal will be non-null. 12807 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12808 LHSValue.Base && RHSValue.Base) 12809 return Error(E); 12810 // We can't tell whether weak symbols will end up pointing to the same 12811 // object. 12812 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12813 return Error(E); 12814 // We can't compare the address of the start of one object with the 12815 // past-the-end address of another object, per C++ DR1652. 12816 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12817 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12818 (RHSValue.Base && RHSValue.Offset.isZero() && 12819 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12820 return Error(E); 12821 // We can't tell whether an object is at the same address as another 12822 // zero sized object. 12823 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12824 (LHSValue.Base && isZeroSized(RHSValue))) 12825 return Error(E); 12826 return Success(CmpResult::Unequal, E); 12827 } 12828 12829 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12830 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12831 12832 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12833 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12834 12835 // C++11 [expr.rel]p3: 12836 // Pointers to void (after pointer conversions) can be compared, with a 12837 // result defined as follows: If both pointers represent the same 12838 // address or are both the null pointer value, the result is true if the 12839 // operator is <= or >= and false otherwise; otherwise the result is 12840 // unspecified. 12841 // We interpret this as applying to pointers to *cv* void. 12842 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12843 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12844 12845 // C++11 [expr.rel]p2: 12846 // - If two pointers point to non-static data members of the same object, 12847 // or to subobjects or array elements fo such members, recursively, the 12848 // pointer to the later declared member compares greater provided the 12849 // two members have the same access control and provided their class is 12850 // not a union. 12851 // [...] 12852 // - Otherwise pointer comparisons are unspecified. 12853 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12854 bool WasArrayIndex; 12855 unsigned Mismatch = FindDesignatorMismatch( 12856 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12857 // At the point where the designators diverge, the comparison has a 12858 // specified value if: 12859 // - we are comparing array indices 12860 // - we are comparing fields of a union, or fields with the same access 12861 // Otherwise, the result is unspecified and thus the comparison is not a 12862 // constant expression. 12863 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12864 Mismatch < RHSDesignator.Entries.size()) { 12865 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12866 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12867 if (!LF && !RF) 12868 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12869 else if (!LF) 12870 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12871 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12872 << RF->getParent() << RF; 12873 else if (!RF) 12874 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12875 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12876 << LF->getParent() << LF; 12877 else if (!LF->getParent()->isUnion() && 12878 LF->getAccess() != RF->getAccess()) 12879 Info.CCEDiag(E, 12880 diag::note_constexpr_pointer_comparison_differing_access) 12881 << LF << LF->getAccess() << RF << RF->getAccess() 12882 << LF->getParent(); 12883 } 12884 } 12885 12886 // The comparison here must be unsigned, and performed with the same 12887 // width as the pointer. 12888 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12889 uint64_t CompareLHS = LHSOffset.getQuantity(); 12890 uint64_t CompareRHS = RHSOffset.getQuantity(); 12891 assert(PtrSize <= 64 && "Unexpected pointer width"); 12892 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12893 CompareLHS &= Mask; 12894 CompareRHS &= Mask; 12895 12896 // If there is a base and this is a relational operator, we can only 12897 // compare pointers within the object in question; otherwise, the result 12898 // depends on where the object is located in memory. 12899 if (!LHSValue.Base.isNull() && IsRelational) { 12900 QualType BaseTy = getType(LHSValue.Base); 12901 if (BaseTy->isIncompleteType()) 12902 return Error(E); 12903 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12904 uint64_t OffsetLimit = Size.getQuantity(); 12905 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12906 return Error(E); 12907 } 12908 12909 if (CompareLHS < CompareRHS) 12910 return Success(CmpResult::Less, E); 12911 if (CompareLHS > CompareRHS) 12912 return Success(CmpResult::Greater, E); 12913 return Success(CmpResult::Equal, E); 12914 } 12915 12916 if (LHSTy->isMemberPointerType()) { 12917 assert(IsEquality && "unexpected member pointer operation"); 12918 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12919 12920 MemberPtr LHSValue, RHSValue; 12921 12922 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12923 if (!LHSOK && !Info.noteFailure()) 12924 return false; 12925 12926 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12927 return false; 12928 12929 // C++11 [expr.eq]p2: 12930 // If both operands are null, they compare equal. Otherwise if only one is 12931 // null, they compare unequal. 12932 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12933 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12934 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12935 } 12936 12937 // Otherwise if either is a pointer to a virtual member function, the 12938 // result is unspecified. 12939 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12940 if (MD->isVirtual()) 12941 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12942 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12943 if (MD->isVirtual()) 12944 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12945 12946 // Otherwise they compare equal if and only if they would refer to the 12947 // same member of the same most derived object or the same subobject if 12948 // they were dereferenced with a hypothetical object of the associated 12949 // class type. 12950 bool Equal = LHSValue == RHSValue; 12951 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12952 } 12953 12954 if (LHSTy->isNullPtrType()) { 12955 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12956 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12957 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12958 // are compared, the result is true of the operator is <=, >= or ==, and 12959 // false otherwise. 12960 return Success(CmpResult::Equal, E); 12961 } 12962 12963 return DoAfter(); 12964 } 12965 12966 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12967 if (!CheckLiteralType(Info, E)) 12968 return false; 12969 12970 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12971 ComparisonCategoryResult CCR; 12972 switch (CR) { 12973 case CmpResult::Unequal: 12974 llvm_unreachable("should never produce Unequal for three-way comparison"); 12975 case CmpResult::Less: 12976 CCR = ComparisonCategoryResult::Less; 12977 break; 12978 case CmpResult::Equal: 12979 CCR = ComparisonCategoryResult::Equal; 12980 break; 12981 case CmpResult::Greater: 12982 CCR = ComparisonCategoryResult::Greater; 12983 break; 12984 case CmpResult::Unordered: 12985 CCR = ComparisonCategoryResult::Unordered; 12986 break; 12987 } 12988 // Evaluation succeeded. Lookup the information for the comparison category 12989 // type and fetch the VarDecl for the result. 12990 const ComparisonCategoryInfo &CmpInfo = 12991 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12992 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12993 // Check and evaluate the result as a constant expression. 12994 LValue LV; 12995 LV.set(VD); 12996 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12997 return false; 12998 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12999 ConstantExprKind::Normal); 13000 }; 13001 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13002 return ExprEvaluatorBaseTy::VisitBinCmp(E); 13003 }); 13004 } 13005 13006 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13007 // We don't support assignment in C. C++ assignments don't get here because 13008 // assignment is an lvalue in C++. 13009 if (E->isAssignmentOp()) { 13010 Error(E); 13011 if (!Info.noteFailure()) 13012 return false; 13013 } 13014 13015 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 13016 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 13017 13018 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 13019 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 13020 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 13021 13022 if (E->isComparisonOp()) { 13023 // Evaluate builtin binary comparisons by evaluating them as three-way 13024 // comparisons and then translating the result. 13025 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13026 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 13027 "should only produce Unequal for equality comparisons"); 13028 bool IsEqual = CR == CmpResult::Equal, 13029 IsLess = CR == CmpResult::Less, 13030 IsGreater = CR == CmpResult::Greater; 13031 auto Op = E->getOpcode(); 13032 switch (Op) { 13033 default: 13034 llvm_unreachable("unsupported binary operator"); 13035 case BO_EQ: 13036 case BO_NE: 13037 return Success(IsEqual == (Op == BO_EQ), E); 13038 case BO_LT: 13039 return Success(IsLess, E); 13040 case BO_GT: 13041 return Success(IsGreater, E); 13042 case BO_LE: 13043 return Success(IsEqual || IsLess, E); 13044 case BO_GE: 13045 return Success(IsEqual || IsGreater, E); 13046 } 13047 }; 13048 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13049 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13050 }); 13051 } 13052 13053 QualType LHSTy = E->getLHS()->getType(); 13054 QualType RHSTy = E->getRHS()->getType(); 13055 13056 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 13057 E->getOpcode() == BO_Sub) { 13058 LValue LHSValue, RHSValue; 13059 13060 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13061 if (!LHSOK && !Info.noteFailure()) 13062 return false; 13063 13064 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13065 return false; 13066 13067 // Reject differing bases from the normal codepath; we special-case 13068 // comparisons to null. 13069 if (!HasSameBase(LHSValue, RHSValue)) { 13070 // Handle &&A - &&B. 13071 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 13072 return Error(E); 13073 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 13074 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 13075 if (!LHSExpr || !RHSExpr) 13076 return Error(E); 13077 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13078 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13079 if (!LHSAddrExpr || !RHSAddrExpr) 13080 return Error(E); 13081 // Make sure both labels come from the same function. 13082 if (LHSAddrExpr->getLabel()->getDeclContext() != 13083 RHSAddrExpr->getLabel()->getDeclContext()) 13084 return Error(E); 13085 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 13086 } 13087 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13088 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13089 13090 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13091 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13092 13093 // C++11 [expr.add]p6: 13094 // Unless both pointers point to elements of the same array object, or 13095 // one past the last element of the array object, the behavior is 13096 // undefined. 13097 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 13098 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 13099 RHSDesignator)) 13100 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 13101 13102 QualType Type = E->getLHS()->getType(); 13103 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 13104 13105 CharUnits ElementSize; 13106 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 13107 return false; 13108 13109 // As an extension, a type may have zero size (empty struct or union in 13110 // C, array of zero length). Pointer subtraction in such cases has 13111 // undefined behavior, so is not constant. 13112 if (ElementSize.isZero()) { 13113 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 13114 << ElementType; 13115 return false; 13116 } 13117 13118 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 13119 // and produce incorrect results when it overflows. Such behavior 13120 // appears to be non-conforming, but is common, so perhaps we should 13121 // assume the standard intended for such cases to be undefined behavior 13122 // and check for them. 13123 13124 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 13125 // overflow in the final conversion to ptrdiff_t. 13126 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 13127 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 13128 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 13129 false); 13130 APSInt TrueResult = (LHS - RHS) / ElemSize; 13131 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 13132 13133 if (Result.extend(65) != TrueResult && 13134 !HandleOverflow(Info, E, TrueResult, E->getType())) 13135 return false; 13136 return Success(Result, E); 13137 } 13138 13139 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13140 } 13141 13142 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 13143 /// a result as the expression's type. 13144 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13145 const UnaryExprOrTypeTraitExpr *E) { 13146 switch(E->getKind()) { 13147 case UETT_PreferredAlignOf: 13148 case UETT_AlignOf: { 13149 if (E->isArgumentType()) 13150 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13151 E); 13152 else 13153 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13154 E); 13155 } 13156 13157 case UETT_VecStep: { 13158 QualType Ty = E->getTypeOfArgument(); 13159 13160 if (Ty->isVectorType()) { 13161 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13162 13163 // The vec_step built-in functions that take a 3-component 13164 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13165 if (n == 3) 13166 n = 4; 13167 13168 return Success(n, E); 13169 } else 13170 return Success(1, E); 13171 } 13172 13173 case UETT_SizeOf: { 13174 QualType SrcTy = E->getTypeOfArgument(); 13175 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13176 // the result is the size of the referenced type." 13177 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13178 SrcTy = Ref->getPointeeType(); 13179 13180 CharUnits Sizeof; 13181 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13182 return false; 13183 return Success(Sizeof, E); 13184 } 13185 case UETT_OpenMPRequiredSimdAlign: 13186 assert(E->isArgumentType()); 13187 return Success( 13188 Info.Ctx.toCharUnitsFromBits( 13189 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13190 .getQuantity(), 13191 E); 13192 } 13193 13194 llvm_unreachable("unknown expr/type trait"); 13195 } 13196 13197 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13198 CharUnits Result; 13199 unsigned n = OOE->getNumComponents(); 13200 if (n == 0) 13201 return Error(OOE); 13202 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13203 for (unsigned i = 0; i != n; ++i) { 13204 OffsetOfNode ON = OOE->getComponent(i); 13205 switch (ON.getKind()) { 13206 case OffsetOfNode::Array: { 13207 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13208 APSInt IdxResult; 13209 if (!EvaluateInteger(Idx, IdxResult, Info)) 13210 return false; 13211 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13212 if (!AT) 13213 return Error(OOE); 13214 CurrentType = AT->getElementType(); 13215 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13216 Result += IdxResult.getSExtValue() * ElementSize; 13217 break; 13218 } 13219 13220 case OffsetOfNode::Field: { 13221 FieldDecl *MemberDecl = ON.getField(); 13222 const RecordType *RT = CurrentType->getAs<RecordType>(); 13223 if (!RT) 13224 return Error(OOE); 13225 RecordDecl *RD = RT->getDecl(); 13226 if (RD->isInvalidDecl()) return false; 13227 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13228 unsigned i = MemberDecl->getFieldIndex(); 13229 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13230 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13231 CurrentType = MemberDecl->getType().getNonReferenceType(); 13232 break; 13233 } 13234 13235 case OffsetOfNode::Identifier: 13236 llvm_unreachable("dependent __builtin_offsetof"); 13237 13238 case OffsetOfNode::Base: { 13239 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13240 if (BaseSpec->isVirtual()) 13241 return Error(OOE); 13242 13243 // Find the layout of the class whose base we are looking into. 13244 const RecordType *RT = CurrentType->getAs<RecordType>(); 13245 if (!RT) 13246 return Error(OOE); 13247 RecordDecl *RD = RT->getDecl(); 13248 if (RD->isInvalidDecl()) return false; 13249 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13250 13251 // Find the base class itself. 13252 CurrentType = BaseSpec->getType(); 13253 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13254 if (!BaseRT) 13255 return Error(OOE); 13256 13257 // Add the offset to the base. 13258 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13259 break; 13260 } 13261 } 13262 } 13263 return Success(Result, OOE); 13264 } 13265 13266 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13267 switch (E->getOpcode()) { 13268 default: 13269 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13270 // See C99 6.6p3. 13271 return Error(E); 13272 case UO_Extension: 13273 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13274 // If so, we could clear the diagnostic ID. 13275 return Visit(E->getSubExpr()); 13276 case UO_Plus: 13277 // The result is just the value. 13278 return Visit(E->getSubExpr()); 13279 case UO_Minus: { 13280 if (!Visit(E->getSubExpr())) 13281 return false; 13282 if (!Result.isInt()) return Error(E); 13283 const APSInt &Value = Result.getInt(); 13284 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13285 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13286 E->getType())) 13287 return false; 13288 return Success(-Value, E); 13289 } 13290 case UO_Not: { 13291 if (!Visit(E->getSubExpr())) 13292 return false; 13293 if (!Result.isInt()) return Error(E); 13294 return Success(~Result.getInt(), E); 13295 } 13296 case UO_LNot: { 13297 bool bres; 13298 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13299 return false; 13300 return Success(!bres, E); 13301 } 13302 } 13303 } 13304 13305 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13306 /// result type is integer. 13307 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13308 const Expr *SubExpr = E->getSubExpr(); 13309 QualType DestType = E->getType(); 13310 QualType SrcType = SubExpr->getType(); 13311 13312 switch (E->getCastKind()) { 13313 case CK_BaseToDerived: 13314 case CK_DerivedToBase: 13315 case CK_UncheckedDerivedToBase: 13316 case CK_Dynamic: 13317 case CK_ToUnion: 13318 case CK_ArrayToPointerDecay: 13319 case CK_FunctionToPointerDecay: 13320 case CK_NullToPointer: 13321 case CK_NullToMemberPointer: 13322 case CK_BaseToDerivedMemberPointer: 13323 case CK_DerivedToBaseMemberPointer: 13324 case CK_ReinterpretMemberPointer: 13325 case CK_ConstructorConversion: 13326 case CK_IntegralToPointer: 13327 case CK_ToVoid: 13328 case CK_VectorSplat: 13329 case CK_IntegralToFloating: 13330 case CK_FloatingCast: 13331 case CK_CPointerToObjCPointerCast: 13332 case CK_BlockPointerToObjCPointerCast: 13333 case CK_AnyPointerToBlockPointerCast: 13334 case CK_ObjCObjectLValueCast: 13335 case CK_FloatingRealToComplex: 13336 case CK_FloatingComplexToReal: 13337 case CK_FloatingComplexCast: 13338 case CK_FloatingComplexToIntegralComplex: 13339 case CK_IntegralRealToComplex: 13340 case CK_IntegralComplexCast: 13341 case CK_IntegralComplexToFloatingComplex: 13342 case CK_BuiltinFnToFnPtr: 13343 case CK_ZeroToOCLOpaqueType: 13344 case CK_NonAtomicToAtomic: 13345 case CK_AddressSpaceConversion: 13346 case CK_IntToOCLSampler: 13347 case CK_FloatingToFixedPoint: 13348 case CK_FixedPointToFloating: 13349 case CK_FixedPointCast: 13350 case CK_IntegralToFixedPoint: 13351 case CK_MatrixCast: 13352 llvm_unreachable("invalid cast kind for integral value"); 13353 13354 case CK_BitCast: 13355 case CK_Dependent: 13356 case CK_LValueBitCast: 13357 case CK_ARCProduceObject: 13358 case CK_ARCConsumeObject: 13359 case CK_ARCReclaimReturnedObject: 13360 case CK_ARCExtendBlockObject: 13361 case CK_CopyAndAutoreleaseBlockObject: 13362 return Error(E); 13363 13364 case CK_UserDefinedConversion: 13365 case CK_LValueToRValue: 13366 case CK_AtomicToNonAtomic: 13367 case CK_NoOp: 13368 case CK_LValueToRValueBitCast: 13369 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13370 13371 case CK_MemberPointerToBoolean: 13372 case CK_PointerToBoolean: 13373 case CK_IntegralToBoolean: 13374 case CK_FloatingToBoolean: 13375 case CK_BooleanToSignedIntegral: 13376 case CK_FloatingComplexToBoolean: 13377 case CK_IntegralComplexToBoolean: { 13378 bool BoolResult; 13379 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13380 return false; 13381 uint64_t IntResult = BoolResult; 13382 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13383 IntResult = (uint64_t)-1; 13384 return Success(IntResult, E); 13385 } 13386 13387 case CK_FixedPointToIntegral: { 13388 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13389 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13390 return false; 13391 bool Overflowed; 13392 llvm::APSInt Result = Src.convertToInt( 13393 Info.Ctx.getIntWidth(DestType), 13394 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13395 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13396 return false; 13397 return Success(Result, E); 13398 } 13399 13400 case CK_FixedPointToBoolean: { 13401 // Unsigned padding does not affect this. 13402 APValue Val; 13403 if (!Evaluate(Val, Info, SubExpr)) 13404 return false; 13405 return Success(Val.getFixedPoint().getBoolValue(), E); 13406 } 13407 13408 case CK_IntegralCast: { 13409 if (!Visit(SubExpr)) 13410 return false; 13411 13412 if (!Result.isInt()) { 13413 // Allow casts of address-of-label differences if they are no-ops 13414 // or narrowing. (The narrowing case isn't actually guaranteed to 13415 // be constant-evaluatable except in some narrow cases which are hard 13416 // to detect here. We let it through on the assumption the user knows 13417 // what they are doing.) 13418 if (Result.isAddrLabelDiff()) 13419 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13420 // Only allow casts of lvalues if they are lossless. 13421 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13422 } 13423 13424 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13425 Result.getInt()), E); 13426 } 13427 13428 case CK_PointerToIntegral: { 13429 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13430 13431 LValue LV; 13432 if (!EvaluatePointer(SubExpr, LV, Info)) 13433 return false; 13434 13435 if (LV.getLValueBase()) { 13436 // Only allow based lvalue casts if they are lossless. 13437 // FIXME: Allow a larger integer size than the pointer size, and allow 13438 // narrowing back down to pointer width in subsequent integral casts. 13439 // FIXME: Check integer type's active bits, not its type size. 13440 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13441 return Error(E); 13442 13443 LV.Designator.setInvalid(); 13444 LV.moveInto(Result); 13445 return true; 13446 } 13447 13448 APSInt AsInt; 13449 APValue V; 13450 LV.moveInto(V); 13451 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13452 llvm_unreachable("Can't cast this!"); 13453 13454 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13455 } 13456 13457 case CK_IntegralComplexToReal: { 13458 ComplexValue C; 13459 if (!EvaluateComplex(SubExpr, C, Info)) 13460 return false; 13461 return Success(C.getComplexIntReal(), E); 13462 } 13463 13464 case CK_FloatingToIntegral: { 13465 APFloat F(0.0); 13466 if (!EvaluateFloat(SubExpr, F, Info)) 13467 return false; 13468 13469 APSInt Value; 13470 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13471 return false; 13472 return Success(Value, E); 13473 } 13474 } 13475 13476 llvm_unreachable("unknown cast resulting in integral value"); 13477 } 13478 13479 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13480 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13481 ComplexValue LV; 13482 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13483 return false; 13484 if (!LV.isComplexInt()) 13485 return Error(E); 13486 return Success(LV.getComplexIntReal(), E); 13487 } 13488 13489 return Visit(E->getSubExpr()); 13490 } 13491 13492 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13493 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13494 ComplexValue LV; 13495 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13496 return false; 13497 if (!LV.isComplexInt()) 13498 return Error(E); 13499 return Success(LV.getComplexIntImag(), E); 13500 } 13501 13502 VisitIgnoredValue(E->getSubExpr()); 13503 return Success(0, E); 13504 } 13505 13506 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13507 return Success(E->getPackLength(), E); 13508 } 13509 13510 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13511 return Success(E->getValue(), E); 13512 } 13513 13514 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13515 const ConceptSpecializationExpr *E) { 13516 return Success(E->isSatisfied(), E); 13517 } 13518 13519 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13520 return Success(E->isSatisfied(), E); 13521 } 13522 13523 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13524 switch (E->getOpcode()) { 13525 default: 13526 // Invalid unary operators 13527 return Error(E); 13528 case UO_Plus: 13529 // The result is just the value. 13530 return Visit(E->getSubExpr()); 13531 case UO_Minus: { 13532 if (!Visit(E->getSubExpr())) return false; 13533 if (!Result.isFixedPoint()) 13534 return Error(E); 13535 bool Overflowed; 13536 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13537 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13538 return false; 13539 return Success(Negated, E); 13540 } 13541 case UO_LNot: { 13542 bool bres; 13543 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13544 return false; 13545 return Success(!bres, E); 13546 } 13547 } 13548 } 13549 13550 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13551 const Expr *SubExpr = E->getSubExpr(); 13552 QualType DestType = E->getType(); 13553 assert(DestType->isFixedPointType() && 13554 "Expected destination type to be a fixed point type"); 13555 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13556 13557 switch (E->getCastKind()) { 13558 case CK_FixedPointCast: { 13559 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13560 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13561 return false; 13562 bool Overflowed; 13563 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13564 if (Overflowed) { 13565 if (Info.checkingForUndefinedBehavior()) 13566 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13567 diag::warn_fixedpoint_constant_overflow) 13568 << Result.toString() << E->getType(); 13569 if (!HandleOverflow(Info, E, Result, E->getType())) 13570 return false; 13571 } 13572 return Success(Result, E); 13573 } 13574 case CK_IntegralToFixedPoint: { 13575 APSInt Src; 13576 if (!EvaluateInteger(SubExpr, Src, Info)) 13577 return false; 13578 13579 bool Overflowed; 13580 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13581 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13582 13583 if (Overflowed) { 13584 if (Info.checkingForUndefinedBehavior()) 13585 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13586 diag::warn_fixedpoint_constant_overflow) 13587 << IntResult.toString() << E->getType(); 13588 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13589 return false; 13590 } 13591 13592 return Success(IntResult, E); 13593 } 13594 case CK_FloatingToFixedPoint: { 13595 APFloat Src(0.0); 13596 if (!EvaluateFloat(SubExpr, Src, Info)) 13597 return false; 13598 13599 bool Overflowed; 13600 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13601 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13602 13603 if (Overflowed) { 13604 if (Info.checkingForUndefinedBehavior()) 13605 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13606 diag::warn_fixedpoint_constant_overflow) 13607 << Result.toString() << E->getType(); 13608 if (!HandleOverflow(Info, E, Result, E->getType())) 13609 return false; 13610 } 13611 13612 return Success(Result, E); 13613 } 13614 case CK_NoOp: 13615 case CK_LValueToRValue: 13616 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13617 default: 13618 return Error(E); 13619 } 13620 } 13621 13622 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13623 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13624 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13625 13626 const Expr *LHS = E->getLHS(); 13627 const Expr *RHS = E->getRHS(); 13628 FixedPointSemantics ResultFXSema = 13629 Info.Ctx.getFixedPointSemantics(E->getType()); 13630 13631 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13632 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13633 return false; 13634 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13635 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13636 return false; 13637 13638 bool OpOverflow = false, ConversionOverflow = false; 13639 APFixedPoint Result(LHSFX.getSemantics()); 13640 switch (E->getOpcode()) { 13641 case BO_Add: { 13642 Result = LHSFX.add(RHSFX, &OpOverflow) 13643 .convert(ResultFXSema, &ConversionOverflow); 13644 break; 13645 } 13646 case BO_Sub: { 13647 Result = LHSFX.sub(RHSFX, &OpOverflow) 13648 .convert(ResultFXSema, &ConversionOverflow); 13649 break; 13650 } 13651 case BO_Mul: { 13652 Result = LHSFX.mul(RHSFX, &OpOverflow) 13653 .convert(ResultFXSema, &ConversionOverflow); 13654 break; 13655 } 13656 case BO_Div: { 13657 if (RHSFX.getValue() == 0) { 13658 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13659 return false; 13660 } 13661 Result = LHSFX.div(RHSFX, &OpOverflow) 13662 .convert(ResultFXSema, &ConversionOverflow); 13663 break; 13664 } 13665 case BO_Shl: 13666 case BO_Shr: { 13667 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13668 llvm::APSInt RHSVal = RHSFX.getValue(); 13669 13670 unsigned ShiftBW = 13671 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13672 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13673 // Embedded-C 4.1.6.2.2: 13674 // The right operand must be nonnegative and less than the total number 13675 // of (nonpadding) bits of the fixed-point operand ... 13676 if (RHSVal.isNegative()) 13677 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13678 else if (Amt != RHSVal) 13679 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13680 << RHSVal << E->getType() << ShiftBW; 13681 13682 if (E->getOpcode() == BO_Shl) 13683 Result = LHSFX.shl(Amt, &OpOverflow); 13684 else 13685 Result = LHSFX.shr(Amt, &OpOverflow); 13686 break; 13687 } 13688 default: 13689 return false; 13690 } 13691 if (OpOverflow || ConversionOverflow) { 13692 if (Info.checkingForUndefinedBehavior()) 13693 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13694 diag::warn_fixedpoint_constant_overflow) 13695 << Result.toString() << E->getType(); 13696 if (!HandleOverflow(Info, E, Result, E->getType())) 13697 return false; 13698 } 13699 return Success(Result, E); 13700 } 13701 13702 //===----------------------------------------------------------------------===// 13703 // Float Evaluation 13704 //===----------------------------------------------------------------------===// 13705 13706 namespace { 13707 class FloatExprEvaluator 13708 : public ExprEvaluatorBase<FloatExprEvaluator> { 13709 APFloat &Result; 13710 public: 13711 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13712 : ExprEvaluatorBaseTy(info), Result(result) {} 13713 13714 bool Success(const APValue &V, const Expr *e) { 13715 Result = V.getFloat(); 13716 return true; 13717 } 13718 13719 bool ZeroInitialization(const Expr *E) { 13720 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13721 return true; 13722 } 13723 13724 bool VisitCallExpr(const CallExpr *E); 13725 13726 bool VisitUnaryOperator(const UnaryOperator *E); 13727 bool VisitBinaryOperator(const BinaryOperator *E); 13728 bool VisitFloatingLiteral(const FloatingLiteral *E); 13729 bool VisitCastExpr(const CastExpr *E); 13730 13731 bool VisitUnaryReal(const UnaryOperator *E); 13732 bool VisitUnaryImag(const UnaryOperator *E); 13733 13734 // FIXME: Missing: array subscript of vector, member of vector 13735 }; 13736 } // end anonymous namespace 13737 13738 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13739 assert(!E->isValueDependent()); 13740 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 13741 return FloatExprEvaluator(Info, Result).Visit(E); 13742 } 13743 13744 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13745 QualType ResultTy, 13746 const Expr *Arg, 13747 bool SNaN, 13748 llvm::APFloat &Result) { 13749 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13750 if (!S) return false; 13751 13752 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13753 13754 llvm::APInt fill; 13755 13756 // Treat empty strings as if they were zero. 13757 if (S->getString().empty()) 13758 fill = llvm::APInt(32, 0); 13759 else if (S->getString().getAsInteger(0, fill)) 13760 return false; 13761 13762 if (Context.getTargetInfo().isNan2008()) { 13763 if (SNaN) 13764 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13765 else 13766 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13767 } else { 13768 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13769 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13770 // a different encoding to what became a standard in 2008, and for pre- 13771 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13772 // sNaN. This is now known as "legacy NaN" encoding. 13773 if (SNaN) 13774 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13775 else 13776 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13777 } 13778 13779 return true; 13780 } 13781 13782 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13783 switch (E->getBuiltinCallee()) { 13784 default: 13785 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13786 13787 case Builtin::BI__builtin_huge_val: 13788 case Builtin::BI__builtin_huge_valf: 13789 case Builtin::BI__builtin_huge_vall: 13790 case Builtin::BI__builtin_huge_valf128: 13791 case Builtin::BI__builtin_inf: 13792 case Builtin::BI__builtin_inff: 13793 case Builtin::BI__builtin_infl: 13794 case Builtin::BI__builtin_inff128: { 13795 const llvm::fltSemantics &Sem = 13796 Info.Ctx.getFloatTypeSemantics(E->getType()); 13797 Result = llvm::APFloat::getInf(Sem); 13798 return true; 13799 } 13800 13801 case Builtin::BI__builtin_nans: 13802 case Builtin::BI__builtin_nansf: 13803 case Builtin::BI__builtin_nansl: 13804 case Builtin::BI__builtin_nansf128: 13805 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13806 true, Result)) 13807 return Error(E); 13808 return true; 13809 13810 case Builtin::BI__builtin_nan: 13811 case Builtin::BI__builtin_nanf: 13812 case Builtin::BI__builtin_nanl: 13813 case Builtin::BI__builtin_nanf128: 13814 // If this is __builtin_nan() turn this into a nan, otherwise we 13815 // can't constant fold it. 13816 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13817 false, Result)) 13818 return Error(E); 13819 return true; 13820 13821 case Builtin::BI__builtin_fabs: 13822 case Builtin::BI__builtin_fabsf: 13823 case Builtin::BI__builtin_fabsl: 13824 case Builtin::BI__builtin_fabsf128: 13825 // The C standard says "fabs raises no floating-point exceptions, 13826 // even if x is a signaling NaN. The returned value is independent of 13827 // the current rounding direction mode." Therefore constant folding can 13828 // proceed without regard to the floating point settings. 13829 // Reference, WG14 N2478 F.10.4.3 13830 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13831 return false; 13832 13833 if (Result.isNegative()) 13834 Result.changeSign(); 13835 return true; 13836 13837 case Builtin::BI__arithmetic_fence: 13838 return EvaluateFloat(E->getArg(0), Result, Info); 13839 13840 // FIXME: Builtin::BI__builtin_powi 13841 // FIXME: Builtin::BI__builtin_powif 13842 // FIXME: Builtin::BI__builtin_powil 13843 13844 case Builtin::BI__builtin_copysign: 13845 case Builtin::BI__builtin_copysignf: 13846 case Builtin::BI__builtin_copysignl: 13847 case Builtin::BI__builtin_copysignf128: { 13848 APFloat RHS(0.); 13849 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13850 !EvaluateFloat(E->getArg(1), RHS, Info)) 13851 return false; 13852 Result.copySign(RHS); 13853 return true; 13854 } 13855 } 13856 } 13857 13858 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13859 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13860 ComplexValue CV; 13861 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13862 return false; 13863 Result = CV.FloatReal; 13864 return true; 13865 } 13866 13867 return Visit(E->getSubExpr()); 13868 } 13869 13870 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13871 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13872 ComplexValue CV; 13873 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13874 return false; 13875 Result = CV.FloatImag; 13876 return true; 13877 } 13878 13879 VisitIgnoredValue(E->getSubExpr()); 13880 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13881 Result = llvm::APFloat::getZero(Sem); 13882 return true; 13883 } 13884 13885 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13886 switch (E->getOpcode()) { 13887 default: return Error(E); 13888 case UO_Plus: 13889 return EvaluateFloat(E->getSubExpr(), Result, Info); 13890 case UO_Minus: 13891 // In C standard, WG14 N2478 F.3 p4 13892 // "the unary - raises no floating point exceptions, 13893 // even if the operand is signalling." 13894 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13895 return false; 13896 Result.changeSign(); 13897 return true; 13898 } 13899 } 13900 13901 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13902 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13903 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13904 13905 APFloat RHS(0.0); 13906 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13907 if (!LHSOK && !Info.noteFailure()) 13908 return false; 13909 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13910 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13911 } 13912 13913 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13914 Result = E->getValue(); 13915 return true; 13916 } 13917 13918 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13919 const Expr* SubExpr = E->getSubExpr(); 13920 13921 switch (E->getCastKind()) { 13922 default: 13923 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13924 13925 case CK_IntegralToFloating: { 13926 APSInt IntResult; 13927 const FPOptions FPO = E->getFPFeaturesInEffect( 13928 Info.Ctx.getLangOpts()); 13929 return EvaluateInteger(SubExpr, IntResult, Info) && 13930 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13931 IntResult, E->getType(), Result); 13932 } 13933 13934 case CK_FixedPointToFloating: { 13935 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13936 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13937 return false; 13938 Result = 13939 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13940 return true; 13941 } 13942 13943 case CK_FloatingCast: { 13944 if (!Visit(SubExpr)) 13945 return false; 13946 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13947 Result); 13948 } 13949 13950 case CK_FloatingComplexToReal: { 13951 ComplexValue V; 13952 if (!EvaluateComplex(SubExpr, V, Info)) 13953 return false; 13954 Result = V.getComplexFloatReal(); 13955 return true; 13956 } 13957 } 13958 } 13959 13960 //===----------------------------------------------------------------------===// 13961 // Complex Evaluation (for float and integer) 13962 //===----------------------------------------------------------------------===// 13963 13964 namespace { 13965 class ComplexExprEvaluator 13966 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13967 ComplexValue &Result; 13968 13969 public: 13970 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13971 : ExprEvaluatorBaseTy(info), Result(Result) {} 13972 13973 bool Success(const APValue &V, const Expr *e) { 13974 Result.setFrom(V); 13975 return true; 13976 } 13977 13978 bool ZeroInitialization(const Expr *E); 13979 13980 //===--------------------------------------------------------------------===// 13981 // Visitor Methods 13982 //===--------------------------------------------------------------------===// 13983 13984 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13985 bool VisitCastExpr(const CastExpr *E); 13986 bool VisitBinaryOperator(const BinaryOperator *E); 13987 bool VisitUnaryOperator(const UnaryOperator *E); 13988 bool VisitInitListExpr(const InitListExpr *E); 13989 bool VisitCallExpr(const CallExpr *E); 13990 }; 13991 } // end anonymous namespace 13992 13993 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13994 EvalInfo &Info) { 13995 assert(!E->isValueDependent()); 13996 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 13997 return ComplexExprEvaluator(Info, Result).Visit(E); 13998 } 13999 14000 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 14001 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 14002 if (ElemTy->isRealFloatingType()) { 14003 Result.makeComplexFloat(); 14004 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 14005 Result.FloatReal = Zero; 14006 Result.FloatImag = Zero; 14007 } else { 14008 Result.makeComplexInt(); 14009 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 14010 Result.IntReal = Zero; 14011 Result.IntImag = Zero; 14012 } 14013 return true; 14014 } 14015 14016 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 14017 const Expr* SubExpr = E->getSubExpr(); 14018 14019 if (SubExpr->getType()->isRealFloatingType()) { 14020 Result.makeComplexFloat(); 14021 APFloat &Imag = Result.FloatImag; 14022 if (!EvaluateFloat(SubExpr, Imag, Info)) 14023 return false; 14024 14025 Result.FloatReal = APFloat(Imag.getSemantics()); 14026 return true; 14027 } else { 14028 assert(SubExpr->getType()->isIntegerType() && 14029 "Unexpected imaginary literal."); 14030 14031 Result.makeComplexInt(); 14032 APSInt &Imag = Result.IntImag; 14033 if (!EvaluateInteger(SubExpr, Imag, Info)) 14034 return false; 14035 14036 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 14037 return true; 14038 } 14039 } 14040 14041 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 14042 14043 switch (E->getCastKind()) { 14044 case CK_BitCast: 14045 case CK_BaseToDerived: 14046 case CK_DerivedToBase: 14047 case CK_UncheckedDerivedToBase: 14048 case CK_Dynamic: 14049 case CK_ToUnion: 14050 case CK_ArrayToPointerDecay: 14051 case CK_FunctionToPointerDecay: 14052 case CK_NullToPointer: 14053 case CK_NullToMemberPointer: 14054 case CK_BaseToDerivedMemberPointer: 14055 case CK_DerivedToBaseMemberPointer: 14056 case CK_MemberPointerToBoolean: 14057 case CK_ReinterpretMemberPointer: 14058 case CK_ConstructorConversion: 14059 case CK_IntegralToPointer: 14060 case CK_PointerToIntegral: 14061 case CK_PointerToBoolean: 14062 case CK_ToVoid: 14063 case CK_VectorSplat: 14064 case CK_IntegralCast: 14065 case CK_BooleanToSignedIntegral: 14066 case CK_IntegralToBoolean: 14067 case CK_IntegralToFloating: 14068 case CK_FloatingToIntegral: 14069 case CK_FloatingToBoolean: 14070 case CK_FloatingCast: 14071 case CK_CPointerToObjCPointerCast: 14072 case CK_BlockPointerToObjCPointerCast: 14073 case CK_AnyPointerToBlockPointerCast: 14074 case CK_ObjCObjectLValueCast: 14075 case CK_FloatingComplexToReal: 14076 case CK_FloatingComplexToBoolean: 14077 case CK_IntegralComplexToReal: 14078 case CK_IntegralComplexToBoolean: 14079 case CK_ARCProduceObject: 14080 case CK_ARCConsumeObject: 14081 case CK_ARCReclaimReturnedObject: 14082 case CK_ARCExtendBlockObject: 14083 case CK_CopyAndAutoreleaseBlockObject: 14084 case CK_BuiltinFnToFnPtr: 14085 case CK_ZeroToOCLOpaqueType: 14086 case CK_NonAtomicToAtomic: 14087 case CK_AddressSpaceConversion: 14088 case CK_IntToOCLSampler: 14089 case CK_FloatingToFixedPoint: 14090 case CK_FixedPointToFloating: 14091 case CK_FixedPointCast: 14092 case CK_FixedPointToBoolean: 14093 case CK_FixedPointToIntegral: 14094 case CK_IntegralToFixedPoint: 14095 case CK_MatrixCast: 14096 llvm_unreachable("invalid cast kind for complex value"); 14097 14098 case CK_LValueToRValue: 14099 case CK_AtomicToNonAtomic: 14100 case CK_NoOp: 14101 case CK_LValueToRValueBitCast: 14102 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14103 14104 case CK_Dependent: 14105 case CK_LValueBitCast: 14106 case CK_UserDefinedConversion: 14107 return Error(E); 14108 14109 case CK_FloatingRealToComplex: { 14110 APFloat &Real = Result.FloatReal; 14111 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 14112 return false; 14113 14114 Result.makeComplexFloat(); 14115 Result.FloatImag = APFloat(Real.getSemantics()); 14116 return true; 14117 } 14118 14119 case CK_FloatingComplexCast: { 14120 if (!Visit(E->getSubExpr())) 14121 return false; 14122 14123 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14124 QualType From 14125 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14126 14127 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 14128 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 14129 } 14130 14131 case CK_FloatingComplexToIntegralComplex: { 14132 if (!Visit(E->getSubExpr())) 14133 return false; 14134 14135 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14136 QualType From 14137 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14138 Result.makeComplexInt(); 14139 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 14140 To, Result.IntReal) && 14141 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 14142 To, Result.IntImag); 14143 } 14144 14145 case CK_IntegralRealToComplex: { 14146 APSInt &Real = Result.IntReal; 14147 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14148 return false; 14149 14150 Result.makeComplexInt(); 14151 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14152 return true; 14153 } 14154 14155 case CK_IntegralComplexCast: { 14156 if (!Visit(E->getSubExpr())) 14157 return false; 14158 14159 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14160 QualType From 14161 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14162 14163 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14164 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14165 return true; 14166 } 14167 14168 case CK_IntegralComplexToFloatingComplex: { 14169 if (!Visit(E->getSubExpr())) 14170 return false; 14171 14172 const FPOptions FPO = E->getFPFeaturesInEffect( 14173 Info.Ctx.getLangOpts()); 14174 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14175 QualType From 14176 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14177 Result.makeComplexFloat(); 14178 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14179 To, Result.FloatReal) && 14180 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14181 To, Result.FloatImag); 14182 } 14183 } 14184 14185 llvm_unreachable("unknown cast resulting in complex value"); 14186 } 14187 14188 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14189 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14190 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14191 14192 // Track whether the LHS or RHS is real at the type system level. When this is 14193 // the case we can simplify our evaluation strategy. 14194 bool LHSReal = false, RHSReal = false; 14195 14196 bool LHSOK; 14197 if (E->getLHS()->getType()->isRealFloatingType()) { 14198 LHSReal = true; 14199 APFloat &Real = Result.FloatReal; 14200 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14201 if (LHSOK) { 14202 Result.makeComplexFloat(); 14203 Result.FloatImag = APFloat(Real.getSemantics()); 14204 } 14205 } else { 14206 LHSOK = Visit(E->getLHS()); 14207 } 14208 if (!LHSOK && !Info.noteFailure()) 14209 return false; 14210 14211 ComplexValue RHS; 14212 if (E->getRHS()->getType()->isRealFloatingType()) { 14213 RHSReal = true; 14214 APFloat &Real = RHS.FloatReal; 14215 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14216 return false; 14217 RHS.makeComplexFloat(); 14218 RHS.FloatImag = APFloat(Real.getSemantics()); 14219 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14220 return false; 14221 14222 assert(!(LHSReal && RHSReal) && 14223 "Cannot have both operands of a complex operation be real."); 14224 switch (E->getOpcode()) { 14225 default: return Error(E); 14226 case BO_Add: 14227 if (Result.isComplexFloat()) { 14228 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14229 APFloat::rmNearestTiesToEven); 14230 if (LHSReal) 14231 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14232 else if (!RHSReal) 14233 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14234 APFloat::rmNearestTiesToEven); 14235 } else { 14236 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14237 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14238 } 14239 break; 14240 case BO_Sub: 14241 if (Result.isComplexFloat()) { 14242 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14243 APFloat::rmNearestTiesToEven); 14244 if (LHSReal) { 14245 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14246 Result.getComplexFloatImag().changeSign(); 14247 } else if (!RHSReal) { 14248 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14249 APFloat::rmNearestTiesToEven); 14250 } 14251 } else { 14252 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14253 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14254 } 14255 break; 14256 case BO_Mul: 14257 if (Result.isComplexFloat()) { 14258 // This is an implementation of complex multiplication according to the 14259 // constraints laid out in C11 Annex G. The implementation uses the 14260 // following naming scheme: 14261 // (a + ib) * (c + id) 14262 ComplexValue LHS = Result; 14263 APFloat &A = LHS.getComplexFloatReal(); 14264 APFloat &B = LHS.getComplexFloatImag(); 14265 APFloat &C = RHS.getComplexFloatReal(); 14266 APFloat &D = RHS.getComplexFloatImag(); 14267 APFloat &ResR = Result.getComplexFloatReal(); 14268 APFloat &ResI = Result.getComplexFloatImag(); 14269 if (LHSReal) { 14270 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14271 ResR = A * C; 14272 ResI = A * D; 14273 } else if (RHSReal) { 14274 ResR = C * A; 14275 ResI = C * B; 14276 } else { 14277 // In the fully general case, we need to handle NaNs and infinities 14278 // robustly. 14279 APFloat AC = A * C; 14280 APFloat BD = B * D; 14281 APFloat AD = A * D; 14282 APFloat BC = B * C; 14283 ResR = AC - BD; 14284 ResI = AD + BC; 14285 if (ResR.isNaN() && ResI.isNaN()) { 14286 bool Recalc = false; 14287 if (A.isInfinity() || B.isInfinity()) { 14288 A = APFloat::copySign( 14289 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14290 B = APFloat::copySign( 14291 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14292 if (C.isNaN()) 14293 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14294 if (D.isNaN()) 14295 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14296 Recalc = true; 14297 } 14298 if (C.isInfinity() || D.isInfinity()) { 14299 C = APFloat::copySign( 14300 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14301 D = APFloat::copySign( 14302 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14303 if (A.isNaN()) 14304 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14305 if (B.isNaN()) 14306 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14307 Recalc = true; 14308 } 14309 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14310 AD.isInfinity() || BC.isInfinity())) { 14311 if (A.isNaN()) 14312 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14313 if (B.isNaN()) 14314 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14315 if (C.isNaN()) 14316 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14317 if (D.isNaN()) 14318 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14319 Recalc = true; 14320 } 14321 if (Recalc) { 14322 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14323 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14324 } 14325 } 14326 } 14327 } else { 14328 ComplexValue LHS = Result; 14329 Result.getComplexIntReal() = 14330 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14331 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14332 Result.getComplexIntImag() = 14333 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14334 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14335 } 14336 break; 14337 case BO_Div: 14338 if (Result.isComplexFloat()) { 14339 // This is an implementation of complex division according to the 14340 // constraints laid out in C11 Annex G. The implementation uses the 14341 // following naming scheme: 14342 // (a + ib) / (c + id) 14343 ComplexValue LHS = Result; 14344 APFloat &A = LHS.getComplexFloatReal(); 14345 APFloat &B = LHS.getComplexFloatImag(); 14346 APFloat &C = RHS.getComplexFloatReal(); 14347 APFloat &D = RHS.getComplexFloatImag(); 14348 APFloat &ResR = Result.getComplexFloatReal(); 14349 APFloat &ResI = Result.getComplexFloatImag(); 14350 if (RHSReal) { 14351 ResR = A / C; 14352 ResI = B / C; 14353 } else { 14354 if (LHSReal) { 14355 // No real optimizations we can do here, stub out with zero. 14356 B = APFloat::getZero(A.getSemantics()); 14357 } 14358 int DenomLogB = 0; 14359 APFloat MaxCD = maxnum(abs(C), abs(D)); 14360 if (MaxCD.isFinite()) { 14361 DenomLogB = ilogb(MaxCD); 14362 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14363 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14364 } 14365 APFloat Denom = C * C + D * D; 14366 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14367 APFloat::rmNearestTiesToEven); 14368 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14369 APFloat::rmNearestTiesToEven); 14370 if (ResR.isNaN() && ResI.isNaN()) { 14371 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14372 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14373 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14374 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14375 D.isFinite()) { 14376 A = APFloat::copySign( 14377 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14378 B = APFloat::copySign( 14379 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14380 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14381 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14382 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14383 C = APFloat::copySign( 14384 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14385 D = APFloat::copySign( 14386 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14387 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14388 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14389 } 14390 } 14391 } 14392 } else { 14393 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14394 return Error(E, diag::note_expr_divide_by_zero); 14395 14396 ComplexValue LHS = Result; 14397 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14398 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14399 Result.getComplexIntReal() = 14400 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14401 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14402 Result.getComplexIntImag() = 14403 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14404 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14405 } 14406 break; 14407 } 14408 14409 return true; 14410 } 14411 14412 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14413 // Get the operand value into 'Result'. 14414 if (!Visit(E->getSubExpr())) 14415 return false; 14416 14417 switch (E->getOpcode()) { 14418 default: 14419 return Error(E); 14420 case UO_Extension: 14421 return true; 14422 case UO_Plus: 14423 // The result is always just the subexpr. 14424 return true; 14425 case UO_Minus: 14426 if (Result.isComplexFloat()) { 14427 Result.getComplexFloatReal().changeSign(); 14428 Result.getComplexFloatImag().changeSign(); 14429 } 14430 else { 14431 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14432 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14433 } 14434 return true; 14435 case UO_Not: 14436 if (Result.isComplexFloat()) 14437 Result.getComplexFloatImag().changeSign(); 14438 else 14439 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14440 return true; 14441 } 14442 } 14443 14444 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14445 if (E->getNumInits() == 2) { 14446 if (E->getType()->isComplexType()) { 14447 Result.makeComplexFloat(); 14448 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14449 return false; 14450 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14451 return false; 14452 } else { 14453 Result.makeComplexInt(); 14454 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14455 return false; 14456 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14457 return false; 14458 } 14459 return true; 14460 } 14461 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14462 } 14463 14464 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14465 switch (E->getBuiltinCallee()) { 14466 case Builtin::BI__builtin_complex: 14467 Result.makeComplexFloat(); 14468 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14469 return false; 14470 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14471 return false; 14472 return true; 14473 14474 default: 14475 break; 14476 } 14477 14478 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14479 } 14480 14481 //===----------------------------------------------------------------------===// 14482 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14483 // implicit conversion. 14484 //===----------------------------------------------------------------------===// 14485 14486 namespace { 14487 class AtomicExprEvaluator : 14488 public ExprEvaluatorBase<AtomicExprEvaluator> { 14489 const LValue *This; 14490 APValue &Result; 14491 public: 14492 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14493 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14494 14495 bool Success(const APValue &V, const Expr *E) { 14496 Result = V; 14497 return true; 14498 } 14499 14500 bool ZeroInitialization(const Expr *E) { 14501 ImplicitValueInitExpr VIE( 14502 E->getType()->castAs<AtomicType>()->getValueType()); 14503 // For atomic-qualified class (and array) types in C++, initialize the 14504 // _Atomic-wrapped subobject directly, in-place. 14505 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14506 : Evaluate(Result, Info, &VIE); 14507 } 14508 14509 bool VisitCastExpr(const CastExpr *E) { 14510 switch (E->getCastKind()) { 14511 default: 14512 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14513 case CK_NonAtomicToAtomic: 14514 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14515 : Evaluate(Result, Info, E->getSubExpr()); 14516 } 14517 } 14518 }; 14519 } // end anonymous namespace 14520 14521 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14522 EvalInfo &Info) { 14523 assert(!E->isValueDependent()); 14524 assert(E->isPRValue() && E->getType()->isAtomicType()); 14525 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14526 } 14527 14528 //===----------------------------------------------------------------------===// 14529 // Void expression evaluation, primarily for a cast to void on the LHS of a 14530 // comma operator 14531 //===----------------------------------------------------------------------===// 14532 14533 namespace { 14534 class VoidExprEvaluator 14535 : public ExprEvaluatorBase<VoidExprEvaluator> { 14536 public: 14537 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14538 14539 bool Success(const APValue &V, const Expr *e) { return true; } 14540 14541 bool ZeroInitialization(const Expr *E) { return true; } 14542 14543 bool VisitCastExpr(const CastExpr *E) { 14544 switch (E->getCastKind()) { 14545 default: 14546 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14547 case CK_ToVoid: 14548 VisitIgnoredValue(E->getSubExpr()); 14549 return true; 14550 } 14551 } 14552 14553 bool VisitCallExpr(const CallExpr *E) { 14554 switch (E->getBuiltinCallee()) { 14555 case Builtin::BI__assume: 14556 case Builtin::BI__builtin_assume: 14557 // The argument is not evaluated! 14558 return true; 14559 14560 case Builtin::BI__builtin_operator_delete: 14561 return HandleOperatorDeleteCall(Info, E); 14562 14563 default: 14564 break; 14565 } 14566 14567 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14568 } 14569 14570 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14571 }; 14572 } // end anonymous namespace 14573 14574 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14575 // We cannot speculatively evaluate a delete expression. 14576 if (Info.SpeculativeEvaluationDepth) 14577 return false; 14578 14579 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14580 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14581 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14582 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14583 return false; 14584 } 14585 14586 const Expr *Arg = E->getArgument(); 14587 14588 LValue Pointer; 14589 if (!EvaluatePointer(Arg, Pointer, Info)) 14590 return false; 14591 if (Pointer.Designator.Invalid) 14592 return false; 14593 14594 // Deleting a null pointer has no effect. 14595 if (Pointer.isNullPointer()) { 14596 // This is the only case where we need to produce an extension warning: 14597 // the only other way we can succeed is if we find a dynamic allocation, 14598 // and we will have warned when we allocated it in that case. 14599 if (!Info.getLangOpts().CPlusPlus20) 14600 Info.CCEDiag(E, diag::note_constexpr_new); 14601 return true; 14602 } 14603 14604 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14605 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14606 if (!Alloc) 14607 return false; 14608 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14609 14610 // For the non-array case, the designator must be empty if the static type 14611 // does not have a virtual destructor. 14612 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14613 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14614 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14615 << Arg->getType()->getPointeeType() << AllocType; 14616 return false; 14617 } 14618 14619 // For a class type with a virtual destructor, the selected operator delete 14620 // is the one looked up when building the destructor. 14621 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14622 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14623 if (VirtualDelete && 14624 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14625 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14626 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14627 return false; 14628 } 14629 } 14630 14631 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14632 (*Alloc)->Value, AllocType)) 14633 return false; 14634 14635 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14636 // The element was already erased. This means the destructor call also 14637 // deleted the object. 14638 // FIXME: This probably results in undefined behavior before we get this 14639 // far, and should be diagnosed elsewhere first. 14640 Info.FFDiag(E, diag::note_constexpr_double_delete); 14641 return false; 14642 } 14643 14644 return true; 14645 } 14646 14647 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14648 assert(!E->isValueDependent()); 14649 assert(E->isPRValue() && E->getType()->isVoidType()); 14650 return VoidExprEvaluator(Info).Visit(E); 14651 } 14652 14653 //===----------------------------------------------------------------------===// 14654 // Top level Expr::EvaluateAsRValue method. 14655 //===----------------------------------------------------------------------===// 14656 14657 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14658 assert(!E->isValueDependent()); 14659 // In C, function designators are not lvalues, but we evaluate them as if they 14660 // are. 14661 QualType T = E->getType(); 14662 if (E->isGLValue() || T->isFunctionType()) { 14663 LValue LV; 14664 if (!EvaluateLValue(E, LV, Info)) 14665 return false; 14666 LV.moveInto(Result); 14667 } else if (T->isVectorType()) { 14668 if (!EvaluateVector(E, Result, Info)) 14669 return false; 14670 } else if (T->isIntegralOrEnumerationType()) { 14671 if (!IntExprEvaluator(Info, Result).Visit(E)) 14672 return false; 14673 } else if (T->hasPointerRepresentation()) { 14674 LValue LV; 14675 if (!EvaluatePointer(E, LV, Info)) 14676 return false; 14677 LV.moveInto(Result); 14678 } else if (T->isRealFloatingType()) { 14679 llvm::APFloat F(0.0); 14680 if (!EvaluateFloat(E, F, Info)) 14681 return false; 14682 Result = APValue(F); 14683 } else if (T->isAnyComplexType()) { 14684 ComplexValue C; 14685 if (!EvaluateComplex(E, C, Info)) 14686 return false; 14687 C.moveInto(Result); 14688 } else if (T->isFixedPointType()) { 14689 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14690 } else if (T->isMemberPointerType()) { 14691 MemberPtr P; 14692 if (!EvaluateMemberPointer(E, P, Info)) 14693 return false; 14694 P.moveInto(Result); 14695 return true; 14696 } else if (T->isArrayType()) { 14697 LValue LV; 14698 APValue &Value = 14699 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14700 if (!EvaluateArray(E, LV, Value, Info)) 14701 return false; 14702 Result = Value; 14703 } else if (T->isRecordType()) { 14704 LValue LV; 14705 APValue &Value = 14706 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14707 if (!EvaluateRecord(E, LV, Value, Info)) 14708 return false; 14709 Result = Value; 14710 } else if (T->isVoidType()) { 14711 if (!Info.getLangOpts().CPlusPlus11) 14712 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14713 << E->getType(); 14714 if (!EvaluateVoid(E, Info)) 14715 return false; 14716 } else if (T->isAtomicType()) { 14717 QualType Unqual = T.getAtomicUnqualifiedType(); 14718 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14719 LValue LV; 14720 APValue &Value = Info.CurrentCall->createTemporary( 14721 E, Unqual, ScopeKind::FullExpression, LV); 14722 if (!EvaluateAtomic(E, &LV, Value, Info)) 14723 return false; 14724 } else { 14725 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14726 return false; 14727 } 14728 } else if (Info.getLangOpts().CPlusPlus11) { 14729 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14730 return false; 14731 } else { 14732 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14733 return false; 14734 } 14735 14736 return true; 14737 } 14738 14739 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14740 /// cases, the in-place evaluation is essential, since later initializers for 14741 /// an object can indirectly refer to subobjects which were initialized earlier. 14742 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14743 const Expr *E, bool AllowNonLiteralTypes) { 14744 assert(!E->isValueDependent()); 14745 14746 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14747 return false; 14748 14749 if (E->isPRValue()) { 14750 // Evaluate arrays and record types in-place, so that later initializers can 14751 // refer to earlier-initialized members of the object. 14752 QualType T = E->getType(); 14753 if (T->isArrayType()) 14754 return EvaluateArray(E, This, Result, Info); 14755 else if (T->isRecordType()) 14756 return EvaluateRecord(E, This, Result, Info); 14757 else if (T->isAtomicType()) { 14758 QualType Unqual = T.getAtomicUnqualifiedType(); 14759 if (Unqual->isArrayType() || Unqual->isRecordType()) 14760 return EvaluateAtomic(E, &This, Result, Info); 14761 } 14762 } 14763 14764 // For any other type, in-place evaluation is unimportant. 14765 return Evaluate(Result, Info, E); 14766 } 14767 14768 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14769 /// lvalue-to-rvalue cast if it is an lvalue. 14770 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14771 assert(!E->isValueDependent()); 14772 if (Info.EnableNewConstInterp) { 14773 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14774 return false; 14775 } else { 14776 if (E->getType().isNull()) 14777 return false; 14778 14779 if (!CheckLiteralType(Info, E)) 14780 return false; 14781 14782 if (!::Evaluate(Result, Info, E)) 14783 return false; 14784 14785 if (E->isGLValue()) { 14786 LValue LV; 14787 LV.setFrom(Info.Ctx, Result); 14788 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14789 return false; 14790 } 14791 } 14792 14793 // Check this core constant expression is a constant expression. 14794 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14795 ConstantExprKind::Normal) && 14796 CheckMemoryLeaks(Info); 14797 } 14798 14799 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14800 const ASTContext &Ctx, bool &IsConst) { 14801 // Fast-path evaluations of integer literals, since we sometimes see files 14802 // containing vast quantities of these. 14803 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14804 Result.Val = APValue(APSInt(L->getValue(), 14805 L->getType()->isUnsignedIntegerType())); 14806 IsConst = true; 14807 return true; 14808 } 14809 14810 // This case should be rare, but we need to check it before we check on 14811 // the type below. 14812 if (Exp->getType().isNull()) { 14813 IsConst = false; 14814 return true; 14815 } 14816 14817 // FIXME: Evaluating values of large array and record types can cause 14818 // performance problems. Only do so in C++11 for now. 14819 if (Exp->isPRValue() && 14820 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && 14821 !Ctx.getLangOpts().CPlusPlus11) { 14822 IsConst = false; 14823 return true; 14824 } 14825 return false; 14826 } 14827 14828 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14829 Expr::SideEffectsKind SEK) { 14830 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14831 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14832 } 14833 14834 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14835 const ASTContext &Ctx, EvalInfo &Info) { 14836 assert(!E->isValueDependent()); 14837 bool IsConst; 14838 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14839 return IsConst; 14840 14841 return EvaluateAsRValue(Info, E, Result.Val); 14842 } 14843 14844 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14845 const ASTContext &Ctx, 14846 Expr::SideEffectsKind AllowSideEffects, 14847 EvalInfo &Info) { 14848 assert(!E->isValueDependent()); 14849 if (!E->getType()->isIntegralOrEnumerationType()) 14850 return false; 14851 14852 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14853 !ExprResult.Val.isInt() || 14854 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14855 return false; 14856 14857 return true; 14858 } 14859 14860 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14861 const ASTContext &Ctx, 14862 Expr::SideEffectsKind AllowSideEffects, 14863 EvalInfo &Info) { 14864 assert(!E->isValueDependent()); 14865 if (!E->getType()->isFixedPointType()) 14866 return false; 14867 14868 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14869 return false; 14870 14871 if (!ExprResult.Val.isFixedPoint() || 14872 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14873 return false; 14874 14875 return true; 14876 } 14877 14878 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14879 /// any crazy technique (that has nothing to do with language standards) that 14880 /// we want to. If this function returns true, it returns the folded constant 14881 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14882 /// will be applied to the result. 14883 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14884 bool InConstantContext) const { 14885 assert(!isValueDependent() && 14886 "Expression evaluator can't be called on a dependent expression."); 14887 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14888 Info.InConstantContext = InConstantContext; 14889 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14890 } 14891 14892 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14893 bool InConstantContext) const { 14894 assert(!isValueDependent() && 14895 "Expression evaluator can't be called on a dependent expression."); 14896 EvalResult Scratch; 14897 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14898 HandleConversionToBool(Scratch.Val, Result); 14899 } 14900 14901 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14902 SideEffectsKind AllowSideEffects, 14903 bool InConstantContext) const { 14904 assert(!isValueDependent() && 14905 "Expression evaluator can't be called on a dependent expression."); 14906 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14907 Info.InConstantContext = InConstantContext; 14908 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14909 } 14910 14911 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14912 SideEffectsKind AllowSideEffects, 14913 bool InConstantContext) const { 14914 assert(!isValueDependent() && 14915 "Expression evaluator can't be called on a dependent expression."); 14916 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14917 Info.InConstantContext = InConstantContext; 14918 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14919 } 14920 14921 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14922 SideEffectsKind AllowSideEffects, 14923 bool InConstantContext) const { 14924 assert(!isValueDependent() && 14925 "Expression evaluator can't be called on a dependent expression."); 14926 14927 if (!getType()->isRealFloatingType()) 14928 return false; 14929 14930 EvalResult ExprResult; 14931 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14932 !ExprResult.Val.isFloat() || 14933 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14934 return false; 14935 14936 Result = ExprResult.Val.getFloat(); 14937 return true; 14938 } 14939 14940 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14941 bool InConstantContext) const { 14942 assert(!isValueDependent() && 14943 "Expression evaluator can't be called on a dependent expression."); 14944 14945 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14946 Info.InConstantContext = InConstantContext; 14947 LValue LV; 14948 CheckedTemporaries CheckedTemps; 14949 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14950 Result.HasSideEffects || 14951 !CheckLValueConstantExpression(Info, getExprLoc(), 14952 Ctx.getLValueReferenceType(getType()), LV, 14953 ConstantExprKind::Normal, CheckedTemps)) 14954 return false; 14955 14956 LV.moveInto(Result.Val); 14957 return true; 14958 } 14959 14960 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14961 APValue DestroyedValue, QualType Type, 14962 SourceLocation Loc, Expr::EvalStatus &EStatus, 14963 bool IsConstantDestruction) { 14964 EvalInfo Info(Ctx, EStatus, 14965 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14966 : EvalInfo::EM_ConstantFold); 14967 Info.setEvaluatingDecl(Base, DestroyedValue, 14968 EvalInfo::EvaluatingDeclKind::Dtor); 14969 Info.InConstantContext = IsConstantDestruction; 14970 14971 LValue LVal; 14972 LVal.set(Base); 14973 14974 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14975 EStatus.HasSideEffects) 14976 return false; 14977 14978 if (!Info.discardCleanups()) 14979 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14980 14981 return true; 14982 } 14983 14984 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14985 ConstantExprKind Kind) const { 14986 assert(!isValueDependent() && 14987 "Expression evaluator can't be called on a dependent expression."); 14988 14989 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14990 EvalInfo Info(Ctx, Result, EM); 14991 Info.InConstantContext = true; 14992 14993 // The type of the object we're initializing is 'const T' for a class NTTP. 14994 QualType T = getType(); 14995 if (Kind == ConstantExprKind::ClassTemplateArgument) 14996 T.addConst(); 14997 14998 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14999 // represent the result of the evaluation. CheckConstantExpression ensures 15000 // this doesn't escape. 15001 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 15002 APValue::LValueBase Base(&BaseMTE); 15003 15004 Info.setEvaluatingDecl(Base, Result.Val); 15005 LValue LVal; 15006 LVal.set(Base); 15007 15008 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 15009 return false; 15010 15011 if (!Info.discardCleanups()) 15012 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15013 15014 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 15015 Result.Val, Kind)) 15016 return false; 15017 if (!CheckMemoryLeaks(Info)) 15018 return false; 15019 15020 // If this is a class template argument, it's required to have constant 15021 // destruction too. 15022 if (Kind == ConstantExprKind::ClassTemplateArgument && 15023 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 15024 true) || 15025 Result.HasSideEffects)) { 15026 // FIXME: Prefix a note to indicate that the problem is lack of constant 15027 // destruction. 15028 return false; 15029 } 15030 15031 return true; 15032 } 15033 15034 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 15035 const VarDecl *VD, 15036 SmallVectorImpl<PartialDiagnosticAt> &Notes, 15037 bool IsConstantInitialization) const { 15038 assert(!isValueDependent() && 15039 "Expression evaluator can't be called on a dependent expression."); 15040 15041 // FIXME: Evaluating initializers for large array and record types can cause 15042 // performance problems. Only do so in C++11 for now. 15043 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 15044 !Ctx.getLangOpts().CPlusPlus11) 15045 return false; 15046 15047 Expr::EvalStatus EStatus; 15048 EStatus.Diag = &Notes; 15049 15050 EvalInfo Info(Ctx, EStatus, 15051 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 15052 ? EvalInfo::EM_ConstantExpression 15053 : EvalInfo::EM_ConstantFold); 15054 Info.setEvaluatingDecl(VD, Value); 15055 Info.InConstantContext = IsConstantInitialization; 15056 15057 SourceLocation DeclLoc = VD->getLocation(); 15058 QualType DeclTy = VD->getType(); 15059 15060 if (Info.EnableNewConstInterp) { 15061 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 15062 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 15063 return false; 15064 } else { 15065 LValue LVal; 15066 LVal.set(VD); 15067 15068 if (!EvaluateInPlace(Value, Info, LVal, this, 15069 /*AllowNonLiteralTypes=*/true) || 15070 EStatus.HasSideEffects) 15071 return false; 15072 15073 // At this point, any lifetime-extended temporaries are completely 15074 // initialized. 15075 Info.performLifetimeExtension(); 15076 15077 if (!Info.discardCleanups()) 15078 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15079 } 15080 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 15081 ConstantExprKind::Normal) && 15082 CheckMemoryLeaks(Info); 15083 } 15084 15085 bool VarDecl::evaluateDestruction( 15086 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15087 Expr::EvalStatus EStatus; 15088 EStatus.Diag = &Notes; 15089 15090 // Only treat the destruction as constant destruction if we formally have 15091 // constant initialization (or are usable in a constant expression). 15092 bool IsConstantDestruction = hasConstantInitialization(); 15093 15094 // Make a copy of the value for the destructor to mutate, if we know it. 15095 // Otherwise, treat the value as default-initialized; if the destructor works 15096 // anyway, then the destruction is constant (and must be essentially empty). 15097 APValue DestroyedValue; 15098 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 15099 DestroyedValue = *getEvaluatedValue(); 15100 else if (!getDefaultInitValue(getType(), DestroyedValue)) 15101 return false; 15102 15103 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 15104 getType(), getLocation(), EStatus, 15105 IsConstantDestruction) || 15106 EStatus.HasSideEffects) 15107 return false; 15108 15109 ensureEvaluatedStmt()->HasConstantDestruction = true; 15110 return true; 15111 } 15112 15113 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 15114 /// constant folded, but discard the result. 15115 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 15116 assert(!isValueDependent() && 15117 "Expression evaluator can't be called on a dependent expression."); 15118 15119 EvalResult Result; 15120 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 15121 !hasUnacceptableSideEffect(Result, SEK); 15122 } 15123 15124 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 15125 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15126 assert(!isValueDependent() && 15127 "Expression evaluator can't be called on a dependent expression."); 15128 15129 EvalResult EVResult; 15130 EVResult.Diag = Diag; 15131 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15132 Info.InConstantContext = true; 15133 15134 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 15135 (void)Result; 15136 assert(Result && "Could not evaluate expression"); 15137 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15138 15139 return EVResult.Val.getInt(); 15140 } 15141 15142 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 15143 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15144 assert(!isValueDependent() && 15145 "Expression evaluator can't be called on a dependent expression."); 15146 15147 EvalResult EVResult; 15148 EVResult.Diag = Diag; 15149 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15150 Info.InConstantContext = true; 15151 Info.CheckingForUndefinedBehavior = true; 15152 15153 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15154 (void)Result; 15155 assert(Result && "Could not evaluate expression"); 15156 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15157 15158 return EVResult.Val.getInt(); 15159 } 15160 15161 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15162 assert(!isValueDependent() && 15163 "Expression evaluator can't be called on a dependent expression."); 15164 15165 bool IsConst; 15166 EvalResult EVResult; 15167 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15168 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15169 Info.CheckingForUndefinedBehavior = true; 15170 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15171 } 15172 } 15173 15174 bool Expr::EvalResult::isGlobalLValue() const { 15175 assert(Val.isLValue()); 15176 return IsGlobalLValue(Val.getLValueBase()); 15177 } 15178 15179 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15180 /// an integer constant expression. 15181 15182 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15183 /// comma, etc 15184 15185 // CheckICE - This function does the fundamental ICE checking: the returned 15186 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15187 // and a (possibly null) SourceLocation indicating the location of the problem. 15188 // 15189 // Note that to reduce code duplication, this helper does no evaluation 15190 // itself; the caller checks whether the expression is evaluatable, and 15191 // in the rare cases where CheckICE actually cares about the evaluated 15192 // value, it calls into Evaluate. 15193 15194 namespace { 15195 15196 enum ICEKind { 15197 /// This expression is an ICE. 15198 IK_ICE, 15199 /// This expression is not an ICE, but if it isn't evaluated, it's 15200 /// a legal subexpression for an ICE. This return value is used to handle 15201 /// the comma operator in C99 mode, and non-constant subexpressions. 15202 IK_ICEIfUnevaluated, 15203 /// This expression is not an ICE, and is not a legal subexpression for one. 15204 IK_NotICE 15205 }; 15206 15207 struct ICEDiag { 15208 ICEKind Kind; 15209 SourceLocation Loc; 15210 15211 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15212 }; 15213 15214 } 15215 15216 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15217 15218 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15219 15220 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15221 Expr::EvalResult EVResult; 15222 Expr::EvalStatus Status; 15223 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15224 15225 Info.InConstantContext = true; 15226 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15227 !EVResult.Val.isInt()) 15228 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15229 15230 return NoDiag(); 15231 } 15232 15233 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15234 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15235 if (!E->getType()->isIntegralOrEnumerationType()) 15236 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15237 15238 switch (E->getStmtClass()) { 15239 #define ABSTRACT_STMT(Node) 15240 #define STMT(Node, Base) case Expr::Node##Class: 15241 #define EXPR(Node, Base) 15242 #include "clang/AST/StmtNodes.inc" 15243 case Expr::PredefinedExprClass: 15244 case Expr::FloatingLiteralClass: 15245 case Expr::ImaginaryLiteralClass: 15246 case Expr::StringLiteralClass: 15247 case Expr::ArraySubscriptExprClass: 15248 case Expr::MatrixSubscriptExprClass: 15249 case Expr::OMPArraySectionExprClass: 15250 case Expr::OMPArrayShapingExprClass: 15251 case Expr::OMPIteratorExprClass: 15252 case Expr::MemberExprClass: 15253 case Expr::CompoundAssignOperatorClass: 15254 case Expr::CompoundLiteralExprClass: 15255 case Expr::ExtVectorElementExprClass: 15256 case Expr::DesignatedInitExprClass: 15257 case Expr::ArrayInitLoopExprClass: 15258 case Expr::ArrayInitIndexExprClass: 15259 case Expr::NoInitExprClass: 15260 case Expr::DesignatedInitUpdateExprClass: 15261 case Expr::ImplicitValueInitExprClass: 15262 case Expr::ParenListExprClass: 15263 case Expr::VAArgExprClass: 15264 case Expr::AddrLabelExprClass: 15265 case Expr::StmtExprClass: 15266 case Expr::CXXMemberCallExprClass: 15267 case Expr::CUDAKernelCallExprClass: 15268 case Expr::CXXAddrspaceCastExprClass: 15269 case Expr::CXXDynamicCastExprClass: 15270 case Expr::CXXTypeidExprClass: 15271 case Expr::CXXUuidofExprClass: 15272 case Expr::MSPropertyRefExprClass: 15273 case Expr::MSPropertySubscriptExprClass: 15274 case Expr::CXXNullPtrLiteralExprClass: 15275 case Expr::UserDefinedLiteralClass: 15276 case Expr::CXXThisExprClass: 15277 case Expr::CXXThrowExprClass: 15278 case Expr::CXXNewExprClass: 15279 case Expr::CXXDeleteExprClass: 15280 case Expr::CXXPseudoDestructorExprClass: 15281 case Expr::UnresolvedLookupExprClass: 15282 case Expr::TypoExprClass: 15283 case Expr::RecoveryExprClass: 15284 case Expr::DependentScopeDeclRefExprClass: 15285 case Expr::CXXConstructExprClass: 15286 case Expr::CXXInheritedCtorInitExprClass: 15287 case Expr::CXXStdInitializerListExprClass: 15288 case Expr::CXXBindTemporaryExprClass: 15289 case Expr::ExprWithCleanupsClass: 15290 case Expr::CXXTemporaryObjectExprClass: 15291 case Expr::CXXUnresolvedConstructExprClass: 15292 case Expr::CXXDependentScopeMemberExprClass: 15293 case Expr::UnresolvedMemberExprClass: 15294 case Expr::ObjCStringLiteralClass: 15295 case Expr::ObjCBoxedExprClass: 15296 case Expr::ObjCArrayLiteralClass: 15297 case Expr::ObjCDictionaryLiteralClass: 15298 case Expr::ObjCEncodeExprClass: 15299 case Expr::ObjCMessageExprClass: 15300 case Expr::ObjCSelectorExprClass: 15301 case Expr::ObjCProtocolExprClass: 15302 case Expr::ObjCIvarRefExprClass: 15303 case Expr::ObjCPropertyRefExprClass: 15304 case Expr::ObjCSubscriptRefExprClass: 15305 case Expr::ObjCIsaExprClass: 15306 case Expr::ObjCAvailabilityCheckExprClass: 15307 case Expr::ShuffleVectorExprClass: 15308 case Expr::ConvertVectorExprClass: 15309 case Expr::BlockExprClass: 15310 case Expr::NoStmtClass: 15311 case Expr::OpaqueValueExprClass: 15312 case Expr::PackExpansionExprClass: 15313 case Expr::SubstNonTypeTemplateParmPackExprClass: 15314 case Expr::FunctionParmPackExprClass: 15315 case Expr::AsTypeExprClass: 15316 case Expr::ObjCIndirectCopyRestoreExprClass: 15317 case Expr::MaterializeTemporaryExprClass: 15318 case Expr::PseudoObjectExprClass: 15319 case Expr::AtomicExprClass: 15320 case Expr::LambdaExprClass: 15321 case Expr::CXXFoldExprClass: 15322 case Expr::CoawaitExprClass: 15323 case Expr::DependentCoawaitExprClass: 15324 case Expr::CoyieldExprClass: 15325 case Expr::SYCLUniqueStableNameExprClass: 15326 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15327 15328 case Expr::InitListExprClass: { 15329 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15330 // form "T x = { a };" is equivalent to "T x = a;". 15331 // Unless we're initializing a reference, T is a scalar as it is known to be 15332 // of integral or enumeration type. 15333 if (E->isPRValue()) 15334 if (cast<InitListExpr>(E)->getNumInits() == 1) 15335 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15336 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15337 } 15338 15339 case Expr::SizeOfPackExprClass: 15340 case Expr::GNUNullExprClass: 15341 case Expr::SourceLocExprClass: 15342 return NoDiag(); 15343 15344 case Expr::SubstNonTypeTemplateParmExprClass: 15345 return 15346 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15347 15348 case Expr::ConstantExprClass: 15349 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15350 15351 case Expr::ParenExprClass: 15352 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15353 case Expr::GenericSelectionExprClass: 15354 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15355 case Expr::IntegerLiteralClass: 15356 case Expr::FixedPointLiteralClass: 15357 case Expr::CharacterLiteralClass: 15358 case Expr::ObjCBoolLiteralExprClass: 15359 case Expr::CXXBoolLiteralExprClass: 15360 case Expr::CXXScalarValueInitExprClass: 15361 case Expr::TypeTraitExprClass: 15362 case Expr::ConceptSpecializationExprClass: 15363 case Expr::RequiresExprClass: 15364 case Expr::ArrayTypeTraitExprClass: 15365 case Expr::ExpressionTraitExprClass: 15366 case Expr::CXXNoexceptExprClass: 15367 return NoDiag(); 15368 case Expr::CallExprClass: 15369 case Expr::CXXOperatorCallExprClass: { 15370 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15371 // constant expressions, but they can never be ICEs because an ICE cannot 15372 // contain an operand of (pointer to) function type. 15373 const CallExpr *CE = cast<CallExpr>(E); 15374 if (CE->getBuiltinCallee()) 15375 return CheckEvalInICE(E, Ctx); 15376 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15377 } 15378 case Expr::CXXRewrittenBinaryOperatorClass: 15379 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15380 Ctx); 15381 case Expr::DeclRefExprClass: { 15382 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15383 if (isa<EnumConstantDecl>(D)) 15384 return NoDiag(); 15385 15386 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15387 // integer variables in constant expressions: 15388 // 15389 // C++ 7.1.5.1p2 15390 // A variable of non-volatile const-qualified integral or enumeration 15391 // type initialized by an ICE can be used in ICEs. 15392 // 15393 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15394 // that mode, use of reference variables should not be allowed. 15395 const VarDecl *VD = dyn_cast<VarDecl>(D); 15396 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15397 !VD->getType()->isReferenceType()) 15398 return NoDiag(); 15399 15400 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15401 } 15402 case Expr::UnaryOperatorClass: { 15403 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15404 switch (Exp->getOpcode()) { 15405 case UO_PostInc: 15406 case UO_PostDec: 15407 case UO_PreInc: 15408 case UO_PreDec: 15409 case UO_AddrOf: 15410 case UO_Deref: 15411 case UO_Coawait: 15412 // C99 6.6/3 allows increment and decrement within unevaluated 15413 // subexpressions of constant expressions, but they can never be ICEs 15414 // because an ICE cannot contain an lvalue operand. 15415 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15416 case UO_Extension: 15417 case UO_LNot: 15418 case UO_Plus: 15419 case UO_Minus: 15420 case UO_Not: 15421 case UO_Real: 15422 case UO_Imag: 15423 return CheckICE(Exp->getSubExpr(), Ctx); 15424 } 15425 llvm_unreachable("invalid unary operator class"); 15426 } 15427 case Expr::OffsetOfExprClass: { 15428 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15429 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15430 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15431 // compliance: we should warn earlier for offsetof expressions with 15432 // array subscripts that aren't ICEs, and if the array subscripts 15433 // are ICEs, the value of the offsetof must be an integer constant. 15434 return CheckEvalInICE(E, Ctx); 15435 } 15436 case Expr::UnaryExprOrTypeTraitExprClass: { 15437 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15438 if ((Exp->getKind() == UETT_SizeOf) && 15439 Exp->getTypeOfArgument()->isVariableArrayType()) 15440 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15441 return NoDiag(); 15442 } 15443 case Expr::BinaryOperatorClass: { 15444 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15445 switch (Exp->getOpcode()) { 15446 case BO_PtrMemD: 15447 case BO_PtrMemI: 15448 case BO_Assign: 15449 case BO_MulAssign: 15450 case BO_DivAssign: 15451 case BO_RemAssign: 15452 case BO_AddAssign: 15453 case BO_SubAssign: 15454 case BO_ShlAssign: 15455 case BO_ShrAssign: 15456 case BO_AndAssign: 15457 case BO_XorAssign: 15458 case BO_OrAssign: 15459 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15460 // constant expressions, but they can never be ICEs because an ICE cannot 15461 // contain an lvalue operand. 15462 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15463 15464 case BO_Mul: 15465 case BO_Div: 15466 case BO_Rem: 15467 case BO_Add: 15468 case BO_Sub: 15469 case BO_Shl: 15470 case BO_Shr: 15471 case BO_LT: 15472 case BO_GT: 15473 case BO_LE: 15474 case BO_GE: 15475 case BO_EQ: 15476 case BO_NE: 15477 case BO_And: 15478 case BO_Xor: 15479 case BO_Or: 15480 case BO_Comma: 15481 case BO_Cmp: { 15482 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15483 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15484 if (Exp->getOpcode() == BO_Div || 15485 Exp->getOpcode() == BO_Rem) { 15486 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15487 // we don't evaluate one. 15488 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15489 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15490 if (REval == 0) 15491 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15492 if (REval.isSigned() && REval.isAllOnes()) { 15493 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15494 if (LEval.isMinSignedValue()) 15495 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15496 } 15497 } 15498 } 15499 if (Exp->getOpcode() == BO_Comma) { 15500 if (Ctx.getLangOpts().C99) { 15501 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15502 // if it isn't evaluated. 15503 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15504 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15505 } else { 15506 // In both C89 and C++, commas in ICEs are illegal. 15507 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15508 } 15509 } 15510 return Worst(LHSResult, RHSResult); 15511 } 15512 case BO_LAnd: 15513 case BO_LOr: { 15514 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15515 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15516 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15517 // Rare case where the RHS has a comma "side-effect"; we need 15518 // to actually check the condition to see whether the side 15519 // with the comma is evaluated. 15520 if ((Exp->getOpcode() == BO_LAnd) != 15521 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15522 return RHSResult; 15523 return NoDiag(); 15524 } 15525 15526 return Worst(LHSResult, RHSResult); 15527 } 15528 } 15529 llvm_unreachable("invalid binary operator kind"); 15530 } 15531 case Expr::ImplicitCastExprClass: 15532 case Expr::CStyleCastExprClass: 15533 case Expr::CXXFunctionalCastExprClass: 15534 case Expr::CXXStaticCastExprClass: 15535 case Expr::CXXReinterpretCastExprClass: 15536 case Expr::CXXConstCastExprClass: 15537 case Expr::ObjCBridgedCastExprClass: { 15538 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15539 if (isa<ExplicitCastExpr>(E)) { 15540 if (const FloatingLiteral *FL 15541 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15542 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15543 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15544 APSInt IgnoredVal(DestWidth, !DestSigned); 15545 bool Ignored; 15546 // If the value does not fit in the destination type, the behavior is 15547 // undefined, so we are not required to treat it as a constant 15548 // expression. 15549 if (FL->getValue().convertToInteger(IgnoredVal, 15550 llvm::APFloat::rmTowardZero, 15551 &Ignored) & APFloat::opInvalidOp) 15552 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15553 return NoDiag(); 15554 } 15555 } 15556 switch (cast<CastExpr>(E)->getCastKind()) { 15557 case CK_LValueToRValue: 15558 case CK_AtomicToNonAtomic: 15559 case CK_NonAtomicToAtomic: 15560 case CK_NoOp: 15561 case CK_IntegralToBoolean: 15562 case CK_IntegralCast: 15563 return CheckICE(SubExpr, Ctx); 15564 default: 15565 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15566 } 15567 } 15568 case Expr::BinaryConditionalOperatorClass: { 15569 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15570 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15571 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15572 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15573 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15574 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15575 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15576 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15577 return FalseResult; 15578 } 15579 case Expr::ConditionalOperatorClass: { 15580 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15581 // If the condition (ignoring parens) is a __builtin_constant_p call, 15582 // then only the true side is actually considered in an integer constant 15583 // expression, and it is fully evaluated. This is an important GNU 15584 // extension. See GCC PR38377 for discussion. 15585 if (const CallExpr *CallCE 15586 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15587 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15588 return CheckEvalInICE(E, Ctx); 15589 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15590 if (CondResult.Kind == IK_NotICE) 15591 return CondResult; 15592 15593 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15594 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15595 15596 if (TrueResult.Kind == IK_NotICE) 15597 return TrueResult; 15598 if (FalseResult.Kind == IK_NotICE) 15599 return FalseResult; 15600 if (CondResult.Kind == IK_ICEIfUnevaluated) 15601 return CondResult; 15602 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15603 return NoDiag(); 15604 // Rare case where the diagnostics depend on which side is evaluated 15605 // Note that if we get here, CondResult is 0, and at least one of 15606 // TrueResult and FalseResult is non-zero. 15607 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15608 return FalseResult; 15609 return TrueResult; 15610 } 15611 case Expr::CXXDefaultArgExprClass: 15612 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15613 case Expr::CXXDefaultInitExprClass: 15614 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15615 case Expr::ChooseExprClass: { 15616 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15617 } 15618 case Expr::BuiltinBitCastExprClass: { 15619 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15620 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15621 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15622 } 15623 } 15624 15625 llvm_unreachable("Invalid StmtClass!"); 15626 } 15627 15628 /// Evaluate an expression as a C++11 integral constant expression. 15629 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15630 const Expr *E, 15631 llvm::APSInt *Value, 15632 SourceLocation *Loc) { 15633 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15634 if (Loc) *Loc = E->getExprLoc(); 15635 return false; 15636 } 15637 15638 APValue Result; 15639 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15640 return false; 15641 15642 if (!Result.isInt()) { 15643 if (Loc) *Loc = E->getExprLoc(); 15644 return false; 15645 } 15646 15647 if (Value) *Value = Result.getInt(); 15648 return true; 15649 } 15650 15651 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15652 SourceLocation *Loc) const { 15653 assert(!isValueDependent() && 15654 "Expression evaluator can't be called on a dependent expression."); 15655 15656 if (Ctx.getLangOpts().CPlusPlus11) 15657 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15658 15659 ICEDiag D = CheckICE(this, Ctx); 15660 if (D.Kind != IK_ICE) { 15661 if (Loc) *Loc = D.Loc; 15662 return false; 15663 } 15664 return true; 15665 } 15666 15667 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15668 SourceLocation *Loc, 15669 bool isEvaluated) const { 15670 if (isValueDependent()) { 15671 // Expression evaluator can't succeed on a dependent expression. 15672 return None; 15673 } 15674 15675 APSInt Value; 15676 15677 if (Ctx.getLangOpts().CPlusPlus11) { 15678 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15679 return Value; 15680 return None; 15681 } 15682 15683 if (!isIntegerConstantExpr(Ctx, Loc)) 15684 return None; 15685 15686 // The only possible side-effects here are due to UB discovered in the 15687 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15688 // required to treat the expression as an ICE, so we produce the folded 15689 // value. 15690 EvalResult ExprResult; 15691 Expr::EvalStatus Status; 15692 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15693 Info.InConstantContext = true; 15694 15695 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15696 llvm_unreachable("ICE cannot be evaluated!"); 15697 15698 return ExprResult.Val.getInt(); 15699 } 15700 15701 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15702 assert(!isValueDependent() && 15703 "Expression evaluator can't be called on a dependent expression."); 15704 15705 return CheckICE(this, Ctx).Kind == IK_ICE; 15706 } 15707 15708 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15709 SourceLocation *Loc) const { 15710 assert(!isValueDependent() && 15711 "Expression evaluator can't be called on a dependent expression."); 15712 15713 // We support this checking in C++98 mode in order to diagnose compatibility 15714 // issues. 15715 assert(Ctx.getLangOpts().CPlusPlus); 15716 15717 // Build evaluation settings. 15718 Expr::EvalStatus Status; 15719 SmallVector<PartialDiagnosticAt, 8> Diags; 15720 Status.Diag = &Diags; 15721 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15722 15723 APValue Scratch; 15724 bool IsConstExpr = 15725 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15726 // FIXME: We don't produce a diagnostic for this, but the callers that 15727 // call us on arbitrary full-expressions should generally not care. 15728 Info.discardCleanups() && !Status.HasSideEffects; 15729 15730 if (!Diags.empty()) { 15731 IsConstExpr = false; 15732 if (Loc) *Loc = Diags[0].first; 15733 } else if (!IsConstExpr) { 15734 // FIXME: This shouldn't happen. 15735 if (Loc) *Loc = getExprLoc(); 15736 } 15737 15738 return IsConstExpr; 15739 } 15740 15741 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15742 const FunctionDecl *Callee, 15743 ArrayRef<const Expr*> Args, 15744 const Expr *This) const { 15745 assert(!isValueDependent() && 15746 "Expression evaluator can't be called on a dependent expression."); 15747 15748 Expr::EvalStatus Status; 15749 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15750 Info.InConstantContext = true; 15751 15752 LValue ThisVal; 15753 const LValue *ThisPtr = nullptr; 15754 if (This) { 15755 #ifndef NDEBUG 15756 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15757 assert(MD && "Don't provide `this` for non-methods."); 15758 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15759 #endif 15760 if (!This->isValueDependent() && 15761 EvaluateObjectArgument(Info, This, ThisVal) && 15762 !Info.EvalStatus.HasSideEffects) 15763 ThisPtr = &ThisVal; 15764 15765 // Ignore any side-effects from a failed evaluation. This is safe because 15766 // they can't interfere with any other argument evaluation. 15767 Info.EvalStatus.HasSideEffects = false; 15768 } 15769 15770 CallRef Call = Info.CurrentCall->createCall(Callee); 15771 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15772 I != E; ++I) { 15773 unsigned Idx = I - Args.begin(); 15774 if (Idx >= Callee->getNumParams()) 15775 break; 15776 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15777 if ((*I)->isValueDependent() || 15778 !EvaluateCallArg(PVD, *I, Call, Info) || 15779 Info.EvalStatus.HasSideEffects) { 15780 // If evaluation fails, throw away the argument entirely. 15781 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15782 *Slot = APValue(); 15783 } 15784 15785 // Ignore any side-effects from a failed evaluation. This is safe because 15786 // they can't interfere with any other argument evaluation. 15787 Info.EvalStatus.HasSideEffects = false; 15788 } 15789 15790 // Parameter cleanups happen in the caller and are not part of this 15791 // evaluation. 15792 Info.discardCleanups(); 15793 Info.EvalStatus.HasSideEffects = false; 15794 15795 // Build fake call to Callee. 15796 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15797 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15798 FullExpressionRAII Scope(Info); 15799 return Evaluate(Value, Info, this) && Scope.destroy() && 15800 !Info.EvalStatus.HasSideEffects; 15801 } 15802 15803 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15804 SmallVectorImpl< 15805 PartialDiagnosticAt> &Diags) { 15806 // FIXME: It would be useful to check constexpr function templates, but at the 15807 // moment the constant expression evaluator cannot cope with the non-rigorous 15808 // ASTs which we build for dependent expressions. 15809 if (FD->isDependentContext()) 15810 return true; 15811 15812 Expr::EvalStatus Status; 15813 Status.Diag = &Diags; 15814 15815 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15816 Info.InConstantContext = true; 15817 Info.CheckingPotentialConstantExpression = true; 15818 15819 // The constexpr VM attempts to compile all methods to bytecode here. 15820 if (Info.EnableNewConstInterp) { 15821 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15822 return Diags.empty(); 15823 } 15824 15825 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15826 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15827 15828 // Fabricate an arbitrary expression on the stack and pretend that it 15829 // is a temporary being used as the 'this' pointer. 15830 LValue This; 15831 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15832 This.set({&VIE, Info.CurrentCall->Index}); 15833 15834 ArrayRef<const Expr*> Args; 15835 15836 APValue Scratch; 15837 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15838 // Evaluate the call as a constant initializer, to allow the construction 15839 // of objects of non-literal types. 15840 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15841 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15842 } else { 15843 SourceLocation Loc = FD->getLocation(); 15844 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15845 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15846 } 15847 15848 return Diags.empty(); 15849 } 15850 15851 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15852 const FunctionDecl *FD, 15853 SmallVectorImpl< 15854 PartialDiagnosticAt> &Diags) { 15855 assert(!E->isValueDependent() && 15856 "Expression evaluator can't be called on a dependent expression."); 15857 15858 Expr::EvalStatus Status; 15859 Status.Diag = &Diags; 15860 15861 EvalInfo Info(FD->getASTContext(), Status, 15862 EvalInfo::EM_ConstantExpressionUnevaluated); 15863 Info.InConstantContext = true; 15864 Info.CheckingPotentialConstantExpression = true; 15865 15866 // Fabricate a call stack frame to give the arguments a plausible cover story. 15867 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15868 15869 APValue ResultScratch; 15870 Evaluate(ResultScratch, Info, E); 15871 return Diags.empty(); 15872 } 15873 15874 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15875 unsigned Type) const { 15876 if (!getType()->isPointerType()) 15877 return false; 15878 15879 Expr::EvalStatus Status; 15880 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15881 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15882 } 15883 15884 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 15885 EvalInfo &Info) { 15886 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 15887 return false; 15888 15889 LValue String; 15890 15891 if (!EvaluatePointer(E, String, Info)) 15892 return false; 15893 15894 QualType CharTy = E->getType()->getPointeeType(); 15895 15896 // Fast path: if it's a string literal, search the string value. 15897 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 15898 String.getLValueBase().dyn_cast<const Expr *>())) { 15899 StringRef Str = S->getBytes(); 15900 int64_t Off = String.Offset.getQuantity(); 15901 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 15902 S->getCharByteWidth() == 1 && 15903 // FIXME: Add fast-path for wchar_t too. 15904 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 15905 Str = Str.substr(Off); 15906 15907 StringRef::size_type Pos = Str.find(0); 15908 if (Pos != StringRef::npos) 15909 Str = Str.substr(0, Pos); 15910 15911 Result = Str.size(); 15912 return true; 15913 } 15914 15915 // Fall through to slow path. 15916 } 15917 15918 // Slow path: scan the bytes of the string looking for the terminating 0. 15919 for (uint64_t Strlen = 0; /**/; ++Strlen) { 15920 APValue Char; 15921 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 15922 !Char.isInt()) 15923 return false; 15924 if (!Char.getInt()) { 15925 Result = Strlen; 15926 return true; 15927 } 15928 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 15929 return false; 15930 } 15931 } 15932 15933 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 15934 Expr::EvalStatus Status; 15935 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15936 return EvaluateBuiltinStrLen(this, Result, Info); 15937 } 15938