1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Expr constant evaluator. 11 // 12 // Constant expression evaluation produces four main results: 13 // 14 // * A success/failure flag indicating whether constant folding was successful. 15 // This is the 'bool' return value used by most of the code in this file. A 16 // 'false' return value indicates that constant folding has failed, and any 17 // appropriate diagnostic has already been produced. 18 // 19 // * An evaluated result, valid only if constant folding has not failed. 20 // 21 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 23 // where it is possible to determine the evaluated result regardless. 24 // 25 // * A set of notes indicating why the evaluation was not a constant expression 26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 27 // too, why the expression could not be folded. 28 // 29 // If we are checking for a potential constant expression, failure to constant 30 // fold a potential constant sub-expression will be indicated by a 'false' 31 // return value (the expression could not be folded) and no diagnostic (the 32 // expression is not necessarily non-constant). 33 // 34 //===----------------------------------------------------------------------===// 35 36 #include "clang/AST/APValue.h" 37 #include "clang/AST/ASTContext.h" 38 #include "clang/AST/ASTDiagnostic.h" 39 #include "clang/AST/ASTLambda.h" 40 #include "clang/AST/CharUnits.h" 41 #include "clang/AST/Expr.h" 42 #include "clang/AST/RecordLayout.h" 43 #include "clang/AST/StmtVisitor.h" 44 #include "clang/AST/TypeLoc.h" 45 #include "clang/Basic/Builtins.h" 46 #include "clang/Basic/TargetInfo.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include <cstring> 49 #include <functional> 50 51 #define DEBUG_TYPE "exprconstant" 52 53 using namespace clang; 54 using llvm::APSInt; 55 using llvm::APFloat; 56 57 static bool IsGlobalLValue(APValue::LValueBase B); 58 59 namespace { 60 struct LValue; 61 struct CallStackFrame; 62 struct EvalInfo; 63 64 static QualType getType(APValue::LValueBase B) { 65 if (!B) return QualType(); 66 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 67 // FIXME: It's unclear where we're supposed to take the type from, and 68 // this actually matters for arrays of unknown bound. Eg: 69 // 70 // extern int arr[]; void f() { extern int arr[3]; }; 71 // constexpr int *p = &arr[1]; // valid? 72 // 73 // For now, we take the array bound from the most recent declaration. 74 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 75 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 76 QualType T = Redecl->getType(); 77 if (!T->isIncompleteArrayType()) 78 return T; 79 } 80 return D->getType(); 81 } 82 83 const Expr *Base = B.get<const Expr*>(); 84 85 // For a materialized temporary, the type of the temporary we materialized 86 // may not be the type of the expression. 87 if (const MaterializeTemporaryExpr *MTE = 88 dyn_cast<MaterializeTemporaryExpr>(Base)) { 89 SmallVector<const Expr *, 2> CommaLHSs; 90 SmallVector<SubobjectAdjustment, 2> Adjustments; 91 const Expr *Temp = MTE->GetTemporaryExpr(); 92 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 93 Adjustments); 94 // Keep any cv-qualifiers from the reference if we generated a temporary 95 // for it directly. Otherwise use the type after adjustment. 96 if (!Adjustments.empty()) 97 return Inner->getType(); 98 } 99 100 return Base->getType(); 101 } 102 103 /// Get an LValue path entry, which is known to not be an array index, as a 104 /// field or base class. 105 static 106 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) { 107 APValue::BaseOrMemberType Value; 108 Value.setFromOpaqueValue(E.BaseOrMember); 109 return Value; 110 } 111 112 /// Get an LValue path entry, which is known to not be an array index, as a 113 /// field declaration. 114 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 115 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer()); 116 } 117 /// Get an LValue path entry, which is known to not be an array index, as a 118 /// base class declaration. 119 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 120 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer()); 121 } 122 /// Determine whether this LValue path entry for a base class names a virtual 123 /// base class. 124 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 125 return getAsBaseOrMember(E).getInt(); 126 } 127 128 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 129 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 130 const FunctionDecl *Callee = CE->getDirectCallee(); 131 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 132 } 133 134 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 135 /// This will look through a single cast. 136 /// 137 /// Returns null if we couldn't unwrap a function with alloc_size. 138 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 139 if (!E->getType()->isPointerType()) 140 return nullptr; 141 142 E = E->IgnoreParens(); 143 // If we're doing a variable assignment from e.g. malloc(N), there will 144 // probably be a cast of some kind. In exotic cases, we might also see a 145 // top-level ExprWithCleanups. Ignore them either way. 146 if (const auto *EC = dyn_cast<ExprWithCleanups>(E)) 147 E = EC->getSubExpr()->IgnoreParens(); 148 149 if (const auto *Cast = dyn_cast<CastExpr>(E)) 150 E = Cast->getSubExpr()->IgnoreParens(); 151 152 if (const auto *CE = dyn_cast<CallExpr>(E)) 153 return getAllocSizeAttr(CE) ? CE : nullptr; 154 return nullptr; 155 } 156 157 /// Determines whether or not the given Base contains a call to a function 158 /// with the alloc_size attribute. 159 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 160 const auto *E = Base.dyn_cast<const Expr *>(); 161 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 162 } 163 164 /// The bound to claim that an array of unknown bound has. 165 /// The value in MostDerivedArraySize is undefined in this case. So, set it 166 /// to an arbitrary value that's likely to loudly break things if it's used. 167 static const uint64_t AssumedSizeForUnsizedArray = 168 std::numeric_limits<uint64_t>::max() / 2; 169 170 /// Determines if an LValue with the given LValueBase will have an unsized 171 /// array in its designator. 172 /// Find the path length and type of the most-derived subobject in the given 173 /// path, and find the size of the containing array, if any. 174 static unsigned 175 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 176 ArrayRef<APValue::LValuePathEntry> Path, 177 uint64_t &ArraySize, QualType &Type, bool &IsArray, 178 bool &FirstEntryIsUnsizedArray) { 179 // This only accepts LValueBases from APValues, and APValues don't support 180 // arrays that lack size info. 181 assert(!isBaseAnAllocSizeCall(Base) && 182 "Unsized arrays shouldn't appear here"); 183 unsigned MostDerivedLength = 0; 184 Type = getType(Base); 185 186 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 187 if (Type->isArrayType()) { 188 const ArrayType *AT = Ctx.getAsArrayType(Type); 189 Type = AT->getElementType(); 190 MostDerivedLength = I + 1; 191 IsArray = true; 192 193 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 194 ArraySize = CAT->getSize().getZExtValue(); 195 } else { 196 assert(I == 0 && "unexpected unsized array designator"); 197 FirstEntryIsUnsizedArray = true; 198 ArraySize = AssumedSizeForUnsizedArray; 199 } 200 } else if (Type->isAnyComplexType()) { 201 const ComplexType *CT = Type->castAs<ComplexType>(); 202 Type = CT->getElementType(); 203 ArraySize = 2; 204 MostDerivedLength = I + 1; 205 IsArray = true; 206 } else if (const FieldDecl *FD = getAsField(Path[I])) { 207 Type = FD->getType(); 208 ArraySize = 0; 209 MostDerivedLength = I + 1; 210 IsArray = false; 211 } else { 212 // Path[I] describes a base class. 213 ArraySize = 0; 214 IsArray = false; 215 } 216 } 217 return MostDerivedLength; 218 } 219 220 // The order of this enum is important for diagnostics. 221 enum CheckSubobjectKind { 222 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 223 CSK_This, CSK_Real, CSK_Imag 224 }; 225 226 /// A path from a glvalue to a subobject of that glvalue. 227 struct SubobjectDesignator { 228 /// True if the subobject was named in a manner not supported by C++11. Such 229 /// lvalues can still be folded, but they are not core constant expressions 230 /// and we cannot perform lvalue-to-rvalue conversions on them. 231 unsigned Invalid : 1; 232 233 /// Is this a pointer one past the end of an object? 234 unsigned IsOnePastTheEnd : 1; 235 236 /// Indicator of whether the first entry is an unsized array. 237 unsigned FirstEntryIsAnUnsizedArray : 1; 238 239 /// Indicator of whether the most-derived object is an array element. 240 unsigned MostDerivedIsArrayElement : 1; 241 242 /// The length of the path to the most-derived object of which this is a 243 /// subobject. 244 unsigned MostDerivedPathLength : 28; 245 246 /// The size of the array of which the most-derived object is an element. 247 /// This will always be 0 if the most-derived object is not an array 248 /// element. 0 is not an indicator of whether or not the most-derived object 249 /// is an array, however, because 0-length arrays are allowed. 250 /// 251 /// If the current array is an unsized array, the value of this is 252 /// undefined. 253 uint64_t MostDerivedArraySize; 254 255 /// The type of the most derived object referred to by this address. 256 QualType MostDerivedType; 257 258 typedef APValue::LValuePathEntry PathEntry; 259 260 /// The entries on the path from the glvalue to the designated subobject. 261 SmallVector<PathEntry, 8> Entries; 262 263 SubobjectDesignator() : Invalid(true) {} 264 265 explicit SubobjectDesignator(QualType T) 266 : Invalid(false), IsOnePastTheEnd(false), 267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 268 MostDerivedPathLength(0), MostDerivedArraySize(0), 269 MostDerivedType(T) {} 270 271 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 272 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 274 MostDerivedPathLength(0), MostDerivedArraySize(0) { 275 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 276 if (!Invalid) { 277 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 278 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 279 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 280 if (V.getLValueBase()) { 281 bool IsArray = false; 282 bool FirstIsUnsizedArray = false; 283 MostDerivedPathLength = findMostDerivedSubobject( 284 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 285 MostDerivedType, IsArray, FirstIsUnsizedArray); 286 MostDerivedIsArrayElement = IsArray; 287 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 288 } 289 } 290 } 291 292 void setInvalid() { 293 Invalid = true; 294 Entries.clear(); 295 } 296 297 /// Determine whether the most derived subobject is an array without a 298 /// known bound. 299 bool isMostDerivedAnUnsizedArray() const { 300 assert(!Invalid && "Calling this makes no sense on invalid designators"); 301 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 302 } 303 304 /// Determine what the most derived array's size is. Results in an assertion 305 /// failure if the most derived array lacks a size. 306 uint64_t getMostDerivedArraySize() const { 307 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 308 return MostDerivedArraySize; 309 } 310 311 /// Determine whether this is a one-past-the-end pointer. 312 bool isOnePastTheEnd() const { 313 assert(!Invalid); 314 if (IsOnePastTheEnd) 315 return true; 316 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 317 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 318 return true; 319 return false; 320 } 321 322 /// Check that this refers to a valid subobject. 323 bool isValidSubobject() const { 324 if (Invalid) 325 return false; 326 return !isOnePastTheEnd(); 327 } 328 /// Check that this refers to a valid subobject, and if not, produce a 329 /// relevant diagnostic and set the designator as invalid. 330 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 331 332 /// Update this designator to refer to the first element within this array. 333 void addArrayUnchecked(const ConstantArrayType *CAT) { 334 PathEntry Entry; 335 Entry.ArrayIndex = 0; 336 Entries.push_back(Entry); 337 338 // This is a most-derived object. 339 MostDerivedType = CAT->getElementType(); 340 MostDerivedIsArrayElement = true; 341 MostDerivedArraySize = CAT->getSize().getZExtValue(); 342 MostDerivedPathLength = Entries.size(); 343 } 344 /// Update this designator to refer to the first element within the array of 345 /// elements of type T. This is an array of unknown size. 346 void addUnsizedArrayUnchecked(QualType ElemTy) { 347 PathEntry Entry; 348 Entry.ArrayIndex = 0; 349 Entries.push_back(Entry); 350 351 MostDerivedType = ElemTy; 352 MostDerivedIsArrayElement = true; 353 // The value in MostDerivedArraySize is undefined in this case. So, set it 354 // to an arbitrary value that's likely to loudly break things if it's 355 // used. 356 MostDerivedArraySize = AssumedSizeForUnsizedArray; 357 MostDerivedPathLength = Entries.size(); 358 } 359 /// Update this designator to refer to the given base or member of this 360 /// object. 361 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 362 PathEntry Entry; 363 APValue::BaseOrMemberType Value(D, Virtual); 364 Entry.BaseOrMember = Value.getOpaqueValue(); 365 Entries.push_back(Entry); 366 367 // If this isn't a base class, it's a new most-derived object. 368 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 369 MostDerivedType = FD->getType(); 370 MostDerivedIsArrayElement = false; 371 MostDerivedArraySize = 0; 372 MostDerivedPathLength = Entries.size(); 373 } 374 } 375 /// Update this designator to refer to the given complex component. 376 void addComplexUnchecked(QualType EltTy, bool Imag) { 377 PathEntry Entry; 378 Entry.ArrayIndex = Imag; 379 Entries.push_back(Entry); 380 381 // This is technically a most-derived object, though in practice this 382 // is unlikely to matter. 383 MostDerivedType = EltTy; 384 MostDerivedIsArrayElement = true; 385 MostDerivedArraySize = 2; 386 MostDerivedPathLength = Entries.size(); 387 } 388 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 389 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 390 const APSInt &N); 391 /// Add N to the address of this subobject. 392 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 393 if (Invalid || !N) return; 394 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 395 if (isMostDerivedAnUnsizedArray()) { 396 diagnoseUnsizedArrayPointerArithmetic(Info, E); 397 // Can't verify -- trust that the user is doing the right thing (or if 398 // not, trust that the caller will catch the bad behavior). 399 // FIXME: Should we reject if this overflows, at least? 400 Entries.back().ArrayIndex += TruncatedN; 401 return; 402 } 403 404 // [expr.add]p4: For the purposes of these operators, a pointer to a 405 // nonarray object behaves the same as a pointer to the first element of 406 // an array of length one with the type of the object as its element type. 407 bool IsArray = MostDerivedPathLength == Entries.size() && 408 MostDerivedIsArrayElement; 409 uint64_t ArrayIndex = 410 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 411 uint64_t ArraySize = 412 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 413 414 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 415 // Calculate the actual index in a wide enough type, so we can include 416 // it in the note. 417 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 418 (llvm::APInt&)N += ArrayIndex; 419 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 420 diagnosePointerArithmetic(Info, E, N); 421 setInvalid(); 422 return; 423 } 424 425 ArrayIndex += TruncatedN; 426 assert(ArrayIndex <= ArraySize && 427 "bounds check succeeded for out-of-bounds index"); 428 429 if (IsArray) 430 Entries.back().ArrayIndex = ArrayIndex; 431 else 432 IsOnePastTheEnd = (ArrayIndex != 0); 433 } 434 }; 435 436 /// A stack frame in the constexpr call stack. 437 struct CallStackFrame { 438 EvalInfo &Info; 439 440 /// Parent - The caller of this stack frame. 441 CallStackFrame *Caller; 442 443 /// Callee - The function which was called. 444 const FunctionDecl *Callee; 445 446 /// This - The binding for the this pointer in this call, if any. 447 const LValue *This; 448 449 /// Arguments - Parameter bindings for this function call, indexed by 450 /// parameters' function scope indices. 451 APValue *Arguments; 452 453 // Note that we intentionally use std::map here so that references to 454 // values are stable. 455 typedef std::map<const void*, APValue> MapTy; 456 typedef MapTy::const_iterator temp_iterator; 457 /// Temporaries - Temporary lvalues materialized within this stack frame. 458 MapTy Temporaries; 459 460 /// CallLoc - The location of the call expression for this call. 461 SourceLocation CallLoc; 462 463 /// Index - The call index of this call. 464 unsigned Index; 465 466 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 467 // on the overall stack usage of deeply-recursing constexpr evaluataions. 468 // (We should cache this map rather than recomputing it repeatedly.) 469 // But let's try this and see how it goes; we can look into caching the map 470 // as a later change. 471 472 /// LambdaCaptureFields - Mapping from captured variables/this to 473 /// corresponding data members in the closure class. 474 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 475 FieldDecl *LambdaThisCaptureField; 476 477 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 478 const FunctionDecl *Callee, const LValue *This, 479 APValue *Arguments); 480 ~CallStackFrame(); 481 482 APValue *getTemporary(const void *Key) { 483 MapTy::iterator I = Temporaries.find(Key); 484 return I == Temporaries.end() ? nullptr : &I->second; 485 } 486 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 487 }; 488 489 /// Temporarily override 'this'. 490 class ThisOverrideRAII { 491 public: 492 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 493 : Frame(Frame), OldThis(Frame.This) { 494 if (Enable) 495 Frame.This = NewThis; 496 } 497 ~ThisOverrideRAII() { 498 Frame.This = OldThis; 499 } 500 private: 501 CallStackFrame &Frame; 502 const LValue *OldThis; 503 }; 504 505 /// A partial diagnostic which we might know in advance that we are not going 506 /// to emit. 507 class OptionalDiagnostic { 508 PartialDiagnostic *Diag; 509 510 public: 511 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 512 : Diag(Diag) {} 513 514 template<typename T> 515 OptionalDiagnostic &operator<<(const T &v) { 516 if (Diag) 517 *Diag << v; 518 return *this; 519 } 520 521 OptionalDiagnostic &operator<<(const APSInt &I) { 522 if (Diag) { 523 SmallVector<char, 32> Buffer; 524 I.toString(Buffer); 525 *Diag << StringRef(Buffer.data(), Buffer.size()); 526 } 527 return *this; 528 } 529 530 OptionalDiagnostic &operator<<(const APFloat &F) { 531 if (Diag) { 532 // FIXME: Force the precision of the source value down so we don't 533 // print digits which are usually useless (we don't really care here if 534 // we truncate a digit by accident in edge cases). Ideally, 535 // APFloat::toString would automatically print the shortest 536 // representation which rounds to the correct value, but it's a bit 537 // tricky to implement. 538 unsigned precision = 539 llvm::APFloat::semanticsPrecision(F.getSemantics()); 540 precision = (precision * 59 + 195) / 196; 541 SmallVector<char, 32> Buffer; 542 F.toString(Buffer, precision); 543 *Diag << StringRef(Buffer.data(), Buffer.size()); 544 } 545 return *this; 546 } 547 }; 548 549 /// A cleanup, and a flag indicating whether it is lifetime-extended. 550 class Cleanup { 551 llvm::PointerIntPair<APValue*, 1, bool> Value; 552 553 public: 554 Cleanup(APValue *Val, bool IsLifetimeExtended) 555 : Value(Val, IsLifetimeExtended) {} 556 557 bool isLifetimeExtended() const { return Value.getInt(); } 558 void endLifetime() { 559 *Value.getPointer() = APValue(); 560 } 561 }; 562 563 /// EvalInfo - This is a private struct used by the evaluator to capture 564 /// information about a subexpression as it is folded. It retains information 565 /// about the AST context, but also maintains information about the folded 566 /// expression. 567 /// 568 /// If an expression could be evaluated, it is still possible it is not a C 569 /// "integer constant expression" or constant expression. If not, this struct 570 /// captures information about how and why not. 571 /// 572 /// One bit of information passed *into* the request for constant folding 573 /// indicates whether the subexpression is "evaluated" or not according to C 574 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 575 /// evaluate the expression regardless of what the RHS is, but C only allows 576 /// certain things in certain situations. 577 struct EvalInfo { 578 ASTContext &Ctx; 579 580 /// EvalStatus - Contains information about the evaluation. 581 Expr::EvalStatus &EvalStatus; 582 583 /// CurrentCall - The top of the constexpr call stack. 584 CallStackFrame *CurrentCall; 585 586 /// CallStackDepth - The number of calls in the call stack right now. 587 unsigned CallStackDepth; 588 589 /// NextCallIndex - The next call index to assign. 590 unsigned NextCallIndex; 591 592 /// StepsLeft - The remaining number of evaluation steps we're permitted 593 /// to perform. This is essentially a limit for the number of statements 594 /// we will evaluate. 595 unsigned StepsLeft; 596 597 /// BottomFrame - The frame in which evaluation started. This must be 598 /// initialized after CurrentCall and CallStackDepth. 599 CallStackFrame BottomFrame; 600 601 /// A stack of values whose lifetimes end at the end of some surrounding 602 /// evaluation frame. 603 llvm::SmallVector<Cleanup, 16> CleanupStack; 604 605 /// EvaluatingDecl - This is the declaration whose initializer is being 606 /// evaluated, if any. 607 APValue::LValueBase EvaluatingDecl; 608 609 /// EvaluatingDeclValue - This is the value being constructed for the 610 /// declaration whose initializer is being evaluated, if any. 611 APValue *EvaluatingDeclValue; 612 613 /// EvaluatingObject - Pair of the AST node that an lvalue represents and 614 /// the call index that that lvalue was allocated in. 615 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject; 616 617 /// EvaluatingConstructors - Set of objects that are currently being 618 /// constructed. 619 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors; 620 621 struct EvaluatingConstructorRAII { 622 EvalInfo &EI; 623 EvaluatingObject Object; 624 bool DidInsert; 625 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object) 626 : EI(EI), Object(Object) { 627 DidInsert = EI.EvaluatingConstructors.insert(Object).second; 628 } 629 ~EvaluatingConstructorRAII() { 630 if (DidInsert) EI.EvaluatingConstructors.erase(Object); 631 } 632 }; 633 634 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) { 635 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex)); 636 } 637 638 /// The current array initialization index, if we're performing array 639 /// initialization. 640 uint64_t ArrayInitIndex = -1; 641 642 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 643 /// notes attached to it will also be stored, otherwise they will not be. 644 bool HasActiveDiagnostic; 645 646 /// \brief Have we emitted a diagnostic explaining why we couldn't constant 647 /// fold (not just why it's not strictly a constant expression)? 648 bool HasFoldFailureDiagnostic; 649 650 /// \brief Whether or not we're currently speculatively evaluating. 651 bool IsSpeculativelyEvaluating; 652 653 enum EvaluationMode { 654 /// Evaluate as a constant expression. Stop if we find that the expression 655 /// is not a constant expression. 656 EM_ConstantExpression, 657 658 /// Evaluate as a potential constant expression. Keep going if we hit a 659 /// construct that we can't evaluate yet (because we don't yet know the 660 /// value of something) but stop if we hit something that could never be 661 /// a constant expression. 662 EM_PotentialConstantExpression, 663 664 /// Fold the expression to a constant. Stop if we hit a side-effect that 665 /// we can't model. 666 EM_ConstantFold, 667 668 /// Evaluate the expression looking for integer overflow and similar 669 /// issues. Don't worry about side-effects, and try to visit all 670 /// subexpressions. 671 EM_EvaluateForOverflow, 672 673 /// Evaluate in any way we know how. Don't worry about side-effects that 674 /// can't be modeled. 675 EM_IgnoreSideEffects, 676 677 /// Evaluate as a constant expression. Stop if we find that the expression 678 /// is not a constant expression. Some expressions can be retried in the 679 /// optimizer if we don't constant fold them here, but in an unevaluated 680 /// context we try to fold them immediately since the optimizer never 681 /// gets a chance to look at it. 682 EM_ConstantExpressionUnevaluated, 683 684 /// Evaluate as a potential constant expression. Keep going if we hit a 685 /// construct that we can't evaluate yet (because we don't yet know the 686 /// value of something) but stop if we hit something that could never be 687 /// a constant expression. Some expressions can be retried in the 688 /// optimizer if we don't constant fold them here, but in an unevaluated 689 /// context we try to fold them immediately since the optimizer never 690 /// gets a chance to look at it. 691 EM_PotentialConstantExpressionUnevaluated, 692 693 /// Evaluate as a constant expression. In certain scenarios, if: 694 /// - we find a MemberExpr with a base that can't be evaluated, or 695 /// - we find a variable initialized with a call to a function that has 696 /// the alloc_size attribute on it 697 /// then we may consider evaluation to have succeeded. 698 /// 699 /// In either case, the LValue returned shall have an invalid base; in the 700 /// former, the base will be the invalid MemberExpr, in the latter, the 701 /// base will be either the alloc_size CallExpr or a CastExpr wrapping 702 /// said CallExpr. 703 EM_OffsetFold, 704 } EvalMode; 705 706 /// Are we checking whether the expression is a potential constant 707 /// expression? 708 bool checkingPotentialConstantExpression() const { 709 return EvalMode == EM_PotentialConstantExpression || 710 EvalMode == EM_PotentialConstantExpressionUnevaluated; 711 } 712 713 /// Are we checking an expression for overflow? 714 // FIXME: We should check for any kind of undefined or suspicious behavior 715 // in such constructs, not just overflow. 716 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 717 718 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 719 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 720 CallStackDepth(0), NextCallIndex(1), 721 StepsLeft(getLangOpts().ConstexprStepLimit), 722 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 723 EvaluatingDecl((const ValueDecl *)nullptr), 724 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 725 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false), 726 EvalMode(Mode) {} 727 728 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 729 EvaluatingDecl = Base; 730 EvaluatingDeclValue = &Value; 731 EvaluatingConstructors.insert({Base, 0}); 732 } 733 734 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 735 736 bool CheckCallLimit(SourceLocation Loc) { 737 // Don't perform any constexpr calls (other than the call we're checking) 738 // when checking a potential constant expression. 739 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 740 return false; 741 if (NextCallIndex == 0) { 742 // NextCallIndex has wrapped around. 743 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 744 return false; 745 } 746 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 747 return true; 748 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 749 << getLangOpts().ConstexprCallDepth; 750 return false; 751 } 752 753 CallStackFrame *getCallFrame(unsigned CallIndex) { 754 assert(CallIndex && "no call index in getCallFrame"); 755 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 756 // be null in this loop. 757 CallStackFrame *Frame = CurrentCall; 758 while (Frame->Index > CallIndex) 759 Frame = Frame->Caller; 760 return (Frame->Index == CallIndex) ? Frame : nullptr; 761 } 762 763 bool nextStep(const Stmt *S) { 764 if (!StepsLeft) { 765 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded); 766 return false; 767 } 768 --StepsLeft; 769 return true; 770 } 771 772 private: 773 /// Add a diagnostic to the diagnostics list. 774 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 775 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 776 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 777 return EvalStatus.Diag->back().second; 778 } 779 780 /// Add notes containing a call stack to the current point of evaluation. 781 void addCallStack(unsigned Limit); 782 783 private: 784 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 785 unsigned ExtraNotes, bool IsCCEDiag) { 786 787 if (EvalStatus.Diag) { 788 // If we have a prior diagnostic, it will be noting that the expression 789 // isn't a constant expression. This diagnostic is more important, 790 // unless we require this evaluation to produce a constant expression. 791 // 792 // FIXME: We might want to show both diagnostics to the user in 793 // EM_ConstantFold mode. 794 if (!EvalStatus.Diag->empty()) { 795 switch (EvalMode) { 796 case EM_ConstantFold: 797 case EM_IgnoreSideEffects: 798 case EM_EvaluateForOverflow: 799 if (!HasFoldFailureDiagnostic) 800 break; 801 // We've already failed to fold something. Keep that diagnostic. 802 LLVM_FALLTHROUGH; 803 case EM_ConstantExpression: 804 case EM_PotentialConstantExpression: 805 case EM_ConstantExpressionUnevaluated: 806 case EM_PotentialConstantExpressionUnevaluated: 807 case EM_OffsetFold: 808 HasActiveDiagnostic = false; 809 return OptionalDiagnostic(); 810 } 811 } 812 813 unsigned CallStackNotes = CallStackDepth - 1; 814 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 815 if (Limit) 816 CallStackNotes = std::min(CallStackNotes, Limit + 1); 817 if (checkingPotentialConstantExpression()) 818 CallStackNotes = 0; 819 820 HasActiveDiagnostic = true; 821 HasFoldFailureDiagnostic = !IsCCEDiag; 822 EvalStatus.Diag->clear(); 823 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 824 addDiag(Loc, DiagId); 825 if (!checkingPotentialConstantExpression()) 826 addCallStack(Limit); 827 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 828 } 829 HasActiveDiagnostic = false; 830 return OptionalDiagnostic(); 831 } 832 public: 833 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 834 OptionalDiagnostic 835 FFDiag(SourceLocation Loc, 836 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 837 unsigned ExtraNotes = 0) { 838 return Diag(Loc, DiagId, ExtraNotes, false); 839 } 840 841 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 842 = diag::note_invalid_subexpr_in_const_expr, 843 unsigned ExtraNotes = 0) { 844 if (EvalStatus.Diag) 845 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 846 HasActiveDiagnostic = false; 847 return OptionalDiagnostic(); 848 } 849 850 /// Diagnose that the evaluation does not produce a C++11 core constant 851 /// expression. 852 /// 853 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 854 /// EM_PotentialConstantExpression mode and we produce one of these. 855 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 856 = diag::note_invalid_subexpr_in_const_expr, 857 unsigned ExtraNotes = 0) { 858 // Don't override a previous diagnostic. Don't bother collecting 859 // diagnostics if we're evaluating for overflow. 860 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 861 HasActiveDiagnostic = false; 862 return OptionalDiagnostic(); 863 } 864 return Diag(Loc, DiagId, ExtraNotes, true); 865 } 866 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 867 = diag::note_invalid_subexpr_in_const_expr, 868 unsigned ExtraNotes = 0) { 869 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 870 } 871 /// Add a note to a prior diagnostic. 872 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 873 if (!HasActiveDiagnostic) 874 return OptionalDiagnostic(); 875 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 876 } 877 878 /// Add a stack of notes to a prior diagnostic. 879 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 880 if (HasActiveDiagnostic) { 881 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 882 Diags.begin(), Diags.end()); 883 } 884 } 885 886 /// Should we continue evaluation after encountering a side-effect that we 887 /// couldn't model? 888 bool keepEvaluatingAfterSideEffect() { 889 switch (EvalMode) { 890 case EM_PotentialConstantExpression: 891 case EM_PotentialConstantExpressionUnevaluated: 892 case EM_EvaluateForOverflow: 893 case EM_IgnoreSideEffects: 894 return true; 895 896 case EM_ConstantExpression: 897 case EM_ConstantExpressionUnevaluated: 898 case EM_ConstantFold: 899 case EM_OffsetFold: 900 return false; 901 } 902 llvm_unreachable("Missed EvalMode case"); 903 } 904 905 /// Note that we have had a side-effect, and determine whether we should 906 /// keep evaluating. 907 bool noteSideEffect() { 908 EvalStatus.HasSideEffects = true; 909 return keepEvaluatingAfterSideEffect(); 910 } 911 912 /// Should we continue evaluation after encountering undefined behavior? 913 bool keepEvaluatingAfterUndefinedBehavior() { 914 switch (EvalMode) { 915 case EM_EvaluateForOverflow: 916 case EM_IgnoreSideEffects: 917 case EM_ConstantFold: 918 case EM_OffsetFold: 919 return true; 920 921 case EM_PotentialConstantExpression: 922 case EM_PotentialConstantExpressionUnevaluated: 923 case EM_ConstantExpression: 924 case EM_ConstantExpressionUnevaluated: 925 return false; 926 } 927 llvm_unreachable("Missed EvalMode case"); 928 } 929 930 /// Note that we hit something that was technically undefined behavior, but 931 /// that we can evaluate past it (such as signed overflow or floating-point 932 /// division by zero.) 933 bool noteUndefinedBehavior() { 934 EvalStatus.HasUndefinedBehavior = true; 935 return keepEvaluatingAfterUndefinedBehavior(); 936 } 937 938 /// Should we continue evaluation as much as possible after encountering a 939 /// construct which can't be reduced to a value? 940 bool keepEvaluatingAfterFailure() { 941 if (!StepsLeft) 942 return false; 943 944 switch (EvalMode) { 945 case EM_PotentialConstantExpression: 946 case EM_PotentialConstantExpressionUnevaluated: 947 case EM_EvaluateForOverflow: 948 return true; 949 950 case EM_ConstantExpression: 951 case EM_ConstantExpressionUnevaluated: 952 case EM_ConstantFold: 953 case EM_IgnoreSideEffects: 954 case EM_OffsetFold: 955 return false; 956 } 957 llvm_unreachable("Missed EvalMode case"); 958 } 959 960 /// Notes that we failed to evaluate an expression that other expressions 961 /// directly depend on, and determine if we should keep evaluating. This 962 /// should only be called if we actually intend to keep evaluating. 963 /// 964 /// Call noteSideEffect() instead if we may be able to ignore the value that 965 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 966 /// 967 /// (Foo(), 1) // use noteSideEffect 968 /// (Foo() || true) // use noteSideEffect 969 /// Foo() + 1 // use noteFailure 970 LLVM_NODISCARD bool noteFailure() { 971 // Failure when evaluating some expression often means there is some 972 // subexpression whose evaluation was skipped. Therefore, (because we 973 // don't track whether we skipped an expression when unwinding after an 974 // evaluation failure) every evaluation failure that bubbles up from a 975 // subexpression implies that a side-effect has potentially happened. We 976 // skip setting the HasSideEffects flag to true until we decide to 977 // continue evaluating after that point, which happens here. 978 bool KeepGoing = keepEvaluatingAfterFailure(); 979 EvalStatus.HasSideEffects |= KeepGoing; 980 return KeepGoing; 981 } 982 983 class ArrayInitLoopIndex { 984 EvalInfo &Info; 985 uint64_t OuterIndex; 986 987 public: 988 ArrayInitLoopIndex(EvalInfo &Info) 989 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 990 Info.ArrayInitIndex = 0; 991 } 992 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 993 994 operator uint64_t&() { return Info.ArrayInitIndex; } 995 }; 996 }; 997 998 /// Object used to treat all foldable expressions as constant expressions. 999 struct FoldConstant { 1000 EvalInfo &Info; 1001 bool Enabled; 1002 bool HadNoPriorDiags; 1003 EvalInfo::EvaluationMode OldMode; 1004 1005 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1006 : Info(Info), 1007 Enabled(Enabled), 1008 HadNoPriorDiags(Info.EvalStatus.Diag && 1009 Info.EvalStatus.Diag->empty() && 1010 !Info.EvalStatus.HasSideEffects), 1011 OldMode(Info.EvalMode) { 1012 if (Enabled && 1013 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 1014 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 1015 Info.EvalMode = EvalInfo::EM_ConstantFold; 1016 } 1017 void keepDiagnostics() { Enabled = false; } 1018 ~FoldConstant() { 1019 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1020 !Info.EvalStatus.HasSideEffects) 1021 Info.EvalStatus.Diag->clear(); 1022 Info.EvalMode = OldMode; 1023 } 1024 }; 1025 1026 /// RAII object used to treat the current evaluation as the correct pointer 1027 /// offset fold for the current EvalMode 1028 struct FoldOffsetRAII { 1029 EvalInfo &Info; 1030 EvalInfo::EvaluationMode OldMode; 1031 explicit FoldOffsetRAII(EvalInfo &Info) 1032 : Info(Info), OldMode(Info.EvalMode) { 1033 if (!Info.checkingPotentialConstantExpression()) 1034 Info.EvalMode = EvalInfo::EM_OffsetFold; 1035 } 1036 1037 ~FoldOffsetRAII() { Info.EvalMode = OldMode; } 1038 }; 1039 1040 /// RAII object used to optionally suppress diagnostics and side-effects from 1041 /// a speculative evaluation. 1042 class SpeculativeEvaluationRAII { 1043 EvalInfo *Info = nullptr; 1044 Expr::EvalStatus OldStatus; 1045 bool OldIsSpeculativelyEvaluating; 1046 1047 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1048 Info = Other.Info; 1049 OldStatus = Other.OldStatus; 1050 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating; 1051 Other.Info = nullptr; 1052 } 1053 1054 void maybeRestoreState() { 1055 if (!Info) 1056 return; 1057 1058 Info->EvalStatus = OldStatus; 1059 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating; 1060 } 1061 1062 public: 1063 SpeculativeEvaluationRAII() = default; 1064 1065 SpeculativeEvaluationRAII( 1066 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1067 : Info(&Info), OldStatus(Info.EvalStatus), 1068 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) { 1069 Info.EvalStatus.Diag = NewDiag; 1070 Info.IsSpeculativelyEvaluating = true; 1071 } 1072 1073 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1074 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1075 moveFromAndCancel(std::move(Other)); 1076 } 1077 1078 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1079 maybeRestoreState(); 1080 moveFromAndCancel(std::move(Other)); 1081 return *this; 1082 } 1083 1084 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1085 }; 1086 1087 /// RAII object wrapping a full-expression or block scope, and handling 1088 /// the ending of the lifetime of temporaries created within it. 1089 template<bool IsFullExpression> 1090 class ScopeRAII { 1091 EvalInfo &Info; 1092 unsigned OldStackSize; 1093 public: 1094 ScopeRAII(EvalInfo &Info) 1095 : Info(Info), OldStackSize(Info.CleanupStack.size()) {} 1096 ~ScopeRAII() { 1097 // Body moved to a static method to encourage the compiler to inline away 1098 // instances of this class. 1099 cleanup(Info, OldStackSize); 1100 } 1101 private: 1102 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1103 unsigned NewEnd = OldStackSize; 1104 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1105 I != N; ++I) { 1106 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1107 // Full-expression cleanup of a lifetime-extended temporary: nothing 1108 // to do, just move this cleanup to the right place in the stack. 1109 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1110 ++NewEnd; 1111 } else { 1112 // End the lifetime of the object. 1113 Info.CleanupStack[I].endLifetime(); 1114 } 1115 } 1116 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1117 Info.CleanupStack.end()); 1118 } 1119 }; 1120 typedef ScopeRAII<false> BlockScopeRAII; 1121 typedef ScopeRAII<true> FullExpressionRAII; 1122 } 1123 1124 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1125 CheckSubobjectKind CSK) { 1126 if (Invalid) 1127 return false; 1128 if (isOnePastTheEnd()) { 1129 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1130 << CSK; 1131 setInvalid(); 1132 return false; 1133 } 1134 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1135 // must actually be at least one array element; even a VLA cannot have a 1136 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1137 return true; 1138 } 1139 1140 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1141 const Expr *E) { 1142 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1143 // Do not set the designator as invalid: we can represent this situation, 1144 // and correct handling of __builtin_object_size requires us to do so. 1145 } 1146 1147 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1148 const Expr *E, 1149 const APSInt &N) { 1150 // If we're complaining, we must be able to statically determine the size of 1151 // the most derived array. 1152 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1153 Info.CCEDiag(E, diag::note_constexpr_array_index) 1154 << N << /*array*/ 0 1155 << static_cast<unsigned>(getMostDerivedArraySize()); 1156 else 1157 Info.CCEDiag(E, diag::note_constexpr_array_index) 1158 << N << /*non-array*/ 1; 1159 setInvalid(); 1160 } 1161 1162 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1163 const FunctionDecl *Callee, const LValue *This, 1164 APValue *Arguments) 1165 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1166 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1167 Info.CurrentCall = this; 1168 ++Info.CallStackDepth; 1169 } 1170 1171 CallStackFrame::~CallStackFrame() { 1172 assert(Info.CurrentCall == this && "calls retired out of order"); 1173 --Info.CallStackDepth; 1174 Info.CurrentCall = Caller; 1175 } 1176 1177 APValue &CallStackFrame::createTemporary(const void *Key, 1178 bool IsLifetimeExtended) { 1179 APValue &Result = Temporaries[Key]; 1180 assert(Result.isUninit() && "temporary created multiple times"); 1181 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1182 return Result; 1183 } 1184 1185 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1186 1187 void EvalInfo::addCallStack(unsigned Limit) { 1188 // Determine which calls to skip, if any. 1189 unsigned ActiveCalls = CallStackDepth - 1; 1190 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1191 if (Limit && Limit < ActiveCalls) { 1192 SkipStart = Limit / 2 + Limit % 2; 1193 SkipEnd = ActiveCalls - Limit / 2; 1194 } 1195 1196 // Walk the call stack and add the diagnostics. 1197 unsigned CallIdx = 0; 1198 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1199 Frame = Frame->Caller, ++CallIdx) { 1200 // Skip this call? 1201 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1202 if (CallIdx == SkipStart) { 1203 // Note that we're skipping calls. 1204 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1205 << unsigned(ActiveCalls - Limit); 1206 } 1207 continue; 1208 } 1209 1210 // Use a different note for an inheriting constructor, because from the 1211 // user's perspective it's not really a function at all. 1212 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1213 if (CD->isInheritingConstructor()) { 1214 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1215 << CD->getParent(); 1216 continue; 1217 } 1218 } 1219 1220 SmallVector<char, 128> Buffer; 1221 llvm::raw_svector_ostream Out(Buffer); 1222 describeCall(Frame, Out); 1223 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1224 } 1225 } 1226 1227 namespace { 1228 struct ComplexValue { 1229 private: 1230 bool IsInt; 1231 1232 public: 1233 APSInt IntReal, IntImag; 1234 APFloat FloatReal, FloatImag; 1235 1236 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1237 1238 void makeComplexFloat() { IsInt = false; } 1239 bool isComplexFloat() const { return !IsInt; } 1240 APFloat &getComplexFloatReal() { return FloatReal; } 1241 APFloat &getComplexFloatImag() { return FloatImag; } 1242 1243 void makeComplexInt() { IsInt = true; } 1244 bool isComplexInt() const { return IsInt; } 1245 APSInt &getComplexIntReal() { return IntReal; } 1246 APSInt &getComplexIntImag() { return IntImag; } 1247 1248 void moveInto(APValue &v) const { 1249 if (isComplexFloat()) 1250 v = APValue(FloatReal, FloatImag); 1251 else 1252 v = APValue(IntReal, IntImag); 1253 } 1254 void setFrom(const APValue &v) { 1255 assert(v.isComplexFloat() || v.isComplexInt()); 1256 if (v.isComplexFloat()) { 1257 makeComplexFloat(); 1258 FloatReal = v.getComplexFloatReal(); 1259 FloatImag = v.getComplexFloatImag(); 1260 } else { 1261 makeComplexInt(); 1262 IntReal = v.getComplexIntReal(); 1263 IntImag = v.getComplexIntImag(); 1264 } 1265 } 1266 }; 1267 1268 struct LValue { 1269 APValue::LValueBase Base; 1270 CharUnits Offset; 1271 unsigned InvalidBase : 1; 1272 unsigned CallIndex : 31; 1273 SubobjectDesignator Designator; 1274 bool IsNullPtr; 1275 1276 const APValue::LValueBase getLValueBase() const { return Base; } 1277 CharUnits &getLValueOffset() { return Offset; } 1278 const CharUnits &getLValueOffset() const { return Offset; } 1279 unsigned getLValueCallIndex() const { return CallIndex; } 1280 SubobjectDesignator &getLValueDesignator() { return Designator; } 1281 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1282 bool isNullPointer() const { return IsNullPtr;} 1283 1284 void moveInto(APValue &V) const { 1285 if (Designator.Invalid) 1286 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex, 1287 IsNullPtr); 1288 else { 1289 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1290 V = APValue(Base, Offset, Designator.Entries, 1291 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr); 1292 } 1293 } 1294 void setFrom(ASTContext &Ctx, const APValue &V) { 1295 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1296 Base = V.getLValueBase(); 1297 Offset = V.getLValueOffset(); 1298 InvalidBase = false; 1299 CallIndex = V.getLValueCallIndex(); 1300 Designator = SubobjectDesignator(Ctx, V); 1301 IsNullPtr = V.isNullPointer(); 1302 } 1303 1304 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) { 1305 #ifndef NDEBUG 1306 // We only allow a few types of invalid bases. Enforce that here. 1307 if (BInvalid) { 1308 const auto *E = B.get<const Expr *>(); 1309 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1310 "Unexpected type of invalid base"); 1311 } 1312 #endif 1313 1314 Base = B; 1315 Offset = CharUnits::fromQuantity(0); 1316 InvalidBase = BInvalid; 1317 CallIndex = I; 1318 Designator = SubobjectDesignator(getType(B)); 1319 IsNullPtr = false; 1320 } 1321 1322 void setNull(QualType PointerTy, uint64_t TargetVal) { 1323 Base = (Expr *)nullptr; 1324 Offset = CharUnits::fromQuantity(TargetVal); 1325 InvalidBase = false; 1326 CallIndex = 0; 1327 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1328 IsNullPtr = true; 1329 } 1330 1331 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1332 set(B, I, true); 1333 } 1334 1335 // Check that this LValue is not based on a null pointer. If it is, produce 1336 // a diagnostic and mark the designator as invalid. 1337 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1338 CheckSubobjectKind CSK) { 1339 if (Designator.Invalid) 1340 return false; 1341 if (IsNullPtr) { 1342 Info.CCEDiag(E, diag::note_constexpr_null_subobject) 1343 << CSK; 1344 Designator.setInvalid(); 1345 return false; 1346 } 1347 return true; 1348 } 1349 1350 // Check this LValue refers to an object. If not, set the designator to be 1351 // invalid and emit a diagnostic. 1352 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1353 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1354 Designator.checkSubobject(Info, E, CSK); 1355 } 1356 1357 void addDecl(EvalInfo &Info, const Expr *E, 1358 const Decl *D, bool Virtual = false) { 1359 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1360 Designator.addDeclUnchecked(D, Virtual); 1361 } 1362 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1363 if (!Designator.Entries.empty()) { 1364 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1365 Designator.setInvalid(); 1366 return; 1367 } 1368 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1369 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1370 Designator.FirstEntryIsAnUnsizedArray = true; 1371 Designator.addUnsizedArrayUnchecked(ElemTy); 1372 } 1373 } 1374 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1375 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1376 Designator.addArrayUnchecked(CAT); 1377 } 1378 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1379 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1380 Designator.addComplexUnchecked(EltTy, Imag); 1381 } 1382 void clearIsNullPointer() { 1383 IsNullPtr = false; 1384 } 1385 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1386 const APSInt &Index, CharUnits ElementSize) { 1387 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1388 // but we're not required to diagnose it and it's valid in C++.) 1389 if (!Index) 1390 return; 1391 1392 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1393 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1394 // offsets. 1395 uint64_t Offset64 = Offset.getQuantity(); 1396 uint64_t ElemSize64 = ElementSize.getQuantity(); 1397 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1398 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1399 1400 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1401 Designator.adjustIndex(Info, E, Index); 1402 clearIsNullPointer(); 1403 } 1404 void adjustOffset(CharUnits N) { 1405 Offset += N; 1406 if (N.getQuantity()) 1407 clearIsNullPointer(); 1408 } 1409 }; 1410 1411 struct MemberPtr { 1412 MemberPtr() {} 1413 explicit MemberPtr(const ValueDecl *Decl) : 1414 DeclAndIsDerivedMember(Decl, false), Path() {} 1415 1416 /// The member or (direct or indirect) field referred to by this member 1417 /// pointer, or 0 if this is a null member pointer. 1418 const ValueDecl *getDecl() const { 1419 return DeclAndIsDerivedMember.getPointer(); 1420 } 1421 /// Is this actually a member of some type derived from the relevant class? 1422 bool isDerivedMember() const { 1423 return DeclAndIsDerivedMember.getInt(); 1424 } 1425 /// Get the class which the declaration actually lives in. 1426 const CXXRecordDecl *getContainingRecord() const { 1427 return cast<CXXRecordDecl>( 1428 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1429 } 1430 1431 void moveInto(APValue &V) const { 1432 V = APValue(getDecl(), isDerivedMember(), Path); 1433 } 1434 void setFrom(const APValue &V) { 1435 assert(V.isMemberPointer()); 1436 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1437 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1438 Path.clear(); 1439 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1440 Path.insert(Path.end(), P.begin(), P.end()); 1441 } 1442 1443 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1444 /// whether the member is a member of some class derived from the class type 1445 /// of the member pointer. 1446 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1447 /// Path - The path of base/derived classes from the member declaration's 1448 /// class (exclusive) to the class type of the member pointer (inclusive). 1449 SmallVector<const CXXRecordDecl*, 4> Path; 1450 1451 /// Perform a cast towards the class of the Decl (either up or down the 1452 /// hierarchy). 1453 bool castBack(const CXXRecordDecl *Class) { 1454 assert(!Path.empty()); 1455 const CXXRecordDecl *Expected; 1456 if (Path.size() >= 2) 1457 Expected = Path[Path.size() - 2]; 1458 else 1459 Expected = getContainingRecord(); 1460 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1461 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1462 // if B does not contain the original member and is not a base or 1463 // derived class of the class containing the original member, the result 1464 // of the cast is undefined. 1465 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1466 // (D::*). We consider that to be a language defect. 1467 return false; 1468 } 1469 Path.pop_back(); 1470 return true; 1471 } 1472 /// Perform a base-to-derived member pointer cast. 1473 bool castToDerived(const CXXRecordDecl *Derived) { 1474 if (!getDecl()) 1475 return true; 1476 if (!isDerivedMember()) { 1477 Path.push_back(Derived); 1478 return true; 1479 } 1480 if (!castBack(Derived)) 1481 return false; 1482 if (Path.empty()) 1483 DeclAndIsDerivedMember.setInt(false); 1484 return true; 1485 } 1486 /// Perform a derived-to-base member pointer cast. 1487 bool castToBase(const CXXRecordDecl *Base) { 1488 if (!getDecl()) 1489 return true; 1490 if (Path.empty()) 1491 DeclAndIsDerivedMember.setInt(true); 1492 if (isDerivedMember()) { 1493 Path.push_back(Base); 1494 return true; 1495 } 1496 return castBack(Base); 1497 } 1498 }; 1499 1500 /// Compare two member pointers, which are assumed to be of the same type. 1501 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1502 if (!LHS.getDecl() || !RHS.getDecl()) 1503 return !LHS.getDecl() && !RHS.getDecl(); 1504 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1505 return false; 1506 return LHS.Path == RHS.Path; 1507 } 1508 } 1509 1510 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1511 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1512 const LValue &This, const Expr *E, 1513 bool AllowNonLiteralTypes = false); 1514 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1515 bool InvalidBaseOK = false); 1516 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1517 bool InvalidBaseOK = false); 1518 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1519 EvalInfo &Info); 1520 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1521 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1522 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1523 EvalInfo &Info); 1524 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1525 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1526 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1527 EvalInfo &Info); 1528 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1529 1530 //===----------------------------------------------------------------------===// 1531 // Misc utilities 1532 //===----------------------------------------------------------------------===// 1533 1534 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1535 /// preserving its value (by extending by up to one bit as needed). 1536 static void negateAsSigned(APSInt &Int) { 1537 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1538 Int = Int.extend(Int.getBitWidth() + 1); 1539 Int.setIsSigned(true); 1540 } 1541 Int = -Int; 1542 } 1543 1544 /// Produce a string describing the given constexpr call. 1545 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1546 unsigned ArgIndex = 0; 1547 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1548 !isa<CXXConstructorDecl>(Frame->Callee) && 1549 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1550 1551 if (!IsMemberCall) 1552 Out << *Frame->Callee << '('; 1553 1554 if (Frame->This && IsMemberCall) { 1555 APValue Val; 1556 Frame->This->moveInto(Val); 1557 Val.printPretty(Out, Frame->Info.Ctx, 1558 Frame->This->Designator.MostDerivedType); 1559 // FIXME: Add parens around Val if needed. 1560 Out << "->" << *Frame->Callee << '('; 1561 IsMemberCall = false; 1562 } 1563 1564 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1565 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1566 if (ArgIndex > (unsigned)IsMemberCall) 1567 Out << ", "; 1568 1569 const ParmVarDecl *Param = *I; 1570 const APValue &Arg = Frame->Arguments[ArgIndex]; 1571 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1572 1573 if (ArgIndex == 0 && IsMemberCall) 1574 Out << "->" << *Frame->Callee << '('; 1575 } 1576 1577 Out << ')'; 1578 } 1579 1580 /// Evaluate an expression to see if it had side-effects, and discard its 1581 /// result. 1582 /// \return \c true if the caller should keep evaluating. 1583 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1584 APValue Scratch; 1585 if (!Evaluate(Scratch, Info, E)) 1586 // We don't need the value, but we might have skipped a side effect here. 1587 return Info.noteSideEffect(); 1588 return true; 1589 } 1590 1591 /// Should this call expression be treated as a string literal? 1592 static bool IsStringLiteralCall(const CallExpr *E) { 1593 unsigned Builtin = E->getBuiltinCallee(); 1594 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1595 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1596 } 1597 1598 static bool IsGlobalLValue(APValue::LValueBase B) { 1599 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1600 // constant expression of pointer type that evaluates to... 1601 1602 // ... a null pointer value, or a prvalue core constant expression of type 1603 // std::nullptr_t. 1604 if (!B) return true; 1605 1606 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1607 // ... the address of an object with static storage duration, 1608 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1609 return VD->hasGlobalStorage(); 1610 // ... the address of a function, 1611 return isa<FunctionDecl>(D); 1612 } 1613 1614 const Expr *E = B.get<const Expr*>(); 1615 switch (E->getStmtClass()) { 1616 default: 1617 return false; 1618 case Expr::CompoundLiteralExprClass: { 1619 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1620 return CLE->isFileScope() && CLE->isLValue(); 1621 } 1622 case Expr::MaterializeTemporaryExprClass: 1623 // A materialized temporary might have been lifetime-extended to static 1624 // storage duration. 1625 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1626 // A string literal has static storage duration. 1627 case Expr::StringLiteralClass: 1628 case Expr::PredefinedExprClass: 1629 case Expr::ObjCStringLiteralClass: 1630 case Expr::ObjCEncodeExprClass: 1631 case Expr::CXXTypeidExprClass: 1632 case Expr::CXXUuidofExprClass: 1633 return true; 1634 case Expr::CallExprClass: 1635 return IsStringLiteralCall(cast<CallExpr>(E)); 1636 // For GCC compatibility, &&label has static storage duration. 1637 case Expr::AddrLabelExprClass: 1638 return true; 1639 // A Block literal expression may be used as the initialization value for 1640 // Block variables at global or local static scope. 1641 case Expr::BlockExprClass: 1642 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1643 case Expr::ImplicitValueInitExprClass: 1644 // FIXME: 1645 // We can never form an lvalue with an implicit value initialization as its 1646 // base through expression evaluation, so these only appear in one case: the 1647 // implicit variable declaration we invent when checking whether a constexpr 1648 // constructor can produce a constant expression. We must assume that such 1649 // an expression might be a global lvalue. 1650 return true; 1651 } 1652 } 1653 1654 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1655 assert(Base && "no location for a null lvalue"); 1656 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1657 if (VD) 1658 Info.Note(VD->getLocation(), diag::note_declared_at); 1659 else 1660 Info.Note(Base.get<const Expr*>()->getExprLoc(), 1661 diag::note_constexpr_temporary_here); 1662 } 1663 1664 /// Check that this reference or pointer core constant expression is a valid 1665 /// value for an address or reference constant expression. Return true if we 1666 /// can fold this expression, whether or not it's a constant expression. 1667 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1668 QualType Type, const LValue &LVal) { 1669 bool IsReferenceType = Type->isReferenceType(); 1670 1671 APValue::LValueBase Base = LVal.getLValueBase(); 1672 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1673 1674 // Check that the object is a global. Note that the fake 'this' object we 1675 // manufacture when checking potential constant expressions is conservatively 1676 // assumed to be global here. 1677 if (!IsGlobalLValue(Base)) { 1678 if (Info.getLangOpts().CPlusPlus11) { 1679 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1680 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1681 << IsReferenceType << !Designator.Entries.empty() 1682 << !!VD << VD; 1683 NoteLValueLocation(Info, Base); 1684 } else { 1685 Info.FFDiag(Loc); 1686 } 1687 // Don't allow references to temporaries to escape. 1688 return false; 1689 } 1690 assert((Info.checkingPotentialConstantExpression() || 1691 LVal.getLValueCallIndex() == 0) && 1692 "have call index for global lvalue"); 1693 1694 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1695 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1696 // Check if this is a thread-local variable. 1697 if (Var->getTLSKind()) 1698 return false; 1699 1700 // A dllimport variable never acts like a constant. 1701 if (Var->hasAttr<DLLImportAttr>()) 1702 return false; 1703 } 1704 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1705 // __declspec(dllimport) must be handled very carefully: 1706 // We must never initialize an expression with the thunk in C++. 1707 // Doing otherwise would allow the same id-expression to yield 1708 // different addresses for the same function in different translation 1709 // units. However, this means that we must dynamically initialize the 1710 // expression with the contents of the import address table at runtime. 1711 // 1712 // The C language has no notion of ODR; furthermore, it has no notion of 1713 // dynamic initialization. This means that we are permitted to 1714 // perform initialization with the address of the thunk. 1715 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>()) 1716 return false; 1717 } 1718 } 1719 1720 // Allow address constant expressions to be past-the-end pointers. This is 1721 // an extension: the standard requires them to point to an object. 1722 if (!IsReferenceType) 1723 return true; 1724 1725 // A reference constant expression must refer to an object. 1726 if (!Base) { 1727 // FIXME: diagnostic 1728 Info.CCEDiag(Loc); 1729 return true; 1730 } 1731 1732 // Does this refer one past the end of some object? 1733 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1734 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1735 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1736 << !Designator.Entries.empty() << !!VD << VD; 1737 NoteLValueLocation(Info, Base); 1738 } 1739 1740 return true; 1741 } 1742 1743 /// Member pointers are constant expressions unless they point to a 1744 /// non-virtual dllimport member function. 1745 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 1746 SourceLocation Loc, 1747 QualType Type, 1748 const APValue &Value) { 1749 const ValueDecl *Member = Value.getMemberPointerDecl(); 1750 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 1751 if (!FD) 1752 return true; 1753 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>(); 1754 } 1755 1756 /// Check that this core constant expression is of literal type, and if not, 1757 /// produce an appropriate diagnostic. 1758 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 1759 const LValue *This = nullptr) { 1760 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 1761 return true; 1762 1763 // C++1y: A constant initializer for an object o [...] may also invoke 1764 // constexpr constructors for o and its subobjects even if those objects 1765 // are of non-literal class types. 1766 // 1767 // C++11 missed this detail for aggregates, so classes like this: 1768 // struct foo_t { union { int i; volatile int j; } u; }; 1769 // are not (obviously) initializable like so: 1770 // __attribute__((__require_constant_initialization__)) 1771 // static const foo_t x = {{0}}; 1772 // because "i" is a subobject with non-literal initialization (due to the 1773 // volatile member of the union). See: 1774 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 1775 // Therefore, we use the C++1y behavior. 1776 if (This && Info.EvaluatingDecl == This->getLValueBase()) 1777 return true; 1778 1779 // Prvalue constant expressions must be of literal types. 1780 if (Info.getLangOpts().CPlusPlus11) 1781 Info.FFDiag(E, diag::note_constexpr_nonliteral) 1782 << E->getType(); 1783 else 1784 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1785 return false; 1786 } 1787 1788 /// Check that this core constant expression value is a valid value for a 1789 /// constant expression. If not, report an appropriate diagnostic. Does not 1790 /// check that the expression is of literal type. 1791 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 1792 QualType Type, const APValue &Value) { 1793 if (Value.isUninit()) { 1794 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 1795 << true << Type; 1796 return false; 1797 } 1798 1799 // We allow _Atomic(T) to be initialized from anything that T can be 1800 // initialized from. 1801 if (const AtomicType *AT = Type->getAs<AtomicType>()) 1802 Type = AT->getValueType(); 1803 1804 // Core issue 1454: For a literal constant expression of array or class type, 1805 // each subobject of its value shall have been initialized by a constant 1806 // expression. 1807 if (Value.isArray()) { 1808 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 1809 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 1810 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 1811 Value.getArrayInitializedElt(I))) 1812 return false; 1813 } 1814 if (!Value.hasArrayFiller()) 1815 return true; 1816 return CheckConstantExpression(Info, DiagLoc, EltTy, 1817 Value.getArrayFiller()); 1818 } 1819 if (Value.isUnion() && Value.getUnionField()) { 1820 return CheckConstantExpression(Info, DiagLoc, 1821 Value.getUnionField()->getType(), 1822 Value.getUnionValue()); 1823 } 1824 if (Value.isStruct()) { 1825 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 1826 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 1827 unsigned BaseIndex = 0; 1828 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 1829 End = CD->bases_end(); I != End; ++I, ++BaseIndex) { 1830 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1831 Value.getStructBase(BaseIndex))) 1832 return false; 1833 } 1834 } 1835 for (const auto *I : RD->fields()) { 1836 if (I->isUnnamedBitfield()) 1837 continue; 1838 1839 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1840 Value.getStructField(I->getFieldIndex()))) 1841 return false; 1842 } 1843 } 1844 1845 if (Value.isLValue()) { 1846 LValue LVal; 1847 LVal.setFrom(Info.Ctx, Value); 1848 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal); 1849 } 1850 1851 if (Value.isMemberPointer()) 1852 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value); 1853 1854 // Everything else is fine. 1855 return true; 1856 } 1857 1858 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1859 return LVal.Base.dyn_cast<const ValueDecl*>(); 1860 } 1861 1862 static bool IsLiteralLValue(const LValue &Value) { 1863 if (Value.CallIndex) 1864 return false; 1865 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1866 return E && !isa<MaterializeTemporaryExpr>(E); 1867 } 1868 1869 static bool IsWeakLValue(const LValue &Value) { 1870 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1871 return Decl && Decl->isWeak(); 1872 } 1873 1874 static bool isZeroSized(const LValue &Value) { 1875 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1876 if (Decl && isa<VarDecl>(Decl)) { 1877 QualType Ty = Decl->getType(); 1878 if (Ty->isArrayType()) 1879 return Ty->isIncompleteType() || 1880 Decl->getASTContext().getTypeSize(Ty) == 0; 1881 } 1882 return false; 1883 } 1884 1885 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 1886 // A null base expression indicates a null pointer. These are always 1887 // evaluatable, and they are false unless the offset is zero. 1888 if (!Value.getLValueBase()) { 1889 Result = !Value.getLValueOffset().isZero(); 1890 return true; 1891 } 1892 1893 // We have a non-null base. These are generally known to be true, but if it's 1894 // a weak declaration it can be null at runtime. 1895 Result = true; 1896 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 1897 return !Decl || !Decl->isWeak(); 1898 } 1899 1900 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 1901 switch (Val.getKind()) { 1902 case APValue::Uninitialized: 1903 return false; 1904 case APValue::Int: 1905 Result = Val.getInt().getBoolValue(); 1906 return true; 1907 case APValue::Float: 1908 Result = !Val.getFloat().isZero(); 1909 return true; 1910 case APValue::ComplexInt: 1911 Result = Val.getComplexIntReal().getBoolValue() || 1912 Val.getComplexIntImag().getBoolValue(); 1913 return true; 1914 case APValue::ComplexFloat: 1915 Result = !Val.getComplexFloatReal().isZero() || 1916 !Val.getComplexFloatImag().isZero(); 1917 return true; 1918 case APValue::LValue: 1919 return EvalPointerValueAsBool(Val, Result); 1920 case APValue::MemberPointer: 1921 Result = Val.getMemberPointerDecl(); 1922 return true; 1923 case APValue::Vector: 1924 case APValue::Array: 1925 case APValue::Struct: 1926 case APValue::Union: 1927 case APValue::AddrLabelDiff: 1928 return false; 1929 } 1930 1931 llvm_unreachable("unknown APValue kind"); 1932 } 1933 1934 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 1935 EvalInfo &Info) { 1936 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 1937 APValue Val; 1938 if (!Evaluate(Val, Info, E)) 1939 return false; 1940 return HandleConversionToBool(Val, Result); 1941 } 1942 1943 template<typename T> 1944 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 1945 const T &SrcValue, QualType DestType) { 1946 Info.CCEDiag(E, diag::note_constexpr_overflow) 1947 << SrcValue << DestType; 1948 return Info.noteUndefinedBehavior(); 1949 } 1950 1951 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 1952 QualType SrcType, const APFloat &Value, 1953 QualType DestType, APSInt &Result) { 1954 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 1955 // Determine whether we are converting to unsigned or signed. 1956 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 1957 1958 Result = APSInt(DestWidth, !DestSigned); 1959 bool ignored; 1960 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 1961 & APFloat::opInvalidOp) 1962 return HandleOverflow(Info, E, Value, DestType); 1963 return true; 1964 } 1965 1966 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 1967 QualType SrcType, QualType DestType, 1968 APFloat &Result) { 1969 APFloat Value = Result; 1970 bool ignored; 1971 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 1972 APFloat::rmNearestTiesToEven, &ignored) 1973 & APFloat::opOverflow) 1974 return HandleOverflow(Info, E, Value, DestType); 1975 return true; 1976 } 1977 1978 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 1979 QualType DestType, QualType SrcType, 1980 const APSInt &Value) { 1981 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 1982 APSInt Result = Value; 1983 // Figure out if this is a truncate, extend or noop cast. 1984 // If the input is signed, do a sign extend, noop, or truncate. 1985 Result = Result.extOrTrunc(DestWidth); 1986 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 1987 return Result; 1988 } 1989 1990 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 1991 QualType SrcType, const APSInt &Value, 1992 QualType DestType, APFloat &Result) { 1993 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 1994 if (Result.convertFromAPInt(Value, Value.isSigned(), 1995 APFloat::rmNearestTiesToEven) 1996 & APFloat::opOverflow) 1997 return HandleOverflow(Info, E, Value, DestType); 1998 return true; 1999 } 2000 2001 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2002 APValue &Value, const FieldDecl *FD) { 2003 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2004 2005 if (!Value.isInt()) { 2006 // Trying to store a pointer-cast-to-integer into a bitfield. 2007 // FIXME: In this case, we should provide the diagnostic for casting 2008 // a pointer to an integer. 2009 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2010 Info.FFDiag(E); 2011 return false; 2012 } 2013 2014 APSInt &Int = Value.getInt(); 2015 unsigned OldBitWidth = Int.getBitWidth(); 2016 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2017 if (NewBitWidth < OldBitWidth) 2018 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2019 return true; 2020 } 2021 2022 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2023 llvm::APInt &Res) { 2024 APValue SVal; 2025 if (!Evaluate(SVal, Info, E)) 2026 return false; 2027 if (SVal.isInt()) { 2028 Res = SVal.getInt(); 2029 return true; 2030 } 2031 if (SVal.isFloat()) { 2032 Res = SVal.getFloat().bitcastToAPInt(); 2033 return true; 2034 } 2035 if (SVal.isVector()) { 2036 QualType VecTy = E->getType(); 2037 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2038 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2039 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2040 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2041 Res = llvm::APInt::getNullValue(VecSize); 2042 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2043 APValue &Elt = SVal.getVectorElt(i); 2044 llvm::APInt EltAsInt; 2045 if (Elt.isInt()) { 2046 EltAsInt = Elt.getInt(); 2047 } else if (Elt.isFloat()) { 2048 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2049 } else { 2050 // Don't try to handle vectors of anything other than int or float 2051 // (not sure if it's possible to hit this case). 2052 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2053 return false; 2054 } 2055 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2056 if (BigEndian) 2057 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2058 else 2059 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2060 } 2061 return true; 2062 } 2063 // Give up if the input isn't an int, float, or vector. For example, we 2064 // reject "(v4i16)(intptr_t)&a". 2065 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2066 return false; 2067 } 2068 2069 /// Perform the given integer operation, which is known to need at most BitWidth 2070 /// bits, and check for overflow in the original type (if that type was not an 2071 /// unsigned type). 2072 template<typename Operation> 2073 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2074 const APSInt &LHS, const APSInt &RHS, 2075 unsigned BitWidth, Operation Op, 2076 APSInt &Result) { 2077 if (LHS.isUnsigned()) { 2078 Result = Op(LHS, RHS); 2079 return true; 2080 } 2081 2082 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2083 Result = Value.trunc(LHS.getBitWidth()); 2084 if (Result.extend(BitWidth) != Value) { 2085 if (Info.checkingForOverflow()) 2086 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2087 diag::warn_integer_constant_overflow) 2088 << Result.toString(10) << E->getType(); 2089 else 2090 return HandleOverflow(Info, E, Value, E->getType()); 2091 } 2092 return true; 2093 } 2094 2095 /// Perform the given binary integer operation. 2096 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2097 BinaryOperatorKind Opcode, APSInt RHS, 2098 APSInt &Result) { 2099 switch (Opcode) { 2100 default: 2101 Info.FFDiag(E); 2102 return false; 2103 case BO_Mul: 2104 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2105 std::multiplies<APSInt>(), Result); 2106 case BO_Add: 2107 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2108 std::plus<APSInt>(), Result); 2109 case BO_Sub: 2110 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2111 std::minus<APSInt>(), Result); 2112 case BO_And: Result = LHS & RHS; return true; 2113 case BO_Xor: Result = LHS ^ RHS; return true; 2114 case BO_Or: Result = LHS | RHS; return true; 2115 case BO_Div: 2116 case BO_Rem: 2117 if (RHS == 0) { 2118 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2119 return false; 2120 } 2121 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2122 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2123 // this operation and gives the two's complement result. 2124 if (RHS.isNegative() && RHS.isAllOnesValue() && 2125 LHS.isSigned() && LHS.isMinSignedValue()) 2126 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2127 E->getType()); 2128 return true; 2129 case BO_Shl: { 2130 if (Info.getLangOpts().OpenCL) 2131 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2132 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2133 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2134 RHS.isUnsigned()); 2135 else if (RHS.isSigned() && RHS.isNegative()) { 2136 // During constant-folding, a negative shift is an opposite shift. Such 2137 // a shift is not a constant expression. 2138 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2139 RHS = -RHS; 2140 goto shift_right; 2141 } 2142 shift_left: 2143 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2144 // the shifted type. 2145 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2146 if (SA != RHS) { 2147 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2148 << RHS << E->getType() << LHS.getBitWidth(); 2149 } else if (LHS.isSigned()) { 2150 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2151 // operand, and must not overflow the corresponding unsigned type. 2152 if (LHS.isNegative()) 2153 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2154 else if (LHS.countLeadingZeros() < SA) 2155 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2156 } 2157 Result = LHS << SA; 2158 return true; 2159 } 2160 case BO_Shr: { 2161 if (Info.getLangOpts().OpenCL) 2162 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2163 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2164 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2165 RHS.isUnsigned()); 2166 else if (RHS.isSigned() && RHS.isNegative()) { 2167 // During constant-folding, a negative shift is an opposite shift. Such a 2168 // shift is not a constant expression. 2169 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2170 RHS = -RHS; 2171 goto shift_left; 2172 } 2173 shift_right: 2174 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2175 // shifted type. 2176 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2177 if (SA != RHS) 2178 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2179 << RHS << E->getType() << LHS.getBitWidth(); 2180 Result = LHS >> SA; 2181 return true; 2182 } 2183 2184 case BO_LT: Result = LHS < RHS; return true; 2185 case BO_GT: Result = LHS > RHS; return true; 2186 case BO_LE: Result = LHS <= RHS; return true; 2187 case BO_GE: Result = LHS >= RHS; return true; 2188 case BO_EQ: Result = LHS == RHS; return true; 2189 case BO_NE: Result = LHS != RHS; return true; 2190 } 2191 } 2192 2193 /// Perform the given binary floating-point operation, in-place, on LHS. 2194 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2195 APFloat &LHS, BinaryOperatorKind Opcode, 2196 const APFloat &RHS) { 2197 switch (Opcode) { 2198 default: 2199 Info.FFDiag(E); 2200 return false; 2201 case BO_Mul: 2202 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2203 break; 2204 case BO_Add: 2205 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2206 break; 2207 case BO_Sub: 2208 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2209 break; 2210 case BO_Div: 2211 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2212 break; 2213 } 2214 2215 if (LHS.isInfinity() || LHS.isNaN()) { 2216 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2217 return Info.noteUndefinedBehavior(); 2218 } 2219 return true; 2220 } 2221 2222 /// Cast an lvalue referring to a base subobject to a derived class, by 2223 /// truncating the lvalue's path to the given length. 2224 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2225 const RecordDecl *TruncatedType, 2226 unsigned TruncatedElements) { 2227 SubobjectDesignator &D = Result.Designator; 2228 2229 // Check we actually point to a derived class object. 2230 if (TruncatedElements == D.Entries.size()) 2231 return true; 2232 assert(TruncatedElements >= D.MostDerivedPathLength && 2233 "not casting to a derived class"); 2234 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2235 return false; 2236 2237 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2238 const RecordDecl *RD = TruncatedType; 2239 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2240 if (RD->isInvalidDecl()) return false; 2241 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2242 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2243 if (isVirtualBaseClass(D.Entries[I])) 2244 Result.Offset -= Layout.getVBaseClassOffset(Base); 2245 else 2246 Result.Offset -= Layout.getBaseClassOffset(Base); 2247 RD = Base; 2248 } 2249 D.Entries.resize(TruncatedElements); 2250 return true; 2251 } 2252 2253 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2254 const CXXRecordDecl *Derived, 2255 const CXXRecordDecl *Base, 2256 const ASTRecordLayout *RL = nullptr) { 2257 if (!RL) { 2258 if (Derived->isInvalidDecl()) return false; 2259 RL = &Info.Ctx.getASTRecordLayout(Derived); 2260 } 2261 2262 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2263 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2264 return true; 2265 } 2266 2267 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2268 const CXXRecordDecl *DerivedDecl, 2269 const CXXBaseSpecifier *Base) { 2270 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2271 2272 if (!Base->isVirtual()) 2273 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2274 2275 SubobjectDesignator &D = Obj.Designator; 2276 if (D.Invalid) 2277 return false; 2278 2279 // Extract most-derived object and corresponding type. 2280 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2281 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2282 return false; 2283 2284 // Find the virtual base class. 2285 if (DerivedDecl->isInvalidDecl()) return false; 2286 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2287 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2288 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2289 return true; 2290 } 2291 2292 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2293 QualType Type, LValue &Result) { 2294 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2295 PathE = E->path_end(); 2296 PathI != PathE; ++PathI) { 2297 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2298 *PathI)) 2299 return false; 2300 Type = (*PathI)->getType(); 2301 } 2302 return true; 2303 } 2304 2305 /// Update LVal to refer to the given field, which must be a member of the type 2306 /// currently described by LVal. 2307 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2308 const FieldDecl *FD, 2309 const ASTRecordLayout *RL = nullptr) { 2310 if (!RL) { 2311 if (FD->getParent()->isInvalidDecl()) return false; 2312 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2313 } 2314 2315 unsigned I = FD->getFieldIndex(); 2316 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2317 LVal.addDecl(Info, E, FD); 2318 return true; 2319 } 2320 2321 /// Update LVal to refer to the given indirect field. 2322 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2323 LValue &LVal, 2324 const IndirectFieldDecl *IFD) { 2325 for (const auto *C : IFD->chain()) 2326 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2327 return false; 2328 return true; 2329 } 2330 2331 /// Get the size of the given type in char units. 2332 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2333 QualType Type, CharUnits &Size) { 2334 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2335 // extension. 2336 if (Type->isVoidType() || Type->isFunctionType()) { 2337 Size = CharUnits::One(); 2338 return true; 2339 } 2340 2341 if (Type->isDependentType()) { 2342 Info.FFDiag(Loc); 2343 return false; 2344 } 2345 2346 if (!Type->isConstantSizeType()) { 2347 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2348 // FIXME: Better diagnostic. 2349 Info.FFDiag(Loc); 2350 return false; 2351 } 2352 2353 Size = Info.Ctx.getTypeSizeInChars(Type); 2354 return true; 2355 } 2356 2357 /// Update a pointer value to model pointer arithmetic. 2358 /// \param Info - Information about the ongoing evaluation. 2359 /// \param E - The expression being evaluated, for diagnostic purposes. 2360 /// \param LVal - The pointer value to be updated. 2361 /// \param EltTy - The pointee type represented by LVal. 2362 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2363 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2364 LValue &LVal, QualType EltTy, 2365 APSInt Adjustment) { 2366 CharUnits SizeOfPointee; 2367 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2368 return false; 2369 2370 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2371 return true; 2372 } 2373 2374 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2375 LValue &LVal, QualType EltTy, 2376 int64_t Adjustment) { 2377 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2378 APSInt::get(Adjustment)); 2379 } 2380 2381 /// Update an lvalue to refer to a component of a complex number. 2382 /// \param Info - Information about the ongoing evaluation. 2383 /// \param LVal - The lvalue to be updated. 2384 /// \param EltTy - The complex number's component type. 2385 /// \param Imag - False for the real component, true for the imaginary. 2386 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2387 LValue &LVal, QualType EltTy, 2388 bool Imag) { 2389 if (Imag) { 2390 CharUnits SizeOfComponent; 2391 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2392 return false; 2393 LVal.Offset += SizeOfComponent; 2394 } 2395 LVal.addComplex(Info, E, EltTy, Imag); 2396 return true; 2397 } 2398 2399 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 2400 QualType Type, const LValue &LVal, 2401 APValue &RVal); 2402 2403 /// Try to evaluate the initializer for a variable declaration. 2404 /// 2405 /// \param Info Information about the ongoing evaluation. 2406 /// \param E An expression to be used when printing diagnostics. 2407 /// \param VD The variable whose initializer should be obtained. 2408 /// \param Frame The frame in which the variable was created. Must be null 2409 /// if this variable is not local to the evaluation. 2410 /// \param Result Filled in with a pointer to the value of the variable. 2411 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2412 const VarDecl *VD, CallStackFrame *Frame, 2413 APValue *&Result) { 2414 2415 // If this is a parameter to an active constexpr function call, perform 2416 // argument substitution. 2417 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2418 // Assume arguments of a potential constant expression are unknown 2419 // constant expressions. 2420 if (Info.checkingPotentialConstantExpression()) 2421 return false; 2422 if (!Frame || !Frame->Arguments) { 2423 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2424 return false; 2425 } 2426 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2427 return true; 2428 } 2429 2430 // If this is a local variable, dig out its value. 2431 if (Frame) { 2432 Result = Frame->getTemporary(VD); 2433 if (!Result) { 2434 // Assume variables referenced within a lambda's call operator that were 2435 // not declared within the call operator are captures and during checking 2436 // of a potential constant expression, assume they are unknown constant 2437 // expressions. 2438 assert(isLambdaCallOperator(Frame->Callee) && 2439 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2440 "missing value for local variable"); 2441 if (Info.checkingPotentialConstantExpression()) 2442 return false; 2443 // FIXME: implement capture evaluation during constant expr evaluation. 2444 Info.FFDiag(E->getLocStart(), 2445 diag::note_unimplemented_constexpr_lambda_feature_ast) 2446 << "captures not currently allowed"; 2447 return false; 2448 } 2449 return true; 2450 } 2451 2452 // Dig out the initializer, and use the declaration which it's attached to. 2453 const Expr *Init = VD->getAnyInitializer(VD); 2454 if (!Init || Init->isValueDependent()) { 2455 // If we're checking a potential constant expression, the variable could be 2456 // initialized later. 2457 if (!Info.checkingPotentialConstantExpression()) 2458 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2459 return false; 2460 } 2461 2462 // If we're currently evaluating the initializer of this declaration, use that 2463 // in-flight value. 2464 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2465 Result = Info.EvaluatingDeclValue; 2466 return true; 2467 } 2468 2469 // Never evaluate the initializer of a weak variable. We can't be sure that 2470 // this is the definition which will be used. 2471 if (VD->isWeak()) { 2472 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2473 return false; 2474 } 2475 2476 // Check that we can fold the initializer. In C++, we will have already done 2477 // this in the cases where it matters for conformance. 2478 SmallVector<PartialDiagnosticAt, 8> Notes; 2479 if (!VD->evaluateValue(Notes)) { 2480 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2481 Notes.size() + 1) << VD; 2482 Info.Note(VD->getLocation(), diag::note_declared_at); 2483 Info.addNotes(Notes); 2484 return false; 2485 } else if (!VD->checkInitIsICE()) { 2486 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2487 Notes.size() + 1) << VD; 2488 Info.Note(VD->getLocation(), diag::note_declared_at); 2489 Info.addNotes(Notes); 2490 } 2491 2492 Result = VD->getEvaluatedValue(); 2493 return true; 2494 } 2495 2496 static bool IsConstNonVolatile(QualType T) { 2497 Qualifiers Quals = T.getQualifiers(); 2498 return Quals.hasConst() && !Quals.hasVolatile(); 2499 } 2500 2501 /// Get the base index of the given base class within an APValue representing 2502 /// the given derived class. 2503 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2504 const CXXRecordDecl *Base) { 2505 Base = Base->getCanonicalDecl(); 2506 unsigned Index = 0; 2507 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2508 E = Derived->bases_end(); I != E; ++I, ++Index) { 2509 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2510 return Index; 2511 } 2512 2513 llvm_unreachable("base class missing from derived class's bases list"); 2514 } 2515 2516 /// Extract the value of a character from a string literal. 2517 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2518 uint64_t Index) { 2519 // FIXME: Support MakeStringConstant 2520 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2521 std::string Str; 2522 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2523 assert(Index <= Str.size() && "Index too large"); 2524 return APSInt::getUnsigned(Str.c_str()[Index]); 2525 } 2526 2527 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2528 Lit = PE->getFunctionName(); 2529 const StringLiteral *S = cast<StringLiteral>(Lit); 2530 const ConstantArrayType *CAT = 2531 Info.Ctx.getAsConstantArrayType(S->getType()); 2532 assert(CAT && "string literal isn't an array"); 2533 QualType CharType = CAT->getElementType(); 2534 assert(CharType->isIntegerType() && "unexpected character type"); 2535 2536 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2537 CharType->isUnsignedIntegerType()); 2538 if (Index < S->getLength()) 2539 Value = S->getCodeUnit(Index); 2540 return Value; 2541 } 2542 2543 // Expand a string literal into an array of characters. 2544 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit, 2545 APValue &Result) { 2546 const StringLiteral *S = cast<StringLiteral>(Lit); 2547 const ConstantArrayType *CAT = 2548 Info.Ctx.getAsConstantArrayType(S->getType()); 2549 assert(CAT && "string literal isn't an array"); 2550 QualType CharType = CAT->getElementType(); 2551 assert(CharType->isIntegerType() && "unexpected character type"); 2552 2553 unsigned Elts = CAT->getSize().getZExtValue(); 2554 Result = APValue(APValue::UninitArray(), 2555 std::min(S->getLength(), Elts), Elts); 2556 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2557 CharType->isUnsignedIntegerType()); 2558 if (Result.hasArrayFiller()) 2559 Result.getArrayFiller() = APValue(Value); 2560 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2561 Value = S->getCodeUnit(I); 2562 Result.getArrayInitializedElt(I) = APValue(Value); 2563 } 2564 } 2565 2566 // Expand an array so that it has more than Index filled elements. 2567 static void expandArray(APValue &Array, unsigned Index) { 2568 unsigned Size = Array.getArraySize(); 2569 assert(Index < Size); 2570 2571 // Always at least double the number of elements for which we store a value. 2572 unsigned OldElts = Array.getArrayInitializedElts(); 2573 unsigned NewElts = std::max(Index+1, OldElts * 2); 2574 NewElts = std::min(Size, std::max(NewElts, 8u)); 2575 2576 // Copy the data across. 2577 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2578 for (unsigned I = 0; I != OldElts; ++I) 2579 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2580 for (unsigned I = OldElts; I != NewElts; ++I) 2581 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2582 if (NewValue.hasArrayFiller()) 2583 NewValue.getArrayFiller() = Array.getArrayFiller(); 2584 Array.swap(NewValue); 2585 } 2586 2587 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2588 /// conversion. If it's of class type, we may assume that the copy operation 2589 /// is trivial. Note that this is never true for a union type with fields 2590 /// (because the copy always "reads" the active member) and always true for 2591 /// a non-class type. 2592 static bool isReadByLvalueToRvalueConversion(QualType T) { 2593 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2594 if (!RD || (RD->isUnion() && !RD->field_empty())) 2595 return true; 2596 if (RD->isEmpty()) 2597 return false; 2598 2599 for (auto *Field : RD->fields()) 2600 if (isReadByLvalueToRvalueConversion(Field->getType())) 2601 return true; 2602 2603 for (auto &BaseSpec : RD->bases()) 2604 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2605 return true; 2606 2607 return false; 2608 } 2609 2610 /// Diagnose an attempt to read from any unreadable field within the specified 2611 /// type, which might be a class type. 2612 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2613 QualType T) { 2614 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2615 if (!RD) 2616 return false; 2617 2618 if (!RD->hasMutableFields()) 2619 return false; 2620 2621 for (auto *Field : RD->fields()) { 2622 // If we're actually going to read this field in some way, then it can't 2623 // be mutable. If we're in a union, then assigning to a mutable field 2624 // (even an empty one) can change the active member, so that's not OK. 2625 // FIXME: Add core issue number for the union case. 2626 if (Field->isMutable() && 2627 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2628 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2629 Info.Note(Field->getLocation(), diag::note_declared_at); 2630 return true; 2631 } 2632 2633 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2634 return true; 2635 } 2636 2637 for (auto &BaseSpec : RD->bases()) 2638 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2639 return true; 2640 2641 // All mutable fields were empty, and thus not actually read. 2642 return false; 2643 } 2644 2645 /// Kinds of access we can perform on an object, for diagnostics. 2646 enum AccessKinds { 2647 AK_Read, 2648 AK_Assign, 2649 AK_Increment, 2650 AK_Decrement 2651 }; 2652 2653 namespace { 2654 /// A handle to a complete object (an object that is not a subobject of 2655 /// another object). 2656 struct CompleteObject { 2657 /// The value of the complete object. 2658 APValue *Value; 2659 /// The type of the complete object. 2660 QualType Type; 2661 bool LifetimeStartedInEvaluation; 2662 2663 CompleteObject() : Value(nullptr) {} 2664 CompleteObject(APValue *Value, QualType Type, 2665 bool LifetimeStartedInEvaluation) 2666 : Value(Value), Type(Type), 2667 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) { 2668 assert(Value && "missing value for complete object"); 2669 } 2670 2671 explicit operator bool() const { return Value; } 2672 }; 2673 } // end anonymous namespace 2674 2675 /// Find the designated sub-object of an rvalue. 2676 template<typename SubobjectHandler> 2677 typename SubobjectHandler::result_type 2678 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2679 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2680 if (Sub.Invalid) 2681 // A diagnostic will have already been produced. 2682 return handler.failed(); 2683 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2684 if (Info.getLangOpts().CPlusPlus11) 2685 Info.FFDiag(E, Sub.isOnePastTheEnd() 2686 ? diag::note_constexpr_access_past_end 2687 : diag::note_constexpr_access_unsized_array) 2688 << handler.AccessKind; 2689 else 2690 Info.FFDiag(E); 2691 return handler.failed(); 2692 } 2693 2694 APValue *O = Obj.Value; 2695 QualType ObjType = Obj.Type; 2696 const FieldDecl *LastField = nullptr; 2697 const bool MayReadMutableMembers = 2698 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14; 2699 2700 // Walk the designator's path to find the subobject. 2701 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 2702 if (O->isUninit()) { 2703 if (!Info.checkingPotentialConstantExpression()) 2704 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind; 2705 return handler.failed(); 2706 } 2707 2708 if (I == N) { 2709 // If we are reading an object of class type, there may still be more 2710 // things we need to check: if there are any mutable subobjects, we 2711 // cannot perform this read. (This only happens when performing a trivial 2712 // copy or assignment.) 2713 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 2714 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType)) 2715 return handler.failed(); 2716 2717 if (!handler.found(*O, ObjType)) 2718 return false; 2719 2720 // If we modified a bit-field, truncate it to the right width. 2721 if (handler.AccessKind != AK_Read && 2722 LastField && LastField->isBitField() && 2723 !truncateBitfieldValue(Info, E, *O, LastField)) 2724 return false; 2725 2726 return true; 2727 } 2728 2729 LastField = nullptr; 2730 if (ObjType->isArrayType()) { 2731 // Next subobject is an array element. 2732 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 2733 assert(CAT && "vla in literal type?"); 2734 uint64_t Index = Sub.Entries[I].ArrayIndex; 2735 if (CAT->getSize().ule(Index)) { 2736 // Note, it should not be possible to form a pointer with a valid 2737 // designator which points more than one past the end of the array. 2738 if (Info.getLangOpts().CPlusPlus11) 2739 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2740 << handler.AccessKind; 2741 else 2742 Info.FFDiag(E); 2743 return handler.failed(); 2744 } 2745 2746 ObjType = CAT->getElementType(); 2747 2748 // An array object is represented as either an Array APValue or as an 2749 // LValue which refers to a string literal. 2750 if (O->isLValue()) { 2751 assert(I == N - 1 && "extracting subobject of character?"); 2752 assert(!O->hasLValuePath() || O->getLValuePath().empty()); 2753 if (handler.AccessKind != AK_Read) 2754 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(), 2755 *O); 2756 else 2757 return handler.foundString(*O, ObjType, Index); 2758 } 2759 2760 if (O->getArrayInitializedElts() > Index) 2761 O = &O->getArrayInitializedElt(Index); 2762 else if (handler.AccessKind != AK_Read) { 2763 expandArray(*O, Index); 2764 O = &O->getArrayInitializedElt(Index); 2765 } else 2766 O = &O->getArrayFiller(); 2767 } else if (ObjType->isAnyComplexType()) { 2768 // Next subobject is a complex number. 2769 uint64_t Index = Sub.Entries[I].ArrayIndex; 2770 if (Index > 1) { 2771 if (Info.getLangOpts().CPlusPlus11) 2772 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2773 << handler.AccessKind; 2774 else 2775 Info.FFDiag(E); 2776 return handler.failed(); 2777 } 2778 2779 bool WasConstQualified = ObjType.isConstQualified(); 2780 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2781 if (WasConstQualified) 2782 ObjType.addConst(); 2783 2784 assert(I == N - 1 && "extracting subobject of scalar?"); 2785 if (O->isComplexInt()) { 2786 return handler.found(Index ? O->getComplexIntImag() 2787 : O->getComplexIntReal(), ObjType); 2788 } else { 2789 assert(O->isComplexFloat()); 2790 return handler.found(Index ? O->getComplexFloatImag() 2791 : O->getComplexFloatReal(), ObjType); 2792 } 2793 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 2794 // In C++14 onwards, it is permitted to read a mutable member whose 2795 // lifetime began within the evaluation. 2796 // FIXME: Should we also allow this in C++11? 2797 if (Field->isMutable() && handler.AccessKind == AK_Read && 2798 !MayReadMutableMembers) { 2799 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 2800 << Field; 2801 Info.Note(Field->getLocation(), diag::note_declared_at); 2802 return handler.failed(); 2803 } 2804 2805 // Next subobject is a class, struct or union field. 2806 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 2807 if (RD->isUnion()) { 2808 const FieldDecl *UnionField = O->getUnionField(); 2809 if (!UnionField || 2810 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 2811 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 2812 << handler.AccessKind << Field << !UnionField << UnionField; 2813 return handler.failed(); 2814 } 2815 O = &O->getUnionValue(); 2816 } else 2817 O = &O->getStructField(Field->getFieldIndex()); 2818 2819 bool WasConstQualified = ObjType.isConstQualified(); 2820 ObjType = Field->getType(); 2821 if (WasConstQualified && !Field->isMutable()) 2822 ObjType.addConst(); 2823 2824 if (ObjType.isVolatileQualified()) { 2825 if (Info.getLangOpts().CPlusPlus) { 2826 // FIXME: Include a description of the path to the volatile subobject. 2827 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2828 << handler.AccessKind << 2 << Field; 2829 Info.Note(Field->getLocation(), diag::note_declared_at); 2830 } else { 2831 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2832 } 2833 return handler.failed(); 2834 } 2835 2836 LastField = Field; 2837 } else { 2838 // Next subobject is a base class. 2839 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 2840 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 2841 O = &O->getStructBase(getBaseIndex(Derived, Base)); 2842 2843 bool WasConstQualified = ObjType.isConstQualified(); 2844 ObjType = Info.Ctx.getRecordType(Base); 2845 if (WasConstQualified) 2846 ObjType.addConst(); 2847 } 2848 } 2849 } 2850 2851 namespace { 2852 struct ExtractSubobjectHandler { 2853 EvalInfo &Info; 2854 APValue &Result; 2855 2856 static const AccessKinds AccessKind = AK_Read; 2857 2858 typedef bool result_type; 2859 bool failed() { return false; } 2860 bool found(APValue &Subobj, QualType SubobjType) { 2861 Result = Subobj; 2862 return true; 2863 } 2864 bool found(APSInt &Value, QualType SubobjType) { 2865 Result = APValue(Value); 2866 return true; 2867 } 2868 bool found(APFloat &Value, QualType SubobjType) { 2869 Result = APValue(Value); 2870 return true; 2871 } 2872 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2873 Result = APValue(extractStringLiteralCharacter( 2874 Info, Subobj.getLValueBase().get<const Expr *>(), Character)); 2875 return true; 2876 } 2877 }; 2878 } // end anonymous namespace 2879 2880 const AccessKinds ExtractSubobjectHandler::AccessKind; 2881 2882 /// Extract the designated sub-object of an rvalue. 2883 static bool extractSubobject(EvalInfo &Info, const Expr *E, 2884 const CompleteObject &Obj, 2885 const SubobjectDesignator &Sub, 2886 APValue &Result) { 2887 ExtractSubobjectHandler Handler = { Info, Result }; 2888 return findSubobject(Info, E, Obj, Sub, Handler); 2889 } 2890 2891 namespace { 2892 struct ModifySubobjectHandler { 2893 EvalInfo &Info; 2894 APValue &NewVal; 2895 const Expr *E; 2896 2897 typedef bool result_type; 2898 static const AccessKinds AccessKind = AK_Assign; 2899 2900 bool checkConst(QualType QT) { 2901 // Assigning to a const object has undefined behavior. 2902 if (QT.isConstQualified()) { 2903 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 2904 return false; 2905 } 2906 return true; 2907 } 2908 2909 bool failed() { return false; } 2910 bool found(APValue &Subobj, QualType SubobjType) { 2911 if (!checkConst(SubobjType)) 2912 return false; 2913 // We've been given ownership of NewVal, so just swap it in. 2914 Subobj.swap(NewVal); 2915 return true; 2916 } 2917 bool found(APSInt &Value, QualType SubobjType) { 2918 if (!checkConst(SubobjType)) 2919 return false; 2920 if (!NewVal.isInt()) { 2921 // Maybe trying to write a cast pointer value into a complex? 2922 Info.FFDiag(E); 2923 return false; 2924 } 2925 Value = NewVal.getInt(); 2926 return true; 2927 } 2928 bool found(APFloat &Value, QualType SubobjType) { 2929 if (!checkConst(SubobjType)) 2930 return false; 2931 Value = NewVal.getFloat(); 2932 return true; 2933 } 2934 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2935 llvm_unreachable("shouldn't encounter string elements with ExpandArrays"); 2936 } 2937 }; 2938 } // end anonymous namespace 2939 2940 const AccessKinds ModifySubobjectHandler::AccessKind; 2941 2942 /// Update the designated sub-object of an rvalue to the given value. 2943 static bool modifySubobject(EvalInfo &Info, const Expr *E, 2944 const CompleteObject &Obj, 2945 const SubobjectDesignator &Sub, 2946 APValue &NewVal) { 2947 ModifySubobjectHandler Handler = { Info, NewVal, E }; 2948 return findSubobject(Info, E, Obj, Sub, Handler); 2949 } 2950 2951 /// Find the position where two subobject designators diverge, or equivalently 2952 /// the length of the common initial subsequence. 2953 static unsigned FindDesignatorMismatch(QualType ObjType, 2954 const SubobjectDesignator &A, 2955 const SubobjectDesignator &B, 2956 bool &WasArrayIndex) { 2957 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 2958 for (/**/; I != N; ++I) { 2959 if (!ObjType.isNull() && 2960 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 2961 // Next subobject is an array element. 2962 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) { 2963 WasArrayIndex = true; 2964 return I; 2965 } 2966 if (ObjType->isAnyComplexType()) 2967 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2968 else 2969 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 2970 } else { 2971 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) { 2972 WasArrayIndex = false; 2973 return I; 2974 } 2975 if (const FieldDecl *FD = getAsField(A.Entries[I])) 2976 // Next subobject is a field. 2977 ObjType = FD->getType(); 2978 else 2979 // Next subobject is a base class. 2980 ObjType = QualType(); 2981 } 2982 } 2983 WasArrayIndex = false; 2984 return I; 2985 } 2986 2987 /// Determine whether the given subobject designators refer to elements of the 2988 /// same array object. 2989 static bool AreElementsOfSameArray(QualType ObjType, 2990 const SubobjectDesignator &A, 2991 const SubobjectDesignator &B) { 2992 if (A.Entries.size() != B.Entries.size()) 2993 return false; 2994 2995 bool IsArray = A.MostDerivedIsArrayElement; 2996 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 2997 // A is a subobject of the array element. 2998 return false; 2999 3000 // If A (and B) designates an array element, the last entry will be the array 3001 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3002 // of length 1' case, and the entire path must match. 3003 bool WasArrayIndex; 3004 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3005 return CommonLength >= A.Entries.size() - IsArray; 3006 } 3007 3008 /// Find the complete object to which an LValue refers. 3009 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3010 AccessKinds AK, const LValue &LVal, 3011 QualType LValType) { 3012 if (!LVal.Base) { 3013 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3014 return CompleteObject(); 3015 } 3016 3017 CallStackFrame *Frame = nullptr; 3018 if (LVal.CallIndex) { 3019 Frame = Info.getCallFrame(LVal.CallIndex); 3020 if (!Frame) { 3021 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3022 << AK << LVal.Base.is<const ValueDecl*>(); 3023 NoteLValueLocation(Info, LVal.Base); 3024 return CompleteObject(); 3025 } 3026 } 3027 3028 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3029 // is not a constant expression (even if the object is non-volatile). We also 3030 // apply this rule to C++98, in order to conform to the expected 'volatile' 3031 // semantics. 3032 if (LValType.isVolatileQualified()) { 3033 if (Info.getLangOpts().CPlusPlus) 3034 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3035 << AK << LValType; 3036 else 3037 Info.FFDiag(E); 3038 return CompleteObject(); 3039 } 3040 3041 // Compute value storage location and type of base object. 3042 APValue *BaseVal = nullptr; 3043 QualType BaseType = getType(LVal.Base); 3044 bool LifetimeStartedInEvaluation = Frame; 3045 3046 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3047 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3048 // In C++11, constexpr, non-volatile variables initialized with constant 3049 // expressions are constant expressions too. Inside constexpr functions, 3050 // parameters are constant expressions even if they're non-const. 3051 // In C++1y, objects local to a constant expression (those with a Frame) are 3052 // both readable and writable inside constant expressions. 3053 // In C, such things can also be folded, although they are not ICEs. 3054 const VarDecl *VD = dyn_cast<VarDecl>(D); 3055 if (VD) { 3056 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3057 VD = VDef; 3058 } 3059 if (!VD || VD->isInvalidDecl()) { 3060 Info.FFDiag(E); 3061 return CompleteObject(); 3062 } 3063 3064 // Accesses of volatile-qualified objects are not allowed. 3065 if (BaseType.isVolatileQualified()) { 3066 if (Info.getLangOpts().CPlusPlus) { 3067 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3068 << AK << 1 << VD; 3069 Info.Note(VD->getLocation(), diag::note_declared_at); 3070 } else { 3071 Info.FFDiag(E); 3072 } 3073 return CompleteObject(); 3074 } 3075 3076 // Unless we're looking at a local variable or argument in a constexpr call, 3077 // the variable we're reading must be const. 3078 if (!Frame) { 3079 if (Info.getLangOpts().CPlusPlus14 && 3080 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) { 3081 // OK, we can read and modify an object if we're in the process of 3082 // evaluating its initializer, because its lifetime began in this 3083 // evaluation. 3084 } else if (AK != AK_Read) { 3085 // All the remaining cases only permit reading. 3086 Info.FFDiag(E, diag::note_constexpr_modify_global); 3087 return CompleteObject(); 3088 } else if (VD->isConstexpr()) { 3089 // OK, we can read this variable. 3090 } else if (BaseType->isIntegralOrEnumerationType()) { 3091 // In OpenCL if a variable is in constant address space it is a const value. 3092 if (!(BaseType.isConstQualified() || 3093 (Info.getLangOpts().OpenCL && 3094 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3095 if (Info.getLangOpts().CPlusPlus) { 3096 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3097 Info.Note(VD->getLocation(), diag::note_declared_at); 3098 } else { 3099 Info.FFDiag(E); 3100 } 3101 return CompleteObject(); 3102 } 3103 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3104 // We support folding of const floating-point types, in order to make 3105 // static const data members of such types (supported as an extension) 3106 // more useful. 3107 if (Info.getLangOpts().CPlusPlus11) { 3108 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3109 Info.Note(VD->getLocation(), diag::note_declared_at); 3110 } else { 3111 Info.CCEDiag(E); 3112 } 3113 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3114 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3115 // Keep evaluating to see what we can do. 3116 } else { 3117 // FIXME: Allow folding of values of any literal type in all languages. 3118 if (Info.checkingPotentialConstantExpression() && 3119 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3120 // The definition of this variable could be constexpr. We can't 3121 // access it right now, but may be able to in future. 3122 } else if (Info.getLangOpts().CPlusPlus11) { 3123 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3124 Info.Note(VD->getLocation(), diag::note_declared_at); 3125 } else { 3126 Info.FFDiag(E); 3127 } 3128 return CompleteObject(); 3129 } 3130 } 3131 3132 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal)) 3133 return CompleteObject(); 3134 } else { 3135 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3136 3137 if (!Frame) { 3138 if (const MaterializeTemporaryExpr *MTE = 3139 dyn_cast<MaterializeTemporaryExpr>(Base)) { 3140 assert(MTE->getStorageDuration() == SD_Static && 3141 "should have a frame for a non-global materialized temporary"); 3142 3143 // Per C++1y [expr.const]p2: 3144 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3145 // - a [...] glvalue of integral or enumeration type that refers to 3146 // a non-volatile const object [...] 3147 // [...] 3148 // - a [...] glvalue of literal type that refers to a non-volatile 3149 // object whose lifetime began within the evaluation of e. 3150 // 3151 // C++11 misses the 'began within the evaluation of e' check and 3152 // instead allows all temporaries, including things like: 3153 // int &&r = 1; 3154 // int x = ++r; 3155 // constexpr int k = r; 3156 // Therefore we use the C++14 rules in C++11 too. 3157 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3158 const ValueDecl *ED = MTE->getExtendingDecl(); 3159 if (!(BaseType.isConstQualified() && 3160 BaseType->isIntegralOrEnumerationType()) && 3161 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3162 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3163 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3164 return CompleteObject(); 3165 } 3166 3167 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3168 assert(BaseVal && "got reference to unevaluated temporary"); 3169 LifetimeStartedInEvaluation = true; 3170 } else { 3171 Info.FFDiag(E); 3172 return CompleteObject(); 3173 } 3174 } else { 3175 BaseVal = Frame->getTemporary(Base); 3176 assert(BaseVal && "missing value for temporary"); 3177 } 3178 3179 // Volatile temporary objects cannot be accessed in constant expressions. 3180 if (BaseType.isVolatileQualified()) { 3181 if (Info.getLangOpts().CPlusPlus) { 3182 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3183 << AK << 0; 3184 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 3185 } else { 3186 Info.FFDiag(E); 3187 } 3188 return CompleteObject(); 3189 } 3190 } 3191 3192 // During the construction of an object, it is not yet 'const'. 3193 // FIXME: This doesn't do quite the right thing for const subobjects of the 3194 // object under construction. 3195 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) { 3196 BaseType = Info.Ctx.getCanonicalType(BaseType); 3197 BaseType.removeLocalConst(); 3198 LifetimeStartedInEvaluation = true; 3199 } 3200 3201 // In C++14, we can't safely access any mutable state when we might be 3202 // evaluating after an unmodeled side effect. 3203 // 3204 // FIXME: Not all local state is mutable. Allow local constant subobjects 3205 // to be read here (but take care with 'mutable' fields). 3206 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3207 Info.EvalStatus.HasSideEffects) || 3208 (AK != AK_Read && Info.IsSpeculativelyEvaluating)) 3209 return CompleteObject(); 3210 3211 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation); 3212 } 3213 3214 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This 3215 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3216 /// glvalue referred to by an entity of reference type. 3217 /// 3218 /// \param Info - Information about the ongoing evaluation. 3219 /// \param Conv - The expression for which we are performing the conversion. 3220 /// Used for diagnostics. 3221 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3222 /// case of a non-class type). 3223 /// \param LVal - The glvalue on which we are attempting to perform this action. 3224 /// \param RVal - The produced value will be placed here. 3225 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3226 QualType Type, 3227 const LValue &LVal, APValue &RVal) { 3228 if (LVal.Designator.Invalid) 3229 return false; 3230 3231 // Check for special cases where there is no existing APValue to look at. 3232 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3233 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) { 3234 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3235 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3236 // initializer until now for such expressions. Such an expression can't be 3237 // an ICE in C, so this only matters for fold. 3238 if (Type.isVolatileQualified()) { 3239 Info.FFDiag(Conv); 3240 return false; 3241 } 3242 APValue Lit; 3243 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3244 return false; 3245 CompleteObject LitObj(&Lit, Base->getType(), false); 3246 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3247 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3248 // We represent a string literal array as an lvalue pointing at the 3249 // corresponding expression, rather than building an array of chars. 3250 // FIXME: Support ObjCEncodeExpr, MakeStringConstant 3251 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0); 3252 CompleteObject StrObj(&Str, Base->getType(), false); 3253 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal); 3254 } 3255 } 3256 3257 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3258 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3259 } 3260 3261 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3262 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3263 QualType LValType, APValue &Val) { 3264 if (LVal.Designator.Invalid) 3265 return false; 3266 3267 if (!Info.getLangOpts().CPlusPlus14) { 3268 Info.FFDiag(E); 3269 return false; 3270 } 3271 3272 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3273 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3274 } 3275 3276 namespace { 3277 struct CompoundAssignSubobjectHandler { 3278 EvalInfo &Info; 3279 const Expr *E; 3280 QualType PromotedLHSType; 3281 BinaryOperatorKind Opcode; 3282 const APValue &RHS; 3283 3284 static const AccessKinds AccessKind = AK_Assign; 3285 3286 typedef bool result_type; 3287 3288 bool checkConst(QualType QT) { 3289 // Assigning to a const object has undefined behavior. 3290 if (QT.isConstQualified()) { 3291 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3292 return false; 3293 } 3294 return true; 3295 } 3296 3297 bool failed() { return false; } 3298 bool found(APValue &Subobj, QualType SubobjType) { 3299 switch (Subobj.getKind()) { 3300 case APValue::Int: 3301 return found(Subobj.getInt(), SubobjType); 3302 case APValue::Float: 3303 return found(Subobj.getFloat(), SubobjType); 3304 case APValue::ComplexInt: 3305 case APValue::ComplexFloat: 3306 // FIXME: Implement complex compound assignment. 3307 Info.FFDiag(E); 3308 return false; 3309 case APValue::LValue: 3310 return foundPointer(Subobj, SubobjType); 3311 default: 3312 // FIXME: can this happen? 3313 Info.FFDiag(E); 3314 return false; 3315 } 3316 } 3317 bool found(APSInt &Value, QualType SubobjType) { 3318 if (!checkConst(SubobjType)) 3319 return false; 3320 3321 if (!SubobjType->isIntegerType() || !RHS.isInt()) { 3322 // We don't support compound assignment on integer-cast-to-pointer 3323 // values. 3324 Info.FFDiag(E); 3325 return false; 3326 } 3327 3328 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType, 3329 SubobjType, Value); 3330 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3331 return false; 3332 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3333 return true; 3334 } 3335 bool found(APFloat &Value, QualType SubobjType) { 3336 return checkConst(SubobjType) && 3337 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3338 Value) && 3339 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3340 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3341 } 3342 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3343 if (!checkConst(SubobjType)) 3344 return false; 3345 3346 QualType PointeeType; 3347 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3348 PointeeType = PT->getPointeeType(); 3349 3350 if (PointeeType.isNull() || !RHS.isInt() || 3351 (Opcode != BO_Add && Opcode != BO_Sub)) { 3352 Info.FFDiag(E); 3353 return false; 3354 } 3355 3356 APSInt Offset = RHS.getInt(); 3357 if (Opcode == BO_Sub) 3358 negateAsSigned(Offset); 3359 3360 LValue LVal; 3361 LVal.setFrom(Info.Ctx, Subobj); 3362 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3363 return false; 3364 LVal.moveInto(Subobj); 3365 return true; 3366 } 3367 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3368 llvm_unreachable("shouldn't encounter string elements here"); 3369 } 3370 }; 3371 } // end anonymous namespace 3372 3373 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3374 3375 /// Perform a compound assignment of LVal <op>= RVal. 3376 static bool handleCompoundAssignment( 3377 EvalInfo &Info, const Expr *E, 3378 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3379 BinaryOperatorKind Opcode, const APValue &RVal) { 3380 if (LVal.Designator.Invalid) 3381 return false; 3382 3383 if (!Info.getLangOpts().CPlusPlus14) { 3384 Info.FFDiag(E); 3385 return false; 3386 } 3387 3388 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3389 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3390 RVal }; 3391 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3392 } 3393 3394 namespace { 3395 struct IncDecSubobjectHandler { 3396 EvalInfo &Info; 3397 const UnaryOperator *E; 3398 AccessKinds AccessKind; 3399 APValue *Old; 3400 3401 typedef bool result_type; 3402 3403 bool checkConst(QualType QT) { 3404 // Assigning to a const object has undefined behavior. 3405 if (QT.isConstQualified()) { 3406 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3407 return false; 3408 } 3409 return true; 3410 } 3411 3412 bool failed() { return false; } 3413 bool found(APValue &Subobj, QualType SubobjType) { 3414 // Stash the old value. Also clear Old, so we don't clobber it later 3415 // if we're post-incrementing a complex. 3416 if (Old) { 3417 *Old = Subobj; 3418 Old = nullptr; 3419 } 3420 3421 switch (Subobj.getKind()) { 3422 case APValue::Int: 3423 return found(Subobj.getInt(), SubobjType); 3424 case APValue::Float: 3425 return found(Subobj.getFloat(), SubobjType); 3426 case APValue::ComplexInt: 3427 return found(Subobj.getComplexIntReal(), 3428 SubobjType->castAs<ComplexType>()->getElementType() 3429 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3430 case APValue::ComplexFloat: 3431 return found(Subobj.getComplexFloatReal(), 3432 SubobjType->castAs<ComplexType>()->getElementType() 3433 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3434 case APValue::LValue: 3435 return foundPointer(Subobj, SubobjType); 3436 default: 3437 // FIXME: can this happen? 3438 Info.FFDiag(E); 3439 return false; 3440 } 3441 } 3442 bool found(APSInt &Value, QualType SubobjType) { 3443 if (!checkConst(SubobjType)) 3444 return false; 3445 3446 if (!SubobjType->isIntegerType()) { 3447 // We don't support increment / decrement on integer-cast-to-pointer 3448 // values. 3449 Info.FFDiag(E); 3450 return false; 3451 } 3452 3453 if (Old) *Old = APValue(Value); 3454 3455 // bool arithmetic promotes to int, and the conversion back to bool 3456 // doesn't reduce mod 2^n, so special-case it. 3457 if (SubobjType->isBooleanType()) { 3458 if (AccessKind == AK_Increment) 3459 Value = 1; 3460 else 3461 Value = !Value; 3462 return true; 3463 } 3464 3465 bool WasNegative = Value.isNegative(); 3466 if (AccessKind == AK_Increment) { 3467 ++Value; 3468 3469 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3470 APSInt ActualValue(Value, /*IsUnsigned*/true); 3471 return HandleOverflow(Info, E, ActualValue, SubobjType); 3472 } 3473 } else { 3474 --Value; 3475 3476 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3477 unsigned BitWidth = Value.getBitWidth(); 3478 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3479 ActualValue.setBit(BitWidth); 3480 return HandleOverflow(Info, E, ActualValue, SubobjType); 3481 } 3482 } 3483 return true; 3484 } 3485 bool found(APFloat &Value, QualType SubobjType) { 3486 if (!checkConst(SubobjType)) 3487 return false; 3488 3489 if (Old) *Old = APValue(Value); 3490 3491 APFloat One(Value.getSemantics(), 1); 3492 if (AccessKind == AK_Increment) 3493 Value.add(One, APFloat::rmNearestTiesToEven); 3494 else 3495 Value.subtract(One, APFloat::rmNearestTiesToEven); 3496 return true; 3497 } 3498 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3499 if (!checkConst(SubobjType)) 3500 return false; 3501 3502 QualType PointeeType; 3503 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3504 PointeeType = PT->getPointeeType(); 3505 else { 3506 Info.FFDiag(E); 3507 return false; 3508 } 3509 3510 LValue LVal; 3511 LVal.setFrom(Info.Ctx, Subobj); 3512 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3513 AccessKind == AK_Increment ? 1 : -1)) 3514 return false; 3515 LVal.moveInto(Subobj); 3516 return true; 3517 } 3518 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3519 llvm_unreachable("shouldn't encounter string elements here"); 3520 } 3521 }; 3522 } // end anonymous namespace 3523 3524 /// Perform an increment or decrement on LVal. 3525 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3526 QualType LValType, bool IsIncrement, APValue *Old) { 3527 if (LVal.Designator.Invalid) 3528 return false; 3529 3530 if (!Info.getLangOpts().CPlusPlus14) { 3531 Info.FFDiag(E); 3532 return false; 3533 } 3534 3535 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3536 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3537 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3538 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3539 } 3540 3541 /// Build an lvalue for the object argument of a member function call. 3542 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3543 LValue &This) { 3544 if (Object->getType()->isPointerType()) 3545 return EvaluatePointer(Object, This, Info); 3546 3547 if (Object->isGLValue()) 3548 return EvaluateLValue(Object, This, Info); 3549 3550 if (Object->getType()->isLiteralType(Info.Ctx)) 3551 return EvaluateTemporary(Object, This, Info); 3552 3553 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3554 return false; 3555 } 3556 3557 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3558 /// lvalue referring to the result. 3559 /// 3560 /// \param Info - Information about the ongoing evaluation. 3561 /// \param LV - An lvalue referring to the base of the member pointer. 3562 /// \param RHS - The member pointer expression. 3563 /// \param IncludeMember - Specifies whether the member itself is included in 3564 /// the resulting LValue subobject designator. This is not possible when 3565 /// creating a bound member function. 3566 /// \return The field or method declaration to which the member pointer refers, 3567 /// or 0 if evaluation fails. 3568 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3569 QualType LVType, 3570 LValue &LV, 3571 const Expr *RHS, 3572 bool IncludeMember = true) { 3573 MemberPtr MemPtr; 3574 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3575 return nullptr; 3576 3577 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3578 // member value, the behavior is undefined. 3579 if (!MemPtr.getDecl()) { 3580 // FIXME: Specific diagnostic. 3581 Info.FFDiag(RHS); 3582 return nullptr; 3583 } 3584 3585 if (MemPtr.isDerivedMember()) { 3586 // This is a member of some derived class. Truncate LV appropriately. 3587 // The end of the derived-to-base path for the base object must match the 3588 // derived-to-base path for the member pointer. 3589 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3590 LV.Designator.Entries.size()) { 3591 Info.FFDiag(RHS); 3592 return nullptr; 3593 } 3594 unsigned PathLengthToMember = 3595 LV.Designator.Entries.size() - MemPtr.Path.size(); 3596 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3597 const CXXRecordDecl *LVDecl = getAsBaseClass( 3598 LV.Designator.Entries[PathLengthToMember + I]); 3599 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3600 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3601 Info.FFDiag(RHS); 3602 return nullptr; 3603 } 3604 } 3605 3606 // Truncate the lvalue to the appropriate derived class. 3607 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3608 PathLengthToMember)) 3609 return nullptr; 3610 } else if (!MemPtr.Path.empty()) { 3611 // Extend the LValue path with the member pointer's path. 3612 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3613 MemPtr.Path.size() + IncludeMember); 3614 3615 // Walk down to the appropriate base class. 3616 if (const PointerType *PT = LVType->getAs<PointerType>()) 3617 LVType = PT->getPointeeType(); 3618 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3619 assert(RD && "member pointer access on non-class-type expression"); 3620 // The first class in the path is that of the lvalue. 3621 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3622 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3623 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3624 return nullptr; 3625 RD = Base; 3626 } 3627 // Finally cast to the class containing the member. 3628 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3629 MemPtr.getContainingRecord())) 3630 return nullptr; 3631 } 3632 3633 // Add the member. Note that we cannot build bound member functions here. 3634 if (IncludeMember) { 3635 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3636 if (!HandleLValueMember(Info, RHS, LV, FD)) 3637 return nullptr; 3638 } else if (const IndirectFieldDecl *IFD = 3639 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3640 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3641 return nullptr; 3642 } else { 3643 llvm_unreachable("can't construct reference to bound member function"); 3644 } 3645 } 3646 3647 return MemPtr.getDecl(); 3648 } 3649 3650 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3651 const BinaryOperator *BO, 3652 LValue &LV, 3653 bool IncludeMember = true) { 3654 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3655 3656 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3657 if (Info.noteFailure()) { 3658 MemberPtr MemPtr; 3659 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3660 } 3661 return nullptr; 3662 } 3663 3664 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3665 BO->getRHS(), IncludeMember); 3666 } 3667 3668 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3669 /// the provided lvalue, which currently refers to the base object. 3670 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3671 LValue &Result) { 3672 SubobjectDesignator &D = Result.Designator; 3673 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3674 return false; 3675 3676 QualType TargetQT = E->getType(); 3677 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3678 TargetQT = PT->getPointeeType(); 3679 3680 // Check this cast lands within the final derived-to-base subobject path. 3681 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 3682 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3683 << D.MostDerivedType << TargetQT; 3684 return false; 3685 } 3686 3687 // Check the type of the final cast. We don't need to check the path, 3688 // since a cast can only be formed if the path is unique. 3689 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 3690 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 3691 const CXXRecordDecl *FinalType; 3692 if (NewEntriesSize == D.MostDerivedPathLength) 3693 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 3694 else 3695 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 3696 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 3697 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3698 << D.MostDerivedType << TargetQT; 3699 return false; 3700 } 3701 3702 // Truncate the lvalue to the appropriate derived class. 3703 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 3704 } 3705 3706 namespace { 3707 enum EvalStmtResult { 3708 /// Evaluation failed. 3709 ESR_Failed, 3710 /// Hit a 'return' statement. 3711 ESR_Returned, 3712 /// Evaluation succeeded. 3713 ESR_Succeeded, 3714 /// Hit a 'continue' statement. 3715 ESR_Continue, 3716 /// Hit a 'break' statement. 3717 ESR_Break, 3718 /// Still scanning for 'case' or 'default' statement. 3719 ESR_CaseNotFound 3720 }; 3721 } 3722 3723 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 3724 // We don't need to evaluate the initializer for a static local. 3725 if (!VD->hasLocalStorage()) 3726 return true; 3727 3728 LValue Result; 3729 Result.set(VD, Info.CurrentCall->Index); 3730 APValue &Val = Info.CurrentCall->createTemporary(VD, true); 3731 3732 const Expr *InitE = VD->getInit(); 3733 if (!InitE) { 3734 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized) 3735 << false << VD->getType(); 3736 Val = APValue(); 3737 return false; 3738 } 3739 3740 if (InitE->isValueDependent()) 3741 return false; 3742 3743 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 3744 // Wipe out any partially-computed value, to allow tracking that this 3745 // evaluation failed. 3746 Val = APValue(); 3747 return false; 3748 } 3749 3750 return true; 3751 } 3752 3753 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 3754 bool OK = true; 3755 3756 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 3757 OK &= EvaluateVarDecl(Info, VD); 3758 3759 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 3760 for (auto *BD : DD->bindings()) 3761 if (auto *VD = BD->getHoldingVar()) 3762 OK &= EvaluateDecl(Info, VD); 3763 3764 return OK; 3765 } 3766 3767 3768 /// Evaluate a condition (either a variable declaration or an expression). 3769 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 3770 const Expr *Cond, bool &Result) { 3771 FullExpressionRAII Scope(Info); 3772 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 3773 return false; 3774 return EvaluateAsBooleanCondition(Cond, Result, Info); 3775 } 3776 3777 namespace { 3778 /// \brief A location where the result (returned value) of evaluating a 3779 /// statement should be stored. 3780 struct StmtResult { 3781 /// The APValue that should be filled in with the returned value. 3782 APValue &Value; 3783 /// The location containing the result, if any (used to support RVO). 3784 const LValue *Slot; 3785 }; 3786 } 3787 3788 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3789 const Stmt *S, 3790 const SwitchCase *SC = nullptr); 3791 3792 /// Evaluate the body of a loop, and translate the result as appropriate. 3793 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 3794 const Stmt *Body, 3795 const SwitchCase *Case = nullptr) { 3796 BlockScopeRAII Scope(Info); 3797 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 3798 case ESR_Break: 3799 return ESR_Succeeded; 3800 case ESR_Succeeded: 3801 case ESR_Continue: 3802 return ESR_Continue; 3803 case ESR_Failed: 3804 case ESR_Returned: 3805 case ESR_CaseNotFound: 3806 return ESR; 3807 } 3808 llvm_unreachable("Invalid EvalStmtResult!"); 3809 } 3810 3811 /// Evaluate a switch statement. 3812 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 3813 const SwitchStmt *SS) { 3814 BlockScopeRAII Scope(Info); 3815 3816 // Evaluate the switch condition. 3817 APSInt Value; 3818 { 3819 FullExpressionRAII Scope(Info); 3820 if (const Stmt *Init = SS->getInit()) { 3821 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3822 if (ESR != ESR_Succeeded) 3823 return ESR; 3824 } 3825 if (SS->getConditionVariable() && 3826 !EvaluateDecl(Info, SS->getConditionVariable())) 3827 return ESR_Failed; 3828 if (!EvaluateInteger(SS->getCond(), Value, Info)) 3829 return ESR_Failed; 3830 } 3831 3832 // Find the switch case corresponding to the value of the condition. 3833 // FIXME: Cache this lookup. 3834 const SwitchCase *Found = nullptr; 3835 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 3836 SC = SC->getNextSwitchCase()) { 3837 if (isa<DefaultStmt>(SC)) { 3838 Found = SC; 3839 continue; 3840 } 3841 3842 const CaseStmt *CS = cast<CaseStmt>(SC); 3843 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 3844 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 3845 : LHS; 3846 if (LHS <= Value && Value <= RHS) { 3847 Found = SC; 3848 break; 3849 } 3850 } 3851 3852 if (!Found) 3853 return ESR_Succeeded; 3854 3855 // Search the switch body for the switch case and evaluate it from there. 3856 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 3857 case ESR_Break: 3858 return ESR_Succeeded; 3859 case ESR_Succeeded: 3860 case ESR_Continue: 3861 case ESR_Failed: 3862 case ESR_Returned: 3863 return ESR; 3864 case ESR_CaseNotFound: 3865 // This can only happen if the switch case is nested within a statement 3866 // expression. We have no intention of supporting that. 3867 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported); 3868 return ESR_Failed; 3869 } 3870 llvm_unreachable("Invalid EvalStmtResult!"); 3871 } 3872 3873 // Evaluate a statement. 3874 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3875 const Stmt *S, const SwitchCase *Case) { 3876 if (!Info.nextStep(S)) 3877 return ESR_Failed; 3878 3879 // If we're hunting down a 'case' or 'default' label, recurse through 3880 // substatements until we hit the label. 3881 if (Case) { 3882 // FIXME: We don't start the lifetime of objects whose initialization we 3883 // jump over. However, such objects must be of class type with a trivial 3884 // default constructor that initialize all subobjects, so must be empty, 3885 // so this almost never matters. 3886 switch (S->getStmtClass()) { 3887 case Stmt::CompoundStmtClass: 3888 // FIXME: Precompute which substatement of a compound statement we 3889 // would jump to, and go straight there rather than performing a 3890 // linear scan each time. 3891 case Stmt::LabelStmtClass: 3892 case Stmt::AttributedStmtClass: 3893 case Stmt::DoStmtClass: 3894 break; 3895 3896 case Stmt::CaseStmtClass: 3897 case Stmt::DefaultStmtClass: 3898 if (Case == S) 3899 Case = nullptr; 3900 break; 3901 3902 case Stmt::IfStmtClass: { 3903 // FIXME: Precompute which side of an 'if' we would jump to, and go 3904 // straight there rather than scanning both sides. 3905 const IfStmt *IS = cast<IfStmt>(S); 3906 3907 // Wrap the evaluation in a block scope, in case it's a DeclStmt 3908 // preceded by our switch label. 3909 BlockScopeRAII Scope(Info); 3910 3911 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 3912 if (ESR != ESR_CaseNotFound || !IS->getElse()) 3913 return ESR; 3914 return EvaluateStmt(Result, Info, IS->getElse(), Case); 3915 } 3916 3917 case Stmt::WhileStmtClass: { 3918 EvalStmtResult ESR = 3919 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 3920 if (ESR != ESR_Continue) 3921 return ESR; 3922 break; 3923 } 3924 3925 case Stmt::ForStmtClass: { 3926 const ForStmt *FS = cast<ForStmt>(S); 3927 EvalStmtResult ESR = 3928 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 3929 if (ESR != ESR_Continue) 3930 return ESR; 3931 if (FS->getInc()) { 3932 FullExpressionRAII IncScope(Info); 3933 if (!EvaluateIgnoredValue(Info, FS->getInc())) 3934 return ESR_Failed; 3935 } 3936 break; 3937 } 3938 3939 case Stmt::DeclStmtClass: 3940 // FIXME: If the variable has initialization that can't be jumped over, 3941 // bail out of any immediately-surrounding compound-statement too. 3942 default: 3943 return ESR_CaseNotFound; 3944 } 3945 } 3946 3947 switch (S->getStmtClass()) { 3948 default: 3949 if (const Expr *E = dyn_cast<Expr>(S)) { 3950 // Don't bother evaluating beyond an expression-statement which couldn't 3951 // be evaluated. 3952 FullExpressionRAII Scope(Info); 3953 if (!EvaluateIgnoredValue(Info, E)) 3954 return ESR_Failed; 3955 return ESR_Succeeded; 3956 } 3957 3958 Info.FFDiag(S->getLocStart()); 3959 return ESR_Failed; 3960 3961 case Stmt::NullStmtClass: 3962 return ESR_Succeeded; 3963 3964 case Stmt::DeclStmtClass: { 3965 const DeclStmt *DS = cast<DeclStmt>(S); 3966 for (const auto *DclIt : DS->decls()) { 3967 // Each declaration initialization is its own full-expression. 3968 // FIXME: This isn't quite right; if we're performing aggregate 3969 // initialization, each braced subexpression is its own full-expression. 3970 FullExpressionRAII Scope(Info); 3971 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 3972 return ESR_Failed; 3973 } 3974 return ESR_Succeeded; 3975 } 3976 3977 case Stmt::ReturnStmtClass: { 3978 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 3979 FullExpressionRAII Scope(Info); 3980 if (RetExpr && 3981 !(Result.Slot 3982 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 3983 : Evaluate(Result.Value, Info, RetExpr))) 3984 return ESR_Failed; 3985 return ESR_Returned; 3986 } 3987 3988 case Stmt::CompoundStmtClass: { 3989 BlockScopeRAII Scope(Info); 3990 3991 const CompoundStmt *CS = cast<CompoundStmt>(S); 3992 for (const auto *BI : CS->body()) { 3993 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 3994 if (ESR == ESR_Succeeded) 3995 Case = nullptr; 3996 else if (ESR != ESR_CaseNotFound) 3997 return ESR; 3998 } 3999 return Case ? ESR_CaseNotFound : ESR_Succeeded; 4000 } 4001 4002 case Stmt::IfStmtClass: { 4003 const IfStmt *IS = cast<IfStmt>(S); 4004 4005 // Evaluate the condition, as either a var decl or as an expression. 4006 BlockScopeRAII Scope(Info); 4007 if (const Stmt *Init = IS->getInit()) { 4008 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4009 if (ESR != ESR_Succeeded) 4010 return ESR; 4011 } 4012 bool Cond; 4013 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4014 return ESR_Failed; 4015 4016 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4017 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4018 if (ESR != ESR_Succeeded) 4019 return ESR; 4020 } 4021 return ESR_Succeeded; 4022 } 4023 4024 case Stmt::WhileStmtClass: { 4025 const WhileStmt *WS = cast<WhileStmt>(S); 4026 while (true) { 4027 BlockScopeRAII Scope(Info); 4028 bool Continue; 4029 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4030 Continue)) 4031 return ESR_Failed; 4032 if (!Continue) 4033 break; 4034 4035 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4036 if (ESR != ESR_Continue) 4037 return ESR; 4038 } 4039 return ESR_Succeeded; 4040 } 4041 4042 case Stmt::DoStmtClass: { 4043 const DoStmt *DS = cast<DoStmt>(S); 4044 bool Continue; 4045 do { 4046 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4047 if (ESR != ESR_Continue) 4048 return ESR; 4049 Case = nullptr; 4050 4051 FullExpressionRAII CondScope(Info); 4052 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4053 return ESR_Failed; 4054 } while (Continue); 4055 return ESR_Succeeded; 4056 } 4057 4058 case Stmt::ForStmtClass: { 4059 const ForStmt *FS = cast<ForStmt>(S); 4060 BlockScopeRAII Scope(Info); 4061 if (FS->getInit()) { 4062 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4063 if (ESR != ESR_Succeeded) 4064 return ESR; 4065 } 4066 while (true) { 4067 BlockScopeRAII Scope(Info); 4068 bool Continue = true; 4069 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4070 FS->getCond(), Continue)) 4071 return ESR_Failed; 4072 if (!Continue) 4073 break; 4074 4075 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4076 if (ESR != ESR_Continue) 4077 return ESR; 4078 4079 if (FS->getInc()) { 4080 FullExpressionRAII IncScope(Info); 4081 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4082 return ESR_Failed; 4083 } 4084 } 4085 return ESR_Succeeded; 4086 } 4087 4088 case Stmt::CXXForRangeStmtClass: { 4089 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4090 BlockScopeRAII Scope(Info); 4091 4092 // Initialize the __range variable. 4093 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4094 if (ESR != ESR_Succeeded) 4095 return ESR; 4096 4097 // Create the __begin and __end iterators. 4098 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4099 if (ESR != ESR_Succeeded) 4100 return ESR; 4101 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4102 if (ESR != ESR_Succeeded) 4103 return ESR; 4104 4105 while (true) { 4106 // Condition: __begin != __end. 4107 { 4108 bool Continue = true; 4109 FullExpressionRAII CondExpr(Info); 4110 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4111 return ESR_Failed; 4112 if (!Continue) 4113 break; 4114 } 4115 4116 // User's variable declaration, initialized by *__begin. 4117 BlockScopeRAII InnerScope(Info); 4118 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4119 if (ESR != ESR_Succeeded) 4120 return ESR; 4121 4122 // Loop body. 4123 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4124 if (ESR != ESR_Continue) 4125 return ESR; 4126 4127 // Increment: ++__begin 4128 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4129 return ESR_Failed; 4130 } 4131 4132 return ESR_Succeeded; 4133 } 4134 4135 case Stmt::SwitchStmtClass: 4136 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4137 4138 case Stmt::ContinueStmtClass: 4139 return ESR_Continue; 4140 4141 case Stmt::BreakStmtClass: 4142 return ESR_Break; 4143 4144 case Stmt::LabelStmtClass: 4145 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4146 4147 case Stmt::AttributedStmtClass: 4148 // As a general principle, C++11 attributes can be ignored without 4149 // any semantic impact. 4150 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4151 Case); 4152 4153 case Stmt::CaseStmtClass: 4154 case Stmt::DefaultStmtClass: 4155 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4156 } 4157 } 4158 4159 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4160 /// default constructor. If so, we'll fold it whether or not it's marked as 4161 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4162 /// so we need special handling. 4163 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4164 const CXXConstructorDecl *CD, 4165 bool IsValueInitialization) { 4166 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4167 return false; 4168 4169 // Value-initialization does not call a trivial default constructor, so such a 4170 // call is a core constant expression whether or not the constructor is 4171 // constexpr. 4172 if (!CD->isConstexpr() && !IsValueInitialization) { 4173 if (Info.getLangOpts().CPlusPlus11) { 4174 // FIXME: If DiagDecl is an implicitly-declared special member function, 4175 // we should be much more explicit about why it's not constexpr. 4176 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4177 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4178 Info.Note(CD->getLocation(), diag::note_declared_at); 4179 } else { 4180 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4181 } 4182 } 4183 return true; 4184 } 4185 4186 /// CheckConstexprFunction - Check that a function can be called in a constant 4187 /// expression. 4188 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4189 const FunctionDecl *Declaration, 4190 const FunctionDecl *Definition, 4191 const Stmt *Body) { 4192 // Potential constant expressions can contain calls to declared, but not yet 4193 // defined, constexpr functions. 4194 if (Info.checkingPotentialConstantExpression() && !Definition && 4195 Declaration->isConstexpr()) 4196 return false; 4197 4198 // Bail out with no diagnostic if the function declaration itself is invalid. 4199 // We will have produced a relevant diagnostic while parsing it. 4200 if (Declaration->isInvalidDecl()) 4201 return false; 4202 4203 // Can we evaluate this function call? 4204 if (Definition && Definition->isConstexpr() && 4205 !Definition->isInvalidDecl() && Body) 4206 return true; 4207 4208 if (Info.getLangOpts().CPlusPlus11) { 4209 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4210 4211 // If this function is not constexpr because it is an inherited 4212 // non-constexpr constructor, diagnose that directly. 4213 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4214 if (CD && CD->isInheritingConstructor()) { 4215 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4216 if (!Inherited->isConstexpr()) 4217 DiagDecl = CD = Inherited; 4218 } 4219 4220 // FIXME: If DiagDecl is an implicitly-declared special member function 4221 // or an inheriting constructor, we should be much more explicit about why 4222 // it's not constexpr. 4223 if (CD && CD->isInheritingConstructor()) 4224 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4225 << CD->getInheritedConstructor().getConstructor()->getParent(); 4226 else 4227 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4228 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4229 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4230 } else { 4231 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4232 } 4233 return false; 4234 } 4235 4236 /// Determine if a class has any fields that might need to be copied by a 4237 /// trivial copy or move operation. 4238 static bool hasFields(const CXXRecordDecl *RD) { 4239 if (!RD || RD->isEmpty()) 4240 return false; 4241 for (auto *FD : RD->fields()) { 4242 if (FD->isUnnamedBitfield()) 4243 continue; 4244 return true; 4245 } 4246 for (auto &Base : RD->bases()) 4247 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 4248 return true; 4249 return false; 4250 } 4251 4252 namespace { 4253 typedef SmallVector<APValue, 8> ArgVector; 4254 } 4255 4256 /// EvaluateArgs - Evaluate the arguments to a function call. 4257 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 4258 EvalInfo &Info) { 4259 bool Success = true; 4260 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 4261 I != E; ++I) { 4262 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 4263 // If we're checking for a potential constant expression, evaluate all 4264 // initializers even if some of them fail. 4265 if (!Info.noteFailure()) 4266 return false; 4267 Success = false; 4268 } 4269 } 4270 return Success; 4271 } 4272 4273 /// Evaluate a function call. 4274 static bool HandleFunctionCall(SourceLocation CallLoc, 4275 const FunctionDecl *Callee, const LValue *This, 4276 ArrayRef<const Expr*> Args, const Stmt *Body, 4277 EvalInfo &Info, APValue &Result, 4278 const LValue *ResultSlot) { 4279 ArgVector ArgValues(Args.size()); 4280 if (!EvaluateArgs(Args, ArgValues, Info)) 4281 return false; 4282 4283 if (!Info.CheckCallLimit(CallLoc)) 4284 return false; 4285 4286 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 4287 4288 // For a trivial copy or move assignment, perform an APValue copy. This is 4289 // essential for unions, where the operations performed by the assignment 4290 // operator cannot be represented as statements. 4291 // 4292 // Skip this for non-union classes with no fields; in that case, the defaulted 4293 // copy/move does not actually read the object. 4294 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 4295 if (MD && MD->isDefaulted() && 4296 (MD->getParent()->isUnion() || 4297 (MD->isTrivial() && hasFields(MD->getParent())))) { 4298 assert(This && 4299 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 4300 LValue RHS; 4301 RHS.setFrom(Info.Ctx, ArgValues[0]); 4302 APValue RHSValue; 4303 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 4304 RHS, RHSValue)) 4305 return false; 4306 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx), 4307 RHSValue)) 4308 return false; 4309 This->moveInto(Result); 4310 return true; 4311 } else if (MD && isLambdaCallOperator(MD)) { 4312 // We're in a lambda; determine the lambda capture field maps unless we're 4313 // just constexpr checking a lambda's call operator. constexpr checking is 4314 // done before the captures have been added to the closure object (unless 4315 // we're inferring constexpr-ness), so we don't have access to them in this 4316 // case. But since we don't need the captures to constexpr check, we can 4317 // just ignore them. 4318 if (!Info.checkingPotentialConstantExpression()) 4319 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 4320 Frame.LambdaThisCaptureField); 4321 } 4322 4323 StmtResult Ret = {Result, ResultSlot}; 4324 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 4325 if (ESR == ESR_Succeeded) { 4326 if (Callee->getReturnType()->isVoidType()) 4327 return true; 4328 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return); 4329 } 4330 return ESR == ESR_Returned; 4331 } 4332 4333 /// Evaluate a constructor call. 4334 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4335 APValue *ArgValues, 4336 const CXXConstructorDecl *Definition, 4337 EvalInfo &Info, APValue &Result) { 4338 SourceLocation CallLoc = E->getExprLoc(); 4339 if (!Info.CheckCallLimit(CallLoc)) 4340 return false; 4341 4342 const CXXRecordDecl *RD = Definition->getParent(); 4343 if (RD->getNumVBases()) { 4344 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 4345 return false; 4346 } 4347 4348 EvalInfo::EvaluatingConstructorRAII EvalObj( 4349 Info, {This.getLValueBase(), This.CallIndex}); 4350 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 4351 4352 // FIXME: Creating an APValue just to hold a nonexistent return value is 4353 // wasteful. 4354 APValue RetVal; 4355 StmtResult Ret = {RetVal, nullptr}; 4356 4357 // If it's a delegating constructor, delegate. 4358 if (Definition->isDelegatingConstructor()) { 4359 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 4360 { 4361 FullExpressionRAII InitScope(Info); 4362 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 4363 return false; 4364 } 4365 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4366 } 4367 4368 // For a trivial copy or move constructor, perform an APValue copy. This is 4369 // essential for unions (or classes with anonymous union members), where the 4370 // operations performed by the constructor cannot be represented by 4371 // ctor-initializers. 4372 // 4373 // Skip this for empty non-union classes; we should not perform an 4374 // lvalue-to-rvalue conversion on them because their copy constructor does not 4375 // actually read them. 4376 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 4377 (Definition->getParent()->isUnion() || 4378 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 4379 LValue RHS; 4380 RHS.setFrom(Info.Ctx, ArgValues[0]); 4381 return handleLValueToRValueConversion( 4382 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 4383 RHS, Result); 4384 } 4385 4386 // Reserve space for the struct members. 4387 if (!RD->isUnion() && Result.isUninit()) 4388 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4389 std::distance(RD->field_begin(), RD->field_end())); 4390 4391 if (RD->isInvalidDecl()) return false; 4392 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 4393 4394 // A scope for temporaries lifetime-extended by reference members. 4395 BlockScopeRAII LifetimeExtendedScope(Info); 4396 4397 bool Success = true; 4398 unsigned BasesSeen = 0; 4399 #ifndef NDEBUG 4400 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 4401 #endif 4402 for (const auto *I : Definition->inits()) { 4403 LValue Subobject = This; 4404 LValue SubobjectParent = This; 4405 APValue *Value = &Result; 4406 4407 // Determine the subobject to initialize. 4408 FieldDecl *FD = nullptr; 4409 if (I->isBaseInitializer()) { 4410 QualType BaseType(I->getBaseClass(), 0); 4411 #ifndef NDEBUG 4412 // Non-virtual base classes are initialized in the order in the class 4413 // definition. We have already checked for virtual base classes. 4414 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 4415 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 4416 "base class initializers not in expected order"); 4417 ++BaseIt; 4418 #endif 4419 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 4420 BaseType->getAsCXXRecordDecl(), &Layout)) 4421 return false; 4422 Value = &Result.getStructBase(BasesSeen++); 4423 } else if ((FD = I->getMember())) { 4424 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 4425 return false; 4426 if (RD->isUnion()) { 4427 Result = APValue(FD); 4428 Value = &Result.getUnionValue(); 4429 } else { 4430 Value = &Result.getStructField(FD->getFieldIndex()); 4431 } 4432 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 4433 // Walk the indirect field decl's chain to find the object to initialize, 4434 // and make sure we've initialized every step along it. 4435 auto IndirectFieldChain = IFD->chain(); 4436 for (auto *C : IndirectFieldChain) { 4437 FD = cast<FieldDecl>(C); 4438 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 4439 // Switch the union field if it differs. This happens if we had 4440 // preceding zero-initialization, and we're now initializing a union 4441 // subobject other than the first. 4442 // FIXME: In this case, the values of the other subobjects are 4443 // specified, since zero-initialization sets all padding bits to zero. 4444 if (Value->isUninit() || 4445 (Value->isUnion() && Value->getUnionField() != FD)) { 4446 if (CD->isUnion()) 4447 *Value = APValue(FD); 4448 else 4449 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 4450 std::distance(CD->field_begin(), CD->field_end())); 4451 } 4452 // Store Subobject as its parent before updating it for the last element 4453 // in the chain. 4454 if (C == IndirectFieldChain.back()) 4455 SubobjectParent = Subobject; 4456 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 4457 return false; 4458 if (CD->isUnion()) 4459 Value = &Value->getUnionValue(); 4460 else 4461 Value = &Value->getStructField(FD->getFieldIndex()); 4462 } 4463 } else { 4464 llvm_unreachable("unknown base initializer kind"); 4465 } 4466 4467 // Need to override This for implicit field initializers as in this case 4468 // This refers to innermost anonymous struct/union containing initializer, 4469 // not to currently constructed class. 4470 const Expr *Init = I->getInit(); 4471 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 4472 isa<CXXDefaultInitExpr>(Init)); 4473 FullExpressionRAII InitScope(Info); 4474 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 4475 (FD && FD->isBitField() && 4476 !truncateBitfieldValue(Info, Init, *Value, FD))) { 4477 // If we're checking for a potential constant expression, evaluate all 4478 // initializers even if some of them fail. 4479 if (!Info.noteFailure()) 4480 return false; 4481 Success = false; 4482 } 4483 } 4484 4485 return Success && 4486 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4487 } 4488 4489 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4490 ArrayRef<const Expr*> Args, 4491 const CXXConstructorDecl *Definition, 4492 EvalInfo &Info, APValue &Result) { 4493 ArgVector ArgValues(Args.size()); 4494 if (!EvaluateArgs(Args, ArgValues, Info)) 4495 return false; 4496 4497 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 4498 Info, Result); 4499 } 4500 4501 //===----------------------------------------------------------------------===// 4502 // Generic Evaluation 4503 //===----------------------------------------------------------------------===// 4504 namespace { 4505 4506 template <class Derived> 4507 class ExprEvaluatorBase 4508 : public ConstStmtVisitor<Derived, bool> { 4509 private: 4510 Derived &getDerived() { return static_cast<Derived&>(*this); } 4511 bool DerivedSuccess(const APValue &V, const Expr *E) { 4512 return getDerived().Success(V, E); 4513 } 4514 bool DerivedZeroInitialization(const Expr *E) { 4515 return getDerived().ZeroInitialization(E); 4516 } 4517 4518 // Check whether a conditional operator with a non-constant condition is a 4519 // potential constant expression. If neither arm is a potential constant 4520 // expression, then the conditional operator is not either. 4521 template<typename ConditionalOperator> 4522 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 4523 assert(Info.checkingPotentialConstantExpression()); 4524 4525 // Speculatively evaluate both arms. 4526 SmallVector<PartialDiagnosticAt, 8> Diag; 4527 { 4528 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4529 StmtVisitorTy::Visit(E->getFalseExpr()); 4530 if (Diag.empty()) 4531 return; 4532 } 4533 4534 { 4535 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4536 Diag.clear(); 4537 StmtVisitorTy::Visit(E->getTrueExpr()); 4538 if (Diag.empty()) 4539 return; 4540 } 4541 4542 Error(E, diag::note_constexpr_conditional_never_const); 4543 } 4544 4545 4546 template<typename ConditionalOperator> 4547 bool HandleConditionalOperator(const ConditionalOperator *E) { 4548 bool BoolResult; 4549 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 4550 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 4551 CheckPotentialConstantConditional(E); 4552 return false; 4553 } 4554 if (Info.noteFailure()) { 4555 StmtVisitorTy::Visit(E->getTrueExpr()); 4556 StmtVisitorTy::Visit(E->getFalseExpr()); 4557 } 4558 return false; 4559 } 4560 4561 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 4562 return StmtVisitorTy::Visit(EvalExpr); 4563 } 4564 4565 protected: 4566 EvalInfo &Info; 4567 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 4568 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 4569 4570 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 4571 return Info.CCEDiag(E, D); 4572 } 4573 4574 bool ZeroInitialization(const Expr *E) { return Error(E); } 4575 4576 public: 4577 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 4578 4579 EvalInfo &getEvalInfo() { return Info; } 4580 4581 /// Report an evaluation error. This should only be called when an error is 4582 /// first discovered. When propagating an error, just return false. 4583 bool Error(const Expr *E, diag::kind D) { 4584 Info.FFDiag(E, D); 4585 return false; 4586 } 4587 bool Error(const Expr *E) { 4588 return Error(E, diag::note_invalid_subexpr_in_const_expr); 4589 } 4590 4591 bool VisitStmt(const Stmt *) { 4592 llvm_unreachable("Expression evaluator should not be called on stmts"); 4593 } 4594 bool VisitExpr(const Expr *E) { 4595 return Error(E); 4596 } 4597 4598 bool VisitParenExpr(const ParenExpr *E) 4599 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4600 bool VisitUnaryExtension(const UnaryOperator *E) 4601 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4602 bool VisitUnaryPlus(const UnaryOperator *E) 4603 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4604 bool VisitChooseExpr(const ChooseExpr *E) 4605 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 4606 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 4607 { return StmtVisitorTy::Visit(E->getResultExpr()); } 4608 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 4609 { return StmtVisitorTy::Visit(E->getReplacement()); } 4610 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) 4611 { return StmtVisitorTy::Visit(E->getExpr()); } 4612 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4613 // The initializer may not have been parsed yet, or might be erroneous. 4614 if (!E->getExpr()) 4615 return Error(E); 4616 return StmtVisitorTy::Visit(E->getExpr()); 4617 } 4618 // We cannot create any objects for which cleanups are required, so there is 4619 // nothing to do here; all cleanups must come from unevaluated subexpressions. 4620 bool VisitExprWithCleanups(const ExprWithCleanups *E) 4621 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4622 4623 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 4624 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 4625 return static_cast<Derived*>(this)->VisitCastExpr(E); 4626 } 4627 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 4628 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 4629 return static_cast<Derived*>(this)->VisitCastExpr(E); 4630 } 4631 4632 bool VisitBinaryOperator(const BinaryOperator *E) { 4633 switch (E->getOpcode()) { 4634 default: 4635 return Error(E); 4636 4637 case BO_Comma: 4638 VisitIgnoredValue(E->getLHS()); 4639 return StmtVisitorTy::Visit(E->getRHS()); 4640 4641 case BO_PtrMemD: 4642 case BO_PtrMemI: { 4643 LValue Obj; 4644 if (!HandleMemberPointerAccess(Info, E, Obj)) 4645 return false; 4646 APValue Result; 4647 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 4648 return false; 4649 return DerivedSuccess(Result, E); 4650 } 4651 } 4652 } 4653 4654 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 4655 // Evaluate and cache the common expression. We treat it as a temporary, 4656 // even though it's not quite the same thing. 4657 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 4658 Info, E->getCommon())) 4659 return false; 4660 4661 return HandleConditionalOperator(E); 4662 } 4663 4664 bool VisitConditionalOperator(const ConditionalOperator *E) { 4665 bool IsBcpCall = false; 4666 // If the condition (ignoring parens) is a __builtin_constant_p call, 4667 // the result is a constant expression if it can be folded without 4668 // side-effects. This is an important GNU extension. See GCC PR38377 4669 // for discussion. 4670 if (const CallExpr *CallCE = 4671 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 4672 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 4673 IsBcpCall = true; 4674 4675 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 4676 // constant expression; we can't check whether it's potentially foldable. 4677 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 4678 return false; 4679 4680 FoldConstant Fold(Info, IsBcpCall); 4681 if (!HandleConditionalOperator(E)) { 4682 Fold.keepDiagnostics(); 4683 return false; 4684 } 4685 4686 return true; 4687 } 4688 4689 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 4690 if (APValue *Value = Info.CurrentCall->getTemporary(E)) 4691 return DerivedSuccess(*Value, E); 4692 4693 const Expr *Source = E->getSourceExpr(); 4694 if (!Source) 4695 return Error(E); 4696 if (Source == E) { // sanity checking. 4697 assert(0 && "OpaqueValueExpr recursively refers to itself"); 4698 return Error(E); 4699 } 4700 return StmtVisitorTy::Visit(Source); 4701 } 4702 4703 bool VisitCallExpr(const CallExpr *E) { 4704 APValue Result; 4705 if (!handleCallExpr(E, Result, nullptr)) 4706 return false; 4707 return DerivedSuccess(Result, E); 4708 } 4709 4710 bool handleCallExpr(const CallExpr *E, APValue &Result, 4711 const LValue *ResultSlot) { 4712 const Expr *Callee = E->getCallee()->IgnoreParens(); 4713 QualType CalleeType = Callee->getType(); 4714 4715 const FunctionDecl *FD = nullptr; 4716 LValue *This = nullptr, ThisVal; 4717 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 4718 bool HasQualifier = false; 4719 4720 // Extract function decl and 'this' pointer from the callee. 4721 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 4722 const ValueDecl *Member = nullptr; 4723 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 4724 // Explicit bound member calls, such as x.f() or p->g(); 4725 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 4726 return false; 4727 Member = ME->getMemberDecl(); 4728 This = &ThisVal; 4729 HasQualifier = ME->hasQualifier(); 4730 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 4731 // Indirect bound member calls ('.*' or '->*'). 4732 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 4733 if (!Member) return false; 4734 This = &ThisVal; 4735 } else 4736 return Error(Callee); 4737 4738 FD = dyn_cast<FunctionDecl>(Member); 4739 if (!FD) 4740 return Error(Callee); 4741 } else if (CalleeType->isFunctionPointerType()) { 4742 LValue Call; 4743 if (!EvaluatePointer(Callee, Call, Info)) 4744 return false; 4745 4746 if (!Call.getLValueOffset().isZero()) 4747 return Error(Callee); 4748 FD = dyn_cast_or_null<FunctionDecl>( 4749 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 4750 if (!FD) 4751 return Error(Callee); 4752 // Don't call function pointers which have been cast to some other type. 4753 // Per DR (no number yet), the caller and callee can differ in noexcept. 4754 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 4755 CalleeType->getPointeeType(), FD->getType())) { 4756 return Error(E); 4757 } 4758 4759 // Overloaded operator calls to member functions are represented as normal 4760 // calls with '*this' as the first argument. 4761 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 4762 if (MD && !MD->isStatic()) { 4763 // FIXME: When selecting an implicit conversion for an overloaded 4764 // operator delete, we sometimes try to evaluate calls to conversion 4765 // operators without a 'this' parameter! 4766 if (Args.empty()) 4767 return Error(E); 4768 4769 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 4770 return false; 4771 This = &ThisVal; 4772 Args = Args.slice(1); 4773 } else if (MD && MD->isLambdaStaticInvoker()) { 4774 // Map the static invoker for the lambda back to the call operator. 4775 // Conveniently, we don't have to slice out the 'this' argument (as is 4776 // being done for the non-static case), since a static member function 4777 // doesn't have an implicit argument passed in. 4778 const CXXRecordDecl *ClosureClass = MD->getParent(); 4779 assert( 4780 ClosureClass->captures_begin() == ClosureClass->captures_end() && 4781 "Number of captures must be zero for conversion to function-ptr"); 4782 4783 const CXXMethodDecl *LambdaCallOp = 4784 ClosureClass->getLambdaCallOperator(); 4785 4786 // Set 'FD', the function that will be called below, to the call 4787 // operator. If the closure object represents a generic lambda, find 4788 // the corresponding specialization of the call operator. 4789 4790 if (ClosureClass->isGenericLambda()) { 4791 assert(MD->isFunctionTemplateSpecialization() && 4792 "A generic lambda's static-invoker function must be a " 4793 "template specialization"); 4794 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 4795 FunctionTemplateDecl *CallOpTemplate = 4796 LambdaCallOp->getDescribedFunctionTemplate(); 4797 void *InsertPos = nullptr; 4798 FunctionDecl *CorrespondingCallOpSpecialization = 4799 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 4800 assert(CorrespondingCallOpSpecialization && 4801 "We must always have a function call operator specialization " 4802 "that corresponds to our static invoker specialization"); 4803 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 4804 } else 4805 FD = LambdaCallOp; 4806 } 4807 4808 4809 } else 4810 return Error(E); 4811 4812 if (This && !This->checkSubobject(Info, E, CSK_This)) 4813 return false; 4814 4815 // DR1358 allows virtual constexpr functions in some cases. Don't allow 4816 // calls to such functions in constant expressions. 4817 if (This && !HasQualifier && 4818 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual()) 4819 return Error(E, diag::note_constexpr_virtual_call); 4820 4821 const FunctionDecl *Definition = nullptr; 4822 Stmt *Body = FD->getBody(Definition); 4823 4824 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 4825 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 4826 Result, ResultSlot)) 4827 return false; 4828 4829 return true; 4830 } 4831 4832 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 4833 return StmtVisitorTy::Visit(E->getInitializer()); 4834 } 4835 bool VisitInitListExpr(const InitListExpr *E) { 4836 if (E->getNumInits() == 0) 4837 return DerivedZeroInitialization(E); 4838 if (E->getNumInits() == 1) 4839 return StmtVisitorTy::Visit(E->getInit(0)); 4840 return Error(E); 4841 } 4842 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 4843 return DerivedZeroInitialization(E); 4844 } 4845 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 4846 return DerivedZeroInitialization(E); 4847 } 4848 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 4849 return DerivedZeroInitialization(E); 4850 } 4851 4852 /// A member expression where the object is a prvalue is itself a prvalue. 4853 bool VisitMemberExpr(const MemberExpr *E) { 4854 assert(!E->isArrow() && "missing call to bound member function?"); 4855 4856 APValue Val; 4857 if (!Evaluate(Val, Info, E->getBase())) 4858 return false; 4859 4860 QualType BaseTy = E->getBase()->getType(); 4861 4862 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 4863 if (!FD) return Error(E); 4864 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 4865 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 4866 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 4867 4868 CompleteObject Obj(&Val, BaseTy, true); 4869 SubobjectDesignator Designator(BaseTy); 4870 Designator.addDeclUnchecked(FD); 4871 4872 APValue Result; 4873 return extractSubobject(Info, E, Obj, Designator, Result) && 4874 DerivedSuccess(Result, E); 4875 } 4876 4877 bool VisitCastExpr(const CastExpr *E) { 4878 switch (E->getCastKind()) { 4879 default: 4880 break; 4881 4882 case CK_AtomicToNonAtomic: { 4883 APValue AtomicVal; 4884 // This does not need to be done in place even for class/array types: 4885 // atomic-to-non-atomic conversion implies copying the object 4886 // representation. 4887 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 4888 return false; 4889 return DerivedSuccess(AtomicVal, E); 4890 } 4891 4892 case CK_NoOp: 4893 case CK_UserDefinedConversion: 4894 return StmtVisitorTy::Visit(E->getSubExpr()); 4895 4896 case CK_LValueToRValue: { 4897 LValue LVal; 4898 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 4899 return false; 4900 APValue RVal; 4901 // Note, we use the subexpression's type in order to retain cv-qualifiers. 4902 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 4903 LVal, RVal)) 4904 return false; 4905 return DerivedSuccess(RVal, E); 4906 } 4907 } 4908 4909 return Error(E); 4910 } 4911 4912 bool VisitUnaryPostInc(const UnaryOperator *UO) { 4913 return VisitUnaryPostIncDec(UO); 4914 } 4915 bool VisitUnaryPostDec(const UnaryOperator *UO) { 4916 return VisitUnaryPostIncDec(UO); 4917 } 4918 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 4919 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 4920 return Error(UO); 4921 4922 LValue LVal; 4923 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 4924 return false; 4925 APValue RVal; 4926 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 4927 UO->isIncrementOp(), &RVal)) 4928 return false; 4929 return DerivedSuccess(RVal, UO); 4930 } 4931 4932 bool VisitStmtExpr(const StmtExpr *E) { 4933 // We will have checked the full-expressions inside the statement expression 4934 // when they were completed, and don't need to check them again now. 4935 if (Info.checkingForOverflow()) 4936 return Error(E); 4937 4938 BlockScopeRAII Scope(Info); 4939 const CompoundStmt *CS = E->getSubStmt(); 4940 if (CS->body_empty()) 4941 return true; 4942 4943 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 4944 BE = CS->body_end(); 4945 /**/; ++BI) { 4946 if (BI + 1 == BE) { 4947 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 4948 if (!FinalExpr) { 4949 Info.FFDiag((*BI)->getLocStart(), 4950 diag::note_constexpr_stmt_expr_unsupported); 4951 return false; 4952 } 4953 return this->Visit(FinalExpr); 4954 } 4955 4956 APValue ReturnValue; 4957 StmtResult Result = { ReturnValue, nullptr }; 4958 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 4959 if (ESR != ESR_Succeeded) { 4960 // FIXME: If the statement-expression terminated due to 'return', 4961 // 'break', or 'continue', it would be nice to propagate that to 4962 // the outer statement evaluation rather than bailing out. 4963 if (ESR != ESR_Failed) 4964 Info.FFDiag((*BI)->getLocStart(), 4965 diag::note_constexpr_stmt_expr_unsupported); 4966 return false; 4967 } 4968 } 4969 4970 llvm_unreachable("Return from function from the loop above."); 4971 } 4972 4973 /// Visit a value which is evaluated, but whose value is ignored. 4974 void VisitIgnoredValue(const Expr *E) { 4975 EvaluateIgnoredValue(Info, E); 4976 } 4977 4978 /// Potentially visit a MemberExpr's base expression. 4979 void VisitIgnoredBaseExpression(const Expr *E) { 4980 // While MSVC doesn't evaluate the base expression, it does diagnose the 4981 // presence of side-effecting behavior. 4982 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 4983 return; 4984 VisitIgnoredValue(E); 4985 } 4986 }; 4987 4988 } 4989 4990 //===----------------------------------------------------------------------===// 4991 // Common base class for lvalue and temporary evaluation. 4992 //===----------------------------------------------------------------------===// 4993 namespace { 4994 template<class Derived> 4995 class LValueExprEvaluatorBase 4996 : public ExprEvaluatorBase<Derived> { 4997 protected: 4998 LValue &Result; 4999 bool InvalidBaseOK; 5000 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 5001 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 5002 5003 bool Success(APValue::LValueBase B) { 5004 Result.set(B); 5005 return true; 5006 } 5007 5008 bool evaluatePointer(const Expr *E, LValue &Result) { 5009 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 5010 } 5011 5012 public: 5013 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 5014 : ExprEvaluatorBaseTy(Info), Result(Result), 5015 InvalidBaseOK(InvalidBaseOK) {} 5016 5017 bool Success(const APValue &V, const Expr *E) { 5018 Result.setFrom(this->Info.Ctx, V); 5019 return true; 5020 } 5021 5022 bool VisitMemberExpr(const MemberExpr *E) { 5023 // Handle non-static data members. 5024 QualType BaseTy; 5025 bool EvalOK; 5026 if (E->isArrow()) { 5027 EvalOK = evaluatePointer(E->getBase(), Result); 5028 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 5029 } else if (E->getBase()->isRValue()) { 5030 assert(E->getBase()->getType()->isRecordType()); 5031 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 5032 BaseTy = E->getBase()->getType(); 5033 } else { 5034 EvalOK = this->Visit(E->getBase()); 5035 BaseTy = E->getBase()->getType(); 5036 } 5037 if (!EvalOK) { 5038 if (!InvalidBaseOK) 5039 return false; 5040 Result.setInvalid(E); 5041 return true; 5042 } 5043 5044 const ValueDecl *MD = E->getMemberDecl(); 5045 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 5046 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 5047 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5048 (void)BaseTy; 5049 if (!HandleLValueMember(this->Info, E, Result, FD)) 5050 return false; 5051 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 5052 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 5053 return false; 5054 } else 5055 return this->Error(E); 5056 5057 if (MD->getType()->isReferenceType()) { 5058 APValue RefValue; 5059 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 5060 RefValue)) 5061 return false; 5062 return Success(RefValue, E); 5063 } 5064 return true; 5065 } 5066 5067 bool VisitBinaryOperator(const BinaryOperator *E) { 5068 switch (E->getOpcode()) { 5069 default: 5070 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5071 5072 case BO_PtrMemD: 5073 case BO_PtrMemI: 5074 return HandleMemberPointerAccess(this->Info, E, Result); 5075 } 5076 } 5077 5078 bool VisitCastExpr(const CastExpr *E) { 5079 switch (E->getCastKind()) { 5080 default: 5081 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5082 5083 case CK_DerivedToBase: 5084 case CK_UncheckedDerivedToBase: 5085 if (!this->Visit(E->getSubExpr())) 5086 return false; 5087 5088 // Now figure out the necessary offset to add to the base LV to get from 5089 // the derived class to the base class. 5090 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 5091 Result); 5092 } 5093 } 5094 }; 5095 } 5096 5097 //===----------------------------------------------------------------------===// 5098 // LValue Evaluation 5099 // 5100 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 5101 // function designators (in C), decl references to void objects (in C), and 5102 // temporaries (if building with -Wno-address-of-temporary). 5103 // 5104 // LValue evaluation produces values comprising a base expression of one of the 5105 // following types: 5106 // - Declarations 5107 // * VarDecl 5108 // * FunctionDecl 5109 // - Literals 5110 // * CompoundLiteralExpr in C (and in global scope in C++) 5111 // * StringLiteral 5112 // * CXXTypeidExpr 5113 // * PredefinedExpr 5114 // * ObjCStringLiteralExpr 5115 // * ObjCEncodeExpr 5116 // * AddrLabelExpr 5117 // * BlockExpr 5118 // * CallExpr for a MakeStringConstant builtin 5119 // - Locals and temporaries 5120 // * MaterializeTemporaryExpr 5121 // * Any Expr, with a CallIndex indicating the function in which the temporary 5122 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 5123 // from the AST (FIXME). 5124 // * A MaterializeTemporaryExpr that has static storage duration, with no 5125 // CallIndex, for a lifetime-extended temporary. 5126 // plus an offset in bytes. 5127 //===----------------------------------------------------------------------===// 5128 namespace { 5129 class LValueExprEvaluator 5130 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 5131 public: 5132 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 5133 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 5134 5135 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 5136 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 5137 5138 bool VisitDeclRefExpr(const DeclRefExpr *E); 5139 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 5140 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 5141 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 5142 bool VisitMemberExpr(const MemberExpr *E); 5143 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 5144 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 5145 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 5146 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 5147 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 5148 bool VisitUnaryDeref(const UnaryOperator *E); 5149 bool VisitUnaryReal(const UnaryOperator *E); 5150 bool VisitUnaryImag(const UnaryOperator *E); 5151 bool VisitUnaryPreInc(const UnaryOperator *UO) { 5152 return VisitUnaryPreIncDec(UO); 5153 } 5154 bool VisitUnaryPreDec(const UnaryOperator *UO) { 5155 return VisitUnaryPreIncDec(UO); 5156 } 5157 bool VisitBinAssign(const BinaryOperator *BO); 5158 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 5159 5160 bool VisitCastExpr(const CastExpr *E) { 5161 switch (E->getCastKind()) { 5162 default: 5163 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 5164 5165 case CK_LValueBitCast: 5166 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5167 if (!Visit(E->getSubExpr())) 5168 return false; 5169 Result.Designator.setInvalid(); 5170 return true; 5171 5172 case CK_BaseToDerived: 5173 if (!Visit(E->getSubExpr())) 5174 return false; 5175 return HandleBaseToDerivedCast(Info, E, Result); 5176 } 5177 } 5178 }; 5179 } // end anonymous namespace 5180 5181 /// Evaluate an expression as an lvalue. This can be legitimately called on 5182 /// expressions which are not glvalues, in three cases: 5183 /// * function designators in C, and 5184 /// * "extern void" objects 5185 /// * @selector() expressions in Objective-C 5186 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 5187 bool InvalidBaseOK) { 5188 assert(E->isGLValue() || E->getType()->isFunctionType() || 5189 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 5190 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5191 } 5192 5193 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 5194 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 5195 return Success(FD); 5196 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 5197 return VisitVarDecl(E, VD); 5198 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 5199 return Visit(BD->getBinding()); 5200 return Error(E); 5201 } 5202 5203 5204 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 5205 5206 // If we are within a lambda's call operator, check whether the 'VD' referred 5207 // to within 'E' actually represents a lambda-capture that maps to a 5208 // data-member/field within the closure object, and if so, evaluate to the 5209 // field or what the field refers to. 5210 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 5211 isa<DeclRefExpr>(E) && 5212 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 5213 // We don't always have a complete capture-map when checking or inferring if 5214 // the function call operator meets the requirements of a constexpr function 5215 // - but we don't need to evaluate the captures to determine constexprness 5216 // (dcl.constexpr C++17). 5217 if (Info.checkingPotentialConstantExpression()) 5218 return false; 5219 5220 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 5221 // Start with 'Result' referring to the complete closure object... 5222 Result = *Info.CurrentCall->This; 5223 // ... then update it to refer to the field of the closure object 5224 // that represents the capture. 5225 if (!HandleLValueMember(Info, E, Result, FD)) 5226 return false; 5227 // And if the field is of reference type, update 'Result' to refer to what 5228 // the field refers to. 5229 if (FD->getType()->isReferenceType()) { 5230 APValue RVal; 5231 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 5232 RVal)) 5233 return false; 5234 Result.setFrom(Info.Ctx, RVal); 5235 } 5236 return true; 5237 } 5238 } 5239 CallStackFrame *Frame = nullptr; 5240 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 5241 // Only if a local variable was declared in the function currently being 5242 // evaluated, do we expect to be able to find its value in the current 5243 // frame. (Otherwise it was likely declared in an enclosing context and 5244 // could either have a valid evaluatable value (for e.g. a constexpr 5245 // variable) or be ill-formed (and trigger an appropriate evaluation 5246 // diagnostic)). 5247 if (Info.CurrentCall->Callee && 5248 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 5249 Frame = Info.CurrentCall; 5250 } 5251 } 5252 5253 if (!VD->getType()->isReferenceType()) { 5254 if (Frame) { 5255 Result.set(VD, Frame->Index); 5256 return true; 5257 } 5258 return Success(VD); 5259 } 5260 5261 APValue *V; 5262 if (!evaluateVarDeclInit(Info, E, VD, Frame, V)) 5263 return false; 5264 if (V->isUninit()) { 5265 if (!Info.checkingPotentialConstantExpression()) 5266 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 5267 return false; 5268 } 5269 return Success(*V, E); 5270 } 5271 5272 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 5273 const MaterializeTemporaryExpr *E) { 5274 // Walk through the expression to find the materialized temporary itself. 5275 SmallVector<const Expr *, 2> CommaLHSs; 5276 SmallVector<SubobjectAdjustment, 2> Adjustments; 5277 const Expr *Inner = E->GetTemporaryExpr()-> 5278 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 5279 5280 // If we passed any comma operators, evaluate their LHSs. 5281 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 5282 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 5283 return false; 5284 5285 // A materialized temporary with static storage duration can appear within the 5286 // result of a constant expression evaluation, so we need to preserve its 5287 // value for use outside this evaluation. 5288 APValue *Value; 5289 if (E->getStorageDuration() == SD_Static) { 5290 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 5291 *Value = APValue(); 5292 Result.set(E); 5293 } else { 5294 Value = &Info.CurrentCall-> 5295 createTemporary(E, E->getStorageDuration() == SD_Automatic); 5296 Result.set(E, Info.CurrentCall->Index); 5297 } 5298 5299 QualType Type = Inner->getType(); 5300 5301 // Materialize the temporary itself. 5302 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 5303 (E->getStorageDuration() == SD_Static && 5304 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 5305 *Value = APValue(); 5306 return false; 5307 } 5308 5309 // Adjust our lvalue to refer to the desired subobject. 5310 for (unsigned I = Adjustments.size(); I != 0; /**/) { 5311 --I; 5312 switch (Adjustments[I].Kind) { 5313 case SubobjectAdjustment::DerivedToBaseAdjustment: 5314 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 5315 Type, Result)) 5316 return false; 5317 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 5318 break; 5319 5320 case SubobjectAdjustment::FieldAdjustment: 5321 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 5322 return false; 5323 Type = Adjustments[I].Field->getType(); 5324 break; 5325 5326 case SubobjectAdjustment::MemberPointerAdjustment: 5327 if (!HandleMemberPointerAccess(this->Info, Type, Result, 5328 Adjustments[I].Ptr.RHS)) 5329 return false; 5330 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 5331 break; 5332 } 5333 } 5334 5335 return true; 5336 } 5337 5338 bool 5339 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 5340 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 5341 "lvalue compound literal in c++?"); 5342 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 5343 // only see this when folding in C, so there's no standard to follow here. 5344 return Success(E); 5345 } 5346 5347 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 5348 if (!E->isPotentiallyEvaluated()) 5349 return Success(E); 5350 5351 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic) 5352 << E->getExprOperand()->getType() 5353 << E->getExprOperand()->getSourceRange(); 5354 return false; 5355 } 5356 5357 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 5358 return Success(E); 5359 } 5360 5361 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 5362 // Handle static data members. 5363 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 5364 VisitIgnoredBaseExpression(E->getBase()); 5365 return VisitVarDecl(E, VD); 5366 } 5367 5368 // Handle static member functions. 5369 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 5370 if (MD->isStatic()) { 5371 VisitIgnoredBaseExpression(E->getBase()); 5372 return Success(MD); 5373 } 5374 } 5375 5376 // Handle non-static data members. 5377 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 5378 } 5379 5380 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 5381 // FIXME: Deal with vectors as array subscript bases. 5382 if (E->getBase()->getType()->isVectorType()) 5383 return Error(E); 5384 5385 bool Success = true; 5386 if (!evaluatePointer(E->getBase(), Result)) { 5387 if (!Info.noteFailure()) 5388 return false; 5389 Success = false; 5390 } 5391 5392 APSInt Index; 5393 if (!EvaluateInteger(E->getIdx(), Index, Info)) 5394 return false; 5395 5396 return Success && 5397 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 5398 } 5399 5400 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 5401 return evaluatePointer(E->getSubExpr(), Result); 5402 } 5403 5404 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 5405 if (!Visit(E->getSubExpr())) 5406 return false; 5407 // __real is a no-op on scalar lvalues. 5408 if (E->getSubExpr()->getType()->isAnyComplexType()) 5409 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 5410 return true; 5411 } 5412 5413 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 5414 assert(E->getSubExpr()->getType()->isAnyComplexType() && 5415 "lvalue __imag__ on scalar?"); 5416 if (!Visit(E->getSubExpr())) 5417 return false; 5418 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 5419 return true; 5420 } 5421 5422 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 5423 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5424 return Error(UO); 5425 5426 if (!this->Visit(UO->getSubExpr())) 5427 return false; 5428 5429 return handleIncDec( 5430 this->Info, UO, Result, UO->getSubExpr()->getType(), 5431 UO->isIncrementOp(), nullptr); 5432 } 5433 5434 bool LValueExprEvaluator::VisitCompoundAssignOperator( 5435 const CompoundAssignOperator *CAO) { 5436 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5437 return Error(CAO); 5438 5439 APValue RHS; 5440 5441 // The overall lvalue result is the result of evaluating the LHS. 5442 if (!this->Visit(CAO->getLHS())) { 5443 if (Info.noteFailure()) 5444 Evaluate(RHS, this->Info, CAO->getRHS()); 5445 return false; 5446 } 5447 5448 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 5449 return false; 5450 5451 return handleCompoundAssignment( 5452 this->Info, CAO, 5453 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 5454 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 5455 } 5456 5457 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 5458 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5459 return Error(E); 5460 5461 APValue NewVal; 5462 5463 if (!this->Visit(E->getLHS())) { 5464 if (Info.noteFailure()) 5465 Evaluate(NewVal, this->Info, E->getRHS()); 5466 return false; 5467 } 5468 5469 if (!Evaluate(NewVal, this->Info, E->getRHS())) 5470 return false; 5471 5472 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 5473 NewVal); 5474 } 5475 5476 //===----------------------------------------------------------------------===// 5477 // Pointer Evaluation 5478 //===----------------------------------------------------------------------===// 5479 5480 /// \brief Attempts to compute the number of bytes available at the pointer 5481 /// returned by a function with the alloc_size attribute. Returns true if we 5482 /// were successful. Places an unsigned number into `Result`. 5483 /// 5484 /// This expects the given CallExpr to be a call to a function with an 5485 /// alloc_size attribute. 5486 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5487 const CallExpr *Call, 5488 llvm::APInt &Result) { 5489 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 5490 5491 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 5492 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 5493 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 5494 if (Call->getNumArgs() <= SizeArgNo) 5495 return false; 5496 5497 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 5498 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects)) 5499 return false; 5500 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 5501 return false; 5502 Into = Into.zextOrSelf(BitsInSizeT); 5503 return true; 5504 }; 5505 5506 APSInt SizeOfElem; 5507 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 5508 return false; 5509 5510 if (!AllocSize->getNumElemsParam().isValid()) { 5511 Result = std::move(SizeOfElem); 5512 return true; 5513 } 5514 5515 APSInt NumberOfElems; 5516 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 5517 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 5518 return false; 5519 5520 bool Overflow; 5521 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 5522 if (Overflow) 5523 return false; 5524 5525 Result = std::move(BytesAvailable); 5526 return true; 5527 } 5528 5529 /// \brief Convenience function. LVal's base must be a call to an alloc_size 5530 /// function. 5531 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5532 const LValue &LVal, 5533 llvm::APInt &Result) { 5534 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 5535 "Can't get the size of a non alloc_size function"); 5536 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 5537 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 5538 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 5539 } 5540 5541 /// \brief Attempts to evaluate the given LValueBase as the result of a call to 5542 /// a function with the alloc_size attribute. If it was possible to do so, this 5543 /// function will return true, make Result's Base point to said function call, 5544 /// and mark Result's Base as invalid. 5545 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 5546 LValue &Result) { 5547 if (Base.isNull()) 5548 return false; 5549 5550 // Because we do no form of static analysis, we only support const variables. 5551 // 5552 // Additionally, we can't support parameters, nor can we support static 5553 // variables (in the latter case, use-before-assign isn't UB; in the former, 5554 // we have no clue what they'll be assigned to). 5555 const auto *VD = 5556 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 5557 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 5558 return false; 5559 5560 const Expr *Init = VD->getAnyInitializer(); 5561 if (!Init) 5562 return false; 5563 5564 const Expr *E = Init->IgnoreParens(); 5565 if (!tryUnwrapAllocSizeCall(E)) 5566 return false; 5567 5568 // Store E instead of E unwrapped so that the type of the LValue's base is 5569 // what the user wanted. 5570 Result.setInvalid(E); 5571 5572 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 5573 Result.addUnsizedArray(Info, E, Pointee); 5574 return true; 5575 } 5576 5577 namespace { 5578 class PointerExprEvaluator 5579 : public ExprEvaluatorBase<PointerExprEvaluator> { 5580 LValue &Result; 5581 bool InvalidBaseOK; 5582 5583 bool Success(const Expr *E) { 5584 Result.set(E); 5585 return true; 5586 } 5587 5588 bool evaluateLValue(const Expr *E, LValue &Result) { 5589 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 5590 } 5591 5592 bool evaluatePointer(const Expr *E, LValue &Result) { 5593 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 5594 } 5595 5596 bool visitNonBuiltinCallExpr(const CallExpr *E); 5597 public: 5598 5599 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 5600 : ExprEvaluatorBaseTy(info), Result(Result), 5601 InvalidBaseOK(InvalidBaseOK) {} 5602 5603 bool Success(const APValue &V, const Expr *E) { 5604 Result.setFrom(Info.Ctx, V); 5605 return true; 5606 } 5607 bool ZeroInitialization(const Expr *E) { 5608 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 5609 Result.setNull(E->getType(), TargetVal); 5610 return true; 5611 } 5612 5613 bool VisitBinaryOperator(const BinaryOperator *E); 5614 bool VisitCastExpr(const CastExpr* E); 5615 bool VisitUnaryAddrOf(const UnaryOperator *E); 5616 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 5617 { return Success(E); } 5618 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 5619 if (Info.noteFailure()) 5620 EvaluateIgnoredValue(Info, E->getSubExpr()); 5621 return Error(E); 5622 } 5623 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 5624 { return Success(E); } 5625 bool VisitCallExpr(const CallExpr *E); 5626 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 5627 bool VisitBlockExpr(const BlockExpr *E) { 5628 if (!E->getBlockDecl()->hasCaptures()) 5629 return Success(E); 5630 return Error(E); 5631 } 5632 bool VisitCXXThisExpr(const CXXThisExpr *E) { 5633 // Can't look at 'this' when checking a potential constant expression. 5634 if (Info.checkingPotentialConstantExpression()) 5635 return false; 5636 if (!Info.CurrentCall->This) { 5637 if (Info.getLangOpts().CPlusPlus11) 5638 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 5639 else 5640 Info.FFDiag(E); 5641 return false; 5642 } 5643 Result = *Info.CurrentCall->This; 5644 // If we are inside a lambda's call operator, the 'this' expression refers 5645 // to the enclosing '*this' object (either by value or reference) which is 5646 // either copied into the closure object's field that represents the '*this' 5647 // or refers to '*this'. 5648 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 5649 // Update 'Result' to refer to the data member/field of the closure object 5650 // that represents the '*this' capture. 5651 if (!HandleLValueMember(Info, E, Result, 5652 Info.CurrentCall->LambdaThisCaptureField)) 5653 return false; 5654 // If we captured '*this' by reference, replace the field with its referent. 5655 if (Info.CurrentCall->LambdaThisCaptureField->getType() 5656 ->isPointerType()) { 5657 APValue RVal; 5658 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 5659 RVal)) 5660 return false; 5661 5662 Result.setFrom(Info.Ctx, RVal); 5663 } 5664 } 5665 return true; 5666 } 5667 5668 // FIXME: Missing: @protocol, @selector 5669 }; 5670 } // end anonymous namespace 5671 5672 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 5673 bool InvalidBaseOK) { 5674 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 5675 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5676 } 5677 5678 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 5679 if (E->getOpcode() != BO_Add && 5680 E->getOpcode() != BO_Sub) 5681 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5682 5683 const Expr *PExp = E->getLHS(); 5684 const Expr *IExp = E->getRHS(); 5685 if (IExp->getType()->isPointerType()) 5686 std::swap(PExp, IExp); 5687 5688 bool EvalPtrOK = evaluatePointer(PExp, Result); 5689 if (!EvalPtrOK && !Info.noteFailure()) 5690 return false; 5691 5692 llvm::APSInt Offset; 5693 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 5694 return false; 5695 5696 if (E->getOpcode() == BO_Sub) 5697 negateAsSigned(Offset); 5698 5699 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 5700 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 5701 } 5702 5703 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5704 return evaluateLValue(E->getSubExpr(), Result); 5705 } 5706 5707 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { 5708 const Expr* SubExpr = E->getSubExpr(); 5709 5710 switch (E->getCastKind()) { 5711 default: 5712 break; 5713 5714 case CK_BitCast: 5715 case CK_CPointerToObjCPointerCast: 5716 case CK_BlockPointerToObjCPointerCast: 5717 case CK_AnyPointerToBlockPointerCast: 5718 case CK_AddressSpaceConversion: 5719 if (!Visit(SubExpr)) 5720 return false; 5721 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 5722 // permitted in constant expressions in C++11. Bitcasts from cv void* are 5723 // also static_casts, but we disallow them as a resolution to DR1312. 5724 if (!E->getType()->isVoidPointerType()) { 5725 Result.Designator.setInvalid(); 5726 if (SubExpr->getType()->isVoidPointerType()) 5727 CCEDiag(E, diag::note_constexpr_invalid_cast) 5728 << 3 << SubExpr->getType(); 5729 else 5730 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5731 } 5732 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 5733 ZeroInitialization(E); 5734 return true; 5735 5736 case CK_DerivedToBase: 5737 case CK_UncheckedDerivedToBase: 5738 if (!evaluatePointer(E->getSubExpr(), Result)) 5739 return false; 5740 if (!Result.Base && Result.Offset.isZero()) 5741 return true; 5742 5743 // Now figure out the necessary offset to add to the base LV to get from 5744 // the derived class to the base class. 5745 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 5746 castAs<PointerType>()->getPointeeType(), 5747 Result); 5748 5749 case CK_BaseToDerived: 5750 if (!Visit(E->getSubExpr())) 5751 return false; 5752 if (!Result.Base && Result.Offset.isZero()) 5753 return true; 5754 return HandleBaseToDerivedCast(Info, E, Result); 5755 5756 case CK_NullToPointer: 5757 VisitIgnoredValue(E->getSubExpr()); 5758 return ZeroInitialization(E); 5759 5760 case CK_IntegralToPointer: { 5761 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5762 5763 APValue Value; 5764 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 5765 break; 5766 5767 if (Value.isInt()) { 5768 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 5769 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 5770 Result.Base = (Expr*)nullptr; 5771 Result.InvalidBase = false; 5772 Result.Offset = CharUnits::fromQuantity(N); 5773 Result.CallIndex = 0; 5774 Result.Designator.setInvalid(); 5775 Result.IsNullPtr = false; 5776 return true; 5777 } else { 5778 // Cast is of an lvalue, no need to change value. 5779 Result.setFrom(Info.Ctx, Value); 5780 return true; 5781 } 5782 } 5783 5784 case CK_ArrayToPointerDecay: { 5785 if (SubExpr->isGLValue()) { 5786 if (!evaluateLValue(SubExpr, Result)) 5787 return false; 5788 } else { 5789 Result.set(SubExpr, Info.CurrentCall->Index); 5790 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false), 5791 Info, Result, SubExpr)) 5792 return false; 5793 } 5794 // The result is a pointer to the first element of the array. 5795 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 5796 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5797 Result.addArray(Info, E, CAT); 5798 else 5799 Result.addUnsizedArray(Info, E, AT->getElementType()); 5800 return true; 5801 } 5802 5803 case CK_FunctionToPointerDecay: 5804 return evaluateLValue(SubExpr, Result); 5805 5806 case CK_LValueToRValue: { 5807 LValue LVal; 5808 if (!evaluateLValue(E->getSubExpr(), LVal)) 5809 return false; 5810 5811 APValue RVal; 5812 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5813 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5814 LVal, RVal)) 5815 return InvalidBaseOK && 5816 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 5817 return Success(RVal, E); 5818 } 5819 } 5820 5821 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5822 } 5823 5824 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) { 5825 // C++ [expr.alignof]p3: 5826 // When alignof is applied to a reference type, the result is the 5827 // alignment of the referenced type. 5828 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 5829 T = Ref->getPointeeType(); 5830 5831 // __alignof is defined to return the preferred alignment. 5832 if (T.getQualifiers().hasUnaligned()) 5833 return CharUnits::One(); 5834 return Info.Ctx.toCharUnitsFromBits( 5835 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 5836 } 5837 5838 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) { 5839 E = E->IgnoreParens(); 5840 5841 // The kinds of expressions that we have special-case logic here for 5842 // should be kept up to date with the special checks for those 5843 // expressions in Sema. 5844 5845 // alignof decl is always accepted, even if it doesn't make sense: we default 5846 // to 1 in those cases. 5847 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5848 return Info.Ctx.getDeclAlign(DRE->getDecl(), 5849 /*RefAsPointee*/true); 5850 5851 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 5852 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 5853 /*RefAsPointee*/true); 5854 5855 return GetAlignOfType(Info, E->getType()); 5856 } 5857 5858 // To be clear: this happily visits unsupported builtins. Better name welcomed. 5859 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 5860 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 5861 return true; 5862 5863 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 5864 return false; 5865 5866 Result.setInvalid(E); 5867 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 5868 Result.addUnsizedArray(Info, E, PointeeTy); 5869 return true; 5870 } 5871 5872 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 5873 if (IsStringLiteralCall(E)) 5874 return Success(E); 5875 5876 if (unsigned BuiltinOp = E->getBuiltinCallee()) 5877 return VisitBuiltinCallExpr(E, BuiltinOp); 5878 5879 return visitNonBuiltinCallExpr(E); 5880 } 5881 5882 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 5883 unsigned BuiltinOp) { 5884 switch (BuiltinOp) { 5885 case Builtin::BI__builtin_addressof: 5886 return evaluateLValue(E->getArg(0), Result); 5887 case Builtin::BI__builtin_assume_aligned: { 5888 // We need to be very careful here because: if the pointer does not have the 5889 // asserted alignment, then the behavior is undefined, and undefined 5890 // behavior is non-constant. 5891 if (!evaluatePointer(E->getArg(0), Result)) 5892 return false; 5893 5894 LValue OffsetResult(Result); 5895 APSInt Alignment; 5896 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 5897 return false; 5898 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 5899 5900 if (E->getNumArgs() > 2) { 5901 APSInt Offset; 5902 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 5903 return false; 5904 5905 int64_t AdditionalOffset = -Offset.getZExtValue(); 5906 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 5907 } 5908 5909 // If there is a base object, then it must have the correct alignment. 5910 if (OffsetResult.Base) { 5911 CharUnits BaseAlignment; 5912 if (const ValueDecl *VD = 5913 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 5914 BaseAlignment = Info.Ctx.getDeclAlign(VD); 5915 } else { 5916 BaseAlignment = 5917 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>()); 5918 } 5919 5920 if (BaseAlignment < Align) { 5921 Result.Designator.setInvalid(); 5922 // FIXME: Add support to Diagnostic for long / long long. 5923 CCEDiag(E->getArg(0), 5924 diag::note_constexpr_baa_insufficient_alignment) << 0 5925 << (unsigned)BaseAlignment.getQuantity() 5926 << (unsigned)Align.getQuantity(); 5927 return false; 5928 } 5929 } 5930 5931 // The offset must also have the correct alignment. 5932 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 5933 Result.Designator.setInvalid(); 5934 5935 (OffsetResult.Base 5936 ? CCEDiag(E->getArg(0), 5937 diag::note_constexpr_baa_insufficient_alignment) << 1 5938 : CCEDiag(E->getArg(0), 5939 diag::note_constexpr_baa_value_insufficient_alignment)) 5940 << (int)OffsetResult.Offset.getQuantity() 5941 << (unsigned)Align.getQuantity(); 5942 return false; 5943 } 5944 5945 return true; 5946 } 5947 5948 case Builtin::BIstrchr: 5949 case Builtin::BIwcschr: 5950 case Builtin::BImemchr: 5951 case Builtin::BIwmemchr: 5952 if (Info.getLangOpts().CPlusPlus11) 5953 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 5954 << /*isConstexpr*/0 << /*isConstructor*/0 5955 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 5956 else 5957 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 5958 LLVM_FALLTHROUGH; 5959 case Builtin::BI__builtin_strchr: 5960 case Builtin::BI__builtin_wcschr: 5961 case Builtin::BI__builtin_memchr: 5962 case Builtin::BI__builtin_char_memchr: 5963 case Builtin::BI__builtin_wmemchr: { 5964 if (!Visit(E->getArg(0))) 5965 return false; 5966 APSInt Desired; 5967 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 5968 return false; 5969 uint64_t MaxLength = uint64_t(-1); 5970 if (BuiltinOp != Builtin::BIstrchr && 5971 BuiltinOp != Builtin::BIwcschr && 5972 BuiltinOp != Builtin::BI__builtin_strchr && 5973 BuiltinOp != Builtin::BI__builtin_wcschr) { 5974 APSInt N; 5975 if (!EvaluateInteger(E->getArg(2), N, Info)) 5976 return false; 5977 MaxLength = N.getExtValue(); 5978 } 5979 5980 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 5981 5982 // Figure out what value we're actually looking for (after converting to 5983 // the corresponding unsigned type if necessary). 5984 uint64_t DesiredVal; 5985 bool StopAtNull = false; 5986 switch (BuiltinOp) { 5987 case Builtin::BIstrchr: 5988 case Builtin::BI__builtin_strchr: 5989 // strchr compares directly to the passed integer, and therefore 5990 // always fails if given an int that is not a char. 5991 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 5992 E->getArg(1)->getType(), 5993 Desired), 5994 Desired)) 5995 return ZeroInitialization(E); 5996 StopAtNull = true; 5997 LLVM_FALLTHROUGH; 5998 case Builtin::BImemchr: 5999 case Builtin::BI__builtin_memchr: 6000 case Builtin::BI__builtin_char_memchr: 6001 // memchr compares by converting both sides to unsigned char. That's also 6002 // correct for strchr if we get this far (to cope with plain char being 6003 // unsigned in the strchr case). 6004 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 6005 break; 6006 6007 case Builtin::BIwcschr: 6008 case Builtin::BI__builtin_wcschr: 6009 StopAtNull = true; 6010 LLVM_FALLTHROUGH; 6011 case Builtin::BIwmemchr: 6012 case Builtin::BI__builtin_wmemchr: 6013 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 6014 DesiredVal = Desired.getZExtValue(); 6015 break; 6016 } 6017 6018 for (; MaxLength; --MaxLength) { 6019 APValue Char; 6020 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 6021 !Char.isInt()) 6022 return false; 6023 if (Char.getInt().getZExtValue() == DesiredVal) 6024 return true; 6025 if (StopAtNull && !Char.getInt()) 6026 break; 6027 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 6028 return false; 6029 } 6030 // Not found: return nullptr. 6031 return ZeroInitialization(E); 6032 } 6033 6034 default: 6035 return visitNonBuiltinCallExpr(E); 6036 } 6037 } 6038 6039 //===----------------------------------------------------------------------===// 6040 // Member Pointer Evaluation 6041 //===----------------------------------------------------------------------===// 6042 6043 namespace { 6044 class MemberPointerExprEvaluator 6045 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 6046 MemberPtr &Result; 6047 6048 bool Success(const ValueDecl *D) { 6049 Result = MemberPtr(D); 6050 return true; 6051 } 6052 public: 6053 6054 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 6055 : ExprEvaluatorBaseTy(Info), Result(Result) {} 6056 6057 bool Success(const APValue &V, const Expr *E) { 6058 Result.setFrom(V); 6059 return true; 6060 } 6061 bool ZeroInitialization(const Expr *E) { 6062 return Success((const ValueDecl*)nullptr); 6063 } 6064 6065 bool VisitCastExpr(const CastExpr *E); 6066 bool VisitUnaryAddrOf(const UnaryOperator *E); 6067 }; 6068 } // end anonymous namespace 6069 6070 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 6071 EvalInfo &Info) { 6072 assert(E->isRValue() && E->getType()->isMemberPointerType()); 6073 return MemberPointerExprEvaluator(Info, Result).Visit(E); 6074 } 6075 6076 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 6077 switch (E->getCastKind()) { 6078 default: 6079 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6080 6081 case CK_NullToMemberPointer: 6082 VisitIgnoredValue(E->getSubExpr()); 6083 return ZeroInitialization(E); 6084 6085 case CK_BaseToDerivedMemberPointer: { 6086 if (!Visit(E->getSubExpr())) 6087 return false; 6088 if (E->path_empty()) 6089 return true; 6090 // Base-to-derived member pointer casts store the path in derived-to-base 6091 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 6092 // the wrong end of the derived->base arc, so stagger the path by one class. 6093 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 6094 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 6095 PathI != PathE; ++PathI) { 6096 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6097 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 6098 if (!Result.castToDerived(Derived)) 6099 return Error(E); 6100 } 6101 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 6102 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 6103 return Error(E); 6104 return true; 6105 } 6106 6107 case CK_DerivedToBaseMemberPointer: 6108 if (!Visit(E->getSubExpr())) 6109 return false; 6110 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6111 PathE = E->path_end(); PathI != PathE; ++PathI) { 6112 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6113 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6114 if (!Result.castToBase(Base)) 6115 return Error(E); 6116 } 6117 return true; 6118 } 6119 } 6120 6121 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 6122 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 6123 // member can be formed. 6124 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 6125 } 6126 6127 //===----------------------------------------------------------------------===// 6128 // Record Evaluation 6129 //===----------------------------------------------------------------------===// 6130 6131 namespace { 6132 class RecordExprEvaluator 6133 : public ExprEvaluatorBase<RecordExprEvaluator> { 6134 const LValue &This; 6135 APValue &Result; 6136 public: 6137 6138 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 6139 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 6140 6141 bool Success(const APValue &V, const Expr *E) { 6142 Result = V; 6143 return true; 6144 } 6145 bool ZeroInitialization(const Expr *E) { 6146 return ZeroInitialization(E, E->getType()); 6147 } 6148 bool ZeroInitialization(const Expr *E, QualType T); 6149 6150 bool VisitCallExpr(const CallExpr *E) { 6151 return handleCallExpr(E, Result, &This); 6152 } 6153 bool VisitCastExpr(const CastExpr *E); 6154 bool VisitInitListExpr(const InitListExpr *E); 6155 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6156 return VisitCXXConstructExpr(E, E->getType()); 6157 } 6158 bool VisitLambdaExpr(const LambdaExpr *E); 6159 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 6160 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 6161 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 6162 }; 6163 } 6164 6165 /// Perform zero-initialization on an object of non-union class type. 6166 /// C++11 [dcl.init]p5: 6167 /// To zero-initialize an object or reference of type T means: 6168 /// [...] 6169 /// -- if T is a (possibly cv-qualified) non-union class type, 6170 /// each non-static data member and each base-class subobject is 6171 /// zero-initialized 6172 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 6173 const RecordDecl *RD, 6174 const LValue &This, APValue &Result) { 6175 assert(!RD->isUnion() && "Expected non-union class type"); 6176 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 6177 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 6178 std::distance(RD->field_begin(), RD->field_end())); 6179 6180 if (RD->isInvalidDecl()) return false; 6181 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6182 6183 if (CD) { 6184 unsigned Index = 0; 6185 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 6186 End = CD->bases_end(); I != End; ++I, ++Index) { 6187 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 6188 LValue Subobject = This; 6189 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 6190 return false; 6191 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 6192 Result.getStructBase(Index))) 6193 return false; 6194 } 6195 } 6196 6197 for (const auto *I : RD->fields()) { 6198 // -- if T is a reference type, no initialization is performed. 6199 if (I->getType()->isReferenceType()) 6200 continue; 6201 6202 LValue Subobject = This; 6203 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 6204 return false; 6205 6206 ImplicitValueInitExpr VIE(I->getType()); 6207 if (!EvaluateInPlace( 6208 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 6209 return false; 6210 } 6211 6212 return true; 6213 } 6214 6215 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 6216 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 6217 if (RD->isInvalidDecl()) return false; 6218 if (RD->isUnion()) { 6219 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 6220 // object's first non-static named data member is zero-initialized 6221 RecordDecl::field_iterator I = RD->field_begin(); 6222 if (I == RD->field_end()) { 6223 Result = APValue((const FieldDecl*)nullptr); 6224 return true; 6225 } 6226 6227 LValue Subobject = This; 6228 if (!HandleLValueMember(Info, E, Subobject, *I)) 6229 return false; 6230 Result = APValue(*I); 6231 ImplicitValueInitExpr VIE(I->getType()); 6232 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 6233 } 6234 6235 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 6236 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 6237 return false; 6238 } 6239 6240 return HandleClassZeroInitialization(Info, E, RD, This, Result); 6241 } 6242 6243 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 6244 switch (E->getCastKind()) { 6245 default: 6246 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6247 6248 case CK_ConstructorConversion: 6249 return Visit(E->getSubExpr()); 6250 6251 case CK_DerivedToBase: 6252 case CK_UncheckedDerivedToBase: { 6253 APValue DerivedObject; 6254 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 6255 return false; 6256 if (!DerivedObject.isStruct()) 6257 return Error(E->getSubExpr()); 6258 6259 // Derived-to-base rvalue conversion: just slice off the derived part. 6260 APValue *Value = &DerivedObject; 6261 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 6262 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6263 PathE = E->path_end(); PathI != PathE; ++PathI) { 6264 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 6265 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6266 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 6267 RD = Base; 6268 } 6269 Result = *Value; 6270 return true; 6271 } 6272 } 6273 } 6274 6275 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6276 if (E->isTransparent()) 6277 return Visit(E->getInit(0)); 6278 6279 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 6280 if (RD->isInvalidDecl()) return false; 6281 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6282 6283 if (RD->isUnion()) { 6284 const FieldDecl *Field = E->getInitializedFieldInUnion(); 6285 Result = APValue(Field); 6286 if (!Field) 6287 return true; 6288 6289 // If the initializer list for a union does not contain any elements, the 6290 // first element of the union is value-initialized. 6291 // FIXME: The element should be initialized from an initializer list. 6292 // Is this difference ever observable for initializer lists which 6293 // we don't build? 6294 ImplicitValueInitExpr VIE(Field->getType()); 6295 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 6296 6297 LValue Subobject = This; 6298 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 6299 return false; 6300 6301 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6302 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6303 isa<CXXDefaultInitExpr>(InitExpr)); 6304 6305 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 6306 } 6307 6308 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 6309 if (Result.isUninit()) 6310 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 6311 std::distance(RD->field_begin(), RD->field_end())); 6312 unsigned ElementNo = 0; 6313 bool Success = true; 6314 6315 // Initialize base classes. 6316 if (CXXRD) { 6317 for (const auto &Base : CXXRD->bases()) { 6318 assert(ElementNo < E->getNumInits() && "missing init for base class"); 6319 const Expr *Init = E->getInit(ElementNo); 6320 6321 LValue Subobject = This; 6322 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 6323 return false; 6324 6325 APValue &FieldVal = Result.getStructBase(ElementNo); 6326 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 6327 if (!Info.noteFailure()) 6328 return false; 6329 Success = false; 6330 } 6331 ++ElementNo; 6332 } 6333 } 6334 6335 // Initialize members. 6336 for (const auto *Field : RD->fields()) { 6337 // Anonymous bit-fields are not considered members of the class for 6338 // purposes of aggregate initialization. 6339 if (Field->isUnnamedBitfield()) 6340 continue; 6341 6342 LValue Subobject = This; 6343 6344 bool HaveInit = ElementNo < E->getNumInits(); 6345 6346 // FIXME: Diagnostics here should point to the end of the initializer 6347 // list, not the start. 6348 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 6349 Subobject, Field, &Layout)) 6350 return false; 6351 6352 // Perform an implicit value-initialization for members beyond the end of 6353 // the initializer list. 6354 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 6355 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 6356 6357 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6358 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6359 isa<CXXDefaultInitExpr>(Init)); 6360 6361 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6362 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 6363 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 6364 FieldVal, Field))) { 6365 if (!Info.noteFailure()) 6366 return false; 6367 Success = false; 6368 } 6369 } 6370 6371 return Success; 6372 } 6373 6374 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6375 QualType T) { 6376 // Note that E's type is not necessarily the type of our class here; we might 6377 // be initializing an array element instead. 6378 const CXXConstructorDecl *FD = E->getConstructor(); 6379 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 6380 6381 bool ZeroInit = E->requiresZeroInitialization(); 6382 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 6383 // If we've already performed zero-initialization, we're already done. 6384 if (!Result.isUninit()) 6385 return true; 6386 6387 // We can get here in two different ways: 6388 // 1) We're performing value-initialization, and should zero-initialize 6389 // the object, or 6390 // 2) We're performing default-initialization of an object with a trivial 6391 // constexpr default constructor, in which case we should start the 6392 // lifetimes of all the base subobjects (there can be no data member 6393 // subobjects in this case) per [basic.life]p1. 6394 // Either way, ZeroInitialization is appropriate. 6395 return ZeroInitialization(E, T); 6396 } 6397 6398 const FunctionDecl *Definition = nullptr; 6399 auto Body = FD->getBody(Definition); 6400 6401 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6402 return false; 6403 6404 // Avoid materializing a temporary for an elidable copy/move constructor. 6405 if (E->isElidable() && !ZeroInit) 6406 if (const MaterializeTemporaryExpr *ME 6407 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 6408 return Visit(ME->GetTemporaryExpr()); 6409 6410 if (ZeroInit && !ZeroInitialization(E, T)) 6411 return false; 6412 6413 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6414 return HandleConstructorCall(E, This, Args, 6415 cast<CXXConstructorDecl>(Definition), Info, 6416 Result); 6417 } 6418 6419 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 6420 const CXXInheritedCtorInitExpr *E) { 6421 if (!Info.CurrentCall) { 6422 assert(Info.checkingPotentialConstantExpression()); 6423 return false; 6424 } 6425 6426 const CXXConstructorDecl *FD = E->getConstructor(); 6427 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 6428 return false; 6429 6430 const FunctionDecl *Definition = nullptr; 6431 auto Body = FD->getBody(Definition); 6432 6433 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6434 return false; 6435 6436 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 6437 cast<CXXConstructorDecl>(Definition), Info, 6438 Result); 6439 } 6440 6441 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 6442 const CXXStdInitializerListExpr *E) { 6443 const ConstantArrayType *ArrayType = 6444 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 6445 6446 LValue Array; 6447 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 6448 return false; 6449 6450 // Get a pointer to the first element of the array. 6451 Array.addArray(Info, E, ArrayType); 6452 6453 // FIXME: Perform the checks on the field types in SemaInit. 6454 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 6455 RecordDecl::field_iterator Field = Record->field_begin(); 6456 if (Field == Record->field_end()) 6457 return Error(E); 6458 6459 // Start pointer. 6460 if (!Field->getType()->isPointerType() || 6461 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6462 ArrayType->getElementType())) 6463 return Error(E); 6464 6465 // FIXME: What if the initializer_list type has base classes, etc? 6466 Result = APValue(APValue::UninitStruct(), 0, 2); 6467 Array.moveInto(Result.getStructField(0)); 6468 6469 if (++Field == Record->field_end()) 6470 return Error(E); 6471 6472 if (Field->getType()->isPointerType() && 6473 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6474 ArrayType->getElementType())) { 6475 // End pointer. 6476 if (!HandleLValueArrayAdjustment(Info, E, Array, 6477 ArrayType->getElementType(), 6478 ArrayType->getSize().getZExtValue())) 6479 return false; 6480 Array.moveInto(Result.getStructField(1)); 6481 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 6482 // Length. 6483 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 6484 else 6485 return Error(E); 6486 6487 if (++Field != Record->field_end()) 6488 return Error(E); 6489 6490 return true; 6491 } 6492 6493 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 6494 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 6495 if (ClosureClass->isInvalidDecl()) return false; 6496 6497 if (Info.checkingPotentialConstantExpression()) return true; 6498 6499 const size_t NumFields = 6500 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 6501 6502 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 6503 E->capture_init_end()) && 6504 "The number of lambda capture initializers should equal the number of " 6505 "fields within the closure type"); 6506 6507 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 6508 // Iterate through all the lambda's closure object's fields and initialize 6509 // them. 6510 auto *CaptureInitIt = E->capture_init_begin(); 6511 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 6512 bool Success = true; 6513 for (const auto *Field : ClosureClass->fields()) { 6514 assert(CaptureInitIt != E->capture_init_end()); 6515 // Get the initializer for this field 6516 Expr *const CurFieldInit = *CaptureInitIt++; 6517 6518 // If there is no initializer, either this is a VLA or an error has 6519 // occurred. 6520 if (!CurFieldInit) 6521 return Error(E); 6522 6523 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6524 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 6525 if (!Info.keepEvaluatingAfterFailure()) 6526 return false; 6527 Success = false; 6528 } 6529 ++CaptureIt; 6530 } 6531 return Success; 6532 } 6533 6534 static bool EvaluateRecord(const Expr *E, const LValue &This, 6535 APValue &Result, EvalInfo &Info) { 6536 assert(E->isRValue() && E->getType()->isRecordType() && 6537 "can't evaluate expression as a record rvalue"); 6538 return RecordExprEvaluator(Info, This, Result).Visit(E); 6539 } 6540 6541 //===----------------------------------------------------------------------===// 6542 // Temporary Evaluation 6543 // 6544 // Temporaries are represented in the AST as rvalues, but generally behave like 6545 // lvalues. The full-object of which the temporary is a subobject is implicitly 6546 // materialized so that a reference can bind to it. 6547 //===----------------------------------------------------------------------===// 6548 namespace { 6549 class TemporaryExprEvaluator 6550 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 6551 public: 6552 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 6553 LValueExprEvaluatorBaseTy(Info, Result, false) {} 6554 6555 /// Visit an expression which constructs the value of this temporary. 6556 bool VisitConstructExpr(const Expr *E) { 6557 Result.set(E, Info.CurrentCall->Index); 6558 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false), 6559 Info, Result, E); 6560 } 6561 6562 bool VisitCastExpr(const CastExpr *E) { 6563 switch (E->getCastKind()) { 6564 default: 6565 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6566 6567 case CK_ConstructorConversion: 6568 return VisitConstructExpr(E->getSubExpr()); 6569 } 6570 } 6571 bool VisitInitListExpr(const InitListExpr *E) { 6572 return VisitConstructExpr(E); 6573 } 6574 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6575 return VisitConstructExpr(E); 6576 } 6577 bool VisitCallExpr(const CallExpr *E) { 6578 return VisitConstructExpr(E); 6579 } 6580 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 6581 return VisitConstructExpr(E); 6582 } 6583 bool VisitLambdaExpr(const LambdaExpr *E) { 6584 return VisitConstructExpr(E); 6585 } 6586 }; 6587 } // end anonymous namespace 6588 6589 /// Evaluate an expression of record type as a temporary. 6590 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 6591 assert(E->isRValue() && E->getType()->isRecordType()); 6592 return TemporaryExprEvaluator(Info, Result).Visit(E); 6593 } 6594 6595 //===----------------------------------------------------------------------===// 6596 // Vector Evaluation 6597 //===----------------------------------------------------------------------===// 6598 6599 namespace { 6600 class VectorExprEvaluator 6601 : public ExprEvaluatorBase<VectorExprEvaluator> { 6602 APValue &Result; 6603 public: 6604 6605 VectorExprEvaluator(EvalInfo &info, APValue &Result) 6606 : ExprEvaluatorBaseTy(info), Result(Result) {} 6607 6608 bool Success(ArrayRef<APValue> V, const Expr *E) { 6609 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 6610 // FIXME: remove this APValue copy. 6611 Result = APValue(V.data(), V.size()); 6612 return true; 6613 } 6614 bool Success(const APValue &V, const Expr *E) { 6615 assert(V.isVector()); 6616 Result = V; 6617 return true; 6618 } 6619 bool ZeroInitialization(const Expr *E); 6620 6621 bool VisitUnaryReal(const UnaryOperator *E) 6622 { return Visit(E->getSubExpr()); } 6623 bool VisitCastExpr(const CastExpr* E); 6624 bool VisitInitListExpr(const InitListExpr *E); 6625 bool VisitUnaryImag(const UnaryOperator *E); 6626 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 6627 // binary comparisons, binary and/or/xor, 6628 // shufflevector, ExtVectorElementExpr 6629 }; 6630 } // end anonymous namespace 6631 6632 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 6633 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 6634 return VectorExprEvaluator(Info, Result).Visit(E); 6635 } 6636 6637 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 6638 const VectorType *VTy = E->getType()->castAs<VectorType>(); 6639 unsigned NElts = VTy->getNumElements(); 6640 6641 const Expr *SE = E->getSubExpr(); 6642 QualType SETy = SE->getType(); 6643 6644 switch (E->getCastKind()) { 6645 case CK_VectorSplat: { 6646 APValue Val = APValue(); 6647 if (SETy->isIntegerType()) { 6648 APSInt IntResult; 6649 if (!EvaluateInteger(SE, IntResult, Info)) 6650 return false; 6651 Val = APValue(std::move(IntResult)); 6652 } else if (SETy->isRealFloatingType()) { 6653 APFloat FloatResult(0.0); 6654 if (!EvaluateFloat(SE, FloatResult, Info)) 6655 return false; 6656 Val = APValue(std::move(FloatResult)); 6657 } else { 6658 return Error(E); 6659 } 6660 6661 // Splat and create vector APValue. 6662 SmallVector<APValue, 4> Elts(NElts, Val); 6663 return Success(Elts, E); 6664 } 6665 case CK_BitCast: { 6666 // Evaluate the operand into an APInt we can extract from. 6667 llvm::APInt SValInt; 6668 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 6669 return false; 6670 // Extract the elements 6671 QualType EltTy = VTy->getElementType(); 6672 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 6673 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 6674 SmallVector<APValue, 4> Elts; 6675 if (EltTy->isRealFloatingType()) { 6676 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 6677 unsigned FloatEltSize = EltSize; 6678 if (&Sem == &APFloat::x87DoubleExtended()) 6679 FloatEltSize = 80; 6680 for (unsigned i = 0; i < NElts; i++) { 6681 llvm::APInt Elt; 6682 if (BigEndian) 6683 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 6684 else 6685 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 6686 Elts.push_back(APValue(APFloat(Sem, Elt))); 6687 } 6688 } else if (EltTy->isIntegerType()) { 6689 for (unsigned i = 0; i < NElts; i++) { 6690 llvm::APInt Elt; 6691 if (BigEndian) 6692 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 6693 else 6694 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 6695 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 6696 } 6697 } else { 6698 return Error(E); 6699 } 6700 return Success(Elts, E); 6701 } 6702 default: 6703 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6704 } 6705 } 6706 6707 bool 6708 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6709 const VectorType *VT = E->getType()->castAs<VectorType>(); 6710 unsigned NumInits = E->getNumInits(); 6711 unsigned NumElements = VT->getNumElements(); 6712 6713 QualType EltTy = VT->getElementType(); 6714 SmallVector<APValue, 4> Elements; 6715 6716 // The number of initializers can be less than the number of 6717 // vector elements. For OpenCL, this can be due to nested vector 6718 // initialization. For GCC compatibility, missing trailing elements 6719 // should be initialized with zeroes. 6720 unsigned CountInits = 0, CountElts = 0; 6721 while (CountElts < NumElements) { 6722 // Handle nested vector initialization. 6723 if (CountInits < NumInits 6724 && E->getInit(CountInits)->getType()->isVectorType()) { 6725 APValue v; 6726 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 6727 return Error(E); 6728 unsigned vlen = v.getVectorLength(); 6729 for (unsigned j = 0; j < vlen; j++) 6730 Elements.push_back(v.getVectorElt(j)); 6731 CountElts += vlen; 6732 } else if (EltTy->isIntegerType()) { 6733 llvm::APSInt sInt(32); 6734 if (CountInits < NumInits) { 6735 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 6736 return false; 6737 } else // trailing integer zero. 6738 sInt = Info.Ctx.MakeIntValue(0, EltTy); 6739 Elements.push_back(APValue(sInt)); 6740 CountElts++; 6741 } else { 6742 llvm::APFloat f(0.0); 6743 if (CountInits < NumInits) { 6744 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 6745 return false; 6746 } else // trailing float zero. 6747 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 6748 Elements.push_back(APValue(f)); 6749 CountElts++; 6750 } 6751 CountInits++; 6752 } 6753 return Success(Elements, E); 6754 } 6755 6756 bool 6757 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 6758 const VectorType *VT = E->getType()->getAs<VectorType>(); 6759 QualType EltTy = VT->getElementType(); 6760 APValue ZeroElement; 6761 if (EltTy->isIntegerType()) 6762 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 6763 else 6764 ZeroElement = 6765 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 6766 6767 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 6768 return Success(Elements, E); 6769 } 6770 6771 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 6772 VisitIgnoredValue(E->getSubExpr()); 6773 return ZeroInitialization(E); 6774 } 6775 6776 //===----------------------------------------------------------------------===// 6777 // Array Evaluation 6778 //===----------------------------------------------------------------------===// 6779 6780 namespace { 6781 class ArrayExprEvaluator 6782 : public ExprEvaluatorBase<ArrayExprEvaluator> { 6783 const LValue &This; 6784 APValue &Result; 6785 public: 6786 6787 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 6788 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 6789 6790 bool Success(const APValue &V, const Expr *E) { 6791 assert((V.isArray() || V.isLValue()) && 6792 "expected array or string literal"); 6793 Result = V; 6794 return true; 6795 } 6796 6797 bool ZeroInitialization(const Expr *E) { 6798 const ConstantArrayType *CAT = 6799 Info.Ctx.getAsConstantArrayType(E->getType()); 6800 if (!CAT) 6801 return Error(E); 6802 6803 Result = APValue(APValue::UninitArray(), 0, 6804 CAT->getSize().getZExtValue()); 6805 if (!Result.hasArrayFiller()) return true; 6806 6807 // Zero-initialize all elements. 6808 LValue Subobject = This; 6809 Subobject.addArray(Info, E, CAT); 6810 ImplicitValueInitExpr VIE(CAT->getElementType()); 6811 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 6812 } 6813 6814 bool VisitCallExpr(const CallExpr *E) { 6815 return handleCallExpr(E, Result, &This); 6816 } 6817 bool VisitInitListExpr(const InitListExpr *E); 6818 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 6819 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 6820 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 6821 const LValue &Subobject, 6822 APValue *Value, QualType Type); 6823 }; 6824 } // end anonymous namespace 6825 6826 static bool EvaluateArray(const Expr *E, const LValue &This, 6827 APValue &Result, EvalInfo &Info) { 6828 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 6829 return ArrayExprEvaluator(Info, This, Result).Visit(E); 6830 } 6831 6832 // Return true iff the given array filler may depend on the element index. 6833 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 6834 // For now, just whitelist non-class value-initialization and initialization 6835 // lists comprised of them. 6836 if (isa<ImplicitValueInitExpr>(FillerExpr)) 6837 return false; 6838 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 6839 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 6840 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 6841 return true; 6842 } 6843 return false; 6844 } 6845 return true; 6846 } 6847 6848 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6849 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 6850 if (!CAT) 6851 return Error(E); 6852 6853 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 6854 // an appropriately-typed string literal enclosed in braces. 6855 if (E->isStringLiteralInit()) { 6856 LValue LV; 6857 if (!EvaluateLValue(E->getInit(0), LV, Info)) 6858 return false; 6859 APValue Val; 6860 LV.moveInto(Val); 6861 return Success(Val, E); 6862 } 6863 6864 bool Success = true; 6865 6866 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 6867 "zero-initialized array shouldn't have any initialized elts"); 6868 APValue Filler; 6869 if (Result.isArray() && Result.hasArrayFiller()) 6870 Filler = Result.getArrayFiller(); 6871 6872 unsigned NumEltsToInit = E->getNumInits(); 6873 unsigned NumElts = CAT->getSize().getZExtValue(); 6874 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 6875 6876 // If the initializer might depend on the array index, run it for each 6877 // array element. 6878 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 6879 NumEltsToInit = NumElts; 6880 6881 DEBUG(llvm::dbgs() << "The number of elements to initialize: " << 6882 NumEltsToInit << ".\n"); 6883 6884 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 6885 6886 // If the array was previously zero-initialized, preserve the 6887 // zero-initialized values. 6888 if (!Filler.isUninit()) { 6889 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 6890 Result.getArrayInitializedElt(I) = Filler; 6891 if (Result.hasArrayFiller()) 6892 Result.getArrayFiller() = Filler; 6893 } 6894 6895 LValue Subobject = This; 6896 Subobject.addArray(Info, E, CAT); 6897 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 6898 const Expr *Init = 6899 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 6900 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 6901 Info, Subobject, Init) || 6902 !HandleLValueArrayAdjustment(Info, Init, Subobject, 6903 CAT->getElementType(), 1)) { 6904 if (!Info.noteFailure()) 6905 return false; 6906 Success = false; 6907 } 6908 } 6909 6910 if (!Result.hasArrayFiller()) 6911 return Success; 6912 6913 // If we get here, we have a trivial filler, which we can just evaluate 6914 // once and splat over the rest of the array elements. 6915 assert(FillerExpr && "no array filler for incomplete init list"); 6916 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 6917 FillerExpr) && Success; 6918 } 6919 6920 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 6921 if (E->getCommonExpr() && 6922 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 6923 Info, E->getCommonExpr()->getSourceExpr())) 6924 return false; 6925 6926 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 6927 6928 uint64_t Elements = CAT->getSize().getZExtValue(); 6929 Result = APValue(APValue::UninitArray(), Elements, Elements); 6930 6931 LValue Subobject = This; 6932 Subobject.addArray(Info, E, CAT); 6933 6934 bool Success = true; 6935 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 6936 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 6937 Info, Subobject, E->getSubExpr()) || 6938 !HandleLValueArrayAdjustment(Info, E, Subobject, 6939 CAT->getElementType(), 1)) { 6940 if (!Info.noteFailure()) 6941 return false; 6942 Success = false; 6943 } 6944 } 6945 6946 return Success; 6947 } 6948 6949 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 6950 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 6951 } 6952 6953 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6954 const LValue &Subobject, 6955 APValue *Value, 6956 QualType Type) { 6957 bool HadZeroInit = !Value->isUninit(); 6958 6959 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 6960 unsigned N = CAT->getSize().getZExtValue(); 6961 6962 // Preserve the array filler if we had prior zero-initialization. 6963 APValue Filler = 6964 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 6965 : APValue(); 6966 6967 *Value = APValue(APValue::UninitArray(), N, N); 6968 6969 if (HadZeroInit) 6970 for (unsigned I = 0; I != N; ++I) 6971 Value->getArrayInitializedElt(I) = Filler; 6972 6973 // Initialize the elements. 6974 LValue ArrayElt = Subobject; 6975 ArrayElt.addArray(Info, E, CAT); 6976 for (unsigned I = 0; I != N; ++I) 6977 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 6978 CAT->getElementType()) || 6979 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 6980 CAT->getElementType(), 1)) 6981 return false; 6982 6983 return true; 6984 } 6985 6986 if (!Type->isRecordType()) 6987 return Error(E); 6988 6989 return RecordExprEvaluator(Info, Subobject, *Value) 6990 .VisitCXXConstructExpr(E, Type); 6991 } 6992 6993 //===----------------------------------------------------------------------===// 6994 // Integer Evaluation 6995 // 6996 // As a GNU extension, we support casting pointers to sufficiently-wide integer 6997 // types and back in constant folding. Integer values are thus represented 6998 // either as an integer-valued APValue, or as an lvalue-valued APValue. 6999 //===----------------------------------------------------------------------===// 7000 7001 namespace { 7002 class IntExprEvaluator 7003 : public ExprEvaluatorBase<IntExprEvaluator> { 7004 APValue &Result; 7005 public: 7006 IntExprEvaluator(EvalInfo &info, APValue &result) 7007 : ExprEvaluatorBaseTy(info), Result(result) {} 7008 7009 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 7010 assert(E->getType()->isIntegralOrEnumerationType() && 7011 "Invalid evaluation result."); 7012 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 7013 "Invalid evaluation result."); 7014 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7015 "Invalid evaluation result."); 7016 Result = APValue(SI); 7017 return true; 7018 } 7019 bool Success(const llvm::APSInt &SI, const Expr *E) { 7020 return Success(SI, E, Result); 7021 } 7022 7023 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 7024 assert(E->getType()->isIntegralOrEnumerationType() && 7025 "Invalid evaluation result."); 7026 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7027 "Invalid evaluation result."); 7028 Result = APValue(APSInt(I)); 7029 Result.getInt().setIsUnsigned( 7030 E->getType()->isUnsignedIntegerOrEnumerationType()); 7031 return true; 7032 } 7033 bool Success(const llvm::APInt &I, const Expr *E) { 7034 return Success(I, E, Result); 7035 } 7036 7037 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7038 assert(E->getType()->isIntegralOrEnumerationType() && 7039 "Invalid evaluation result."); 7040 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 7041 return true; 7042 } 7043 bool Success(uint64_t Value, const Expr *E) { 7044 return Success(Value, E, Result); 7045 } 7046 7047 bool Success(CharUnits Size, const Expr *E) { 7048 return Success(Size.getQuantity(), E); 7049 } 7050 7051 bool Success(const APValue &V, const Expr *E) { 7052 if (V.isLValue() || V.isAddrLabelDiff()) { 7053 Result = V; 7054 return true; 7055 } 7056 return Success(V.getInt(), E); 7057 } 7058 7059 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7060 7061 //===--------------------------------------------------------------------===// 7062 // Visitor Methods 7063 //===--------------------------------------------------------------------===// 7064 7065 bool VisitIntegerLiteral(const IntegerLiteral *E) { 7066 return Success(E->getValue(), E); 7067 } 7068 bool VisitCharacterLiteral(const CharacterLiteral *E) { 7069 return Success(E->getValue(), E); 7070 } 7071 7072 bool CheckReferencedDecl(const Expr *E, const Decl *D); 7073 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7074 if (CheckReferencedDecl(E, E->getDecl())) 7075 return true; 7076 7077 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 7078 } 7079 bool VisitMemberExpr(const MemberExpr *E) { 7080 if (CheckReferencedDecl(E, E->getMemberDecl())) { 7081 VisitIgnoredBaseExpression(E->getBase()); 7082 return true; 7083 } 7084 7085 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 7086 } 7087 7088 bool VisitCallExpr(const CallExpr *E); 7089 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7090 bool VisitBinaryOperator(const BinaryOperator *E); 7091 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 7092 bool VisitUnaryOperator(const UnaryOperator *E); 7093 7094 bool VisitCastExpr(const CastExpr* E); 7095 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 7096 7097 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 7098 return Success(E->getValue(), E); 7099 } 7100 7101 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 7102 return Success(E->getValue(), E); 7103 } 7104 7105 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 7106 if (Info.ArrayInitIndex == uint64_t(-1)) { 7107 // We were asked to evaluate this subexpression independent of the 7108 // enclosing ArrayInitLoopExpr. We can't do that. 7109 Info.FFDiag(E); 7110 return false; 7111 } 7112 return Success(Info.ArrayInitIndex, E); 7113 } 7114 7115 // Note, GNU defines __null as an integer, not a pointer. 7116 bool VisitGNUNullExpr(const GNUNullExpr *E) { 7117 return ZeroInitialization(E); 7118 } 7119 7120 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 7121 return Success(E->getValue(), E); 7122 } 7123 7124 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 7125 return Success(E->getValue(), E); 7126 } 7127 7128 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 7129 return Success(E->getValue(), E); 7130 } 7131 7132 bool VisitUnaryReal(const UnaryOperator *E); 7133 bool VisitUnaryImag(const UnaryOperator *E); 7134 7135 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 7136 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 7137 7138 // FIXME: Missing: array subscript of vector, member of vector 7139 }; 7140 } // end anonymous namespace 7141 7142 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 7143 /// produce either the integer value or a pointer. 7144 /// 7145 /// GCC has a heinous extension which folds casts between pointer types and 7146 /// pointer-sized integral types. We support this by allowing the evaluation of 7147 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 7148 /// Some simple arithmetic on such values is supported (they are treated much 7149 /// like char*). 7150 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 7151 EvalInfo &Info) { 7152 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 7153 return IntExprEvaluator(Info, Result).Visit(E); 7154 } 7155 7156 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 7157 APValue Val; 7158 if (!EvaluateIntegerOrLValue(E, Val, Info)) 7159 return false; 7160 if (!Val.isInt()) { 7161 // FIXME: It would be better to produce the diagnostic for casting 7162 // a pointer to an integer. 7163 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 7164 return false; 7165 } 7166 Result = Val.getInt(); 7167 return true; 7168 } 7169 7170 /// Check whether the given declaration can be directly converted to an integral 7171 /// rvalue. If not, no diagnostic is produced; there are other things we can 7172 /// try. 7173 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 7174 // Enums are integer constant exprs. 7175 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 7176 // Check for signedness/width mismatches between E type and ECD value. 7177 bool SameSign = (ECD->getInitVal().isSigned() 7178 == E->getType()->isSignedIntegerOrEnumerationType()); 7179 bool SameWidth = (ECD->getInitVal().getBitWidth() 7180 == Info.Ctx.getIntWidth(E->getType())); 7181 if (SameSign && SameWidth) 7182 return Success(ECD->getInitVal(), E); 7183 else { 7184 // Get rid of mismatch (otherwise Success assertions will fail) 7185 // by computing a new value matching the type of E. 7186 llvm::APSInt Val = ECD->getInitVal(); 7187 if (!SameSign) 7188 Val.setIsSigned(!ECD->getInitVal().isSigned()); 7189 if (!SameWidth) 7190 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 7191 return Success(Val, E); 7192 } 7193 } 7194 return false; 7195 } 7196 7197 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7198 /// as GCC. 7199 static int EvaluateBuiltinClassifyType(const CallExpr *E, 7200 const LangOptions &LangOpts) { 7201 // The following enum mimics the values returned by GCC. 7202 // FIXME: Does GCC differ between lvalue and rvalue references here? 7203 enum gcc_type_class { 7204 no_type_class = -1, 7205 void_type_class, integer_type_class, char_type_class, 7206 enumeral_type_class, boolean_type_class, 7207 pointer_type_class, reference_type_class, offset_type_class, 7208 real_type_class, complex_type_class, 7209 function_type_class, method_type_class, 7210 record_type_class, union_type_class, 7211 array_type_class, string_type_class, 7212 lang_type_class 7213 }; 7214 7215 // If no argument was supplied, default to "no_type_class". This isn't 7216 // ideal, however it is what gcc does. 7217 if (E->getNumArgs() == 0) 7218 return no_type_class; 7219 7220 QualType CanTy = E->getArg(0)->getType().getCanonicalType(); 7221 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 7222 7223 switch (CanTy->getTypeClass()) { 7224 #define TYPE(ID, BASE) 7225 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 7226 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 7227 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 7228 #include "clang/AST/TypeNodes.def" 7229 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7230 7231 case Type::Builtin: 7232 switch (BT->getKind()) { 7233 #define BUILTIN_TYPE(ID, SINGLETON_ID) 7234 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class; 7235 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class; 7236 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break; 7237 #include "clang/AST/BuiltinTypes.def" 7238 case BuiltinType::Void: 7239 return void_type_class; 7240 7241 case BuiltinType::Bool: 7242 return boolean_type_class; 7243 7244 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class 7245 case BuiltinType::UChar: 7246 case BuiltinType::UShort: 7247 case BuiltinType::UInt: 7248 case BuiltinType::ULong: 7249 case BuiltinType::ULongLong: 7250 case BuiltinType::UInt128: 7251 return integer_type_class; 7252 7253 case BuiltinType::NullPtr: 7254 return pointer_type_class; 7255 7256 case BuiltinType::WChar_U: 7257 case BuiltinType::Char16: 7258 case BuiltinType::Char32: 7259 case BuiltinType::ObjCId: 7260 case BuiltinType::ObjCClass: 7261 case BuiltinType::ObjCSel: 7262 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7263 case BuiltinType::Id: 7264 #include "clang/Basic/OpenCLImageTypes.def" 7265 case BuiltinType::OCLSampler: 7266 case BuiltinType::OCLEvent: 7267 case BuiltinType::OCLClkEvent: 7268 case BuiltinType::OCLQueue: 7269 case BuiltinType::OCLReserveID: 7270 case BuiltinType::Dependent: 7271 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7272 }; 7273 break; 7274 7275 case Type::Enum: 7276 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class; 7277 break; 7278 7279 case Type::Pointer: 7280 return pointer_type_class; 7281 break; 7282 7283 case Type::MemberPointer: 7284 if (CanTy->isMemberDataPointerType()) 7285 return offset_type_class; 7286 else { 7287 // We expect member pointers to be either data or function pointers, 7288 // nothing else. 7289 assert(CanTy->isMemberFunctionPointerType()); 7290 return method_type_class; 7291 } 7292 7293 case Type::Complex: 7294 return complex_type_class; 7295 7296 case Type::FunctionNoProto: 7297 case Type::FunctionProto: 7298 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class; 7299 7300 case Type::Record: 7301 if (const RecordType *RT = CanTy->getAs<RecordType>()) { 7302 switch (RT->getDecl()->getTagKind()) { 7303 case TagTypeKind::TTK_Struct: 7304 case TagTypeKind::TTK_Class: 7305 case TagTypeKind::TTK_Interface: 7306 return record_type_class; 7307 7308 case TagTypeKind::TTK_Enum: 7309 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class; 7310 7311 case TagTypeKind::TTK_Union: 7312 return union_type_class; 7313 } 7314 } 7315 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7316 7317 case Type::ConstantArray: 7318 case Type::VariableArray: 7319 case Type::IncompleteArray: 7320 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class; 7321 7322 case Type::BlockPointer: 7323 case Type::LValueReference: 7324 case Type::RValueReference: 7325 case Type::Vector: 7326 case Type::ExtVector: 7327 case Type::Auto: 7328 case Type::DeducedTemplateSpecialization: 7329 case Type::ObjCObject: 7330 case Type::ObjCInterface: 7331 case Type::ObjCObjectPointer: 7332 case Type::Pipe: 7333 case Type::Atomic: 7334 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7335 } 7336 7337 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7338 } 7339 7340 /// EvaluateBuiltinConstantPForLValue - Determine the result of 7341 /// __builtin_constant_p when applied to the given lvalue. 7342 /// 7343 /// An lvalue is only "constant" if it is a pointer or reference to the first 7344 /// character of a string literal. 7345 template<typename LValue> 7346 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 7347 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>(); 7348 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 7349 } 7350 7351 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 7352 /// GCC as we can manage. 7353 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 7354 QualType ArgType = Arg->getType(); 7355 7356 // __builtin_constant_p always has one operand. The rules which gcc follows 7357 // are not precisely documented, but are as follows: 7358 // 7359 // - If the operand is of integral, floating, complex or enumeration type, 7360 // and can be folded to a known value of that type, it returns 1. 7361 // - If the operand and can be folded to a pointer to the first character 7362 // of a string literal (or such a pointer cast to an integral type), it 7363 // returns 1. 7364 // 7365 // Otherwise, it returns 0. 7366 // 7367 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 7368 // its support for this does not currently work. 7369 if (ArgType->isIntegralOrEnumerationType()) { 7370 Expr::EvalResult Result; 7371 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 7372 return false; 7373 7374 APValue &V = Result.Val; 7375 if (V.getKind() == APValue::Int) 7376 return true; 7377 if (V.getKind() == APValue::LValue) 7378 return EvaluateBuiltinConstantPForLValue(V); 7379 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 7380 return Arg->isEvaluatable(Ctx); 7381 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 7382 LValue LV; 7383 Expr::EvalStatus Status; 7384 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 7385 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 7386 : EvaluatePointer(Arg, LV, Info)) && 7387 !Status.HasSideEffects) 7388 return EvaluateBuiltinConstantPForLValue(LV); 7389 } 7390 7391 // Anything else isn't considered to be sufficiently constant. 7392 return false; 7393 } 7394 7395 /// Retrieves the "underlying object type" of the given expression, 7396 /// as used by __builtin_object_size. 7397 static QualType getObjectType(APValue::LValueBase B) { 7398 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 7399 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 7400 return VD->getType(); 7401 } else if (const Expr *E = B.get<const Expr*>()) { 7402 if (isa<CompoundLiteralExpr>(E)) 7403 return E->getType(); 7404 } 7405 7406 return QualType(); 7407 } 7408 7409 /// A more selective version of E->IgnoreParenCasts for 7410 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 7411 /// to change the type of E. 7412 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 7413 /// 7414 /// Always returns an RValue with a pointer representation. 7415 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 7416 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7417 7418 auto *NoParens = E->IgnoreParens(); 7419 auto *Cast = dyn_cast<CastExpr>(NoParens); 7420 if (Cast == nullptr) 7421 return NoParens; 7422 7423 // We only conservatively allow a few kinds of casts, because this code is 7424 // inherently a simple solution that seeks to support the common case. 7425 auto CastKind = Cast->getCastKind(); 7426 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 7427 CastKind != CK_AddressSpaceConversion) 7428 return NoParens; 7429 7430 auto *SubExpr = Cast->getSubExpr(); 7431 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 7432 return NoParens; 7433 return ignorePointerCastsAndParens(SubExpr); 7434 } 7435 7436 /// Checks to see if the given LValue's Designator is at the end of the LValue's 7437 /// record layout. e.g. 7438 /// struct { struct { int a, b; } fst, snd; } obj; 7439 /// obj.fst // no 7440 /// obj.snd // yes 7441 /// obj.fst.a // no 7442 /// obj.fst.b // no 7443 /// obj.snd.a // no 7444 /// obj.snd.b // yes 7445 /// 7446 /// Please note: this function is specialized for how __builtin_object_size 7447 /// views "objects". 7448 /// 7449 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 7450 /// correct result, it will always return true. 7451 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 7452 assert(!LVal.Designator.Invalid); 7453 7454 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 7455 const RecordDecl *Parent = FD->getParent(); 7456 Invalid = Parent->isInvalidDecl(); 7457 if (Invalid || Parent->isUnion()) 7458 return true; 7459 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 7460 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 7461 }; 7462 7463 auto &Base = LVal.getLValueBase(); 7464 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 7465 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 7466 bool Invalid; 7467 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7468 return Invalid; 7469 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 7470 for (auto *FD : IFD->chain()) { 7471 bool Invalid; 7472 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 7473 return Invalid; 7474 } 7475 } 7476 } 7477 7478 unsigned I = 0; 7479 QualType BaseType = getType(Base); 7480 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 7481 // If we don't know the array bound, conservatively assume we're looking at 7482 // the final array element. 7483 ++I; 7484 if (BaseType->isIncompleteArrayType()) 7485 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 7486 else 7487 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 7488 } 7489 7490 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 7491 const auto &Entry = LVal.Designator.Entries[I]; 7492 if (BaseType->isArrayType()) { 7493 // Because __builtin_object_size treats arrays as objects, we can ignore 7494 // the index iff this is the last array in the Designator. 7495 if (I + 1 == E) 7496 return true; 7497 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 7498 uint64_t Index = Entry.ArrayIndex; 7499 if (Index + 1 != CAT->getSize()) 7500 return false; 7501 BaseType = CAT->getElementType(); 7502 } else if (BaseType->isAnyComplexType()) { 7503 const auto *CT = BaseType->castAs<ComplexType>(); 7504 uint64_t Index = Entry.ArrayIndex; 7505 if (Index != 1) 7506 return false; 7507 BaseType = CT->getElementType(); 7508 } else if (auto *FD = getAsField(Entry)) { 7509 bool Invalid; 7510 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7511 return Invalid; 7512 BaseType = FD->getType(); 7513 } else { 7514 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 7515 return false; 7516 } 7517 } 7518 return true; 7519 } 7520 7521 /// Tests to see if the LValue has a user-specified designator (that isn't 7522 /// necessarily valid). Note that this always returns 'true' if the LValue has 7523 /// an unsized array as its first designator entry, because there's currently no 7524 /// way to tell if the user typed *foo or foo[0]. 7525 static bool refersToCompleteObject(const LValue &LVal) { 7526 if (LVal.Designator.Invalid) 7527 return false; 7528 7529 if (!LVal.Designator.Entries.empty()) 7530 return LVal.Designator.isMostDerivedAnUnsizedArray(); 7531 7532 if (!LVal.InvalidBase) 7533 return true; 7534 7535 // If `E` is a MemberExpr, then the first part of the designator is hiding in 7536 // the LValueBase. 7537 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 7538 return !E || !isa<MemberExpr>(E); 7539 } 7540 7541 /// Attempts to detect a user writing into a piece of memory that's impossible 7542 /// to figure out the size of by just using types. 7543 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 7544 const SubobjectDesignator &Designator = LVal.Designator; 7545 // Notes: 7546 // - Users can only write off of the end when we have an invalid base. Invalid 7547 // bases imply we don't know where the memory came from. 7548 // - We used to be a bit more aggressive here; we'd only be conservative if 7549 // the array at the end was flexible, or if it had 0 or 1 elements. This 7550 // broke some common standard library extensions (PR30346), but was 7551 // otherwise seemingly fine. It may be useful to reintroduce this behavior 7552 // with some sort of whitelist. OTOH, it seems that GCC is always 7553 // conservative with the last element in structs (if it's an array), so our 7554 // current behavior is more compatible than a whitelisting approach would 7555 // be. 7556 return LVal.InvalidBase && 7557 Designator.Entries.size() == Designator.MostDerivedPathLength && 7558 Designator.MostDerivedIsArrayElement && 7559 isDesignatorAtObjectEnd(Ctx, LVal); 7560 } 7561 7562 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 7563 /// Fails if the conversion would cause loss of precision. 7564 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 7565 CharUnits &Result) { 7566 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 7567 if (Int.ugt(CharUnitsMax)) 7568 return false; 7569 Result = CharUnits::fromQuantity(Int.getZExtValue()); 7570 return true; 7571 } 7572 7573 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 7574 /// determine how many bytes exist from the beginning of the object to either 7575 /// the end of the current subobject, or the end of the object itself, depending 7576 /// on what the LValue looks like + the value of Type. 7577 /// 7578 /// If this returns false, the value of Result is undefined. 7579 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 7580 unsigned Type, const LValue &LVal, 7581 CharUnits &EndOffset) { 7582 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 7583 7584 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 7585 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 7586 return false; 7587 return HandleSizeof(Info, ExprLoc, Ty, Result); 7588 }; 7589 7590 // We want to evaluate the size of the entire object. This is a valid fallback 7591 // for when Type=1 and the designator is invalid, because we're asked for an 7592 // upper-bound. 7593 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 7594 // Type=3 wants a lower bound, so we can't fall back to this. 7595 if (Type == 3 && !DetermineForCompleteObject) 7596 return false; 7597 7598 llvm::APInt APEndOffset; 7599 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7600 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7601 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7602 7603 if (LVal.InvalidBase) 7604 return false; 7605 7606 QualType BaseTy = getObjectType(LVal.getLValueBase()); 7607 return CheckedHandleSizeof(BaseTy, EndOffset); 7608 } 7609 7610 // We want to evaluate the size of a subobject. 7611 const SubobjectDesignator &Designator = LVal.Designator; 7612 7613 // The following is a moderately common idiom in C: 7614 // 7615 // struct Foo { int a; char c[1]; }; 7616 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 7617 // strcpy(&F->c[0], Bar); 7618 // 7619 // In order to not break too much legacy code, we need to support it. 7620 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 7621 // If we can resolve this to an alloc_size call, we can hand that back, 7622 // because we know for certain how many bytes there are to write to. 7623 llvm::APInt APEndOffset; 7624 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7625 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7626 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7627 7628 // If we cannot determine the size of the initial allocation, then we can't 7629 // given an accurate upper-bound. However, we are still able to give 7630 // conservative lower-bounds for Type=3. 7631 if (Type == 1) 7632 return false; 7633 } 7634 7635 CharUnits BytesPerElem; 7636 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 7637 return false; 7638 7639 // According to the GCC documentation, we want the size of the subobject 7640 // denoted by the pointer. But that's not quite right -- what we actually 7641 // want is the size of the immediately-enclosing array, if there is one. 7642 int64_t ElemsRemaining; 7643 if (Designator.MostDerivedIsArrayElement && 7644 Designator.Entries.size() == Designator.MostDerivedPathLength) { 7645 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 7646 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex; 7647 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 7648 } else { 7649 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 7650 } 7651 7652 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 7653 return true; 7654 } 7655 7656 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful, 7657 /// returns true and stores the result in @p Size. 7658 /// 7659 /// If @p WasError is non-null, this will report whether the failure to evaluate 7660 /// is to be treated as an Error in IntExprEvaluator. 7661 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 7662 EvalInfo &Info, uint64_t &Size) { 7663 // Determine the denoted object. 7664 LValue LVal; 7665 { 7666 // The operand of __builtin_object_size is never evaluated for side-effects. 7667 // If there are any, but we can determine the pointed-to object anyway, then 7668 // ignore the side-effects. 7669 SpeculativeEvaluationRAII SpeculativeEval(Info); 7670 FoldOffsetRAII Fold(Info); 7671 7672 if (E->isGLValue()) { 7673 // It's possible for us to be given GLValues if we're called via 7674 // Expr::tryEvaluateObjectSize. 7675 APValue RVal; 7676 if (!EvaluateAsRValue(Info, E, RVal)) 7677 return false; 7678 LVal.setFrom(Info.Ctx, RVal); 7679 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 7680 /*InvalidBaseOK=*/true)) 7681 return false; 7682 } 7683 7684 // If we point to before the start of the object, there are no accessible 7685 // bytes. 7686 if (LVal.getLValueOffset().isNegative()) { 7687 Size = 0; 7688 return true; 7689 } 7690 7691 CharUnits EndOffset; 7692 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 7693 return false; 7694 7695 // If we've fallen outside of the end offset, just pretend there's nothing to 7696 // write to/read from. 7697 if (EndOffset <= LVal.getLValueOffset()) 7698 Size = 0; 7699 else 7700 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 7701 return true; 7702 } 7703 7704 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 7705 if (unsigned BuiltinOp = E->getBuiltinCallee()) 7706 return VisitBuiltinCallExpr(E, BuiltinOp); 7707 7708 return ExprEvaluatorBaseTy::VisitCallExpr(E); 7709 } 7710 7711 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 7712 unsigned BuiltinOp) { 7713 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 7714 default: 7715 return ExprEvaluatorBaseTy::VisitCallExpr(E); 7716 7717 case Builtin::BI__builtin_object_size: { 7718 // The type was checked when we built the expression. 7719 unsigned Type = 7720 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 7721 assert(Type <= 3 && "unexpected type"); 7722 7723 uint64_t Size; 7724 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 7725 return Success(Size, E); 7726 7727 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 7728 return Success((Type & 2) ? 0 : -1, E); 7729 7730 // Expression had no side effects, but we couldn't statically determine the 7731 // size of the referenced object. 7732 switch (Info.EvalMode) { 7733 case EvalInfo::EM_ConstantExpression: 7734 case EvalInfo::EM_PotentialConstantExpression: 7735 case EvalInfo::EM_ConstantFold: 7736 case EvalInfo::EM_EvaluateForOverflow: 7737 case EvalInfo::EM_IgnoreSideEffects: 7738 case EvalInfo::EM_OffsetFold: 7739 // Leave it to IR generation. 7740 return Error(E); 7741 case EvalInfo::EM_ConstantExpressionUnevaluated: 7742 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 7743 // Reduce it to a constant now. 7744 return Success((Type & 2) ? 0 : -1, E); 7745 } 7746 7747 llvm_unreachable("unexpected EvalMode"); 7748 } 7749 7750 case Builtin::BI__builtin_bswap16: 7751 case Builtin::BI__builtin_bswap32: 7752 case Builtin::BI__builtin_bswap64: { 7753 APSInt Val; 7754 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7755 return false; 7756 7757 return Success(Val.byteSwap(), E); 7758 } 7759 7760 case Builtin::BI__builtin_classify_type: 7761 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 7762 7763 // FIXME: BI__builtin_clrsb 7764 // FIXME: BI__builtin_clrsbl 7765 // FIXME: BI__builtin_clrsbll 7766 7767 case Builtin::BI__builtin_clz: 7768 case Builtin::BI__builtin_clzl: 7769 case Builtin::BI__builtin_clzll: 7770 case Builtin::BI__builtin_clzs: { 7771 APSInt Val; 7772 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7773 return false; 7774 if (!Val) 7775 return Error(E); 7776 7777 return Success(Val.countLeadingZeros(), E); 7778 } 7779 7780 case Builtin::BI__builtin_constant_p: 7781 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E); 7782 7783 case Builtin::BI__builtin_ctz: 7784 case Builtin::BI__builtin_ctzl: 7785 case Builtin::BI__builtin_ctzll: 7786 case Builtin::BI__builtin_ctzs: { 7787 APSInt Val; 7788 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7789 return false; 7790 if (!Val) 7791 return Error(E); 7792 7793 return Success(Val.countTrailingZeros(), E); 7794 } 7795 7796 case Builtin::BI__builtin_eh_return_data_regno: { 7797 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 7798 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 7799 return Success(Operand, E); 7800 } 7801 7802 case Builtin::BI__builtin_expect: 7803 return Visit(E->getArg(0)); 7804 7805 case Builtin::BI__builtin_ffs: 7806 case Builtin::BI__builtin_ffsl: 7807 case Builtin::BI__builtin_ffsll: { 7808 APSInt Val; 7809 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7810 return false; 7811 7812 unsigned N = Val.countTrailingZeros(); 7813 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 7814 } 7815 7816 case Builtin::BI__builtin_fpclassify: { 7817 APFloat Val(0.0); 7818 if (!EvaluateFloat(E->getArg(5), Val, Info)) 7819 return false; 7820 unsigned Arg; 7821 switch (Val.getCategory()) { 7822 case APFloat::fcNaN: Arg = 0; break; 7823 case APFloat::fcInfinity: Arg = 1; break; 7824 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 7825 case APFloat::fcZero: Arg = 4; break; 7826 } 7827 return Visit(E->getArg(Arg)); 7828 } 7829 7830 case Builtin::BI__builtin_isinf_sign: { 7831 APFloat Val(0.0); 7832 return EvaluateFloat(E->getArg(0), Val, Info) && 7833 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 7834 } 7835 7836 case Builtin::BI__builtin_isinf: { 7837 APFloat Val(0.0); 7838 return EvaluateFloat(E->getArg(0), Val, Info) && 7839 Success(Val.isInfinity() ? 1 : 0, E); 7840 } 7841 7842 case Builtin::BI__builtin_isfinite: { 7843 APFloat Val(0.0); 7844 return EvaluateFloat(E->getArg(0), Val, Info) && 7845 Success(Val.isFinite() ? 1 : 0, E); 7846 } 7847 7848 case Builtin::BI__builtin_isnan: { 7849 APFloat Val(0.0); 7850 return EvaluateFloat(E->getArg(0), Val, Info) && 7851 Success(Val.isNaN() ? 1 : 0, E); 7852 } 7853 7854 case Builtin::BI__builtin_isnormal: { 7855 APFloat Val(0.0); 7856 return EvaluateFloat(E->getArg(0), Val, Info) && 7857 Success(Val.isNormal() ? 1 : 0, E); 7858 } 7859 7860 case Builtin::BI__builtin_parity: 7861 case Builtin::BI__builtin_parityl: 7862 case Builtin::BI__builtin_parityll: { 7863 APSInt Val; 7864 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7865 return false; 7866 7867 return Success(Val.countPopulation() % 2, E); 7868 } 7869 7870 case Builtin::BI__builtin_popcount: 7871 case Builtin::BI__builtin_popcountl: 7872 case Builtin::BI__builtin_popcountll: { 7873 APSInt Val; 7874 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7875 return false; 7876 7877 return Success(Val.countPopulation(), E); 7878 } 7879 7880 case Builtin::BIstrlen: 7881 case Builtin::BIwcslen: 7882 // A call to strlen is not a constant expression. 7883 if (Info.getLangOpts().CPlusPlus11) 7884 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7885 << /*isConstexpr*/0 << /*isConstructor*/0 7886 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7887 else 7888 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7889 LLVM_FALLTHROUGH; 7890 case Builtin::BI__builtin_strlen: 7891 case Builtin::BI__builtin_wcslen: { 7892 // As an extension, we support __builtin_strlen() as a constant expression, 7893 // and support folding strlen() to a constant. 7894 LValue String; 7895 if (!EvaluatePointer(E->getArg(0), String, Info)) 7896 return false; 7897 7898 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 7899 7900 // Fast path: if it's a string literal, search the string value. 7901 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 7902 String.getLValueBase().dyn_cast<const Expr *>())) { 7903 // The string literal may have embedded null characters. Find the first 7904 // one and truncate there. 7905 StringRef Str = S->getBytes(); 7906 int64_t Off = String.Offset.getQuantity(); 7907 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 7908 S->getCharByteWidth() == 1 && 7909 // FIXME: Add fast-path for wchar_t too. 7910 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 7911 Str = Str.substr(Off); 7912 7913 StringRef::size_type Pos = Str.find(0); 7914 if (Pos != StringRef::npos) 7915 Str = Str.substr(0, Pos); 7916 7917 return Success(Str.size(), E); 7918 } 7919 7920 // Fall through to slow path to issue appropriate diagnostic. 7921 } 7922 7923 // Slow path: scan the bytes of the string looking for the terminating 0. 7924 for (uint64_t Strlen = 0; /**/; ++Strlen) { 7925 APValue Char; 7926 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 7927 !Char.isInt()) 7928 return false; 7929 if (!Char.getInt()) 7930 return Success(Strlen, E); 7931 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 7932 return false; 7933 } 7934 } 7935 7936 case Builtin::BIstrcmp: 7937 case Builtin::BIwcscmp: 7938 case Builtin::BIstrncmp: 7939 case Builtin::BIwcsncmp: 7940 case Builtin::BImemcmp: 7941 case Builtin::BIwmemcmp: 7942 // A call to strlen is not a constant expression. 7943 if (Info.getLangOpts().CPlusPlus11) 7944 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7945 << /*isConstexpr*/0 << /*isConstructor*/0 7946 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7947 else 7948 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7949 LLVM_FALLTHROUGH; 7950 case Builtin::BI__builtin_strcmp: 7951 case Builtin::BI__builtin_wcscmp: 7952 case Builtin::BI__builtin_strncmp: 7953 case Builtin::BI__builtin_wcsncmp: 7954 case Builtin::BI__builtin_memcmp: 7955 case Builtin::BI__builtin_wmemcmp: { 7956 LValue String1, String2; 7957 if (!EvaluatePointer(E->getArg(0), String1, Info) || 7958 !EvaluatePointer(E->getArg(1), String2, Info)) 7959 return false; 7960 7961 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 7962 7963 uint64_t MaxLength = uint64_t(-1); 7964 if (BuiltinOp != Builtin::BIstrcmp && 7965 BuiltinOp != Builtin::BIwcscmp && 7966 BuiltinOp != Builtin::BI__builtin_strcmp && 7967 BuiltinOp != Builtin::BI__builtin_wcscmp) { 7968 APSInt N; 7969 if (!EvaluateInteger(E->getArg(2), N, Info)) 7970 return false; 7971 MaxLength = N.getExtValue(); 7972 } 7973 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp && 7974 BuiltinOp != Builtin::BIwmemcmp && 7975 BuiltinOp != Builtin::BI__builtin_memcmp && 7976 BuiltinOp != Builtin::BI__builtin_wmemcmp); 7977 for (; MaxLength; --MaxLength) { 7978 APValue Char1, Char2; 7979 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) || 7980 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) || 7981 !Char1.isInt() || !Char2.isInt()) 7982 return false; 7983 if (Char1.getInt() != Char2.getInt()) 7984 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 7985 if (StopAtNull && !Char1.getInt()) 7986 return Success(0, E); 7987 assert(!(StopAtNull && !Char2.getInt())); 7988 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) || 7989 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1)) 7990 return false; 7991 } 7992 // We hit the strncmp / memcmp limit. 7993 return Success(0, E); 7994 } 7995 7996 case Builtin::BI__atomic_always_lock_free: 7997 case Builtin::BI__atomic_is_lock_free: 7998 case Builtin::BI__c11_atomic_is_lock_free: { 7999 APSInt SizeVal; 8000 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 8001 return false; 8002 8003 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 8004 // of two less than the maximum inline atomic width, we know it is 8005 // lock-free. If the size isn't a power of two, or greater than the 8006 // maximum alignment where we promote atomics, we know it is not lock-free 8007 // (at least not in the sense of atomic_is_lock_free). Otherwise, 8008 // the answer can only be determined at runtime; for example, 16-byte 8009 // atomics have lock-free implementations on some, but not all, 8010 // x86-64 processors. 8011 8012 // Check power-of-two. 8013 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 8014 if (Size.isPowerOfTwo()) { 8015 // Check against inlining width. 8016 unsigned InlineWidthBits = 8017 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 8018 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 8019 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 8020 Size == CharUnits::One() || 8021 E->getArg(1)->isNullPointerConstant(Info.Ctx, 8022 Expr::NPC_NeverValueDependent)) 8023 // OK, we will inline appropriately-aligned operations of this size, 8024 // and _Atomic(T) is appropriately-aligned. 8025 return Success(1, E); 8026 8027 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 8028 castAs<PointerType>()->getPointeeType(); 8029 if (!PointeeType->isIncompleteType() && 8030 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 8031 // OK, we will inline operations on this object. 8032 return Success(1, E); 8033 } 8034 } 8035 } 8036 8037 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 8038 Success(0, E) : Error(E); 8039 } 8040 case Builtin::BIomp_is_initial_device: 8041 // We can decide statically which value the runtime would return if called. 8042 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 8043 } 8044 } 8045 8046 static bool HasSameBase(const LValue &A, const LValue &B) { 8047 if (!A.getLValueBase()) 8048 return !B.getLValueBase(); 8049 if (!B.getLValueBase()) 8050 return false; 8051 8052 if (A.getLValueBase().getOpaqueValue() != 8053 B.getLValueBase().getOpaqueValue()) { 8054 const Decl *ADecl = GetLValueBaseDecl(A); 8055 if (!ADecl) 8056 return false; 8057 const Decl *BDecl = GetLValueBaseDecl(B); 8058 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 8059 return false; 8060 } 8061 8062 return IsGlobalLValue(A.getLValueBase()) || 8063 A.getLValueCallIndex() == B.getLValueCallIndex(); 8064 } 8065 8066 /// \brief Determine whether this is a pointer past the end of the complete 8067 /// object referred to by the lvalue. 8068 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 8069 const LValue &LV) { 8070 // A null pointer can be viewed as being "past the end" but we don't 8071 // choose to look at it that way here. 8072 if (!LV.getLValueBase()) 8073 return false; 8074 8075 // If the designator is valid and refers to a subobject, we're not pointing 8076 // past the end. 8077 if (!LV.getLValueDesignator().Invalid && 8078 !LV.getLValueDesignator().isOnePastTheEnd()) 8079 return false; 8080 8081 // A pointer to an incomplete type might be past-the-end if the type's size is 8082 // zero. We cannot tell because the type is incomplete. 8083 QualType Ty = getType(LV.getLValueBase()); 8084 if (Ty->isIncompleteType()) 8085 return true; 8086 8087 // We're a past-the-end pointer if we point to the byte after the object, 8088 // no matter what our type or path is. 8089 auto Size = Ctx.getTypeSizeInChars(Ty); 8090 return LV.getLValueOffset() == Size; 8091 } 8092 8093 namespace { 8094 8095 /// \brief Data recursive integer evaluator of certain binary operators. 8096 /// 8097 /// We use a data recursive algorithm for binary operators so that we are able 8098 /// to handle extreme cases of chained binary operators without causing stack 8099 /// overflow. 8100 class DataRecursiveIntBinOpEvaluator { 8101 struct EvalResult { 8102 APValue Val; 8103 bool Failed; 8104 8105 EvalResult() : Failed(false) { } 8106 8107 void swap(EvalResult &RHS) { 8108 Val.swap(RHS.Val); 8109 Failed = RHS.Failed; 8110 RHS.Failed = false; 8111 } 8112 }; 8113 8114 struct Job { 8115 const Expr *E; 8116 EvalResult LHSResult; // meaningful only for binary operator expression. 8117 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 8118 8119 Job() = default; 8120 Job(Job &&) = default; 8121 8122 void startSpeculativeEval(EvalInfo &Info) { 8123 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 8124 } 8125 8126 private: 8127 SpeculativeEvaluationRAII SpecEvalRAII; 8128 }; 8129 8130 SmallVector<Job, 16> Queue; 8131 8132 IntExprEvaluator &IntEval; 8133 EvalInfo &Info; 8134 APValue &FinalResult; 8135 8136 public: 8137 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 8138 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 8139 8140 /// \brief True if \param E is a binary operator that we are going to handle 8141 /// data recursively. 8142 /// We handle binary operators that are comma, logical, or that have operands 8143 /// with integral or enumeration type. 8144 static bool shouldEnqueue(const BinaryOperator *E) { 8145 return E->getOpcode() == BO_Comma || 8146 E->isLogicalOp() || 8147 (E->isRValue() && 8148 E->getType()->isIntegralOrEnumerationType() && 8149 E->getLHS()->getType()->isIntegralOrEnumerationType() && 8150 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8151 } 8152 8153 bool Traverse(const BinaryOperator *E) { 8154 enqueue(E); 8155 EvalResult PrevResult; 8156 while (!Queue.empty()) 8157 process(PrevResult); 8158 8159 if (PrevResult.Failed) return false; 8160 8161 FinalResult.swap(PrevResult.Val); 8162 return true; 8163 } 8164 8165 private: 8166 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8167 return IntEval.Success(Value, E, Result); 8168 } 8169 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 8170 return IntEval.Success(Value, E, Result); 8171 } 8172 bool Error(const Expr *E) { 8173 return IntEval.Error(E); 8174 } 8175 bool Error(const Expr *E, diag::kind D) { 8176 return IntEval.Error(E, D); 8177 } 8178 8179 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 8180 return Info.CCEDiag(E, D); 8181 } 8182 8183 // \brief Returns true if visiting the RHS is necessary, false otherwise. 8184 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8185 bool &SuppressRHSDiags); 8186 8187 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8188 const BinaryOperator *E, APValue &Result); 8189 8190 void EvaluateExpr(const Expr *E, EvalResult &Result) { 8191 Result.Failed = !Evaluate(Result.Val, Info, E); 8192 if (Result.Failed) 8193 Result.Val = APValue(); 8194 } 8195 8196 void process(EvalResult &Result); 8197 8198 void enqueue(const Expr *E) { 8199 E = E->IgnoreParens(); 8200 Queue.resize(Queue.size()+1); 8201 Queue.back().E = E; 8202 Queue.back().Kind = Job::AnyExprKind; 8203 } 8204 }; 8205 8206 } 8207 8208 bool DataRecursiveIntBinOpEvaluator:: 8209 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8210 bool &SuppressRHSDiags) { 8211 if (E->getOpcode() == BO_Comma) { 8212 // Ignore LHS but note if we could not evaluate it. 8213 if (LHSResult.Failed) 8214 return Info.noteSideEffect(); 8215 return true; 8216 } 8217 8218 if (E->isLogicalOp()) { 8219 bool LHSAsBool; 8220 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 8221 // We were able to evaluate the LHS, see if we can get away with not 8222 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 8223 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 8224 Success(LHSAsBool, E, LHSResult.Val); 8225 return false; // Ignore RHS 8226 } 8227 } else { 8228 LHSResult.Failed = true; 8229 8230 // Since we weren't able to evaluate the left hand side, it 8231 // might have had side effects. 8232 if (!Info.noteSideEffect()) 8233 return false; 8234 8235 // We can't evaluate the LHS; however, sometimes the result 8236 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8237 // Don't ignore RHS and suppress diagnostics from this arm. 8238 SuppressRHSDiags = true; 8239 } 8240 8241 return true; 8242 } 8243 8244 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8245 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8246 8247 if (LHSResult.Failed && !Info.noteFailure()) 8248 return false; // Ignore RHS; 8249 8250 return true; 8251 } 8252 8253 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 8254 bool IsSub) { 8255 // Compute the new offset in the appropriate width, wrapping at 64 bits. 8256 // FIXME: When compiling for a 32-bit target, we should use 32-bit 8257 // offsets. 8258 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 8259 CharUnits &Offset = LVal.getLValueOffset(); 8260 uint64_t Offset64 = Offset.getQuantity(); 8261 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 8262 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 8263 : Offset64 + Index64); 8264 } 8265 8266 bool DataRecursiveIntBinOpEvaluator:: 8267 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8268 const BinaryOperator *E, APValue &Result) { 8269 if (E->getOpcode() == BO_Comma) { 8270 if (RHSResult.Failed) 8271 return false; 8272 Result = RHSResult.Val; 8273 return true; 8274 } 8275 8276 if (E->isLogicalOp()) { 8277 bool lhsResult, rhsResult; 8278 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 8279 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 8280 8281 if (LHSIsOK) { 8282 if (RHSIsOK) { 8283 if (E->getOpcode() == BO_LOr) 8284 return Success(lhsResult || rhsResult, E, Result); 8285 else 8286 return Success(lhsResult && rhsResult, E, Result); 8287 } 8288 } else { 8289 if (RHSIsOK) { 8290 // We can't evaluate the LHS; however, sometimes the result 8291 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8292 if (rhsResult == (E->getOpcode() == BO_LOr)) 8293 return Success(rhsResult, E, Result); 8294 } 8295 } 8296 8297 return false; 8298 } 8299 8300 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8301 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8302 8303 if (LHSResult.Failed || RHSResult.Failed) 8304 return false; 8305 8306 const APValue &LHSVal = LHSResult.Val; 8307 const APValue &RHSVal = RHSResult.Val; 8308 8309 // Handle cases like (unsigned long)&a + 4. 8310 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 8311 Result = LHSVal; 8312 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 8313 return true; 8314 } 8315 8316 // Handle cases like 4 + (unsigned long)&a 8317 if (E->getOpcode() == BO_Add && 8318 RHSVal.isLValue() && LHSVal.isInt()) { 8319 Result = RHSVal; 8320 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 8321 return true; 8322 } 8323 8324 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 8325 // Handle (intptr_t)&&A - (intptr_t)&&B. 8326 if (!LHSVal.getLValueOffset().isZero() || 8327 !RHSVal.getLValueOffset().isZero()) 8328 return false; 8329 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 8330 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 8331 if (!LHSExpr || !RHSExpr) 8332 return false; 8333 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8334 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8335 if (!LHSAddrExpr || !RHSAddrExpr) 8336 return false; 8337 // Make sure both labels come from the same function. 8338 if (LHSAddrExpr->getLabel()->getDeclContext() != 8339 RHSAddrExpr->getLabel()->getDeclContext()) 8340 return false; 8341 Result = APValue(LHSAddrExpr, RHSAddrExpr); 8342 return true; 8343 } 8344 8345 // All the remaining cases expect both operands to be an integer 8346 if (!LHSVal.isInt() || !RHSVal.isInt()) 8347 return Error(E); 8348 8349 // Set up the width and signedness manually, in case it can't be deduced 8350 // from the operation we're performing. 8351 // FIXME: Don't do this in the cases where we can deduce it. 8352 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 8353 E->getType()->isUnsignedIntegerOrEnumerationType()); 8354 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 8355 RHSVal.getInt(), Value)) 8356 return false; 8357 return Success(Value, E, Result); 8358 } 8359 8360 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 8361 Job &job = Queue.back(); 8362 8363 switch (job.Kind) { 8364 case Job::AnyExprKind: { 8365 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 8366 if (shouldEnqueue(Bop)) { 8367 job.Kind = Job::BinOpKind; 8368 enqueue(Bop->getLHS()); 8369 return; 8370 } 8371 } 8372 8373 EvaluateExpr(job.E, Result); 8374 Queue.pop_back(); 8375 return; 8376 } 8377 8378 case Job::BinOpKind: { 8379 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8380 bool SuppressRHSDiags = false; 8381 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 8382 Queue.pop_back(); 8383 return; 8384 } 8385 if (SuppressRHSDiags) 8386 job.startSpeculativeEval(Info); 8387 job.LHSResult.swap(Result); 8388 job.Kind = Job::BinOpVisitedLHSKind; 8389 enqueue(Bop->getRHS()); 8390 return; 8391 } 8392 8393 case Job::BinOpVisitedLHSKind: { 8394 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8395 EvalResult RHS; 8396 RHS.swap(Result); 8397 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 8398 Queue.pop_back(); 8399 return; 8400 } 8401 } 8402 8403 llvm_unreachable("Invalid Job::Kind!"); 8404 } 8405 8406 namespace { 8407 /// Used when we determine that we should fail, but can keep evaluating prior to 8408 /// noting that we had a failure. 8409 class DelayedNoteFailureRAII { 8410 EvalInfo &Info; 8411 bool NoteFailure; 8412 8413 public: 8414 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 8415 : Info(Info), NoteFailure(NoteFailure) {} 8416 ~DelayedNoteFailureRAII() { 8417 if (NoteFailure) { 8418 bool ContinueAfterFailure = Info.noteFailure(); 8419 (void)ContinueAfterFailure; 8420 assert(ContinueAfterFailure && 8421 "Shouldn't have kept evaluating on failure."); 8422 } 8423 } 8424 }; 8425 } 8426 8427 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8428 // We don't call noteFailure immediately because the assignment happens after 8429 // we evaluate LHS and RHS. 8430 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 8431 return Error(E); 8432 8433 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 8434 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 8435 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 8436 8437 QualType LHSTy = E->getLHS()->getType(); 8438 QualType RHSTy = E->getRHS()->getType(); 8439 8440 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 8441 ComplexValue LHS, RHS; 8442 bool LHSOK; 8443 if (E->isAssignmentOp()) { 8444 LValue LV; 8445 EvaluateLValue(E->getLHS(), LV, Info); 8446 LHSOK = false; 8447 } else if (LHSTy->isRealFloatingType()) { 8448 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 8449 if (LHSOK) { 8450 LHS.makeComplexFloat(); 8451 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 8452 } 8453 } else { 8454 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 8455 } 8456 if (!LHSOK && !Info.noteFailure()) 8457 return false; 8458 8459 if (E->getRHS()->getType()->isRealFloatingType()) { 8460 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 8461 return false; 8462 RHS.makeComplexFloat(); 8463 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 8464 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 8465 return false; 8466 8467 if (LHS.isComplexFloat()) { 8468 APFloat::cmpResult CR_r = 8469 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 8470 APFloat::cmpResult CR_i = 8471 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 8472 8473 if (E->getOpcode() == BO_EQ) 8474 return Success((CR_r == APFloat::cmpEqual && 8475 CR_i == APFloat::cmpEqual), E); 8476 else { 8477 assert(E->getOpcode() == BO_NE && 8478 "Invalid complex comparison."); 8479 return Success(((CR_r == APFloat::cmpGreaterThan || 8480 CR_r == APFloat::cmpLessThan || 8481 CR_r == APFloat::cmpUnordered) || 8482 (CR_i == APFloat::cmpGreaterThan || 8483 CR_i == APFloat::cmpLessThan || 8484 CR_i == APFloat::cmpUnordered)), E); 8485 } 8486 } else { 8487 if (E->getOpcode() == BO_EQ) 8488 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() && 8489 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E); 8490 else { 8491 assert(E->getOpcode() == BO_NE && 8492 "Invalid compex comparison."); 8493 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() || 8494 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E); 8495 } 8496 } 8497 } 8498 8499 if (LHSTy->isRealFloatingType() && 8500 RHSTy->isRealFloatingType()) { 8501 APFloat RHS(0.0), LHS(0.0); 8502 8503 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 8504 if (!LHSOK && !Info.noteFailure()) 8505 return false; 8506 8507 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 8508 return false; 8509 8510 APFloat::cmpResult CR = LHS.compare(RHS); 8511 8512 switch (E->getOpcode()) { 8513 default: 8514 llvm_unreachable("Invalid binary operator!"); 8515 case BO_LT: 8516 return Success(CR == APFloat::cmpLessThan, E); 8517 case BO_GT: 8518 return Success(CR == APFloat::cmpGreaterThan, E); 8519 case BO_LE: 8520 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); 8521 case BO_GE: 8522 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, 8523 E); 8524 case BO_EQ: 8525 return Success(CR == APFloat::cmpEqual, E); 8526 case BO_NE: 8527 return Success(CR == APFloat::cmpGreaterThan 8528 || CR == APFloat::cmpLessThan 8529 || CR == APFloat::cmpUnordered, E); 8530 } 8531 } 8532 8533 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 8534 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) { 8535 LValue LHSValue, RHSValue; 8536 8537 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 8538 if (!LHSOK && !Info.noteFailure()) 8539 return false; 8540 8541 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 8542 return false; 8543 8544 // Reject differing bases from the normal codepath; we special-case 8545 // comparisons to null. 8546 if (!HasSameBase(LHSValue, RHSValue)) { 8547 if (E->getOpcode() == BO_Sub) { 8548 // Handle &&A - &&B. 8549 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 8550 return Error(E); 8551 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>(); 8552 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>(); 8553 if (!LHSExpr || !RHSExpr) 8554 return Error(E); 8555 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8556 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8557 if (!LHSAddrExpr || !RHSAddrExpr) 8558 return Error(E); 8559 // Make sure both labels come from the same function. 8560 if (LHSAddrExpr->getLabel()->getDeclContext() != 8561 RHSAddrExpr->getLabel()->getDeclContext()) 8562 return Error(E); 8563 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 8564 } 8565 // Inequalities and subtractions between unrelated pointers have 8566 // unspecified or undefined behavior. 8567 if (!E->isEqualityOp()) 8568 return Error(E); 8569 // A constant address may compare equal to the address of a symbol. 8570 // The one exception is that address of an object cannot compare equal 8571 // to a null pointer constant. 8572 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 8573 (!RHSValue.Base && !RHSValue.Offset.isZero())) 8574 return Error(E); 8575 // It's implementation-defined whether distinct literals will have 8576 // distinct addresses. In clang, the result of such a comparison is 8577 // unspecified, so it is not a constant expression. However, we do know 8578 // that the address of a literal will be non-null. 8579 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 8580 LHSValue.Base && RHSValue.Base) 8581 return Error(E); 8582 // We can't tell whether weak symbols will end up pointing to the same 8583 // object. 8584 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 8585 return Error(E); 8586 // We can't compare the address of the start of one object with the 8587 // past-the-end address of another object, per C++ DR1652. 8588 if ((LHSValue.Base && LHSValue.Offset.isZero() && 8589 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 8590 (RHSValue.Base && RHSValue.Offset.isZero() && 8591 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 8592 return Error(E); 8593 // We can't tell whether an object is at the same address as another 8594 // zero sized object. 8595 if ((RHSValue.Base && isZeroSized(LHSValue)) || 8596 (LHSValue.Base && isZeroSized(RHSValue))) 8597 return Error(E); 8598 // Pointers with different bases cannot represent the same object. 8599 return Success(E->getOpcode() == BO_NE, E); 8600 } 8601 8602 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 8603 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 8604 8605 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 8606 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 8607 8608 if (E->getOpcode() == BO_Sub) { 8609 // C++11 [expr.add]p6: 8610 // Unless both pointers point to elements of the same array object, or 8611 // one past the last element of the array object, the behavior is 8612 // undefined. 8613 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 8614 !AreElementsOfSameArray(getType(LHSValue.Base), 8615 LHSDesignator, RHSDesignator)) 8616 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 8617 8618 QualType Type = E->getLHS()->getType(); 8619 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 8620 8621 CharUnits ElementSize; 8622 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 8623 return false; 8624 8625 // As an extension, a type may have zero size (empty struct or union in 8626 // C, array of zero length). Pointer subtraction in such cases has 8627 // undefined behavior, so is not constant. 8628 if (ElementSize.isZero()) { 8629 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 8630 << ElementType; 8631 return false; 8632 } 8633 8634 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 8635 // and produce incorrect results when it overflows. Such behavior 8636 // appears to be non-conforming, but is common, so perhaps we should 8637 // assume the standard intended for such cases to be undefined behavior 8638 // and check for them. 8639 8640 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 8641 // overflow in the final conversion to ptrdiff_t. 8642 APSInt LHS( 8643 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 8644 APSInt RHS( 8645 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 8646 APSInt ElemSize( 8647 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false); 8648 APSInt TrueResult = (LHS - RHS) / ElemSize; 8649 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 8650 8651 if (Result.extend(65) != TrueResult && 8652 !HandleOverflow(Info, E, TrueResult, E->getType())) 8653 return false; 8654 return Success(Result, E); 8655 } 8656 8657 // C++11 [expr.rel]p3: 8658 // Pointers to void (after pointer conversions) can be compared, with a 8659 // result defined as follows: If both pointers represent the same 8660 // address or are both the null pointer value, the result is true if the 8661 // operator is <= or >= and false otherwise; otherwise the result is 8662 // unspecified. 8663 // We interpret this as applying to pointers to *cv* void. 8664 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && 8665 E->isRelationalOp()) 8666 CCEDiag(E, diag::note_constexpr_void_comparison); 8667 8668 // C++11 [expr.rel]p2: 8669 // - If two pointers point to non-static data members of the same object, 8670 // or to subobjects or array elements fo such members, recursively, the 8671 // pointer to the later declared member compares greater provided the 8672 // two members have the same access control and provided their class is 8673 // not a union. 8674 // [...] 8675 // - Otherwise pointer comparisons are unspecified. 8676 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 8677 E->isRelationalOp()) { 8678 bool WasArrayIndex; 8679 unsigned Mismatch = 8680 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator, 8681 RHSDesignator, WasArrayIndex); 8682 // At the point where the designators diverge, the comparison has a 8683 // specified value if: 8684 // - we are comparing array indices 8685 // - we are comparing fields of a union, or fields with the same access 8686 // Otherwise, the result is unspecified and thus the comparison is not a 8687 // constant expression. 8688 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 8689 Mismatch < RHSDesignator.Entries.size()) { 8690 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 8691 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 8692 if (!LF && !RF) 8693 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 8694 else if (!LF) 8695 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 8696 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 8697 << RF->getParent() << RF; 8698 else if (!RF) 8699 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 8700 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 8701 << LF->getParent() << LF; 8702 else if (!LF->getParent()->isUnion() && 8703 LF->getAccess() != RF->getAccess()) 8704 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access) 8705 << LF << LF->getAccess() << RF << RF->getAccess() 8706 << LF->getParent(); 8707 } 8708 } 8709 8710 // The comparison here must be unsigned, and performed with the same 8711 // width as the pointer. 8712 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 8713 uint64_t CompareLHS = LHSOffset.getQuantity(); 8714 uint64_t CompareRHS = RHSOffset.getQuantity(); 8715 assert(PtrSize <= 64 && "Unexpected pointer width"); 8716 uint64_t Mask = ~0ULL >> (64 - PtrSize); 8717 CompareLHS &= Mask; 8718 CompareRHS &= Mask; 8719 8720 // If there is a base and this is a relational operator, we can only 8721 // compare pointers within the object in question; otherwise, the result 8722 // depends on where the object is located in memory. 8723 if (!LHSValue.Base.isNull() && E->isRelationalOp()) { 8724 QualType BaseTy = getType(LHSValue.Base); 8725 if (BaseTy->isIncompleteType()) 8726 return Error(E); 8727 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 8728 uint64_t OffsetLimit = Size.getQuantity(); 8729 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 8730 return Error(E); 8731 } 8732 8733 switch (E->getOpcode()) { 8734 default: llvm_unreachable("missing comparison operator"); 8735 case BO_LT: return Success(CompareLHS < CompareRHS, E); 8736 case BO_GT: return Success(CompareLHS > CompareRHS, E); 8737 case BO_LE: return Success(CompareLHS <= CompareRHS, E); 8738 case BO_GE: return Success(CompareLHS >= CompareRHS, E); 8739 case BO_EQ: return Success(CompareLHS == CompareRHS, E); 8740 case BO_NE: return Success(CompareLHS != CompareRHS, E); 8741 } 8742 } 8743 } 8744 8745 if (LHSTy->isMemberPointerType()) { 8746 assert(E->isEqualityOp() && "unexpected member pointer operation"); 8747 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 8748 8749 MemberPtr LHSValue, RHSValue; 8750 8751 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 8752 if (!LHSOK && !Info.noteFailure()) 8753 return false; 8754 8755 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 8756 return false; 8757 8758 // C++11 [expr.eq]p2: 8759 // If both operands are null, they compare equal. Otherwise if only one is 8760 // null, they compare unequal. 8761 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 8762 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 8763 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 8764 } 8765 8766 // Otherwise if either is a pointer to a virtual member function, the 8767 // result is unspecified. 8768 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 8769 if (MD->isVirtual()) 8770 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 8771 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 8772 if (MD->isVirtual()) 8773 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 8774 8775 // Otherwise they compare equal if and only if they would refer to the 8776 // same member of the same most derived object or the same subobject if 8777 // they were dereferenced with a hypothetical object of the associated 8778 // class type. 8779 bool Equal = LHSValue == RHSValue; 8780 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 8781 } 8782 8783 if (LHSTy->isNullPtrType()) { 8784 assert(E->isComparisonOp() && "unexpected nullptr operation"); 8785 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 8786 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 8787 // are compared, the result is true of the operator is <=, >= or ==, and 8788 // false otherwise. 8789 BinaryOperator::Opcode Opcode = E->getOpcode(); 8790 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E); 8791 } 8792 8793 assert((!LHSTy->isIntegralOrEnumerationType() || 8794 !RHSTy->isIntegralOrEnumerationType()) && 8795 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 8796 // We can't continue from here for non-integral types. 8797 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8798 } 8799 8800 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 8801 /// a result as the expression's type. 8802 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 8803 const UnaryExprOrTypeTraitExpr *E) { 8804 switch(E->getKind()) { 8805 case UETT_AlignOf: { 8806 if (E->isArgumentType()) 8807 return Success(GetAlignOfType(Info, E->getArgumentType()), E); 8808 else 8809 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E); 8810 } 8811 8812 case UETT_VecStep: { 8813 QualType Ty = E->getTypeOfArgument(); 8814 8815 if (Ty->isVectorType()) { 8816 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 8817 8818 // The vec_step built-in functions that take a 3-component 8819 // vector return 4. (OpenCL 1.1 spec 6.11.12) 8820 if (n == 3) 8821 n = 4; 8822 8823 return Success(n, E); 8824 } else 8825 return Success(1, E); 8826 } 8827 8828 case UETT_SizeOf: { 8829 QualType SrcTy = E->getTypeOfArgument(); 8830 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 8831 // the result is the size of the referenced type." 8832 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 8833 SrcTy = Ref->getPointeeType(); 8834 8835 CharUnits Sizeof; 8836 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 8837 return false; 8838 return Success(Sizeof, E); 8839 } 8840 case UETT_OpenMPRequiredSimdAlign: 8841 assert(E->isArgumentType()); 8842 return Success( 8843 Info.Ctx.toCharUnitsFromBits( 8844 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 8845 .getQuantity(), 8846 E); 8847 } 8848 8849 llvm_unreachable("unknown expr/type trait"); 8850 } 8851 8852 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 8853 CharUnits Result; 8854 unsigned n = OOE->getNumComponents(); 8855 if (n == 0) 8856 return Error(OOE); 8857 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 8858 for (unsigned i = 0; i != n; ++i) { 8859 OffsetOfNode ON = OOE->getComponent(i); 8860 switch (ON.getKind()) { 8861 case OffsetOfNode::Array: { 8862 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 8863 APSInt IdxResult; 8864 if (!EvaluateInteger(Idx, IdxResult, Info)) 8865 return false; 8866 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 8867 if (!AT) 8868 return Error(OOE); 8869 CurrentType = AT->getElementType(); 8870 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 8871 Result += IdxResult.getSExtValue() * ElementSize; 8872 break; 8873 } 8874 8875 case OffsetOfNode::Field: { 8876 FieldDecl *MemberDecl = ON.getField(); 8877 const RecordType *RT = CurrentType->getAs<RecordType>(); 8878 if (!RT) 8879 return Error(OOE); 8880 RecordDecl *RD = RT->getDecl(); 8881 if (RD->isInvalidDecl()) return false; 8882 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 8883 unsigned i = MemberDecl->getFieldIndex(); 8884 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 8885 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 8886 CurrentType = MemberDecl->getType().getNonReferenceType(); 8887 break; 8888 } 8889 8890 case OffsetOfNode::Identifier: 8891 llvm_unreachable("dependent __builtin_offsetof"); 8892 8893 case OffsetOfNode::Base: { 8894 CXXBaseSpecifier *BaseSpec = ON.getBase(); 8895 if (BaseSpec->isVirtual()) 8896 return Error(OOE); 8897 8898 // Find the layout of the class whose base we are looking into. 8899 const RecordType *RT = CurrentType->getAs<RecordType>(); 8900 if (!RT) 8901 return Error(OOE); 8902 RecordDecl *RD = RT->getDecl(); 8903 if (RD->isInvalidDecl()) return false; 8904 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 8905 8906 // Find the base class itself. 8907 CurrentType = BaseSpec->getType(); 8908 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 8909 if (!BaseRT) 8910 return Error(OOE); 8911 8912 // Add the offset to the base. 8913 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 8914 break; 8915 } 8916 } 8917 } 8918 return Success(Result, OOE); 8919 } 8920 8921 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 8922 switch (E->getOpcode()) { 8923 default: 8924 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 8925 // See C99 6.6p3. 8926 return Error(E); 8927 case UO_Extension: 8928 // FIXME: Should extension allow i-c-e extension expressions in its scope? 8929 // If so, we could clear the diagnostic ID. 8930 return Visit(E->getSubExpr()); 8931 case UO_Plus: 8932 // The result is just the value. 8933 return Visit(E->getSubExpr()); 8934 case UO_Minus: { 8935 if (!Visit(E->getSubExpr())) 8936 return false; 8937 if (!Result.isInt()) return Error(E); 8938 const APSInt &Value = Result.getInt(); 8939 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 8940 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 8941 E->getType())) 8942 return false; 8943 return Success(-Value, E); 8944 } 8945 case UO_Not: { 8946 if (!Visit(E->getSubExpr())) 8947 return false; 8948 if (!Result.isInt()) return Error(E); 8949 return Success(~Result.getInt(), E); 8950 } 8951 case UO_LNot: { 8952 bool bres; 8953 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 8954 return false; 8955 return Success(!bres, E); 8956 } 8957 } 8958 } 8959 8960 /// HandleCast - This is used to evaluate implicit or explicit casts where the 8961 /// result type is integer. 8962 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 8963 const Expr *SubExpr = E->getSubExpr(); 8964 QualType DestType = E->getType(); 8965 QualType SrcType = SubExpr->getType(); 8966 8967 switch (E->getCastKind()) { 8968 case CK_BaseToDerived: 8969 case CK_DerivedToBase: 8970 case CK_UncheckedDerivedToBase: 8971 case CK_Dynamic: 8972 case CK_ToUnion: 8973 case CK_ArrayToPointerDecay: 8974 case CK_FunctionToPointerDecay: 8975 case CK_NullToPointer: 8976 case CK_NullToMemberPointer: 8977 case CK_BaseToDerivedMemberPointer: 8978 case CK_DerivedToBaseMemberPointer: 8979 case CK_ReinterpretMemberPointer: 8980 case CK_ConstructorConversion: 8981 case CK_IntegralToPointer: 8982 case CK_ToVoid: 8983 case CK_VectorSplat: 8984 case CK_IntegralToFloating: 8985 case CK_FloatingCast: 8986 case CK_CPointerToObjCPointerCast: 8987 case CK_BlockPointerToObjCPointerCast: 8988 case CK_AnyPointerToBlockPointerCast: 8989 case CK_ObjCObjectLValueCast: 8990 case CK_FloatingRealToComplex: 8991 case CK_FloatingComplexToReal: 8992 case CK_FloatingComplexCast: 8993 case CK_FloatingComplexToIntegralComplex: 8994 case CK_IntegralRealToComplex: 8995 case CK_IntegralComplexCast: 8996 case CK_IntegralComplexToFloatingComplex: 8997 case CK_BuiltinFnToFnPtr: 8998 case CK_ZeroToOCLEvent: 8999 case CK_ZeroToOCLQueue: 9000 case CK_NonAtomicToAtomic: 9001 case CK_AddressSpaceConversion: 9002 case CK_IntToOCLSampler: 9003 llvm_unreachable("invalid cast kind for integral value"); 9004 9005 case CK_BitCast: 9006 case CK_Dependent: 9007 case CK_LValueBitCast: 9008 case CK_ARCProduceObject: 9009 case CK_ARCConsumeObject: 9010 case CK_ARCReclaimReturnedObject: 9011 case CK_ARCExtendBlockObject: 9012 case CK_CopyAndAutoreleaseBlockObject: 9013 return Error(E); 9014 9015 case CK_UserDefinedConversion: 9016 case CK_LValueToRValue: 9017 case CK_AtomicToNonAtomic: 9018 case CK_NoOp: 9019 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9020 9021 case CK_MemberPointerToBoolean: 9022 case CK_PointerToBoolean: 9023 case CK_IntegralToBoolean: 9024 case CK_FloatingToBoolean: 9025 case CK_BooleanToSignedIntegral: 9026 case CK_FloatingComplexToBoolean: 9027 case CK_IntegralComplexToBoolean: { 9028 bool BoolResult; 9029 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 9030 return false; 9031 uint64_t IntResult = BoolResult; 9032 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 9033 IntResult = (uint64_t)-1; 9034 return Success(IntResult, E); 9035 } 9036 9037 case CK_IntegralCast: { 9038 if (!Visit(SubExpr)) 9039 return false; 9040 9041 if (!Result.isInt()) { 9042 // Allow casts of address-of-label differences if they are no-ops 9043 // or narrowing. (The narrowing case isn't actually guaranteed to 9044 // be constant-evaluatable except in some narrow cases which are hard 9045 // to detect here. We let it through on the assumption the user knows 9046 // what they are doing.) 9047 if (Result.isAddrLabelDiff()) 9048 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 9049 // Only allow casts of lvalues if they are lossless. 9050 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 9051 } 9052 9053 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 9054 Result.getInt()), E); 9055 } 9056 9057 case CK_PointerToIntegral: { 9058 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 9059 9060 LValue LV; 9061 if (!EvaluatePointer(SubExpr, LV, Info)) 9062 return false; 9063 9064 if (LV.getLValueBase()) { 9065 // Only allow based lvalue casts if they are lossless. 9066 // FIXME: Allow a larger integer size than the pointer size, and allow 9067 // narrowing back down to pointer width in subsequent integral casts. 9068 // FIXME: Check integer type's active bits, not its type size. 9069 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 9070 return Error(E); 9071 9072 LV.Designator.setInvalid(); 9073 LV.moveInto(Result); 9074 return true; 9075 } 9076 9077 uint64_t V; 9078 if (LV.isNullPointer()) 9079 V = Info.Ctx.getTargetNullPointerValue(SrcType); 9080 else 9081 V = LV.getLValueOffset().getQuantity(); 9082 9083 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType); 9084 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 9085 } 9086 9087 case CK_IntegralComplexToReal: { 9088 ComplexValue C; 9089 if (!EvaluateComplex(SubExpr, C, Info)) 9090 return false; 9091 return Success(C.getComplexIntReal(), E); 9092 } 9093 9094 case CK_FloatingToIntegral: { 9095 APFloat F(0.0); 9096 if (!EvaluateFloat(SubExpr, F, Info)) 9097 return false; 9098 9099 APSInt Value; 9100 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 9101 return false; 9102 return Success(Value, E); 9103 } 9104 } 9105 9106 llvm_unreachable("unknown cast resulting in integral value"); 9107 } 9108 9109 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9110 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9111 ComplexValue LV; 9112 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9113 return false; 9114 if (!LV.isComplexInt()) 9115 return Error(E); 9116 return Success(LV.getComplexIntReal(), E); 9117 } 9118 9119 return Visit(E->getSubExpr()); 9120 } 9121 9122 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9123 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 9124 ComplexValue LV; 9125 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9126 return false; 9127 if (!LV.isComplexInt()) 9128 return Error(E); 9129 return Success(LV.getComplexIntImag(), E); 9130 } 9131 9132 VisitIgnoredValue(E->getSubExpr()); 9133 return Success(0, E); 9134 } 9135 9136 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 9137 return Success(E->getPackLength(), E); 9138 } 9139 9140 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 9141 return Success(E->getValue(), E); 9142 } 9143 9144 //===----------------------------------------------------------------------===// 9145 // Float Evaluation 9146 //===----------------------------------------------------------------------===// 9147 9148 namespace { 9149 class FloatExprEvaluator 9150 : public ExprEvaluatorBase<FloatExprEvaluator> { 9151 APFloat &Result; 9152 public: 9153 FloatExprEvaluator(EvalInfo &info, APFloat &result) 9154 : ExprEvaluatorBaseTy(info), Result(result) {} 9155 9156 bool Success(const APValue &V, const Expr *e) { 9157 Result = V.getFloat(); 9158 return true; 9159 } 9160 9161 bool ZeroInitialization(const Expr *E) { 9162 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 9163 return true; 9164 } 9165 9166 bool VisitCallExpr(const CallExpr *E); 9167 9168 bool VisitUnaryOperator(const UnaryOperator *E); 9169 bool VisitBinaryOperator(const BinaryOperator *E); 9170 bool VisitFloatingLiteral(const FloatingLiteral *E); 9171 bool VisitCastExpr(const CastExpr *E); 9172 9173 bool VisitUnaryReal(const UnaryOperator *E); 9174 bool VisitUnaryImag(const UnaryOperator *E); 9175 9176 // FIXME: Missing: array subscript of vector, member of vector 9177 }; 9178 } // end anonymous namespace 9179 9180 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 9181 assert(E->isRValue() && E->getType()->isRealFloatingType()); 9182 return FloatExprEvaluator(Info, Result).Visit(E); 9183 } 9184 9185 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 9186 QualType ResultTy, 9187 const Expr *Arg, 9188 bool SNaN, 9189 llvm::APFloat &Result) { 9190 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 9191 if (!S) return false; 9192 9193 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 9194 9195 llvm::APInt fill; 9196 9197 // Treat empty strings as if they were zero. 9198 if (S->getString().empty()) 9199 fill = llvm::APInt(32, 0); 9200 else if (S->getString().getAsInteger(0, fill)) 9201 return false; 9202 9203 if (Context.getTargetInfo().isNan2008()) { 9204 if (SNaN) 9205 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9206 else 9207 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9208 } else { 9209 // Prior to IEEE 754-2008, architectures were allowed to choose whether 9210 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 9211 // a different encoding to what became a standard in 2008, and for pre- 9212 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 9213 // sNaN. This is now known as "legacy NaN" encoding. 9214 if (SNaN) 9215 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9216 else 9217 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9218 } 9219 9220 return true; 9221 } 9222 9223 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 9224 switch (E->getBuiltinCallee()) { 9225 default: 9226 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9227 9228 case Builtin::BI__builtin_huge_val: 9229 case Builtin::BI__builtin_huge_valf: 9230 case Builtin::BI__builtin_huge_vall: 9231 case Builtin::BI__builtin_huge_valf128: 9232 case Builtin::BI__builtin_inf: 9233 case Builtin::BI__builtin_inff: 9234 case Builtin::BI__builtin_infl: 9235 case Builtin::BI__builtin_inff128: { 9236 const llvm::fltSemantics &Sem = 9237 Info.Ctx.getFloatTypeSemantics(E->getType()); 9238 Result = llvm::APFloat::getInf(Sem); 9239 return true; 9240 } 9241 9242 case Builtin::BI__builtin_nans: 9243 case Builtin::BI__builtin_nansf: 9244 case Builtin::BI__builtin_nansl: 9245 case Builtin::BI__builtin_nansf128: 9246 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9247 true, Result)) 9248 return Error(E); 9249 return true; 9250 9251 case Builtin::BI__builtin_nan: 9252 case Builtin::BI__builtin_nanf: 9253 case Builtin::BI__builtin_nanl: 9254 case Builtin::BI__builtin_nanf128: 9255 // If this is __builtin_nan() turn this into a nan, otherwise we 9256 // can't constant fold it. 9257 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9258 false, Result)) 9259 return Error(E); 9260 return true; 9261 9262 case Builtin::BI__builtin_fabs: 9263 case Builtin::BI__builtin_fabsf: 9264 case Builtin::BI__builtin_fabsl: 9265 case Builtin::BI__builtin_fabsf128: 9266 if (!EvaluateFloat(E->getArg(0), Result, Info)) 9267 return false; 9268 9269 if (Result.isNegative()) 9270 Result.changeSign(); 9271 return true; 9272 9273 // FIXME: Builtin::BI__builtin_powi 9274 // FIXME: Builtin::BI__builtin_powif 9275 // FIXME: Builtin::BI__builtin_powil 9276 9277 case Builtin::BI__builtin_copysign: 9278 case Builtin::BI__builtin_copysignf: 9279 case Builtin::BI__builtin_copysignl: 9280 case Builtin::BI__builtin_copysignf128: { 9281 APFloat RHS(0.); 9282 if (!EvaluateFloat(E->getArg(0), Result, Info) || 9283 !EvaluateFloat(E->getArg(1), RHS, Info)) 9284 return false; 9285 Result.copySign(RHS); 9286 return true; 9287 } 9288 } 9289 } 9290 9291 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9292 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9293 ComplexValue CV; 9294 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9295 return false; 9296 Result = CV.FloatReal; 9297 return true; 9298 } 9299 9300 return Visit(E->getSubExpr()); 9301 } 9302 9303 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9304 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9305 ComplexValue CV; 9306 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9307 return false; 9308 Result = CV.FloatImag; 9309 return true; 9310 } 9311 9312 VisitIgnoredValue(E->getSubExpr()); 9313 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 9314 Result = llvm::APFloat::getZero(Sem); 9315 return true; 9316 } 9317 9318 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9319 switch (E->getOpcode()) { 9320 default: return Error(E); 9321 case UO_Plus: 9322 return EvaluateFloat(E->getSubExpr(), Result, Info); 9323 case UO_Minus: 9324 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 9325 return false; 9326 Result.changeSign(); 9327 return true; 9328 } 9329 } 9330 9331 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9332 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9333 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9334 9335 APFloat RHS(0.0); 9336 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 9337 if (!LHSOK && !Info.noteFailure()) 9338 return false; 9339 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 9340 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 9341 } 9342 9343 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 9344 Result = E->getValue(); 9345 return true; 9346 } 9347 9348 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 9349 const Expr* SubExpr = E->getSubExpr(); 9350 9351 switch (E->getCastKind()) { 9352 default: 9353 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9354 9355 case CK_IntegralToFloating: { 9356 APSInt IntResult; 9357 return EvaluateInteger(SubExpr, IntResult, Info) && 9358 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 9359 E->getType(), Result); 9360 } 9361 9362 case CK_FloatingCast: { 9363 if (!Visit(SubExpr)) 9364 return false; 9365 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 9366 Result); 9367 } 9368 9369 case CK_FloatingComplexToReal: { 9370 ComplexValue V; 9371 if (!EvaluateComplex(SubExpr, V, Info)) 9372 return false; 9373 Result = V.getComplexFloatReal(); 9374 return true; 9375 } 9376 } 9377 } 9378 9379 //===----------------------------------------------------------------------===// 9380 // Complex Evaluation (for float and integer) 9381 //===----------------------------------------------------------------------===// 9382 9383 namespace { 9384 class ComplexExprEvaluator 9385 : public ExprEvaluatorBase<ComplexExprEvaluator> { 9386 ComplexValue &Result; 9387 9388 public: 9389 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 9390 : ExprEvaluatorBaseTy(info), Result(Result) {} 9391 9392 bool Success(const APValue &V, const Expr *e) { 9393 Result.setFrom(V); 9394 return true; 9395 } 9396 9397 bool ZeroInitialization(const Expr *E); 9398 9399 //===--------------------------------------------------------------------===// 9400 // Visitor Methods 9401 //===--------------------------------------------------------------------===// 9402 9403 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 9404 bool VisitCastExpr(const CastExpr *E); 9405 bool VisitBinaryOperator(const BinaryOperator *E); 9406 bool VisitUnaryOperator(const UnaryOperator *E); 9407 bool VisitInitListExpr(const InitListExpr *E); 9408 }; 9409 } // end anonymous namespace 9410 9411 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 9412 EvalInfo &Info) { 9413 assert(E->isRValue() && E->getType()->isAnyComplexType()); 9414 return ComplexExprEvaluator(Info, Result).Visit(E); 9415 } 9416 9417 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 9418 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 9419 if (ElemTy->isRealFloatingType()) { 9420 Result.makeComplexFloat(); 9421 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 9422 Result.FloatReal = Zero; 9423 Result.FloatImag = Zero; 9424 } else { 9425 Result.makeComplexInt(); 9426 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 9427 Result.IntReal = Zero; 9428 Result.IntImag = Zero; 9429 } 9430 return true; 9431 } 9432 9433 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 9434 const Expr* SubExpr = E->getSubExpr(); 9435 9436 if (SubExpr->getType()->isRealFloatingType()) { 9437 Result.makeComplexFloat(); 9438 APFloat &Imag = Result.FloatImag; 9439 if (!EvaluateFloat(SubExpr, Imag, Info)) 9440 return false; 9441 9442 Result.FloatReal = APFloat(Imag.getSemantics()); 9443 return true; 9444 } else { 9445 assert(SubExpr->getType()->isIntegerType() && 9446 "Unexpected imaginary literal."); 9447 9448 Result.makeComplexInt(); 9449 APSInt &Imag = Result.IntImag; 9450 if (!EvaluateInteger(SubExpr, Imag, Info)) 9451 return false; 9452 9453 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 9454 return true; 9455 } 9456 } 9457 9458 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 9459 9460 switch (E->getCastKind()) { 9461 case CK_BitCast: 9462 case CK_BaseToDerived: 9463 case CK_DerivedToBase: 9464 case CK_UncheckedDerivedToBase: 9465 case CK_Dynamic: 9466 case CK_ToUnion: 9467 case CK_ArrayToPointerDecay: 9468 case CK_FunctionToPointerDecay: 9469 case CK_NullToPointer: 9470 case CK_NullToMemberPointer: 9471 case CK_BaseToDerivedMemberPointer: 9472 case CK_DerivedToBaseMemberPointer: 9473 case CK_MemberPointerToBoolean: 9474 case CK_ReinterpretMemberPointer: 9475 case CK_ConstructorConversion: 9476 case CK_IntegralToPointer: 9477 case CK_PointerToIntegral: 9478 case CK_PointerToBoolean: 9479 case CK_ToVoid: 9480 case CK_VectorSplat: 9481 case CK_IntegralCast: 9482 case CK_BooleanToSignedIntegral: 9483 case CK_IntegralToBoolean: 9484 case CK_IntegralToFloating: 9485 case CK_FloatingToIntegral: 9486 case CK_FloatingToBoolean: 9487 case CK_FloatingCast: 9488 case CK_CPointerToObjCPointerCast: 9489 case CK_BlockPointerToObjCPointerCast: 9490 case CK_AnyPointerToBlockPointerCast: 9491 case CK_ObjCObjectLValueCast: 9492 case CK_FloatingComplexToReal: 9493 case CK_FloatingComplexToBoolean: 9494 case CK_IntegralComplexToReal: 9495 case CK_IntegralComplexToBoolean: 9496 case CK_ARCProduceObject: 9497 case CK_ARCConsumeObject: 9498 case CK_ARCReclaimReturnedObject: 9499 case CK_ARCExtendBlockObject: 9500 case CK_CopyAndAutoreleaseBlockObject: 9501 case CK_BuiltinFnToFnPtr: 9502 case CK_ZeroToOCLEvent: 9503 case CK_ZeroToOCLQueue: 9504 case CK_NonAtomicToAtomic: 9505 case CK_AddressSpaceConversion: 9506 case CK_IntToOCLSampler: 9507 llvm_unreachable("invalid cast kind for complex value"); 9508 9509 case CK_LValueToRValue: 9510 case CK_AtomicToNonAtomic: 9511 case CK_NoOp: 9512 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9513 9514 case CK_Dependent: 9515 case CK_LValueBitCast: 9516 case CK_UserDefinedConversion: 9517 return Error(E); 9518 9519 case CK_FloatingRealToComplex: { 9520 APFloat &Real = Result.FloatReal; 9521 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 9522 return false; 9523 9524 Result.makeComplexFloat(); 9525 Result.FloatImag = APFloat(Real.getSemantics()); 9526 return true; 9527 } 9528 9529 case CK_FloatingComplexCast: { 9530 if (!Visit(E->getSubExpr())) 9531 return false; 9532 9533 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 9534 QualType From 9535 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 9536 9537 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 9538 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 9539 } 9540 9541 case CK_FloatingComplexToIntegralComplex: { 9542 if (!Visit(E->getSubExpr())) 9543 return false; 9544 9545 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 9546 QualType From 9547 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 9548 Result.makeComplexInt(); 9549 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 9550 To, Result.IntReal) && 9551 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 9552 To, Result.IntImag); 9553 } 9554 9555 case CK_IntegralRealToComplex: { 9556 APSInt &Real = Result.IntReal; 9557 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 9558 return false; 9559 9560 Result.makeComplexInt(); 9561 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 9562 return true; 9563 } 9564 9565 case CK_IntegralComplexCast: { 9566 if (!Visit(E->getSubExpr())) 9567 return false; 9568 9569 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 9570 QualType From 9571 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 9572 9573 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 9574 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 9575 return true; 9576 } 9577 9578 case CK_IntegralComplexToFloatingComplex: { 9579 if (!Visit(E->getSubExpr())) 9580 return false; 9581 9582 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 9583 QualType From 9584 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 9585 Result.makeComplexFloat(); 9586 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 9587 To, Result.FloatReal) && 9588 HandleIntToFloatCast(Info, E, From, Result.IntImag, 9589 To, Result.FloatImag); 9590 } 9591 } 9592 9593 llvm_unreachable("unknown cast resulting in complex value"); 9594 } 9595 9596 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9597 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9598 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9599 9600 // Track whether the LHS or RHS is real at the type system level. When this is 9601 // the case we can simplify our evaluation strategy. 9602 bool LHSReal = false, RHSReal = false; 9603 9604 bool LHSOK; 9605 if (E->getLHS()->getType()->isRealFloatingType()) { 9606 LHSReal = true; 9607 APFloat &Real = Result.FloatReal; 9608 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 9609 if (LHSOK) { 9610 Result.makeComplexFloat(); 9611 Result.FloatImag = APFloat(Real.getSemantics()); 9612 } 9613 } else { 9614 LHSOK = Visit(E->getLHS()); 9615 } 9616 if (!LHSOK && !Info.noteFailure()) 9617 return false; 9618 9619 ComplexValue RHS; 9620 if (E->getRHS()->getType()->isRealFloatingType()) { 9621 RHSReal = true; 9622 APFloat &Real = RHS.FloatReal; 9623 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 9624 return false; 9625 RHS.makeComplexFloat(); 9626 RHS.FloatImag = APFloat(Real.getSemantics()); 9627 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 9628 return false; 9629 9630 assert(!(LHSReal && RHSReal) && 9631 "Cannot have both operands of a complex operation be real."); 9632 switch (E->getOpcode()) { 9633 default: return Error(E); 9634 case BO_Add: 9635 if (Result.isComplexFloat()) { 9636 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 9637 APFloat::rmNearestTiesToEven); 9638 if (LHSReal) 9639 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 9640 else if (!RHSReal) 9641 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 9642 APFloat::rmNearestTiesToEven); 9643 } else { 9644 Result.getComplexIntReal() += RHS.getComplexIntReal(); 9645 Result.getComplexIntImag() += RHS.getComplexIntImag(); 9646 } 9647 break; 9648 case BO_Sub: 9649 if (Result.isComplexFloat()) { 9650 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 9651 APFloat::rmNearestTiesToEven); 9652 if (LHSReal) { 9653 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 9654 Result.getComplexFloatImag().changeSign(); 9655 } else if (!RHSReal) { 9656 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 9657 APFloat::rmNearestTiesToEven); 9658 } 9659 } else { 9660 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 9661 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 9662 } 9663 break; 9664 case BO_Mul: 9665 if (Result.isComplexFloat()) { 9666 // This is an implementation of complex multiplication according to the 9667 // constraints laid out in C11 Annex G. The implemention uses the 9668 // following naming scheme: 9669 // (a + ib) * (c + id) 9670 ComplexValue LHS = Result; 9671 APFloat &A = LHS.getComplexFloatReal(); 9672 APFloat &B = LHS.getComplexFloatImag(); 9673 APFloat &C = RHS.getComplexFloatReal(); 9674 APFloat &D = RHS.getComplexFloatImag(); 9675 APFloat &ResR = Result.getComplexFloatReal(); 9676 APFloat &ResI = Result.getComplexFloatImag(); 9677 if (LHSReal) { 9678 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 9679 ResR = A * C; 9680 ResI = A * D; 9681 } else if (RHSReal) { 9682 ResR = C * A; 9683 ResI = C * B; 9684 } else { 9685 // In the fully general case, we need to handle NaNs and infinities 9686 // robustly. 9687 APFloat AC = A * C; 9688 APFloat BD = B * D; 9689 APFloat AD = A * D; 9690 APFloat BC = B * C; 9691 ResR = AC - BD; 9692 ResI = AD + BC; 9693 if (ResR.isNaN() && ResI.isNaN()) { 9694 bool Recalc = false; 9695 if (A.isInfinity() || B.isInfinity()) { 9696 A = APFloat::copySign( 9697 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 9698 B = APFloat::copySign( 9699 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 9700 if (C.isNaN()) 9701 C = APFloat::copySign(APFloat(C.getSemantics()), C); 9702 if (D.isNaN()) 9703 D = APFloat::copySign(APFloat(D.getSemantics()), D); 9704 Recalc = true; 9705 } 9706 if (C.isInfinity() || D.isInfinity()) { 9707 C = APFloat::copySign( 9708 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 9709 D = APFloat::copySign( 9710 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 9711 if (A.isNaN()) 9712 A = APFloat::copySign(APFloat(A.getSemantics()), A); 9713 if (B.isNaN()) 9714 B = APFloat::copySign(APFloat(B.getSemantics()), B); 9715 Recalc = true; 9716 } 9717 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 9718 AD.isInfinity() || BC.isInfinity())) { 9719 if (A.isNaN()) 9720 A = APFloat::copySign(APFloat(A.getSemantics()), A); 9721 if (B.isNaN()) 9722 B = APFloat::copySign(APFloat(B.getSemantics()), B); 9723 if (C.isNaN()) 9724 C = APFloat::copySign(APFloat(C.getSemantics()), C); 9725 if (D.isNaN()) 9726 D = APFloat::copySign(APFloat(D.getSemantics()), D); 9727 Recalc = true; 9728 } 9729 if (Recalc) { 9730 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 9731 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 9732 } 9733 } 9734 } 9735 } else { 9736 ComplexValue LHS = Result; 9737 Result.getComplexIntReal() = 9738 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 9739 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 9740 Result.getComplexIntImag() = 9741 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 9742 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 9743 } 9744 break; 9745 case BO_Div: 9746 if (Result.isComplexFloat()) { 9747 // This is an implementation of complex division according to the 9748 // constraints laid out in C11 Annex G. The implemention uses the 9749 // following naming scheme: 9750 // (a + ib) / (c + id) 9751 ComplexValue LHS = Result; 9752 APFloat &A = LHS.getComplexFloatReal(); 9753 APFloat &B = LHS.getComplexFloatImag(); 9754 APFloat &C = RHS.getComplexFloatReal(); 9755 APFloat &D = RHS.getComplexFloatImag(); 9756 APFloat &ResR = Result.getComplexFloatReal(); 9757 APFloat &ResI = Result.getComplexFloatImag(); 9758 if (RHSReal) { 9759 ResR = A / C; 9760 ResI = B / C; 9761 } else { 9762 if (LHSReal) { 9763 // No real optimizations we can do here, stub out with zero. 9764 B = APFloat::getZero(A.getSemantics()); 9765 } 9766 int DenomLogB = 0; 9767 APFloat MaxCD = maxnum(abs(C), abs(D)); 9768 if (MaxCD.isFinite()) { 9769 DenomLogB = ilogb(MaxCD); 9770 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 9771 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 9772 } 9773 APFloat Denom = C * C + D * D; 9774 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 9775 APFloat::rmNearestTiesToEven); 9776 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 9777 APFloat::rmNearestTiesToEven); 9778 if (ResR.isNaN() && ResI.isNaN()) { 9779 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 9780 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 9781 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 9782 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 9783 D.isFinite()) { 9784 A = APFloat::copySign( 9785 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 9786 B = APFloat::copySign( 9787 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 9788 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 9789 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 9790 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 9791 C = APFloat::copySign( 9792 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 9793 D = APFloat::copySign( 9794 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 9795 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 9796 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 9797 } 9798 } 9799 } 9800 } else { 9801 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 9802 return Error(E, diag::note_expr_divide_by_zero); 9803 9804 ComplexValue LHS = Result; 9805 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 9806 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 9807 Result.getComplexIntReal() = 9808 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 9809 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 9810 Result.getComplexIntImag() = 9811 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 9812 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 9813 } 9814 break; 9815 } 9816 9817 return true; 9818 } 9819 9820 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9821 // Get the operand value into 'Result'. 9822 if (!Visit(E->getSubExpr())) 9823 return false; 9824 9825 switch (E->getOpcode()) { 9826 default: 9827 return Error(E); 9828 case UO_Extension: 9829 return true; 9830 case UO_Plus: 9831 // The result is always just the subexpr. 9832 return true; 9833 case UO_Minus: 9834 if (Result.isComplexFloat()) { 9835 Result.getComplexFloatReal().changeSign(); 9836 Result.getComplexFloatImag().changeSign(); 9837 } 9838 else { 9839 Result.getComplexIntReal() = -Result.getComplexIntReal(); 9840 Result.getComplexIntImag() = -Result.getComplexIntImag(); 9841 } 9842 return true; 9843 case UO_Not: 9844 if (Result.isComplexFloat()) 9845 Result.getComplexFloatImag().changeSign(); 9846 else 9847 Result.getComplexIntImag() = -Result.getComplexIntImag(); 9848 return true; 9849 } 9850 } 9851 9852 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9853 if (E->getNumInits() == 2) { 9854 if (E->getType()->isComplexType()) { 9855 Result.makeComplexFloat(); 9856 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 9857 return false; 9858 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 9859 return false; 9860 } else { 9861 Result.makeComplexInt(); 9862 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 9863 return false; 9864 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 9865 return false; 9866 } 9867 return true; 9868 } 9869 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 9870 } 9871 9872 //===----------------------------------------------------------------------===// 9873 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 9874 // implicit conversion. 9875 //===----------------------------------------------------------------------===// 9876 9877 namespace { 9878 class AtomicExprEvaluator : 9879 public ExprEvaluatorBase<AtomicExprEvaluator> { 9880 const LValue *This; 9881 APValue &Result; 9882 public: 9883 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 9884 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 9885 9886 bool Success(const APValue &V, const Expr *E) { 9887 Result = V; 9888 return true; 9889 } 9890 9891 bool ZeroInitialization(const Expr *E) { 9892 ImplicitValueInitExpr VIE( 9893 E->getType()->castAs<AtomicType>()->getValueType()); 9894 // For atomic-qualified class (and array) types in C++, initialize the 9895 // _Atomic-wrapped subobject directly, in-place. 9896 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 9897 : Evaluate(Result, Info, &VIE); 9898 } 9899 9900 bool VisitCastExpr(const CastExpr *E) { 9901 switch (E->getCastKind()) { 9902 default: 9903 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9904 case CK_NonAtomicToAtomic: 9905 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 9906 : Evaluate(Result, Info, E->getSubExpr()); 9907 } 9908 } 9909 }; 9910 } // end anonymous namespace 9911 9912 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 9913 EvalInfo &Info) { 9914 assert(E->isRValue() && E->getType()->isAtomicType()); 9915 return AtomicExprEvaluator(Info, This, Result).Visit(E); 9916 } 9917 9918 //===----------------------------------------------------------------------===// 9919 // Void expression evaluation, primarily for a cast to void on the LHS of a 9920 // comma operator 9921 //===----------------------------------------------------------------------===// 9922 9923 namespace { 9924 class VoidExprEvaluator 9925 : public ExprEvaluatorBase<VoidExprEvaluator> { 9926 public: 9927 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 9928 9929 bool Success(const APValue &V, const Expr *e) { return true; } 9930 9931 bool ZeroInitialization(const Expr *E) { return true; } 9932 9933 bool VisitCastExpr(const CastExpr *E) { 9934 switch (E->getCastKind()) { 9935 default: 9936 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9937 case CK_ToVoid: 9938 VisitIgnoredValue(E->getSubExpr()); 9939 return true; 9940 } 9941 } 9942 9943 bool VisitCallExpr(const CallExpr *E) { 9944 switch (E->getBuiltinCallee()) { 9945 default: 9946 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9947 case Builtin::BI__assume: 9948 case Builtin::BI__builtin_assume: 9949 // The argument is not evaluated! 9950 return true; 9951 } 9952 } 9953 }; 9954 } // end anonymous namespace 9955 9956 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 9957 assert(E->isRValue() && E->getType()->isVoidType()); 9958 return VoidExprEvaluator(Info).Visit(E); 9959 } 9960 9961 //===----------------------------------------------------------------------===// 9962 // Top level Expr::EvaluateAsRValue method. 9963 //===----------------------------------------------------------------------===// 9964 9965 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 9966 // In C, function designators are not lvalues, but we evaluate them as if they 9967 // are. 9968 QualType T = E->getType(); 9969 if (E->isGLValue() || T->isFunctionType()) { 9970 LValue LV; 9971 if (!EvaluateLValue(E, LV, Info)) 9972 return false; 9973 LV.moveInto(Result); 9974 } else if (T->isVectorType()) { 9975 if (!EvaluateVector(E, Result, Info)) 9976 return false; 9977 } else if (T->isIntegralOrEnumerationType()) { 9978 if (!IntExprEvaluator(Info, Result).Visit(E)) 9979 return false; 9980 } else if (T->hasPointerRepresentation()) { 9981 LValue LV; 9982 if (!EvaluatePointer(E, LV, Info)) 9983 return false; 9984 LV.moveInto(Result); 9985 } else if (T->isRealFloatingType()) { 9986 llvm::APFloat F(0.0); 9987 if (!EvaluateFloat(E, F, Info)) 9988 return false; 9989 Result = APValue(F); 9990 } else if (T->isAnyComplexType()) { 9991 ComplexValue C; 9992 if (!EvaluateComplex(E, C, Info)) 9993 return false; 9994 C.moveInto(Result); 9995 } else if (T->isMemberPointerType()) { 9996 MemberPtr P; 9997 if (!EvaluateMemberPointer(E, P, Info)) 9998 return false; 9999 P.moveInto(Result); 10000 return true; 10001 } else if (T->isArrayType()) { 10002 LValue LV; 10003 LV.set(E, Info.CurrentCall->Index); 10004 APValue &Value = Info.CurrentCall->createTemporary(E, false); 10005 if (!EvaluateArray(E, LV, Value, Info)) 10006 return false; 10007 Result = Value; 10008 } else if (T->isRecordType()) { 10009 LValue LV; 10010 LV.set(E, Info.CurrentCall->Index); 10011 APValue &Value = Info.CurrentCall->createTemporary(E, false); 10012 if (!EvaluateRecord(E, LV, Value, Info)) 10013 return false; 10014 Result = Value; 10015 } else if (T->isVoidType()) { 10016 if (!Info.getLangOpts().CPlusPlus11) 10017 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 10018 << E->getType(); 10019 if (!EvaluateVoid(E, Info)) 10020 return false; 10021 } else if (T->isAtomicType()) { 10022 QualType Unqual = T.getAtomicUnqualifiedType(); 10023 if (Unqual->isArrayType() || Unqual->isRecordType()) { 10024 LValue LV; 10025 LV.set(E, Info.CurrentCall->Index); 10026 APValue &Value = Info.CurrentCall->createTemporary(E, false); 10027 if (!EvaluateAtomic(E, &LV, Value, Info)) 10028 return false; 10029 } else { 10030 if (!EvaluateAtomic(E, nullptr, Result, Info)) 10031 return false; 10032 } 10033 } else if (Info.getLangOpts().CPlusPlus11) { 10034 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 10035 return false; 10036 } else { 10037 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10038 return false; 10039 } 10040 10041 return true; 10042 } 10043 10044 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 10045 /// cases, the in-place evaluation is essential, since later initializers for 10046 /// an object can indirectly refer to subobjects which were initialized earlier. 10047 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 10048 const Expr *E, bool AllowNonLiteralTypes) { 10049 assert(!E->isValueDependent()); 10050 10051 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 10052 return false; 10053 10054 if (E->isRValue()) { 10055 // Evaluate arrays and record types in-place, so that later initializers can 10056 // refer to earlier-initialized members of the object. 10057 QualType T = E->getType(); 10058 if (T->isArrayType()) 10059 return EvaluateArray(E, This, Result, Info); 10060 else if (T->isRecordType()) 10061 return EvaluateRecord(E, This, Result, Info); 10062 else if (T->isAtomicType()) { 10063 QualType Unqual = T.getAtomicUnqualifiedType(); 10064 if (Unqual->isArrayType() || Unqual->isRecordType()) 10065 return EvaluateAtomic(E, &This, Result, Info); 10066 } 10067 } 10068 10069 // For any other type, in-place evaluation is unimportant. 10070 return Evaluate(Result, Info, E); 10071 } 10072 10073 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 10074 /// lvalue-to-rvalue cast if it is an lvalue. 10075 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 10076 if (E->getType().isNull()) 10077 return false; 10078 10079 if (!CheckLiteralType(Info, E)) 10080 return false; 10081 10082 if (!::Evaluate(Result, Info, E)) 10083 return false; 10084 10085 if (E->isGLValue()) { 10086 LValue LV; 10087 LV.setFrom(Info.Ctx, Result); 10088 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10089 return false; 10090 } 10091 10092 // Check this core constant expression is a constant expression. 10093 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10094 } 10095 10096 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 10097 const ASTContext &Ctx, bool &IsConst) { 10098 // Fast-path evaluations of integer literals, since we sometimes see files 10099 // containing vast quantities of these. 10100 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 10101 Result.Val = APValue(APSInt(L->getValue(), 10102 L->getType()->isUnsignedIntegerType())); 10103 IsConst = true; 10104 return true; 10105 } 10106 10107 // This case should be rare, but we need to check it before we check on 10108 // the type below. 10109 if (Exp->getType().isNull()) { 10110 IsConst = false; 10111 return true; 10112 } 10113 10114 // FIXME: Evaluating values of large array and record types can cause 10115 // performance problems. Only do so in C++11 for now. 10116 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 10117 Exp->getType()->isRecordType()) && 10118 !Ctx.getLangOpts().CPlusPlus11) { 10119 IsConst = false; 10120 return true; 10121 } 10122 return false; 10123 } 10124 10125 10126 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 10127 /// any crazy technique (that has nothing to do with language standards) that 10128 /// we want to. If this function returns true, it returns the folded constant 10129 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 10130 /// will be applied to the result. 10131 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 10132 bool IsConst; 10133 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) 10134 return IsConst; 10135 10136 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 10137 return ::EvaluateAsRValue(Info, this, Result.Val); 10138 } 10139 10140 bool Expr::EvaluateAsBooleanCondition(bool &Result, 10141 const ASTContext &Ctx) const { 10142 EvalResult Scratch; 10143 return EvaluateAsRValue(Scratch, Ctx) && 10144 HandleConversionToBool(Scratch.Val, Result); 10145 } 10146 10147 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 10148 Expr::SideEffectsKind SEK) { 10149 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 10150 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 10151 } 10152 10153 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx, 10154 SideEffectsKind AllowSideEffects) const { 10155 if (!getType()->isIntegralOrEnumerationType()) 10156 return false; 10157 10158 EvalResult ExprResult; 10159 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() || 10160 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10161 return false; 10162 10163 Result = ExprResult.Val.getInt(); 10164 return true; 10165 } 10166 10167 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 10168 SideEffectsKind AllowSideEffects) const { 10169 if (!getType()->isRealFloatingType()) 10170 return false; 10171 10172 EvalResult ExprResult; 10173 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() || 10174 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10175 return false; 10176 10177 Result = ExprResult.Val.getFloat(); 10178 return true; 10179 } 10180 10181 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 10182 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 10183 10184 LValue LV; 10185 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 10186 !CheckLValueConstantExpression(Info, getExprLoc(), 10187 Ctx.getLValueReferenceType(getType()), LV)) 10188 return false; 10189 10190 LV.moveInto(Result.Val); 10191 return true; 10192 } 10193 10194 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 10195 const VarDecl *VD, 10196 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 10197 // FIXME: Evaluating initializers for large array and record types can cause 10198 // performance problems. Only do so in C++11 for now. 10199 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 10200 !Ctx.getLangOpts().CPlusPlus11) 10201 return false; 10202 10203 Expr::EvalStatus EStatus; 10204 EStatus.Diag = &Notes; 10205 10206 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 10207 ? EvalInfo::EM_ConstantExpression 10208 : EvalInfo::EM_ConstantFold); 10209 InitInfo.setEvaluatingDecl(VD, Value); 10210 10211 LValue LVal; 10212 LVal.set(VD); 10213 10214 // C++11 [basic.start.init]p2: 10215 // Variables with static storage duration or thread storage duration shall be 10216 // zero-initialized before any other initialization takes place. 10217 // This behavior is not present in C. 10218 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 10219 !VD->getType()->isReferenceType()) { 10220 ImplicitValueInitExpr VIE(VD->getType()); 10221 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 10222 /*AllowNonLiteralTypes=*/true)) 10223 return false; 10224 } 10225 10226 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 10227 /*AllowNonLiteralTypes=*/true) || 10228 EStatus.HasSideEffects) 10229 return false; 10230 10231 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 10232 Value); 10233 } 10234 10235 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 10236 /// constant folded, but discard the result. 10237 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 10238 EvalResult Result; 10239 return EvaluateAsRValue(Result, Ctx) && 10240 !hasUnacceptableSideEffect(Result, SEK); 10241 } 10242 10243 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 10244 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 10245 EvalResult EvalResult; 10246 EvalResult.Diag = Diag; 10247 bool Result = EvaluateAsRValue(EvalResult, Ctx); 10248 (void)Result; 10249 assert(Result && "Could not evaluate expression"); 10250 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 10251 10252 return EvalResult.Val.getInt(); 10253 } 10254 10255 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 10256 bool IsConst; 10257 EvalResult EvalResult; 10258 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) { 10259 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); 10260 (void)::EvaluateAsRValue(Info, this, EvalResult.Val); 10261 } 10262 } 10263 10264 bool Expr::EvalResult::isGlobalLValue() const { 10265 assert(Val.isLValue()); 10266 return IsGlobalLValue(Val.getLValueBase()); 10267 } 10268 10269 10270 /// isIntegerConstantExpr - this recursive routine will test if an expression is 10271 /// an integer constant expression. 10272 10273 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 10274 /// comma, etc 10275 10276 // CheckICE - This function does the fundamental ICE checking: the returned 10277 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 10278 // and a (possibly null) SourceLocation indicating the location of the problem. 10279 // 10280 // Note that to reduce code duplication, this helper does no evaluation 10281 // itself; the caller checks whether the expression is evaluatable, and 10282 // in the rare cases where CheckICE actually cares about the evaluated 10283 // value, it calls into Evaluate. 10284 10285 namespace { 10286 10287 enum ICEKind { 10288 /// This expression is an ICE. 10289 IK_ICE, 10290 /// This expression is not an ICE, but if it isn't evaluated, it's 10291 /// a legal subexpression for an ICE. This return value is used to handle 10292 /// the comma operator in C99 mode, and non-constant subexpressions. 10293 IK_ICEIfUnevaluated, 10294 /// This expression is not an ICE, and is not a legal subexpression for one. 10295 IK_NotICE 10296 }; 10297 10298 struct ICEDiag { 10299 ICEKind Kind; 10300 SourceLocation Loc; 10301 10302 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 10303 }; 10304 10305 } 10306 10307 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 10308 10309 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 10310 10311 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 10312 Expr::EvalResult EVResult; 10313 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 10314 !EVResult.Val.isInt()) 10315 return ICEDiag(IK_NotICE, E->getLocStart()); 10316 10317 return NoDiag(); 10318 } 10319 10320 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 10321 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 10322 if (!E->getType()->isIntegralOrEnumerationType()) 10323 return ICEDiag(IK_NotICE, E->getLocStart()); 10324 10325 switch (E->getStmtClass()) { 10326 #define ABSTRACT_STMT(Node) 10327 #define STMT(Node, Base) case Expr::Node##Class: 10328 #define EXPR(Node, Base) 10329 #include "clang/AST/StmtNodes.inc" 10330 case Expr::PredefinedExprClass: 10331 case Expr::FloatingLiteralClass: 10332 case Expr::ImaginaryLiteralClass: 10333 case Expr::StringLiteralClass: 10334 case Expr::ArraySubscriptExprClass: 10335 case Expr::OMPArraySectionExprClass: 10336 case Expr::MemberExprClass: 10337 case Expr::CompoundAssignOperatorClass: 10338 case Expr::CompoundLiteralExprClass: 10339 case Expr::ExtVectorElementExprClass: 10340 case Expr::DesignatedInitExprClass: 10341 case Expr::ArrayInitLoopExprClass: 10342 case Expr::ArrayInitIndexExprClass: 10343 case Expr::NoInitExprClass: 10344 case Expr::DesignatedInitUpdateExprClass: 10345 case Expr::ImplicitValueInitExprClass: 10346 case Expr::ParenListExprClass: 10347 case Expr::VAArgExprClass: 10348 case Expr::AddrLabelExprClass: 10349 case Expr::StmtExprClass: 10350 case Expr::CXXMemberCallExprClass: 10351 case Expr::CUDAKernelCallExprClass: 10352 case Expr::CXXDynamicCastExprClass: 10353 case Expr::CXXTypeidExprClass: 10354 case Expr::CXXUuidofExprClass: 10355 case Expr::MSPropertyRefExprClass: 10356 case Expr::MSPropertySubscriptExprClass: 10357 case Expr::CXXNullPtrLiteralExprClass: 10358 case Expr::UserDefinedLiteralClass: 10359 case Expr::CXXThisExprClass: 10360 case Expr::CXXThrowExprClass: 10361 case Expr::CXXNewExprClass: 10362 case Expr::CXXDeleteExprClass: 10363 case Expr::CXXPseudoDestructorExprClass: 10364 case Expr::UnresolvedLookupExprClass: 10365 case Expr::TypoExprClass: 10366 case Expr::DependentScopeDeclRefExprClass: 10367 case Expr::CXXConstructExprClass: 10368 case Expr::CXXInheritedCtorInitExprClass: 10369 case Expr::CXXStdInitializerListExprClass: 10370 case Expr::CXXBindTemporaryExprClass: 10371 case Expr::ExprWithCleanupsClass: 10372 case Expr::CXXTemporaryObjectExprClass: 10373 case Expr::CXXUnresolvedConstructExprClass: 10374 case Expr::CXXDependentScopeMemberExprClass: 10375 case Expr::UnresolvedMemberExprClass: 10376 case Expr::ObjCStringLiteralClass: 10377 case Expr::ObjCBoxedExprClass: 10378 case Expr::ObjCArrayLiteralClass: 10379 case Expr::ObjCDictionaryLiteralClass: 10380 case Expr::ObjCEncodeExprClass: 10381 case Expr::ObjCMessageExprClass: 10382 case Expr::ObjCSelectorExprClass: 10383 case Expr::ObjCProtocolExprClass: 10384 case Expr::ObjCIvarRefExprClass: 10385 case Expr::ObjCPropertyRefExprClass: 10386 case Expr::ObjCSubscriptRefExprClass: 10387 case Expr::ObjCIsaExprClass: 10388 case Expr::ObjCAvailabilityCheckExprClass: 10389 case Expr::ShuffleVectorExprClass: 10390 case Expr::ConvertVectorExprClass: 10391 case Expr::BlockExprClass: 10392 case Expr::NoStmtClass: 10393 case Expr::OpaqueValueExprClass: 10394 case Expr::PackExpansionExprClass: 10395 case Expr::SubstNonTypeTemplateParmPackExprClass: 10396 case Expr::FunctionParmPackExprClass: 10397 case Expr::AsTypeExprClass: 10398 case Expr::ObjCIndirectCopyRestoreExprClass: 10399 case Expr::MaterializeTemporaryExprClass: 10400 case Expr::PseudoObjectExprClass: 10401 case Expr::AtomicExprClass: 10402 case Expr::LambdaExprClass: 10403 case Expr::CXXFoldExprClass: 10404 case Expr::CoawaitExprClass: 10405 case Expr::DependentCoawaitExprClass: 10406 case Expr::CoyieldExprClass: 10407 return ICEDiag(IK_NotICE, E->getLocStart()); 10408 10409 case Expr::InitListExprClass: { 10410 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 10411 // form "T x = { a };" is equivalent to "T x = a;". 10412 // Unless we're initializing a reference, T is a scalar as it is known to be 10413 // of integral or enumeration type. 10414 if (E->isRValue()) 10415 if (cast<InitListExpr>(E)->getNumInits() == 1) 10416 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 10417 return ICEDiag(IK_NotICE, E->getLocStart()); 10418 } 10419 10420 case Expr::SizeOfPackExprClass: 10421 case Expr::GNUNullExprClass: 10422 // GCC considers the GNU __null value to be an integral constant expression. 10423 return NoDiag(); 10424 10425 case Expr::SubstNonTypeTemplateParmExprClass: 10426 return 10427 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 10428 10429 case Expr::ParenExprClass: 10430 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 10431 case Expr::GenericSelectionExprClass: 10432 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 10433 case Expr::IntegerLiteralClass: 10434 case Expr::CharacterLiteralClass: 10435 case Expr::ObjCBoolLiteralExprClass: 10436 case Expr::CXXBoolLiteralExprClass: 10437 case Expr::CXXScalarValueInitExprClass: 10438 case Expr::TypeTraitExprClass: 10439 case Expr::ArrayTypeTraitExprClass: 10440 case Expr::ExpressionTraitExprClass: 10441 case Expr::CXXNoexceptExprClass: 10442 return NoDiag(); 10443 case Expr::CallExprClass: 10444 case Expr::CXXOperatorCallExprClass: { 10445 // C99 6.6/3 allows function calls within unevaluated subexpressions of 10446 // constant expressions, but they can never be ICEs because an ICE cannot 10447 // contain an operand of (pointer to) function type. 10448 const CallExpr *CE = cast<CallExpr>(E); 10449 if (CE->getBuiltinCallee()) 10450 return CheckEvalInICE(E, Ctx); 10451 return ICEDiag(IK_NotICE, E->getLocStart()); 10452 } 10453 case Expr::DeclRefExprClass: { 10454 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 10455 return NoDiag(); 10456 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 10457 if (Ctx.getLangOpts().CPlusPlus && 10458 D && IsConstNonVolatile(D->getType())) { 10459 // Parameter variables are never constants. Without this check, 10460 // getAnyInitializer() can find a default argument, which leads 10461 // to chaos. 10462 if (isa<ParmVarDecl>(D)) 10463 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 10464 10465 // C++ 7.1.5.1p2 10466 // A variable of non-volatile const-qualified integral or enumeration 10467 // type initialized by an ICE can be used in ICEs. 10468 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 10469 if (!Dcl->getType()->isIntegralOrEnumerationType()) 10470 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 10471 10472 const VarDecl *VD; 10473 // Look for a declaration of this variable that has an initializer, and 10474 // check whether it is an ICE. 10475 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 10476 return NoDiag(); 10477 else 10478 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 10479 } 10480 } 10481 return ICEDiag(IK_NotICE, E->getLocStart()); 10482 } 10483 case Expr::UnaryOperatorClass: { 10484 const UnaryOperator *Exp = cast<UnaryOperator>(E); 10485 switch (Exp->getOpcode()) { 10486 case UO_PostInc: 10487 case UO_PostDec: 10488 case UO_PreInc: 10489 case UO_PreDec: 10490 case UO_AddrOf: 10491 case UO_Deref: 10492 case UO_Coawait: 10493 // C99 6.6/3 allows increment and decrement within unevaluated 10494 // subexpressions of constant expressions, but they can never be ICEs 10495 // because an ICE cannot contain an lvalue operand. 10496 return ICEDiag(IK_NotICE, E->getLocStart()); 10497 case UO_Extension: 10498 case UO_LNot: 10499 case UO_Plus: 10500 case UO_Minus: 10501 case UO_Not: 10502 case UO_Real: 10503 case UO_Imag: 10504 return CheckICE(Exp->getSubExpr(), Ctx); 10505 } 10506 10507 // OffsetOf falls through here. 10508 LLVM_FALLTHROUGH; 10509 } 10510 case Expr::OffsetOfExprClass: { 10511 // Note that per C99, offsetof must be an ICE. And AFAIK, using 10512 // EvaluateAsRValue matches the proposed gcc behavior for cases like 10513 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 10514 // compliance: we should warn earlier for offsetof expressions with 10515 // array subscripts that aren't ICEs, and if the array subscripts 10516 // are ICEs, the value of the offsetof must be an integer constant. 10517 return CheckEvalInICE(E, Ctx); 10518 } 10519 case Expr::UnaryExprOrTypeTraitExprClass: { 10520 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 10521 if ((Exp->getKind() == UETT_SizeOf) && 10522 Exp->getTypeOfArgument()->isVariableArrayType()) 10523 return ICEDiag(IK_NotICE, E->getLocStart()); 10524 return NoDiag(); 10525 } 10526 case Expr::BinaryOperatorClass: { 10527 const BinaryOperator *Exp = cast<BinaryOperator>(E); 10528 switch (Exp->getOpcode()) { 10529 case BO_PtrMemD: 10530 case BO_PtrMemI: 10531 case BO_Assign: 10532 case BO_MulAssign: 10533 case BO_DivAssign: 10534 case BO_RemAssign: 10535 case BO_AddAssign: 10536 case BO_SubAssign: 10537 case BO_ShlAssign: 10538 case BO_ShrAssign: 10539 case BO_AndAssign: 10540 case BO_XorAssign: 10541 case BO_OrAssign: 10542 case BO_Cmp: // FIXME: Re-enable once we can evaluate this. 10543 // C99 6.6/3 allows assignments within unevaluated subexpressions of 10544 // constant expressions, but they can never be ICEs because an ICE cannot 10545 // contain an lvalue operand. 10546 return ICEDiag(IK_NotICE, E->getLocStart()); 10547 10548 case BO_Mul: 10549 case BO_Div: 10550 case BO_Rem: 10551 case BO_Add: 10552 case BO_Sub: 10553 case BO_Shl: 10554 case BO_Shr: 10555 case BO_LT: 10556 case BO_GT: 10557 case BO_LE: 10558 case BO_GE: 10559 case BO_EQ: 10560 case BO_NE: 10561 case BO_And: 10562 case BO_Xor: 10563 case BO_Or: 10564 case BO_Comma: { 10565 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 10566 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 10567 if (Exp->getOpcode() == BO_Div || 10568 Exp->getOpcode() == BO_Rem) { 10569 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 10570 // we don't evaluate one. 10571 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 10572 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 10573 if (REval == 0) 10574 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 10575 if (REval.isSigned() && REval.isAllOnesValue()) { 10576 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 10577 if (LEval.isMinSignedValue()) 10578 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 10579 } 10580 } 10581 } 10582 if (Exp->getOpcode() == BO_Comma) { 10583 if (Ctx.getLangOpts().C99) { 10584 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 10585 // if it isn't evaluated. 10586 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 10587 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 10588 } else { 10589 // In both C89 and C++, commas in ICEs are illegal. 10590 return ICEDiag(IK_NotICE, E->getLocStart()); 10591 } 10592 } 10593 return Worst(LHSResult, RHSResult); 10594 } 10595 case BO_LAnd: 10596 case BO_LOr: { 10597 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 10598 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 10599 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 10600 // Rare case where the RHS has a comma "side-effect"; we need 10601 // to actually check the condition to see whether the side 10602 // with the comma is evaluated. 10603 if ((Exp->getOpcode() == BO_LAnd) != 10604 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 10605 return RHSResult; 10606 return NoDiag(); 10607 } 10608 10609 return Worst(LHSResult, RHSResult); 10610 } 10611 } 10612 LLVM_FALLTHROUGH; 10613 } 10614 case Expr::ImplicitCastExprClass: 10615 case Expr::CStyleCastExprClass: 10616 case Expr::CXXFunctionalCastExprClass: 10617 case Expr::CXXStaticCastExprClass: 10618 case Expr::CXXReinterpretCastExprClass: 10619 case Expr::CXXConstCastExprClass: 10620 case Expr::ObjCBridgedCastExprClass: { 10621 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 10622 if (isa<ExplicitCastExpr>(E)) { 10623 if (const FloatingLiteral *FL 10624 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 10625 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 10626 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 10627 APSInt IgnoredVal(DestWidth, !DestSigned); 10628 bool Ignored; 10629 // If the value does not fit in the destination type, the behavior is 10630 // undefined, so we are not required to treat it as a constant 10631 // expression. 10632 if (FL->getValue().convertToInteger(IgnoredVal, 10633 llvm::APFloat::rmTowardZero, 10634 &Ignored) & APFloat::opInvalidOp) 10635 return ICEDiag(IK_NotICE, E->getLocStart()); 10636 return NoDiag(); 10637 } 10638 } 10639 switch (cast<CastExpr>(E)->getCastKind()) { 10640 case CK_LValueToRValue: 10641 case CK_AtomicToNonAtomic: 10642 case CK_NonAtomicToAtomic: 10643 case CK_NoOp: 10644 case CK_IntegralToBoolean: 10645 case CK_IntegralCast: 10646 return CheckICE(SubExpr, Ctx); 10647 default: 10648 return ICEDiag(IK_NotICE, E->getLocStart()); 10649 } 10650 } 10651 case Expr::BinaryConditionalOperatorClass: { 10652 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 10653 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 10654 if (CommonResult.Kind == IK_NotICE) return CommonResult; 10655 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 10656 if (FalseResult.Kind == IK_NotICE) return FalseResult; 10657 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 10658 if (FalseResult.Kind == IK_ICEIfUnevaluated && 10659 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 10660 return FalseResult; 10661 } 10662 case Expr::ConditionalOperatorClass: { 10663 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 10664 // If the condition (ignoring parens) is a __builtin_constant_p call, 10665 // then only the true side is actually considered in an integer constant 10666 // expression, and it is fully evaluated. This is an important GNU 10667 // extension. See GCC PR38377 for discussion. 10668 if (const CallExpr *CallCE 10669 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 10670 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 10671 return CheckEvalInICE(E, Ctx); 10672 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 10673 if (CondResult.Kind == IK_NotICE) 10674 return CondResult; 10675 10676 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 10677 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 10678 10679 if (TrueResult.Kind == IK_NotICE) 10680 return TrueResult; 10681 if (FalseResult.Kind == IK_NotICE) 10682 return FalseResult; 10683 if (CondResult.Kind == IK_ICEIfUnevaluated) 10684 return CondResult; 10685 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 10686 return NoDiag(); 10687 // Rare case where the diagnostics depend on which side is evaluated 10688 // Note that if we get here, CondResult is 0, and at least one of 10689 // TrueResult and FalseResult is non-zero. 10690 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 10691 return FalseResult; 10692 return TrueResult; 10693 } 10694 case Expr::CXXDefaultArgExprClass: 10695 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 10696 case Expr::CXXDefaultInitExprClass: 10697 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 10698 case Expr::ChooseExprClass: { 10699 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 10700 } 10701 } 10702 10703 llvm_unreachable("Invalid StmtClass!"); 10704 } 10705 10706 /// Evaluate an expression as a C++11 integral constant expression. 10707 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 10708 const Expr *E, 10709 llvm::APSInt *Value, 10710 SourceLocation *Loc) { 10711 if (!E->getType()->isIntegralOrEnumerationType()) { 10712 if (Loc) *Loc = E->getExprLoc(); 10713 return false; 10714 } 10715 10716 APValue Result; 10717 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 10718 return false; 10719 10720 if (!Result.isInt()) { 10721 if (Loc) *Loc = E->getExprLoc(); 10722 return false; 10723 } 10724 10725 if (Value) *Value = Result.getInt(); 10726 return true; 10727 } 10728 10729 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 10730 SourceLocation *Loc) const { 10731 if (Ctx.getLangOpts().CPlusPlus11) 10732 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 10733 10734 ICEDiag D = CheckICE(this, Ctx); 10735 if (D.Kind != IK_ICE) { 10736 if (Loc) *Loc = D.Loc; 10737 return false; 10738 } 10739 return true; 10740 } 10741 10742 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 10743 SourceLocation *Loc, bool isEvaluated) const { 10744 if (Ctx.getLangOpts().CPlusPlus11) 10745 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 10746 10747 if (!isIntegerConstantExpr(Ctx, Loc)) 10748 return false; 10749 // The only possible side-effects here are due to UB discovered in the 10750 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 10751 // required to treat the expression as an ICE, so we produce the folded 10752 // value. 10753 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects)) 10754 llvm_unreachable("ICE cannot be evaluated!"); 10755 return true; 10756 } 10757 10758 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 10759 return CheckICE(this, Ctx).Kind == IK_ICE; 10760 } 10761 10762 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 10763 SourceLocation *Loc) const { 10764 // We support this checking in C++98 mode in order to diagnose compatibility 10765 // issues. 10766 assert(Ctx.getLangOpts().CPlusPlus); 10767 10768 // Build evaluation settings. 10769 Expr::EvalStatus Status; 10770 SmallVector<PartialDiagnosticAt, 8> Diags; 10771 Status.Diag = &Diags; 10772 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 10773 10774 APValue Scratch; 10775 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 10776 10777 if (!Diags.empty()) { 10778 IsConstExpr = false; 10779 if (Loc) *Loc = Diags[0].first; 10780 } else if (!IsConstExpr) { 10781 // FIXME: This shouldn't happen. 10782 if (Loc) *Loc = getExprLoc(); 10783 } 10784 10785 return IsConstExpr; 10786 } 10787 10788 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 10789 const FunctionDecl *Callee, 10790 ArrayRef<const Expr*> Args, 10791 const Expr *This) const { 10792 Expr::EvalStatus Status; 10793 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 10794 10795 LValue ThisVal; 10796 const LValue *ThisPtr = nullptr; 10797 if (This) { 10798 #ifndef NDEBUG 10799 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 10800 assert(MD && "Don't provide `this` for non-methods."); 10801 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 10802 #endif 10803 if (EvaluateObjectArgument(Info, This, ThisVal)) 10804 ThisPtr = &ThisVal; 10805 if (Info.EvalStatus.HasSideEffects) 10806 return false; 10807 } 10808 10809 ArgVector ArgValues(Args.size()); 10810 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 10811 I != E; ++I) { 10812 if ((*I)->isValueDependent() || 10813 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 10814 // If evaluation fails, throw away the argument entirely. 10815 ArgValues[I - Args.begin()] = APValue(); 10816 if (Info.EvalStatus.HasSideEffects) 10817 return false; 10818 } 10819 10820 // Build fake call to Callee. 10821 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 10822 ArgValues.data()); 10823 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 10824 } 10825 10826 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 10827 SmallVectorImpl< 10828 PartialDiagnosticAt> &Diags) { 10829 // FIXME: It would be useful to check constexpr function templates, but at the 10830 // moment the constant expression evaluator cannot cope with the non-rigorous 10831 // ASTs which we build for dependent expressions. 10832 if (FD->isDependentContext()) 10833 return true; 10834 10835 Expr::EvalStatus Status; 10836 Status.Diag = &Diags; 10837 10838 EvalInfo Info(FD->getASTContext(), Status, 10839 EvalInfo::EM_PotentialConstantExpression); 10840 10841 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 10842 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 10843 10844 // Fabricate an arbitrary expression on the stack and pretend that it 10845 // is a temporary being used as the 'this' pointer. 10846 LValue This; 10847 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 10848 This.set(&VIE, Info.CurrentCall->Index); 10849 10850 ArrayRef<const Expr*> Args; 10851 10852 APValue Scratch; 10853 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 10854 // Evaluate the call as a constant initializer, to allow the construction 10855 // of objects of non-literal types. 10856 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 10857 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 10858 } else { 10859 SourceLocation Loc = FD->getLocation(); 10860 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 10861 Args, FD->getBody(), Info, Scratch, nullptr); 10862 } 10863 10864 return Diags.empty(); 10865 } 10866 10867 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 10868 const FunctionDecl *FD, 10869 SmallVectorImpl< 10870 PartialDiagnosticAt> &Diags) { 10871 Expr::EvalStatus Status; 10872 Status.Diag = &Diags; 10873 10874 EvalInfo Info(FD->getASTContext(), Status, 10875 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 10876 10877 // Fabricate a call stack frame to give the arguments a plausible cover story. 10878 ArrayRef<const Expr*> Args; 10879 ArgVector ArgValues(0); 10880 bool Success = EvaluateArgs(Args, ArgValues, Info); 10881 (void)Success; 10882 assert(Success && 10883 "Failed to set up arguments for potential constant evaluation"); 10884 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 10885 10886 APValue ResultScratch; 10887 Evaluate(ResultScratch, Info, E); 10888 return Diags.empty(); 10889 } 10890 10891 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 10892 unsigned Type) const { 10893 if (!getType()->isPointerType()) 10894 return false; 10895 10896 Expr::EvalStatus Status; 10897 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 10898 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 10899 } 10900