1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 return B.getType(); 83 } 84 85 /// Get an LValue path entry, which is known to not be an array index, as a 86 /// field declaration. 87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 89 } 90 /// Get an LValue path entry, which is known to not be an array index, as a 91 /// base class declaration. 92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 94 } 95 /// Determine whether this LValue path entry for a base class names a virtual 96 /// base class. 97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 98 return E.getAsBaseOrMember().getInt(); 99 } 100 101 /// Given an expression, determine the type used to store the result of 102 /// evaluating that expression. 103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 104 if (E->isRValue()) 105 return E->getType(); 106 return Ctx.getLValueReferenceType(E->getType()); 107 } 108 109 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 111 const FunctionDecl *Callee = CE->getDirectCallee(); 112 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 113 } 114 115 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 116 /// This will look through a single cast. 117 /// 118 /// Returns null if we couldn't unwrap a function with alloc_size. 119 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 120 if (!E->getType()->isPointerType()) 121 return nullptr; 122 123 E = E->IgnoreParens(); 124 // If we're doing a variable assignment from e.g. malloc(N), there will 125 // probably be a cast of some kind. In exotic cases, we might also see a 126 // top-level ExprWithCleanups. Ignore them either way. 127 if (const auto *FE = dyn_cast<FullExpr>(E)) 128 E = FE->getSubExpr()->IgnoreParens(); 129 130 if (const auto *Cast = dyn_cast<CastExpr>(E)) 131 E = Cast->getSubExpr()->IgnoreParens(); 132 133 if (const auto *CE = dyn_cast<CallExpr>(E)) 134 return getAllocSizeAttr(CE) ? CE : nullptr; 135 return nullptr; 136 } 137 138 /// Determines whether or not the given Base contains a call to a function 139 /// with the alloc_size attribute. 140 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 141 const auto *E = Base.dyn_cast<const Expr *>(); 142 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 143 } 144 145 /// Determines whether the given kind of constant expression is only ever 146 /// used for name mangling. If so, it's permitted to reference things that we 147 /// can't generate code for (in particular, dllimported functions). 148 static bool isForManglingOnly(ConstantExprKind Kind) { 149 switch (Kind) { 150 case ConstantExprKind::Normal: 151 case ConstantExprKind::ClassTemplateArgument: 152 case ConstantExprKind::ImmediateInvocation: 153 // Note that non-type template arguments of class type are emitted as 154 // template parameter objects. 155 return false; 156 157 case ConstantExprKind::NonClassTemplateArgument: 158 return true; 159 } 160 llvm_unreachable("unknown ConstantExprKind"); 161 } 162 163 static bool isTemplateArgument(ConstantExprKind Kind) { 164 switch (Kind) { 165 case ConstantExprKind::Normal: 166 case ConstantExprKind::ImmediateInvocation: 167 return false; 168 169 case ConstantExprKind::ClassTemplateArgument: 170 case ConstantExprKind::NonClassTemplateArgument: 171 return true; 172 } 173 llvm_unreachable("unknown ConstantExprKind"); 174 } 175 176 /// The bound to claim that an array of unknown bound has. 177 /// The value in MostDerivedArraySize is undefined in this case. So, set it 178 /// to an arbitrary value that's likely to loudly break things if it's used. 179 static const uint64_t AssumedSizeForUnsizedArray = 180 std::numeric_limits<uint64_t>::max() / 2; 181 182 /// Determines if an LValue with the given LValueBase will have an unsized 183 /// array in its designator. 184 /// Find the path length and type of the most-derived subobject in the given 185 /// path, and find the size of the containing array, if any. 186 static unsigned 187 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 188 ArrayRef<APValue::LValuePathEntry> Path, 189 uint64_t &ArraySize, QualType &Type, bool &IsArray, 190 bool &FirstEntryIsUnsizedArray) { 191 // This only accepts LValueBases from APValues, and APValues don't support 192 // arrays that lack size info. 193 assert(!isBaseAnAllocSizeCall(Base) && 194 "Unsized arrays shouldn't appear here"); 195 unsigned MostDerivedLength = 0; 196 Type = getType(Base); 197 198 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 199 if (Type->isArrayType()) { 200 const ArrayType *AT = Ctx.getAsArrayType(Type); 201 Type = AT->getElementType(); 202 MostDerivedLength = I + 1; 203 IsArray = true; 204 205 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 206 ArraySize = CAT->getSize().getZExtValue(); 207 } else { 208 assert(I == 0 && "unexpected unsized array designator"); 209 FirstEntryIsUnsizedArray = true; 210 ArraySize = AssumedSizeForUnsizedArray; 211 } 212 } else if (Type->isAnyComplexType()) { 213 const ComplexType *CT = Type->castAs<ComplexType>(); 214 Type = CT->getElementType(); 215 ArraySize = 2; 216 MostDerivedLength = I + 1; 217 IsArray = true; 218 } else if (const FieldDecl *FD = getAsField(Path[I])) { 219 Type = FD->getType(); 220 ArraySize = 0; 221 MostDerivedLength = I + 1; 222 IsArray = false; 223 } else { 224 // Path[I] describes a base class. 225 ArraySize = 0; 226 IsArray = false; 227 } 228 } 229 return MostDerivedLength; 230 } 231 232 /// A path from a glvalue to a subobject of that glvalue. 233 struct SubobjectDesignator { 234 /// True if the subobject was named in a manner not supported by C++11. Such 235 /// lvalues can still be folded, but they are not core constant expressions 236 /// and we cannot perform lvalue-to-rvalue conversions on them. 237 unsigned Invalid : 1; 238 239 /// Is this a pointer one past the end of an object? 240 unsigned IsOnePastTheEnd : 1; 241 242 /// Indicator of whether the first entry is an unsized array. 243 unsigned FirstEntryIsAnUnsizedArray : 1; 244 245 /// Indicator of whether the most-derived object is an array element. 246 unsigned MostDerivedIsArrayElement : 1; 247 248 /// The length of the path to the most-derived object of which this is a 249 /// subobject. 250 unsigned MostDerivedPathLength : 28; 251 252 /// The size of the array of which the most-derived object is an element. 253 /// This will always be 0 if the most-derived object is not an array 254 /// element. 0 is not an indicator of whether or not the most-derived object 255 /// is an array, however, because 0-length arrays are allowed. 256 /// 257 /// If the current array is an unsized array, the value of this is 258 /// undefined. 259 uint64_t MostDerivedArraySize; 260 261 /// The type of the most derived object referred to by this address. 262 QualType MostDerivedType; 263 264 typedef APValue::LValuePathEntry PathEntry; 265 266 /// The entries on the path from the glvalue to the designated subobject. 267 SmallVector<PathEntry, 8> Entries; 268 269 SubobjectDesignator() : Invalid(true) {} 270 271 explicit SubobjectDesignator(QualType T) 272 : Invalid(false), IsOnePastTheEnd(false), 273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 274 MostDerivedPathLength(0), MostDerivedArraySize(0), 275 MostDerivedType(T) {} 276 277 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 278 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 280 MostDerivedPathLength(0), MostDerivedArraySize(0) { 281 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 282 if (!Invalid) { 283 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 284 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 285 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 286 if (V.getLValueBase()) { 287 bool IsArray = false; 288 bool FirstIsUnsizedArray = false; 289 MostDerivedPathLength = findMostDerivedSubobject( 290 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 291 MostDerivedType, IsArray, FirstIsUnsizedArray); 292 MostDerivedIsArrayElement = IsArray; 293 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 294 } 295 } 296 } 297 298 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 299 unsigned NewLength) { 300 if (Invalid) 301 return; 302 303 assert(Base && "cannot truncate path for null pointer"); 304 assert(NewLength <= Entries.size() && "not a truncation"); 305 306 if (NewLength == Entries.size()) 307 return; 308 Entries.resize(NewLength); 309 310 bool IsArray = false; 311 bool FirstIsUnsizedArray = false; 312 MostDerivedPathLength = findMostDerivedSubobject( 313 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 314 FirstIsUnsizedArray); 315 MostDerivedIsArrayElement = IsArray; 316 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 317 } 318 319 void setInvalid() { 320 Invalid = true; 321 Entries.clear(); 322 } 323 324 /// Determine whether the most derived subobject is an array without a 325 /// known bound. 326 bool isMostDerivedAnUnsizedArray() const { 327 assert(!Invalid && "Calling this makes no sense on invalid designators"); 328 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 329 } 330 331 /// Determine what the most derived array's size is. Results in an assertion 332 /// failure if the most derived array lacks a size. 333 uint64_t getMostDerivedArraySize() const { 334 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 335 return MostDerivedArraySize; 336 } 337 338 /// Determine whether this is a one-past-the-end pointer. 339 bool isOnePastTheEnd() const { 340 assert(!Invalid); 341 if (IsOnePastTheEnd) 342 return true; 343 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 344 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 345 MostDerivedArraySize) 346 return true; 347 return false; 348 } 349 350 /// Get the range of valid index adjustments in the form 351 /// {maximum value that can be subtracted from this pointer, 352 /// maximum value that can be added to this pointer} 353 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 354 if (Invalid || isMostDerivedAnUnsizedArray()) 355 return {0, 0}; 356 357 // [expr.add]p4: For the purposes of these operators, a pointer to a 358 // nonarray object behaves the same as a pointer to the first element of 359 // an array of length one with the type of the object as its element type. 360 bool IsArray = MostDerivedPathLength == Entries.size() && 361 MostDerivedIsArrayElement; 362 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 363 : (uint64_t)IsOnePastTheEnd; 364 uint64_t ArraySize = 365 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 366 return {ArrayIndex, ArraySize - ArrayIndex}; 367 } 368 369 /// Check that this refers to a valid subobject. 370 bool isValidSubobject() const { 371 if (Invalid) 372 return false; 373 return !isOnePastTheEnd(); 374 } 375 /// Check that this refers to a valid subobject, and if not, produce a 376 /// relevant diagnostic and set the designator as invalid. 377 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 378 379 /// Get the type of the designated object. 380 QualType getType(ASTContext &Ctx) const { 381 assert(!Invalid && "invalid designator has no subobject type"); 382 return MostDerivedPathLength == Entries.size() 383 ? MostDerivedType 384 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 385 } 386 387 /// Update this designator to refer to the first element within this array. 388 void addArrayUnchecked(const ConstantArrayType *CAT) { 389 Entries.push_back(PathEntry::ArrayIndex(0)); 390 391 // This is a most-derived object. 392 MostDerivedType = CAT->getElementType(); 393 MostDerivedIsArrayElement = true; 394 MostDerivedArraySize = CAT->getSize().getZExtValue(); 395 MostDerivedPathLength = Entries.size(); 396 } 397 /// Update this designator to refer to the first element within the array of 398 /// elements of type T. This is an array of unknown size. 399 void addUnsizedArrayUnchecked(QualType ElemTy) { 400 Entries.push_back(PathEntry::ArrayIndex(0)); 401 402 MostDerivedType = ElemTy; 403 MostDerivedIsArrayElement = true; 404 // The value in MostDerivedArraySize is undefined in this case. So, set it 405 // to an arbitrary value that's likely to loudly break things if it's 406 // used. 407 MostDerivedArraySize = AssumedSizeForUnsizedArray; 408 MostDerivedPathLength = Entries.size(); 409 } 410 /// Update this designator to refer to the given base or member of this 411 /// object. 412 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 413 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 414 415 // If this isn't a base class, it's a new most-derived object. 416 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 417 MostDerivedType = FD->getType(); 418 MostDerivedIsArrayElement = false; 419 MostDerivedArraySize = 0; 420 MostDerivedPathLength = Entries.size(); 421 } 422 } 423 /// Update this designator to refer to the given complex component. 424 void addComplexUnchecked(QualType EltTy, bool Imag) { 425 Entries.push_back(PathEntry::ArrayIndex(Imag)); 426 427 // This is technically a most-derived object, though in practice this 428 // is unlikely to matter. 429 MostDerivedType = EltTy; 430 MostDerivedIsArrayElement = true; 431 MostDerivedArraySize = 2; 432 MostDerivedPathLength = Entries.size(); 433 } 434 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 435 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 436 const APSInt &N); 437 /// Add N to the address of this subobject. 438 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 439 if (Invalid || !N) return; 440 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 441 if (isMostDerivedAnUnsizedArray()) { 442 diagnoseUnsizedArrayPointerArithmetic(Info, E); 443 // Can't verify -- trust that the user is doing the right thing (or if 444 // not, trust that the caller will catch the bad behavior). 445 // FIXME: Should we reject if this overflows, at least? 446 Entries.back() = PathEntry::ArrayIndex( 447 Entries.back().getAsArrayIndex() + TruncatedN); 448 return; 449 } 450 451 // [expr.add]p4: For the purposes of these operators, a pointer to a 452 // nonarray object behaves the same as a pointer to the first element of 453 // an array of length one with the type of the object as its element type. 454 bool IsArray = MostDerivedPathLength == Entries.size() && 455 MostDerivedIsArrayElement; 456 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 457 : (uint64_t)IsOnePastTheEnd; 458 uint64_t ArraySize = 459 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 460 461 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 462 // Calculate the actual index in a wide enough type, so we can include 463 // it in the note. 464 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 465 (llvm::APInt&)N += ArrayIndex; 466 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 467 diagnosePointerArithmetic(Info, E, N); 468 setInvalid(); 469 return; 470 } 471 472 ArrayIndex += TruncatedN; 473 assert(ArrayIndex <= ArraySize && 474 "bounds check succeeded for out-of-bounds index"); 475 476 if (IsArray) 477 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 478 else 479 IsOnePastTheEnd = (ArrayIndex != 0); 480 } 481 }; 482 483 /// A scope at the end of which an object can need to be destroyed. 484 enum class ScopeKind { 485 Block, 486 FullExpression, 487 Call 488 }; 489 490 /// A reference to a particular call and its arguments. 491 struct CallRef { 492 CallRef() : OrigCallee(), CallIndex(0), Version() {} 493 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 494 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 495 496 explicit operator bool() const { return OrigCallee; } 497 498 /// Get the parameter that the caller initialized, corresponding to the 499 /// given parameter in the callee. 500 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 501 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 502 : PVD; 503 } 504 505 /// The callee at the point where the arguments were evaluated. This might 506 /// be different from the actual callee (a different redeclaration, or a 507 /// virtual override), but this function's parameters are the ones that 508 /// appear in the parameter map. 509 const FunctionDecl *OrigCallee; 510 /// The call index of the frame that holds the argument values. 511 unsigned CallIndex; 512 /// The version of the parameters corresponding to this call. 513 unsigned Version; 514 }; 515 516 /// A stack frame in the constexpr call stack. 517 class CallStackFrame : public interp::Frame { 518 public: 519 EvalInfo &Info; 520 521 /// Parent - The caller of this stack frame. 522 CallStackFrame *Caller; 523 524 /// Callee - The function which was called. 525 const FunctionDecl *Callee; 526 527 /// This - The binding for the this pointer in this call, if any. 528 const LValue *This; 529 530 /// Information on how to find the arguments to this call. Our arguments 531 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 532 /// key and this value as the version. 533 CallRef Arguments; 534 535 /// Source location information about the default argument or default 536 /// initializer expression we're evaluating, if any. 537 CurrentSourceLocExprScope CurSourceLocExprScope; 538 539 // Note that we intentionally use std::map here so that references to 540 // values are stable. 541 typedef std::pair<const void *, unsigned> MapKeyTy; 542 typedef std::map<MapKeyTy, APValue> MapTy; 543 /// Temporaries - Temporary lvalues materialized within this stack frame. 544 MapTy Temporaries; 545 546 /// CallLoc - The location of the call expression for this call. 547 SourceLocation CallLoc; 548 549 /// Index - The call index of this call. 550 unsigned Index; 551 552 /// The stack of integers for tracking version numbers for temporaries. 553 SmallVector<unsigned, 2> TempVersionStack = {1}; 554 unsigned CurTempVersion = TempVersionStack.back(); 555 556 unsigned getTempVersion() const { return TempVersionStack.back(); } 557 558 void pushTempVersion() { 559 TempVersionStack.push_back(++CurTempVersion); 560 } 561 562 void popTempVersion() { 563 TempVersionStack.pop_back(); 564 } 565 566 CallRef createCall(const FunctionDecl *Callee) { 567 return {Callee, Index, ++CurTempVersion}; 568 } 569 570 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 571 // on the overall stack usage of deeply-recursing constexpr evaluations. 572 // (We should cache this map rather than recomputing it repeatedly.) 573 // But let's try this and see how it goes; we can look into caching the map 574 // as a later change. 575 576 /// LambdaCaptureFields - Mapping from captured variables/this to 577 /// corresponding data members in the closure class. 578 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 579 FieldDecl *LambdaThisCaptureField; 580 581 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 582 const FunctionDecl *Callee, const LValue *This, 583 CallRef Arguments); 584 ~CallStackFrame(); 585 586 // Return the temporary for Key whose version number is Version. 587 APValue *getTemporary(const void *Key, unsigned Version) { 588 MapKeyTy KV(Key, Version); 589 auto LB = Temporaries.lower_bound(KV); 590 if (LB != Temporaries.end() && LB->first == KV) 591 return &LB->second; 592 // Pair (Key,Version) wasn't found in the map. Check that no elements 593 // in the map have 'Key' as their key. 594 assert((LB == Temporaries.end() || LB->first.first != Key) && 595 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 596 "Element with key 'Key' found in map"); 597 return nullptr; 598 } 599 600 // Return the current temporary for Key in the map. 601 APValue *getCurrentTemporary(const void *Key) { 602 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 603 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 604 return &std::prev(UB)->second; 605 return nullptr; 606 } 607 608 // Return the version number of the current temporary for Key. 609 unsigned getCurrentTemporaryVersion(const void *Key) const { 610 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 611 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 612 return std::prev(UB)->first.second; 613 return 0; 614 } 615 616 /// Allocate storage for an object of type T in this stack frame. 617 /// Populates LV with a handle to the created object. Key identifies 618 /// the temporary within the stack frame, and must not be reused without 619 /// bumping the temporary version number. 620 template<typename KeyT> 621 APValue &createTemporary(const KeyT *Key, QualType T, 622 ScopeKind Scope, LValue &LV); 623 624 /// Allocate storage for a parameter of a function call made in this frame. 625 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 626 627 void describe(llvm::raw_ostream &OS) override; 628 629 Frame *getCaller() const override { return Caller; } 630 SourceLocation getCallLocation() const override { return CallLoc; } 631 const FunctionDecl *getCallee() const override { return Callee; } 632 633 bool isStdFunction() const { 634 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 635 if (DC->isStdNamespace()) 636 return true; 637 return false; 638 } 639 640 private: 641 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 642 ScopeKind Scope); 643 }; 644 645 /// Temporarily override 'this'. 646 class ThisOverrideRAII { 647 public: 648 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 649 : Frame(Frame), OldThis(Frame.This) { 650 if (Enable) 651 Frame.This = NewThis; 652 } 653 ~ThisOverrideRAII() { 654 Frame.This = OldThis; 655 } 656 private: 657 CallStackFrame &Frame; 658 const LValue *OldThis; 659 }; 660 } 661 662 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 663 const LValue &This, QualType ThisType); 664 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 665 APValue::LValueBase LVBase, APValue &Value, 666 QualType T); 667 668 namespace { 669 /// A cleanup, and a flag indicating whether it is lifetime-extended. 670 class Cleanup { 671 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 672 APValue::LValueBase Base; 673 QualType T; 674 675 public: 676 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 677 ScopeKind Scope) 678 : Value(Val, Scope), Base(Base), T(T) {} 679 680 /// Determine whether this cleanup should be performed at the end of the 681 /// given kind of scope. 682 bool isDestroyedAtEndOf(ScopeKind K) const { 683 return (int)Value.getInt() >= (int)K; 684 } 685 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 686 if (RunDestructors) { 687 SourceLocation Loc; 688 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 689 Loc = VD->getLocation(); 690 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 691 Loc = E->getExprLoc(); 692 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 693 } 694 *Value.getPointer() = APValue(); 695 return true; 696 } 697 698 bool hasSideEffect() { 699 return T.isDestructedType(); 700 } 701 }; 702 703 /// A reference to an object whose construction we are currently evaluating. 704 struct ObjectUnderConstruction { 705 APValue::LValueBase Base; 706 ArrayRef<APValue::LValuePathEntry> Path; 707 friend bool operator==(const ObjectUnderConstruction &LHS, 708 const ObjectUnderConstruction &RHS) { 709 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 710 } 711 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 712 return llvm::hash_combine(Obj.Base, Obj.Path); 713 } 714 }; 715 enum class ConstructionPhase { 716 None, 717 Bases, 718 AfterBases, 719 AfterFields, 720 Destroying, 721 DestroyingBases 722 }; 723 } 724 725 namespace llvm { 726 template<> struct DenseMapInfo<ObjectUnderConstruction> { 727 using Base = DenseMapInfo<APValue::LValueBase>; 728 static ObjectUnderConstruction getEmptyKey() { 729 return {Base::getEmptyKey(), {}}; } 730 static ObjectUnderConstruction getTombstoneKey() { 731 return {Base::getTombstoneKey(), {}}; 732 } 733 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 734 return hash_value(Object); 735 } 736 static bool isEqual(const ObjectUnderConstruction &LHS, 737 const ObjectUnderConstruction &RHS) { 738 return LHS == RHS; 739 } 740 }; 741 } 742 743 namespace { 744 /// A dynamically-allocated heap object. 745 struct DynAlloc { 746 /// The value of this heap-allocated object. 747 APValue Value; 748 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 749 /// or a CallExpr (the latter is for direct calls to operator new inside 750 /// std::allocator<T>::allocate). 751 const Expr *AllocExpr = nullptr; 752 753 enum Kind { 754 New, 755 ArrayNew, 756 StdAllocator 757 }; 758 759 /// Get the kind of the allocation. This must match between allocation 760 /// and deallocation. 761 Kind getKind() const { 762 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 763 return NE->isArray() ? ArrayNew : New; 764 assert(isa<CallExpr>(AllocExpr)); 765 return StdAllocator; 766 } 767 }; 768 769 struct DynAllocOrder { 770 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 771 return L.getIndex() < R.getIndex(); 772 } 773 }; 774 775 /// EvalInfo - This is a private struct used by the evaluator to capture 776 /// information about a subexpression as it is folded. It retains information 777 /// about the AST context, but also maintains information about the folded 778 /// expression. 779 /// 780 /// If an expression could be evaluated, it is still possible it is not a C 781 /// "integer constant expression" or constant expression. If not, this struct 782 /// captures information about how and why not. 783 /// 784 /// One bit of information passed *into* the request for constant folding 785 /// indicates whether the subexpression is "evaluated" or not according to C 786 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 787 /// evaluate the expression regardless of what the RHS is, but C only allows 788 /// certain things in certain situations. 789 class EvalInfo : public interp::State { 790 public: 791 ASTContext &Ctx; 792 793 /// EvalStatus - Contains information about the evaluation. 794 Expr::EvalStatus &EvalStatus; 795 796 /// CurrentCall - The top of the constexpr call stack. 797 CallStackFrame *CurrentCall; 798 799 /// CallStackDepth - The number of calls in the call stack right now. 800 unsigned CallStackDepth; 801 802 /// NextCallIndex - The next call index to assign. 803 unsigned NextCallIndex; 804 805 /// StepsLeft - The remaining number of evaluation steps we're permitted 806 /// to perform. This is essentially a limit for the number of statements 807 /// we will evaluate. 808 unsigned StepsLeft; 809 810 /// Enable the experimental new constant interpreter. If an expression is 811 /// not supported by the interpreter, an error is triggered. 812 bool EnableNewConstInterp; 813 814 /// BottomFrame - The frame in which evaluation started. This must be 815 /// initialized after CurrentCall and CallStackDepth. 816 CallStackFrame BottomFrame; 817 818 /// A stack of values whose lifetimes end at the end of some surrounding 819 /// evaluation frame. 820 llvm::SmallVector<Cleanup, 16> CleanupStack; 821 822 /// EvaluatingDecl - This is the declaration whose initializer is being 823 /// evaluated, if any. 824 APValue::LValueBase EvaluatingDecl; 825 826 enum class EvaluatingDeclKind { 827 None, 828 /// We're evaluating the construction of EvaluatingDecl. 829 Ctor, 830 /// We're evaluating the destruction of EvaluatingDecl. 831 Dtor, 832 }; 833 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 834 835 /// EvaluatingDeclValue - This is the value being constructed for the 836 /// declaration whose initializer is being evaluated, if any. 837 APValue *EvaluatingDeclValue; 838 839 /// Set of objects that are currently being constructed. 840 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 841 ObjectsUnderConstruction; 842 843 /// Current heap allocations, along with the location where each was 844 /// allocated. We use std::map here because we need stable addresses 845 /// for the stored APValues. 846 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 847 848 /// The number of heap allocations performed so far in this evaluation. 849 unsigned NumHeapAllocs = 0; 850 851 struct EvaluatingConstructorRAII { 852 EvalInfo &EI; 853 ObjectUnderConstruction Object; 854 bool DidInsert; 855 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 856 bool HasBases) 857 : EI(EI), Object(Object) { 858 DidInsert = 859 EI.ObjectsUnderConstruction 860 .insert({Object, HasBases ? ConstructionPhase::Bases 861 : ConstructionPhase::AfterBases}) 862 .second; 863 } 864 void finishedConstructingBases() { 865 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 866 } 867 void finishedConstructingFields() { 868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 869 } 870 ~EvaluatingConstructorRAII() { 871 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 872 } 873 }; 874 875 struct EvaluatingDestructorRAII { 876 EvalInfo &EI; 877 ObjectUnderConstruction Object; 878 bool DidInsert; 879 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 880 : EI(EI), Object(Object) { 881 DidInsert = EI.ObjectsUnderConstruction 882 .insert({Object, ConstructionPhase::Destroying}) 883 .second; 884 } 885 void startedDestroyingBases() { 886 EI.ObjectsUnderConstruction[Object] = 887 ConstructionPhase::DestroyingBases; 888 } 889 ~EvaluatingDestructorRAII() { 890 if (DidInsert) 891 EI.ObjectsUnderConstruction.erase(Object); 892 } 893 }; 894 895 ConstructionPhase 896 isEvaluatingCtorDtor(APValue::LValueBase Base, 897 ArrayRef<APValue::LValuePathEntry> Path) { 898 return ObjectsUnderConstruction.lookup({Base, Path}); 899 } 900 901 /// If we're currently speculatively evaluating, the outermost call stack 902 /// depth at which we can mutate state, otherwise 0. 903 unsigned SpeculativeEvaluationDepth = 0; 904 905 /// The current array initialization index, if we're performing array 906 /// initialization. 907 uint64_t ArrayInitIndex = -1; 908 909 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 910 /// notes attached to it will also be stored, otherwise they will not be. 911 bool HasActiveDiagnostic; 912 913 /// Have we emitted a diagnostic explaining why we couldn't constant 914 /// fold (not just why it's not strictly a constant expression)? 915 bool HasFoldFailureDiagnostic; 916 917 /// Whether or not we're in a context where the front end requires a 918 /// constant value. 919 bool InConstantContext; 920 921 /// Whether we're checking that an expression is a potential constant 922 /// expression. If so, do not fail on constructs that could become constant 923 /// later on (such as a use of an undefined global). 924 bool CheckingPotentialConstantExpression = false; 925 926 /// Whether we're checking for an expression that has undefined behavior. 927 /// If so, we will produce warnings if we encounter an operation that is 928 /// always undefined. 929 bool CheckingForUndefinedBehavior = false; 930 931 enum EvaluationMode { 932 /// Evaluate as a constant expression. Stop if we find that the expression 933 /// is not a constant expression. 934 EM_ConstantExpression, 935 936 /// Evaluate as a constant expression. Stop if we find that the expression 937 /// is not a constant expression. Some expressions can be retried in the 938 /// optimizer if we don't constant fold them here, but in an unevaluated 939 /// context we try to fold them immediately since the optimizer never 940 /// gets a chance to look at it. 941 EM_ConstantExpressionUnevaluated, 942 943 /// Fold the expression to a constant. Stop if we hit a side-effect that 944 /// we can't model. 945 EM_ConstantFold, 946 947 /// Evaluate in any way we know how. Don't worry about side-effects that 948 /// can't be modeled. 949 EM_IgnoreSideEffects, 950 } EvalMode; 951 952 /// Are we checking whether the expression is a potential constant 953 /// expression? 954 bool checkingPotentialConstantExpression() const override { 955 return CheckingPotentialConstantExpression; 956 } 957 958 /// Are we checking an expression for overflow? 959 // FIXME: We should check for any kind of undefined or suspicious behavior 960 // in such constructs, not just overflow. 961 bool checkingForUndefinedBehavior() const override { 962 return CheckingForUndefinedBehavior; 963 } 964 965 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 966 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 967 CallStackDepth(0), NextCallIndex(1), 968 StepsLeft(C.getLangOpts().ConstexprStepLimit), 969 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 970 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 971 EvaluatingDecl((const ValueDecl *)nullptr), 972 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 973 HasFoldFailureDiagnostic(false), InConstantContext(false), 974 EvalMode(Mode) {} 975 976 ~EvalInfo() { 977 discardCleanups(); 978 } 979 980 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 981 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 982 EvaluatingDecl = Base; 983 IsEvaluatingDecl = EDK; 984 EvaluatingDeclValue = &Value; 985 } 986 987 bool CheckCallLimit(SourceLocation Loc) { 988 // Don't perform any constexpr calls (other than the call we're checking) 989 // when checking a potential constant expression. 990 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 991 return false; 992 if (NextCallIndex == 0) { 993 // NextCallIndex has wrapped around. 994 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 995 return false; 996 } 997 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 998 return true; 999 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1000 << getLangOpts().ConstexprCallDepth; 1001 return false; 1002 } 1003 1004 std::pair<CallStackFrame *, unsigned> 1005 getCallFrameAndDepth(unsigned CallIndex) { 1006 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1007 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1008 // be null in this loop. 1009 unsigned Depth = CallStackDepth; 1010 CallStackFrame *Frame = CurrentCall; 1011 while (Frame->Index > CallIndex) { 1012 Frame = Frame->Caller; 1013 --Depth; 1014 } 1015 if (Frame->Index == CallIndex) 1016 return {Frame, Depth}; 1017 return {nullptr, 0}; 1018 } 1019 1020 bool nextStep(const Stmt *S) { 1021 if (!StepsLeft) { 1022 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1023 return false; 1024 } 1025 --StepsLeft; 1026 return true; 1027 } 1028 1029 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1030 1031 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1032 Optional<DynAlloc*> Result; 1033 auto It = HeapAllocs.find(DA); 1034 if (It != HeapAllocs.end()) 1035 Result = &It->second; 1036 return Result; 1037 } 1038 1039 /// Get the allocated storage for the given parameter of the given call. 1040 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1041 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1042 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1043 : nullptr; 1044 } 1045 1046 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1047 struct StdAllocatorCaller { 1048 unsigned FrameIndex; 1049 QualType ElemType; 1050 explicit operator bool() const { return FrameIndex != 0; }; 1051 }; 1052 1053 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1054 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1055 Call = Call->Caller) { 1056 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1057 if (!MD) 1058 continue; 1059 const IdentifierInfo *FnII = MD->getIdentifier(); 1060 if (!FnII || !FnII->isStr(FnName)) 1061 continue; 1062 1063 const auto *CTSD = 1064 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1065 if (!CTSD) 1066 continue; 1067 1068 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1069 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1070 if (CTSD->isInStdNamespace() && ClassII && 1071 ClassII->isStr("allocator") && TAL.size() >= 1 && 1072 TAL[0].getKind() == TemplateArgument::Type) 1073 return {Call->Index, TAL[0].getAsType()}; 1074 } 1075 1076 return {}; 1077 } 1078 1079 void performLifetimeExtension() { 1080 // Disable the cleanups for lifetime-extended temporaries. 1081 CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1082 CleanupStack.end(), 1083 [](Cleanup &C) { 1084 return !C.isDestroyedAtEndOf( 1085 ScopeKind::FullExpression); 1086 }), 1087 CleanupStack.end()); 1088 } 1089 1090 /// Throw away any remaining cleanups at the end of evaluation. If any 1091 /// cleanups would have had a side-effect, note that as an unmodeled 1092 /// side-effect and return false. Otherwise, return true. 1093 bool discardCleanups() { 1094 for (Cleanup &C : CleanupStack) { 1095 if (C.hasSideEffect() && !noteSideEffect()) { 1096 CleanupStack.clear(); 1097 return false; 1098 } 1099 } 1100 CleanupStack.clear(); 1101 return true; 1102 } 1103 1104 private: 1105 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1106 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1107 1108 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1109 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1110 1111 void setFoldFailureDiagnostic(bool Flag) override { 1112 HasFoldFailureDiagnostic = Flag; 1113 } 1114 1115 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1116 1117 ASTContext &getCtx() const override { return Ctx; } 1118 1119 // If we have a prior diagnostic, it will be noting that the expression 1120 // isn't a constant expression. This diagnostic is more important, 1121 // unless we require this evaluation to produce a constant expression. 1122 // 1123 // FIXME: We might want to show both diagnostics to the user in 1124 // EM_ConstantFold mode. 1125 bool hasPriorDiagnostic() override { 1126 if (!EvalStatus.Diag->empty()) { 1127 switch (EvalMode) { 1128 case EM_ConstantFold: 1129 case EM_IgnoreSideEffects: 1130 if (!HasFoldFailureDiagnostic) 1131 break; 1132 // We've already failed to fold something. Keep that diagnostic. 1133 LLVM_FALLTHROUGH; 1134 case EM_ConstantExpression: 1135 case EM_ConstantExpressionUnevaluated: 1136 setActiveDiagnostic(false); 1137 return true; 1138 } 1139 } 1140 return false; 1141 } 1142 1143 unsigned getCallStackDepth() override { return CallStackDepth; } 1144 1145 public: 1146 /// Should we continue evaluation after encountering a side-effect that we 1147 /// couldn't model? 1148 bool keepEvaluatingAfterSideEffect() { 1149 switch (EvalMode) { 1150 case EM_IgnoreSideEffects: 1151 return true; 1152 1153 case EM_ConstantExpression: 1154 case EM_ConstantExpressionUnevaluated: 1155 case EM_ConstantFold: 1156 // By default, assume any side effect might be valid in some other 1157 // evaluation of this expression from a different context. 1158 return checkingPotentialConstantExpression() || 1159 checkingForUndefinedBehavior(); 1160 } 1161 llvm_unreachable("Missed EvalMode case"); 1162 } 1163 1164 /// Note that we have had a side-effect, and determine whether we should 1165 /// keep evaluating. 1166 bool noteSideEffect() { 1167 EvalStatus.HasSideEffects = true; 1168 return keepEvaluatingAfterSideEffect(); 1169 } 1170 1171 /// Should we continue evaluation after encountering undefined behavior? 1172 bool keepEvaluatingAfterUndefinedBehavior() { 1173 switch (EvalMode) { 1174 case EM_IgnoreSideEffects: 1175 case EM_ConstantFold: 1176 return true; 1177 1178 case EM_ConstantExpression: 1179 case EM_ConstantExpressionUnevaluated: 1180 return checkingForUndefinedBehavior(); 1181 } 1182 llvm_unreachable("Missed EvalMode case"); 1183 } 1184 1185 /// Note that we hit something that was technically undefined behavior, but 1186 /// that we can evaluate past it (such as signed overflow or floating-point 1187 /// division by zero.) 1188 bool noteUndefinedBehavior() override { 1189 EvalStatus.HasUndefinedBehavior = true; 1190 return keepEvaluatingAfterUndefinedBehavior(); 1191 } 1192 1193 /// Should we continue evaluation as much as possible after encountering a 1194 /// construct which can't be reduced to a value? 1195 bool keepEvaluatingAfterFailure() const override { 1196 if (!StepsLeft) 1197 return false; 1198 1199 switch (EvalMode) { 1200 case EM_ConstantExpression: 1201 case EM_ConstantExpressionUnevaluated: 1202 case EM_ConstantFold: 1203 case EM_IgnoreSideEffects: 1204 return checkingPotentialConstantExpression() || 1205 checkingForUndefinedBehavior(); 1206 } 1207 llvm_unreachable("Missed EvalMode case"); 1208 } 1209 1210 /// Notes that we failed to evaluate an expression that other expressions 1211 /// directly depend on, and determine if we should keep evaluating. This 1212 /// should only be called if we actually intend to keep evaluating. 1213 /// 1214 /// Call noteSideEffect() instead if we may be able to ignore the value that 1215 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1216 /// 1217 /// (Foo(), 1) // use noteSideEffect 1218 /// (Foo() || true) // use noteSideEffect 1219 /// Foo() + 1 // use noteFailure 1220 LLVM_NODISCARD bool noteFailure() { 1221 // Failure when evaluating some expression often means there is some 1222 // subexpression whose evaluation was skipped. Therefore, (because we 1223 // don't track whether we skipped an expression when unwinding after an 1224 // evaluation failure) every evaluation failure that bubbles up from a 1225 // subexpression implies that a side-effect has potentially happened. We 1226 // skip setting the HasSideEffects flag to true until we decide to 1227 // continue evaluating after that point, which happens here. 1228 bool KeepGoing = keepEvaluatingAfterFailure(); 1229 EvalStatus.HasSideEffects |= KeepGoing; 1230 return KeepGoing; 1231 } 1232 1233 class ArrayInitLoopIndex { 1234 EvalInfo &Info; 1235 uint64_t OuterIndex; 1236 1237 public: 1238 ArrayInitLoopIndex(EvalInfo &Info) 1239 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1240 Info.ArrayInitIndex = 0; 1241 } 1242 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1243 1244 operator uint64_t&() { return Info.ArrayInitIndex; } 1245 }; 1246 }; 1247 1248 /// Object used to treat all foldable expressions as constant expressions. 1249 struct FoldConstant { 1250 EvalInfo &Info; 1251 bool Enabled; 1252 bool HadNoPriorDiags; 1253 EvalInfo::EvaluationMode OldMode; 1254 1255 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1256 : Info(Info), 1257 Enabled(Enabled), 1258 HadNoPriorDiags(Info.EvalStatus.Diag && 1259 Info.EvalStatus.Diag->empty() && 1260 !Info.EvalStatus.HasSideEffects), 1261 OldMode(Info.EvalMode) { 1262 if (Enabled) 1263 Info.EvalMode = EvalInfo::EM_ConstantFold; 1264 } 1265 void keepDiagnostics() { Enabled = false; } 1266 ~FoldConstant() { 1267 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1268 !Info.EvalStatus.HasSideEffects) 1269 Info.EvalStatus.Diag->clear(); 1270 Info.EvalMode = OldMode; 1271 } 1272 }; 1273 1274 /// RAII object used to set the current evaluation mode to ignore 1275 /// side-effects. 1276 struct IgnoreSideEffectsRAII { 1277 EvalInfo &Info; 1278 EvalInfo::EvaluationMode OldMode; 1279 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1280 : Info(Info), OldMode(Info.EvalMode) { 1281 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1282 } 1283 1284 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1285 }; 1286 1287 /// RAII object used to optionally suppress diagnostics and side-effects from 1288 /// a speculative evaluation. 1289 class SpeculativeEvaluationRAII { 1290 EvalInfo *Info = nullptr; 1291 Expr::EvalStatus OldStatus; 1292 unsigned OldSpeculativeEvaluationDepth; 1293 1294 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1295 Info = Other.Info; 1296 OldStatus = Other.OldStatus; 1297 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1298 Other.Info = nullptr; 1299 } 1300 1301 void maybeRestoreState() { 1302 if (!Info) 1303 return; 1304 1305 Info->EvalStatus = OldStatus; 1306 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1307 } 1308 1309 public: 1310 SpeculativeEvaluationRAII() = default; 1311 1312 SpeculativeEvaluationRAII( 1313 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1314 : Info(&Info), OldStatus(Info.EvalStatus), 1315 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1316 Info.EvalStatus.Diag = NewDiag; 1317 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1318 } 1319 1320 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1321 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1322 moveFromAndCancel(std::move(Other)); 1323 } 1324 1325 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1326 maybeRestoreState(); 1327 moveFromAndCancel(std::move(Other)); 1328 return *this; 1329 } 1330 1331 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1332 }; 1333 1334 /// RAII object wrapping a full-expression or block scope, and handling 1335 /// the ending of the lifetime of temporaries created within it. 1336 template<ScopeKind Kind> 1337 class ScopeRAII { 1338 EvalInfo &Info; 1339 unsigned OldStackSize; 1340 public: 1341 ScopeRAII(EvalInfo &Info) 1342 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1343 // Push a new temporary version. This is needed to distinguish between 1344 // temporaries created in different iterations of a loop. 1345 Info.CurrentCall->pushTempVersion(); 1346 } 1347 bool destroy(bool RunDestructors = true) { 1348 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1349 OldStackSize = -1U; 1350 return OK; 1351 } 1352 ~ScopeRAII() { 1353 if (OldStackSize != -1U) 1354 destroy(false); 1355 // Body moved to a static method to encourage the compiler to inline away 1356 // instances of this class. 1357 Info.CurrentCall->popTempVersion(); 1358 } 1359 private: 1360 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1361 unsigned OldStackSize) { 1362 assert(OldStackSize <= Info.CleanupStack.size() && 1363 "running cleanups out of order?"); 1364 1365 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1366 // for a full-expression scope. 1367 bool Success = true; 1368 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1369 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1370 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1371 Success = false; 1372 break; 1373 } 1374 } 1375 } 1376 1377 // Compact any retained cleanups. 1378 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1379 if (Kind != ScopeKind::Block) 1380 NewEnd = 1381 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1382 return C.isDestroyedAtEndOf(Kind); 1383 }); 1384 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1385 return Success; 1386 } 1387 }; 1388 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1389 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1390 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1391 } 1392 1393 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1394 CheckSubobjectKind CSK) { 1395 if (Invalid) 1396 return false; 1397 if (isOnePastTheEnd()) { 1398 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1399 << CSK; 1400 setInvalid(); 1401 return false; 1402 } 1403 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1404 // must actually be at least one array element; even a VLA cannot have a 1405 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1406 return true; 1407 } 1408 1409 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1410 const Expr *E) { 1411 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1412 // Do not set the designator as invalid: we can represent this situation, 1413 // and correct handling of __builtin_object_size requires us to do so. 1414 } 1415 1416 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1417 const Expr *E, 1418 const APSInt &N) { 1419 // If we're complaining, we must be able to statically determine the size of 1420 // the most derived array. 1421 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1422 Info.CCEDiag(E, diag::note_constexpr_array_index) 1423 << N << /*array*/ 0 1424 << static_cast<unsigned>(getMostDerivedArraySize()); 1425 else 1426 Info.CCEDiag(E, diag::note_constexpr_array_index) 1427 << N << /*non-array*/ 1; 1428 setInvalid(); 1429 } 1430 1431 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1432 const FunctionDecl *Callee, const LValue *This, 1433 CallRef Call) 1434 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1435 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1436 Info.CurrentCall = this; 1437 ++Info.CallStackDepth; 1438 } 1439 1440 CallStackFrame::~CallStackFrame() { 1441 assert(Info.CurrentCall == this && "calls retired out of order"); 1442 --Info.CallStackDepth; 1443 Info.CurrentCall = Caller; 1444 } 1445 1446 static bool isRead(AccessKinds AK) { 1447 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1448 } 1449 1450 static bool isModification(AccessKinds AK) { 1451 switch (AK) { 1452 case AK_Read: 1453 case AK_ReadObjectRepresentation: 1454 case AK_MemberCall: 1455 case AK_DynamicCast: 1456 case AK_TypeId: 1457 return false; 1458 case AK_Assign: 1459 case AK_Increment: 1460 case AK_Decrement: 1461 case AK_Construct: 1462 case AK_Destroy: 1463 return true; 1464 } 1465 llvm_unreachable("unknown access kind"); 1466 } 1467 1468 static bool isAnyAccess(AccessKinds AK) { 1469 return isRead(AK) || isModification(AK); 1470 } 1471 1472 /// Is this an access per the C++ definition? 1473 static bool isFormalAccess(AccessKinds AK) { 1474 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1475 } 1476 1477 /// Is this kind of axcess valid on an indeterminate object value? 1478 static bool isValidIndeterminateAccess(AccessKinds AK) { 1479 switch (AK) { 1480 case AK_Read: 1481 case AK_Increment: 1482 case AK_Decrement: 1483 // These need the object's value. 1484 return false; 1485 1486 case AK_ReadObjectRepresentation: 1487 case AK_Assign: 1488 case AK_Construct: 1489 case AK_Destroy: 1490 // Construction and destruction don't need the value. 1491 return true; 1492 1493 case AK_MemberCall: 1494 case AK_DynamicCast: 1495 case AK_TypeId: 1496 // These aren't really meaningful on scalars. 1497 return true; 1498 } 1499 llvm_unreachable("unknown access kind"); 1500 } 1501 1502 namespace { 1503 struct ComplexValue { 1504 private: 1505 bool IsInt; 1506 1507 public: 1508 APSInt IntReal, IntImag; 1509 APFloat FloatReal, FloatImag; 1510 1511 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1512 1513 void makeComplexFloat() { IsInt = false; } 1514 bool isComplexFloat() const { return !IsInt; } 1515 APFloat &getComplexFloatReal() { return FloatReal; } 1516 APFloat &getComplexFloatImag() { return FloatImag; } 1517 1518 void makeComplexInt() { IsInt = true; } 1519 bool isComplexInt() const { return IsInt; } 1520 APSInt &getComplexIntReal() { return IntReal; } 1521 APSInt &getComplexIntImag() { return IntImag; } 1522 1523 void moveInto(APValue &v) const { 1524 if (isComplexFloat()) 1525 v = APValue(FloatReal, FloatImag); 1526 else 1527 v = APValue(IntReal, IntImag); 1528 } 1529 void setFrom(const APValue &v) { 1530 assert(v.isComplexFloat() || v.isComplexInt()); 1531 if (v.isComplexFloat()) { 1532 makeComplexFloat(); 1533 FloatReal = v.getComplexFloatReal(); 1534 FloatImag = v.getComplexFloatImag(); 1535 } else { 1536 makeComplexInt(); 1537 IntReal = v.getComplexIntReal(); 1538 IntImag = v.getComplexIntImag(); 1539 } 1540 } 1541 }; 1542 1543 struct LValue { 1544 APValue::LValueBase Base; 1545 CharUnits Offset; 1546 SubobjectDesignator Designator; 1547 bool IsNullPtr : 1; 1548 bool InvalidBase : 1; 1549 1550 const APValue::LValueBase getLValueBase() const { return Base; } 1551 CharUnits &getLValueOffset() { return Offset; } 1552 const CharUnits &getLValueOffset() const { return Offset; } 1553 SubobjectDesignator &getLValueDesignator() { return Designator; } 1554 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1555 bool isNullPointer() const { return IsNullPtr;} 1556 1557 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1558 unsigned getLValueVersion() const { return Base.getVersion(); } 1559 1560 void moveInto(APValue &V) const { 1561 if (Designator.Invalid) 1562 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1563 else { 1564 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1565 V = APValue(Base, Offset, Designator.Entries, 1566 Designator.IsOnePastTheEnd, IsNullPtr); 1567 } 1568 } 1569 void setFrom(ASTContext &Ctx, const APValue &V) { 1570 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1571 Base = V.getLValueBase(); 1572 Offset = V.getLValueOffset(); 1573 InvalidBase = false; 1574 Designator = SubobjectDesignator(Ctx, V); 1575 IsNullPtr = V.isNullPointer(); 1576 } 1577 1578 void set(APValue::LValueBase B, bool BInvalid = false) { 1579 #ifndef NDEBUG 1580 // We only allow a few types of invalid bases. Enforce that here. 1581 if (BInvalid) { 1582 const auto *E = B.get<const Expr *>(); 1583 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1584 "Unexpected type of invalid base"); 1585 } 1586 #endif 1587 1588 Base = B; 1589 Offset = CharUnits::fromQuantity(0); 1590 InvalidBase = BInvalid; 1591 Designator = SubobjectDesignator(getType(B)); 1592 IsNullPtr = false; 1593 } 1594 1595 void setNull(ASTContext &Ctx, QualType PointerTy) { 1596 Base = (const ValueDecl *)nullptr; 1597 Offset = 1598 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1599 InvalidBase = false; 1600 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1601 IsNullPtr = true; 1602 } 1603 1604 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1605 set(B, true); 1606 } 1607 1608 std::string toString(ASTContext &Ctx, QualType T) const { 1609 APValue Printable; 1610 moveInto(Printable); 1611 return Printable.getAsString(Ctx, T); 1612 } 1613 1614 private: 1615 // Check that this LValue is not based on a null pointer. If it is, produce 1616 // a diagnostic and mark the designator as invalid. 1617 template <typename GenDiagType> 1618 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1619 if (Designator.Invalid) 1620 return false; 1621 if (IsNullPtr) { 1622 GenDiag(); 1623 Designator.setInvalid(); 1624 return false; 1625 } 1626 return true; 1627 } 1628 1629 public: 1630 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1631 CheckSubobjectKind CSK) { 1632 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1633 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1634 }); 1635 } 1636 1637 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1638 AccessKinds AK) { 1639 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1640 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1641 }); 1642 } 1643 1644 // Check this LValue refers to an object. If not, set the designator to be 1645 // invalid and emit a diagnostic. 1646 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1647 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1648 Designator.checkSubobject(Info, E, CSK); 1649 } 1650 1651 void addDecl(EvalInfo &Info, const Expr *E, 1652 const Decl *D, bool Virtual = false) { 1653 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1654 Designator.addDeclUnchecked(D, Virtual); 1655 } 1656 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1657 if (!Designator.Entries.empty()) { 1658 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1659 Designator.setInvalid(); 1660 return; 1661 } 1662 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1663 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1664 Designator.FirstEntryIsAnUnsizedArray = true; 1665 Designator.addUnsizedArrayUnchecked(ElemTy); 1666 } 1667 } 1668 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1669 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1670 Designator.addArrayUnchecked(CAT); 1671 } 1672 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1673 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1674 Designator.addComplexUnchecked(EltTy, Imag); 1675 } 1676 void clearIsNullPointer() { 1677 IsNullPtr = false; 1678 } 1679 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1680 const APSInt &Index, CharUnits ElementSize) { 1681 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1682 // but we're not required to diagnose it and it's valid in C++.) 1683 if (!Index) 1684 return; 1685 1686 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1687 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1688 // offsets. 1689 uint64_t Offset64 = Offset.getQuantity(); 1690 uint64_t ElemSize64 = ElementSize.getQuantity(); 1691 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1692 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1693 1694 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1695 Designator.adjustIndex(Info, E, Index); 1696 clearIsNullPointer(); 1697 } 1698 void adjustOffset(CharUnits N) { 1699 Offset += N; 1700 if (N.getQuantity()) 1701 clearIsNullPointer(); 1702 } 1703 }; 1704 1705 struct MemberPtr { 1706 MemberPtr() {} 1707 explicit MemberPtr(const ValueDecl *Decl) : 1708 DeclAndIsDerivedMember(Decl, false), Path() {} 1709 1710 /// The member or (direct or indirect) field referred to by this member 1711 /// pointer, or 0 if this is a null member pointer. 1712 const ValueDecl *getDecl() const { 1713 return DeclAndIsDerivedMember.getPointer(); 1714 } 1715 /// Is this actually a member of some type derived from the relevant class? 1716 bool isDerivedMember() const { 1717 return DeclAndIsDerivedMember.getInt(); 1718 } 1719 /// Get the class which the declaration actually lives in. 1720 const CXXRecordDecl *getContainingRecord() const { 1721 return cast<CXXRecordDecl>( 1722 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1723 } 1724 1725 void moveInto(APValue &V) const { 1726 V = APValue(getDecl(), isDerivedMember(), Path); 1727 } 1728 void setFrom(const APValue &V) { 1729 assert(V.isMemberPointer()); 1730 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1731 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1732 Path.clear(); 1733 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1734 Path.insert(Path.end(), P.begin(), P.end()); 1735 } 1736 1737 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1738 /// whether the member is a member of some class derived from the class type 1739 /// of the member pointer. 1740 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1741 /// Path - The path of base/derived classes from the member declaration's 1742 /// class (exclusive) to the class type of the member pointer (inclusive). 1743 SmallVector<const CXXRecordDecl*, 4> Path; 1744 1745 /// Perform a cast towards the class of the Decl (either up or down the 1746 /// hierarchy). 1747 bool castBack(const CXXRecordDecl *Class) { 1748 assert(!Path.empty()); 1749 const CXXRecordDecl *Expected; 1750 if (Path.size() >= 2) 1751 Expected = Path[Path.size() - 2]; 1752 else 1753 Expected = getContainingRecord(); 1754 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1755 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1756 // if B does not contain the original member and is not a base or 1757 // derived class of the class containing the original member, the result 1758 // of the cast is undefined. 1759 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1760 // (D::*). We consider that to be a language defect. 1761 return false; 1762 } 1763 Path.pop_back(); 1764 return true; 1765 } 1766 /// Perform a base-to-derived member pointer cast. 1767 bool castToDerived(const CXXRecordDecl *Derived) { 1768 if (!getDecl()) 1769 return true; 1770 if (!isDerivedMember()) { 1771 Path.push_back(Derived); 1772 return true; 1773 } 1774 if (!castBack(Derived)) 1775 return false; 1776 if (Path.empty()) 1777 DeclAndIsDerivedMember.setInt(false); 1778 return true; 1779 } 1780 /// Perform a derived-to-base member pointer cast. 1781 bool castToBase(const CXXRecordDecl *Base) { 1782 if (!getDecl()) 1783 return true; 1784 if (Path.empty()) 1785 DeclAndIsDerivedMember.setInt(true); 1786 if (isDerivedMember()) { 1787 Path.push_back(Base); 1788 return true; 1789 } 1790 return castBack(Base); 1791 } 1792 }; 1793 1794 /// Compare two member pointers, which are assumed to be of the same type. 1795 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1796 if (!LHS.getDecl() || !RHS.getDecl()) 1797 return !LHS.getDecl() && !RHS.getDecl(); 1798 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1799 return false; 1800 return LHS.Path == RHS.Path; 1801 } 1802 } 1803 1804 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1805 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1806 const LValue &This, const Expr *E, 1807 bool AllowNonLiteralTypes = false); 1808 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1809 bool InvalidBaseOK = false); 1810 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1811 bool InvalidBaseOK = false); 1812 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1813 EvalInfo &Info); 1814 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1815 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1816 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1817 EvalInfo &Info); 1818 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1819 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1820 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1821 EvalInfo &Info); 1822 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1823 1824 /// Evaluate an integer or fixed point expression into an APResult. 1825 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1826 EvalInfo &Info); 1827 1828 /// Evaluate only a fixed point expression into an APResult. 1829 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1830 EvalInfo &Info); 1831 1832 //===----------------------------------------------------------------------===// 1833 // Misc utilities 1834 //===----------------------------------------------------------------------===// 1835 1836 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1837 /// preserving its value (by extending by up to one bit as needed). 1838 static void negateAsSigned(APSInt &Int) { 1839 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1840 Int = Int.extend(Int.getBitWidth() + 1); 1841 Int.setIsSigned(true); 1842 } 1843 Int = -Int; 1844 } 1845 1846 template<typename KeyT> 1847 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1848 ScopeKind Scope, LValue &LV) { 1849 unsigned Version = getTempVersion(); 1850 APValue::LValueBase Base(Key, Index, Version); 1851 LV.set(Base); 1852 return createLocal(Base, Key, T, Scope); 1853 } 1854 1855 /// Allocate storage for a parameter of a function call made in this frame. 1856 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1857 LValue &LV) { 1858 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1859 APValue::LValueBase Base(PVD, Index, Args.Version); 1860 LV.set(Base); 1861 // We always destroy parameters at the end of the call, even if we'd allow 1862 // them to live to the end of the full-expression at runtime, in order to 1863 // give portable results and match other compilers. 1864 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1865 } 1866 1867 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1868 QualType T, ScopeKind Scope) { 1869 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1870 unsigned Version = Base.getVersion(); 1871 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1872 assert(Result.isAbsent() && "local created multiple times"); 1873 1874 // If we're creating a local immediately in the operand of a speculative 1875 // evaluation, don't register a cleanup to be run outside the speculative 1876 // evaluation context, since we won't actually be able to initialize this 1877 // object. 1878 if (Index <= Info.SpeculativeEvaluationDepth) { 1879 if (T.isDestructedType()) 1880 Info.noteSideEffect(); 1881 } else { 1882 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1883 } 1884 return Result; 1885 } 1886 1887 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1888 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1889 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1890 return nullptr; 1891 } 1892 1893 DynamicAllocLValue DA(NumHeapAllocs++); 1894 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1895 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1896 std::forward_as_tuple(DA), std::tuple<>()); 1897 assert(Result.second && "reused a heap alloc index?"); 1898 Result.first->second.AllocExpr = E; 1899 return &Result.first->second.Value; 1900 } 1901 1902 /// Produce a string describing the given constexpr call. 1903 void CallStackFrame::describe(raw_ostream &Out) { 1904 unsigned ArgIndex = 0; 1905 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1906 !isa<CXXConstructorDecl>(Callee) && 1907 cast<CXXMethodDecl>(Callee)->isInstance(); 1908 1909 if (!IsMemberCall) 1910 Out << *Callee << '('; 1911 1912 if (This && IsMemberCall) { 1913 APValue Val; 1914 This->moveInto(Val); 1915 Val.printPretty(Out, Info.Ctx, 1916 This->Designator.MostDerivedType); 1917 // FIXME: Add parens around Val if needed. 1918 Out << "->" << *Callee << '('; 1919 IsMemberCall = false; 1920 } 1921 1922 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1923 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1924 if (ArgIndex > (unsigned)IsMemberCall) 1925 Out << ", "; 1926 1927 const ParmVarDecl *Param = *I; 1928 APValue *V = Info.getParamSlot(Arguments, Param); 1929 if (V) 1930 V->printPretty(Out, Info.Ctx, Param->getType()); 1931 else 1932 Out << "<...>"; 1933 1934 if (ArgIndex == 0 && IsMemberCall) 1935 Out << "->" << *Callee << '('; 1936 } 1937 1938 Out << ')'; 1939 } 1940 1941 /// Evaluate an expression to see if it had side-effects, and discard its 1942 /// result. 1943 /// \return \c true if the caller should keep evaluating. 1944 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1945 assert(!E->isValueDependent()); 1946 APValue Scratch; 1947 if (!Evaluate(Scratch, Info, E)) 1948 // We don't need the value, but we might have skipped a side effect here. 1949 return Info.noteSideEffect(); 1950 return true; 1951 } 1952 1953 /// Should this call expression be treated as a string literal? 1954 static bool IsStringLiteralCall(const CallExpr *E) { 1955 unsigned Builtin = E->getBuiltinCallee(); 1956 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1957 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1958 } 1959 1960 static bool IsGlobalLValue(APValue::LValueBase B) { 1961 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1962 // constant expression of pointer type that evaluates to... 1963 1964 // ... a null pointer value, or a prvalue core constant expression of type 1965 // std::nullptr_t. 1966 if (!B) return true; 1967 1968 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1969 // ... the address of an object with static storage duration, 1970 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1971 return VD->hasGlobalStorage(); 1972 if (isa<TemplateParamObjectDecl>(D)) 1973 return true; 1974 // ... the address of a function, 1975 // ... the address of a GUID [MS extension], 1976 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1977 } 1978 1979 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1980 return true; 1981 1982 const Expr *E = B.get<const Expr*>(); 1983 switch (E->getStmtClass()) { 1984 default: 1985 return false; 1986 case Expr::CompoundLiteralExprClass: { 1987 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1988 return CLE->isFileScope() && CLE->isLValue(); 1989 } 1990 case Expr::MaterializeTemporaryExprClass: 1991 // A materialized temporary might have been lifetime-extended to static 1992 // storage duration. 1993 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1994 // A string literal has static storage duration. 1995 case Expr::StringLiteralClass: 1996 case Expr::PredefinedExprClass: 1997 case Expr::ObjCStringLiteralClass: 1998 case Expr::ObjCEncodeExprClass: 1999 return true; 2000 case Expr::ObjCBoxedExprClass: 2001 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2002 case Expr::CallExprClass: 2003 return IsStringLiteralCall(cast<CallExpr>(E)); 2004 // For GCC compatibility, &&label has static storage duration. 2005 case Expr::AddrLabelExprClass: 2006 return true; 2007 // A Block literal expression may be used as the initialization value for 2008 // Block variables at global or local static scope. 2009 case Expr::BlockExprClass: 2010 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2011 case Expr::ImplicitValueInitExprClass: 2012 // FIXME: 2013 // We can never form an lvalue with an implicit value initialization as its 2014 // base through expression evaluation, so these only appear in one case: the 2015 // implicit variable declaration we invent when checking whether a constexpr 2016 // constructor can produce a constant expression. We must assume that such 2017 // an expression might be a global lvalue. 2018 return true; 2019 } 2020 } 2021 2022 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2023 return LVal.Base.dyn_cast<const ValueDecl*>(); 2024 } 2025 2026 static bool IsLiteralLValue(const LValue &Value) { 2027 if (Value.getLValueCallIndex()) 2028 return false; 2029 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2030 return E && !isa<MaterializeTemporaryExpr>(E); 2031 } 2032 2033 static bool IsWeakLValue(const LValue &Value) { 2034 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2035 return Decl && Decl->isWeak(); 2036 } 2037 2038 static bool isZeroSized(const LValue &Value) { 2039 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2040 if (Decl && isa<VarDecl>(Decl)) { 2041 QualType Ty = Decl->getType(); 2042 if (Ty->isArrayType()) 2043 return Ty->isIncompleteType() || 2044 Decl->getASTContext().getTypeSize(Ty) == 0; 2045 } 2046 return false; 2047 } 2048 2049 static bool HasSameBase(const LValue &A, const LValue &B) { 2050 if (!A.getLValueBase()) 2051 return !B.getLValueBase(); 2052 if (!B.getLValueBase()) 2053 return false; 2054 2055 if (A.getLValueBase().getOpaqueValue() != 2056 B.getLValueBase().getOpaqueValue()) 2057 return false; 2058 2059 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2060 A.getLValueVersion() == B.getLValueVersion(); 2061 } 2062 2063 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2064 assert(Base && "no location for a null lvalue"); 2065 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2066 2067 // For a parameter, find the corresponding call stack frame (if it still 2068 // exists), and point at the parameter of the function definition we actually 2069 // invoked. 2070 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2071 unsigned Idx = PVD->getFunctionScopeIndex(); 2072 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2073 if (F->Arguments.CallIndex == Base.getCallIndex() && 2074 F->Arguments.Version == Base.getVersion() && F->Callee && 2075 Idx < F->Callee->getNumParams()) { 2076 VD = F->Callee->getParamDecl(Idx); 2077 break; 2078 } 2079 } 2080 } 2081 2082 if (VD) 2083 Info.Note(VD->getLocation(), diag::note_declared_at); 2084 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2085 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2086 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2087 // FIXME: Produce a note for dangling pointers too. 2088 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2089 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2090 diag::note_constexpr_dynamic_alloc_here); 2091 } 2092 // We have no information to show for a typeid(T) object. 2093 } 2094 2095 enum class CheckEvaluationResultKind { 2096 ConstantExpression, 2097 FullyInitialized, 2098 }; 2099 2100 /// Materialized temporaries that we've already checked to determine if they're 2101 /// initializsed by a constant expression. 2102 using CheckedTemporaries = 2103 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2104 2105 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2106 EvalInfo &Info, SourceLocation DiagLoc, 2107 QualType Type, const APValue &Value, 2108 ConstantExprKind Kind, 2109 SourceLocation SubobjectLoc, 2110 CheckedTemporaries &CheckedTemps); 2111 2112 /// Check that this reference or pointer core constant expression is a valid 2113 /// value for an address or reference constant expression. Return true if we 2114 /// can fold this expression, whether or not it's a constant expression. 2115 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2116 QualType Type, const LValue &LVal, 2117 ConstantExprKind Kind, 2118 CheckedTemporaries &CheckedTemps) { 2119 bool IsReferenceType = Type->isReferenceType(); 2120 2121 APValue::LValueBase Base = LVal.getLValueBase(); 2122 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2123 2124 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2125 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2126 2127 // Additional restrictions apply in a template argument. We only enforce the 2128 // C++20 restrictions here; additional syntactic and semantic restrictions 2129 // are applied elsewhere. 2130 if (isTemplateArgument(Kind)) { 2131 int InvalidBaseKind = -1; 2132 StringRef Ident; 2133 if (Base.is<TypeInfoLValue>()) 2134 InvalidBaseKind = 0; 2135 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2136 InvalidBaseKind = 1; 2137 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2138 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2139 InvalidBaseKind = 2; 2140 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2141 InvalidBaseKind = 3; 2142 Ident = PE->getIdentKindName(); 2143 } 2144 2145 if (InvalidBaseKind != -1) { 2146 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2147 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2148 << Ident; 2149 return false; 2150 } 2151 } 2152 2153 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2154 if (FD->isConsteval()) { 2155 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2156 << !Type->isAnyPointerType(); 2157 Info.Note(FD->getLocation(), diag::note_declared_at); 2158 return false; 2159 } 2160 } 2161 2162 // Check that the object is a global. Note that the fake 'this' object we 2163 // manufacture when checking potential constant expressions is conservatively 2164 // assumed to be global here. 2165 if (!IsGlobalLValue(Base)) { 2166 if (Info.getLangOpts().CPlusPlus11) { 2167 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2168 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2169 << IsReferenceType << !Designator.Entries.empty() 2170 << !!VD << VD; 2171 2172 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2173 if (VarD && VarD->isConstexpr()) { 2174 // Non-static local constexpr variables have unintuitive semantics: 2175 // constexpr int a = 1; 2176 // constexpr const int *p = &a; 2177 // ... is invalid because the address of 'a' is not constant. Suggest 2178 // adding a 'static' in this case. 2179 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2180 << VarD 2181 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2182 } else { 2183 NoteLValueLocation(Info, Base); 2184 } 2185 } else { 2186 Info.FFDiag(Loc); 2187 } 2188 // Don't allow references to temporaries to escape. 2189 return false; 2190 } 2191 assert((Info.checkingPotentialConstantExpression() || 2192 LVal.getLValueCallIndex() == 0) && 2193 "have call index for global lvalue"); 2194 2195 if (Base.is<DynamicAllocLValue>()) { 2196 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2197 << IsReferenceType << !Designator.Entries.empty(); 2198 NoteLValueLocation(Info, Base); 2199 return false; 2200 } 2201 2202 if (BaseVD) { 2203 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2204 // Check if this is a thread-local variable. 2205 if (Var->getTLSKind()) 2206 // FIXME: Diagnostic! 2207 return false; 2208 2209 // A dllimport variable never acts like a constant, unless we're 2210 // evaluating a value for use only in name mangling. 2211 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2212 // FIXME: Diagnostic! 2213 return false; 2214 } 2215 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2216 // __declspec(dllimport) must be handled very carefully: 2217 // We must never initialize an expression with the thunk in C++. 2218 // Doing otherwise would allow the same id-expression to yield 2219 // different addresses for the same function in different translation 2220 // units. However, this means that we must dynamically initialize the 2221 // expression with the contents of the import address table at runtime. 2222 // 2223 // The C language has no notion of ODR; furthermore, it has no notion of 2224 // dynamic initialization. This means that we are permitted to 2225 // perform initialization with the address of the thunk. 2226 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2227 FD->hasAttr<DLLImportAttr>()) 2228 // FIXME: Diagnostic! 2229 return false; 2230 } 2231 } else if (const auto *MTE = 2232 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2233 if (CheckedTemps.insert(MTE).second) { 2234 QualType TempType = getType(Base); 2235 if (TempType.isDestructedType()) { 2236 Info.FFDiag(MTE->getExprLoc(), 2237 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2238 << TempType; 2239 return false; 2240 } 2241 2242 APValue *V = MTE->getOrCreateValue(false); 2243 assert(V && "evasluation result refers to uninitialised temporary"); 2244 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2245 Info, MTE->getExprLoc(), TempType, *V, 2246 Kind, SourceLocation(), CheckedTemps)) 2247 return false; 2248 } 2249 } 2250 2251 // Allow address constant expressions to be past-the-end pointers. This is 2252 // an extension: the standard requires them to point to an object. 2253 if (!IsReferenceType) 2254 return true; 2255 2256 // A reference constant expression must refer to an object. 2257 if (!Base) { 2258 // FIXME: diagnostic 2259 Info.CCEDiag(Loc); 2260 return true; 2261 } 2262 2263 // Does this refer one past the end of some object? 2264 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2265 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2266 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2267 NoteLValueLocation(Info, Base); 2268 } 2269 2270 return true; 2271 } 2272 2273 /// Member pointers are constant expressions unless they point to a 2274 /// non-virtual dllimport member function. 2275 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2276 SourceLocation Loc, 2277 QualType Type, 2278 const APValue &Value, 2279 ConstantExprKind Kind) { 2280 const ValueDecl *Member = Value.getMemberPointerDecl(); 2281 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2282 if (!FD) 2283 return true; 2284 if (FD->isConsteval()) { 2285 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2286 Info.Note(FD->getLocation(), diag::note_declared_at); 2287 return false; 2288 } 2289 return isForManglingOnly(Kind) || FD->isVirtual() || 2290 !FD->hasAttr<DLLImportAttr>(); 2291 } 2292 2293 /// Check that this core constant expression is of literal type, and if not, 2294 /// produce an appropriate diagnostic. 2295 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2296 const LValue *This = nullptr) { 2297 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2298 return true; 2299 2300 // C++1y: A constant initializer for an object o [...] may also invoke 2301 // constexpr constructors for o and its subobjects even if those objects 2302 // are of non-literal class types. 2303 // 2304 // C++11 missed this detail for aggregates, so classes like this: 2305 // struct foo_t { union { int i; volatile int j; } u; }; 2306 // are not (obviously) initializable like so: 2307 // __attribute__((__require_constant_initialization__)) 2308 // static const foo_t x = {{0}}; 2309 // because "i" is a subobject with non-literal initialization (due to the 2310 // volatile member of the union). See: 2311 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2312 // Therefore, we use the C++1y behavior. 2313 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2314 return true; 2315 2316 // Prvalue constant expressions must be of literal types. 2317 if (Info.getLangOpts().CPlusPlus11) 2318 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2319 << E->getType(); 2320 else 2321 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2322 return false; 2323 } 2324 2325 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2326 EvalInfo &Info, SourceLocation DiagLoc, 2327 QualType Type, const APValue &Value, 2328 ConstantExprKind Kind, 2329 SourceLocation SubobjectLoc, 2330 CheckedTemporaries &CheckedTemps) { 2331 if (!Value.hasValue()) { 2332 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2333 << true << Type; 2334 if (SubobjectLoc.isValid()) 2335 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2336 return false; 2337 } 2338 2339 // We allow _Atomic(T) to be initialized from anything that T can be 2340 // initialized from. 2341 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2342 Type = AT->getValueType(); 2343 2344 // Core issue 1454: For a literal constant expression of array or class type, 2345 // each subobject of its value shall have been initialized by a constant 2346 // expression. 2347 if (Value.isArray()) { 2348 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2349 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2350 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2351 Value.getArrayInitializedElt(I), Kind, 2352 SubobjectLoc, CheckedTemps)) 2353 return false; 2354 } 2355 if (!Value.hasArrayFiller()) 2356 return true; 2357 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2358 Value.getArrayFiller(), Kind, SubobjectLoc, 2359 CheckedTemps); 2360 } 2361 if (Value.isUnion() && Value.getUnionField()) { 2362 return CheckEvaluationResult( 2363 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2364 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2365 CheckedTemps); 2366 } 2367 if (Value.isStruct()) { 2368 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2369 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2370 unsigned BaseIndex = 0; 2371 for (const CXXBaseSpecifier &BS : CD->bases()) { 2372 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2373 Value.getStructBase(BaseIndex), Kind, 2374 BS.getBeginLoc(), CheckedTemps)) 2375 return false; 2376 ++BaseIndex; 2377 } 2378 } 2379 for (const auto *I : RD->fields()) { 2380 if (I->isUnnamedBitfield()) 2381 continue; 2382 2383 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2384 Value.getStructField(I->getFieldIndex()), 2385 Kind, I->getLocation(), CheckedTemps)) 2386 return false; 2387 } 2388 } 2389 2390 if (Value.isLValue() && 2391 CERK == CheckEvaluationResultKind::ConstantExpression) { 2392 LValue LVal; 2393 LVal.setFrom(Info.Ctx, Value); 2394 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2395 CheckedTemps); 2396 } 2397 2398 if (Value.isMemberPointer() && 2399 CERK == CheckEvaluationResultKind::ConstantExpression) 2400 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2401 2402 // Everything else is fine. 2403 return true; 2404 } 2405 2406 /// Check that this core constant expression value is a valid value for a 2407 /// constant expression. If not, report an appropriate diagnostic. Does not 2408 /// check that the expression is of literal type. 2409 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2410 QualType Type, const APValue &Value, 2411 ConstantExprKind Kind) { 2412 // Nothing to check for a constant expression of type 'cv void'. 2413 if (Type->isVoidType()) 2414 return true; 2415 2416 CheckedTemporaries CheckedTemps; 2417 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2418 Info, DiagLoc, Type, Value, Kind, 2419 SourceLocation(), CheckedTemps); 2420 } 2421 2422 /// Check that this evaluated value is fully-initialized and can be loaded by 2423 /// an lvalue-to-rvalue conversion. 2424 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2425 QualType Type, const APValue &Value) { 2426 CheckedTemporaries CheckedTemps; 2427 return CheckEvaluationResult( 2428 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2429 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2430 } 2431 2432 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2433 /// "the allocated storage is deallocated within the evaluation". 2434 static bool CheckMemoryLeaks(EvalInfo &Info) { 2435 if (!Info.HeapAllocs.empty()) { 2436 // We can still fold to a constant despite a compile-time memory leak, 2437 // so long as the heap allocation isn't referenced in the result (we check 2438 // that in CheckConstantExpression). 2439 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2440 diag::note_constexpr_memory_leak) 2441 << unsigned(Info.HeapAllocs.size() - 1); 2442 } 2443 return true; 2444 } 2445 2446 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2447 // A null base expression indicates a null pointer. These are always 2448 // evaluatable, and they are false unless the offset is zero. 2449 if (!Value.getLValueBase()) { 2450 Result = !Value.getLValueOffset().isZero(); 2451 return true; 2452 } 2453 2454 // We have a non-null base. These are generally known to be true, but if it's 2455 // a weak declaration it can be null at runtime. 2456 Result = true; 2457 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2458 return !Decl || !Decl->isWeak(); 2459 } 2460 2461 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2462 switch (Val.getKind()) { 2463 case APValue::None: 2464 case APValue::Indeterminate: 2465 return false; 2466 case APValue::Int: 2467 Result = Val.getInt().getBoolValue(); 2468 return true; 2469 case APValue::FixedPoint: 2470 Result = Val.getFixedPoint().getBoolValue(); 2471 return true; 2472 case APValue::Float: 2473 Result = !Val.getFloat().isZero(); 2474 return true; 2475 case APValue::ComplexInt: 2476 Result = Val.getComplexIntReal().getBoolValue() || 2477 Val.getComplexIntImag().getBoolValue(); 2478 return true; 2479 case APValue::ComplexFloat: 2480 Result = !Val.getComplexFloatReal().isZero() || 2481 !Val.getComplexFloatImag().isZero(); 2482 return true; 2483 case APValue::LValue: 2484 return EvalPointerValueAsBool(Val, Result); 2485 case APValue::MemberPointer: 2486 Result = Val.getMemberPointerDecl(); 2487 return true; 2488 case APValue::Vector: 2489 case APValue::Array: 2490 case APValue::Struct: 2491 case APValue::Union: 2492 case APValue::AddrLabelDiff: 2493 return false; 2494 } 2495 2496 llvm_unreachable("unknown APValue kind"); 2497 } 2498 2499 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2500 EvalInfo &Info) { 2501 assert(!E->isValueDependent()); 2502 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2503 APValue Val; 2504 if (!Evaluate(Val, Info, E)) 2505 return false; 2506 return HandleConversionToBool(Val, Result); 2507 } 2508 2509 template<typename T> 2510 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2511 const T &SrcValue, QualType DestType) { 2512 Info.CCEDiag(E, diag::note_constexpr_overflow) 2513 << SrcValue << DestType; 2514 return Info.noteUndefinedBehavior(); 2515 } 2516 2517 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2518 QualType SrcType, const APFloat &Value, 2519 QualType DestType, APSInt &Result) { 2520 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2521 // Determine whether we are converting to unsigned or signed. 2522 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2523 2524 Result = APSInt(DestWidth, !DestSigned); 2525 bool ignored; 2526 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2527 & APFloat::opInvalidOp) 2528 return HandleOverflow(Info, E, Value, DestType); 2529 return true; 2530 } 2531 2532 /// Get rounding mode used for evaluation of the specified expression. 2533 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2534 /// dynamic. 2535 /// If rounding mode is unknown at compile time, still try to evaluate the 2536 /// expression. If the result is exact, it does not depend on rounding mode. 2537 /// So return "tonearest" mode instead of "dynamic". 2538 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2539 bool &DynamicRM) { 2540 llvm::RoundingMode RM = 2541 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2542 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2543 if (DynamicRM) 2544 RM = llvm::RoundingMode::NearestTiesToEven; 2545 return RM; 2546 } 2547 2548 /// Check if the given evaluation result is allowed for constant evaluation. 2549 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2550 APFloat::opStatus St) { 2551 // In a constant context, assume that any dynamic rounding mode or FP 2552 // exception state matches the default floating-point environment. 2553 if (Info.InConstantContext) 2554 return true; 2555 2556 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2557 if ((St & APFloat::opInexact) && 2558 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2559 // Inexact result means that it depends on rounding mode. If the requested 2560 // mode is dynamic, the evaluation cannot be made in compile time. 2561 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2562 return false; 2563 } 2564 2565 if ((St != APFloat::opOK) && 2566 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2567 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2568 FPO.getAllowFEnvAccess())) { 2569 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2570 return false; 2571 } 2572 2573 if ((St & APFloat::opStatus::opInvalidOp) && 2574 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2575 // There is no usefully definable result. 2576 Info.FFDiag(E); 2577 return false; 2578 } 2579 2580 // FIXME: if: 2581 // - evaluation triggered other FP exception, and 2582 // - exception mode is not "ignore", and 2583 // - the expression being evaluated is not a part of global variable 2584 // initializer, 2585 // the evaluation probably need to be rejected. 2586 return true; 2587 } 2588 2589 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2590 QualType SrcType, QualType DestType, 2591 APFloat &Result) { 2592 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2593 bool DynamicRM; 2594 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2595 APFloat::opStatus St; 2596 APFloat Value = Result; 2597 bool ignored; 2598 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2599 return checkFloatingPointResult(Info, E, St); 2600 } 2601 2602 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2603 QualType DestType, QualType SrcType, 2604 const APSInt &Value) { 2605 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2606 // Figure out if this is a truncate, extend or noop cast. 2607 // If the input is signed, do a sign extend, noop, or truncate. 2608 APSInt Result = Value.extOrTrunc(DestWidth); 2609 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2610 if (DestType->isBooleanType()) 2611 Result = Value.getBoolValue(); 2612 return Result; 2613 } 2614 2615 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2616 const FPOptions FPO, 2617 QualType SrcType, const APSInt &Value, 2618 QualType DestType, APFloat &Result) { 2619 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2620 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2621 APFloat::rmNearestTiesToEven); 2622 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2623 FPO.isFPConstrained()) { 2624 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2625 return false; 2626 } 2627 return true; 2628 } 2629 2630 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2631 APValue &Value, const FieldDecl *FD) { 2632 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2633 2634 if (!Value.isInt()) { 2635 // Trying to store a pointer-cast-to-integer into a bitfield. 2636 // FIXME: In this case, we should provide the diagnostic for casting 2637 // a pointer to an integer. 2638 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2639 Info.FFDiag(E); 2640 return false; 2641 } 2642 2643 APSInt &Int = Value.getInt(); 2644 unsigned OldBitWidth = Int.getBitWidth(); 2645 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2646 if (NewBitWidth < OldBitWidth) 2647 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2648 return true; 2649 } 2650 2651 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2652 llvm::APInt &Res) { 2653 APValue SVal; 2654 if (!Evaluate(SVal, Info, E)) 2655 return false; 2656 if (SVal.isInt()) { 2657 Res = SVal.getInt(); 2658 return true; 2659 } 2660 if (SVal.isFloat()) { 2661 Res = SVal.getFloat().bitcastToAPInt(); 2662 return true; 2663 } 2664 if (SVal.isVector()) { 2665 QualType VecTy = E->getType(); 2666 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2667 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2668 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2669 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2670 Res = llvm::APInt::getNullValue(VecSize); 2671 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2672 APValue &Elt = SVal.getVectorElt(i); 2673 llvm::APInt EltAsInt; 2674 if (Elt.isInt()) { 2675 EltAsInt = Elt.getInt(); 2676 } else if (Elt.isFloat()) { 2677 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2678 } else { 2679 // Don't try to handle vectors of anything other than int or float 2680 // (not sure if it's possible to hit this case). 2681 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2682 return false; 2683 } 2684 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2685 if (BigEndian) 2686 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2687 else 2688 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2689 } 2690 return true; 2691 } 2692 // Give up if the input isn't an int, float, or vector. For example, we 2693 // reject "(v4i16)(intptr_t)&a". 2694 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2695 return false; 2696 } 2697 2698 /// Perform the given integer operation, which is known to need at most BitWidth 2699 /// bits, and check for overflow in the original type (if that type was not an 2700 /// unsigned type). 2701 template<typename Operation> 2702 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2703 const APSInt &LHS, const APSInt &RHS, 2704 unsigned BitWidth, Operation Op, 2705 APSInt &Result) { 2706 if (LHS.isUnsigned()) { 2707 Result = Op(LHS, RHS); 2708 return true; 2709 } 2710 2711 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2712 Result = Value.trunc(LHS.getBitWidth()); 2713 if (Result.extend(BitWidth) != Value) { 2714 if (Info.checkingForUndefinedBehavior()) 2715 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2716 diag::warn_integer_constant_overflow) 2717 << Result.toString(10) << E->getType(); 2718 else 2719 return HandleOverflow(Info, E, Value, E->getType()); 2720 } 2721 return true; 2722 } 2723 2724 /// Perform the given binary integer operation. 2725 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2726 BinaryOperatorKind Opcode, APSInt RHS, 2727 APSInt &Result) { 2728 switch (Opcode) { 2729 default: 2730 Info.FFDiag(E); 2731 return false; 2732 case BO_Mul: 2733 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2734 std::multiplies<APSInt>(), Result); 2735 case BO_Add: 2736 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2737 std::plus<APSInt>(), Result); 2738 case BO_Sub: 2739 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2740 std::minus<APSInt>(), Result); 2741 case BO_And: Result = LHS & RHS; return true; 2742 case BO_Xor: Result = LHS ^ RHS; return true; 2743 case BO_Or: Result = LHS | RHS; return true; 2744 case BO_Div: 2745 case BO_Rem: 2746 if (RHS == 0) { 2747 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2748 return false; 2749 } 2750 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2751 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2752 // this operation and gives the two's complement result. 2753 if (RHS.isNegative() && RHS.isAllOnesValue() && 2754 LHS.isSigned() && LHS.isMinSignedValue()) 2755 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2756 E->getType()); 2757 return true; 2758 case BO_Shl: { 2759 if (Info.getLangOpts().OpenCL) 2760 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2761 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2762 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2763 RHS.isUnsigned()); 2764 else if (RHS.isSigned() && RHS.isNegative()) { 2765 // During constant-folding, a negative shift is an opposite shift. Such 2766 // a shift is not a constant expression. 2767 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2768 RHS = -RHS; 2769 goto shift_right; 2770 } 2771 shift_left: 2772 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2773 // the shifted type. 2774 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2775 if (SA != RHS) { 2776 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2777 << RHS << E->getType() << LHS.getBitWidth(); 2778 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2779 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2780 // operand, and must not overflow the corresponding unsigned type. 2781 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2782 // E1 x 2^E2 module 2^N. 2783 if (LHS.isNegative()) 2784 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2785 else if (LHS.countLeadingZeros() < SA) 2786 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2787 } 2788 Result = LHS << SA; 2789 return true; 2790 } 2791 case BO_Shr: { 2792 if (Info.getLangOpts().OpenCL) 2793 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2794 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2795 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2796 RHS.isUnsigned()); 2797 else if (RHS.isSigned() && RHS.isNegative()) { 2798 // During constant-folding, a negative shift is an opposite shift. Such a 2799 // shift is not a constant expression. 2800 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2801 RHS = -RHS; 2802 goto shift_left; 2803 } 2804 shift_right: 2805 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2806 // shifted type. 2807 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2808 if (SA != RHS) 2809 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2810 << RHS << E->getType() << LHS.getBitWidth(); 2811 Result = LHS >> SA; 2812 return true; 2813 } 2814 2815 case BO_LT: Result = LHS < RHS; return true; 2816 case BO_GT: Result = LHS > RHS; return true; 2817 case BO_LE: Result = LHS <= RHS; return true; 2818 case BO_GE: Result = LHS >= RHS; return true; 2819 case BO_EQ: Result = LHS == RHS; return true; 2820 case BO_NE: Result = LHS != RHS; return true; 2821 case BO_Cmp: 2822 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2823 } 2824 } 2825 2826 /// Perform the given binary floating-point operation, in-place, on LHS. 2827 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2828 APFloat &LHS, BinaryOperatorKind Opcode, 2829 const APFloat &RHS) { 2830 bool DynamicRM; 2831 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2832 APFloat::opStatus St; 2833 switch (Opcode) { 2834 default: 2835 Info.FFDiag(E); 2836 return false; 2837 case BO_Mul: 2838 St = LHS.multiply(RHS, RM); 2839 break; 2840 case BO_Add: 2841 St = LHS.add(RHS, RM); 2842 break; 2843 case BO_Sub: 2844 St = LHS.subtract(RHS, RM); 2845 break; 2846 case BO_Div: 2847 // [expr.mul]p4: 2848 // If the second operand of / or % is zero the behavior is undefined. 2849 if (RHS.isZero()) 2850 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2851 St = LHS.divide(RHS, RM); 2852 break; 2853 } 2854 2855 // [expr.pre]p4: 2856 // If during the evaluation of an expression, the result is not 2857 // mathematically defined [...], the behavior is undefined. 2858 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2859 if (LHS.isNaN()) { 2860 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2861 return Info.noteUndefinedBehavior(); 2862 } 2863 2864 return checkFloatingPointResult(Info, E, St); 2865 } 2866 2867 static bool handleLogicalOpForVector(const APInt &LHSValue, 2868 BinaryOperatorKind Opcode, 2869 const APInt &RHSValue, APInt &Result) { 2870 bool LHS = (LHSValue != 0); 2871 bool RHS = (RHSValue != 0); 2872 2873 if (Opcode == BO_LAnd) 2874 Result = LHS && RHS; 2875 else 2876 Result = LHS || RHS; 2877 return true; 2878 } 2879 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2880 BinaryOperatorKind Opcode, 2881 const APFloat &RHSValue, APInt &Result) { 2882 bool LHS = !LHSValue.isZero(); 2883 bool RHS = !RHSValue.isZero(); 2884 2885 if (Opcode == BO_LAnd) 2886 Result = LHS && RHS; 2887 else 2888 Result = LHS || RHS; 2889 return true; 2890 } 2891 2892 static bool handleLogicalOpForVector(const APValue &LHSValue, 2893 BinaryOperatorKind Opcode, 2894 const APValue &RHSValue, APInt &Result) { 2895 // The result is always an int type, however operands match the first. 2896 if (LHSValue.getKind() == APValue::Int) 2897 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2898 RHSValue.getInt(), Result); 2899 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2900 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2901 RHSValue.getFloat(), Result); 2902 } 2903 2904 template <typename APTy> 2905 static bool 2906 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2907 const APTy &RHSValue, APInt &Result) { 2908 switch (Opcode) { 2909 default: 2910 llvm_unreachable("unsupported binary operator"); 2911 case BO_EQ: 2912 Result = (LHSValue == RHSValue); 2913 break; 2914 case BO_NE: 2915 Result = (LHSValue != RHSValue); 2916 break; 2917 case BO_LT: 2918 Result = (LHSValue < RHSValue); 2919 break; 2920 case BO_GT: 2921 Result = (LHSValue > RHSValue); 2922 break; 2923 case BO_LE: 2924 Result = (LHSValue <= RHSValue); 2925 break; 2926 case BO_GE: 2927 Result = (LHSValue >= RHSValue); 2928 break; 2929 } 2930 2931 return true; 2932 } 2933 2934 static bool handleCompareOpForVector(const APValue &LHSValue, 2935 BinaryOperatorKind Opcode, 2936 const APValue &RHSValue, APInt &Result) { 2937 // The result is always an int type, however operands match the first. 2938 if (LHSValue.getKind() == APValue::Int) 2939 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2940 RHSValue.getInt(), Result); 2941 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2942 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2943 RHSValue.getFloat(), Result); 2944 } 2945 2946 // Perform binary operations for vector types, in place on the LHS. 2947 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2948 BinaryOperatorKind Opcode, 2949 APValue &LHSValue, 2950 const APValue &RHSValue) { 2951 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2952 "Operation not supported on vector types"); 2953 2954 const auto *VT = E->getType()->castAs<VectorType>(); 2955 unsigned NumElements = VT->getNumElements(); 2956 QualType EltTy = VT->getElementType(); 2957 2958 // In the cases (typically C as I've observed) where we aren't evaluating 2959 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2960 // just give up. 2961 if (!LHSValue.isVector()) { 2962 assert(LHSValue.isLValue() && 2963 "A vector result that isn't a vector OR uncalculated LValue"); 2964 Info.FFDiag(E); 2965 return false; 2966 } 2967 2968 assert(LHSValue.getVectorLength() == NumElements && 2969 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2970 2971 SmallVector<APValue, 4> ResultElements; 2972 2973 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2974 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2975 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2976 2977 if (EltTy->isIntegerType()) { 2978 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2979 EltTy->isUnsignedIntegerType()}; 2980 bool Success = true; 2981 2982 if (BinaryOperator::isLogicalOp(Opcode)) 2983 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2984 else if (BinaryOperator::isComparisonOp(Opcode)) 2985 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2986 else 2987 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2988 RHSElt.getInt(), EltResult); 2989 2990 if (!Success) { 2991 Info.FFDiag(E); 2992 return false; 2993 } 2994 ResultElements.emplace_back(EltResult); 2995 2996 } else if (EltTy->isFloatingType()) { 2997 assert(LHSElt.getKind() == APValue::Float && 2998 RHSElt.getKind() == APValue::Float && 2999 "Mismatched LHS/RHS/Result Type"); 3000 APFloat LHSFloat = LHSElt.getFloat(); 3001 3002 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3003 RHSElt.getFloat())) { 3004 Info.FFDiag(E); 3005 return false; 3006 } 3007 3008 ResultElements.emplace_back(LHSFloat); 3009 } 3010 } 3011 3012 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3013 return true; 3014 } 3015 3016 /// Cast an lvalue referring to a base subobject to a derived class, by 3017 /// truncating the lvalue's path to the given length. 3018 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3019 const RecordDecl *TruncatedType, 3020 unsigned TruncatedElements) { 3021 SubobjectDesignator &D = Result.Designator; 3022 3023 // Check we actually point to a derived class object. 3024 if (TruncatedElements == D.Entries.size()) 3025 return true; 3026 assert(TruncatedElements >= D.MostDerivedPathLength && 3027 "not casting to a derived class"); 3028 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3029 return false; 3030 3031 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3032 const RecordDecl *RD = TruncatedType; 3033 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3034 if (RD->isInvalidDecl()) return false; 3035 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3036 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3037 if (isVirtualBaseClass(D.Entries[I])) 3038 Result.Offset -= Layout.getVBaseClassOffset(Base); 3039 else 3040 Result.Offset -= Layout.getBaseClassOffset(Base); 3041 RD = Base; 3042 } 3043 D.Entries.resize(TruncatedElements); 3044 return true; 3045 } 3046 3047 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3048 const CXXRecordDecl *Derived, 3049 const CXXRecordDecl *Base, 3050 const ASTRecordLayout *RL = nullptr) { 3051 if (!RL) { 3052 if (Derived->isInvalidDecl()) return false; 3053 RL = &Info.Ctx.getASTRecordLayout(Derived); 3054 } 3055 3056 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3057 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3058 return true; 3059 } 3060 3061 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3062 const CXXRecordDecl *DerivedDecl, 3063 const CXXBaseSpecifier *Base) { 3064 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3065 3066 if (!Base->isVirtual()) 3067 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3068 3069 SubobjectDesignator &D = Obj.Designator; 3070 if (D.Invalid) 3071 return false; 3072 3073 // Extract most-derived object and corresponding type. 3074 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3075 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3076 return false; 3077 3078 // Find the virtual base class. 3079 if (DerivedDecl->isInvalidDecl()) return false; 3080 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3081 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3082 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3083 return true; 3084 } 3085 3086 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3087 QualType Type, LValue &Result) { 3088 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3089 PathE = E->path_end(); 3090 PathI != PathE; ++PathI) { 3091 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3092 *PathI)) 3093 return false; 3094 Type = (*PathI)->getType(); 3095 } 3096 return true; 3097 } 3098 3099 /// Cast an lvalue referring to a derived class to a known base subobject. 3100 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3101 const CXXRecordDecl *DerivedRD, 3102 const CXXRecordDecl *BaseRD) { 3103 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3104 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3105 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3106 llvm_unreachable("Class must be derived from the passed in base class!"); 3107 3108 for (CXXBasePathElement &Elem : Paths.front()) 3109 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3110 return false; 3111 return true; 3112 } 3113 3114 /// Update LVal to refer to the given field, which must be a member of the type 3115 /// currently described by LVal. 3116 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3117 const FieldDecl *FD, 3118 const ASTRecordLayout *RL = nullptr) { 3119 if (!RL) { 3120 if (FD->getParent()->isInvalidDecl()) return false; 3121 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3122 } 3123 3124 unsigned I = FD->getFieldIndex(); 3125 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3126 LVal.addDecl(Info, E, FD); 3127 return true; 3128 } 3129 3130 /// Update LVal to refer to the given indirect field. 3131 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3132 LValue &LVal, 3133 const IndirectFieldDecl *IFD) { 3134 for (const auto *C : IFD->chain()) 3135 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3136 return false; 3137 return true; 3138 } 3139 3140 /// Get the size of the given type in char units. 3141 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3142 QualType Type, CharUnits &Size) { 3143 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3144 // extension. 3145 if (Type->isVoidType() || Type->isFunctionType()) { 3146 Size = CharUnits::One(); 3147 return true; 3148 } 3149 3150 if (Type->isDependentType()) { 3151 Info.FFDiag(Loc); 3152 return false; 3153 } 3154 3155 if (!Type->isConstantSizeType()) { 3156 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3157 // FIXME: Better diagnostic. 3158 Info.FFDiag(Loc); 3159 return false; 3160 } 3161 3162 Size = Info.Ctx.getTypeSizeInChars(Type); 3163 return true; 3164 } 3165 3166 /// Update a pointer value to model pointer arithmetic. 3167 /// \param Info - Information about the ongoing evaluation. 3168 /// \param E - The expression being evaluated, for diagnostic purposes. 3169 /// \param LVal - The pointer value to be updated. 3170 /// \param EltTy - The pointee type represented by LVal. 3171 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3172 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3173 LValue &LVal, QualType EltTy, 3174 APSInt Adjustment) { 3175 CharUnits SizeOfPointee; 3176 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3177 return false; 3178 3179 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3180 return true; 3181 } 3182 3183 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3184 LValue &LVal, QualType EltTy, 3185 int64_t Adjustment) { 3186 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3187 APSInt::get(Adjustment)); 3188 } 3189 3190 /// Update an lvalue to refer to a component of a complex number. 3191 /// \param Info - Information about the ongoing evaluation. 3192 /// \param LVal - The lvalue to be updated. 3193 /// \param EltTy - The complex number's component type. 3194 /// \param Imag - False for the real component, true for the imaginary. 3195 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3196 LValue &LVal, QualType EltTy, 3197 bool Imag) { 3198 if (Imag) { 3199 CharUnits SizeOfComponent; 3200 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3201 return false; 3202 LVal.Offset += SizeOfComponent; 3203 } 3204 LVal.addComplex(Info, E, EltTy, Imag); 3205 return true; 3206 } 3207 3208 /// Try to evaluate the initializer for a variable declaration. 3209 /// 3210 /// \param Info Information about the ongoing evaluation. 3211 /// \param E An expression to be used when printing diagnostics. 3212 /// \param VD The variable whose initializer should be obtained. 3213 /// \param Version The version of the variable within the frame. 3214 /// \param Frame The frame in which the variable was created. Must be null 3215 /// if this variable is not local to the evaluation. 3216 /// \param Result Filled in with a pointer to the value of the variable. 3217 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3218 const VarDecl *VD, CallStackFrame *Frame, 3219 unsigned Version, APValue *&Result) { 3220 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3221 3222 // If this is a local variable, dig out its value. 3223 if (Frame) { 3224 Result = Frame->getTemporary(VD, Version); 3225 if (Result) 3226 return true; 3227 3228 if (!isa<ParmVarDecl>(VD)) { 3229 // Assume variables referenced within a lambda's call operator that were 3230 // not declared within the call operator are captures and during checking 3231 // of a potential constant expression, assume they are unknown constant 3232 // expressions. 3233 assert(isLambdaCallOperator(Frame->Callee) && 3234 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3235 "missing value for local variable"); 3236 if (Info.checkingPotentialConstantExpression()) 3237 return false; 3238 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3239 // still reachable at all? 3240 Info.FFDiag(E->getBeginLoc(), 3241 diag::note_unimplemented_constexpr_lambda_feature_ast) 3242 << "captures not currently allowed"; 3243 return false; 3244 } 3245 } 3246 3247 // If we're currently evaluating the initializer of this declaration, use that 3248 // in-flight value. 3249 if (Info.EvaluatingDecl == Base) { 3250 Result = Info.EvaluatingDeclValue; 3251 return true; 3252 } 3253 3254 if (isa<ParmVarDecl>(VD)) { 3255 // Assume parameters of a potential constant expression are usable in 3256 // constant expressions. 3257 if (!Info.checkingPotentialConstantExpression() || 3258 !Info.CurrentCall->Callee || 3259 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3260 if (Info.getLangOpts().CPlusPlus11) { 3261 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3262 << VD; 3263 NoteLValueLocation(Info, Base); 3264 } else { 3265 Info.FFDiag(E); 3266 } 3267 } 3268 return false; 3269 } 3270 3271 // Dig out the initializer, and use the declaration which it's attached to. 3272 // FIXME: We should eventually check whether the variable has a reachable 3273 // initializing declaration. 3274 const Expr *Init = VD->getAnyInitializer(VD); 3275 if (!Init) { 3276 // Don't diagnose during potential constant expression checking; an 3277 // initializer might be added later. 3278 if (!Info.checkingPotentialConstantExpression()) { 3279 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3280 << VD; 3281 NoteLValueLocation(Info, Base); 3282 } 3283 return false; 3284 } 3285 3286 if (Init->isValueDependent()) { 3287 // The DeclRefExpr is not value-dependent, but the variable it refers to 3288 // has a value-dependent initializer. This should only happen in 3289 // constant-folding cases, where the variable is not actually of a suitable 3290 // type for use in a constant expression (otherwise the DeclRefExpr would 3291 // have been value-dependent too), so diagnose that. 3292 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3293 if (!Info.checkingPotentialConstantExpression()) { 3294 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3295 ? diag::note_constexpr_ltor_non_constexpr 3296 : diag::note_constexpr_ltor_non_integral, 1) 3297 << VD << VD->getType(); 3298 NoteLValueLocation(Info, Base); 3299 } 3300 return false; 3301 } 3302 3303 // Check that we can fold the initializer. In C++, we will have already done 3304 // this in the cases where it matters for conformance. 3305 if (!VD->evaluateValue()) { 3306 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3307 NoteLValueLocation(Info, Base); 3308 return false; 3309 } 3310 3311 // Check that the variable is actually usable in constant expressions. For a 3312 // const integral variable or a reference, we might have a non-constant 3313 // initializer that we can nonetheless evaluate the initializer for. Such 3314 // variables are not usable in constant expressions. In C++98, the 3315 // initializer also syntactically needs to be an ICE. 3316 // 3317 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3318 // expressions here; doing so would regress diagnostics for things like 3319 // reading from a volatile constexpr variable. 3320 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3321 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3322 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3323 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3324 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3325 NoteLValueLocation(Info, Base); 3326 } 3327 3328 // Never use the initializer of a weak variable, not even for constant 3329 // folding. We can't be sure that this is the definition that will be used. 3330 if (VD->isWeak()) { 3331 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3332 NoteLValueLocation(Info, Base); 3333 return false; 3334 } 3335 3336 Result = VD->getEvaluatedValue(); 3337 return true; 3338 } 3339 3340 /// Get the base index of the given base class within an APValue representing 3341 /// the given derived class. 3342 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3343 const CXXRecordDecl *Base) { 3344 Base = Base->getCanonicalDecl(); 3345 unsigned Index = 0; 3346 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3347 E = Derived->bases_end(); I != E; ++I, ++Index) { 3348 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3349 return Index; 3350 } 3351 3352 llvm_unreachable("base class missing from derived class's bases list"); 3353 } 3354 3355 /// Extract the value of a character from a string literal. 3356 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3357 uint64_t Index) { 3358 assert(!isa<SourceLocExpr>(Lit) && 3359 "SourceLocExpr should have already been converted to a StringLiteral"); 3360 3361 // FIXME: Support MakeStringConstant 3362 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3363 std::string Str; 3364 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3365 assert(Index <= Str.size() && "Index too large"); 3366 return APSInt::getUnsigned(Str.c_str()[Index]); 3367 } 3368 3369 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3370 Lit = PE->getFunctionName(); 3371 const StringLiteral *S = cast<StringLiteral>(Lit); 3372 const ConstantArrayType *CAT = 3373 Info.Ctx.getAsConstantArrayType(S->getType()); 3374 assert(CAT && "string literal isn't an array"); 3375 QualType CharType = CAT->getElementType(); 3376 assert(CharType->isIntegerType() && "unexpected character type"); 3377 3378 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3379 CharType->isUnsignedIntegerType()); 3380 if (Index < S->getLength()) 3381 Value = S->getCodeUnit(Index); 3382 return Value; 3383 } 3384 3385 // Expand a string literal into an array of characters. 3386 // 3387 // FIXME: This is inefficient; we should probably introduce something similar 3388 // to the LLVM ConstantDataArray to make this cheaper. 3389 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3390 APValue &Result, 3391 QualType AllocType = QualType()) { 3392 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3393 AllocType.isNull() ? S->getType() : AllocType); 3394 assert(CAT && "string literal isn't an array"); 3395 QualType CharType = CAT->getElementType(); 3396 assert(CharType->isIntegerType() && "unexpected character type"); 3397 3398 unsigned Elts = CAT->getSize().getZExtValue(); 3399 Result = APValue(APValue::UninitArray(), 3400 std::min(S->getLength(), Elts), Elts); 3401 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3402 CharType->isUnsignedIntegerType()); 3403 if (Result.hasArrayFiller()) 3404 Result.getArrayFiller() = APValue(Value); 3405 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3406 Value = S->getCodeUnit(I); 3407 Result.getArrayInitializedElt(I) = APValue(Value); 3408 } 3409 } 3410 3411 // Expand an array so that it has more than Index filled elements. 3412 static void expandArray(APValue &Array, unsigned Index) { 3413 unsigned Size = Array.getArraySize(); 3414 assert(Index < Size); 3415 3416 // Always at least double the number of elements for which we store a value. 3417 unsigned OldElts = Array.getArrayInitializedElts(); 3418 unsigned NewElts = std::max(Index+1, OldElts * 2); 3419 NewElts = std::min(Size, std::max(NewElts, 8u)); 3420 3421 // Copy the data across. 3422 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3423 for (unsigned I = 0; I != OldElts; ++I) 3424 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3425 for (unsigned I = OldElts; I != NewElts; ++I) 3426 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3427 if (NewValue.hasArrayFiller()) 3428 NewValue.getArrayFiller() = Array.getArrayFiller(); 3429 Array.swap(NewValue); 3430 } 3431 3432 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3433 /// conversion. If it's of class type, we may assume that the copy operation 3434 /// is trivial. Note that this is never true for a union type with fields 3435 /// (because the copy always "reads" the active member) and always true for 3436 /// a non-class type. 3437 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3438 static bool isReadByLvalueToRvalueConversion(QualType T) { 3439 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3440 return !RD || isReadByLvalueToRvalueConversion(RD); 3441 } 3442 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3443 // FIXME: A trivial copy of a union copies the object representation, even if 3444 // the union is empty. 3445 if (RD->isUnion()) 3446 return !RD->field_empty(); 3447 if (RD->isEmpty()) 3448 return false; 3449 3450 for (auto *Field : RD->fields()) 3451 if (!Field->isUnnamedBitfield() && 3452 isReadByLvalueToRvalueConversion(Field->getType())) 3453 return true; 3454 3455 for (auto &BaseSpec : RD->bases()) 3456 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3457 return true; 3458 3459 return false; 3460 } 3461 3462 /// Diagnose an attempt to read from any unreadable field within the specified 3463 /// type, which might be a class type. 3464 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3465 QualType T) { 3466 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3467 if (!RD) 3468 return false; 3469 3470 if (!RD->hasMutableFields()) 3471 return false; 3472 3473 for (auto *Field : RD->fields()) { 3474 // If we're actually going to read this field in some way, then it can't 3475 // be mutable. If we're in a union, then assigning to a mutable field 3476 // (even an empty one) can change the active member, so that's not OK. 3477 // FIXME: Add core issue number for the union case. 3478 if (Field->isMutable() && 3479 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3480 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3481 Info.Note(Field->getLocation(), diag::note_declared_at); 3482 return true; 3483 } 3484 3485 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3486 return true; 3487 } 3488 3489 for (auto &BaseSpec : RD->bases()) 3490 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3491 return true; 3492 3493 // All mutable fields were empty, and thus not actually read. 3494 return false; 3495 } 3496 3497 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3498 APValue::LValueBase Base, 3499 bool MutableSubobject = false) { 3500 // A temporary we created. 3501 if (Base.getCallIndex()) 3502 return true; 3503 3504 switch (Info.IsEvaluatingDecl) { 3505 case EvalInfo::EvaluatingDeclKind::None: 3506 return false; 3507 3508 case EvalInfo::EvaluatingDeclKind::Ctor: 3509 // The variable whose initializer we're evaluating. 3510 if (Info.EvaluatingDecl == Base) 3511 return true; 3512 3513 // A temporary lifetime-extended by the variable whose initializer we're 3514 // evaluating. 3515 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3516 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3517 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3518 return false; 3519 3520 case EvalInfo::EvaluatingDeclKind::Dtor: 3521 // C++2a [expr.const]p6: 3522 // [during constant destruction] the lifetime of a and its non-mutable 3523 // subobjects (but not its mutable subobjects) [are] considered to start 3524 // within e. 3525 if (MutableSubobject || Base != Info.EvaluatingDecl) 3526 return false; 3527 // FIXME: We can meaningfully extend this to cover non-const objects, but 3528 // we will need special handling: we should be able to access only 3529 // subobjects of such objects that are themselves declared const. 3530 QualType T = getType(Base); 3531 return T.isConstQualified() || T->isReferenceType(); 3532 } 3533 3534 llvm_unreachable("unknown evaluating decl kind"); 3535 } 3536 3537 namespace { 3538 /// A handle to a complete object (an object that is not a subobject of 3539 /// another object). 3540 struct CompleteObject { 3541 /// The identity of the object. 3542 APValue::LValueBase Base; 3543 /// The value of the complete object. 3544 APValue *Value; 3545 /// The type of the complete object. 3546 QualType Type; 3547 3548 CompleteObject() : Value(nullptr) {} 3549 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3550 : Base(Base), Value(Value), Type(Type) {} 3551 3552 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3553 // If this isn't a "real" access (eg, if it's just accessing the type 3554 // info), allow it. We assume the type doesn't change dynamically for 3555 // subobjects of constexpr objects (even though we'd hit UB here if it 3556 // did). FIXME: Is this right? 3557 if (!isAnyAccess(AK)) 3558 return true; 3559 3560 // In C++14 onwards, it is permitted to read a mutable member whose 3561 // lifetime began within the evaluation. 3562 // FIXME: Should we also allow this in C++11? 3563 if (!Info.getLangOpts().CPlusPlus14) 3564 return false; 3565 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3566 } 3567 3568 explicit operator bool() const { return !Type.isNull(); } 3569 }; 3570 } // end anonymous namespace 3571 3572 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3573 bool IsMutable = false) { 3574 // C++ [basic.type.qualifier]p1: 3575 // - A const object is an object of type const T or a non-mutable subobject 3576 // of a const object. 3577 if (ObjType.isConstQualified() && !IsMutable) 3578 SubobjType.addConst(); 3579 // - A volatile object is an object of type const T or a subobject of a 3580 // volatile object. 3581 if (ObjType.isVolatileQualified()) 3582 SubobjType.addVolatile(); 3583 return SubobjType; 3584 } 3585 3586 /// Find the designated sub-object of an rvalue. 3587 template<typename SubobjectHandler> 3588 typename SubobjectHandler::result_type 3589 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3590 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3591 if (Sub.Invalid) 3592 // A diagnostic will have already been produced. 3593 return handler.failed(); 3594 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3595 if (Info.getLangOpts().CPlusPlus11) 3596 Info.FFDiag(E, Sub.isOnePastTheEnd() 3597 ? diag::note_constexpr_access_past_end 3598 : diag::note_constexpr_access_unsized_array) 3599 << handler.AccessKind; 3600 else 3601 Info.FFDiag(E); 3602 return handler.failed(); 3603 } 3604 3605 APValue *O = Obj.Value; 3606 QualType ObjType = Obj.Type; 3607 const FieldDecl *LastField = nullptr; 3608 const FieldDecl *VolatileField = nullptr; 3609 3610 // Walk the designator's path to find the subobject. 3611 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3612 // Reading an indeterminate value is undefined, but assigning over one is OK. 3613 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3614 (O->isIndeterminate() && 3615 !isValidIndeterminateAccess(handler.AccessKind))) { 3616 if (!Info.checkingPotentialConstantExpression()) 3617 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3618 << handler.AccessKind << O->isIndeterminate(); 3619 return handler.failed(); 3620 } 3621 3622 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3623 // const and volatile semantics are not applied on an object under 3624 // {con,de}struction. 3625 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3626 ObjType->isRecordType() && 3627 Info.isEvaluatingCtorDtor( 3628 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3629 Sub.Entries.begin() + I)) != 3630 ConstructionPhase::None) { 3631 ObjType = Info.Ctx.getCanonicalType(ObjType); 3632 ObjType.removeLocalConst(); 3633 ObjType.removeLocalVolatile(); 3634 } 3635 3636 // If this is our last pass, check that the final object type is OK. 3637 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3638 // Accesses to volatile objects are prohibited. 3639 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3640 if (Info.getLangOpts().CPlusPlus) { 3641 int DiagKind; 3642 SourceLocation Loc; 3643 const NamedDecl *Decl = nullptr; 3644 if (VolatileField) { 3645 DiagKind = 2; 3646 Loc = VolatileField->getLocation(); 3647 Decl = VolatileField; 3648 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3649 DiagKind = 1; 3650 Loc = VD->getLocation(); 3651 Decl = VD; 3652 } else { 3653 DiagKind = 0; 3654 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3655 Loc = E->getExprLoc(); 3656 } 3657 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3658 << handler.AccessKind << DiagKind << Decl; 3659 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3660 } else { 3661 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3662 } 3663 return handler.failed(); 3664 } 3665 3666 // If we are reading an object of class type, there may still be more 3667 // things we need to check: if there are any mutable subobjects, we 3668 // cannot perform this read. (This only happens when performing a trivial 3669 // copy or assignment.) 3670 if (ObjType->isRecordType() && 3671 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3672 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3673 return handler.failed(); 3674 } 3675 3676 if (I == N) { 3677 if (!handler.found(*O, ObjType)) 3678 return false; 3679 3680 // If we modified a bit-field, truncate it to the right width. 3681 if (isModification(handler.AccessKind) && 3682 LastField && LastField->isBitField() && 3683 !truncateBitfieldValue(Info, E, *O, LastField)) 3684 return false; 3685 3686 return true; 3687 } 3688 3689 LastField = nullptr; 3690 if (ObjType->isArrayType()) { 3691 // Next subobject is an array element. 3692 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3693 assert(CAT && "vla in literal type?"); 3694 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3695 if (CAT->getSize().ule(Index)) { 3696 // Note, it should not be possible to form a pointer with a valid 3697 // designator which points more than one past the end of the array. 3698 if (Info.getLangOpts().CPlusPlus11) 3699 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3700 << handler.AccessKind; 3701 else 3702 Info.FFDiag(E); 3703 return handler.failed(); 3704 } 3705 3706 ObjType = CAT->getElementType(); 3707 3708 if (O->getArrayInitializedElts() > Index) 3709 O = &O->getArrayInitializedElt(Index); 3710 else if (!isRead(handler.AccessKind)) { 3711 expandArray(*O, Index); 3712 O = &O->getArrayInitializedElt(Index); 3713 } else 3714 O = &O->getArrayFiller(); 3715 } else if (ObjType->isAnyComplexType()) { 3716 // Next subobject is a complex number. 3717 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3718 if (Index > 1) { 3719 if (Info.getLangOpts().CPlusPlus11) 3720 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3721 << handler.AccessKind; 3722 else 3723 Info.FFDiag(E); 3724 return handler.failed(); 3725 } 3726 3727 ObjType = getSubobjectType( 3728 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3729 3730 assert(I == N - 1 && "extracting subobject of scalar?"); 3731 if (O->isComplexInt()) { 3732 return handler.found(Index ? O->getComplexIntImag() 3733 : O->getComplexIntReal(), ObjType); 3734 } else { 3735 assert(O->isComplexFloat()); 3736 return handler.found(Index ? O->getComplexFloatImag() 3737 : O->getComplexFloatReal(), ObjType); 3738 } 3739 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3740 if (Field->isMutable() && 3741 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3742 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3743 << handler.AccessKind << Field; 3744 Info.Note(Field->getLocation(), diag::note_declared_at); 3745 return handler.failed(); 3746 } 3747 3748 // Next subobject is a class, struct or union field. 3749 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3750 if (RD->isUnion()) { 3751 const FieldDecl *UnionField = O->getUnionField(); 3752 if (!UnionField || 3753 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3754 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3755 // Placement new onto an inactive union member makes it active. 3756 O->setUnion(Field, APValue()); 3757 } else { 3758 // FIXME: If O->getUnionValue() is absent, report that there's no 3759 // active union member rather than reporting the prior active union 3760 // member. We'll need to fix nullptr_t to not use APValue() as its 3761 // representation first. 3762 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3763 << handler.AccessKind << Field << !UnionField << UnionField; 3764 return handler.failed(); 3765 } 3766 } 3767 O = &O->getUnionValue(); 3768 } else 3769 O = &O->getStructField(Field->getFieldIndex()); 3770 3771 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3772 LastField = Field; 3773 if (Field->getType().isVolatileQualified()) 3774 VolatileField = Field; 3775 } else { 3776 // Next subobject is a base class. 3777 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3778 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3779 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3780 3781 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3782 } 3783 } 3784 } 3785 3786 namespace { 3787 struct ExtractSubobjectHandler { 3788 EvalInfo &Info; 3789 const Expr *E; 3790 APValue &Result; 3791 const AccessKinds AccessKind; 3792 3793 typedef bool result_type; 3794 bool failed() { return false; } 3795 bool found(APValue &Subobj, QualType SubobjType) { 3796 Result = Subobj; 3797 if (AccessKind == AK_ReadObjectRepresentation) 3798 return true; 3799 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3800 } 3801 bool found(APSInt &Value, QualType SubobjType) { 3802 Result = APValue(Value); 3803 return true; 3804 } 3805 bool found(APFloat &Value, QualType SubobjType) { 3806 Result = APValue(Value); 3807 return true; 3808 } 3809 }; 3810 } // end anonymous namespace 3811 3812 /// Extract the designated sub-object of an rvalue. 3813 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3814 const CompleteObject &Obj, 3815 const SubobjectDesignator &Sub, APValue &Result, 3816 AccessKinds AK = AK_Read) { 3817 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3818 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3819 return findSubobject(Info, E, Obj, Sub, Handler); 3820 } 3821 3822 namespace { 3823 struct ModifySubobjectHandler { 3824 EvalInfo &Info; 3825 APValue &NewVal; 3826 const Expr *E; 3827 3828 typedef bool result_type; 3829 static const AccessKinds AccessKind = AK_Assign; 3830 3831 bool checkConst(QualType QT) { 3832 // Assigning to a const object has undefined behavior. 3833 if (QT.isConstQualified()) { 3834 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3835 return false; 3836 } 3837 return true; 3838 } 3839 3840 bool failed() { return false; } 3841 bool found(APValue &Subobj, QualType SubobjType) { 3842 if (!checkConst(SubobjType)) 3843 return false; 3844 // We've been given ownership of NewVal, so just swap it in. 3845 Subobj.swap(NewVal); 3846 return true; 3847 } 3848 bool found(APSInt &Value, QualType SubobjType) { 3849 if (!checkConst(SubobjType)) 3850 return false; 3851 if (!NewVal.isInt()) { 3852 // Maybe trying to write a cast pointer value into a complex? 3853 Info.FFDiag(E); 3854 return false; 3855 } 3856 Value = NewVal.getInt(); 3857 return true; 3858 } 3859 bool found(APFloat &Value, QualType SubobjType) { 3860 if (!checkConst(SubobjType)) 3861 return false; 3862 Value = NewVal.getFloat(); 3863 return true; 3864 } 3865 }; 3866 } // end anonymous namespace 3867 3868 const AccessKinds ModifySubobjectHandler::AccessKind; 3869 3870 /// Update the designated sub-object of an rvalue to the given value. 3871 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3872 const CompleteObject &Obj, 3873 const SubobjectDesignator &Sub, 3874 APValue &NewVal) { 3875 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3876 return findSubobject(Info, E, Obj, Sub, Handler); 3877 } 3878 3879 /// Find the position where two subobject designators diverge, or equivalently 3880 /// the length of the common initial subsequence. 3881 static unsigned FindDesignatorMismatch(QualType ObjType, 3882 const SubobjectDesignator &A, 3883 const SubobjectDesignator &B, 3884 bool &WasArrayIndex) { 3885 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3886 for (/**/; I != N; ++I) { 3887 if (!ObjType.isNull() && 3888 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3889 // Next subobject is an array element. 3890 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3891 WasArrayIndex = true; 3892 return I; 3893 } 3894 if (ObjType->isAnyComplexType()) 3895 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3896 else 3897 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3898 } else { 3899 if (A.Entries[I].getAsBaseOrMember() != 3900 B.Entries[I].getAsBaseOrMember()) { 3901 WasArrayIndex = false; 3902 return I; 3903 } 3904 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3905 // Next subobject is a field. 3906 ObjType = FD->getType(); 3907 else 3908 // Next subobject is a base class. 3909 ObjType = QualType(); 3910 } 3911 } 3912 WasArrayIndex = false; 3913 return I; 3914 } 3915 3916 /// Determine whether the given subobject designators refer to elements of the 3917 /// same array object. 3918 static bool AreElementsOfSameArray(QualType ObjType, 3919 const SubobjectDesignator &A, 3920 const SubobjectDesignator &B) { 3921 if (A.Entries.size() != B.Entries.size()) 3922 return false; 3923 3924 bool IsArray = A.MostDerivedIsArrayElement; 3925 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3926 // A is a subobject of the array element. 3927 return false; 3928 3929 // If A (and B) designates an array element, the last entry will be the array 3930 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3931 // of length 1' case, and the entire path must match. 3932 bool WasArrayIndex; 3933 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3934 return CommonLength >= A.Entries.size() - IsArray; 3935 } 3936 3937 /// Find the complete object to which an LValue refers. 3938 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3939 AccessKinds AK, const LValue &LVal, 3940 QualType LValType) { 3941 if (LVal.InvalidBase) { 3942 Info.FFDiag(E); 3943 return CompleteObject(); 3944 } 3945 3946 if (!LVal.Base) { 3947 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3948 return CompleteObject(); 3949 } 3950 3951 CallStackFrame *Frame = nullptr; 3952 unsigned Depth = 0; 3953 if (LVal.getLValueCallIndex()) { 3954 std::tie(Frame, Depth) = 3955 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3956 if (!Frame) { 3957 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3958 << AK << LVal.Base.is<const ValueDecl*>(); 3959 NoteLValueLocation(Info, LVal.Base); 3960 return CompleteObject(); 3961 } 3962 } 3963 3964 bool IsAccess = isAnyAccess(AK); 3965 3966 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3967 // is not a constant expression (even if the object is non-volatile). We also 3968 // apply this rule to C++98, in order to conform to the expected 'volatile' 3969 // semantics. 3970 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3971 if (Info.getLangOpts().CPlusPlus) 3972 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3973 << AK << LValType; 3974 else 3975 Info.FFDiag(E); 3976 return CompleteObject(); 3977 } 3978 3979 // Compute value storage location and type of base object. 3980 APValue *BaseVal = nullptr; 3981 QualType BaseType = getType(LVal.Base); 3982 3983 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3984 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3985 // This is the object whose initializer we're evaluating, so its lifetime 3986 // started in the current evaluation. 3987 BaseVal = Info.EvaluatingDeclValue; 3988 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3989 // Allow reading from a GUID declaration. 3990 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3991 if (isModification(AK)) { 3992 // All the remaining cases do not permit modification of the object. 3993 Info.FFDiag(E, diag::note_constexpr_modify_global); 3994 return CompleteObject(); 3995 } 3996 APValue &V = GD->getAsAPValue(); 3997 if (V.isAbsent()) { 3998 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3999 << GD->getType(); 4000 return CompleteObject(); 4001 } 4002 return CompleteObject(LVal.Base, &V, GD->getType()); 4003 } 4004 4005 // Allow reading from template parameter objects. 4006 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4007 if (isModification(AK)) { 4008 Info.FFDiag(E, diag::note_constexpr_modify_global); 4009 return CompleteObject(); 4010 } 4011 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4012 TPO->getType()); 4013 } 4014 4015 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4016 // In C++11, constexpr, non-volatile variables initialized with constant 4017 // expressions are constant expressions too. Inside constexpr functions, 4018 // parameters are constant expressions even if they're non-const. 4019 // In C++1y, objects local to a constant expression (those with a Frame) are 4020 // both readable and writable inside constant expressions. 4021 // In C, such things can also be folded, although they are not ICEs. 4022 const VarDecl *VD = dyn_cast<VarDecl>(D); 4023 if (VD) { 4024 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4025 VD = VDef; 4026 } 4027 if (!VD || VD->isInvalidDecl()) { 4028 Info.FFDiag(E); 4029 return CompleteObject(); 4030 } 4031 4032 bool IsConstant = BaseType.isConstant(Info.Ctx); 4033 4034 // Unless we're looking at a local variable or argument in a constexpr call, 4035 // the variable we're reading must be const. 4036 if (!Frame) { 4037 if (IsAccess && isa<ParmVarDecl>(VD)) { 4038 // Access of a parameter that's not associated with a frame isn't going 4039 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4040 // suitable diagnostic. 4041 } else if (Info.getLangOpts().CPlusPlus14 && 4042 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4043 // OK, we can read and modify an object if we're in the process of 4044 // evaluating its initializer, because its lifetime began in this 4045 // evaluation. 4046 } else if (isModification(AK)) { 4047 // All the remaining cases do not permit modification of the object. 4048 Info.FFDiag(E, diag::note_constexpr_modify_global); 4049 return CompleteObject(); 4050 } else if (VD->isConstexpr()) { 4051 // OK, we can read this variable. 4052 } else if (BaseType->isIntegralOrEnumerationType()) { 4053 if (!IsConstant) { 4054 if (!IsAccess) 4055 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4056 if (Info.getLangOpts().CPlusPlus) { 4057 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4058 Info.Note(VD->getLocation(), diag::note_declared_at); 4059 } else { 4060 Info.FFDiag(E); 4061 } 4062 return CompleteObject(); 4063 } 4064 } else if (!IsAccess) { 4065 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4066 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4067 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4068 // This variable might end up being constexpr. Don't diagnose it yet. 4069 } else if (IsConstant) { 4070 // Keep evaluating to see what we can do. In particular, we support 4071 // folding of const floating-point types, in order to make static const 4072 // data members of such types (supported as an extension) more useful. 4073 if (Info.getLangOpts().CPlusPlus) { 4074 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4075 ? diag::note_constexpr_ltor_non_constexpr 4076 : diag::note_constexpr_ltor_non_integral, 1) 4077 << VD << BaseType; 4078 Info.Note(VD->getLocation(), diag::note_declared_at); 4079 } else { 4080 Info.CCEDiag(E); 4081 } 4082 } else { 4083 // Never allow reading a non-const value. 4084 if (Info.getLangOpts().CPlusPlus) { 4085 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4086 ? diag::note_constexpr_ltor_non_constexpr 4087 : diag::note_constexpr_ltor_non_integral, 1) 4088 << VD << BaseType; 4089 Info.Note(VD->getLocation(), diag::note_declared_at); 4090 } else { 4091 Info.FFDiag(E); 4092 } 4093 return CompleteObject(); 4094 } 4095 } 4096 4097 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4098 return CompleteObject(); 4099 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4100 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4101 if (!Alloc) { 4102 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4103 return CompleteObject(); 4104 } 4105 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4106 LVal.Base.getDynamicAllocType()); 4107 } else { 4108 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4109 4110 if (!Frame) { 4111 if (const MaterializeTemporaryExpr *MTE = 4112 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4113 assert(MTE->getStorageDuration() == SD_Static && 4114 "should have a frame for a non-global materialized temporary"); 4115 4116 // C++20 [expr.const]p4: [DR2126] 4117 // An object or reference is usable in constant expressions if it is 4118 // - a temporary object of non-volatile const-qualified literal type 4119 // whose lifetime is extended to that of a variable that is usable 4120 // in constant expressions 4121 // 4122 // C++20 [expr.const]p5: 4123 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4124 // - a non-volatile glvalue that refers to an object that is usable 4125 // in constant expressions, or 4126 // - a non-volatile glvalue of literal type that refers to a 4127 // non-volatile object whose lifetime began within the evaluation 4128 // of E; 4129 // 4130 // C++11 misses the 'began within the evaluation of e' check and 4131 // instead allows all temporaries, including things like: 4132 // int &&r = 1; 4133 // int x = ++r; 4134 // constexpr int k = r; 4135 // Therefore we use the C++14-onwards rules in C++11 too. 4136 // 4137 // Note that temporaries whose lifetimes began while evaluating a 4138 // variable's constructor are not usable while evaluating the 4139 // corresponding destructor, not even if they're of const-qualified 4140 // types. 4141 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4142 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4143 if (!IsAccess) 4144 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4145 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4146 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4147 return CompleteObject(); 4148 } 4149 4150 BaseVal = MTE->getOrCreateValue(false); 4151 assert(BaseVal && "got reference to unevaluated temporary"); 4152 } else { 4153 if (!IsAccess) 4154 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4155 APValue Val; 4156 LVal.moveInto(Val); 4157 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4158 << AK 4159 << Val.getAsString(Info.Ctx, 4160 Info.Ctx.getLValueReferenceType(LValType)); 4161 NoteLValueLocation(Info, LVal.Base); 4162 return CompleteObject(); 4163 } 4164 } else { 4165 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4166 assert(BaseVal && "missing value for temporary"); 4167 } 4168 } 4169 4170 // In C++14, we can't safely access any mutable state when we might be 4171 // evaluating after an unmodeled side effect. Parameters are modeled as state 4172 // in the caller, but aren't visible once the call returns, so they can be 4173 // modified in a speculatively-evaluated call. 4174 // 4175 // FIXME: Not all local state is mutable. Allow local constant subobjects 4176 // to be read here (but take care with 'mutable' fields). 4177 unsigned VisibleDepth = Depth; 4178 if (llvm::isa_and_nonnull<ParmVarDecl>( 4179 LVal.Base.dyn_cast<const ValueDecl *>())) 4180 ++VisibleDepth; 4181 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4182 Info.EvalStatus.HasSideEffects) || 4183 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4184 return CompleteObject(); 4185 4186 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4187 } 4188 4189 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4190 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4191 /// glvalue referred to by an entity of reference type. 4192 /// 4193 /// \param Info - Information about the ongoing evaluation. 4194 /// \param Conv - The expression for which we are performing the conversion. 4195 /// Used for diagnostics. 4196 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4197 /// case of a non-class type). 4198 /// \param LVal - The glvalue on which we are attempting to perform this action. 4199 /// \param RVal - The produced value will be placed here. 4200 /// \param WantObjectRepresentation - If true, we're looking for the object 4201 /// representation rather than the value, and in particular, 4202 /// there is no requirement that the result be fully initialized. 4203 static bool 4204 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4205 const LValue &LVal, APValue &RVal, 4206 bool WantObjectRepresentation = false) { 4207 if (LVal.Designator.Invalid) 4208 return false; 4209 4210 // Check for special cases where there is no existing APValue to look at. 4211 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4212 4213 AccessKinds AK = 4214 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4215 4216 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4217 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4218 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4219 // initializer until now for such expressions. Such an expression can't be 4220 // an ICE in C, so this only matters for fold. 4221 if (Type.isVolatileQualified()) { 4222 Info.FFDiag(Conv); 4223 return false; 4224 } 4225 APValue Lit; 4226 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4227 return false; 4228 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4229 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4230 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4231 // Special-case character extraction so we don't have to construct an 4232 // APValue for the whole string. 4233 assert(LVal.Designator.Entries.size() <= 1 && 4234 "Can only read characters from string literals"); 4235 if (LVal.Designator.Entries.empty()) { 4236 // Fail for now for LValue to RValue conversion of an array. 4237 // (This shouldn't show up in C/C++, but it could be triggered by a 4238 // weird EvaluateAsRValue call from a tool.) 4239 Info.FFDiag(Conv); 4240 return false; 4241 } 4242 if (LVal.Designator.isOnePastTheEnd()) { 4243 if (Info.getLangOpts().CPlusPlus11) 4244 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4245 else 4246 Info.FFDiag(Conv); 4247 return false; 4248 } 4249 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4250 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4251 return true; 4252 } 4253 } 4254 4255 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4256 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4257 } 4258 4259 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4260 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4261 QualType LValType, APValue &Val) { 4262 if (LVal.Designator.Invalid) 4263 return false; 4264 4265 if (!Info.getLangOpts().CPlusPlus14) { 4266 Info.FFDiag(E); 4267 return false; 4268 } 4269 4270 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4271 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4272 } 4273 4274 namespace { 4275 struct CompoundAssignSubobjectHandler { 4276 EvalInfo &Info; 4277 const CompoundAssignOperator *E; 4278 QualType PromotedLHSType; 4279 BinaryOperatorKind Opcode; 4280 const APValue &RHS; 4281 4282 static const AccessKinds AccessKind = AK_Assign; 4283 4284 typedef bool result_type; 4285 4286 bool checkConst(QualType QT) { 4287 // Assigning to a const object has undefined behavior. 4288 if (QT.isConstQualified()) { 4289 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4290 return false; 4291 } 4292 return true; 4293 } 4294 4295 bool failed() { return false; } 4296 bool found(APValue &Subobj, QualType SubobjType) { 4297 switch (Subobj.getKind()) { 4298 case APValue::Int: 4299 return found(Subobj.getInt(), SubobjType); 4300 case APValue::Float: 4301 return found(Subobj.getFloat(), SubobjType); 4302 case APValue::ComplexInt: 4303 case APValue::ComplexFloat: 4304 // FIXME: Implement complex compound assignment. 4305 Info.FFDiag(E); 4306 return false; 4307 case APValue::LValue: 4308 return foundPointer(Subobj, SubobjType); 4309 case APValue::Vector: 4310 return foundVector(Subobj, SubobjType); 4311 default: 4312 // FIXME: can this happen? 4313 Info.FFDiag(E); 4314 return false; 4315 } 4316 } 4317 4318 bool foundVector(APValue &Value, QualType SubobjType) { 4319 if (!checkConst(SubobjType)) 4320 return false; 4321 4322 if (!SubobjType->isVectorType()) { 4323 Info.FFDiag(E); 4324 return false; 4325 } 4326 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4327 } 4328 4329 bool found(APSInt &Value, QualType SubobjType) { 4330 if (!checkConst(SubobjType)) 4331 return false; 4332 4333 if (!SubobjType->isIntegerType()) { 4334 // We don't support compound assignment on integer-cast-to-pointer 4335 // values. 4336 Info.FFDiag(E); 4337 return false; 4338 } 4339 4340 if (RHS.isInt()) { 4341 APSInt LHS = 4342 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4343 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4344 return false; 4345 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4346 return true; 4347 } else if (RHS.isFloat()) { 4348 const FPOptions FPO = E->getFPFeaturesInEffect( 4349 Info.Ctx.getLangOpts()); 4350 APFloat FValue(0.0); 4351 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4352 PromotedLHSType, FValue) && 4353 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4354 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4355 Value); 4356 } 4357 4358 Info.FFDiag(E); 4359 return false; 4360 } 4361 bool found(APFloat &Value, QualType SubobjType) { 4362 return checkConst(SubobjType) && 4363 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4364 Value) && 4365 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4366 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4367 } 4368 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4369 if (!checkConst(SubobjType)) 4370 return false; 4371 4372 QualType PointeeType; 4373 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4374 PointeeType = PT->getPointeeType(); 4375 4376 if (PointeeType.isNull() || !RHS.isInt() || 4377 (Opcode != BO_Add && Opcode != BO_Sub)) { 4378 Info.FFDiag(E); 4379 return false; 4380 } 4381 4382 APSInt Offset = RHS.getInt(); 4383 if (Opcode == BO_Sub) 4384 negateAsSigned(Offset); 4385 4386 LValue LVal; 4387 LVal.setFrom(Info.Ctx, Subobj); 4388 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4389 return false; 4390 LVal.moveInto(Subobj); 4391 return true; 4392 } 4393 }; 4394 } // end anonymous namespace 4395 4396 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4397 4398 /// Perform a compound assignment of LVal <op>= RVal. 4399 static bool handleCompoundAssignment(EvalInfo &Info, 4400 const CompoundAssignOperator *E, 4401 const LValue &LVal, QualType LValType, 4402 QualType PromotedLValType, 4403 BinaryOperatorKind Opcode, 4404 const APValue &RVal) { 4405 if (LVal.Designator.Invalid) 4406 return false; 4407 4408 if (!Info.getLangOpts().CPlusPlus14) { 4409 Info.FFDiag(E); 4410 return false; 4411 } 4412 4413 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4414 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4415 RVal }; 4416 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4417 } 4418 4419 namespace { 4420 struct IncDecSubobjectHandler { 4421 EvalInfo &Info; 4422 const UnaryOperator *E; 4423 AccessKinds AccessKind; 4424 APValue *Old; 4425 4426 typedef bool result_type; 4427 4428 bool checkConst(QualType QT) { 4429 // Assigning to a const object has undefined behavior. 4430 if (QT.isConstQualified()) { 4431 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4432 return false; 4433 } 4434 return true; 4435 } 4436 4437 bool failed() { return false; } 4438 bool found(APValue &Subobj, QualType SubobjType) { 4439 // Stash the old value. Also clear Old, so we don't clobber it later 4440 // if we're post-incrementing a complex. 4441 if (Old) { 4442 *Old = Subobj; 4443 Old = nullptr; 4444 } 4445 4446 switch (Subobj.getKind()) { 4447 case APValue::Int: 4448 return found(Subobj.getInt(), SubobjType); 4449 case APValue::Float: 4450 return found(Subobj.getFloat(), SubobjType); 4451 case APValue::ComplexInt: 4452 return found(Subobj.getComplexIntReal(), 4453 SubobjType->castAs<ComplexType>()->getElementType() 4454 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4455 case APValue::ComplexFloat: 4456 return found(Subobj.getComplexFloatReal(), 4457 SubobjType->castAs<ComplexType>()->getElementType() 4458 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4459 case APValue::LValue: 4460 return foundPointer(Subobj, SubobjType); 4461 default: 4462 // FIXME: can this happen? 4463 Info.FFDiag(E); 4464 return false; 4465 } 4466 } 4467 bool found(APSInt &Value, QualType SubobjType) { 4468 if (!checkConst(SubobjType)) 4469 return false; 4470 4471 if (!SubobjType->isIntegerType()) { 4472 // We don't support increment / decrement on integer-cast-to-pointer 4473 // values. 4474 Info.FFDiag(E); 4475 return false; 4476 } 4477 4478 if (Old) *Old = APValue(Value); 4479 4480 // bool arithmetic promotes to int, and the conversion back to bool 4481 // doesn't reduce mod 2^n, so special-case it. 4482 if (SubobjType->isBooleanType()) { 4483 if (AccessKind == AK_Increment) 4484 Value = 1; 4485 else 4486 Value = !Value; 4487 return true; 4488 } 4489 4490 bool WasNegative = Value.isNegative(); 4491 if (AccessKind == AK_Increment) { 4492 ++Value; 4493 4494 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4495 APSInt ActualValue(Value, /*IsUnsigned*/true); 4496 return HandleOverflow(Info, E, ActualValue, SubobjType); 4497 } 4498 } else { 4499 --Value; 4500 4501 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4502 unsigned BitWidth = Value.getBitWidth(); 4503 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4504 ActualValue.setBit(BitWidth); 4505 return HandleOverflow(Info, E, ActualValue, SubobjType); 4506 } 4507 } 4508 return true; 4509 } 4510 bool found(APFloat &Value, QualType SubobjType) { 4511 if (!checkConst(SubobjType)) 4512 return false; 4513 4514 if (Old) *Old = APValue(Value); 4515 4516 APFloat One(Value.getSemantics(), 1); 4517 if (AccessKind == AK_Increment) 4518 Value.add(One, APFloat::rmNearestTiesToEven); 4519 else 4520 Value.subtract(One, APFloat::rmNearestTiesToEven); 4521 return true; 4522 } 4523 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4524 if (!checkConst(SubobjType)) 4525 return false; 4526 4527 QualType PointeeType; 4528 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4529 PointeeType = PT->getPointeeType(); 4530 else { 4531 Info.FFDiag(E); 4532 return false; 4533 } 4534 4535 LValue LVal; 4536 LVal.setFrom(Info.Ctx, Subobj); 4537 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4538 AccessKind == AK_Increment ? 1 : -1)) 4539 return false; 4540 LVal.moveInto(Subobj); 4541 return true; 4542 } 4543 }; 4544 } // end anonymous namespace 4545 4546 /// Perform an increment or decrement on LVal. 4547 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4548 QualType LValType, bool IsIncrement, APValue *Old) { 4549 if (LVal.Designator.Invalid) 4550 return false; 4551 4552 if (!Info.getLangOpts().CPlusPlus14) { 4553 Info.FFDiag(E); 4554 return false; 4555 } 4556 4557 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4558 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4559 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4560 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4561 } 4562 4563 /// Build an lvalue for the object argument of a member function call. 4564 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4565 LValue &This) { 4566 if (Object->getType()->isPointerType() && Object->isRValue()) 4567 return EvaluatePointer(Object, This, Info); 4568 4569 if (Object->isGLValue()) 4570 return EvaluateLValue(Object, This, Info); 4571 4572 if (Object->getType()->isLiteralType(Info.Ctx)) 4573 return EvaluateTemporary(Object, This, Info); 4574 4575 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4576 return false; 4577 } 4578 4579 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4580 /// lvalue referring to the result. 4581 /// 4582 /// \param Info - Information about the ongoing evaluation. 4583 /// \param LV - An lvalue referring to the base of the member pointer. 4584 /// \param RHS - The member pointer expression. 4585 /// \param IncludeMember - Specifies whether the member itself is included in 4586 /// the resulting LValue subobject designator. This is not possible when 4587 /// creating a bound member function. 4588 /// \return The field or method declaration to which the member pointer refers, 4589 /// or 0 if evaluation fails. 4590 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4591 QualType LVType, 4592 LValue &LV, 4593 const Expr *RHS, 4594 bool IncludeMember = true) { 4595 MemberPtr MemPtr; 4596 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4597 return nullptr; 4598 4599 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4600 // member value, the behavior is undefined. 4601 if (!MemPtr.getDecl()) { 4602 // FIXME: Specific diagnostic. 4603 Info.FFDiag(RHS); 4604 return nullptr; 4605 } 4606 4607 if (MemPtr.isDerivedMember()) { 4608 // This is a member of some derived class. Truncate LV appropriately. 4609 // The end of the derived-to-base path for the base object must match the 4610 // derived-to-base path for the member pointer. 4611 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4612 LV.Designator.Entries.size()) { 4613 Info.FFDiag(RHS); 4614 return nullptr; 4615 } 4616 unsigned PathLengthToMember = 4617 LV.Designator.Entries.size() - MemPtr.Path.size(); 4618 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4619 const CXXRecordDecl *LVDecl = getAsBaseClass( 4620 LV.Designator.Entries[PathLengthToMember + I]); 4621 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4622 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4623 Info.FFDiag(RHS); 4624 return nullptr; 4625 } 4626 } 4627 4628 // Truncate the lvalue to the appropriate derived class. 4629 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4630 PathLengthToMember)) 4631 return nullptr; 4632 } else if (!MemPtr.Path.empty()) { 4633 // Extend the LValue path with the member pointer's path. 4634 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4635 MemPtr.Path.size() + IncludeMember); 4636 4637 // Walk down to the appropriate base class. 4638 if (const PointerType *PT = LVType->getAs<PointerType>()) 4639 LVType = PT->getPointeeType(); 4640 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4641 assert(RD && "member pointer access on non-class-type expression"); 4642 // The first class in the path is that of the lvalue. 4643 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4644 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4645 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4646 return nullptr; 4647 RD = Base; 4648 } 4649 // Finally cast to the class containing the member. 4650 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4651 MemPtr.getContainingRecord())) 4652 return nullptr; 4653 } 4654 4655 // Add the member. Note that we cannot build bound member functions here. 4656 if (IncludeMember) { 4657 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4658 if (!HandleLValueMember(Info, RHS, LV, FD)) 4659 return nullptr; 4660 } else if (const IndirectFieldDecl *IFD = 4661 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4662 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4663 return nullptr; 4664 } else { 4665 llvm_unreachable("can't construct reference to bound member function"); 4666 } 4667 } 4668 4669 return MemPtr.getDecl(); 4670 } 4671 4672 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4673 const BinaryOperator *BO, 4674 LValue &LV, 4675 bool IncludeMember = true) { 4676 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4677 4678 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4679 if (Info.noteFailure()) { 4680 MemberPtr MemPtr; 4681 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4682 } 4683 return nullptr; 4684 } 4685 4686 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4687 BO->getRHS(), IncludeMember); 4688 } 4689 4690 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4691 /// the provided lvalue, which currently refers to the base object. 4692 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4693 LValue &Result) { 4694 SubobjectDesignator &D = Result.Designator; 4695 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4696 return false; 4697 4698 QualType TargetQT = E->getType(); 4699 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4700 TargetQT = PT->getPointeeType(); 4701 4702 // Check this cast lands within the final derived-to-base subobject path. 4703 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4704 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4705 << D.MostDerivedType << TargetQT; 4706 return false; 4707 } 4708 4709 // Check the type of the final cast. We don't need to check the path, 4710 // since a cast can only be formed if the path is unique. 4711 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4712 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4713 const CXXRecordDecl *FinalType; 4714 if (NewEntriesSize == D.MostDerivedPathLength) 4715 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4716 else 4717 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4718 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4719 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4720 << D.MostDerivedType << TargetQT; 4721 return false; 4722 } 4723 4724 // Truncate the lvalue to the appropriate derived class. 4725 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4726 } 4727 4728 /// Get the value to use for a default-initialized object of type T. 4729 /// Return false if it encounters something invalid. 4730 static bool getDefaultInitValue(QualType T, APValue &Result) { 4731 bool Success = true; 4732 if (auto *RD = T->getAsCXXRecordDecl()) { 4733 if (RD->isInvalidDecl()) { 4734 Result = APValue(); 4735 return false; 4736 } 4737 if (RD->isUnion()) { 4738 Result = APValue((const FieldDecl *)nullptr); 4739 return true; 4740 } 4741 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4742 std::distance(RD->field_begin(), RD->field_end())); 4743 4744 unsigned Index = 0; 4745 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4746 End = RD->bases_end(); 4747 I != End; ++I, ++Index) 4748 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4749 4750 for (const auto *I : RD->fields()) { 4751 if (I->isUnnamedBitfield()) 4752 continue; 4753 Success &= getDefaultInitValue(I->getType(), 4754 Result.getStructField(I->getFieldIndex())); 4755 } 4756 return Success; 4757 } 4758 4759 if (auto *AT = 4760 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4761 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4762 if (Result.hasArrayFiller()) 4763 Success &= 4764 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4765 4766 return Success; 4767 } 4768 4769 Result = APValue::IndeterminateValue(); 4770 return true; 4771 } 4772 4773 namespace { 4774 enum EvalStmtResult { 4775 /// Evaluation failed. 4776 ESR_Failed, 4777 /// Hit a 'return' statement. 4778 ESR_Returned, 4779 /// Evaluation succeeded. 4780 ESR_Succeeded, 4781 /// Hit a 'continue' statement. 4782 ESR_Continue, 4783 /// Hit a 'break' statement. 4784 ESR_Break, 4785 /// Still scanning for 'case' or 'default' statement. 4786 ESR_CaseNotFound 4787 }; 4788 } 4789 4790 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4791 // We don't need to evaluate the initializer for a static local. 4792 if (!VD->hasLocalStorage()) 4793 return true; 4794 4795 LValue Result; 4796 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4797 ScopeKind::Block, Result); 4798 4799 const Expr *InitE = VD->getInit(); 4800 if (!InitE) { 4801 if (VD->getType()->isDependentType()) 4802 return Info.noteSideEffect(); 4803 return getDefaultInitValue(VD->getType(), Val); 4804 } 4805 if (InitE->isValueDependent()) 4806 return false; 4807 4808 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4809 // Wipe out any partially-computed value, to allow tracking that this 4810 // evaluation failed. 4811 Val = APValue(); 4812 return false; 4813 } 4814 4815 return true; 4816 } 4817 4818 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4819 bool OK = true; 4820 4821 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4822 OK &= EvaluateVarDecl(Info, VD); 4823 4824 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4825 for (auto *BD : DD->bindings()) 4826 if (auto *VD = BD->getHoldingVar()) 4827 OK &= EvaluateDecl(Info, VD); 4828 4829 return OK; 4830 } 4831 4832 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4833 assert(E->isValueDependent()); 4834 if (Info.noteSideEffect()) 4835 return true; 4836 assert(E->containsErrors() && "valid value-dependent expression should never " 4837 "reach invalid code path."); 4838 return false; 4839 } 4840 4841 /// Evaluate a condition (either a variable declaration or an expression). 4842 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4843 const Expr *Cond, bool &Result) { 4844 if (Cond->isValueDependent()) 4845 return false; 4846 FullExpressionRAII Scope(Info); 4847 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4848 return false; 4849 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4850 return false; 4851 return Scope.destroy(); 4852 } 4853 4854 namespace { 4855 /// A location where the result (returned value) of evaluating a 4856 /// statement should be stored. 4857 struct StmtResult { 4858 /// The APValue that should be filled in with the returned value. 4859 APValue &Value; 4860 /// The location containing the result, if any (used to support RVO). 4861 const LValue *Slot; 4862 }; 4863 4864 struct TempVersionRAII { 4865 CallStackFrame &Frame; 4866 4867 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4868 Frame.pushTempVersion(); 4869 } 4870 4871 ~TempVersionRAII() { 4872 Frame.popTempVersion(); 4873 } 4874 }; 4875 4876 } 4877 4878 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4879 const Stmt *S, 4880 const SwitchCase *SC = nullptr); 4881 4882 /// Evaluate the body of a loop, and translate the result as appropriate. 4883 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4884 const Stmt *Body, 4885 const SwitchCase *Case = nullptr) { 4886 BlockScopeRAII Scope(Info); 4887 4888 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4889 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4890 ESR = ESR_Failed; 4891 4892 switch (ESR) { 4893 case ESR_Break: 4894 return ESR_Succeeded; 4895 case ESR_Succeeded: 4896 case ESR_Continue: 4897 return ESR_Continue; 4898 case ESR_Failed: 4899 case ESR_Returned: 4900 case ESR_CaseNotFound: 4901 return ESR; 4902 } 4903 llvm_unreachable("Invalid EvalStmtResult!"); 4904 } 4905 4906 /// Evaluate a switch statement. 4907 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4908 const SwitchStmt *SS) { 4909 BlockScopeRAII Scope(Info); 4910 4911 // Evaluate the switch condition. 4912 APSInt Value; 4913 { 4914 if (const Stmt *Init = SS->getInit()) { 4915 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4916 if (ESR != ESR_Succeeded) { 4917 if (ESR != ESR_Failed && !Scope.destroy()) 4918 ESR = ESR_Failed; 4919 return ESR; 4920 } 4921 } 4922 4923 FullExpressionRAII CondScope(Info); 4924 if (SS->getConditionVariable() && 4925 !EvaluateDecl(Info, SS->getConditionVariable())) 4926 return ESR_Failed; 4927 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4928 return ESR_Failed; 4929 if (!CondScope.destroy()) 4930 return ESR_Failed; 4931 } 4932 4933 // Find the switch case corresponding to the value of the condition. 4934 // FIXME: Cache this lookup. 4935 const SwitchCase *Found = nullptr; 4936 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4937 SC = SC->getNextSwitchCase()) { 4938 if (isa<DefaultStmt>(SC)) { 4939 Found = SC; 4940 continue; 4941 } 4942 4943 const CaseStmt *CS = cast<CaseStmt>(SC); 4944 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4945 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4946 : LHS; 4947 if (LHS <= Value && Value <= RHS) { 4948 Found = SC; 4949 break; 4950 } 4951 } 4952 4953 if (!Found) 4954 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4955 4956 // Search the switch body for the switch case and evaluate it from there. 4957 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4958 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4959 return ESR_Failed; 4960 4961 switch (ESR) { 4962 case ESR_Break: 4963 return ESR_Succeeded; 4964 case ESR_Succeeded: 4965 case ESR_Continue: 4966 case ESR_Failed: 4967 case ESR_Returned: 4968 return ESR; 4969 case ESR_CaseNotFound: 4970 // This can only happen if the switch case is nested within a statement 4971 // expression. We have no intention of supporting that. 4972 Info.FFDiag(Found->getBeginLoc(), 4973 diag::note_constexpr_stmt_expr_unsupported); 4974 return ESR_Failed; 4975 } 4976 llvm_unreachable("Invalid EvalStmtResult!"); 4977 } 4978 4979 // Evaluate a statement. 4980 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4981 const Stmt *S, const SwitchCase *Case) { 4982 if (!Info.nextStep(S)) 4983 return ESR_Failed; 4984 4985 // If we're hunting down a 'case' or 'default' label, recurse through 4986 // substatements until we hit the label. 4987 if (Case) { 4988 switch (S->getStmtClass()) { 4989 case Stmt::CompoundStmtClass: 4990 // FIXME: Precompute which substatement of a compound statement we 4991 // would jump to, and go straight there rather than performing a 4992 // linear scan each time. 4993 case Stmt::LabelStmtClass: 4994 case Stmt::AttributedStmtClass: 4995 case Stmt::DoStmtClass: 4996 break; 4997 4998 case Stmt::CaseStmtClass: 4999 case Stmt::DefaultStmtClass: 5000 if (Case == S) 5001 Case = nullptr; 5002 break; 5003 5004 case Stmt::IfStmtClass: { 5005 // FIXME: Precompute which side of an 'if' we would jump to, and go 5006 // straight there rather than scanning both sides. 5007 const IfStmt *IS = cast<IfStmt>(S); 5008 5009 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5010 // preceded by our switch label. 5011 BlockScopeRAII Scope(Info); 5012 5013 // Step into the init statement in case it brings an (uninitialized) 5014 // variable into scope. 5015 if (const Stmt *Init = IS->getInit()) { 5016 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5017 if (ESR != ESR_CaseNotFound) { 5018 assert(ESR != ESR_Succeeded); 5019 return ESR; 5020 } 5021 } 5022 5023 // Condition variable must be initialized if it exists. 5024 // FIXME: We can skip evaluating the body if there's a condition 5025 // variable, as there can't be any case labels within it. 5026 // (The same is true for 'for' statements.) 5027 5028 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5029 if (ESR == ESR_Failed) 5030 return ESR; 5031 if (ESR != ESR_CaseNotFound) 5032 return Scope.destroy() ? ESR : ESR_Failed; 5033 if (!IS->getElse()) 5034 return ESR_CaseNotFound; 5035 5036 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5037 if (ESR == ESR_Failed) 5038 return ESR; 5039 if (ESR != ESR_CaseNotFound) 5040 return Scope.destroy() ? ESR : ESR_Failed; 5041 return ESR_CaseNotFound; 5042 } 5043 5044 case Stmt::WhileStmtClass: { 5045 EvalStmtResult ESR = 5046 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5047 if (ESR != ESR_Continue) 5048 return ESR; 5049 break; 5050 } 5051 5052 case Stmt::ForStmtClass: { 5053 const ForStmt *FS = cast<ForStmt>(S); 5054 BlockScopeRAII Scope(Info); 5055 5056 // Step into the init statement in case it brings an (uninitialized) 5057 // variable into scope. 5058 if (const Stmt *Init = FS->getInit()) { 5059 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5060 if (ESR != ESR_CaseNotFound) { 5061 assert(ESR != ESR_Succeeded); 5062 return ESR; 5063 } 5064 } 5065 5066 EvalStmtResult ESR = 5067 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5068 if (ESR != ESR_Continue) 5069 return ESR; 5070 if (const auto *Inc = FS->getInc()) { 5071 if (Inc->isValueDependent()) { 5072 if (!EvaluateDependentExpr(Inc, Info)) 5073 return ESR_Failed; 5074 } else { 5075 FullExpressionRAII IncScope(Info); 5076 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5077 return ESR_Failed; 5078 } 5079 } 5080 break; 5081 } 5082 5083 case Stmt::DeclStmtClass: { 5084 // Start the lifetime of any uninitialized variables we encounter. They 5085 // might be used by the selected branch of the switch. 5086 const DeclStmt *DS = cast<DeclStmt>(S); 5087 for (const auto *D : DS->decls()) { 5088 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5089 if (VD->hasLocalStorage() && !VD->getInit()) 5090 if (!EvaluateVarDecl(Info, VD)) 5091 return ESR_Failed; 5092 // FIXME: If the variable has initialization that can't be jumped 5093 // over, bail out of any immediately-surrounding compound-statement 5094 // too. There can't be any case labels here. 5095 } 5096 } 5097 return ESR_CaseNotFound; 5098 } 5099 5100 default: 5101 return ESR_CaseNotFound; 5102 } 5103 } 5104 5105 switch (S->getStmtClass()) { 5106 default: 5107 if (const Expr *E = dyn_cast<Expr>(S)) { 5108 if (E->isValueDependent()) { 5109 if (!EvaluateDependentExpr(E, Info)) 5110 return ESR_Failed; 5111 } else { 5112 // Don't bother evaluating beyond an expression-statement which couldn't 5113 // be evaluated. 5114 // FIXME: Do we need the FullExpressionRAII object here? 5115 // VisitExprWithCleanups should create one when necessary. 5116 FullExpressionRAII Scope(Info); 5117 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5118 return ESR_Failed; 5119 } 5120 return ESR_Succeeded; 5121 } 5122 5123 Info.FFDiag(S->getBeginLoc()); 5124 return ESR_Failed; 5125 5126 case Stmt::NullStmtClass: 5127 return ESR_Succeeded; 5128 5129 case Stmt::DeclStmtClass: { 5130 const DeclStmt *DS = cast<DeclStmt>(S); 5131 for (const auto *D : DS->decls()) { 5132 // Each declaration initialization is its own full-expression. 5133 FullExpressionRAII Scope(Info); 5134 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5135 return ESR_Failed; 5136 if (!Scope.destroy()) 5137 return ESR_Failed; 5138 } 5139 return ESR_Succeeded; 5140 } 5141 5142 case Stmt::ReturnStmtClass: { 5143 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5144 FullExpressionRAII Scope(Info); 5145 if (RetExpr && RetExpr->isValueDependent()) { 5146 EvaluateDependentExpr(RetExpr, Info); 5147 // We know we returned, but we don't know what the value is. 5148 return ESR_Failed; 5149 } 5150 if (RetExpr && 5151 !(Result.Slot 5152 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5153 : Evaluate(Result.Value, Info, RetExpr))) 5154 return ESR_Failed; 5155 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5156 } 5157 5158 case Stmt::CompoundStmtClass: { 5159 BlockScopeRAII Scope(Info); 5160 5161 const CompoundStmt *CS = cast<CompoundStmt>(S); 5162 for (const auto *BI : CS->body()) { 5163 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5164 if (ESR == ESR_Succeeded) 5165 Case = nullptr; 5166 else if (ESR != ESR_CaseNotFound) { 5167 if (ESR != ESR_Failed && !Scope.destroy()) 5168 return ESR_Failed; 5169 return ESR; 5170 } 5171 } 5172 if (Case) 5173 return ESR_CaseNotFound; 5174 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5175 } 5176 5177 case Stmt::IfStmtClass: { 5178 const IfStmt *IS = cast<IfStmt>(S); 5179 5180 // Evaluate the condition, as either a var decl or as an expression. 5181 BlockScopeRAII Scope(Info); 5182 if (const Stmt *Init = IS->getInit()) { 5183 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5184 if (ESR != ESR_Succeeded) { 5185 if (ESR != ESR_Failed && !Scope.destroy()) 5186 return ESR_Failed; 5187 return ESR; 5188 } 5189 } 5190 bool Cond; 5191 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5192 return ESR_Failed; 5193 5194 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5195 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5196 if (ESR != ESR_Succeeded) { 5197 if (ESR != ESR_Failed && !Scope.destroy()) 5198 return ESR_Failed; 5199 return ESR; 5200 } 5201 } 5202 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5203 } 5204 5205 case Stmt::WhileStmtClass: { 5206 const WhileStmt *WS = cast<WhileStmt>(S); 5207 while (true) { 5208 BlockScopeRAII Scope(Info); 5209 bool Continue; 5210 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5211 Continue)) 5212 return ESR_Failed; 5213 if (!Continue) 5214 break; 5215 5216 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5217 if (ESR != ESR_Continue) { 5218 if (ESR != ESR_Failed && !Scope.destroy()) 5219 return ESR_Failed; 5220 return ESR; 5221 } 5222 if (!Scope.destroy()) 5223 return ESR_Failed; 5224 } 5225 return ESR_Succeeded; 5226 } 5227 5228 case Stmt::DoStmtClass: { 5229 const DoStmt *DS = cast<DoStmt>(S); 5230 bool Continue; 5231 do { 5232 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5233 if (ESR != ESR_Continue) 5234 return ESR; 5235 Case = nullptr; 5236 5237 if (DS->getCond()->isValueDependent()) { 5238 EvaluateDependentExpr(DS->getCond(), Info); 5239 // Bailout as we don't know whether to keep going or terminate the loop. 5240 return ESR_Failed; 5241 } 5242 FullExpressionRAII CondScope(Info); 5243 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5244 !CondScope.destroy()) 5245 return ESR_Failed; 5246 } while (Continue); 5247 return ESR_Succeeded; 5248 } 5249 5250 case Stmt::ForStmtClass: { 5251 const ForStmt *FS = cast<ForStmt>(S); 5252 BlockScopeRAII ForScope(Info); 5253 if (FS->getInit()) { 5254 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5255 if (ESR != ESR_Succeeded) { 5256 if (ESR != ESR_Failed && !ForScope.destroy()) 5257 return ESR_Failed; 5258 return ESR; 5259 } 5260 } 5261 while (true) { 5262 BlockScopeRAII IterScope(Info); 5263 bool Continue = true; 5264 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5265 FS->getCond(), Continue)) 5266 return ESR_Failed; 5267 if (!Continue) 5268 break; 5269 5270 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5271 if (ESR != ESR_Continue) { 5272 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5273 return ESR_Failed; 5274 return ESR; 5275 } 5276 5277 if (const auto *Inc = FS->getInc()) { 5278 if (Inc->isValueDependent()) { 5279 if (!EvaluateDependentExpr(Inc, Info)) 5280 return ESR_Failed; 5281 } else { 5282 FullExpressionRAII IncScope(Info); 5283 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5284 return ESR_Failed; 5285 } 5286 } 5287 5288 if (!IterScope.destroy()) 5289 return ESR_Failed; 5290 } 5291 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5292 } 5293 5294 case Stmt::CXXForRangeStmtClass: { 5295 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5296 BlockScopeRAII Scope(Info); 5297 5298 // Evaluate the init-statement if present. 5299 if (FS->getInit()) { 5300 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5301 if (ESR != ESR_Succeeded) { 5302 if (ESR != ESR_Failed && !Scope.destroy()) 5303 return ESR_Failed; 5304 return ESR; 5305 } 5306 } 5307 5308 // Initialize the __range variable. 5309 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5310 if (ESR != ESR_Succeeded) { 5311 if (ESR != ESR_Failed && !Scope.destroy()) 5312 return ESR_Failed; 5313 return ESR; 5314 } 5315 5316 // Create the __begin and __end iterators. 5317 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5318 if (ESR != ESR_Succeeded) { 5319 if (ESR != ESR_Failed && !Scope.destroy()) 5320 return ESR_Failed; 5321 return ESR; 5322 } 5323 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5324 if (ESR != ESR_Succeeded) { 5325 if (ESR != ESR_Failed && !Scope.destroy()) 5326 return ESR_Failed; 5327 return ESR; 5328 } 5329 5330 while (true) { 5331 // Condition: __begin != __end. 5332 { 5333 if (FS->getCond()->isValueDependent()) { 5334 EvaluateDependentExpr(FS->getCond(), Info); 5335 // We don't know whether to keep going or terminate the loop. 5336 return ESR_Failed; 5337 } 5338 bool Continue = true; 5339 FullExpressionRAII CondExpr(Info); 5340 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5341 return ESR_Failed; 5342 if (!Continue) 5343 break; 5344 } 5345 5346 // User's variable declaration, initialized by *__begin. 5347 BlockScopeRAII InnerScope(Info); 5348 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5349 if (ESR != ESR_Succeeded) { 5350 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5351 return ESR_Failed; 5352 return ESR; 5353 } 5354 5355 // Loop body. 5356 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5357 if (ESR != ESR_Continue) { 5358 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5359 return ESR_Failed; 5360 return ESR; 5361 } 5362 if (FS->getInc()->isValueDependent()) { 5363 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5364 return ESR_Failed; 5365 } else { 5366 // Increment: ++__begin 5367 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5368 return ESR_Failed; 5369 } 5370 5371 if (!InnerScope.destroy()) 5372 return ESR_Failed; 5373 } 5374 5375 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5376 } 5377 5378 case Stmt::SwitchStmtClass: 5379 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5380 5381 case Stmt::ContinueStmtClass: 5382 return ESR_Continue; 5383 5384 case Stmt::BreakStmtClass: 5385 return ESR_Break; 5386 5387 case Stmt::LabelStmtClass: 5388 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5389 5390 case Stmt::AttributedStmtClass: 5391 // As a general principle, C++11 attributes can be ignored without 5392 // any semantic impact. 5393 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5394 Case); 5395 5396 case Stmt::CaseStmtClass: 5397 case Stmt::DefaultStmtClass: 5398 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5399 case Stmt::CXXTryStmtClass: 5400 // Evaluate try blocks by evaluating all sub statements. 5401 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5402 } 5403 } 5404 5405 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5406 /// default constructor. If so, we'll fold it whether or not it's marked as 5407 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5408 /// so we need special handling. 5409 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5410 const CXXConstructorDecl *CD, 5411 bool IsValueInitialization) { 5412 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5413 return false; 5414 5415 // Value-initialization does not call a trivial default constructor, so such a 5416 // call is a core constant expression whether or not the constructor is 5417 // constexpr. 5418 if (!CD->isConstexpr() && !IsValueInitialization) { 5419 if (Info.getLangOpts().CPlusPlus11) { 5420 // FIXME: If DiagDecl is an implicitly-declared special member function, 5421 // we should be much more explicit about why it's not constexpr. 5422 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5423 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5424 Info.Note(CD->getLocation(), diag::note_declared_at); 5425 } else { 5426 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5427 } 5428 } 5429 return true; 5430 } 5431 5432 /// CheckConstexprFunction - Check that a function can be called in a constant 5433 /// expression. 5434 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5435 const FunctionDecl *Declaration, 5436 const FunctionDecl *Definition, 5437 const Stmt *Body) { 5438 // Potential constant expressions can contain calls to declared, but not yet 5439 // defined, constexpr functions. 5440 if (Info.checkingPotentialConstantExpression() && !Definition && 5441 Declaration->isConstexpr()) 5442 return false; 5443 5444 // Bail out if the function declaration itself is invalid. We will 5445 // have produced a relevant diagnostic while parsing it, so just 5446 // note the problematic sub-expression. 5447 if (Declaration->isInvalidDecl()) { 5448 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5449 return false; 5450 } 5451 5452 // DR1872: An instantiated virtual constexpr function can't be called in a 5453 // constant expression (prior to C++20). We can still constant-fold such a 5454 // call. 5455 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5456 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5457 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5458 5459 if (Definition && Definition->isInvalidDecl()) { 5460 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5461 return false; 5462 } 5463 5464 // Can we evaluate this function call? 5465 if (Definition && Definition->isConstexpr() && Body) 5466 return true; 5467 5468 if (Info.getLangOpts().CPlusPlus11) { 5469 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5470 5471 // If this function is not constexpr because it is an inherited 5472 // non-constexpr constructor, diagnose that directly. 5473 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5474 if (CD && CD->isInheritingConstructor()) { 5475 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5476 if (!Inherited->isConstexpr()) 5477 DiagDecl = CD = Inherited; 5478 } 5479 5480 // FIXME: If DiagDecl is an implicitly-declared special member function 5481 // or an inheriting constructor, we should be much more explicit about why 5482 // it's not constexpr. 5483 if (CD && CD->isInheritingConstructor()) 5484 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5485 << CD->getInheritedConstructor().getConstructor()->getParent(); 5486 else 5487 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5488 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5489 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5490 } else { 5491 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5492 } 5493 return false; 5494 } 5495 5496 namespace { 5497 struct CheckDynamicTypeHandler { 5498 AccessKinds AccessKind; 5499 typedef bool result_type; 5500 bool failed() { return false; } 5501 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5502 bool found(APSInt &Value, QualType SubobjType) { return true; } 5503 bool found(APFloat &Value, QualType SubobjType) { return true; } 5504 }; 5505 } // end anonymous namespace 5506 5507 /// Check that we can access the notional vptr of an object / determine its 5508 /// dynamic type. 5509 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5510 AccessKinds AK, bool Polymorphic) { 5511 if (This.Designator.Invalid) 5512 return false; 5513 5514 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5515 5516 if (!Obj) 5517 return false; 5518 5519 if (!Obj.Value) { 5520 // The object is not usable in constant expressions, so we can't inspect 5521 // its value to see if it's in-lifetime or what the active union members 5522 // are. We can still check for a one-past-the-end lvalue. 5523 if (This.Designator.isOnePastTheEnd() || 5524 This.Designator.isMostDerivedAnUnsizedArray()) { 5525 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5526 ? diag::note_constexpr_access_past_end 5527 : diag::note_constexpr_access_unsized_array) 5528 << AK; 5529 return false; 5530 } else if (Polymorphic) { 5531 // Conservatively refuse to perform a polymorphic operation if we would 5532 // not be able to read a notional 'vptr' value. 5533 APValue Val; 5534 This.moveInto(Val); 5535 QualType StarThisType = 5536 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5537 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5538 << AK << Val.getAsString(Info.Ctx, StarThisType); 5539 return false; 5540 } 5541 return true; 5542 } 5543 5544 CheckDynamicTypeHandler Handler{AK}; 5545 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5546 } 5547 5548 /// Check that the pointee of the 'this' pointer in a member function call is 5549 /// either within its lifetime or in its period of construction or destruction. 5550 static bool 5551 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5552 const LValue &This, 5553 const CXXMethodDecl *NamedMember) { 5554 return checkDynamicType( 5555 Info, E, This, 5556 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5557 } 5558 5559 struct DynamicType { 5560 /// The dynamic class type of the object. 5561 const CXXRecordDecl *Type; 5562 /// The corresponding path length in the lvalue. 5563 unsigned PathLength; 5564 }; 5565 5566 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5567 unsigned PathLength) { 5568 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5569 Designator.Entries.size() && "invalid path length"); 5570 return (PathLength == Designator.MostDerivedPathLength) 5571 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5572 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5573 } 5574 5575 /// Determine the dynamic type of an object. 5576 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5577 LValue &This, AccessKinds AK) { 5578 // If we don't have an lvalue denoting an object of class type, there is no 5579 // meaningful dynamic type. (We consider objects of non-class type to have no 5580 // dynamic type.) 5581 if (!checkDynamicType(Info, E, This, AK, true)) 5582 return None; 5583 5584 // Refuse to compute a dynamic type in the presence of virtual bases. This 5585 // shouldn't happen other than in constant-folding situations, since literal 5586 // types can't have virtual bases. 5587 // 5588 // Note that consumers of DynamicType assume that the type has no virtual 5589 // bases, and will need modifications if this restriction is relaxed. 5590 const CXXRecordDecl *Class = 5591 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5592 if (!Class || Class->getNumVBases()) { 5593 Info.FFDiag(E); 5594 return None; 5595 } 5596 5597 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5598 // binary search here instead. But the overwhelmingly common case is that 5599 // we're not in the middle of a constructor, so it probably doesn't matter 5600 // in practice. 5601 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5602 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5603 PathLength <= Path.size(); ++PathLength) { 5604 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5605 Path.slice(0, PathLength))) { 5606 case ConstructionPhase::Bases: 5607 case ConstructionPhase::DestroyingBases: 5608 // We're constructing or destroying a base class. This is not the dynamic 5609 // type. 5610 break; 5611 5612 case ConstructionPhase::None: 5613 case ConstructionPhase::AfterBases: 5614 case ConstructionPhase::AfterFields: 5615 case ConstructionPhase::Destroying: 5616 // We've finished constructing the base classes and not yet started 5617 // destroying them again, so this is the dynamic type. 5618 return DynamicType{getBaseClassType(This.Designator, PathLength), 5619 PathLength}; 5620 } 5621 } 5622 5623 // CWG issue 1517: we're constructing a base class of the object described by 5624 // 'This', so that object has not yet begun its period of construction and 5625 // any polymorphic operation on it results in undefined behavior. 5626 Info.FFDiag(E); 5627 return None; 5628 } 5629 5630 /// Perform virtual dispatch. 5631 static const CXXMethodDecl *HandleVirtualDispatch( 5632 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5633 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5634 Optional<DynamicType> DynType = ComputeDynamicType( 5635 Info, E, This, 5636 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5637 if (!DynType) 5638 return nullptr; 5639 5640 // Find the final overrider. It must be declared in one of the classes on the 5641 // path from the dynamic type to the static type. 5642 // FIXME: If we ever allow literal types to have virtual base classes, that 5643 // won't be true. 5644 const CXXMethodDecl *Callee = Found; 5645 unsigned PathLength = DynType->PathLength; 5646 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5647 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5648 const CXXMethodDecl *Overrider = 5649 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5650 if (Overrider) { 5651 Callee = Overrider; 5652 break; 5653 } 5654 } 5655 5656 // C++2a [class.abstract]p6: 5657 // the effect of making a virtual call to a pure virtual function [...] is 5658 // undefined 5659 if (Callee->isPure()) { 5660 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5661 Info.Note(Callee->getLocation(), diag::note_declared_at); 5662 return nullptr; 5663 } 5664 5665 // If necessary, walk the rest of the path to determine the sequence of 5666 // covariant adjustment steps to apply. 5667 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5668 Found->getReturnType())) { 5669 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5670 for (unsigned CovariantPathLength = PathLength + 1; 5671 CovariantPathLength != This.Designator.Entries.size(); 5672 ++CovariantPathLength) { 5673 const CXXRecordDecl *NextClass = 5674 getBaseClassType(This.Designator, CovariantPathLength); 5675 const CXXMethodDecl *Next = 5676 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5677 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5678 Next->getReturnType(), CovariantAdjustmentPath.back())) 5679 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5680 } 5681 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5682 CovariantAdjustmentPath.back())) 5683 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5684 } 5685 5686 // Perform 'this' adjustment. 5687 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5688 return nullptr; 5689 5690 return Callee; 5691 } 5692 5693 /// Perform the adjustment from a value returned by a virtual function to 5694 /// a value of the statically expected type, which may be a pointer or 5695 /// reference to a base class of the returned type. 5696 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5697 APValue &Result, 5698 ArrayRef<QualType> Path) { 5699 assert(Result.isLValue() && 5700 "unexpected kind of APValue for covariant return"); 5701 if (Result.isNullPointer()) 5702 return true; 5703 5704 LValue LVal; 5705 LVal.setFrom(Info.Ctx, Result); 5706 5707 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5708 for (unsigned I = 1; I != Path.size(); ++I) { 5709 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5710 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5711 if (OldClass != NewClass && 5712 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5713 return false; 5714 OldClass = NewClass; 5715 } 5716 5717 LVal.moveInto(Result); 5718 return true; 5719 } 5720 5721 /// Determine whether \p Base, which is known to be a direct base class of 5722 /// \p Derived, is a public base class. 5723 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5724 const CXXRecordDecl *Base) { 5725 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5726 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5727 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5728 return BaseSpec.getAccessSpecifier() == AS_public; 5729 } 5730 llvm_unreachable("Base is not a direct base of Derived"); 5731 } 5732 5733 /// Apply the given dynamic cast operation on the provided lvalue. 5734 /// 5735 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5736 /// to find a suitable target subobject. 5737 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5738 LValue &Ptr) { 5739 // We can't do anything with a non-symbolic pointer value. 5740 SubobjectDesignator &D = Ptr.Designator; 5741 if (D.Invalid) 5742 return false; 5743 5744 // C++ [expr.dynamic.cast]p6: 5745 // If v is a null pointer value, the result is a null pointer value. 5746 if (Ptr.isNullPointer() && !E->isGLValue()) 5747 return true; 5748 5749 // For all the other cases, we need the pointer to point to an object within 5750 // its lifetime / period of construction / destruction, and we need to know 5751 // its dynamic type. 5752 Optional<DynamicType> DynType = 5753 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5754 if (!DynType) 5755 return false; 5756 5757 // C++ [expr.dynamic.cast]p7: 5758 // If T is "pointer to cv void", then the result is a pointer to the most 5759 // derived object 5760 if (E->getType()->isVoidPointerType()) 5761 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5762 5763 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5764 assert(C && "dynamic_cast target is not void pointer nor class"); 5765 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5766 5767 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5768 // C++ [expr.dynamic.cast]p9: 5769 if (!E->isGLValue()) { 5770 // The value of a failed cast to pointer type is the null pointer value 5771 // of the required result type. 5772 Ptr.setNull(Info.Ctx, E->getType()); 5773 return true; 5774 } 5775 5776 // A failed cast to reference type throws [...] std::bad_cast. 5777 unsigned DiagKind; 5778 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5779 DynType->Type->isDerivedFrom(C))) 5780 DiagKind = 0; 5781 else if (!Paths || Paths->begin() == Paths->end()) 5782 DiagKind = 1; 5783 else if (Paths->isAmbiguous(CQT)) 5784 DiagKind = 2; 5785 else { 5786 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5787 DiagKind = 3; 5788 } 5789 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5790 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5791 << Info.Ctx.getRecordType(DynType->Type) 5792 << E->getType().getUnqualifiedType(); 5793 return false; 5794 }; 5795 5796 // Runtime check, phase 1: 5797 // Walk from the base subobject towards the derived object looking for the 5798 // target type. 5799 for (int PathLength = Ptr.Designator.Entries.size(); 5800 PathLength >= (int)DynType->PathLength; --PathLength) { 5801 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5802 if (declaresSameEntity(Class, C)) 5803 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5804 // We can only walk across public inheritance edges. 5805 if (PathLength > (int)DynType->PathLength && 5806 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5807 Class)) 5808 return RuntimeCheckFailed(nullptr); 5809 } 5810 5811 // Runtime check, phase 2: 5812 // Search the dynamic type for an unambiguous public base of type C. 5813 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5814 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5815 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5816 Paths.front().Access == AS_public) { 5817 // Downcast to the dynamic type... 5818 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5819 return false; 5820 // ... then upcast to the chosen base class subobject. 5821 for (CXXBasePathElement &Elem : Paths.front()) 5822 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5823 return false; 5824 return true; 5825 } 5826 5827 // Otherwise, the runtime check fails. 5828 return RuntimeCheckFailed(&Paths); 5829 } 5830 5831 namespace { 5832 struct StartLifetimeOfUnionMemberHandler { 5833 EvalInfo &Info; 5834 const Expr *LHSExpr; 5835 const FieldDecl *Field; 5836 bool DuringInit; 5837 bool Failed = false; 5838 static const AccessKinds AccessKind = AK_Assign; 5839 5840 typedef bool result_type; 5841 bool failed() { return Failed; } 5842 bool found(APValue &Subobj, QualType SubobjType) { 5843 // We are supposed to perform no initialization but begin the lifetime of 5844 // the object. We interpret that as meaning to do what default 5845 // initialization of the object would do if all constructors involved were 5846 // trivial: 5847 // * All base, non-variant member, and array element subobjects' lifetimes 5848 // begin 5849 // * No variant members' lifetimes begin 5850 // * All scalar subobjects whose lifetimes begin have indeterminate values 5851 assert(SubobjType->isUnionType()); 5852 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5853 // This union member is already active. If it's also in-lifetime, there's 5854 // nothing to do. 5855 if (Subobj.getUnionValue().hasValue()) 5856 return true; 5857 } else if (DuringInit) { 5858 // We're currently in the process of initializing a different union 5859 // member. If we carried on, that initialization would attempt to 5860 // store to an inactive union member, resulting in undefined behavior. 5861 Info.FFDiag(LHSExpr, 5862 diag::note_constexpr_union_member_change_during_init); 5863 return false; 5864 } 5865 APValue Result; 5866 Failed = !getDefaultInitValue(Field->getType(), Result); 5867 Subobj.setUnion(Field, Result); 5868 return true; 5869 } 5870 bool found(APSInt &Value, QualType SubobjType) { 5871 llvm_unreachable("wrong value kind for union object"); 5872 } 5873 bool found(APFloat &Value, QualType SubobjType) { 5874 llvm_unreachable("wrong value kind for union object"); 5875 } 5876 }; 5877 } // end anonymous namespace 5878 5879 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5880 5881 /// Handle a builtin simple-assignment or a call to a trivial assignment 5882 /// operator whose left-hand side might involve a union member access. If it 5883 /// does, implicitly start the lifetime of any accessed union elements per 5884 /// C++20 [class.union]5. 5885 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5886 const LValue &LHS) { 5887 if (LHS.InvalidBase || LHS.Designator.Invalid) 5888 return false; 5889 5890 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5891 // C++ [class.union]p5: 5892 // define the set S(E) of subexpressions of E as follows: 5893 unsigned PathLength = LHS.Designator.Entries.size(); 5894 for (const Expr *E = LHSExpr; E != nullptr;) { 5895 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5896 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5897 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5898 // Note that we can't implicitly start the lifetime of a reference, 5899 // so we don't need to proceed any further if we reach one. 5900 if (!FD || FD->getType()->isReferenceType()) 5901 break; 5902 5903 // ... and also contains A.B if B names a union member ... 5904 if (FD->getParent()->isUnion()) { 5905 // ... of a non-class, non-array type, or of a class type with a 5906 // trivial default constructor that is not deleted, or an array of 5907 // such types. 5908 auto *RD = 5909 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5910 if (!RD || RD->hasTrivialDefaultConstructor()) 5911 UnionPathLengths.push_back({PathLength - 1, FD}); 5912 } 5913 5914 E = ME->getBase(); 5915 --PathLength; 5916 assert(declaresSameEntity(FD, 5917 LHS.Designator.Entries[PathLength] 5918 .getAsBaseOrMember().getPointer())); 5919 5920 // -- If E is of the form A[B] and is interpreted as a built-in array 5921 // subscripting operator, S(E) is [S(the array operand, if any)]. 5922 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5923 // Step over an ArrayToPointerDecay implicit cast. 5924 auto *Base = ASE->getBase()->IgnoreImplicit(); 5925 if (!Base->getType()->isArrayType()) 5926 break; 5927 5928 E = Base; 5929 --PathLength; 5930 5931 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5932 // Step over a derived-to-base conversion. 5933 E = ICE->getSubExpr(); 5934 if (ICE->getCastKind() == CK_NoOp) 5935 continue; 5936 if (ICE->getCastKind() != CK_DerivedToBase && 5937 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5938 break; 5939 // Walk path backwards as we walk up from the base to the derived class. 5940 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5941 --PathLength; 5942 (void)Elt; 5943 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5944 LHS.Designator.Entries[PathLength] 5945 .getAsBaseOrMember().getPointer())); 5946 } 5947 5948 // -- Otherwise, S(E) is empty. 5949 } else { 5950 break; 5951 } 5952 } 5953 5954 // Common case: no unions' lifetimes are started. 5955 if (UnionPathLengths.empty()) 5956 return true; 5957 5958 // if modification of X [would access an inactive union member], an object 5959 // of the type of X is implicitly created 5960 CompleteObject Obj = 5961 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5962 if (!Obj) 5963 return false; 5964 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5965 llvm::reverse(UnionPathLengths)) { 5966 // Form a designator for the union object. 5967 SubobjectDesignator D = LHS.Designator; 5968 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5969 5970 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5971 ConstructionPhase::AfterBases; 5972 StartLifetimeOfUnionMemberHandler StartLifetime{ 5973 Info, LHSExpr, LengthAndField.second, DuringInit}; 5974 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5975 return false; 5976 } 5977 5978 return true; 5979 } 5980 5981 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5982 CallRef Call, EvalInfo &Info, 5983 bool NonNull = false) { 5984 LValue LV; 5985 // Create the parameter slot and register its destruction. For a vararg 5986 // argument, create a temporary. 5987 // FIXME: For calling conventions that destroy parameters in the callee, 5988 // should we consider performing destruction when the function returns 5989 // instead? 5990 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 5991 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 5992 ScopeKind::Call, LV); 5993 if (!EvaluateInPlace(V, Info, LV, Arg)) 5994 return false; 5995 5996 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 5997 // undefined behavior, so is non-constant. 5998 if (NonNull && V.isLValue() && V.isNullPointer()) { 5999 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6000 return false; 6001 } 6002 6003 return true; 6004 } 6005 6006 /// Evaluate the arguments to a function call. 6007 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6008 EvalInfo &Info, const FunctionDecl *Callee, 6009 bool RightToLeft = false) { 6010 bool Success = true; 6011 llvm::SmallBitVector ForbiddenNullArgs; 6012 if (Callee->hasAttr<NonNullAttr>()) { 6013 ForbiddenNullArgs.resize(Args.size()); 6014 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6015 if (!Attr->args_size()) { 6016 ForbiddenNullArgs.set(); 6017 break; 6018 } else 6019 for (auto Idx : Attr->args()) { 6020 unsigned ASTIdx = Idx.getASTIndex(); 6021 if (ASTIdx >= Args.size()) 6022 continue; 6023 ForbiddenNullArgs[ASTIdx] = 1; 6024 } 6025 } 6026 } 6027 for (unsigned I = 0; I < Args.size(); I++) { 6028 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6029 const ParmVarDecl *PVD = 6030 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6031 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6032 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6033 // If we're checking for a potential constant expression, evaluate all 6034 // initializers even if some of them fail. 6035 if (!Info.noteFailure()) 6036 return false; 6037 Success = false; 6038 } 6039 } 6040 return Success; 6041 } 6042 6043 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6044 /// constructor or assignment operator. 6045 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6046 const Expr *E, APValue &Result, 6047 bool CopyObjectRepresentation) { 6048 // Find the reference argument. 6049 CallStackFrame *Frame = Info.CurrentCall; 6050 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6051 if (!RefValue) { 6052 Info.FFDiag(E); 6053 return false; 6054 } 6055 6056 // Copy out the contents of the RHS object. 6057 LValue RefLValue; 6058 RefLValue.setFrom(Info.Ctx, *RefValue); 6059 return handleLValueToRValueConversion( 6060 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6061 CopyObjectRepresentation); 6062 } 6063 6064 /// Evaluate a function call. 6065 static bool HandleFunctionCall(SourceLocation CallLoc, 6066 const FunctionDecl *Callee, const LValue *This, 6067 ArrayRef<const Expr *> Args, CallRef Call, 6068 const Stmt *Body, EvalInfo &Info, 6069 APValue &Result, const LValue *ResultSlot) { 6070 if (!Info.CheckCallLimit(CallLoc)) 6071 return false; 6072 6073 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6074 6075 // For a trivial copy or move assignment, perform an APValue copy. This is 6076 // essential for unions, where the operations performed by the assignment 6077 // operator cannot be represented as statements. 6078 // 6079 // Skip this for non-union classes with no fields; in that case, the defaulted 6080 // copy/move does not actually read the object. 6081 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6082 if (MD && MD->isDefaulted() && 6083 (MD->getParent()->isUnion() || 6084 (MD->isTrivial() && 6085 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6086 assert(This && 6087 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6088 APValue RHSValue; 6089 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6090 MD->getParent()->isUnion())) 6091 return false; 6092 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6093 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6094 return false; 6095 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6096 RHSValue)) 6097 return false; 6098 This->moveInto(Result); 6099 return true; 6100 } else if (MD && isLambdaCallOperator(MD)) { 6101 // We're in a lambda; determine the lambda capture field maps unless we're 6102 // just constexpr checking a lambda's call operator. constexpr checking is 6103 // done before the captures have been added to the closure object (unless 6104 // we're inferring constexpr-ness), so we don't have access to them in this 6105 // case. But since we don't need the captures to constexpr check, we can 6106 // just ignore them. 6107 if (!Info.checkingPotentialConstantExpression()) 6108 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6109 Frame.LambdaThisCaptureField); 6110 } 6111 6112 StmtResult Ret = {Result, ResultSlot}; 6113 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6114 if (ESR == ESR_Succeeded) { 6115 if (Callee->getReturnType()->isVoidType()) 6116 return true; 6117 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6118 } 6119 return ESR == ESR_Returned; 6120 } 6121 6122 /// Evaluate a constructor call. 6123 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6124 CallRef Call, 6125 const CXXConstructorDecl *Definition, 6126 EvalInfo &Info, APValue &Result) { 6127 SourceLocation CallLoc = E->getExprLoc(); 6128 if (!Info.CheckCallLimit(CallLoc)) 6129 return false; 6130 6131 const CXXRecordDecl *RD = Definition->getParent(); 6132 if (RD->getNumVBases()) { 6133 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6134 return false; 6135 } 6136 6137 EvalInfo::EvaluatingConstructorRAII EvalObj( 6138 Info, 6139 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6140 RD->getNumBases()); 6141 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6142 6143 // FIXME: Creating an APValue just to hold a nonexistent return value is 6144 // wasteful. 6145 APValue RetVal; 6146 StmtResult Ret = {RetVal, nullptr}; 6147 6148 // If it's a delegating constructor, delegate. 6149 if (Definition->isDelegatingConstructor()) { 6150 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6151 if ((*I)->getInit()->isValueDependent()) { 6152 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6153 return false; 6154 } else { 6155 FullExpressionRAII InitScope(Info); 6156 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6157 !InitScope.destroy()) 6158 return false; 6159 } 6160 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6161 } 6162 6163 // For a trivial copy or move constructor, perform an APValue copy. This is 6164 // essential for unions (or classes with anonymous union members), where the 6165 // operations performed by the constructor cannot be represented by 6166 // ctor-initializers. 6167 // 6168 // Skip this for empty non-union classes; we should not perform an 6169 // lvalue-to-rvalue conversion on them because their copy constructor does not 6170 // actually read them. 6171 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6172 (Definition->getParent()->isUnion() || 6173 (Definition->isTrivial() && 6174 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6175 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6176 Definition->getParent()->isUnion()); 6177 } 6178 6179 // Reserve space for the struct members. 6180 if (!Result.hasValue()) { 6181 if (!RD->isUnion()) 6182 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6183 std::distance(RD->field_begin(), RD->field_end())); 6184 else 6185 // A union starts with no active member. 6186 Result = APValue((const FieldDecl*)nullptr); 6187 } 6188 6189 if (RD->isInvalidDecl()) return false; 6190 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6191 6192 // A scope for temporaries lifetime-extended by reference members. 6193 BlockScopeRAII LifetimeExtendedScope(Info); 6194 6195 bool Success = true; 6196 unsigned BasesSeen = 0; 6197 #ifndef NDEBUG 6198 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6199 #endif 6200 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6201 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6202 // We might be initializing the same field again if this is an indirect 6203 // field initialization. 6204 if (FieldIt == RD->field_end() || 6205 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6206 assert(Indirect && "fields out of order?"); 6207 return; 6208 } 6209 6210 // Default-initialize any fields with no explicit initializer. 6211 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6212 assert(FieldIt != RD->field_end() && "missing field?"); 6213 if (!FieldIt->isUnnamedBitfield()) 6214 Success &= getDefaultInitValue( 6215 FieldIt->getType(), 6216 Result.getStructField(FieldIt->getFieldIndex())); 6217 } 6218 ++FieldIt; 6219 }; 6220 for (const auto *I : Definition->inits()) { 6221 LValue Subobject = This; 6222 LValue SubobjectParent = This; 6223 APValue *Value = &Result; 6224 6225 // Determine the subobject to initialize. 6226 FieldDecl *FD = nullptr; 6227 if (I->isBaseInitializer()) { 6228 QualType BaseType(I->getBaseClass(), 0); 6229 #ifndef NDEBUG 6230 // Non-virtual base classes are initialized in the order in the class 6231 // definition. We have already checked for virtual base classes. 6232 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6233 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6234 "base class initializers not in expected order"); 6235 ++BaseIt; 6236 #endif 6237 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6238 BaseType->getAsCXXRecordDecl(), &Layout)) 6239 return false; 6240 Value = &Result.getStructBase(BasesSeen++); 6241 } else if ((FD = I->getMember())) { 6242 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6243 return false; 6244 if (RD->isUnion()) { 6245 Result = APValue(FD); 6246 Value = &Result.getUnionValue(); 6247 } else { 6248 SkipToField(FD, false); 6249 Value = &Result.getStructField(FD->getFieldIndex()); 6250 } 6251 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6252 // Walk the indirect field decl's chain to find the object to initialize, 6253 // and make sure we've initialized every step along it. 6254 auto IndirectFieldChain = IFD->chain(); 6255 for (auto *C : IndirectFieldChain) { 6256 FD = cast<FieldDecl>(C); 6257 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6258 // Switch the union field if it differs. This happens if we had 6259 // preceding zero-initialization, and we're now initializing a union 6260 // subobject other than the first. 6261 // FIXME: In this case, the values of the other subobjects are 6262 // specified, since zero-initialization sets all padding bits to zero. 6263 if (!Value->hasValue() || 6264 (Value->isUnion() && Value->getUnionField() != FD)) { 6265 if (CD->isUnion()) 6266 *Value = APValue(FD); 6267 else 6268 // FIXME: This immediately starts the lifetime of all members of 6269 // an anonymous struct. It would be preferable to strictly start 6270 // member lifetime in initialization order. 6271 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6272 } 6273 // Store Subobject as its parent before updating it for the last element 6274 // in the chain. 6275 if (C == IndirectFieldChain.back()) 6276 SubobjectParent = Subobject; 6277 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6278 return false; 6279 if (CD->isUnion()) 6280 Value = &Value->getUnionValue(); 6281 else { 6282 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6283 SkipToField(FD, true); 6284 Value = &Value->getStructField(FD->getFieldIndex()); 6285 } 6286 } 6287 } else { 6288 llvm_unreachable("unknown base initializer kind"); 6289 } 6290 6291 // Need to override This for implicit field initializers as in this case 6292 // This refers to innermost anonymous struct/union containing initializer, 6293 // not to currently constructed class. 6294 const Expr *Init = I->getInit(); 6295 if (Init->isValueDependent()) { 6296 if (!EvaluateDependentExpr(Init, Info)) 6297 return false; 6298 } else { 6299 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6300 isa<CXXDefaultInitExpr>(Init)); 6301 FullExpressionRAII InitScope(Info); 6302 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6303 (FD && FD->isBitField() && 6304 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6305 // If we're checking for a potential constant expression, evaluate all 6306 // initializers even if some of them fail. 6307 if (!Info.noteFailure()) 6308 return false; 6309 Success = false; 6310 } 6311 } 6312 6313 // This is the point at which the dynamic type of the object becomes this 6314 // class type. 6315 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6316 EvalObj.finishedConstructingBases(); 6317 } 6318 6319 // Default-initialize any remaining fields. 6320 if (!RD->isUnion()) { 6321 for (; FieldIt != RD->field_end(); ++FieldIt) { 6322 if (!FieldIt->isUnnamedBitfield()) 6323 Success &= getDefaultInitValue( 6324 FieldIt->getType(), 6325 Result.getStructField(FieldIt->getFieldIndex())); 6326 } 6327 } 6328 6329 EvalObj.finishedConstructingFields(); 6330 6331 return Success && 6332 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6333 LifetimeExtendedScope.destroy(); 6334 } 6335 6336 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6337 ArrayRef<const Expr*> Args, 6338 const CXXConstructorDecl *Definition, 6339 EvalInfo &Info, APValue &Result) { 6340 CallScopeRAII CallScope(Info); 6341 CallRef Call = Info.CurrentCall->createCall(Definition); 6342 if (!EvaluateArgs(Args, Call, Info, Definition)) 6343 return false; 6344 6345 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6346 CallScope.destroy(); 6347 } 6348 6349 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6350 const LValue &This, APValue &Value, 6351 QualType T) { 6352 // Objects can only be destroyed while they're within their lifetimes. 6353 // FIXME: We have no representation for whether an object of type nullptr_t 6354 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6355 // as indeterminate instead? 6356 if (Value.isAbsent() && !T->isNullPtrType()) { 6357 APValue Printable; 6358 This.moveInto(Printable); 6359 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6360 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6361 return false; 6362 } 6363 6364 // Invent an expression for location purposes. 6365 // FIXME: We shouldn't need to do this. 6366 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6367 6368 // For arrays, destroy elements right-to-left. 6369 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6370 uint64_t Size = CAT->getSize().getZExtValue(); 6371 QualType ElemT = CAT->getElementType(); 6372 6373 LValue ElemLV = This; 6374 ElemLV.addArray(Info, &LocE, CAT); 6375 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6376 return false; 6377 6378 // Ensure that we have actual array elements available to destroy; the 6379 // destructors might mutate the value, so we can't run them on the array 6380 // filler. 6381 if (Size && Size > Value.getArrayInitializedElts()) 6382 expandArray(Value, Value.getArraySize() - 1); 6383 6384 for (; Size != 0; --Size) { 6385 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6386 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6387 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6388 return false; 6389 } 6390 6391 // End the lifetime of this array now. 6392 Value = APValue(); 6393 return true; 6394 } 6395 6396 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6397 if (!RD) { 6398 if (T.isDestructedType()) { 6399 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6400 return false; 6401 } 6402 6403 Value = APValue(); 6404 return true; 6405 } 6406 6407 if (RD->getNumVBases()) { 6408 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6409 return false; 6410 } 6411 6412 const CXXDestructorDecl *DD = RD->getDestructor(); 6413 if (!DD && !RD->hasTrivialDestructor()) { 6414 Info.FFDiag(CallLoc); 6415 return false; 6416 } 6417 6418 if (!DD || DD->isTrivial() || 6419 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6420 // A trivial destructor just ends the lifetime of the object. Check for 6421 // this case before checking for a body, because we might not bother 6422 // building a body for a trivial destructor. Note that it doesn't matter 6423 // whether the destructor is constexpr in this case; all trivial 6424 // destructors are constexpr. 6425 // 6426 // If an anonymous union would be destroyed, some enclosing destructor must 6427 // have been explicitly defined, and the anonymous union destruction should 6428 // have no effect. 6429 Value = APValue(); 6430 return true; 6431 } 6432 6433 if (!Info.CheckCallLimit(CallLoc)) 6434 return false; 6435 6436 const FunctionDecl *Definition = nullptr; 6437 const Stmt *Body = DD->getBody(Definition); 6438 6439 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6440 return false; 6441 6442 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6443 6444 // We're now in the period of destruction of this object. 6445 unsigned BasesLeft = RD->getNumBases(); 6446 EvalInfo::EvaluatingDestructorRAII EvalObj( 6447 Info, 6448 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6449 if (!EvalObj.DidInsert) { 6450 // C++2a [class.dtor]p19: 6451 // the behavior is undefined if the destructor is invoked for an object 6452 // whose lifetime has ended 6453 // (Note that formally the lifetime ends when the period of destruction 6454 // begins, even though certain uses of the object remain valid until the 6455 // period of destruction ends.) 6456 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6457 return false; 6458 } 6459 6460 // FIXME: Creating an APValue just to hold a nonexistent return value is 6461 // wasteful. 6462 APValue RetVal; 6463 StmtResult Ret = {RetVal, nullptr}; 6464 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6465 return false; 6466 6467 // A union destructor does not implicitly destroy its members. 6468 if (RD->isUnion()) 6469 return true; 6470 6471 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6472 6473 // We don't have a good way to iterate fields in reverse, so collect all the 6474 // fields first and then walk them backwards. 6475 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6476 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6477 if (FD->isUnnamedBitfield()) 6478 continue; 6479 6480 LValue Subobject = This; 6481 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6482 return false; 6483 6484 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6485 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6486 FD->getType())) 6487 return false; 6488 } 6489 6490 if (BasesLeft != 0) 6491 EvalObj.startedDestroyingBases(); 6492 6493 // Destroy base classes in reverse order. 6494 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6495 --BasesLeft; 6496 6497 QualType BaseType = Base.getType(); 6498 LValue Subobject = This; 6499 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6500 BaseType->getAsCXXRecordDecl(), &Layout)) 6501 return false; 6502 6503 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6504 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6505 BaseType)) 6506 return false; 6507 } 6508 assert(BasesLeft == 0 && "NumBases was wrong?"); 6509 6510 // The period of destruction ends now. The object is gone. 6511 Value = APValue(); 6512 return true; 6513 } 6514 6515 namespace { 6516 struct DestroyObjectHandler { 6517 EvalInfo &Info; 6518 const Expr *E; 6519 const LValue &This; 6520 const AccessKinds AccessKind; 6521 6522 typedef bool result_type; 6523 bool failed() { return false; } 6524 bool found(APValue &Subobj, QualType SubobjType) { 6525 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6526 SubobjType); 6527 } 6528 bool found(APSInt &Value, QualType SubobjType) { 6529 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6530 return false; 6531 } 6532 bool found(APFloat &Value, QualType SubobjType) { 6533 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6534 return false; 6535 } 6536 }; 6537 } 6538 6539 /// Perform a destructor or pseudo-destructor call on the given object, which 6540 /// might in general not be a complete object. 6541 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6542 const LValue &This, QualType ThisType) { 6543 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6544 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6545 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6546 } 6547 6548 /// Destroy and end the lifetime of the given complete object. 6549 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6550 APValue::LValueBase LVBase, APValue &Value, 6551 QualType T) { 6552 // If we've had an unmodeled side-effect, we can't rely on mutable state 6553 // (such as the object we're about to destroy) being correct. 6554 if (Info.EvalStatus.HasSideEffects) 6555 return false; 6556 6557 LValue LV; 6558 LV.set({LVBase}); 6559 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6560 } 6561 6562 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6563 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6564 LValue &Result) { 6565 if (Info.checkingPotentialConstantExpression() || 6566 Info.SpeculativeEvaluationDepth) 6567 return false; 6568 6569 // This is permitted only within a call to std::allocator<T>::allocate. 6570 auto Caller = Info.getStdAllocatorCaller("allocate"); 6571 if (!Caller) { 6572 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6573 ? diag::note_constexpr_new_untyped 6574 : diag::note_constexpr_new); 6575 return false; 6576 } 6577 6578 QualType ElemType = Caller.ElemType; 6579 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6580 Info.FFDiag(E->getExprLoc(), 6581 diag::note_constexpr_new_not_complete_object_type) 6582 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6583 return false; 6584 } 6585 6586 APSInt ByteSize; 6587 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6588 return false; 6589 bool IsNothrow = false; 6590 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6591 EvaluateIgnoredValue(Info, E->getArg(I)); 6592 IsNothrow |= E->getType()->isNothrowT(); 6593 } 6594 6595 CharUnits ElemSize; 6596 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6597 return false; 6598 APInt Size, Remainder; 6599 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6600 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6601 if (Remainder != 0) { 6602 // This likely indicates a bug in the implementation of 'std::allocator'. 6603 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6604 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6605 return false; 6606 } 6607 6608 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6609 if (IsNothrow) { 6610 Result.setNull(Info.Ctx, E->getType()); 6611 return true; 6612 } 6613 6614 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6615 return false; 6616 } 6617 6618 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6619 ArrayType::Normal, 0); 6620 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6621 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6622 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6623 return true; 6624 } 6625 6626 static bool hasVirtualDestructor(QualType T) { 6627 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6628 if (CXXDestructorDecl *DD = RD->getDestructor()) 6629 return DD->isVirtual(); 6630 return false; 6631 } 6632 6633 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6634 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6635 if (CXXDestructorDecl *DD = RD->getDestructor()) 6636 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6637 return nullptr; 6638 } 6639 6640 /// Check that the given object is a suitable pointer to a heap allocation that 6641 /// still exists and is of the right kind for the purpose of a deletion. 6642 /// 6643 /// On success, returns the heap allocation to deallocate. On failure, produces 6644 /// a diagnostic and returns None. 6645 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6646 const LValue &Pointer, 6647 DynAlloc::Kind DeallocKind) { 6648 auto PointerAsString = [&] { 6649 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6650 }; 6651 6652 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6653 if (!DA) { 6654 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6655 << PointerAsString(); 6656 if (Pointer.Base) 6657 NoteLValueLocation(Info, Pointer.Base); 6658 return None; 6659 } 6660 6661 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6662 if (!Alloc) { 6663 Info.FFDiag(E, diag::note_constexpr_double_delete); 6664 return None; 6665 } 6666 6667 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6668 if (DeallocKind != (*Alloc)->getKind()) { 6669 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6670 << DeallocKind << (*Alloc)->getKind() << AllocType; 6671 NoteLValueLocation(Info, Pointer.Base); 6672 return None; 6673 } 6674 6675 bool Subobject = false; 6676 if (DeallocKind == DynAlloc::New) { 6677 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6678 Pointer.Designator.isOnePastTheEnd(); 6679 } else { 6680 Subobject = Pointer.Designator.Entries.size() != 1 || 6681 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6682 } 6683 if (Subobject) { 6684 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6685 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6686 return None; 6687 } 6688 6689 return Alloc; 6690 } 6691 6692 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6693 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6694 if (Info.checkingPotentialConstantExpression() || 6695 Info.SpeculativeEvaluationDepth) 6696 return false; 6697 6698 // This is permitted only within a call to std::allocator<T>::deallocate. 6699 if (!Info.getStdAllocatorCaller("deallocate")) { 6700 Info.FFDiag(E->getExprLoc()); 6701 return true; 6702 } 6703 6704 LValue Pointer; 6705 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6706 return false; 6707 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6708 EvaluateIgnoredValue(Info, E->getArg(I)); 6709 6710 if (Pointer.Designator.Invalid) 6711 return false; 6712 6713 // Deleting a null pointer has no effect. 6714 if (Pointer.isNullPointer()) 6715 return true; 6716 6717 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6718 return false; 6719 6720 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6721 return true; 6722 } 6723 6724 //===----------------------------------------------------------------------===// 6725 // Generic Evaluation 6726 //===----------------------------------------------------------------------===// 6727 namespace { 6728 6729 class BitCastBuffer { 6730 // FIXME: We're going to need bit-level granularity when we support 6731 // bit-fields. 6732 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6733 // we don't support a host or target where that is the case. Still, we should 6734 // use a more generic type in case we ever do. 6735 SmallVector<Optional<unsigned char>, 32> Bytes; 6736 6737 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6738 "Need at least 8 bit unsigned char"); 6739 6740 bool TargetIsLittleEndian; 6741 6742 public: 6743 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6744 : Bytes(Width.getQuantity()), 6745 TargetIsLittleEndian(TargetIsLittleEndian) {} 6746 6747 LLVM_NODISCARD 6748 bool readObject(CharUnits Offset, CharUnits Width, 6749 SmallVectorImpl<unsigned char> &Output) const { 6750 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6751 // If a byte of an integer is uninitialized, then the whole integer is 6752 // uninitalized. 6753 if (!Bytes[I.getQuantity()]) 6754 return false; 6755 Output.push_back(*Bytes[I.getQuantity()]); 6756 } 6757 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6758 std::reverse(Output.begin(), Output.end()); 6759 return true; 6760 } 6761 6762 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6763 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6764 std::reverse(Input.begin(), Input.end()); 6765 6766 size_t Index = 0; 6767 for (unsigned char Byte : Input) { 6768 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6769 Bytes[Offset.getQuantity() + Index] = Byte; 6770 ++Index; 6771 } 6772 } 6773 6774 size_t size() { return Bytes.size(); } 6775 }; 6776 6777 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6778 /// target would represent the value at runtime. 6779 class APValueToBufferConverter { 6780 EvalInfo &Info; 6781 BitCastBuffer Buffer; 6782 const CastExpr *BCE; 6783 6784 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6785 const CastExpr *BCE) 6786 : Info(Info), 6787 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6788 BCE(BCE) {} 6789 6790 bool visit(const APValue &Val, QualType Ty) { 6791 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6792 } 6793 6794 // Write out Val with type Ty into Buffer starting at Offset. 6795 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6796 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6797 6798 // As a special case, nullptr_t has an indeterminate value. 6799 if (Ty->isNullPtrType()) 6800 return true; 6801 6802 // Dig through Src to find the byte at SrcOffset. 6803 switch (Val.getKind()) { 6804 case APValue::Indeterminate: 6805 case APValue::None: 6806 return true; 6807 6808 case APValue::Int: 6809 return visitInt(Val.getInt(), Ty, Offset); 6810 case APValue::Float: 6811 return visitFloat(Val.getFloat(), Ty, Offset); 6812 case APValue::Array: 6813 return visitArray(Val, Ty, Offset); 6814 case APValue::Struct: 6815 return visitRecord(Val, Ty, Offset); 6816 6817 case APValue::ComplexInt: 6818 case APValue::ComplexFloat: 6819 case APValue::Vector: 6820 case APValue::FixedPoint: 6821 // FIXME: We should support these. 6822 6823 case APValue::Union: 6824 case APValue::MemberPointer: 6825 case APValue::AddrLabelDiff: { 6826 Info.FFDiag(BCE->getBeginLoc(), 6827 diag::note_constexpr_bit_cast_unsupported_type) 6828 << Ty; 6829 return false; 6830 } 6831 6832 case APValue::LValue: 6833 llvm_unreachable("LValue subobject in bit_cast?"); 6834 } 6835 llvm_unreachable("Unhandled APValue::ValueKind"); 6836 } 6837 6838 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6839 const RecordDecl *RD = Ty->getAsRecordDecl(); 6840 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6841 6842 // Visit the base classes. 6843 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6844 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6845 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6846 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6847 6848 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6849 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6850 return false; 6851 } 6852 } 6853 6854 // Visit the fields. 6855 unsigned FieldIdx = 0; 6856 for (FieldDecl *FD : RD->fields()) { 6857 if (FD->isBitField()) { 6858 Info.FFDiag(BCE->getBeginLoc(), 6859 diag::note_constexpr_bit_cast_unsupported_bitfield); 6860 return false; 6861 } 6862 6863 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6864 6865 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6866 "only bit-fields can have sub-char alignment"); 6867 CharUnits FieldOffset = 6868 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6869 QualType FieldTy = FD->getType(); 6870 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6871 return false; 6872 ++FieldIdx; 6873 } 6874 6875 return true; 6876 } 6877 6878 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6879 const auto *CAT = 6880 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6881 if (!CAT) 6882 return false; 6883 6884 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6885 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6886 unsigned ArraySize = Val.getArraySize(); 6887 // First, initialize the initialized elements. 6888 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6889 const APValue &SubObj = Val.getArrayInitializedElt(I); 6890 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6891 return false; 6892 } 6893 6894 // Next, initialize the rest of the array using the filler. 6895 if (Val.hasArrayFiller()) { 6896 const APValue &Filler = Val.getArrayFiller(); 6897 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6898 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6899 return false; 6900 } 6901 } 6902 6903 return true; 6904 } 6905 6906 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6907 APSInt AdjustedVal = Val; 6908 unsigned Width = AdjustedVal.getBitWidth(); 6909 if (Ty->isBooleanType()) { 6910 Width = Info.Ctx.getTypeSize(Ty); 6911 AdjustedVal = AdjustedVal.extend(Width); 6912 } 6913 6914 SmallVector<unsigned char, 8> Bytes(Width / 8); 6915 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6916 Buffer.writeObject(Offset, Bytes); 6917 return true; 6918 } 6919 6920 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6921 APSInt AsInt(Val.bitcastToAPInt()); 6922 return visitInt(AsInt, Ty, Offset); 6923 } 6924 6925 public: 6926 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6927 const CastExpr *BCE) { 6928 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6929 APValueToBufferConverter Converter(Info, DstSize, BCE); 6930 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6931 return None; 6932 return Converter.Buffer; 6933 } 6934 }; 6935 6936 /// Write an BitCastBuffer into an APValue. 6937 class BufferToAPValueConverter { 6938 EvalInfo &Info; 6939 const BitCastBuffer &Buffer; 6940 const CastExpr *BCE; 6941 6942 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6943 const CastExpr *BCE) 6944 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6945 6946 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6947 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6948 // Ideally this will be unreachable. 6949 llvm::NoneType unsupportedType(QualType Ty) { 6950 Info.FFDiag(BCE->getBeginLoc(), 6951 diag::note_constexpr_bit_cast_unsupported_type) 6952 << Ty; 6953 return None; 6954 } 6955 6956 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6957 Info.FFDiag(BCE->getBeginLoc(), 6958 diag::note_constexpr_bit_cast_unrepresentable_value) 6959 << Ty << Val.toString(/*Radix=*/10); 6960 return None; 6961 } 6962 6963 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6964 const EnumType *EnumSugar = nullptr) { 6965 if (T->isNullPtrType()) { 6966 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6967 return APValue((Expr *)nullptr, 6968 /*Offset=*/CharUnits::fromQuantity(NullValue), 6969 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6970 } 6971 6972 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6973 6974 // Work around floating point types that contain unused padding bytes. This 6975 // is really just `long double` on x86, which is the only fundamental type 6976 // with padding bytes. 6977 if (T->isRealFloatingType()) { 6978 const llvm::fltSemantics &Semantics = 6979 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6980 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6981 assert(NumBits % 8 == 0); 6982 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6983 if (NumBytes != SizeOf) 6984 SizeOf = NumBytes; 6985 } 6986 6987 SmallVector<uint8_t, 8> Bytes; 6988 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6989 // If this is std::byte or unsigned char, then its okay to store an 6990 // indeterminate value. 6991 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6992 bool IsUChar = 6993 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6994 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6995 if (!IsStdByte && !IsUChar) { 6996 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6997 Info.FFDiag(BCE->getExprLoc(), 6998 diag::note_constexpr_bit_cast_indet_dest) 6999 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7000 return None; 7001 } 7002 7003 return APValue::IndeterminateValue(); 7004 } 7005 7006 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7007 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7008 7009 if (T->isIntegralOrEnumerationType()) { 7010 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7011 7012 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7013 if (IntWidth != Val.getBitWidth()) { 7014 APSInt Truncated = Val.trunc(IntWidth); 7015 if (Truncated.extend(Val.getBitWidth()) != Val) 7016 return unrepresentableValue(QualType(T, 0), Val); 7017 Val = Truncated; 7018 } 7019 7020 return APValue(Val); 7021 } 7022 7023 if (T->isRealFloatingType()) { 7024 const llvm::fltSemantics &Semantics = 7025 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7026 return APValue(APFloat(Semantics, Val)); 7027 } 7028 7029 return unsupportedType(QualType(T, 0)); 7030 } 7031 7032 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7033 const RecordDecl *RD = RTy->getAsRecordDecl(); 7034 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7035 7036 unsigned NumBases = 0; 7037 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7038 NumBases = CXXRD->getNumBases(); 7039 7040 APValue ResultVal(APValue::UninitStruct(), NumBases, 7041 std::distance(RD->field_begin(), RD->field_end())); 7042 7043 // Visit the base classes. 7044 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7045 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7046 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7047 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7048 if (BaseDecl->isEmpty() || 7049 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7050 continue; 7051 7052 Optional<APValue> SubObj = visitType( 7053 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7054 if (!SubObj) 7055 return None; 7056 ResultVal.getStructBase(I) = *SubObj; 7057 } 7058 } 7059 7060 // Visit the fields. 7061 unsigned FieldIdx = 0; 7062 for (FieldDecl *FD : RD->fields()) { 7063 // FIXME: We don't currently support bit-fields. A lot of the logic for 7064 // this is in CodeGen, so we need to factor it around. 7065 if (FD->isBitField()) { 7066 Info.FFDiag(BCE->getBeginLoc(), 7067 diag::note_constexpr_bit_cast_unsupported_bitfield); 7068 return None; 7069 } 7070 7071 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7072 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7073 7074 CharUnits FieldOffset = 7075 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7076 Offset; 7077 QualType FieldTy = FD->getType(); 7078 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7079 if (!SubObj) 7080 return None; 7081 ResultVal.getStructField(FieldIdx) = *SubObj; 7082 ++FieldIdx; 7083 } 7084 7085 return ResultVal; 7086 } 7087 7088 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7089 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7090 assert(!RepresentationType.isNull() && 7091 "enum forward decl should be caught by Sema"); 7092 const auto *AsBuiltin = 7093 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7094 // Recurse into the underlying type. Treat std::byte transparently as 7095 // unsigned char. 7096 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7097 } 7098 7099 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7100 size_t Size = Ty->getSize().getLimitedValue(); 7101 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7102 7103 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7104 for (size_t I = 0; I != Size; ++I) { 7105 Optional<APValue> ElementValue = 7106 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7107 if (!ElementValue) 7108 return None; 7109 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7110 } 7111 7112 return ArrayValue; 7113 } 7114 7115 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7116 return unsupportedType(QualType(Ty, 0)); 7117 } 7118 7119 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7120 QualType Can = Ty.getCanonicalType(); 7121 7122 switch (Can->getTypeClass()) { 7123 #define TYPE(Class, Base) \ 7124 case Type::Class: \ 7125 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7126 #define ABSTRACT_TYPE(Class, Base) 7127 #define NON_CANONICAL_TYPE(Class, Base) \ 7128 case Type::Class: \ 7129 llvm_unreachable("non-canonical type should be impossible!"); 7130 #define DEPENDENT_TYPE(Class, Base) \ 7131 case Type::Class: \ 7132 llvm_unreachable( \ 7133 "dependent types aren't supported in the constant evaluator!"); 7134 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7135 case Type::Class: \ 7136 llvm_unreachable("either dependent or not canonical!"); 7137 #include "clang/AST/TypeNodes.inc" 7138 } 7139 llvm_unreachable("Unhandled Type::TypeClass"); 7140 } 7141 7142 public: 7143 // Pull out a full value of type DstType. 7144 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7145 const CastExpr *BCE) { 7146 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7147 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7148 } 7149 }; 7150 7151 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7152 QualType Ty, EvalInfo *Info, 7153 const ASTContext &Ctx, 7154 bool CheckingDest) { 7155 Ty = Ty.getCanonicalType(); 7156 7157 auto diag = [&](int Reason) { 7158 if (Info) 7159 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7160 << CheckingDest << (Reason == 4) << Reason; 7161 return false; 7162 }; 7163 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7164 if (Info) 7165 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7166 << NoteTy << Construct << Ty; 7167 return false; 7168 }; 7169 7170 if (Ty->isUnionType()) 7171 return diag(0); 7172 if (Ty->isPointerType()) 7173 return diag(1); 7174 if (Ty->isMemberPointerType()) 7175 return diag(2); 7176 if (Ty.isVolatileQualified()) 7177 return diag(3); 7178 7179 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7180 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7181 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7182 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7183 CheckingDest)) 7184 return note(1, BS.getType(), BS.getBeginLoc()); 7185 } 7186 for (FieldDecl *FD : Record->fields()) { 7187 if (FD->getType()->isReferenceType()) 7188 return diag(4); 7189 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7190 CheckingDest)) 7191 return note(0, FD->getType(), FD->getBeginLoc()); 7192 } 7193 } 7194 7195 if (Ty->isArrayType() && 7196 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7197 Info, Ctx, CheckingDest)) 7198 return false; 7199 7200 return true; 7201 } 7202 7203 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7204 const ASTContext &Ctx, 7205 const CastExpr *BCE) { 7206 bool DestOK = checkBitCastConstexprEligibilityType( 7207 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7208 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7209 BCE->getBeginLoc(), 7210 BCE->getSubExpr()->getType(), Info, Ctx, false); 7211 return SourceOK; 7212 } 7213 7214 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7215 APValue &SourceValue, 7216 const CastExpr *BCE) { 7217 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7218 "no host or target supports non 8-bit chars"); 7219 assert(SourceValue.isLValue() && 7220 "LValueToRValueBitcast requires an lvalue operand!"); 7221 7222 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7223 return false; 7224 7225 LValue SourceLValue; 7226 APValue SourceRValue; 7227 SourceLValue.setFrom(Info.Ctx, SourceValue); 7228 if (!handleLValueToRValueConversion( 7229 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7230 SourceRValue, /*WantObjectRepresentation=*/true)) 7231 return false; 7232 7233 // Read out SourceValue into a char buffer. 7234 Optional<BitCastBuffer> Buffer = 7235 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7236 if (!Buffer) 7237 return false; 7238 7239 // Write out the buffer into a new APValue. 7240 Optional<APValue> MaybeDestValue = 7241 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7242 if (!MaybeDestValue) 7243 return false; 7244 7245 DestValue = std::move(*MaybeDestValue); 7246 return true; 7247 } 7248 7249 template <class Derived> 7250 class ExprEvaluatorBase 7251 : public ConstStmtVisitor<Derived, bool> { 7252 private: 7253 Derived &getDerived() { return static_cast<Derived&>(*this); } 7254 bool DerivedSuccess(const APValue &V, const Expr *E) { 7255 return getDerived().Success(V, E); 7256 } 7257 bool DerivedZeroInitialization(const Expr *E) { 7258 return getDerived().ZeroInitialization(E); 7259 } 7260 7261 // Check whether a conditional operator with a non-constant condition is a 7262 // potential constant expression. If neither arm is a potential constant 7263 // expression, then the conditional operator is not either. 7264 template<typename ConditionalOperator> 7265 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7266 assert(Info.checkingPotentialConstantExpression()); 7267 7268 // Speculatively evaluate both arms. 7269 SmallVector<PartialDiagnosticAt, 8> Diag; 7270 { 7271 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7272 StmtVisitorTy::Visit(E->getFalseExpr()); 7273 if (Diag.empty()) 7274 return; 7275 } 7276 7277 { 7278 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7279 Diag.clear(); 7280 StmtVisitorTy::Visit(E->getTrueExpr()); 7281 if (Diag.empty()) 7282 return; 7283 } 7284 7285 Error(E, diag::note_constexpr_conditional_never_const); 7286 } 7287 7288 7289 template<typename ConditionalOperator> 7290 bool HandleConditionalOperator(const ConditionalOperator *E) { 7291 bool BoolResult; 7292 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7293 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7294 CheckPotentialConstantConditional(E); 7295 return false; 7296 } 7297 if (Info.noteFailure()) { 7298 StmtVisitorTy::Visit(E->getTrueExpr()); 7299 StmtVisitorTy::Visit(E->getFalseExpr()); 7300 } 7301 return false; 7302 } 7303 7304 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7305 return StmtVisitorTy::Visit(EvalExpr); 7306 } 7307 7308 protected: 7309 EvalInfo &Info; 7310 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7311 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7312 7313 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7314 return Info.CCEDiag(E, D); 7315 } 7316 7317 bool ZeroInitialization(const Expr *E) { return Error(E); } 7318 7319 public: 7320 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7321 7322 EvalInfo &getEvalInfo() { return Info; } 7323 7324 /// Report an evaluation error. This should only be called when an error is 7325 /// first discovered. When propagating an error, just return false. 7326 bool Error(const Expr *E, diag::kind D) { 7327 Info.FFDiag(E, D); 7328 return false; 7329 } 7330 bool Error(const Expr *E) { 7331 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7332 } 7333 7334 bool VisitStmt(const Stmt *) { 7335 llvm_unreachable("Expression evaluator should not be called on stmts"); 7336 } 7337 bool VisitExpr(const Expr *E) { 7338 return Error(E); 7339 } 7340 7341 bool VisitConstantExpr(const ConstantExpr *E) { 7342 if (E->hasAPValueResult()) 7343 return DerivedSuccess(E->getAPValueResult(), E); 7344 7345 return StmtVisitorTy::Visit(E->getSubExpr()); 7346 } 7347 7348 bool VisitParenExpr(const ParenExpr *E) 7349 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7350 bool VisitUnaryExtension(const UnaryOperator *E) 7351 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7352 bool VisitUnaryPlus(const UnaryOperator *E) 7353 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7354 bool VisitChooseExpr(const ChooseExpr *E) 7355 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7356 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7357 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7358 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7359 { return StmtVisitorTy::Visit(E->getReplacement()); } 7360 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7361 TempVersionRAII RAII(*Info.CurrentCall); 7362 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7363 return StmtVisitorTy::Visit(E->getExpr()); 7364 } 7365 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7366 TempVersionRAII RAII(*Info.CurrentCall); 7367 // The initializer may not have been parsed yet, or might be erroneous. 7368 if (!E->getExpr()) 7369 return Error(E); 7370 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7371 return StmtVisitorTy::Visit(E->getExpr()); 7372 } 7373 7374 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7375 FullExpressionRAII Scope(Info); 7376 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7377 } 7378 7379 // Temporaries are registered when created, so we don't care about 7380 // CXXBindTemporaryExpr. 7381 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7382 return StmtVisitorTy::Visit(E->getSubExpr()); 7383 } 7384 7385 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7386 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7387 return static_cast<Derived*>(this)->VisitCastExpr(E); 7388 } 7389 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7390 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7391 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7392 return static_cast<Derived*>(this)->VisitCastExpr(E); 7393 } 7394 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7395 return static_cast<Derived*>(this)->VisitCastExpr(E); 7396 } 7397 7398 bool VisitBinaryOperator(const BinaryOperator *E) { 7399 switch (E->getOpcode()) { 7400 default: 7401 return Error(E); 7402 7403 case BO_Comma: 7404 VisitIgnoredValue(E->getLHS()); 7405 return StmtVisitorTy::Visit(E->getRHS()); 7406 7407 case BO_PtrMemD: 7408 case BO_PtrMemI: { 7409 LValue Obj; 7410 if (!HandleMemberPointerAccess(Info, E, Obj)) 7411 return false; 7412 APValue Result; 7413 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7414 return false; 7415 return DerivedSuccess(Result, E); 7416 } 7417 } 7418 } 7419 7420 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7421 return StmtVisitorTy::Visit(E->getSemanticForm()); 7422 } 7423 7424 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7425 // Evaluate and cache the common expression. We treat it as a temporary, 7426 // even though it's not quite the same thing. 7427 LValue CommonLV; 7428 if (!Evaluate(Info.CurrentCall->createTemporary( 7429 E->getOpaqueValue(), 7430 getStorageType(Info.Ctx, E->getOpaqueValue()), 7431 ScopeKind::FullExpression, CommonLV), 7432 Info, E->getCommon())) 7433 return false; 7434 7435 return HandleConditionalOperator(E); 7436 } 7437 7438 bool VisitConditionalOperator(const ConditionalOperator *E) { 7439 bool IsBcpCall = false; 7440 // If the condition (ignoring parens) is a __builtin_constant_p call, 7441 // the result is a constant expression if it can be folded without 7442 // side-effects. This is an important GNU extension. See GCC PR38377 7443 // for discussion. 7444 if (const CallExpr *CallCE = 7445 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7446 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7447 IsBcpCall = true; 7448 7449 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7450 // constant expression; we can't check whether it's potentially foldable. 7451 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7452 // it would return 'false' in this mode. 7453 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7454 return false; 7455 7456 FoldConstant Fold(Info, IsBcpCall); 7457 if (!HandleConditionalOperator(E)) { 7458 Fold.keepDiagnostics(); 7459 return false; 7460 } 7461 7462 return true; 7463 } 7464 7465 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7466 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7467 return DerivedSuccess(*Value, E); 7468 7469 const Expr *Source = E->getSourceExpr(); 7470 if (!Source) 7471 return Error(E); 7472 if (Source == E) { // sanity checking. 7473 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7474 return Error(E); 7475 } 7476 return StmtVisitorTy::Visit(Source); 7477 } 7478 7479 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7480 for (const Expr *SemE : E->semantics()) { 7481 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7482 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7483 // result expression: there could be two different LValues that would 7484 // refer to the same object in that case, and we can't model that. 7485 if (SemE == E->getResultExpr()) 7486 return Error(E); 7487 7488 // Unique OVEs get evaluated if and when we encounter them when 7489 // emitting the rest of the semantic form, rather than eagerly. 7490 if (OVE->isUnique()) 7491 continue; 7492 7493 LValue LV; 7494 if (!Evaluate(Info.CurrentCall->createTemporary( 7495 OVE, getStorageType(Info.Ctx, OVE), 7496 ScopeKind::FullExpression, LV), 7497 Info, OVE->getSourceExpr())) 7498 return false; 7499 } else if (SemE == E->getResultExpr()) { 7500 if (!StmtVisitorTy::Visit(SemE)) 7501 return false; 7502 } else { 7503 if (!EvaluateIgnoredValue(Info, SemE)) 7504 return false; 7505 } 7506 } 7507 return true; 7508 } 7509 7510 bool VisitCallExpr(const CallExpr *E) { 7511 APValue Result; 7512 if (!handleCallExpr(E, Result, nullptr)) 7513 return false; 7514 return DerivedSuccess(Result, E); 7515 } 7516 7517 bool handleCallExpr(const CallExpr *E, APValue &Result, 7518 const LValue *ResultSlot) { 7519 CallScopeRAII CallScope(Info); 7520 7521 const Expr *Callee = E->getCallee()->IgnoreParens(); 7522 QualType CalleeType = Callee->getType(); 7523 7524 const FunctionDecl *FD = nullptr; 7525 LValue *This = nullptr, ThisVal; 7526 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7527 bool HasQualifier = false; 7528 7529 CallRef Call; 7530 7531 // Extract function decl and 'this' pointer from the callee. 7532 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7533 const CXXMethodDecl *Member = nullptr; 7534 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7535 // Explicit bound member calls, such as x.f() or p->g(); 7536 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7537 return false; 7538 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7539 if (!Member) 7540 return Error(Callee); 7541 This = &ThisVal; 7542 HasQualifier = ME->hasQualifier(); 7543 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7544 // Indirect bound member calls ('.*' or '->*'). 7545 const ValueDecl *D = 7546 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7547 if (!D) 7548 return false; 7549 Member = dyn_cast<CXXMethodDecl>(D); 7550 if (!Member) 7551 return Error(Callee); 7552 This = &ThisVal; 7553 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7554 if (!Info.getLangOpts().CPlusPlus20) 7555 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7556 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7557 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7558 } else 7559 return Error(Callee); 7560 FD = Member; 7561 } else if (CalleeType->isFunctionPointerType()) { 7562 LValue CalleeLV; 7563 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7564 return false; 7565 7566 if (!CalleeLV.getLValueOffset().isZero()) 7567 return Error(Callee); 7568 FD = dyn_cast_or_null<FunctionDecl>( 7569 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7570 if (!FD) 7571 return Error(Callee); 7572 // Don't call function pointers which have been cast to some other type. 7573 // Per DR (no number yet), the caller and callee can differ in noexcept. 7574 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7575 CalleeType->getPointeeType(), FD->getType())) { 7576 return Error(E); 7577 } 7578 7579 // For an (overloaded) assignment expression, evaluate the RHS before the 7580 // LHS. 7581 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7582 if (OCE && OCE->isAssignmentOp()) { 7583 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7584 Call = Info.CurrentCall->createCall(FD); 7585 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7586 Info, FD, /*RightToLeft=*/true)) 7587 return false; 7588 } 7589 7590 // Overloaded operator calls to member functions are represented as normal 7591 // calls with '*this' as the first argument. 7592 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7593 if (MD && !MD->isStatic()) { 7594 // FIXME: When selecting an implicit conversion for an overloaded 7595 // operator delete, we sometimes try to evaluate calls to conversion 7596 // operators without a 'this' parameter! 7597 if (Args.empty()) 7598 return Error(E); 7599 7600 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7601 return false; 7602 This = &ThisVal; 7603 Args = Args.slice(1); 7604 } else if (MD && MD->isLambdaStaticInvoker()) { 7605 // Map the static invoker for the lambda back to the call operator. 7606 // Conveniently, we don't have to slice out the 'this' argument (as is 7607 // being done for the non-static case), since a static member function 7608 // doesn't have an implicit argument passed in. 7609 const CXXRecordDecl *ClosureClass = MD->getParent(); 7610 assert( 7611 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7612 "Number of captures must be zero for conversion to function-ptr"); 7613 7614 const CXXMethodDecl *LambdaCallOp = 7615 ClosureClass->getLambdaCallOperator(); 7616 7617 // Set 'FD', the function that will be called below, to the call 7618 // operator. If the closure object represents a generic lambda, find 7619 // the corresponding specialization of the call operator. 7620 7621 if (ClosureClass->isGenericLambda()) { 7622 assert(MD->isFunctionTemplateSpecialization() && 7623 "A generic lambda's static-invoker function must be a " 7624 "template specialization"); 7625 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7626 FunctionTemplateDecl *CallOpTemplate = 7627 LambdaCallOp->getDescribedFunctionTemplate(); 7628 void *InsertPos = nullptr; 7629 FunctionDecl *CorrespondingCallOpSpecialization = 7630 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7631 assert(CorrespondingCallOpSpecialization && 7632 "We must always have a function call operator specialization " 7633 "that corresponds to our static invoker specialization"); 7634 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7635 } else 7636 FD = LambdaCallOp; 7637 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7638 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7639 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7640 LValue Ptr; 7641 if (!HandleOperatorNewCall(Info, E, Ptr)) 7642 return false; 7643 Ptr.moveInto(Result); 7644 return CallScope.destroy(); 7645 } else { 7646 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7647 } 7648 } 7649 } else 7650 return Error(E); 7651 7652 // Evaluate the arguments now if we've not already done so. 7653 if (!Call) { 7654 Call = Info.CurrentCall->createCall(FD); 7655 if (!EvaluateArgs(Args, Call, Info, FD)) 7656 return false; 7657 } 7658 7659 SmallVector<QualType, 4> CovariantAdjustmentPath; 7660 if (This) { 7661 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7662 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7663 // Perform virtual dispatch, if necessary. 7664 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7665 CovariantAdjustmentPath); 7666 if (!FD) 7667 return false; 7668 } else { 7669 // Check that the 'this' pointer points to an object of the right type. 7670 // FIXME: If this is an assignment operator call, we may need to change 7671 // the active union member before we check this. 7672 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7673 return false; 7674 } 7675 } 7676 7677 // Destructor calls are different enough that they have their own codepath. 7678 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7679 assert(This && "no 'this' pointer for destructor call"); 7680 return HandleDestruction(Info, E, *This, 7681 Info.Ctx.getRecordType(DD->getParent())) && 7682 CallScope.destroy(); 7683 } 7684 7685 const FunctionDecl *Definition = nullptr; 7686 Stmt *Body = FD->getBody(Definition); 7687 7688 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7689 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7690 Body, Info, Result, ResultSlot)) 7691 return false; 7692 7693 if (!CovariantAdjustmentPath.empty() && 7694 !HandleCovariantReturnAdjustment(Info, E, Result, 7695 CovariantAdjustmentPath)) 7696 return false; 7697 7698 return CallScope.destroy(); 7699 } 7700 7701 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7702 return StmtVisitorTy::Visit(E->getInitializer()); 7703 } 7704 bool VisitInitListExpr(const InitListExpr *E) { 7705 if (E->getNumInits() == 0) 7706 return DerivedZeroInitialization(E); 7707 if (E->getNumInits() == 1) 7708 return StmtVisitorTy::Visit(E->getInit(0)); 7709 return Error(E); 7710 } 7711 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7712 return DerivedZeroInitialization(E); 7713 } 7714 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7715 return DerivedZeroInitialization(E); 7716 } 7717 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7718 return DerivedZeroInitialization(E); 7719 } 7720 7721 /// A member expression where the object is a prvalue is itself a prvalue. 7722 bool VisitMemberExpr(const MemberExpr *E) { 7723 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7724 "missing temporary materialization conversion"); 7725 assert(!E->isArrow() && "missing call to bound member function?"); 7726 7727 APValue Val; 7728 if (!Evaluate(Val, Info, E->getBase())) 7729 return false; 7730 7731 QualType BaseTy = E->getBase()->getType(); 7732 7733 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7734 if (!FD) return Error(E); 7735 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7736 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7737 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7738 7739 // Note: there is no lvalue base here. But this case should only ever 7740 // happen in C or in C++98, where we cannot be evaluating a constexpr 7741 // constructor, which is the only case the base matters. 7742 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7743 SubobjectDesignator Designator(BaseTy); 7744 Designator.addDeclUnchecked(FD); 7745 7746 APValue Result; 7747 return extractSubobject(Info, E, Obj, Designator, Result) && 7748 DerivedSuccess(Result, E); 7749 } 7750 7751 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7752 APValue Val; 7753 if (!Evaluate(Val, Info, E->getBase())) 7754 return false; 7755 7756 if (Val.isVector()) { 7757 SmallVector<uint32_t, 4> Indices; 7758 E->getEncodedElementAccess(Indices); 7759 if (Indices.size() == 1) { 7760 // Return scalar. 7761 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7762 } else { 7763 // Construct new APValue vector. 7764 SmallVector<APValue, 4> Elts; 7765 for (unsigned I = 0; I < Indices.size(); ++I) { 7766 Elts.push_back(Val.getVectorElt(Indices[I])); 7767 } 7768 APValue VecResult(Elts.data(), Indices.size()); 7769 return DerivedSuccess(VecResult, E); 7770 } 7771 } 7772 7773 return false; 7774 } 7775 7776 bool VisitCastExpr(const CastExpr *E) { 7777 switch (E->getCastKind()) { 7778 default: 7779 break; 7780 7781 case CK_AtomicToNonAtomic: { 7782 APValue AtomicVal; 7783 // This does not need to be done in place even for class/array types: 7784 // atomic-to-non-atomic conversion implies copying the object 7785 // representation. 7786 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7787 return false; 7788 return DerivedSuccess(AtomicVal, E); 7789 } 7790 7791 case CK_NoOp: 7792 case CK_UserDefinedConversion: 7793 return StmtVisitorTy::Visit(E->getSubExpr()); 7794 7795 case CK_LValueToRValue: { 7796 LValue LVal; 7797 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7798 return false; 7799 APValue RVal; 7800 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7801 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7802 LVal, RVal)) 7803 return false; 7804 return DerivedSuccess(RVal, E); 7805 } 7806 case CK_LValueToRValueBitCast: { 7807 APValue DestValue, SourceValue; 7808 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7809 return false; 7810 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7811 return false; 7812 return DerivedSuccess(DestValue, E); 7813 } 7814 7815 case CK_AddressSpaceConversion: { 7816 APValue Value; 7817 if (!Evaluate(Value, Info, E->getSubExpr())) 7818 return false; 7819 return DerivedSuccess(Value, E); 7820 } 7821 } 7822 7823 return Error(E); 7824 } 7825 7826 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7827 return VisitUnaryPostIncDec(UO); 7828 } 7829 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7830 return VisitUnaryPostIncDec(UO); 7831 } 7832 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7833 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7834 return Error(UO); 7835 7836 LValue LVal; 7837 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7838 return false; 7839 APValue RVal; 7840 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7841 UO->isIncrementOp(), &RVal)) 7842 return false; 7843 return DerivedSuccess(RVal, UO); 7844 } 7845 7846 bool VisitStmtExpr(const StmtExpr *E) { 7847 // We will have checked the full-expressions inside the statement expression 7848 // when they were completed, and don't need to check them again now. 7849 if (Info.checkingForUndefinedBehavior()) 7850 return Error(E); 7851 7852 const CompoundStmt *CS = E->getSubStmt(); 7853 if (CS->body_empty()) 7854 return true; 7855 7856 BlockScopeRAII Scope(Info); 7857 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7858 BE = CS->body_end(); 7859 /**/; ++BI) { 7860 if (BI + 1 == BE) { 7861 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7862 if (!FinalExpr) { 7863 Info.FFDiag((*BI)->getBeginLoc(), 7864 diag::note_constexpr_stmt_expr_unsupported); 7865 return false; 7866 } 7867 return this->Visit(FinalExpr) && Scope.destroy(); 7868 } 7869 7870 APValue ReturnValue; 7871 StmtResult Result = { ReturnValue, nullptr }; 7872 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7873 if (ESR != ESR_Succeeded) { 7874 // FIXME: If the statement-expression terminated due to 'return', 7875 // 'break', or 'continue', it would be nice to propagate that to 7876 // the outer statement evaluation rather than bailing out. 7877 if (ESR != ESR_Failed) 7878 Info.FFDiag((*BI)->getBeginLoc(), 7879 diag::note_constexpr_stmt_expr_unsupported); 7880 return false; 7881 } 7882 } 7883 7884 llvm_unreachable("Return from function from the loop above."); 7885 } 7886 7887 /// Visit a value which is evaluated, but whose value is ignored. 7888 void VisitIgnoredValue(const Expr *E) { 7889 EvaluateIgnoredValue(Info, E); 7890 } 7891 7892 /// Potentially visit a MemberExpr's base expression. 7893 void VisitIgnoredBaseExpression(const Expr *E) { 7894 // While MSVC doesn't evaluate the base expression, it does diagnose the 7895 // presence of side-effecting behavior. 7896 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7897 return; 7898 VisitIgnoredValue(E); 7899 } 7900 }; 7901 7902 } // namespace 7903 7904 //===----------------------------------------------------------------------===// 7905 // Common base class for lvalue and temporary evaluation. 7906 //===----------------------------------------------------------------------===// 7907 namespace { 7908 template<class Derived> 7909 class LValueExprEvaluatorBase 7910 : public ExprEvaluatorBase<Derived> { 7911 protected: 7912 LValue &Result; 7913 bool InvalidBaseOK; 7914 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7915 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7916 7917 bool Success(APValue::LValueBase B) { 7918 Result.set(B); 7919 return true; 7920 } 7921 7922 bool evaluatePointer(const Expr *E, LValue &Result) { 7923 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7924 } 7925 7926 public: 7927 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7928 : ExprEvaluatorBaseTy(Info), Result(Result), 7929 InvalidBaseOK(InvalidBaseOK) {} 7930 7931 bool Success(const APValue &V, const Expr *E) { 7932 Result.setFrom(this->Info.Ctx, V); 7933 return true; 7934 } 7935 7936 bool VisitMemberExpr(const MemberExpr *E) { 7937 // Handle non-static data members. 7938 QualType BaseTy; 7939 bool EvalOK; 7940 if (E->isArrow()) { 7941 EvalOK = evaluatePointer(E->getBase(), Result); 7942 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7943 } else if (E->getBase()->isRValue()) { 7944 assert(E->getBase()->getType()->isRecordType()); 7945 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7946 BaseTy = E->getBase()->getType(); 7947 } else { 7948 EvalOK = this->Visit(E->getBase()); 7949 BaseTy = E->getBase()->getType(); 7950 } 7951 if (!EvalOK) { 7952 if (!InvalidBaseOK) 7953 return false; 7954 Result.setInvalid(E); 7955 return true; 7956 } 7957 7958 const ValueDecl *MD = E->getMemberDecl(); 7959 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7960 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7961 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7962 (void)BaseTy; 7963 if (!HandleLValueMember(this->Info, E, Result, FD)) 7964 return false; 7965 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7966 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7967 return false; 7968 } else 7969 return this->Error(E); 7970 7971 if (MD->getType()->isReferenceType()) { 7972 APValue RefValue; 7973 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7974 RefValue)) 7975 return false; 7976 return Success(RefValue, E); 7977 } 7978 return true; 7979 } 7980 7981 bool VisitBinaryOperator(const BinaryOperator *E) { 7982 switch (E->getOpcode()) { 7983 default: 7984 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7985 7986 case BO_PtrMemD: 7987 case BO_PtrMemI: 7988 return HandleMemberPointerAccess(this->Info, E, Result); 7989 } 7990 } 7991 7992 bool VisitCastExpr(const CastExpr *E) { 7993 switch (E->getCastKind()) { 7994 default: 7995 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7996 7997 case CK_DerivedToBase: 7998 case CK_UncheckedDerivedToBase: 7999 if (!this->Visit(E->getSubExpr())) 8000 return false; 8001 8002 // Now figure out the necessary offset to add to the base LV to get from 8003 // the derived class to the base class. 8004 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8005 Result); 8006 } 8007 } 8008 }; 8009 } 8010 8011 //===----------------------------------------------------------------------===// 8012 // LValue Evaluation 8013 // 8014 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8015 // function designators (in C), decl references to void objects (in C), and 8016 // temporaries (if building with -Wno-address-of-temporary). 8017 // 8018 // LValue evaluation produces values comprising a base expression of one of the 8019 // following types: 8020 // - Declarations 8021 // * VarDecl 8022 // * FunctionDecl 8023 // - Literals 8024 // * CompoundLiteralExpr in C (and in global scope in C++) 8025 // * StringLiteral 8026 // * PredefinedExpr 8027 // * ObjCStringLiteralExpr 8028 // * ObjCEncodeExpr 8029 // * AddrLabelExpr 8030 // * BlockExpr 8031 // * CallExpr for a MakeStringConstant builtin 8032 // - typeid(T) expressions, as TypeInfoLValues 8033 // - Locals and temporaries 8034 // * MaterializeTemporaryExpr 8035 // * Any Expr, with a CallIndex indicating the function in which the temporary 8036 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8037 // from the AST (FIXME). 8038 // * A MaterializeTemporaryExpr that has static storage duration, with no 8039 // CallIndex, for a lifetime-extended temporary. 8040 // * The ConstantExpr that is currently being evaluated during evaluation of an 8041 // immediate invocation. 8042 // plus an offset in bytes. 8043 //===----------------------------------------------------------------------===// 8044 namespace { 8045 class LValueExprEvaluator 8046 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8047 public: 8048 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8049 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8050 8051 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8052 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8053 8054 bool VisitDeclRefExpr(const DeclRefExpr *E); 8055 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8056 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8057 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8058 bool VisitMemberExpr(const MemberExpr *E); 8059 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8060 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8061 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8062 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8063 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8064 bool VisitUnaryDeref(const UnaryOperator *E); 8065 bool VisitUnaryReal(const UnaryOperator *E); 8066 bool VisitUnaryImag(const UnaryOperator *E); 8067 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8068 return VisitUnaryPreIncDec(UO); 8069 } 8070 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8071 return VisitUnaryPreIncDec(UO); 8072 } 8073 bool VisitBinAssign(const BinaryOperator *BO); 8074 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8075 8076 bool VisitCastExpr(const CastExpr *E) { 8077 switch (E->getCastKind()) { 8078 default: 8079 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8080 8081 case CK_LValueBitCast: 8082 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8083 if (!Visit(E->getSubExpr())) 8084 return false; 8085 Result.Designator.setInvalid(); 8086 return true; 8087 8088 case CK_BaseToDerived: 8089 if (!Visit(E->getSubExpr())) 8090 return false; 8091 return HandleBaseToDerivedCast(Info, E, Result); 8092 8093 case CK_Dynamic: 8094 if (!Visit(E->getSubExpr())) 8095 return false; 8096 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8097 } 8098 } 8099 }; 8100 } // end anonymous namespace 8101 8102 /// Evaluate an expression as an lvalue. This can be legitimately called on 8103 /// expressions which are not glvalues, in three cases: 8104 /// * function designators in C, and 8105 /// * "extern void" objects 8106 /// * @selector() expressions in Objective-C 8107 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8108 bool InvalidBaseOK) { 8109 assert(!E->isValueDependent()); 8110 assert(E->isGLValue() || E->getType()->isFunctionType() || 8111 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8112 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8113 } 8114 8115 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8116 const NamedDecl *D = E->getDecl(); 8117 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8118 return Success(cast<ValueDecl>(D)); 8119 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8120 return VisitVarDecl(E, VD); 8121 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8122 return Visit(BD->getBinding()); 8123 return Error(E); 8124 } 8125 8126 8127 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8128 8129 // If we are within a lambda's call operator, check whether the 'VD' referred 8130 // to within 'E' actually represents a lambda-capture that maps to a 8131 // data-member/field within the closure object, and if so, evaluate to the 8132 // field or what the field refers to. 8133 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8134 isa<DeclRefExpr>(E) && 8135 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8136 // We don't always have a complete capture-map when checking or inferring if 8137 // the function call operator meets the requirements of a constexpr function 8138 // - but we don't need to evaluate the captures to determine constexprness 8139 // (dcl.constexpr C++17). 8140 if (Info.checkingPotentialConstantExpression()) 8141 return false; 8142 8143 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8144 // Start with 'Result' referring to the complete closure object... 8145 Result = *Info.CurrentCall->This; 8146 // ... then update it to refer to the field of the closure object 8147 // that represents the capture. 8148 if (!HandleLValueMember(Info, E, Result, FD)) 8149 return false; 8150 // And if the field is of reference type, update 'Result' to refer to what 8151 // the field refers to. 8152 if (FD->getType()->isReferenceType()) { 8153 APValue RVal; 8154 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8155 RVal)) 8156 return false; 8157 Result.setFrom(Info.Ctx, RVal); 8158 } 8159 return true; 8160 } 8161 } 8162 8163 CallStackFrame *Frame = nullptr; 8164 unsigned Version = 0; 8165 if (VD->hasLocalStorage()) { 8166 // Only if a local variable was declared in the function currently being 8167 // evaluated, do we expect to be able to find its value in the current 8168 // frame. (Otherwise it was likely declared in an enclosing context and 8169 // could either have a valid evaluatable value (for e.g. a constexpr 8170 // variable) or be ill-formed (and trigger an appropriate evaluation 8171 // diagnostic)). 8172 CallStackFrame *CurrFrame = Info.CurrentCall; 8173 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8174 // Function parameters are stored in some caller's frame. (Usually the 8175 // immediate caller, but for an inherited constructor they may be more 8176 // distant.) 8177 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8178 if (CurrFrame->Arguments) { 8179 VD = CurrFrame->Arguments.getOrigParam(PVD); 8180 Frame = 8181 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8182 Version = CurrFrame->Arguments.Version; 8183 } 8184 } else { 8185 Frame = CurrFrame; 8186 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8187 } 8188 } 8189 } 8190 8191 if (!VD->getType()->isReferenceType()) { 8192 if (Frame) { 8193 Result.set({VD, Frame->Index, Version}); 8194 return true; 8195 } 8196 return Success(VD); 8197 } 8198 8199 if (!Info.getLangOpts().CPlusPlus11) { 8200 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8201 << VD << VD->getType(); 8202 Info.Note(VD->getLocation(), diag::note_declared_at); 8203 } 8204 8205 APValue *V; 8206 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8207 return false; 8208 if (!V->hasValue()) { 8209 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8210 // adjust the diagnostic to say that. 8211 if (!Info.checkingPotentialConstantExpression()) 8212 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8213 return false; 8214 } 8215 return Success(*V, E); 8216 } 8217 8218 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8219 const MaterializeTemporaryExpr *E) { 8220 // Walk through the expression to find the materialized temporary itself. 8221 SmallVector<const Expr *, 2> CommaLHSs; 8222 SmallVector<SubobjectAdjustment, 2> Adjustments; 8223 const Expr *Inner = 8224 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8225 8226 // If we passed any comma operators, evaluate their LHSs. 8227 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8228 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8229 return false; 8230 8231 // A materialized temporary with static storage duration can appear within the 8232 // result of a constant expression evaluation, so we need to preserve its 8233 // value for use outside this evaluation. 8234 APValue *Value; 8235 if (E->getStorageDuration() == SD_Static) { 8236 // FIXME: What about SD_Thread? 8237 Value = E->getOrCreateValue(true); 8238 *Value = APValue(); 8239 Result.set(E); 8240 } else { 8241 Value = &Info.CurrentCall->createTemporary( 8242 E, E->getType(), 8243 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8244 : ScopeKind::Block, 8245 Result); 8246 } 8247 8248 QualType Type = Inner->getType(); 8249 8250 // Materialize the temporary itself. 8251 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8252 *Value = APValue(); 8253 return false; 8254 } 8255 8256 // Adjust our lvalue to refer to the desired subobject. 8257 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8258 --I; 8259 switch (Adjustments[I].Kind) { 8260 case SubobjectAdjustment::DerivedToBaseAdjustment: 8261 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8262 Type, Result)) 8263 return false; 8264 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8265 break; 8266 8267 case SubobjectAdjustment::FieldAdjustment: 8268 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8269 return false; 8270 Type = Adjustments[I].Field->getType(); 8271 break; 8272 8273 case SubobjectAdjustment::MemberPointerAdjustment: 8274 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8275 Adjustments[I].Ptr.RHS)) 8276 return false; 8277 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8278 break; 8279 } 8280 } 8281 8282 return true; 8283 } 8284 8285 bool 8286 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8287 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8288 "lvalue compound literal in c++?"); 8289 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8290 // only see this when folding in C, so there's no standard to follow here. 8291 return Success(E); 8292 } 8293 8294 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8295 TypeInfoLValue TypeInfo; 8296 8297 if (!E->isPotentiallyEvaluated()) { 8298 if (E->isTypeOperand()) 8299 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8300 else 8301 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8302 } else { 8303 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8304 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8305 << E->getExprOperand()->getType() 8306 << E->getExprOperand()->getSourceRange(); 8307 } 8308 8309 if (!Visit(E->getExprOperand())) 8310 return false; 8311 8312 Optional<DynamicType> DynType = 8313 ComputeDynamicType(Info, E, Result, AK_TypeId); 8314 if (!DynType) 8315 return false; 8316 8317 TypeInfo = 8318 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8319 } 8320 8321 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8322 } 8323 8324 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8325 return Success(E->getGuidDecl()); 8326 } 8327 8328 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8329 // Handle static data members. 8330 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8331 VisitIgnoredBaseExpression(E->getBase()); 8332 return VisitVarDecl(E, VD); 8333 } 8334 8335 // Handle static member functions. 8336 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8337 if (MD->isStatic()) { 8338 VisitIgnoredBaseExpression(E->getBase()); 8339 return Success(MD); 8340 } 8341 } 8342 8343 // Handle non-static data members. 8344 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8345 } 8346 8347 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8348 // FIXME: Deal with vectors as array subscript bases. 8349 if (E->getBase()->getType()->isVectorType()) 8350 return Error(E); 8351 8352 APSInt Index; 8353 bool Success = true; 8354 8355 // C++17's rules require us to evaluate the LHS first, regardless of which 8356 // side is the base. 8357 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8358 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8359 : !EvaluateInteger(SubExpr, Index, Info)) { 8360 if (!Info.noteFailure()) 8361 return false; 8362 Success = false; 8363 } 8364 } 8365 8366 return Success && 8367 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8368 } 8369 8370 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8371 return evaluatePointer(E->getSubExpr(), Result); 8372 } 8373 8374 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8375 if (!Visit(E->getSubExpr())) 8376 return false; 8377 // __real is a no-op on scalar lvalues. 8378 if (E->getSubExpr()->getType()->isAnyComplexType()) 8379 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8380 return true; 8381 } 8382 8383 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8384 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8385 "lvalue __imag__ on scalar?"); 8386 if (!Visit(E->getSubExpr())) 8387 return false; 8388 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8389 return true; 8390 } 8391 8392 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8393 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8394 return Error(UO); 8395 8396 if (!this->Visit(UO->getSubExpr())) 8397 return false; 8398 8399 return handleIncDec( 8400 this->Info, UO, Result, UO->getSubExpr()->getType(), 8401 UO->isIncrementOp(), nullptr); 8402 } 8403 8404 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8405 const CompoundAssignOperator *CAO) { 8406 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8407 return Error(CAO); 8408 8409 bool Success = true; 8410 8411 // C++17 onwards require that we evaluate the RHS first. 8412 APValue RHS; 8413 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8414 if (!Info.noteFailure()) 8415 return false; 8416 Success = false; 8417 } 8418 8419 // The overall lvalue result is the result of evaluating the LHS. 8420 if (!this->Visit(CAO->getLHS()) || !Success) 8421 return false; 8422 8423 return handleCompoundAssignment( 8424 this->Info, CAO, 8425 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8426 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8427 } 8428 8429 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8430 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8431 return Error(E); 8432 8433 bool Success = true; 8434 8435 // C++17 onwards require that we evaluate the RHS first. 8436 APValue NewVal; 8437 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8438 if (!Info.noteFailure()) 8439 return false; 8440 Success = false; 8441 } 8442 8443 if (!this->Visit(E->getLHS()) || !Success) 8444 return false; 8445 8446 if (Info.getLangOpts().CPlusPlus20 && 8447 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8448 return false; 8449 8450 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8451 NewVal); 8452 } 8453 8454 //===----------------------------------------------------------------------===// 8455 // Pointer Evaluation 8456 //===----------------------------------------------------------------------===// 8457 8458 /// Attempts to compute the number of bytes available at the pointer 8459 /// returned by a function with the alloc_size attribute. Returns true if we 8460 /// were successful. Places an unsigned number into `Result`. 8461 /// 8462 /// This expects the given CallExpr to be a call to a function with an 8463 /// alloc_size attribute. 8464 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8465 const CallExpr *Call, 8466 llvm::APInt &Result) { 8467 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8468 8469 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8470 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8471 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8472 if (Call->getNumArgs() <= SizeArgNo) 8473 return false; 8474 8475 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8476 Expr::EvalResult ExprResult; 8477 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8478 return false; 8479 Into = ExprResult.Val.getInt(); 8480 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8481 return false; 8482 Into = Into.zextOrSelf(BitsInSizeT); 8483 return true; 8484 }; 8485 8486 APSInt SizeOfElem; 8487 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8488 return false; 8489 8490 if (!AllocSize->getNumElemsParam().isValid()) { 8491 Result = std::move(SizeOfElem); 8492 return true; 8493 } 8494 8495 APSInt NumberOfElems; 8496 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8497 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8498 return false; 8499 8500 bool Overflow; 8501 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8502 if (Overflow) 8503 return false; 8504 8505 Result = std::move(BytesAvailable); 8506 return true; 8507 } 8508 8509 /// Convenience function. LVal's base must be a call to an alloc_size 8510 /// function. 8511 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8512 const LValue &LVal, 8513 llvm::APInt &Result) { 8514 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8515 "Can't get the size of a non alloc_size function"); 8516 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8517 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8518 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8519 } 8520 8521 /// Attempts to evaluate the given LValueBase as the result of a call to 8522 /// a function with the alloc_size attribute. If it was possible to do so, this 8523 /// function will return true, make Result's Base point to said function call, 8524 /// and mark Result's Base as invalid. 8525 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8526 LValue &Result) { 8527 if (Base.isNull()) 8528 return false; 8529 8530 // Because we do no form of static analysis, we only support const variables. 8531 // 8532 // Additionally, we can't support parameters, nor can we support static 8533 // variables (in the latter case, use-before-assign isn't UB; in the former, 8534 // we have no clue what they'll be assigned to). 8535 const auto *VD = 8536 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8537 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8538 return false; 8539 8540 const Expr *Init = VD->getAnyInitializer(); 8541 if (!Init) 8542 return false; 8543 8544 const Expr *E = Init->IgnoreParens(); 8545 if (!tryUnwrapAllocSizeCall(E)) 8546 return false; 8547 8548 // Store E instead of E unwrapped so that the type of the LValue's base is 8549 // what the user wanted. 8550 Result.setInvalid(E); 8551 8552 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8553 Result.addUnsizedArray(Info, E, Pointee); 8554 return true; 8555 } 8556 8557 namespace { 8558 class PointerExprEvaluator 8559 : public ExprEvaluatorBase<PointerExprEvaluator> { 8560 LValue &Result; 8561 bool InvalidBaseOK; 8562 8563 bool Success(const Expr *E) { 8564 Result.set(E); 8565 return true; 8566 } 8567 8568 bool evaluateLValue(const Expr *E, LValue &Result) { 8569 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8570 } 8571 8572 bool evaluatePointer(const Expr *E, LValue &Result) { 8573 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8574 } 8575 8576 bool visitNonBuiltinCallExpr(const CallExpr *E); 8577 public: 8578 8579 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8580 : ExprEvaluatorBaseTy(info), Result(Result), 8581 InvalidBaseOK(InvalidBaseOK) {} 8582 8583 bool Success(const APValue &V, const Expr *E) { 8584 Result.setFrom(Info.Ctx, V); 8585 return true; 8586 } 8587 bool ZeroInitialization(const Expr *E) { 8588 Result.setNull(Info.Ctx, E->getType()); 8589 return true; 8590 } 8591 8592 bool VisitBinaryOperator(const BinaryOperator *E); 8593 bool VisitCastExpr(const CastExpr* E); 8594 bool VisitUnaryAddrOf(const UnaryOperator *E); 8595 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8596 { return Success(E); } 8597 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8598 if (E->isExpressibleAsConstantInitializer()) 8599 return Success(E); 8600 if (Info.noteFailure()) 8601 EvaluateIgnoredValue(Info, E->getSubExpr()); 8602 return Error(E); 8603 } 8604 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8605 { return Success(E); } 8606 bool VisitCallExpr(const CallExpr *E); 8607 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8608 bool VisitBlockExpr(const BlockExpr *E) { 8609 if (!E->getBlockDecl()->hasCaptures()) 8610 return Success(E); 8611 return Error(E); 8612 } 8613 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8614 // Can't look at 'this' when checking a potential constant expression. 8615 if (Info.checkingPotentialConstantExpression()) 8616 return false; 8617 if (!Info.CurrentCall->This) { 8618 if (Info.getLangOpts().CPlusPlus11) 8619 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8620 else 8621 Info.FFDiag(E); 8622 return false; 8623 } 8624 Result = *Info.CurrentCall->This; 8625 // If we are inside a lambda's call operator, the 'this' expression refers 8626 // to the enclosing '*this' object (either by value or reference) which is 8627 // either copied into the closure object's field that represents the '*this' 8628 // or refers to '*this'. 8629 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8630 // Ensure we actually have captured 'this'. (an error will have 8631 // been previously reported if not). 8632 if (!Info.CurrentCall->LambdaThisCaptureField) 8633 return false; 8634 8635 // Update 'Result' to refer to the data member/field of the closure object 8636 // that represents the '*this' capture. 8637 if (!HandleLValueMember(Info, E, Result, 8638 Info.CurrentCall->LambdaThisCaptureField)) 8639 return false; 8640 // If we captured '*this' by reference, replace the field with its referent. 8641 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8642 ->isPointerType()) { 8643 APValue RVal; 8644 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8645 RVal)) 8646 return false; 8647 8648 Result.setFrom(Info.Ctx, RVal); 8649 } 8650 } 8651 return true; 8652 } 8653 8654 bool VisitCXXNewExpr(const CXXNewExpr *E); 8655 8656 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8657 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8658 APValue LValResult = E->EvaluateInContext( 8659 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8660 Result.setFrom(Info.Ctx, LValResult); 8661 return true; 8662 } 8663 8664 // FIXME: Missing: @protocol, @selector 8665 }; 8666 } // end anonymous namespace 8667 8668 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8669 bool InvalidBaseOK) { 8670 assert(!E->isValueDependent()); 8671 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8672 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8673 } 8674 8675 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8676 if (E->getOpcode() != BO_Add && 8677 E->getOpcode() != BO_Sub) 8678 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8679 8680 const Expr *PExp = E->getLHS(); 8681 const Expr *IExp = E->getRHS(); 8682 if (IExp->getType()->isPointerType()) 8683 std::swap(PExp, IExp); 8684 8685 bool EvalPtrOK = evaluatePointer(PExp, Result); 8686 if (!EvalPtrOK && !Info.noteFailure()) 8687 return false; 8688 8689 llvm::APSInt Offset; 8690 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8691 return false; 8692 8693 if (E->getOpcode() == BO_Sub) 8694 negateAsSigned(Offset); 8695 8696 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8697 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8698 } 8699 8700 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8701 return evaluateLValue(E->getSubExpr(), Result); 8702 } 8703 8704 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8705 const Expr *SubExpr = E->getSubExpr(); 8706 8707 switch (E->getCastKind()) { 8708 default: 8709 break; 8710 case CK_BitCast: 8711 case CK_CPointerToObjCPointerCast: 8712 case CK_BlockPointerToObjCPointerCast: 8713 case CK_AnyPointerToBlockPointerCast: 8714 case CK_AddressSpaceConversion: 8715 if (!Visit(SubExpr)) 8716 return false; 8717 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8718 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8719 // also static_casts, but we disallow them as a resolution to DR1312. 8720 if (!E->getType()->isVoidPointerType()) { 8721 if (!Result.InvalidBase && !Result.Designator.Invalid && 8722 !Result.IsNullPtr && 8723 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8724 E->getType()->getPointeeType()) && 8725 Info.getStdAllocatorCaller("allocate")) { 8726 // Inside a call to std::allocator::allocate and friends, we permit 8727 // casting from void* back to cv1 T* for a pointer that points to a 8728 // cv2 T. 8729 } else { 8730 Result.Designator.setInvalid(); 8731 if (SubExpr->getType()->isVoidPointerType()) 8732 CCEDiag(E, diag::note_constexpr_invalid_cast) 8733 << 3 << SubExpr->getType(); 8734 else 8735 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8736 } 8737 } 8738 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8739 ZeroInitialization(E); 8740 return true; 8741 8742 case CK_DerivedToBase: 8743 case CK_UncheckedDerivedToBase: 8744 if (!evaluatePointer(E->getSubExpr(), Result)) 8745 return false; 8746 if (!Result.Base && Result.Offset.isZero()) 8747 return true; 8748 8749 // Now figure out the necessary offset to add to the base LV to get from 8750 // the derived class to the base class. 8751 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8752 castAs<PointerType>()->getPointeeType(), 8753 Result); 8754 8755 case CK_BaseToDerived: 8756 if (!Visit(E->getSubExpr())) 8757 return false; 8758 if (!Result.Base && Result.Offset.isZero()) 8759 return true; 8760 return HandleBaseToDerivedCast(Info, E, Result); 8761 8762 case CK_Dynamic: 8763 if (!Visit(E->getSubExpr())) 8764 return false; 8765 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8766 8767 case CK_NullToPointer: 8768 VisitIgnoredValue(E->getSubExpr()); 8769 return ZeroInitialization(E); 8770 8771 case CK_IntegralToPointer: { 8772 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8773 8774 APValue Value; 8775 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8776 break; 8777 8778 if (Value.isInt()) { 8779 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8780 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8781 Result.Base = (Expr*)nullptr; 8782 Result.InvalidBase = false; 8783 Result.Offset = CharUnits::fromQuantity(N); 8784 Result.Designator.setInvalid(); 8785 Result.IsNullPtr = false; 8786 return true; 8787 } else { 8788 // Cast is of an lvalue, no need to change value. 8789 Result.setFrom(Info.Ctx, Value); 8790 return true; 8791 } 8792 } 8793 8794 case CK_ArrayToPointerDecay: { 8795 if (SubExpr->isGLValue()) { 8796 if (!evaluateLValue(SubExpr, Result)) 8797 return false; 8798 } else { 8799 APValue &Value = Info.CurrentCall->createTemporary( 8800 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8801 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8802 return false; 8803 } 8804 // The result is a pointer to the first element of the array. 8805 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8806 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8807 Result.addArray(Info, E, CAT); 8808 else 8809 Result.addUnsizedArray(Info, E, AT->getElementType()); 8810 return true; 8811 } 8812 8813 case CK_FunctionToPointerDecay: 8814 return evaluateLValue(SubExpr, Result); 8815 8816 case CK_LValueToRValue: { 8817 LValue LVal; 8818 if (!evaluateLValue(E->getSubExpr(), LVal)) 8819 return false; 8820 8821 APValue RVal; 8822 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8823 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8824 LVal, RVal)) 8825 return InvalidBaseOK && 8826 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8827 return Success(RVal, E); 8828 } 8829 } 8830 8831 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8832 } 8833 8834 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8835 UnaryExprOrTypeTrait ExprKind) { 8836 // C++ [expr.alignof]p3: 8837 // When alignof is applied to a reference type, the result is the 8838 // alignment of the referenced type. 8839 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8840 T = Ref->getPointeeType(); 8841 8842 if (T.getQualifiers().hasUnaligned()) 8843 return CharUnits::One(); 8844 8845 const bool AlignOfReturnsPreferred = 8846 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8847 8848 // __alignof is defined to return the preferred alignment. 8849 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8850 // as well. 8851 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8852 return Info.Ctx.toCharUnitsFromBits( 8853 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8854 // alignof and _Alignof are defined to return the ABI alignment. 8855 else if (ExprKind == UETT_AlignOf) 8856 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8857 else 8858 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8859 } 8860 8861 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8862 UnaryExprOrTypeTrait ExprKind) { 8863 E = E->IgnoreParens(); 8864 8865 // The kinds of expressions that we have special-case logic here for 8866 // should be kept up to date with the special checks for those 8867 // expressions in Sema. 8868 8869 // alignof decl is always accepted, even if it doesn't make sense: we default 8870 // to 1 in those cases. 8871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8872 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8873 /*RefAsPointee*/true); 8874 8875 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8876 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8877 /*RefAsPointee*/true); 8878 8879 return GetAlignOfType(Info, E->getType(), ExprKind); 8880 } 8881 8882 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8883 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8884 return Info.Ctx.getDeclAlign(VD); 8885 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8886 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8887 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8888 } 8889 8890 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8891 /// __builtin_is_aligned and __builtin_assume_aligned. 8892 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8893 EvalInfo &Info, APSInt &Alignment) { 8894 if (!EvaluateInteger(E, Alignment, Info)) 8895 return false; 8896 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8897 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8898 return false; 8899 } 8900 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8901 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8902 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8903 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8904 << MaxValue << ForType << Alignment; 8905 return false; 8906 } 8907 // Ensure both alignment and source value have the same bit width so that we 8908 // don't assert when computing the resulting value. 8909 APSInt ExtAlignment = 8910 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8911 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8912 "Alignment should not be changed by ext/trunc"); 8913 Alignment = ExtAlignment; 8914 assert(Alignment.getBitWidth() == SrcWidth); 8915 return true; 8916 } 8917 8918 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8919 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8920 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8921 return true; 8922 8923 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8924 return false; 8925 8926 Result.setInvalid(E); 8927 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8928 Result.addUnsizedArray(Info, E, PointeeTy); 8929 return true; 8930 } 8931 8932 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8933 if (IsStringLiteralCall(E)) 8934 return Success(E); 8935 8936 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8937 return VisitBuiltinCallExpr(E, BuiltinOp); 8938 8939 return visitNonBuiltinCallExpr(E); 8940 } 8941 8942 // Determine if T is a character type for which we guarantee that 8943 // sizeof(T) == 1. 8944 static bool isOneByteCharacterType(QualType T) { 8945 return T->isCharType() || T->isChar8Type(); 8946 } 8947 8948 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8949 unsigned BuiltinOp) { 8950 switch (BuiltinOp) { 8951 case Builtin::BI__builtin_addressof: 8952 return evaluateLValue(E->getArg(0), Result); 8953 case Builtin::BI__builtin_assume_aligned: { 8954 // We need to be very careful here because: if the pointer does not have the 8955 // asserted alignment, then the behavior is undefined, and undefined 8956 // behavior is non-constant. 8957 if (!evaluatePointer(E->getArg(0), Result)) 8958 return false; 8959 8960 LValue OffsetResult(Result); 8961 APSInt Alignment; 8962 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8963 Alignment)) 8964 return false; 8965 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8966 8967 if (E->getNumArgs() > 2) { 8968 APSInt Offset; 8969 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8970 return false; 8971 8972 int64_t AdditionalOffset = -Offset.getZExtValue(); 8973 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8974 } 8975 8976 // If there is a base object, then it must have the correct alignment. 8977 if (OffsetResult.Base) { 8978 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8979 8980 if (BaseAlignment < Align) { 8981 Result.Designator.setInvalid(); 8982 // FIXME: Add support to Diagnostic for long / long long. 8983 CCEDiag(E->getArg(0), 8984 diag::note_constexpr_baa_insufficient_alignment) << 0 8985 << (unsigned)BaseAlignment.getQuantity() 8986 << (unsigned)Align.getQuantity(); 8987 return false; 8988 } 8989 } 8990 8991 // The offset must also have the correct alignment. 8992 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8993 Result.Designator.setInvalid(); 8994 8995 (OffsetResult.Base 8996 ? CCEDiag(E->getArg(0), 8997 diag::note_constexpr_baa_insufficient_alignment) << 1 8998 : CCEDiag(E->getArg(0), 8999 diag::note_constexpr_baa_value_insufficient_alignment)) 9000 << (int)OffsetResult.Offset.getQuantity() 9001 << (unsigned)Align.getQuantity(); 9002 return false; 9003 } 9004 9005 return true; 9006 } 9007 case Builtin::BI__builtin_align_up: 9008 case Builtin::BI__builtin_align_down: { 9009 if (!evaluatePointer(E->getArg(0), Result)) 9010 return false; 9011 APSInt Alignment; 9012 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9013 Alignment)) 9014 return false; 9015 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9016 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9017 // For align_up/align_down, we can return the same value if the alignment 9018 // is known to be greater or equal to the requested value. 9019 if (PtrAlign.getQuantity() >= Alignment) 9020 return true; 9021 9022 // The alignment could be greater than the minimum at run-time, so we cannot 9023 // infer much about the resulting pointer value. One case is possible: 9024 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9025 // can infer the correct index if the requested alignment is smaller than 9026 // the base alignment so we can perform the computation on the offset. 9027 if (BaseAlignment.getQuantity() >= Alignment) { 9028 assert(Alignment.getBitWidth() <= 64 && 9029 "Cannot handle > 64-bit address-space"); 9030 uint64_t Alignment64 = Alignment.getZExtValue(); 9031 CharUnits NewOffset = CharUnits::fromQuantity( 9032 BuiltinOp == Builtin::BI__builtin_align_down 9033 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9034 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9035 Result.adjustOffset(NewOffset - Result.Offset); 9036 // TODO: diagnose out-of-bounds values/only allow for arrays? 9037 return true; 9038 } 9039 // Otherwise, we cannot constant-evaluate the result. 9040 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9041 << Alignment; 9042 return false; 9043 } 9044 case Builtin::BI__builtin_operator_new: 9045 return HandleOperatorNewCall(Info, E, Result); 9046 case Builtin::BI__builtin_launder: 9047 return evaluatePointer(E->getArg(0), Result); 9048 case Builtin::BIstrchr: 9049 case Builtin::BIwcschr: 9050 case Builtin::BImemchr: 9051 case Builtin::BIwmemchr: 9052 if (Info.getLangOpts().CPlusPlus11) 9053 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9054 << /*isConstexpr*/0 << /*isConstructor*/0 9055 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9056 else 9057 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9058 LLVM_FALLTHROUGH; 9059 case Builtin::BI__builtin_strchr: 9060 case Builtin::BI__builtin_wcschr: 9061 case Builtin::BI__builtin_memchr: 9062 case Builtin::BI__builtin_char_memchr: 9063 case Builtin::BI__builtin_wmemchr: { 9064 if (!Visit(E->getArg(0))) 9065 return false; 9066 APSInt Desired; 9067 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9068 return false; 9069 uint64_t MaxLength = uint64_t(-1); 9070 if (BuiltinOp != Builtin::BIstrchr && 9071 BuiltinOp != Builtin::BIwcschr && 9072 BuiltinOp != Builtin::BI__builtin_strchr && 9073 BuiltinOp != Builtin::BI__builtin_wcschr) { 9074 APSInt N; 9075 if (!EvaluateInteger(E->getArg(2), N, Info)) 9076 return false; 9077 MaxLength = N.getExtValue(); 9078 } 9079 // We cannot find the value if there are no candidates to match against. 9080 if (MaxLength == 0u) 9081 return ZeroInitialization(E); 9082 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9083 Result.Designator.Invalid) 9084 return false; 9085 QualType CharTy = Result.Designator.getType(Info.Ctx); 9086 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9087 BuiltinOp == Builtin::BI__builtin_memchr; 9088 assert(IsRawByte || 9089 Info.Ctx.hasSameUnqualifiedType( 9090 CharTy, E->getArg(0)->getType()->getPointeeType())); 9091 // Pointers to const void may point to objects of incomplete type. 9092 if (IsRawByte && CharTy->isIncompleteType()) { 9093 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9094 return false; 9095 } 9096 // Give up on byte-oriented matching against multibyte elements. 9097 // FIXME: We can compare the bytes in the correct order. 9098 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9099 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9100 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9101 << CharTy; 9102 return false; 9103 } 9104 // Figure out what value we're actually looking for (after converting to 9105 // the corresponding unsigned type if necessary). 9106 uint64_t DesiredVal; 9107 bool StopAtNull = false; 9108 switch (BuiltinOp) { 9109 case Builtin::BIstrchr: 9110 case Builtin::BI__builtin_strchr: 9111 // strchr compares directly to the passed integer, and therefore 9112 // always fails if given an int that is not a char. 9113 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9114 E->getArg(1)->getType(), 9115 Desired), 9116 Desired)) 9117 return ZeroInitialization(E); 9118 StopAtNull = true; 9119 LLVM_FALLTHROUGH; 9120 case Builtin::BImemchr: 9121 case Builtin::BI__builtin_memchr: 9122 case Builtin::BI__builtin_char_memchr: 9123 // memchr compares by converting both sides to unsigned char. That's also 9124 // correct for strchr if we get this far (to cope with plain char being 9125 // unsigned in the strchr case). 9126 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9127 break; 9128 9129 case Builtin::BIwcschr: 9130 case Builtin::BI__builtin_wcschr: 9131 StopAtNull = true; 9132 LLVM_FALLTHROUGH; 9133 case Builtin::BIwmemchr: 9134 case Builtin::BI__builtin_wmemchr: 9135 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9136 DesiredVal = Desired.getZExtValue(); 9137 break; 9138 } 9139 9140 for (; MaxLength; --MaxLength) { 9141 APValue Char; 9142 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9143 !Char.isInt()) 9144 return false; 9145 if (Char.getInt().getZExtValue() == DesiredVal) 9146 return true; 9147 if (StopAtNull && !Char.getInt()) 9148 break; 9149 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9150 return false; 9151 } 9152 // Not found: return nullptr. 9153 return ZeroInitialization(E); 9154 } 9155 9156 case Builtin::BImemcpy: 9157 case Builtin::BImemmove: 9158 case Builtin::BIwmemcpy: 9159 case Builtin::BIwmemmove: 9160 if (Info.getLangOpts().CPlusPlus11) 9161 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9162 << /*isConstexpr*/0 << /*isConstructor*/0 9163 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9164 else 9165 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9166 LLVM_FALLTHROUGH; 9167 case Builtin::BI__builtin_memcpy: 9168 case Builtin::BI__builtin_memmove: 9169 case Builtin::BI__builtin_wmemcpy: 9170 case Builtin::BI__builtin_wmemmove: { 9171 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9172 BuiltinOp == Builtin::BIwmemmove || 9173 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9174 BuiltinOp == Builtin::BI__builtin_wmemmove; 9175 bool Move = BuiltinOp == Builtin::BImemmove || 9176 BuiltinOp == Builtin::BIwmemmove || 9177 BuiltinOp == Builtin::BI__builtin_memmove || 9178 BuiltinOp == Builtin::BI__builtin_wmemmove; 9179 9180 // The result of mem* is the first argument. 9181 if (!Visit(E->getArg(0))) 9182 return false; 9183 LValue Dest = Result; 9184 9185 LValue Src; 9186 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9187 return false; 9188 9189 APSInt N; 9190 if (!EvaluateInteger(E->getArg(2), N, Info)) 9191 return false; 9192 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9193 9194 // If the size is zero, we treat this as always being a valid no-op. 9195 // (Even if one of the src and dest pointers is null.) 9196 if (!N) 9197 return true; 9198 9199 // Otherwise, if either of the operands is null, we can't proceed. Don't 9200 // try to determine the type of the copied objects, because there aren't 9201 // any. 9202 if (!Src.Base || !Dest.Base) { 9203 APValue Val; 9204 (!Src.Base ? Src : Dest).moveInto(Val); 9205 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9206 << Move << WChar << !!Src.Base 9207 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9208 return false; 9209 } 9210 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9211 return false; 9212 9213 // We require that Src and Dest are both pointers to arrays of 9214 // trivially-copyable type. (For the wide version, the designator will be 9215 // invalid if the designated object is not a wchar_t.) 9216 QualType T = Dest.Designator.getType(Info.Ctx); 9217 QualType SrcT = Src.Designator.getType(Info.Ctx); 9218 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9219 // FIXME: Consider using our bit_cast implementation to support this. 9220 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9221 return false; 9222 } 9223 if (T->isIncompleteType()) { 9224 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9225 return false; 9226 } 9227 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9228 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9229 return false; 9230 } 9231 9232 // Figure out how many T's we're copying. 9233 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9234 if (!WChar) { 9235 uint64_t Remainder; 9236 llvm::APInt OrigN = N; 9237 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9238 if (Remainder) { 9239 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9240 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 9241 << (unsigned)TSize; 9242 return false; 9243 } 9244 } 9245 9246 // Check that the copying will remain within the arrays, just so that we 9247 // can give a more meaningful diagnostic. This implicitly also checks that 9248 // N fits into 64 bits. 9249 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9250 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9251 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9252 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9253 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9254 << N.toString(10, /*Signed*/false); 9255 return false; 9256 } 9257 uint64_t NElems = N.getZExtValue(); 9258 uint64_t NBytes = NElems * TSize; 9259 9260 // Check for overlap. 9261 int Direction = 1; 9262 if (HasSameBase(Src, Dest)) { 9263 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9264 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9265 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9266 // Dest is inside the source region. 9267 if (!Move) { 9268 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9269 return false; 9270 } 9271 // For memmove and friends, copy backwards. 9272 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9273 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9274 return false; 9275 Direction = -1; 9276 } else if (!Move && SrcOffset >= DestOffset && 9277 SrcOffset - DestOffset < NBytes) { 9278 // Src is inside the destination region for memcpy: invalid. 9279 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9280 return false; 9281 } 9282 } 9283 9284 while (true) { 9285 APValue Val; 9286 // FIXME: Set WantObjectRepresentation to true if we're copying a 9287 // char-like type? 9288 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9289 !handleAssignment(Info, E, Dest, T, Val)) 9290 return false; 9291 // Do not iterate past the last element; if we're copying backwards, that 9292 // might take us off the start of the array. 9293 if (--NElems == 0) 9294 return true; 9295 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9296 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9297 return false; 9298 } 9299 } 9300 9301 default: 9302 break; 9303 } 9304 9305 return visitNonBuiltinCallExpr(E); 9306 } 9307 9308 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9309 APValue &Result, const InitListExpr *ILE, 9310 QualType AllocType); 9311 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9312 APValue &Result, 9313 const CXXConstructExpr *CCE, 9314 QualType AllocType); 9315 9316 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9317 if (!Info.getLangOpts().CPlusPlus20) 9318 Info.CCEDiag(E, diag::note_constexpr_new); 9319 9320 // We cannot speculatively evaluate a delete expression. 9321 if (Info.SpeculativeEvaluationDepth) 9322 return false; 9323 9324 FunctionDecl *OperatorNew = E->getOperatorNew(); 9325 9326 bool IsNothrow = false; 9327 bool IsPlacement = false; 9328 if (OperatorNew->isReservedGlobalPlacementOperator() && 9329 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9330 // FIXME Support array placement new. 9331 assert(E->getNumPlacementArgs() == 1); 9332 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9333 return false; 9334 if (Result.Designator.Invalid) 9335 return false; 9336 IsPlacement = true; 9337 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9338 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9339 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9340 return false; 9341 } else if (E->getNumPlacementArgs()) { 9342 // The only new-placement list we support is of the form (std::nothrow). 9343 // 9344 // FIXME: There is no restriction on this, but it's not clear that any 9345 // other form makes any sense. We get here for cases such as: 9346 // 9347 // new (std::align_val_t{N}) X(int) 9348 // 9349 // (which should presumably be valid only if N is a multiple of 9350 // alignof(int), and in any case can't be deallocated unless N is 9351 // alignof(X) and X has new-extended alignment). 9352 if (E->getNumPlacementArgs() != 1 || 9353 !E->getPlacementArg(0)->getType()->isNothrowT()) 9354 return Error(E, diag::note_constexpr_new_placement); 9355 9356 LValue Nothrow; 9357 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9358 return false; 9359 IsNothrow = true; 9360 } 9361 9362 const Expr *Init = E->getInitializer(); 9363 const InitListExpr *ResizedArrayILE = nullptr; 9364 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9365 bool ValueInit = false; 9366 9367 QualType AllocType = E->getAllocatedType(); 9368 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9369 const Expr *Stripped = *ArraySize; 9370 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9371 Stripped = ICE->getSubExpr()) 9372 if (ICE->getCastKind() != CK_NoOp && 9373 ICE->getCastKind() != CK_IntegralCast) 9374 break; 9375 9376 llvm::APSInt ArrayBound; 9377 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9378 return false; 9379 9380 // C++ [expr.new]p9: 9381 // The expression is erroneous if: 9382 // -- [...] its value before converting to size_t [or] applying the 9383 // second standard conversion sequence is less than zero 9384 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9385 if (IsNothrow) 9386 return ZeroInitialization(E); 9387 9388 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9389 << ArrayBound << (*ArraySize)->getSourceRange(); 9390 return false; 9391 } 9392 9393 // -- its value is such that the size of the allocated object would 9394 // exceed the implementation-defined limit 9395 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9396 ArrayBound) > 9397 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9398 if (IsNothrow) 9399 return ZeroInitialization(E); 9400 9401 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9402 << ArrayBound << (*ArraySize)->getSourceRange(); 9403 return false; 9404 } 9405 9406 // -- the new-initializer is a braced-init-list and the number of 9407 // array elements for which initializers are provided [...] 9408 // exceeds the number of elements to initialize 9409 if (!Init) { 9410 // No initialization is performed. 9411 } else if (isa<CXXScalarValueInitExpr>(Init) || 9412 isa<ImplicitValueInitExpr>(Init)) { 9413 ValueInit = true; 9414 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9415 ResizedArrayCCE = CCE; 9416 } else { 9417 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9418 assert(CAT && "unexpected type for array initializer"); 9419 9420 unsigned Bits = 9421 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9422 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9423 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9424 if (InitBound.ugt(AllocBound)) { 9425 if (IsNothrow) 9426 return ZeroInitialization(E); 9427 9428 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9429 << AllocBound.toString(10, /*Signed=*/false) 9430 << InitBound.toString(10, /*Signed=*/false) 9431 << (*ArraySize)->getSourceRange(); 9432 return false; 9433 } 9434 9435 // If the sizes differ, we must have an initializer list, and we need 9436 // special handling for this case when we initialize. 9437 if (InitBound != AllocBound) 9438 ResizedArrayILE = cast<InitListExpr>(Init); 9439 } 9440 9441 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9442 ArrayType::Normal, 0); 9443 } else { 9444 assert(!AllocType->isArrayType() && 9445 "array allocation with non-array new"); 9446 } 9447 9448 APValue *Val; 9449 if (IsPlacement) { 9450 AccessKinds AK = AK_Construct; 9451 struct FindObjectHandler { 9452 EvalInfo &Info; 9453 const Expr *E; 9454 QualType AllocType; 9455 const AccessKinds AccessKind; 9456 APValue *Value; 9457 9458 typedef bool result_type; 9459 bool failed() { return false; } 9460 bool found(APValue &Subobj, QualType SubobjType) { 9461 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9462 // old name of the object to be used to name the new object. 9463 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9464 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9465 SubobjType << AllocType; 9466 return false; 9467 } 9468 Value = &Subobj; 9469 return true; 9470 } 9471 bool found(APSInt &Value, QualType SubobjType) { 9472 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9473 return false; 9474 } 9475 bool found(APFloat &Value, QualType SubobjType) { 9476 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9477 return false; 9478 } 9479 } Handler = {Info, E, AllocType, AK, nullptr}; 9480 9481 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9482 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9483 return false; 9484 9485 Val = Handler.Value; 9486 9487 // [basic.life]p1: 9488 // The lifetime of an object o of type T ends when [...] the storage 9489 // which the object occupies is [...] reused by an object that is not 9490 // nested within o (6.6.2). 9491 *Val = APValue(); 9492 } else { 9493 // Perform the allocation and obtain a pointer to the resulting object. 9494 Val = Info.createHeapAlloc(E, AllocType, Result); 9495 if (!Val) 9496 return false; 9497 } 9498 9499 if (ValueInit) { 9500 ImplicitValueInitExpr VIE(AllocType); 9501 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9502 return false; 9503 } else if (ResizedArrayILE) { 9504 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9505 AllocType)) 9506 return false; 9507 } else if (ResizedArrayCCE) { 9508 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9509 AllocType)) 9510 return false; 9511 } else if (Init) { 9512 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9513 return false; 9514 } else if (!getDefaultInitValue(AllocType, *Val)) { 9515 return false; 9516 } 9517 9518 // Array new returns a pointer to the first element, not a pointer to the 9519 // array. 9520 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9521 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9522 9523 return true; 9524 } 9525 //===----------------------------------------------------------------------===// 9526 // Member Pointer Evaluation 9527 //===----------------------------------------------------------------------===// 9528 9529 namespace { 9530 class MemberPointerExprEvaluator 9531 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9532 MemberPtr &Result; 9533 9534 bool Success(const ValueDecl *D) { 9535 Result = MemberPtr(D); 9536 return true; 9537 } 9538 public: 9539 9540 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9541 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9542 9543 bool Success(const APValue &V, const Expr *E) { 9544 Result.setFrom(V); 9545 return true; 9546 } 9547 bool ZeroInitialization(const Expr *E) { 9548 return Success((const ValueDecl*)nullptr); 9549 } 9550 9551 bool VisitCastExpr(const CastExpr *E); 9552 bool VisitUnaryAddrOf(const UnaryOperator *E); 9553 }; 9554 } // end anonymous namespace 9555 9556 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9557 EvalInfo &Info) { 9558 assert(!E->isValueDependent()); 9559 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9560 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9561 } 9562 9563 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9564 switch (E->getCastKind()) { 9565 default: 9566 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9567 9568 case CK_NullToMemberPointer: 9569 VisitIgnoredValue(E->getSubExpr()); 9570 return ZeroInitialization(E); 9571 9572 case CK_BaseToDerivedMemberPointer: { 9573 if (!Visit(E->getSubExpr())) 9574 return false; 9575 if (E->path_empty()) 9576 return true; 9577 // Base-to-derived member pointer casts store the path in derived-to-base 9578 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9579 // the wrong end of the derived->base arc, so stagger the path by one class. 9580 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9581 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9582 PathI != PathE; ++PathI) { 9583 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9584 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9585 if (!Result.castToDerived(Derived)) 9586 return Error(E); 9587 } 9588 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9589 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9590 return Error(E); 9591 return true; 9592 } 9593 9594 case CK_DerivedToBaseMemberPointer: 9595 if (!Visit(E->getSubExpr())) 9596 return false; 9597 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9598 PathE = E->path_end(); PathI != PathE; ++PathI) { 9599 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9600 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9601 if (!Result.castToBase(Base)) 9602 return Error(E); 9603 } 9604 return true; 9605 } 9606 } 9607 9608 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9609 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9610 // member can be formed. 9611 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9612 } 9613 9614 //===----------------------------------------------------------------------===// 9615 // Record Evaluation 9616 //===----------------------------------------------------------------------===// 9617 9618 namespace { 9619 class RecordExprEvaluator 9620 : public ExprEvaluatorBase<RecordExprEvaluator> { 9621 const LValue &This; 9622 APValue &Result; 9623 public: 9624 9625 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9626 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9627 9628 bool Success(const APValue &V, const Expr *E) { 9629 Result = V; 9630 return true; 9631 } 9632 bool ZeroInitialization(const Expr *E) { 9633 return ZeroInitialization(E, E->getType()); 9634 } 9635 bool ZeroInitialization(const Expr *E, QualType T); 9636 9637 bool VisitCallExpr(const CallExpr *E) { 9638 return handleCallExpr(E, Result, &This); 9639 } 9640 bool VisitCastExpr(const CastExpr *E); 9641 bool VisitInitListExpr(const InitListExpr *E); 9642 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9643 return VisitCXXConstructExpr(E, E->getType()); 9644 } 9645 bool VisitLambdaExpr(const LambdaExpr *E); 9646 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9647 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9648 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9649 bool VisitBinCmp(const BinaryOperator *E); 9650 }; 9651 } 9652 9653 /// Perform zero-initialization on an object of non-union class type. 9654 /// C++11 [dcl.init]p5: 9655 /// To zero-initialize an object or reference of type T means: 9656 /// [...] 9657 /// -- if T is a (possibly cv-qualified) non-union class type, 9658 /// each non-static data member and each base-class subobject is 9659 /// zero-initialized 9660 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9661 const RecordDecl *RD, 9662 const LValue &This, APValue &Result) { 9663 assert(!RD->isUnion() && "Expected non-union class type"); 9664 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9665 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9666 std::distance(RD->field_begin(), RD->field_end())); 9667 9668 if (RD->isInvalidDecl()) return false; 9669 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9670 9671 if (CD) { 9672 unsigned Index = 0; 9673 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9674 End = CD->bases_end(); I != End; ++I, ++Index) { 9675 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9676 LValue Subobject = This; 9677 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9678 return false; 9679 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9680 Result.getStructBase(Index))) 9681 return false; 9682 } 9683 } 9684 9685 for (const auto *I : RD->fields()) { 9686 // -- if T is a reference type, no initialization is performed. 9687 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9688 continue; 9689 9690 LValue Subobject = This; 9691 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9692 return false; 9693 9694 ImplicitValueInitExpr VIE(I->getType()); 9695 if (!EvaluateInPlace( 9696 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9697 return false; 9698 } 9699 9700 return true; 9701 } 9702 9703 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9704 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9705 if (RD->isInvalidDecl()) return false; 9706 if (RD->isUnion()) { 9707 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9708 // object's first non-static named data member is zero-initialized 9709 RecordDecl::field_iterator I = RD->field_begin(); 9710 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9711 ++I; 9712 if (I == RD->field_end()) { 9713 Result = APValue((const FieldDecl*)nullptr); 9714 return true; 9715 } 9716 9717 LValue Subobject = This; 9718 if (!HandleLValueMember(Info, E, Subobject, *I)) 9719 return false; 9720 Result = APValue(*I); 9721 ImplicitValueInitExpr VIE(I->getType()); 9722 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9723 } 9724 9725 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9726 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9727 return false; 9728 } 9729 9730 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9731 } 9732 9733 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9734 switch (E->getCastKind()) { 9735 default: 9736 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9737 9738 case CK_ConstructorConversion: 9739 return Visit(E->getSubExpr()); 9740 9741 case CK_DerivedToBase: 9742 case CK_UncheckedDerivedToBase: { 9743 APValue DerivedObject; 9744 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9745 return false; 9746 if (!DerivedObject.isStruct()) 9747 return Error(E->getSubExpr()); 9748 9749 // Derived-to-base rvalue conversion: just slice off the derived part. 9750 APValue *Value = &DerivedObject; 9751 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9752 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9753 PathE = E->path_end(); PathI != PathE; ++PathI) { 9754 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9755 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9756 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9757 RD = Base; 9758 } 9759 Result = *Value; 9760 return true; 9761 } 9762 } 9763 } 9764 9765 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9766 if (E->isTransparent()) 9767 return Visit(E->getInit(0)); 9768 9769 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9770 if (RD->isInvalidDecl()) return false; 9771 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9772 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9773 9774 EvalInfo::EvaluatingConstructorRAII EvalObj( 9775 Info, 9776 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9777 CXXRD && CXXRD->getNumBases()); 9778 9779 if (RD->isUnion()) { 9780 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9781 Result = APValue(Field); 9782 if (!Field) 9783 return true; 9784 9785 // If the initializer list for a union does not contain any elements, the 9786 // first element of the union is value-initialized. 9787 // FIXME: The element should be initialized from an initializer list. 9788 // Is this difference ever observable for initializer lists which 9789 // we don't build? 9790 ImplicitValueInitExpr VIE(Field->getType()); 9791 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9792 9793 LValue Subobject = This; 9794 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9795 return false; 9796 9797 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9798 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9799 isa<CXXDefaultInitExpr>(InitExpr)); 9800 9801 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9802 } 9803 9804 if (!Result.hasValue()) 9805 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9806 std::distance(RD->field_begin(), RD->field_end())); 9807 unsigned ElementNo = 0; 9808 bool Success = true; 9809 9810 // Initialize base classes. 9811 if (CXXRD && CXXRD->getNumBases()) { 9812 for (const auto &Base : CXXRD->bases()) { 9813 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9814 const Expr *Init = E->getInit(ElementNo); 9815 9816 LValue Subobject = This; 9817 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9818 return false; 9819 9820 APValue &FieldVal = Result.getStructBase(ElementNo); 9821 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9822 if (!Info.noteFailure()) 9823 return false; 9824 Success = false; 9825 } 9826 ++ElementNo; 9827 } 9828 9829 EvalObj.finishedConstructingBases(); 9830 } 9831 9832 // Initialize members. 9833 for (const auto *Field : RD->fields()) { 9834 // Anonymous bit-fields are not considered members of the class for 9835 // purposes of aggregate initialization. 9836 if (Field->isUnnamedBitfield()) 9837 continue; 9838 9839 LValue Subobject = This; 9840 9841 bool HaveInit = ElementNo < E->getNumInits(); 9842 9843 // FIXME: Diagnostics here should point to the end of the initializer 9844 // list, not the start. 9845 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9846 Subobject, Field, &Layout)) 9847 return false; 9848 9849 // Perform an implicit value-initialization for members beyond the end of 9850 // the initializer list. 9851 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9852 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9853 9854 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9855 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9856 isa<CXXDefaultInitExpr>(Init)); 9857 9858 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9859 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9860 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9861 FieldVal, Field))) { 9862 if (!Info.noteFailure()) 9863 return false; 9864 Success = false; 9865 } 9866 } 9867 9868 EvalObj.finishedConstructingFields(); 9869 9870 return Success; 9871 } 9872 9873 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9874 QualType T) { 9875 // Note that E's type is not necessarily the type of our class here; we might 9876 // be initializing an array element instead. 9877 const CXXConstructorDecl *FD = E->getConstructor(); 9878 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9879 9880 bool ZeroInit = E->requiresZeroInitialization(); 9881 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9882 // If we've already performed zero-initialization, we're already done. 9883 if (Result.hasValue()) 9884 return true; 9885 9886 if (ZeroInit) 9887 return ZeroInitialization(E, T); 9888 9889 return getDefaultInitValue(T, Result); 9890 } 9891 9892 const FunctionDecl *Definition = nullptr; 9893 auto Body = FD->getBody(Definition); 9894 9895 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9896 return false; 9897 9898 // Avoid materializing a temporary for an elidable copy/move constructor. 9899 if (E->isElidable() && !ZeroInit) 9900 if (const MaterializeTemporaryExpr *ME 9901 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9902 return Visit(ME->getSubExpr()); 9903 9904 if (ZeroInit && !ZeroInitialization(E, T)) 9905 return false; 9906 9907 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9908 return HandleConstructorCall(E, This, Args, 9909 cast<CXXConstructorDecl>(Definition), Info, 9910 Result); 9911 } 9912 9913 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9914 const CXXInheritedCtorInitExpr *E) { 9915 if (!Info.CurrentCall) { 9916 assert(Info.checkingPotentialConstantExpression()); 9917 return false; 9918 } 9919 9920 const CXXConstructorDecl *FD = E->getConstructor(); 9921 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9922 return false; 9923 9924 const FunctionDecl *Definition = nullptr; 9925 auto Body = FD->getBody(Definition); 9926 9927 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9928 return false; 9929 9930 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9931 cast<CXXConstructorDecl>(Definition), Info, 9932 Result); 9933 } 9934 9935 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9936 const CXXStdInitializerListExpr *E) { 9937 const ConstantArrayType *ArrayType = 9938 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9939 9940 LValue Array; 9941 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9942 return false; 9943 9944 // Get a pointer to the first element of the array. 9945 Array.addArray(Info, E, ArrayType); 9946 9947 auto InvalidType = [&] { 9948 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9949 << E->getType(); 9950 return false; 9951 }; 9952 9953 // FIXME: Perform the checks on the field types in SemaInit. 9954 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9955 RecordDecl::field_iterator Field = Record->field_begin(); 9956 if (Field == Record->field_end()) 9957 return InvalidType(); 9958 9959 // Start pointer. 9960 if (!Field->getType()->isPointerType() || 9961 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9962 ArrayType->getElementType())) 9963 return InvalidType(); 9964 9965 // FIXME: What if the initializer_list type has base classes, etc? 9966 Result = APValue(APValue::UninitStruct(), 0, 2); 9967 Array.moveInto(Result.getStructField(0)); 9968 9969 if (++Field == Record->field_end()) 9970 return InvalidType(); 9971 9972 if (Field->getType()->isPointerType() && 9973 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9974 ArrayType->getElementType())) { 9975 // End pointer. 9976 if (!HandleLValueArrayAdjustment(Info, E, Array, 9977 ArrayType->getElementType(), 9978 ArrayType->getSize().getZExtValue())) 9979 return false; 9980 Array.moveInto(Result.getStructField(1)); 9981 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9982 // Length. 9983 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9984 else 9985 return InvalidType(); 9986 9987 if (++Field != Record->field_end()) 9988 return InvalidType(); 9989 9990 return true; 9991 } 9992 9993 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9994 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9995 if (ClosureClass->isInvalidDecl()) 9996 return false; 9997 9998 const size_t NumFields = 9999 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10000 10001 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10002 E->capture_init_end()) && 10003 "The number of lambda capture initializers should equal the number of " 10004 "fields within the closure type"); 10005 10006 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10007 // Iterate through all the lambda's closure object's fields and initialize 10008 // them. 10009 auto *CaptureInitIt = E->capture_init_begin(); 10010 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10011 bool Success = true; 10012 for (const auto *Field : ClosureClass->fields()) { 10013 assert(CaptureInitIt != E->capture_init_end()); 10014 // Get the initializer for this field 10015 Expr *const CurFieldInit = *CaptureInitIt++; 10016 10017 // If there is no initializer, either this is a VLA or an error has 10018 // occurred. 10019 if (!CurFieldInit) 10020 return Error(E); 10021 10022 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10023 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 10024 if (!Info.keepEvaluatingAfterFailure()) 10025 return false; 10026 Success = false; 10027 } 10028 ++CaptureIt; 10029 } 10030 return Success; 10031 } 10032 10033 static bool EvaluateRecord(const Expr *E, const LValue &This, 10034 APValue &Result, EvalInfo &Info) { 10035 assert(!E->isValueDependent()); 10036 assert(E->isRValue() && E->getType()->isRecordType() && 10037 "can't evaluate expression as a record rvalue"); 10038 return RecordExprEvaluator(Info, This, Result).Visit(E); 10039 } 10040 10041 //===----------------------------------------------------------------------===// 10042 // Temporary Evaluation 10043 // 10044 // Temporaries are represented in the AST as rvalues, but generally behave like 10045 // lvalues. The full-object of which the temporary is a subobject is implicitly 10046 // materialized so that a reference can bind to it. 10047 //===----------------------------------------------------------------------===// 10048 namespace { 10049 class TemporaryExprEvaluator 10050 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10051 public: 10052 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10053 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10054 10055 /// Visit an expression which constructs the value of this temporary. 10056 bool VisitConstructExpr(const Expr *E) { 10057 APValue &Value = Info.CurrentCall->createTemporary( 10058 E, E->getType(), ScopeKind::FullExpression, Result); 10059 return EvaluateInPlace(Value, Info, Result, E); 10060 } 10061 10062 bool VisitCastExpr(const CastExpr *E) { 10063 switch (E->getCastKind()) { 10064 default: 10065 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10066 10067 case CK_ConstructorConversion: 10068 return VisitConstructExpr(E->getSubExpr()); 10069 } 10070 } 10071 bool VisitInitListExpr(const InitListExpr *E) { 10072 return VisitConstructExpr(E); 10073 } 10074 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10075 return VisitConstructExpr(E); 10076 } 10077 bool VisitCallExpr(const CallExpr *E) { 10078 return VisitConstructExpr(E); 10079 } 10080 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10081 return VisitConstructExpr(E); 10082 } 10083 bool VisitLambdaExpr(const LambdaExpr *E) { 10084 return VisitConstructExpr(E); 10085 } 10086 }; 10087 } // end anonymous namespace 10088 10089 /// Evaluate an expression of record type as a temporary. 10090 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10091 assert(!E->isValueDependent()); 10092 assert(E->isRValue() && E->getType()->isRecordType()); 10093 return TemporaryExprEvaluator(Info, Result).Visit(E); 10094 } 10095 10096 //===----------------------------------------------------------------------===// 10097 // Vector Evaluation 10098 //===----------------------------------------------------------------------===// 10099 10100 namespace { 10101 class VectorExprEvaluator 10102 : public ExprEvaluatorBase<VectorExprEvaluator> { 10103 APValue &Result; 10104 public: 10105 10106 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10107 : ExprEvaluatorBaseTy(info), Result(Result) {} 10108 10109 bool Success(ArrayRef<APValue> V, const Expr *E) { 10110 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10111 // FIXME: remove this APValue copy. 10112 Result = APValue(V.data(), V.size()); 10113 return true; 10114 } 10115 bool Success(const APValue &V, const Expr *E) { 10116 assert(V.isVector()); 10117 Result = V; 10118 return true; 10119 } 10120 bool ZeroInitialization(const Expr *E); 10121 10122 bool VisitUnaryReal(const UnaryOperator *E) 10123 { return Visit(E->getSubExpr()); } 10124 bool VisitCastExpr(const CastExpr* E); 10125 bool VisitInitListExpr(const InitListExpr *E); 10126 bool VisitUnaryImag(const UnaryOperator *E); 10127 bool VisitBinaryOperator(const BinaryOperator *E); 10128 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10129 // conditional select), shufflevector, ExtVectorElementExpr 10130 }; 10131 } // end anonymous namespace 10132 10133 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10134 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 10135 return VectorExprEvaluator(Info, Result).Visit(E); 10136 } 10137 10138 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10139 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10140 unsigned NElts = VTy->getNumElements(); 10141 10142 const Expr *SE = E->getSubExpr(); 10143 QualType SETy = SE->getType(); 10144 10145 switch (E->getCastKind()) { 10146 case CK_VectorSplat: { 10147 APValue Val = APValue(); 10148 if (SETy->isIntegerType()) { 10149 APSInt IntResult; 10150 if (!EvaluateInteger(SE, IntResult, Info)) 10151 return false; 10152 Val = APValue(std::move(IntResult)); 10153 } else if (SETy->isRealFloatingType()) { 10154 APFloat FloatResult(0.0); 10155 if (!EvaluateFloat(SE, FloatResult, Info)) 10156 return false; 10157 Val = APValue(std::move(FloatResult)); 10158 } else { 10159 return Error(E); 10160 } 10161 10162 // Splat and create vector APValue. 10163 SmallVector<APValue, 4> Elts(NElts, Val); 10164 return Success(Elts, E); 10165 } 10166 case CK_BitCast: { 10167 // Evaluate the operand into an APInt we can extract from. 10168 llvm::APInt SValInt; 10169 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10170 return false; 10171 // Extract the elements 10172 QualType EltTy = VTy->getElementType(); 10173 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10174 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10175 SmallVector<APValue, 4> Elts; 10176 if (EltTy->isRealFloatingType()) { 10177 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10178 unsigned FloatEltSize = EltSize; 10179 if (&Sem == &APFloat::x87DoubleExtended()) 10180 FloatEltSize = 80; 10181 for (unsigned i = 0; i < NElts; i++) { 10182 llvm::APInt Elt; 10183 if (BigEndian) 10184 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10185 else 10186 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10187 Elts.push_back(APValue(APFloat(Sem, Elt))); 10188 } 10189 } else if (EltTy->isIntegerType()) { 10190 for (unsigned i = 0; i < NElts; i++) { 10191 llvm::APInt Elt; 10192 if (BigEndian) 10193 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10194 else 10195 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10196 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 10197 } 10198 } else { 10199 return Error(E); 10200 } 10201 return Success(Elts, E); 10202 } 10203 default: 10204 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10205 } 10206 } 10207 10208 bool 10209 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10210 const VectorType *VT = E->getType()->castAs<VectorType>(); 10211 unsigned NumInits = E->getNumInits(); 10212 unsigned NumElements = VT->getNumElements(); 10213 10214 QualType EltTy = VT->getElementType(); 10215 SmallVector<APValue, 4> Elements; 10216 10217 // The number of initializers can be less than the number of 10218 // vector elements. For OpenCL, this can be due to nested vector 10219 // initialization. For GCC compatibility, missing trailing elements 10220 // should be initialized with zeroes. 10221 unsigned CountInits = 0, CountElts = 0; 10222 while (CountElts < NumElements) { 10223 // Handle nested vector initialization. 10224 if (CountInits < NumInits 10225 && E->getInit(CountInits)->getType()->isVectorType()) { 10226 APValue v; 10227 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10228 return Error(E); 10229 unsigned vlen = v.getVectorLength(); 10230 for (unsigned j = 0; j < vlen; j++) 10231 Elements.push_back(v.getVectorElt(j)); 10232 CountElts += vlen; 10233 } else if (EltTy->isIntegerType()) { 10234 llvm::APSInt sInt(32); 10235 if (CountInits < NumInits) { 10236 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10237 return false; 10238 } else // trailing integer zero. 10239 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10240 Elements.push_back(APValue(sInt)); 10241 CountElts++; 10242 } else { 10243 llvm::APFloat f(0.0); 10244 if (CountInits < NumInits) { 10245 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10246 return false; 10247 } else // trailing float zero. 10248 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10249 Elements.push_back(APValue(f)); 10250 CountElts++; 10251 } 10252 CountInits++; 10253 } 10254 return Success(Elements, E); 10255 } 10256 10257 bool 10258 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10259 const auto *VT = E->getType()->castAs<VectorType>(); 10260 QualType EltTy = VT->getElementType(); 10261 APValue ZeroElement; 10262 if (EltTy->isIntegerType()) 10263 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10264 else 10265 ZeroElement = 10266 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10267 10268 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10269 return Success(Elements, E); 10270 } 10271 10272 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10273 VisitIgnoredValue(E->getSubExpr()); 10274 return ZeroInitialization(E); 10275 } 10276 10277 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10278 BinaryOperatorKind Op = E->getOpcode(); 10279 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10280 "Operation not supported on vector types"); 10281 10282 if (Op == BO_Comma) 10283 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10284 10285 Expr *LHS = E->getLHS(); 10286 Expr *RHS = E->getRHS(); 10287 10288 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10289 "Must both be vector types"); 10290 // Checking JUST the types are the same would be fine, except shifts don't 10291 // need to have their types be the same (since you always shift by an int). 10292 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10293 E->getType()->getAs<VectorType>()->getNumElements() && 10294 RHS->getType()->getAs<VectorType>()->getNumElements() == 10295 E->getType()->getAs<VectorType>()->getNumElements() && 10296 "All operands must be the same size."); 10297 10298 APValue LHSValue; 10299 APValue RHSValue; 10300 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10301 if (!LHSOK && !Info.noteFailure()) 10302 return false; 10303 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10304 return false; 10305 10306 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10307 return false; 10308 10309 return Success(LHSValue, E); 10310 } 10311 10312 //===----------------------------------------------------------------------===// 10313 // Array Evaluation 10314 //===----------------------------------------------------------------------===// 10315 10316 namespace { 10317 class ArrayExprEvaluator 10318 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10319 const LValue &This; 10320 APValue &Result; 10321 public: 10322 10323 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10324 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10325 10326 bool Success(const APValue &V, const Expr *E) { 10327 assert(V.isArray() && "expected array"); 10328 Result = V; 10329 return true; 10330 } 10331 10332 bool ZeroInitialization(const Expr *E) { 10333 const ConstantArrayType *CAT = 10334 Info.Ctx.getAsConstantArrayType(E->getType()); 10335 if (!CAT) { 10336 if (E->getType()->isIncompleteArrayType()) { 10337 // We can be asked to zero-initialize a flexible array member; this 10338 // is represented as an ImplicitValueInitExpr of incomplete array 10339 // type. In this case, the array has zero elements. 10340 Result = APValue(APValue::UninitArray(), 0, 0); 10341 return true; 10342 } 10343 // FIXME: We could handle VLAs here. 10344 return Error(E); 10345 } 10346 10347 Result = APValue(APValue::UninitArray(), 0, 10348 CAT->getSize().getZExtValue()); 10349 if (!Result.hasArrayFiller()) return true; 10350 10351 // Zero-initialize all elements. 10352 LValue Subobject = This; 10353 Subobject.addArray(Info, E, CAT); 10354 ImplicitValueInitExpr VIE(CAT->getElementType()); 10355 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10356 } 10357 10358 bool VisitCallExpr(const CallExpr *E) { 10359 return handleCallExpr(E, Result, &This); 10360 } 10361 bool VisitInitListExpr(const InitListExpr *E, 10362 QualType AllocType = QualType()); 10363 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10364 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10365 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10366 const LValue &Subobject, 10367 APValue *Value, QualType Type); 10368 bool VisitStringLiteral(const StringLiteral *E, 10369 QualType AllocType = QualType()) { 10370 expandStringLiteral(Info, E, Result, AllocType); 10371 return true; 10372 } 10373 }; 10374 } // end anonymous namespace 10375 10376 static bool EvaluateArray(const Expr *E, const LValue &This, 10377 APValue &Result, EvalInfo &Info) { 10378 assert(!E->isValueDependent()); 10379 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10380 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10381 } 10382 10383 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10384 APValue &Result, const InitListExpr *ILE, 10385 QualType AllocType) { 10386 assert(!ILE->isValueDependent()); 10387 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10388 "not an array rvalue"); 10389 return ArrayExprEvaluator(Info, This, Result) 10390 .VisitInitListExpr(ILE, AllocType); 10391 } 10392 10393 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10394 APValue &Result, 10395 const CXXConstructExpr *CCE, 10396 QualType AllocType) { 10397 assert(!CCE->isValueDependent()); 10398 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10399 "not an array rvalue"); 10400 return ArrayExprEvaluator(Info, This, Result) 10401 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10402 } 10403 10404 // Return true iff the given array filler may depend on the element index. 10405 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10406 // For now, just allow non-class value-initialization and initialization 10407 // lists comprised of them. 10408 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10409 return false; 10410 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10411 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10412 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10413 return true; 10414 } 10415 return false; 10416 } 10417 return true; 10418 } 10419 10420 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10421 QualType AllocType) { 10422 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10423 AllocType.isNull() ? E->getType() : AllocType); 10424 if (!CAT) 10425 return Error(E); 10426 10427 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10428 // an appropriately-typed string literal enclosed in braces. 10429 if (E->isStringLiteralInit()) { 10430 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10431 // FIXME: Support ObjCEncodeExpr here once we support it in 10432 // ArrayExprEvaluator generally. 10433 if (!SL) 10434 return Error(E); 10435 return VisitStringLiteral(SL, AllocType); 10436 } 10437 10438 bool Success = true; 10439 10440 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10441 "zero-initialized array shouldn't have any initialized elts"); 10442 APValue Filler; 10443 if (Result.isArray() && Result.hasArrayFiller()) 10444 Filler = Result.getArrayFiller(); 10445 10446 unsigned NumEltsToInit = E->getNumInits(); 10447 unsigned NumElts = CAT->getSize().getZExtValue(); 10448 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10449 10450 // If the initializer might depend on the array index, run it for each 10451 // array element. 10452 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10453 NumEltsToInit = NumElts; 10454 10455 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10456 << NumEltsToInit << ".\n"); 10457 10458 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10459 10460 // If the array was previously zero-initialized, preserve the 10461 // zero-initialized values. 10462 if (Filler.hasValue()) { 10463 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10464 Result.getArrayInitializedElt(I) = Filler; 10465 if (Result.hasArrayFiller()) 10466 Result.getArrayFiller() = Filler; 10467 } 10468 10469 LValue Subobject = This; 10470 Subobject.addArray(Info, E, CAT); 10471 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10472 const Expr *Init = 10473 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10474 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10475 Info, Subobject, Init) || 10476 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10477 CAT->getElementType(), 1)) { 10478 if (!Info.noteFailure()) 10479 return false; 10480 Success = false; 10481 } 10482 } 10483 10484 if (!Result.hasArrayFiller()) 10485 return Success; 10486 10487 // If we get here, we have a trivial filler, which we can just evaluate 10488 // once and splat over the rest of the array elements. 10489 assert(FillerExpr && "no array filler for incomplete init list"); 10490 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10491 FillerExpr) && Success; 10492 } 10493 10494 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10495 LValue CommonLV; 10496 if (E->getCommonExpr() && 10497 !Evaluate(Info.CurrentCall->createTemporary( 10498 E->getCommonExpr(), 10499 getStorageType(Info.Ctx, E->getCommonExpr()), 10500 ScopeKind::FullExpression, CommonLV), 10501 Info, E->getCommonExpr()->getSourceExpr())) 10502 return false; 10503 10504 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10505 10506 uint64_t Elements = CAT->getSize().getZExtValue(); 10507 Result = APValue(APValue::UninitArray(), Elements, Elements); 10508 10509 LValue Subobject = This; 10510 Subobject.addArray(Info, E, CAT); 10511 10512 bool Success = true; 10513 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10514 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10515 Info, Subobject, E->getSubExpr()) || 10516 !HandleLValueArrayAdjustment(Info, E, Subobject, 10517 CAT->getElementType(), 1)) { 10518 if (!Info.noteFailure()) 10519 return false; 10520 Success = false; 10521 } 10522 } 10523 10524 return Success; 10525 } 10526 10527 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10528 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10529 } 10530 10531 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10532 const LValue &Subobject, 10533 APValue *Value, 10534 QualType Type) { 10535 bool HadZeroInit = Value->hasValue(); 10536 10537 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10538 unsigned N = CAT->getSize().getZExtValue(); 10539 10540 // Preserve the array filler if we had prior zero-initialization. 10541 APValue Filler = 10542 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10543 : APValue(); 10544 10545 *Value = APValue(APValue::UninitArray(), N, N); 10546 10547 if (HadZeroInit) 10548 for (unsigned I = 0; I != N; ++I) 10549 Value->getArrayInitializedElt(I) = Filler; 10550 10551 // Initialize the elements. 10552 LValue ArrayElt = Subobject; 10553 ArrayElt.addArray(Info, E, CAT); 10554 for (unsigned I = 0; I != N; ++I) 10555 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10556 CAT->getElementType()) || 10557 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10558 CAT->getElementType(), 1)) 10559 return false; 10560 10561 return true; 10562 } 10563 10564 if (!Type->isRecordType()) 10565 return Error(E); 10566 10567 return RecordExprEvaluator(Info, Subobject, *Value) 10568 .VisitCXXConstructExpr(E, Type); 10569 } 10570 10571 //===----------------------------------------------------------------------===// 10572 // Integer Evaluation 10573 // 10574 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10575 // types and back in constant folding. Integer values are thus represented 10576 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10577 //===----------------------------------------------------------------------===// 10578 10579 namespace { 10580 class IntExprEvaluator 10581 : public ExprEvaluatorBase<IntExprEvaluator> { 10582 APValue &Result; 10583 public: 10584 IntExprEvaluator(EvalInfo &info, APValue &result) 10585 : ExprEvaluatorBaseTy(info), Result(result) {} 10586 10587 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10588 assert(E->getType()->isIntegralOrEnumerationType() && 10589 "Invalid evaluation result."); 10590 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10591 "Invalid evaluation result."); 10592 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10593 "Invalid evaluation result."); 10594 Result = APValue(SI); 10595 return true; 10596 } 10597 bool Success(const llvm::APSInt &SI, const Expr *E) { 10598 return Success(SI, E, Result); 10599 } 10600 10601 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10602 assert(E->getType()->isIntegralOrEnumerationType() && 10603 "Invalid evaluation result."); 10604 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10605 "Invalid evaluation result."); 10606 Result = APValue(APSInt(I)); 10607 Result.getInt().setIsUnsigned( 10608 E->getType()->isUnsignedIntegerOrEnumerationType()); 10609 return true; 10610 } 10611 bool Success(const llvm::APInt &I, const Expr *E) { 10612 return Success(I, E, Result); 10613 } 10614 10615 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10616 assert(E->getType()->isIntegralOrEnumerationType() && 10617 "Invalid evaluation result."); 10618 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10619 return true; 10620 } 10621 bool Success(uint64_t Value, const Expr *E) { 10622 return Success(Value, E, Result); 10623 } 10624 10625 bool Success(CharUnits Size, const Expr *E) { 10626 return Success(Size.getQuantity(), E); 10627 } 10628 10629 bool Success(const APValue &V, const Expr *E) { 10630 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10631 Result = V; 10632 return true; 10633 } 10634 return Success(V.getInt(), E); 10635 } 10636 10637 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10638 10639 //===--------------------------------------------------------------------===// 10640 // Visitor Methods 10641 //===--------------------------------------------------------------------===// 10642 10643 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10644 return Success(E->getValue(), E); 10645 } 10646 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10647 return Success(E->getValue(), E); 10648 } 10649 10650 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10651 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10652 if (CheckReferencedDecl(E, E->getDecl())) 10653 return true; 10654 10655 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10656 } 10657 bool VisitMemberExpr(const MemberExpr *E) { 10658 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10659 VisitIgnoredBaseExpression(E->getBase()); 10660 return true; 10661 } 10662 10663 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10664 } 10665 10666 bool VisitCallExpr(const CallExpr *E); 10667 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10668 bool VisitBinaryOperator(const BinaryOperator *E); 10669 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10670 bool VisitUnaryOperator(const UnaryOperator *E); 10671 10672 bool VisitCastExpr(const CastExpr* E); 10673 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10674 10675 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10676 return Success(E->getValue(), E); 10677 } 10678 10679 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10680 return Success(E->getValue(), E); 10681 } 10682 10683 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10684 if (Info.ArrayInitIndex == uint64_t(-1)) { 10685 // We were asked to evaluate this subexpression independent of the 10686 // enclosing ArrayInitLoopExpr. We can't do that. 10687 Info.FFDiag(E); 10688 return false; 10689 } 10690 return Success(Info.ArrayInitIndex, E); 10691 } 10692 10693 // Note, GNU defines __null as an integer, not a pointer. 10694 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10695 return ZeroInitialization(E); 10696 } 10697 10698 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10699 return Success(E->getValue(), E); 10700 } 10701 10702 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10703 return Success(E->getValue(), E); 10704 } 10705 10706 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10707 return Success(E->getValue(), E); 10708 } 10709 10710 bool VisitUnaryReal(const UnaryOperator *E); 10711 bool VisitUnaryImag(const UnaryOperator *E); 10712 10713 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10714 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10715 bool VisitSourceLocExpr(const SourceLocExpr *E); 10716 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10717 bool VisitRequiresExpr(const RequiresExpr *E); 10718 // FIXME: Missing: array subscript of vector, member of vector 10719 }; 10720 10721 class FixedPointExprEvaluator 10722 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10723 APValue &Result; 10724 10725 public: 10726 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10727 : ExprEvaluatorBaseTy(info), Result(result) {} 10728 10729 bool Success(const llvm::APInt &I, const Expr *E) { 10730 return Success( 10731 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10732 } 10733 10734 bool Success(uint64_t Value, const Expr *E) { 10735 return Success( 10736 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10737 } 10738 10739 bool Success(const APValue &V, const Expr *E) { 10740 return Success(V.getFixedPoint(), E); 10741 } 10742 10743 bool Success(const APFixedPoint &V, const Expr *E) { 10744 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10745 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10746 "Invalid evaluation result."); 10747 Result = APValue(V); 10748 return true; 10749 } 10750 10751 //===--------------------------------------------------------------------===// 10752 // Visitor Methods 10753 //===--------------------------------------------------------------------===// 10754 10755 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10756 return Success(E->getValue(), E); 10757 } 10758 10759 bool VisitCastExpr(const CastExpr *E); 10760 bool VisitUnaryOperator(const UnaryOperator *E); 10761 bool VisitBinaryOperator(const BinaryOperator *E); 10762 }; 10763 } // end anonymous namespace 10764 10765 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10766 /// produce either the integer value or a pointer. 10767 /// 10768 /// GCC has a heinous extension which folds casts between pointer types and 10769 /// pointer-sized integral types. We support this by allowing the evaluation of 10770 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10771 /// Some simple arithmetic on such values is supported (they are treated much 10772 /// like char*). 10773 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10774 EvalInfo &Info) { 10775 assert(!E->isValueDependent()); 10776 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10777 return IntExprEvaluator(Info, Result).Visit(E); 10778 } 10779 10780 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10781 assert(!E->isValueDependent()); 10782 APValue Val; 10783 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10784 return false; 10785 if (!Val.isInt()) { 10786 // FIXME: It would be better to produce the diagnostic for casting 10787 // a pointer to an integer. 10788 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10789 return false; 10790 } 10791 Result = Val.getInt(); 10792 return true; 10793 } 10794 10795 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10796 APValue Evaluated = E->EvaluateInContext( 10797 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10798 return Success(Evaluated, E); 10799 } 10800 10801 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10802 EvalInfo &Info) { 10803 assert(!E->isValueDependent()); 10804 if (E->getType()->isFixedPointType()) { 10805 APValue Val; 10806 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10807 return false; 10808 if (!Val.isFixedPoint()) 10809 return false; 10810 10811 Result = Val.getFixedPoint(); 10812 return true; 10813 } 10814 return false; 10815 } 10816 10817 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10818 EvalInfo &Info) { 10819 assert(!E->isValueDependent()); 10820 if (E->getType()->isIntegerType()) { 10821 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10822 APSInt Val; 10823 if (!EvaluateInteger(E, Val, Info)) 10824 return false; 10825 Result = APFixedPoint(Val, FXSema); 10826 return true; 10827 } else if (E->getType()->isFixedPointType()) { 10828 return EvaluateFixedPoint(E, Result, Info); 10829 } 10830 return false; 10831 } 10832 10833 /// Check whether the given declaration can be directly converted to an integral 10834 /// rvalue. If not, no diagnostic is produced; there are other things we can 10835 /// try. 10836 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10837 // Enums are integer constant exprs. 10838 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10839 // Check for signedness/width mismatches between E type and ECD value. 10840 bool SameSign = (ECD->getInitVal().isSigned() 10841 == E->getType()->isSignedIntegerOrEnumerationType()); 10842 bool SameWidth = (ECD->getInitVal().getBitWidth() 10843 == Info.Ctx.getIntWidth(E->getType())); 10844 if (SameSign && SameWidth) 10845 return Success(ECD->getInitVal(), E); 10846 else { 10847 // Get rid of mismatch (otherwise Success assertions will fail) 10848 // by computing a new value matching the type of E. 10849 llvm::APSInt Val = ECD->getInitVal(); 10850 if (!SameSign) 10851 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10852 if (!SameWidth) 10853 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10854 return Success(Val, E); 10855 } 10856 } 10857 return false; 10858 } 10859 10860 /// Values returned by __builtin_classify_type, chosen to match the values 10861 /// produced by GCC's builtin. 10862 enum class GCCTypeClass { 10863 None = -1, 10864 Void = 0, 10865 Integer = 1, 10866 // GCC reserves 2 for character types, but instead classifies them as 10867 // integers. 10868 Enum = 3, 10869 Bool = 4, 10870 Pointer = 5, 10871 // GCC reserves 6 for references, but appears to never use it (because 10872 // expressions never have reference type, presumably). 10873 PointerToDataMember = 7, 10874 RealFloat = 8, 10875 Complex = 9, 10876 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10877 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10878 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10879 // uses 12 for that purpose, same as for a class or struct. Maybe it 10880 // internally implements a pointer to member as a struct? Who knows. 10881 PointerToMemberFunction = 12, // Not a bug, see above. 10882 ClassOrStruct = 12, 10883 Union = 13, 10884 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10885 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10886 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10887 // literals. 10888 }; 10889 10890 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10891 /// as GCC. 10892 static GCCTypeClass 10893 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10894 assert(!T->isDependentType() && "unexpected dependent type"); 10895 10896 QualType CanTy = T.getCanonicalType(); 10897 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10898 10899 switch (CanTy->getTypeClass()) { 10900 #define TYPE(ID, BASE) 10901 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10902 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10903 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10904 #include "clang/AST/TypeNodes.inc" 10905 case Type::Auto: 10906 case Type::DeducedTemplateSpecialization: 10907 llvm_unreachable("unexpected non-canonical or dependent type"); 10908 10909 case Type::Builtin: 10910 switch (BT->getKind()) { 10911 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10912 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10913 case BuiltinType::ID: return GCCTypeClass::Integer; 10914 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10915 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10916 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10917 case BuiltinType::ID: break; 10918 #include "clang/AST/BuiltinTypes.def" 10919 case BuiltinType::Void: 10920 return GCCTypeClass::Void; 10921 10922 case BuiltinType::Bool: 10923 return GCCTypeClass::Bool; 10924 10925 case BuiltinType::Char_U: 10926 case BuiltinType::UChar: 10927 case BuiltinType::WChar_U: 10928 case BuiltinType::Char8: 10929 case BuiltinType::Char16: 10930 case BuiltinType::Char32: 10931 case BuiltinType::UShort: 10932 case BuiltinType::UInt: 10933 case BuiltinType::ULong: 10934 case BuiltinType::ULongLong: 10935 case BuiltinType::UInt128: 10936 return GCCTypeClass::Integer; 10937 10938 case BuiltinType::UShortAccum: 10939 case BuiltinType::UAccum: 10940 case BuiltinType::ULongAccum: 10941 case BuiltinType::UShortFract: 10942 case BuiltinType::UFract: 10943 case BuiltinType::ULongFract: 10944 case BuiltinType::SatUShortAccum: 10945 case BuiltinType::SatUAccum: 10946 case BuiltinType::SatULongAccum: 10947 case BuiltinType::SatUShortFract: 10948 case BuiltinType::SatUFract: 10949 case BuiltinType::SatULongFract: 10950 return GCCTypeClass::None; 10951 10952 case BuiltinType::NullPtr: 10953 10954 case BuiltinType::ObjCId: 10955 case BuiltinType::ObjCClass: 10956 case BuiltinType::ObjCSel: 10957 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10958 case BuiltinType::Id: 10959 #include "clang/Basic/OpenCLImageTypes.def" 10960 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10961 case BuiltinType::Id: 10962 #include "clang/Basic/OpenCLExtensionTypes.def" 10963 case BuiltinType::OCLSampler: 10964 case BuiltinType::OCLEvent: 10965 case BuiltinType::OCLClkEvent: 10966 case BuiltinType::OCLQueue: 10967 case BuiltinType::OCLReserveID: 10968 #define SVE_TYPE(Name, Id, SingletonId) \ 10969 case BuiltinType::Id: 10970 #include "clang/Basic/AArch64SVEACLETypes.def" 10971 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 10972 case BuiltinType::Id: 10973 #include "clang/Basic/PPCTypes.def" 10974 return GCCTypeClass::None; 10975 10976 case BuiltinType::Dependent: 10977 llvm_unreachable("unexpected dependent type"); 10978 }; 10979 llvm_unreachable("unexpected placeholder type"); 10980 10981 case Type::Enum: 10982 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10983 10984 case Type::Pointer: 10985 case Type::ConstantArray: 10986 case Type::VariableArray: 10987 case Type::IncompleteArray: 10988 case Type::FunctionNoProto: 10989 case Type::FunctionProto: 10990 return GCCTypeClass::Pointer; 10991 10992 case Type::MemberPointer: 10993 return CanTy->isMemberDataPointerType() 10994 ? GCCTypeClass::PointerToDataMember 10995 : GCCTypeClass::PointerToMemberFunction; 10996 10997 case Type::Complex: 10998 return GCCTypeClass::Complex; 10999 11000 case Type::Record: 11001 return CanTy->isUnionType() ? GCCTypeClass::Union 11002 : GCCTypeClass::ClassOrStruct; 11003 11004 case Type::Atomic: 11005 // GCC classifies _Atomic T the same as T. 11006 return EvaluateBuiltinClassifyType( 11007 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11008 11009 case Type::BlockPointer: 11010 case Type::Vector: 11011 case Type::ExtVector: 11012 case Type::ConstantMatrix: 11013 case Type::ObjCObject: 11014 case Type::ObjCInterface: 11015 case Type::ObjCObjectPointer: 11016 case Type::Pipe: 11017 case Type::ExtInt: 11018 // GCC classifies vectors as None. We follow its lead and classify all 11019 // other types that don't fit into the regular classification the same way. 11020 return GCCTypeClass::None; 11021 11022 case Type::LValueReference: 11023 case Type::RValueReference: 11024 llvm_unreachable("invalid type for expression"); 11025 } 11026 11027 llvm_unreachable("unexpected type class"); 11028 } 11029 11030 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11031 /// as GCC. 11032 static GCCTypeClass 11033 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11034 // If no argument was supplied, default to None. This isn't 11035 // ideal, however it is what gcc does. 11036 if (E->getNumArgs() == 0) 11037 return GCCTypeClass::None; 11038 11039 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11040 // being an ICE, but still folds it to a constant using the type of the first 11041 // argument. 11042 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11043 } 11044 11045 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11046 /// __builtin_constant_p when applied to the given pointer. 11047 /// 11048 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11049 /// or it points to the first character of a string literal. 11050 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11051 APValue::LValueBase Base = LV.getLValueBase(); 11052 if (Base.isNull()) { 11053 // A null base is acceptable. 11054 return true; 11055 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11056 if (!isa<StringLiteral>(E)) 11057 return false; 11058 return LV.getLValueOffset().isZero(); 11059 } else if (Base.is<TypeInfoLValue>()) { 11060 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11061 // evaluate to true. 11062 return true; 11063 } else { 11064 // Any other base is not constant enough for GCC. 11065 return false; 11066 } 11067 } 11068 11069 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11070 /// GCC as we can manage. 11071 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11072 // This evaluation is not permitted to have side-effects, so evaluate it in 11073 // a speculative evaluation context. 11074 SpeculativeEvaluationRAII SpeculativeEval(Info); 11075 11076 // Constant-folding is always enabled for the operand of __builtin_constant_p 11077 // (even when the enclosing evaluation context otherwise requires a strict 11078 // language-specific constant expression). 11079 FoldConstant Fold(Info, true); 11080 11081 QualType ArgType = Arg->getType(); 11082 11083 // __builtin_constant_p always has one operand. The rules which gcc follows 11084 // are not precisely documented, but are as follows: 11085 // 11086 // - If the operand is of integral, floating, complex or enumeration type, 11087 // and can be folded to a known value of that type, it returns 1. 11088 // - If the operand can be folded to a pointer to the first character 11089 // of a string literal (or such a pointer cast to an integral type) 11090 // or to a null pointer or an integer cast to a pointer, it returns 1. 11091 // 11092 // Otherwise, it returns 0. 11093 // 11094 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11095 // its support for this did not work prior to GCC 9 and is not yet well 11096 // understood. 11097 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11098 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11099 ArgType->isNullPtrType()) { 11100 APValue V; 11101 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11102 Fold.keepDiagnostics(); 11103 return false; 11104 } 11105 11106 // For a pointer (possibly cast to integer), there are special rules. 11107 if (V.getKind() == APValue::LValue) 11108 return EvaluateBuiltinConstantPForLValue(V); 11109 11110 // Otherwise, any constant value is good enough. 11111 return V.hasValue(); 11112 } 11113 11114 // Anything else isn't considered to be sufficiently constant. 11115 return false; 11116 } 11117 11118 /// Retrieves the "underlying object type" of the given expression, 11119 /// as used by __builtin_object_size. 11120 static QualType getObjectType(APValue::LValueBase B) { 11121 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11122 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11123 return VD->getType(); 11124 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11125 if (isa<CompoundLiteralExpr>(E)) 11126 return E->getType(); 11127 } else if (B.is<TypeInfoLValue>()) { 11128 return B.getTypeInfoType(); 11129 } else if (B.is<DynamicAllocLValue>()) { 11130 return B.getDynamicAllocType(); 11131 } 11132 11133 return QualType(); 11134 } 11135 11136 /// A more selective version of E->IgnoreParenCasts for 11137 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11138 /// to change the type of E. 11139 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11140 /// 11141 /// Always returns an RValue with a pointer representation. 11142 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11143 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 11144 11145 auto *NoParens = E->IgnoreParens(); 11146 auto *Cast = dyn_cast<CastExpr>(NoParens); 11147 if (Cast == nullptr) 11148 return NoParens; 11149 11150 // We only conservatively allow a few kinds of casts, because this code is 11151 // inherently a simple solution that seeks to support the common case. 11152 auto CastKind = Cast->getCastKind(); 11153 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11154 CastKind != CK_AddressSpaceConversion) 11155 return NoParens; 11156 11157 auto *SubExpr = Cast->getSubExpr(); 11158 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 11159 return NoParens; 11160 return ignorePointerCastsAndParens(SubExpr); 11161 } 11162 11163 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11164 /// record layout. e.g. 11165 /// struct { struct { int a, b; } fst, snd; } obj; 11166 /// obj.fst // no 11167 /// obj.snd // yes 11168 /// obj.fst.a // no 11169 /// obj.fst.b // no 11170 /// obj.snd.a // no 11171 /// obj.snd.b // yes 11172 /// 11173 /// Please note: this function is specialized for how __builtin_object_size 11174 /// views "objects". 11175 /// 11176 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11177 /// correct result, it will always return true. 11178 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11179 assert(!LVal.Designator.Invalid); 11180 11181 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11182 const RecordDecl *Parent = FD->getParent(); 11183 Invalid = Parent->isInvalidDecl(); 11184 if (Invalid || Parent->isUnion()) 11185 return true; 11186 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11187 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11188 }; 11189 11190 auto &Base = LVal.getLValueBase(); 11191 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11192 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11193 bool Invalid; 11194 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11195 return Invalid; 11196 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11197 for (auto *FD : IFD->chain()) { 11198 bool Invalid; 11199 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11200 return Invalid; 11201 } 11202 } 11203 } 11204 11205 unsigned I = 0; 11206 QualType BaseType = getType(Base); 11207 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11208 // If we don't know the array bound, conservatively assume we're looking at 11209 // the final array element. 11210 ++I; 11211 if (BaseType->isIncompleteArrayType()) 11212 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11213 else 11214 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11215 } 11216 11217 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11218 const auto &Entry = LVal.Designator.Entries[I]; 11219 if (BaseType->isArrayType()) { 11220 // Because __builtin_object_size treats arrays as objects, we can ignore 11221 // the index iff this is the last array in the Designator. 11222 if (I + 1 == E) 11223 return true; 11224 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11225 uint64_t Index = Entry.getAsArrayIndex(); 11226 if (Index + 1 != CAT->getSize()) 11227 return false; 11228 BaseType = CAT->getElementType(); 11229 } else if (BaseType->isAnyComplexType()) { 11230 const auto *CT = BaseType->castAs<ComplexType>(); 11231 uint64_t Index = Entry.getAsArrayIndex(); 11232 if (Index != 1) 11233 return false; 11234 BaseType = CT->getElementType(); 11235 } else if (auto *FD = getAsField(Entry)) { 11236 bool Invalid; 11237 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11238 return Invalid; 11239 BaseType = FD->getType(); 11240 } else { 11241 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11242 return false; 11243 } 11244 } 11245 return true; 11246 } 11247 11248 /// Tests to see if the LValue has a user-specified designator (that isn't 11249 /// necessarily valid). Note that this always returns 'true' if the LValue has 11250 /// an unsized array as its first designator entry, because there's currently no 11251 /// way to tell if the user typed *foo or foo[0]. 11252 static bool refersToCompleteObject(const LValue &LVal) { 11253 if (LVal.Designator.Invalid) 11254 return false; 11255 11256 if (!LVal.Designator.Entries.empty()) 11257 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11258 11259 if (!LVal.InvalidBase) 11260 return true; 11261 11262 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11263 // the LValueBase. 11264 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11265 return !E || !isa<MemberExpr>(E); 11266 } 11267 11268 /// Attempts to detect a user writing into a piece of memory that's impossible 11269 /// to figure out the size of by just using types. 11270 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11271 const SubobjectDesignator &Designator = LVal.Designator; 11272 // Notes: 11273 // - Users can only write off of the end when we have an invalid base. Invalid 11274 // bases imply we don't know where the memory came from. 11275 // - We used to be a bit more aggressive here; we'd only be conservative if 11276 // the array at the end was flexible, or if it had 0 or 1 elements. This 11277 // broke some common standard library extensions (PR30346), but was 11278 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11279 // with some sort of list. OTOH, it seems that GCC is always 11280 // conservative with the last element in structs (if it's an array), so our 11281 // current behavior is more compatible than an explicit list approach would 11282 // be. 11283 return LVal.InvalidBase && 11284 Designator.Entries.size() == Designator.MostDerivedPathLength && 11285 Designator.MostDerivedIsArrayElement && 11286 isDesignatorAtObjectEnd(Ctx, LVal); 11287 } 11288 11289 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11290 /// Fails if the conversion would cause loss of precision. 11291 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11292 CharUnits &Result) { 11293 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11294 if (Int.ugt(CharUnitsMax)) 11295 return false; 11296 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11297 return true; 11298 } 11299 11300 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11301 /// determine how many bytes exist from the beginning of the object to either 11302 /// the end of the current subobject, or the end of the object itself, depending 11303 /// on what the LValue looks like + the value of Type. 11304 /// 11305 /// If this returns false, the value of Result is undefined. 11306 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11307 unsigned Type, const LValue &LVal, 11308 CharUnits &EndOffset) { 11309 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11310 11311 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11312 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11313 return false; 11314 return HandleSizeof(Info, ExprLoc, Ty, Result); 11315 }; 11316 11317 // We want to evaluate the size of the entire object. This is a valid fallback 11318 // for when Type=1 and the designator is invalid, because we're asked for an 11319 // upper-bound. 11320 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11321 // Type=3 wants a lower bound, so we can't fall back to this. 11322 if (Type == 3 && !DetermineForCompleteObject) 11323 return false; 11324 11325 llvm::APInt APEndOffset; 11326 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11327 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11328 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11329 11330 if (LVal.InvalidBase) 11331 return false; 11332 11333 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11334 return CheckedHandleSizeof(BaseTy, EndOffset); 11335 } 11336 11337 // We want to evaluate the size of a subobject. 11338 const SubobjectDesignator &Designator = LVal.Designator; 11339 11340 // The following is a moderately common idiom in C: 11341 // 11342 // struct Foo { int a; char c[1]; }; 11343 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11344 // strcpy(&F->c[0], Bar); 11345 // 11346 // In order to not break too much legacy code, we need to support it. 11347 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11348 // If we can resolve this to an alloc_size call, we can hand that back, 11349 // because we know for certain how many bytes there are to write to. 11350 llvm::APInt APEndOffset; 11351 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11352 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11353 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11354 11355 // If we cannot determine the size of the initial allocation, then we can't 11356 // given an accurate upper-bound. However, we are still able to give 11357 // conservative lower-bounds for Type=3. 11358 if (Type == 1) 11359 return false; 11360 } 11361 11362 CharUnits BytesPerElem; 11363 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11364 return false; 11365 11366 // According to the GCC documentation, we want the size of the subobject 11367 // denoted by the pointer. But that's not quite right -- what we actually 11368 // want is the size of the immediately-enclosing array, if there is one. 11369 int64_t ElemsRemaining; 11370 if (Designator.MostDerivedIsArrayElement && 11371 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11372 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11373 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11374 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11375 } else { 11376 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11377 } 11378 11379 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11380 return true; 11381 } 11382 11383 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11384 /// returns true and stores the result in @p Size. 11385 /// 11386 /// If @p WasError is non-null, this will report whether the failure to evaluate 11387 /// is to be treated as an Error in IntExprEvaluator. 11388 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11389 EvalInfo &Info, uint64_t &Size) { 11390 // Determine the denoted object. 11391 LValue LVal; 11392 { 11393 // The operand of __builtin_object_size is never evaluated for side-effects. 11394 // If there are any, but we can determine the pointed-to object anyway, then 11395 // ignore the side-effects. 11396 SpeculativeEvaluationRAII SpeculativeEval(Info); 11397 IgnoreSideEffectsRAII Fold(Info); 11398 11399 if (E->isGLValue()) { 11400 // It's possible for us to be given GLValues if we're called via 11401 // Expr::tryEvaluateObjectSize. 11402 APValue RVal; 11403 if (!EvaluateAsRValue(Info, E, RVal)) 11404 return false; 11405 LVal.setFrom(Info.Ctx, RVal); 11406 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11407 /*InvalidBaseOK=*/true)) 11408 return false; 11409 } 11410 11411 // If we point outside of the object, there are no accessible bytes. 11412 if (LVal.getLValueOffset().isNegative() || 11413 ((Type & 1) && !LVal.Designator.isValidSubobject())) { 11414 Size = 0; 11415 return true; 11416 } 11417 11418 CharUnits EndOffset; 11419 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11420 return false; 11421 11422 // If we've fallen outside of the end offset, just pretend there's nothing to 11423 // write to/read from. 11424 if (EndOffset <= LVal.getLValueOffset()) 11425 Size = 0; 11426 else 11427 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11428 return true; 11429 } 11430 11431 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11432 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11433 return VisitBuiltinCallExpr(E, BuiltinOp); 11434 11435 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11436 } 11437 11438 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11439 APValue &Val, APSInt &Alignment) { 11440 QualType SrcTy = E->getArg(0)->getType(); 11441 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11442 return false; 11443 // Even though we are evaluating integer expressions we could get a pointer 11444 // argument for the __builtin_is_aligned() case. 11445 if (SrcTy->isPointerType()) { 11446 LValue Ptr; 11447 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11448 return false; 11449 Ptr.moveInto(Val); 11450 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11451 Info.FFDiag(E->getArg(0)); 11452 return false; 11453 } else { 11454 APSInt SrcInt; 11455 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11456 return false; 11457 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11458 "Bit widths must be the same"); 11459 Val = APValue(SrcInt); 11460 } 11461 assert(Val.hasValue()); 11462 return true; 11463 } 11464 11465 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11466 unsigned BuiltinOp) { 11467 switch (BuiltinOp) { 11468 default: 11469 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11470 11471 case Builtin::BI__builtin_dynamic_object_size: 11472 case Builtin::BI__builtin_object_size: { 11473 // The type was checked when we built the expression. 11474 unsigned Type = 11475 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11476 assert(Type <= 3 && "unexpected type"); 11477 11478 uint64_t Size; 11479 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11480 return Success(Size, E); 11481 11482 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11483 return Success((Type & 2) ? 0 : -1, E); 11484 11485 // Expression had no side effects, but we couldn't statically determine the 11486 // size of the referenced object. 11487 switch (Info.EvalMode) { 11488 case EvalInfo::EM_ConstantExpression: 11489 case EvalInfo::EM_ConstantFold: 11490 case EvalInfo::EM_IgnoreSideEffects: 11491 // Leave it to IR generation. 11492 return Error(E); 11493 case EvalInfo::EM_ConstantExpressionUnevaluated: 11494 // Reduce it to a constant now. 11495 return Success((Type & 2) ? 0 : -1, E); 11496 } 11497 11498 llvm_unreachable("unexpected EvalMode"); 11499 } 11500 11501 case Builtin::BI__builtin_os_log_format_buffer_size: { 11502 analyze_os_log::OSLogBufferLayout Layout; 11503 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11504 return Success(Layout.size().getQuantity(), E); 11505 } 11506 11507 case Builtin::BI__builtin_is_aligned: { 11508 APValue Src; 11509 APSInt Alignment; 11510 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11511 return false; 11512 if (Src.isLValue()) { 11513 // If we evaluated a pointer, check the minimum known alignment. 11514 LValue Ptr; 11515 Ptr.setFrom(Info.Ctx, Src); 11516 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11517 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11518 // We can return true if the known alignment at the computed offset is 11519 // greater than the requested alignment. 11520 assert(PtrAlign.isPowerOfTwo()); 11521 assert(Alignment.isPowerOf2()); 11522 if (PtrAlign.getQuantity() >= Alignment) 11523 return Success(1, E); 11524 // If the alignment is not known to be sufficient, some cases could still 11525 // be aligned at run time. However, if the requested alignment is less or 11526 // equal to the base alignment and the offset is not aligned, we know that 11527 // the run-time value can never be aligned. 11528 if (BaseAlignment.getQuantity() >= Alignment && 11529 PtrAlign.getQuantity() < Alignment) 11530 return Success(0, E); 11531 // Otherwise we can't infer whether the value is sufficiently aligned. 11532 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11533 // in cases where we can't fully evaluate the pointer. 11534 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11535 << Alignment; 11536 return false; 11537 } 11538 assert(Src.isInt()); 11539 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11540 } 11541 case Builtin::BI__builtin_align_up: { 11542 APValue Src; 11543 APSInt Alignment; 11544 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11545 return false; 11546 if (!Src.isInt()) 11547 return Error(E); 11548 APSInt AlignedVal = 11549 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11550 Src.getInt().isUnsigned()); 11551 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11552 return Success(AlignedVal, E); 11553 } 11554 case Builtin::BI__builtin_align_down: { 11555 APValue Src; 11556 APSInt Alignment; 11557 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11558 return false; 11559 if (!Src.isInt()) 11560 return Error(E); 11561 APSInt AlignedVal = 11562 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11563 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11564 return Success(AlignedVal, E); 11565 } 11566 11567 case Builtin::BI__builtin_bitreverse8: 11568 case Builtin::BI__builtin_bitreverse16: 11569 case Builtin::BI__builtin_bitreverse32: 11570 case Builtin::BI__builtin_bitreverse64: { 11571 APSInt Val; 11572 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11573 return false; 11574 11575 return Success(Val.reverseBits(), E); 11576 } 11577 11578 case Builtin::BI__builtin_bswap16: 11579 case Builtin::BI__builtin_bswap32: 11580 case Builtin::BI__builtin_bswap64: { 11581 APSInt Val; 11582 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11583 return false; 11584 11585 return Success(Val.byteSwap(), E); 11586 } 11587 11588 case Builtin::BI__builtin_classify_type: 11589 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11590 11591 case Builtin::BI__builtin_clrsb: 11592 case Builtin::BI__builtin_clrsbl: 11593 case Builtin::BI__builtin_clrsbll: { 11594 APSInt Val; 11595 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11596 return false; 11597 11598 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11599 } 11600 11601 case Builtin::BI__builtin_clz: 11602 case Builtin::BI__builtin_clzl: 11603 case Builtin::BI__builtin_clzll: 11604 case Builtin::BI__builtin_clzs: { 11605 APSInt Val; 11606 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11607 return false; 11608 if (!Val) 11609 return Error(E); 11610 11611 return Success(Val.countLeadingZeros(), E); 11612 } 11613 11614 case Builtin::BI__builtin_constant_p: { 11615 const Expr *Arg = E->getArg(0); 11616 if (EvaluateBuiltinConstantP(Info, Arg)) 11617 return Success(true, E); 11618 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11619 // Outside a constant context, eagerly evaluate to false in the presence 11620 // of side-effects in order to avoid -Wunsequenced false-positives in 11621 // a branch on __builtin_constant_p(expr). 11622 return Success(false, E); 11623 } 11624 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11625 return false; 11626 } 11627 11628 case Builtin::BI__builtin_is_constant_evaluated: { 11629 const auto *Callee = Info.CurrentCall->getCallee(); 11630 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11631 (Info.CallStackDepth == 1 || 11632 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11633 Callee->getIdentifier() && 11634 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11635 // FIXME: Find a better way to avoid duplicated diagnostics. 11636 if (Info.EvalStatus.Diag) 11637 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11638 : Info.CurrentCall->CallLoc, 11639 diag::warn_is_constant_evaluated_always_true_constexpr) 11640 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11641 : "std::is_constant_evaluated"); 11642 } 11643 11644 return Success(Info.InConstantContext, E); 11645 } 11646 11647 case Builtin::BI__builtin_ctz: 11648 case Builtin::BI__builtin_ctzl: 11649 case Builtin::BI__builtin_ctzll: 11650 case Builtin::BI__builtin_ctzs: { 11651 APSInt Val; 11652 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11653 return false; 11654 if (!Val) 11655 return Error(E); 11656 11657 return Success(Val.countTrailingZeros(), E); 11658 } 11659 11660 case Builtin::BI__builtin_eh_return_data_regno: { 11661 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11662 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11663 return Success(Operand, E); 11664 } 11665 11666 case Builtin::BI__builtin_expect: 11667 case Builtin::BI__builtin_expect_with_probability: 11668 return Visit(E->getArg(0)); 11669 11670 case Builtin::BI__builtin_ffs: 11671 case Builtin::BI__builtin_ffsl: 11672 case Builtin::BI__builtin_ffsll: { 11673 APSInt Val; 11674 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11675 return false; 11676 11677 unsigned N = Val.countTrailingZeros(); 11678 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11679 } 11680 11681 case Builtin::BI__builtin_fpclassify: { 11682 APFloat Val(0.0); 11683 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11684 return false; 11685 unsigned Arg; 11686 switch (Val.getCategory()) { 11687 case APFloat::fcNaN: Arg = 0; break; 11688 case APFloat::fcInfinity: Arg = 1; break; 11689 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11690 case APFloat::fcZero: Arg = 4; break; 11691 } 11692 return Visit(E->getArg(Arg)); 11693 } 11694 11695 case Builtin::BI__builtin_isinf_sign: { 11696 APFloat Val(0.0); 11697 return EvaluateFloat(E->getArg(0), Val, Info) && 11698 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11699 } 11700 11701 case Builtin::BI__builtin_isinf: { 11702 APFloat Val(0.0); 11703 return EvaluateFloat(E->getArg(0), Val, Info) && 11704 Success(Val.isInfinity() ? 1 : 0, E); 11705 } 11706 11707 case Builtin::BI__builtin_isfinite: { 11708 APFloat Val(0.0); 11709 return EvaluateFloat(E->getArg(0), Val, Info) && 11710 Success(Val.isFinite() ? 1 : 0, E); 11711 } 11712 11713 case Builtin::BI__builtin_isnan: { 11714 APFloat Val(0.0); 11715 return EvaluateFloat(E->getArg(0), Val, Info) && 11716 Success(Val.isNaN() ? 1 : 0, E); 11717 } 11718 11719 case Builtin::BI__builtin_isnormal: { 11720 APFloat Val(0.0); 11721 return EvaluateFloat(E->getArg(0), Val, Info) && 11722 Success(Val.isNormal() ? 1 : 0, E); 11723 } 11724 11725 case Builtin::BI__builtin_parity: 11726 case Builtin::BI__builtin_parityl: 11727 case Builtin::BI__builtin_parityll: { 11728 APSInt Val; 11729 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11730 return false; 11731 11732 return Success(Val.countPopulation() % 2, E); 11733 } 11734 11735 case Builtin::BI__builtin_popcount: 11736 case Builtin::BI__builtin_popcountl: 11737 case Builtin::BI__builtin_popcountll: { 11738 APSInt Val; 11739 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11740 return false; 11741 11742 return Success(Val.countPopulation(), E); 11743 } 11744 11745 case Builtin::BI__builtin_rotateleft8: 11746 case Builtin::BI__builtin_rotateleft16: 11747 case Builtin::BI__builtin_rotateleft32: 11748 case Builtin::BI__builtin_rotateleft64: 11749 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11750 case Builtin::BI_rotl16: 11751 case Builtin::BI_rotl: 11752 case Builtin::BI_lrotl: 11753 case Builtin::BI_rotl64: { 11754 APSInt Val, Amt; 11755 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11756 !EvaluateInteger(E->getArg(1), Amt, Info)) 11757 return false; 11758 11759 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11760 } 11761 11762 case Builtin::BI__builtin_rotateright8: 11763 case Builtin::BI__builtin_rotateright16: 11764 case Builtin::BI__builtin_rotateright32: 11765 case Builtin::BI__builtin_rotateright64: 11766 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11767 case Builtin::BI_rotr16: 11768 case Builtin::BI_rotr: 11769 case Builtin::BI_lrotr: 11770 case Builtin::BI_rotr64: { 11771 APSInt Val, Amt; 11772 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11773 !EvaluateInteger(E->getArg(1), Amt, Info)) 11774 return false; 11775 11776 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11777 } 11778 11779 case Builtin::BIstrlen: 11780 case Builtin::BIwcslen: 11781 // A call to strlen is not a constant expression. 11782 if (Info.getLangOpts().CPlusPlus11) 11783 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11784 << /*isConstexpr*/0 << /*isConstructor*/0 11785 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11786 else 11787 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11788 LLVM_FALLTHROUGH; 11789 case Builtin::BI__builtin_strlen: 11790 case Builtin::BI__builtin_wcslen: { 11791 // As an extension, we support __builtin_strlen() as a constant expression, 11792 // and support folding strlen() to a constant. 11793 LValue String; 11794 if (!EvaluatePointer(E->getArg(0), String, Info)) 11795 return false; 11796 11797 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11798 11799 // Fast path: if it's a string literal, search the string value. 11800 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11801 String.getLValueBase().dyn_cast<const Expr *>())) { 11802 // The string literal may have embedded null characters. Find the first 11803 // one and truncate there. 11804 StringRef Str = S->getBytes(); 11805 int64_t Off = String.Offset.getQuantity(); 11806 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11807 S->getCharByteWidth() == 1 && 11808 // FIXME: Add fast-path for wchar_t too. 11809 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11810 Str = Str.substr(Off); 11811 11812 StringRef::size_type Pos = Str.find(0); 11813 if (Pos != StringRef::npos) 11814 Str = Str.substr(0, Pos); 11815 11816 return Success(Str.size(), E); 11817 } 11818 11819 // Fall through to slow path to issue appropriate diagnostic. 11820 } 11821 11822 // Slow path: scan the bytes of the string looking for the terminating 0. 11823 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11824 APValue Char; 11825 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11826 !Char.isInt()) 11827 return false; 11828 if (!Char.getInt()) 11829 return Success(Strlen, E); 11830 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11831 return false; 11832 } 11833 } 11834 11835 case Builtin::BIstrcmp: 11836 case Builtin::BIwcscmp: 11837 case Builtin::BIstrncmp: 11838 case Builtin::BIwcsncmp: 11839 case Builtin::BImemcmp: 11840 case Builtin::BIbcmp: 11841 case Builtin::BIwmemcmp: 11842 // A call to strlen is not a constant expression. 11843 if (Info.getLangOpts().CPlusPlus11) 11844 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11845 << /*isConstexpr*/0 << /*isConstructor*/0 11846 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11847 else 11848 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11849 LLVM_FALLTHROUGH; 11850 case Builtin::BI__builtin_strcmp: 11851 case Builtin::BI__builtin_wcscmp: 11852 case Builtin::BI__builtin_strncmp: 11853 case Builtin::BI__builtin_wcsncmp: 11854 case Builtin::BI__builtin_memcmp: 11855 case Builtin::BI__builtin_bcmp: 11856 case Builtin::BI__builtin_wmemcmp: { 11857 LValue String1, String2; 11858 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11859 !EvaluatePointer(E->getArg(1), String2, Info)) 11860 return false; 11861 11862 uint64_t MaxLength = uint64_t(-1); 11863 if (BuiltinOp != Builtin::BIstrcmp && 11864 BuiltinOp != Builtin::BIwcscmp && 11865 BuiltinOp != Builtin::BI__builtin_strcmp && 11866 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11867 APSInt N; 11868 if (!EvaluateInteger(E->getArg(2), N, Info)) 11869 return false; 11870 MaxLength = N.getExtValue(); 11871 } 11872 11873 // Empty substrings compare equal by definition. 11874 if (MaxLength == 0u) 11875 return Success(0, E); 11876 11877 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11878 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11879 String1.Designator.Invalid || String2.Designator.Invalid) 11880 return false; 11881 11882 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11883 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11884 11885 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11886 BuiltinOp == Builtin::BIbcmp || 11887 BuiltinOp == Builtin::BI__builtin_memcmp || 11888 BuiltinOp == Builtin::BI__builtin_bcmp; 11889 11890 assert(IsRawByte || 11891 (Info.Ctx.hasSameUnqualifiedType( 11892 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11893 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11894 11895 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11896 // 'char8_t', but no other types. 11897 if (IsRawByte && 11898 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11899 // FIXME: Consider using our bit_cast implementation to support this. 11900 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11901 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11902 << CharTy1 << CharTy2; 11903 return false; 11904 } 11905 11906 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11907 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11908 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11909 Char1.isInt() && Char2.isInt(); 11910 }; 11911 const auto &AdvanceElems = [&] { 11912 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11913 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11914 }; 11915 11916 bool StopAtNull = 11917 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11918 BuiltinOp != Builtin::BIwmemcmp && 11919 BuiltinOp != Builtin::BI__builtin_memcmp && 11920 BuiltinOp != Builtin::BI__builtin_bcmp && 11921 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11922 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11923 BuiltinOp == Builtin::BIwcsncmp || 11924 BuiltinOp == Builtin::BIwmemcmp || 11925 BuiltinOp == Builtin::BI__builtin_wcscmp || 11926 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11927 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11928 11929 for (; MaxLength; --MaxLength) { 11930 APValue Char1, Char2; 11931 if (!ReadCurElems(Char1, Char2)) 11932 return false; 11933 if (Char1.getInt().ne(Char2.getInt())) { 11934 if (IsWide) // wmemcmp compares with wchar_t signedness. 11935 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11936 // memcmp always compares unsigned chars. 11937 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11938 } 11939 if (StopAtNull && !Char1.getInt()) 11940 return Success(0, E); 11941 assert(!(StopAtNull && !Char2.getInt())); 11942 if (!AdvanceElems()) 11943 return false; 11944 } 11945 // We hit the strncmp / memcmp limit. 11946 return Success(0, E); 11947 } 11948 11949 case Builtin::BI__atomic_always_lock_free: 11950 case Builtin::BI__atomic_is_lock_free: 11951 case Builtin::BI__c11_atomic_is_lock_free: { 11952 APSInt SizeVal; 11953 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11954 return false; 11955 11956 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11957 // of two less than or equal to the maximum inline atomic width, we know it 11958 // is lock-free. If the size isn't a power of two, or greater than the 11959 // maximum alignment where we promote atomics, we know it is not lock-free 11960 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11961 // the answer can only be determined at runtime; for example, 16-byte 11962 // atomics have lock-free implementations on some, but not all, 11963 // x86-64 processors. 11964 11965 // Check power-of-two. 11966 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11967 if (Size.isPowerOfTwo()) { 11968 // Check against inlining width. 11969 unsigned InlineWidthBits = 11970 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11971 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11972 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11973 Size == CharUnits::One() || 11974 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11975 Expr::NPC_NeverValueDependent)) 11976 // OK, we will inline appropriately-aligned operations of this size, 11977 // and _Atomic(T) is appropriately-aligned. 11978 return Success(1, E); 11979 11980 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11981 castAs<PointerType>()->getPointeeType(); 11982 if (!PointeeType->isIncompleteType() && 11983 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11984 // OK, we will inline operations on this object. 11985 return Success(1, E); 11986 } 11987 } 11988 } 11989 11990 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11991 Success(0, E) : Error(E); 11992 } 11993 case Builtin::BIomp_is_initial_device: 11994 // We can decide statically which value the runtime would return if called. 11995 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11996 case Builtin::BI__builtin_add_overflow: 11997 case Builtin::BI__builtin_sub_overflow: 11998 case Builtin::BI__builtin_mul_overflow: 11999 case Builtin::BI__builtin_sadd_overflow: 12000 case Builtin::BI__builtin_uadd_overflow: 12001 case Builtin::BI__builtin_uaddl_overflow: 12002 case Builtin::BI__builtin_uaddll_overflow: 12003 case Builtin::BI__builtin_usub_overflow: 12004 case Builtin::BI__builtin_usubl_overflow: 12005 case Builtin::BI__builtin_usubll_overflow: 12006 case Builtin::BI__builtin_umul_overflow: 12007 case Builtin::BI__builtin_umull_overflow: 12008 case Builtin::BI__builtin_umulll_overflow: 12009 case Builtin::BI__builtin_saddl_overflow: 12010 case Builtin::BI__builtin_saddll_overflow: 12011 case Builtin::BI__builtin_ssub_overflow: 12012 case Builtin::BI__builtin_ssubl_overflow: 12013 case Builtin::BI__builtin_ssubll_overflow: 12014 case Builtin::BI__builtin_smul_overflow: 12015 case Builtin::BI__builtin_smull_overflow: 12016 case Builtin::BI__builtin_smulll_overflow: { 12017 LValue ResultLValue; 12018 APSInt LHS, RHS; 12019 12020 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12021 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12022 !EvaluateInteger(E->getArg(1), RHS, Info) || 12023 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12024 return false; 12025 12026 APSInt Result; 12027 bool DidOverflow = false; 12028 12029 // If the types don't have to match, enlarge all 3 to the largest of them. 12030 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12031 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12032 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12033 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12034 ResultType->isSignedIntegerOrEnumerationType(); 12035 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12036 ResultType->isSignedIntegerOrEnumerationType(); 12037 uint64_t LHSSize = LHS.getBitWidth(); 12038 uint64_t RHSSize = RHS.getBitWidth(); 12039 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12040 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12041 12042 // Add an additional bit if the signedness isn't uniformly agreed to. We 12043 // could do this ONLY if there is a signed and an unsigned that both have 12044 // MaxBits, but the code to check that is pretty nasty. The issue will be 12045 // caught in the shrink-to-result later anyway. 12046 if (IsSigned && !AllSigned) 12047 ++MaxBits; 12048 12049 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12050 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12051 Result = APSInt(MaxBits, !IsSigned); 12052 } 12053 12054 // Find largest int. 12055 switch (BuiltinOp) { 12056 default: 12057 llvm_unreachable("Invalid value for BuiltinOp"); 12058 case Builtin::BI__builtin_add_overflow: 12059 case Builtin::BI__builtin_sadd_overflow: 12060 case Builtin::BI__builtin_saddl_overflow: 12061 case Builtin::BI__builtin_saddll_overflow: 12062 case Builtin::BI__builtin_uadd_overflow: 12063 case Builtin::BI__builtin_uaddl_overflow: 12064 case Builtin::BI__builtin_uaddll_overflow: 12065 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12066 : LHS.uadd_ov(RHS, DidOverflow); 12067 break; 12068 case Builtin::BI__builtin_sub_overflow: 12069 case Builtin::BI__builtin_ssub_overflow: 12070 case Builtin::BI__builtin_ssubl_overflow: 12071 case Builtin::BI__builtin_ssubll_overflow: 12072 case Builtin::BI__builtin_usub_overflow: 12073 case Builtin::BI__builtin_usubl_overflow: 12074 case Builtin::BI__builtin_usubll_overflow: 12075 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12076 : LHS.usub_ov(RHS, DidOverflow); 12077 break; 12078 case Builtin::BI__builtin_mul_overflow: 12079 case Builtin::BI__builtin_smul_overflow: 12080 case Builtin::BI__builtin_smull_overflow: 12081 case Builtin::BI__builtin_smulll_overflow: 12082 case Builtin::BI__builtin_umul_overflow: 12083 case Builtin::BI__builtin_umull_overflow: 12084 case Builtin::BI__builtin_umulll_overflow: 12085 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12086 : LHS.umul_ov(RHS, DidOverflow); 12087 break; 12088 } 12089 12090 // In the case where multiple sizes are allowed, truncate and see if 12091 // the values are the same. 12092 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12093 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12094 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12095 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12096 // since it will give us the behavior of a TruncOrSelf in the case where 12097 // its parameter <= its size. We previously set Result to be at least the 12098 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12099 // will work exactly like TruncOrSelf. 12100 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12101 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12102 12103 if (!APSInt::isSameValue(Temp, Result)) 12104 DidOverflow = true; 12105 Result = Temp; 12106 } 12107 12108 APValue APV{Result}; 12109 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12110 return false; 12111 return Success(DidOverflow, E); 12112 } 12113 } 12114 } 12115 12116 /// Determine whether this is a pointer past the end of the complete 12117 /// object referred to by the lvalue. 12118 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12119 const LValue &LV) { 12120 // A null pointer can be viewed as being "past the end" but we don't 12121 // choose to look at it that way here. 12122 if (!LV.getLValueBase()) 12123 return false; 12124 12125 // If the designator is valid and refers to a subobject, we're not pointing 12126 // past the end. 12127 if (!LV.getLValueDesignator().Invalid && 12128 !LV.getLValueDesignator().isOnePastTheEnd()) 12129 return false; 12130 12131 // A pointer to an incomplete type might be past-the-end if the type's size is 12132 // zero. We cannot tell because the type is incomplete. 12133 QualType Ty = getType(LV.getLValueBase()); 12134 if (Ty->isIncompleteType()) 12135 return true; 12136 12137 // We're a past-the-end pointer if we point to the byte after the object, 12138 // no matter what our type or path is. 12139 auto Size = Ctx.getTypeSizeInChars(Ty); 12140 return LV.getLValueOffset() == Size; 12141 } 12142 12143 namespace { 12144 12145 /// Data recursive integer evaluator of certain binary operators. 12146 /// 12147 /// We use a data recursive algorithm for binary operators so that we are able 12148 /// to handle extreme cases of chained binary operators without causing stack 12149 /// overflow. 12150 class DataRecursiveIntBinOpEvaluator { 12151 struct EvalResult { 12152 APValue Val; 12153 bool Failed; 12154 12155 EvalResult() : Failed(false) { } 12156 12157 void swap(EvalResult &RHS) { 12158 Val.swap(RHS.Val); 12159 Failed = RHS.Failed; 12160 RHS.Failed = false; 12161 } 12162 }; 12163 12164 struct Job { 12165 const Expr *E; 12166 EvalResult LHSResult; // meaningful only for binary operator expression. 12167 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12168 12169 Job() = default; 12170 Job(Job &&) = default; 12171 12172 void startSpeculativeEval(EvalInfo &Info) { 12173 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12174 } 12175 12176 private: 12177 SpeculativeEvaluationRAII SpecEvalRAII; 12178 }; 12179 12180 SmallVector<Job, 16> Queue; 12181 12182 IntExprEvaluator &IntEval; 12183 EvalInfo &Info; 12184 APValue &FinalResult; 12185 12186 public: 12187 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12188 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12189 12190 /// True if \param E is a binary operator that we are going to handle 12191 /// data recursively. 12192 /// We handle binary operators that are comma, logical, or that have operands 12193 /// with integral or enumeration type. 12194 static bool shouldEnqueue(const BinaryOperator *E) { 12195 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12196 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 12197 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12198 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12199 } 12200 12201 bool Traverse(const BinaryOperator *E) { 12202 enqueue(E); 12203 EvalResult PrevResult; 12204 while (!Queue.empty()) 12205 process(PrevResult); 12206 12207 if (PrevResult.Failed) return false; 12208 12209 FinalResult.swap(PrevResult.Val); 12210 return true; 12211 } 12212 12213 private: 12214 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12215 return IntEval.Success(Value, E, Result); 12216 } 12217 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12218 return IntEval.Success(Value, E, Result); 12219 } 12220 bool Error(const Expr *E) { 12221 return IntEval.Error(E); 12222 } 12223 bool Error(const Expr *E, diag::kind D) { 12224 return IntEval.Error(E, D); 12225 } 12226 12227 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12228 return Info.CCEDiag(E, D); 12229 } 12230 12231 // Returns true if visiting the RHS is necessary, false otherwise. 12232 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12233 bool &SuppressRHSDiags); 12234 12235 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12236 const BinaryOperator *E, APValue &Result); 12237 12238 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12239 Result.Failed = !Evaluate(Result.Val, Info, E); 12240 if (Result.Failed) 12241 Result.Val = APValue(); 12242 } 12243 12244 void process(EvalResult &Result); 12245 12246 void enqueue(const Expr *E) { 12247 E = E->IgnoreParens(); 12248 Queue.resize(Queue.size()+1); 12249 Queue.back().E = E; 12250 Queue.back().Kind = Job::AnyExprKind; 12251 } 12252 }; 12253 12254 } 12255 12256 bool DataRecursiveIntBinOpEvaluator:: 12257 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12258 bool &SuppressRHSDiags) { 12259 if (E->getOpcode() == BO_Comma) { 12260 // Ignore LHS but note if we could not evaluate it. 12261 if (LHSResult.Failed) 12262 return Info.noteSideEffect(); 12263 return true; 12264 } 12265 12266 if (E->isLogicalOp()) { 12267 bool LHSAsBool; 12268 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12269 // We were able to evaluate the LHS, see if we can get away with not 12270 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12271 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12272 Success(LHSAsBool, E, LHSResult.Val); 12273 return false; // Ignore RHS 12274 } 12275 } else { 12276 LHSResult.Failed = true; 12277 12278 // Since we weren't able to evaluate the left hand side, it 12279 // might have had side effects. 12280 if (!Info.noteSideEffect()) 12281 return false; 12282 12283 // We can't evaluate the LHS; however, sometimes the result 12284 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12285 // Don't ignore RHS and suppress diagnostics from this arm. 12286 SuppressRHSDiags = true; 12287 } 12288 12289 return true; 12290 } 12291 12292 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12293 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12294 12295 if (LHSResult.Failed && !Info.noteFailure()) 12296 return false; // Ignore RHS; 12297 12298 return true; 12299 } 12300 12301 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12302 bool IsSub) { 12303 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12304 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12305 // offsets. 12306 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12307 CharUnits &Offset = LVal.getLValueOffset(); 12308 uint64_t Offset64 = Offset.getQuantity(); 12309 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12310 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12311 : Offset64 + Index64); 12312 } 12313 12314 bool DataRecursiveIntBinOpEvaluator:: 12315 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12316 const BinaryOperator *E, APValue &Result) { 12317 if (E->getOpcode() == BO_Comma) { 12318 if (RHSResult.Failed) 12319 return false; 12320 Result = RHSResult.Val; 12321 return true; 12322 } 12323 12324 if (E->isLogicalOp()) { 12325 bool lhsResult, rhsResult; 12326 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12327 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12328 12329 if (LHSIsOK) { 12330 if (RHSIsOK) { 12331 if (E->getOpcode() == BO_LOr) 12332 return Success(lhsResult || rhsResult, E, Result); 12333 else 12334 return Success(lhsResult && rhsResult, E, Result); 12335 } 12336 } else { 12337 if (RHSIsOK) { 12338 // We can't evaluate the LHS; however, sometimes the result 12339 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12340 if (rhsResult == (E->getOpcode() == BO_LOr)) 12341 return Success(rhsResult, E, Result); 12342 } 12343 } 12344 12345 return false; 12346 } 12347 12348 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12349 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12350 12351 if (LHSResult.Failed || RHSResult.Failed) 12352 return false; 12353 12354 const APValue &LHSVal = LHSResult.Val; 12355 const APValue &RHSVal = RHSResult.Val; 12356 12357 // Handle cases like (unsigned long)&a + 4. 12358 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12359 Result = LHSVal; 12360 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12361 return true; 12362 } 12363 12364 // Handle cases like 4 + (unsigned long)&a 12365 if (E->getOpcode() == BO_Add && 12366 RHSVal.isLValue() && LHSVal.isInt()) { 12367 Result = RHSVal; 12368 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12369 return true; 12370 } 12371 12372 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12373 // Handle (intptr_t)&&A - (intptr_t)&&B. 12374 if (!LHSVal.getLValueOffset().isZero() || 12375 !RHSVal.getLValueOffset().isZero()) 12376 return false; 12377 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12378 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12379 if (!LHSExpr || !RHSExpr) 12380 return false; 12381 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12382 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12383 if (!LHSAddrExpr || !RHSAddrExpr) 12384 return false; 12385 // Make sure both labels come from the same function. 12386 if (LHSAddrExpr->getLabel()->getDeclContext() != 12387 RHSAddrExpr->getLabel()->getDeclContext()) 12388 return false; 12389 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12390 return true; 12391 } 12392 12393 // All the remaining cases expect both operands to be an integer 12394 if (!LHSVal.isInt() || !RHSVal.isInt()) 12395 return Error(E); 12396 12397 // Set up the width and signedness manually, in case it can't be deduced 12398 // from the operation we're performing. 12399 // FIXME: Don't do this in the cases where we can deduce it. 12400 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12401 E->getType()->isUnsignedIntegerOrEnumerationType()); 12402 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12403 RHSVal.getInt(), Value)) 12404 return false; 12405 return Success(Value, E, Result); 12406 } 12407 12408 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12409 Job &job = Queue.back(); 12410 12411 switch (job.Kind) { 12412 case Job::AnyExprKind: { 12413 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12414 if (shouldEnqueue(Bop)) { 12415 job.Kind = Job::BinOpKind; 12416 enqueue(Bop->getLHS()); 12417 return; 12418 } 12419 } 12420 12421 EvaluateExpr(job.E, Result); 12422 Queue.pop_back(); 12423 return; 12424 } 12425 12426 case Job::BinOpKind: { 12427 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12428 bool SuppressRHSDiags = false; 12429 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12430 Queue.pop_back(); 12431 return; 12432 } 12433 if (SuppressRHSDiags) 12434 job.startSpeculativeEval(Info); 12435 job.LHSResult.swap(Result); 12436 job.Kind = Job::BinOpVisitedLHSKind; 12437 enqueue(Bop->getRHS()); 12438 return; 12439 } 12440 12441 case Job::BinOpVisitedLHSKind: { 12442 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12443 EvalResult RHS; 12444 RHS.swap(Result); 12445 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12446 Queue.pop_back(); 12447 return; 12448 } 12449 } 12450 12451 llvm_unreachable("Invalid Job::Kind!"); 12452 } 12453 12454 namespace { 12455 /// Used when we determine that we should fail, but can keep evaluating prior to 12456 /// noting that we had a failure. 12457 class DelayedNoteFailureRAII { 12458 EvalInfo &Info; 12459 bool NoteFailure; 12460 12461 public: 12462 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12463 : Info(Info), NoteFailure(NoteFailure) {} 12464 ~DelayedNoteFailureRAII() { 12465 if (NoteFailure) { 12466 bool ContinueAfterFailure = Info.noteFailure(); 12467 (void)ContinueAfterFailure; 12468 assert(ContinueAfterFailure && 12469 "Shouldn't have kept evaluating on failure."); 12470 } 12471 } 12472 }; 12473 12474 enum class CmpResult { 12475 Unequal, 12476 Less, 12477 Equal, 12478 Greater, 12479 Unordered, 12480 }; 12481 } 12482 12483 template <class SuccessCB, class AfterCB> 12484 static bool 12485 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12486 SuccessCB &&Success, AfterCB &&DoAfter) { 12487 assert(!E->isValueDependent()); 12488 assert(E->isComparisonOp() && "expected comparison operator"); 12489 assert((E->getOpcode() == BO_Cmp || 12490 E->getType()->isIntegralOrEnumerationType()) && 12491 "unsupported binary expression evaluation"); 12492 auto Error = [&](const Expr *E) { 12493 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12494 return false; 12495 }; 12496 12497 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12498 bool IsEquality = E->isEqualityOp(); 12499 12500 QualType LHSTy = E->getLHS()->getType(); 12501 QualType RHSTy = E->getRHS()->getType(); 12502 12503 if (LHSTy->isIntegralOrEnumerationType() && 12504 RHSTy->isIntegralOrEnumerationType()) { 12505 APSInt LHS, RHS; 12506 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12507 if (!LHSOK && !Info.noteFailure()) 12508 return false; 12509 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12510 return false; 12511 if (LHS < RHS) 12512 return Success(CmpResult::Less, E); 12513 if (LHS > RHS) 12514 return Success(CmpResult::Greater, E); 12515 return Success(CmpResult::Equal, E); 12516 } 12517 12518 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12519 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12520 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12521 12522 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12523 if (!LHSOK && !Info.noteFailure()) 12524 return false; 12525 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12526 return false; 12527 if (LHSFX < RHSFX) 12528 return Success(CmpResult::Less, E); 12529 if (LHSFX > RHSFX) 12530 return Success(CmpResult::Greater, E); 12531 return Success(CmpResult::Equal, E); 12532 } 12533 12534 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12535 ComplexValue LHS, RHS; 12536 bool LHSOK; 12537 if (E->isAssignmentOp()) { 12538 LValue LV; 12539 EvaluateLValue(E->getLHS(), LV, Info); 12540 LHSOK = false; 12541 } else if (LHSTy->isRealFloatingType()) { 12542 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12543 if (LHSOK) { 12544 LHS.makeComplexFloat(); 12545 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12546 } 12547 } else { 12548 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12549 } 12550 if (!LHSOK && !Info.noteFailure()) 12551 return false; 12552 12553 if (E->getRHS()->getType()->isRealFloatingType()) { 12554 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12555 return false; 12556 RHS.makeComplexFloat(); 12557 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12558 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12559 return false; 12560 12561 if (LHS.isComplexFloat()) { 12562 APFloat::cmpResult CR_r = 12563 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12564 APFloat::cmpResult CR_i = 12565 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12566 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12567 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12568 } else { 12569 assert(IsEquality && "invalid complex comparison"); 12570 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12571 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12572 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12573 } 12574 } 12575 12576 if (LHSTy->isRealFloatingType() && 12577 RHSTy->isRealFloatingType()) { 12578 APFloat RHS(0.0), LHS(0.0); 12579 12580 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12581 if (!LHSOK && !Info.noteFailure()) 12582 return false; 12583 12584 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12585 return false; 12586 12587 assert(E->isComparisonOp() && "Invalid binary operator!"); 12588 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12589 if (!Info.InConstantContext && 12590 APFloatCmpResult == APFloat::cmpUnordered && 12591 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12592 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12593 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12594 return false; 12595 } 12596 auto GetCmpRes = [&]() { 12597 switch (APFloatCmpResult) { 12598 case APFloat::cmpEqual: 12599 return CmpResult::Equal; 12600 case APFloat::cmpLessThan: 12601 return CmpResult::Less; 12602 case APFloat::cmpGreaterThan: 12603 return CmpResult::Greater; 12604 case APFloat::cmpUnordered: 12605 return CmpResult::Unordered; 12606 } 12607 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12608 }; 12609 return Success(GetCmpRes(), E); 12610 } 12611 12612 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12613 LValue LHSValue, RHSValue; 12614 12615 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12616 if (!LHSOK && !Info.noteFailure()) 12617 return false; 12618 12619 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12620 return false; 12621 12622 // Reject differing bases from the normal codepath; we special-case 12623 // comparisons to null. 12624 if (!HasSameBase(LHSValue, RHSValue)) { 12625 // Inequalities and subtractions between unrelated pointers have 12626 // unspecified or undefined behavior. 12627 if (!IsEquality) { 12628 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12629 return false; 12630 } 12631 // A constant address may compare equal to the address of a symbol. 12632 // The one exception is that address of an object cannot compare equal 12633 // to a null pointer constant. 12634 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12635 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12636 return Error(E); 12637 // It's implementation-defined whether distinct literals will have 12638 // distinct addresses. In clang, the result of such a comparison is 12639 // unspecified, so it is not a constant expression. However, we do know 12640 // that the address of a literal will be non-null. 12641 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12642 LHSValue.Base && RHSValue.Base) 12643 return Error(E); 12644 // We can't tell whether weak symbols will end up pointing to the same 12645 // object. 12646 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12647 return Error(E); 12648 // We can't compare the address of the start of one object with the 12649 // past-the-end address of another object, per C++ DR1652. 12650 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12651 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12652 (RHSValue.Base && RHSValue.Offset.isZero() && 12653 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12654 return Error(E); 12655 // We can't tell whether an object is at the same address as another 12656 // zero sized object. 12657 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12658 (LHSValue.Base && isZeroSized(RHSValue))) 12659 return Error(E); 12660 return Success(CmpResult::Unequal, E); 12661 } 12662 12663 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12664 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12665 12666 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12667 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12668 12669 // C++11 [expr.rel]p3: 12670 // Pointers to void (after pointer conversions) can be compared, with a 12671 // result defined as follows: If both pointers represent the same 12672 // address or are both the null pointer value, the result is true if the 12673 // operator is <= or >= and false otherwise; otherwise the result is 12674 // unspecified. 12675 // We interpret this as applying to pointers to *cv* void. 12676 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12677 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12678 12679 // C++11 [expr.rel]p2: 12680 // - If two pointers point to non-static data members of the same object, 12681 // or to subobjects or array elements fo such members, recursively, the 12682 // pointer to the later declared member compares greater provided the 12683 // two members have the same access control and provided their class is 12684 // not a union. 12685 // [...] 12686 // - Otherwise pointer comparisons are unspecified. 12687 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12688 bool WasArrayIndex; 12689 unsigned Mismatch = FindDesignatorMismatch( 12690 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12691 // At the point where the designators diverge, the comparison has a 12692 // specified value if: 12693 // - we are comparing array indices 12694 // - we are comparing fields of a union, or fields with the same access 12695 // Otherwise, the result is unspecified and thus the comparison is not a 12696 // constant expression. 12697 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12698 Mismatch < RHSDesignator.Entries.size()) { 12699 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12700 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12701 if (!LF && !RF) 12702 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12703 else if (!LF) 12704 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12705 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12706 << RF->getParent() << RF; 12707 else if (!RF) 12708 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12709 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12710 << LF->getParent() << LF; 12711 else if (!LF->getParent()->isUnion() && 12712 LF->getAccess() != RF->getAccess()) 12713 Info.CCEDiag(E, 12714 diag::note_constexpr_pointer_comparison_differing_access) 12715 << LF << LF->getAccess() << RF << RF->getAccess() 12716 << LF->getParent(); 12717 } 12718 } 12719 12720 // The comparison here must be unsigned, and performed with the same 12721 // width as the pointer. 12722 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12723 uint64_t CompareLHS = LHSOffset.getQuantity(); 12724 uint64_t CompareRHS = RHSOffset.getQuantity(); 12725 assert(PtrSize <= 64 && "Unexpected pointer width"); 12726 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12727 CompareLHS &= Mask; 12728 CompareRHS &= Mask; 12729 12730 // If there is a base and this is a relational operator, we can only 12731 // compare pointers within the object in question; otherwise, the result 12732 // depends on where the object is located in memory. 12733 if (!LHSValue.Base.isNull() && IsRelational) { 12734 QualType BaseTy = getType(LHSValue.Base); 12735 if (BaseTy->isIncompleteType()) 12736 return Error(E); 12737 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12738 uint64_t OffsetLimit = Size.getQuantity(); 12739 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12740 return Error(E); 12741 } 12742 12743 if (CompareLHS < CompareRHS) 12744 return Success(CmpResult::Less, E); 12745 if (CompareLHS > CompareRHS) 12746 return Success(CmpResult::Greater, E); 12747 return Success(CmpResult::Equal, E); 12748 } 12749 12750 if (LHSTy->isMemberPointerType()) { 12751 assert(IsEquality && "unexpected member pointer operation"); 12752 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12753 12754 MemberPtr LHSValue, RHSValue; 12755 12756 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12757 if (!LHSOK && !Info.noteFailure()) 12758 return false; 12759 12760 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12761 return false; 12762 12763 // C++11 [expr.eq]p2: 12764 // If both operands are null, they compare equal. Otherwise if only one is 12765 // null, they compare unequal. 12766 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12767 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12768 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12769 } 12770 12771 // Otherwise if either is a pointer to a virtual member function, the 12772 // result is unspecified. 12773 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12774 if (MD->isVirtual()) 12775 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12776 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12777 if (MD->isVirtual()) 12778 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12779 12780 // Otherwise they compare equal if and only if they would refer to the 12781 // same member of the same most derived object or the same subobject if 12782 // they were dereferenced with a hypothetical object of the associated 12783 // class type. 12784 bool Equal = LHSValue == RHSValue; 12785 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12786 } 12787 12788 if (LHSTy->isNullPtrType()) { 12789 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12790 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12791 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12792 // are compared, the result is true of the operator is <=, >= or ==, and 12793 // false otherwise. 12794 return Success(CmpResult::Equal, E); 12795 } 12796 12797 return DoAfter(); 12798 } 12799 12800 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12801 if (!CheckLiteralType(Info, E)) 12802 return false; 12803 12804 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12805 ComparisonCategoryResult CCR; 12806 switch (CR) { 12807 case CmpResult::Unequal: 12808 llvm_unreachable("should never produce Unequal for three-way comparison"); 12809 case CmpResult::Less: 12810 CCR = ComparisonCategoryResult::Less; 12811 break; 12812 case CmpResult::Equal: 12813 CCR = ComparisonCategoryResult::Equal; 12814 break; 12815 case CmpResult::Greater: 12816 CCR = ComparisonCategoryResult::Greater; 12817 break; 12818 case CmpResult::Unordered: 12819 CCR = ComparisonCategoryResult::Unordered; 12820 break; 12821 } 12822 // Evaluation succeeded. Lookup the information for the comparison category 12823 // type and fetch the VarDecl for the result. 12824 const ComparisonCategoryInfo &CmpInfo = 12825 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12826 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12827 // Check and evaluate the result as a constant expression. 12828 LValue LV; 12829 LV.set(VD); 12830 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12831 return false; 12832 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12833 ConstantExprKind::Normal); 12834 }; 12835 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12836 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12837 }); 12838 } 12839 12840 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12841 // We don't call noteFailure immediately because the assignment happens after 12842 // we evaluate LHS and RHS. 12843 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12844 return Error(E); 12845 12846 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12847 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12848 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12849 12850 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12851 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12852 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12853 12854 if (E->isComparisonOp()) { 12855 // Evaluate builtin binary comparisons by evaluating them as three-way 12856 // comparisons and then translating the result. 12857 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12858 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12859 "should only produce Unequal for equality comparisons"); 12860 bool IsEqual = CR == CmpResult::Equal, 12861 IsLess = CR == CmpResult::Less, 12862 IsGreater = CR == CmpResult::Greater; 12863 auto Op = E->getOpcode(); 12864 switch (Op) { 12865 default: 12866 llvm_unreachable("unsupported binary operator"); 12867 case BO_EQ: 12868 case BO_NE: 12869 return Success(IsEqual == (Op == BO_EQ), E); 12870 case BO_LT: 12871 return Success(IsLess, E); 12872 case BO_GT: 12873 return Success(IsGreater, E); 12874 case BO_LE: 12875 return Success(IsEqual || IsLess, E); 12876 case BO_GE: 12877 return Success(IsEqual || IsGreater, E); 12878 } 12879 }; 12880 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12881 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12882 }); 12883 } 12884 12885 QualType LHSTy = E->getLHS()->getType(); 12886 QualType RHSTy = E->getRHS()->getType(); 12887 12888 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12889 E->getOpcode() == BO_Sub) { 12890 LValue LHSValue, RHSValue; 12891 12892 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12893 if (!LHSOK && !Info.noteFailure()) 12894 return false; 12895 12896 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12897 return false; 12898 12899 // Reject differing bases from the normal codepath; we special-case 12900 // comparisons to null. 12901 if (!HasSameBase(LHSValue, RHSValue)) { 12902 // Handle &&A - &&B. 12903 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12904 return Error(E); 12905 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12906 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12907 if (!LHSExpr || !RHSExpr) 12908 return Error(E); 12909 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12910 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12911 if (!LHSAddrExpr || !RHSAddrExpr) 12912 return Error(E); 12913 // Make sure both labels come from the same function. 12914 if (LHSAddrExpr->getLabel()->getDeclContext() != 12915 RHSAddrExpr->getLabel()->getDeclContext()) 12916 return Error(E); 12917 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12918 } 12919 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12920 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12921 12922 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12923 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12924 12925 // C++11 [expr.add]p6: 12926 // Unless both pointers point to elements of the same array object, or 12927 // one past the last element of the array object, the behavior is 12928 // undefined. 12929 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12930 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12931 RHSDesignator)) 12932 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12933 12934 QualType Type = E->getLHS()->getType(); 12935 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12936 12937 CharUnits ElementSize; 12938 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12939 return false; 12940 12941 // As an extension, a type may have zero size (empty struct or union in 12942 // C, array of zero length). Pointer subtraction in such cases has 12943 // undefined behavior, so is not constant. 12944 if (ElementSize.isZero()) { 12945 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12946 << ElementType; 12947 return false; 12948 } 12949 12950 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12951 // and produce incorrect results when it overflows. Such behavior 12952 // appears to be non-conforming, but is common, so perhaps we should 12953 // assume the standard intended for such cases to be undefined behavior 12954 // and check for them. 12955 12956 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12957 // overflow in the final conversion to ptrdiff_t. 12958 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12959 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12960 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12961 false); 12962 APSInt TrueResult = (LHS - RHS) / ElemSize; 12963 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12964 12965 if (Result.extend(65) != TrueResult && 12966 !HandleOverflow(Info, E, TrueResult, E->getType())) 12967 return false; 12968 return Success(Result, E); 12969 } 12970 12971 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12972 } 12973 12974 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12975 /// a result as the expression's type. 12976 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12977 const UnaryExprOrTypeTraitExpr *E) { 12978 switch(E->getKind()) { 12979 case UETT_PreferredAlignOf: 12980 case UETT_AlignOf: { 12981 if (E->isArgumentType()) 12982 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12983 E); 12984 else 12985 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12986 E); 12987 } 12988 12989 case UETT_VecStep: { 12990 QualType Ty = E->getTypeOfArgument(); 12991 12992 if (Ty->isVectorType()) { 12993 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12994 12995 // The vec_step built-in functions that take a 3-component 12996 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12997 if (n == 3) 12998 n = 4; 12999 13000 return Success(n, E); 13001 } else 13002 return Success(1, E); 13003 } 13004 13005 case UETT_SizeOf: { 13006 QualType SrcTy = E->getTypeOfArgument(); 13007 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13008 // the result is the size of the referenced type." 13009 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13010 SrcTy = Ref->getPointeeType(); 13011 13012 CharUnits Sizeof; 13013 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13014 return false; 13015 return Success(Sizeof, E); 13016 } 13017 case UETT_OpenMPRequiredSimdAlign: 13018 assert(E->isArgumentType()); 13019 return Success( 13020 Info.Ctx.toCharUnitsFromBits( 13021 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13022 .getQuantity(), 13023 E); 13024 } 13025 13026 llvm_unreachable("unknown expr/type trait"); 13027 } 13028 13029 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13030 CharUnits Result; 13031 unsigned n = OOE->getNumComponents(); 13032 if (n == 0) 13033 return Error(OOE); 13034 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13035 for (unsigned i = 0; i != n; ++i) { 13036 OffsetOfNode ON = OOE->getComponent(i); 13037 switch (ON.getKind()) { 13038 case OffsetOfNode::Array: { 13039 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13040 APSInt IdxResult; 13041 if (!EvaluateInteger(Idx, IdxResult, Info)) 13042 return false; 13043 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13044 if (!AT) 13045 return Error(OOE); 13046 CurrentType = AT->getElementType(); 13047 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13048 Result += IdxResult.getSExtValue() * ElementSize; 13049 break; 13050 } 13051 13052 case OffsetOfNode::Field: { 13053 FieldDecl *MemberDecl = ON.getField(); 13054 const RecordType *RT = CurrentType->getAs<RecordType>(); 13055 if (!RT) 13056 return Error(OOE); 13057 RecordDecl *RD = RT->getDecl(); 13058 if (RD->isInvalidDecl()) return false; 13059 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13060 unsigned i = MemberDecl->getFieldIndex(); 13061 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13062 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13063 CurrentType = MemberDecl->getType().getNonReferenceType(); 13064 break; 13065 } 13066 13067 case OffsetOfNode::Identifier: 13068 llvm_unreachable("dependent __builtin_offsetof"); 13069 13070 case OffsetOfNode::Base: { 13071 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13072 if (BaseSpec->isVirtual()) 13073 return Error(OOE); 13074 13075 // Find the layout of the class whose base we are looking into. 13076 const RecordType *RT = CurrentType->getAs<RecordType>(); 13077 if (!RT) 13078 return Error(OOE); 13079 RecordDecl *RD = RT->getDecl(); 13080 if (RD->isInvalidDecl()) return false; 13081 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13082 13083 // Find the base class itself. 13084 CurrentType = BaseSpec->getType(); 13085 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13086 if (!BaseRT) 13087 return Error(OOE); 13088 13089 // Add the offset to the base. 13090 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13091 break; 13092 } 13093 } 13094 } 13095 return Success(Result, OOE); 13096 } 13097 13098 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13099 switch (E->getOpcode()) { 13100 default: 13101 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13102 // See C99 6.6p3. 13103 return Error(E); 13104 case UO_Extension: 13105 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13106 // If so, we could clear the diagnostic ID. 13107 return Visit(E->getSubExpr()); 13108 case UO_Plus: 13109 // The result is just the value. 13110 return Visit(E->getSubExpr()); 13111 case UO_Minus: { 13112 if (!Visit(E->getSubExpr())) 13113 return false; 13114 if (!Result.isInt()) return Error(E); 13115 const APSInt &Value = Result.getInt(); 13116 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13117 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13118 E->getType())) 13119 return false; 13120 return Success(-Value, E); 13121 } 13122 case UO_Not: { 13123 if (!Visit(E->getSubExpr())) 13124 return false; 13125 if (!Result.isInt()) return Error(E); 13126 return Success(~Result.getInt(), E); 13127 } 13128 case UO_LNot: { 13129 bool bres; 13130 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13131 return false; 13132 return Success(!bres, E); 13133 } 13134 } 13135 } 13136 13137 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13138 /// result type is integer. 13139 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13140 const Expr *SubExpr = E->getSubExpr(); 13141 QualType DestType = E->getType(); 13142 QualType SrcType = SubExpr->getType(); 13143 13144 switch (E->getCastKind()) { 13145 case CK_BaseToDerived: 13146 case CK_DerivedToBase: 13147 case CK_UncheckedDerivedToBase: 13148 case CK_Dynamic: 13149 case CK_ToUnion: 13150 case CK_ArrayToPointerDecay: 13151 case CK_FunctionToPointerDecay: 13152 case CK_NullToPointer: 13153 case CK_NullToMemberPointer: 13154 case CK_BaseToDerivedMemberPointer: 13155 case CK_DerivedToBaseMemberPointer: 13156 case CK_ReinterpretMemberPointer: 13157 case CK_ConstructorConversion: 13158 case CK_IntegralToPointer: 13159 case CK_ToVoid: 13160 case CK_VectorSplat: 13161 case CK_IntegralToFloating: 13162 case CK_FloatingCast: 13163 case CK_CPointerToObjCPointerCast: 13164 case CK_BlockPointerToObjCPointerCast: 13165 case CK_AnyPointerToBlockPointerCast: 13166 case CK_ObjCObjectLValueCast: 13167 case CK_FloatingRealToComplex: 13168 case CK_FloatingComplexToReal: 13169 case CK_FloatingComplexCast: 13170 case CK_FloatingComplexToIntegralComplex: 13171 case CK_IntegralRealToComplex: 13172 case CK_IntegralComplexCast: 13173 case CK_IntegralComplexToFloatingComplex: 13174 case CK_BuiltinFnToFnPtr: 13175 case CK_ZeroToOCLOpaqueType: 13176 case CK_NonAtomicToAtomic: 13177 case CK_AddressSpaceConversion: 13178 case CK_IntToOCLSampler: 13179 case CK_FloatingToFixedPoint: 13180 case CK_FixedPointToFloating: 13181 case CK_FixedPointCast: 13182 case CK_IntegralToFixedPoint: 13183 llvm_unreachable("invalid cast kind for integral value"); 13184 13185 case CK_BitCast: 13186 case CK_Dependent: 13187 case CK_LValueBitCast: 13188 case CK_ARCProduceObject: 13189 case CK_ARCConsumeObject: 13190 case CK_ARCReclaimReturnedObject: 13191 case CK_ARCExtendBlockObject: 13192 case CK_CopyAndAutoreleaseBlockObject: 13193 return Error(E); 13194 13195 case CK_UserDefinedConversion: 13196 case CK_LValueToRValue: 13197 case CK_AtomicToNonAtomic: 13198 case CK_NoOp: 13199 case CK_LValueToRValueBitCast: 13200 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13201 13202 case CK_MemberPointerToBoolean: 13203 case CK_PointerToBoolean: 13204 case CK_IntegralToBoolean: 13205 case CK_FloatingToBoolean: 13206 case CK_BooleanToSignedIntegral: 13207 case CK_FloatingComplexToBoolean: 13208 case CK_IntegralComplexToBoolean: { 13209 bool BoolResult; 13210 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13211 return false; 13212 uint64_t IntResult = BoolResult; 13213 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13214 IntResult = (uint64_t)-1; 13215 return Success(IntResult, E); 13216 } 13217 13218 case CK_FixedPointToIntegral: { 13219 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13220 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13221 return false; 13222 bool Overflowed; 13223 llvm::APSInt Result = Src.convertToInt( 13224 Info.Ctx.getIntWidth(DestType), 13225 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13226 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13227 return false; 13228 return Success(Result, E); 13229 } 13230 13231 case CK_FixedPointToBoolean: { 13232 // Unsigned padding does not affect this. 13233 APValue Val; 13234 if (!Evaluate(Val, Info, SubExpr)) 13235 return false; 13236 return Success(Val.getFixedPoint().getBoolValue(), E); 13237 } 13238 13239 case CK_IntegralCast: { 13240 if (!Visit(SubExpr)) 13241 return false; 13242 13243 if (!Result.isInt()) { 13244 // Allow casts of address-of-label differences if they are no-ops 13245 // or narrowing. (The narrowing case isn't actually guaranteed to 13246 // be constant-evaluatable except in some narrow cases which are hard 13247 // to detect here. We let it through on the assumption the user knows 13248 // what they are doing.) 13249 if (Result.isAddrLabelDiff()) 13250 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13251 // Only allow casts of lvalues if they are lossless. 13252 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13253 } 13254 13255 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13256 Result.getInt()), E); 13257 } 13258 13259 case CK_PointerToIntegral: { 13260 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13261 13262 LValue LV; 13263 if (!EvaluatePointer(SubExpr, LV, Info)) 13264 return false; 13265 13266 if (LV.getLValueBase()) { 13267 // Only allow based lvalue casts if they are lossless. 13268 // FIXME: Allow a larger integer size than the pointer size, and allow 13269 // narrowing back down to pointer width in subsequent integral casts. 13270 // FIXME: Check integer type's active bits, not its type size. 13271 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13272 return Error(E); 13273 13274 LV.Designator.setInvalid(); 13275 LV.moveInto(Result); 13276 return true; 13277 } 13278 13279 APSInt AsInt; 13280 APValue V; 13281 LV.moveInto(V); 13282 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13283 llvm_unreachable("Can't cast this!"); 13284 13285 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13286 } 13287 13288 case CK_IntegralComplexToReal: { 13289 ComplexValue C; 13290 if (!EvaluateComplex(SubExpr, C, Info)) 13291 return false; 13292 return Success(C.getComplexIntReal(), E); 13293 } 13294 13295 case CK_FloatingToIntegral: { 13296 APFloat F(0.0); 13297 if (!EvaluateFloat(SubExpr, F, Info)) 13298 return false; 13299 13300 APSInt Value; 13301 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13302 return false; 13303 return Success(Value, E); 13304 } 13305 } 13306 13307 llvm_unreachable("unknown cast resulting in integral value"); 13308 } 13309 13310 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13311 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13312 ComplexValue LV; 13313 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13314 return false; 13315 if (!LV.isComplexInt()) 13316 return Error(E); 13317 return Success(LV.getComplexIntReal(), E); 13318 } 13319 13320 return Visit(E->getSubExpr()); 13321 } 13322 13323 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13324 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13325 ComplexValue LV; 13326 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13327 return false; 13328 if (!LV.isComplexInt()) 13329 return Error(E); 13330 return Success(LV.getComplexIntImag(), E); 13331 } 13332 13333 VisitIgnoredValue(E->getSubExpr()); 13334 return Success(0, E); 13335 } 13336 13337 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13338 return Success(E->getPackLength(), E); 13339 } 13340 13341 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13342 return Success(E->getValue(), E); 13343 } 13344 13345 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13346 const ConceptSpecializationExpr *E) { 13347 return Success(E->isSatisfied(), E); 13348 } 13349 13350 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13351 return Success(E->isSatisfied(), E); 13352 } 13353 13354 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13355 switch (E->getOpcode()) { 13356 default: 13357 // Invalid unary operators 13358 return Error(E); 13359 case UO_Plus: 13360 // The result is just the value. 13361 return Visit(E->getSubExpr()); 13362 case UO_Minus: { 13363 if (!Visit(E->getSubExpr())) return false; 13364 if (!Result.isFixedPoint()) 13365 return Error(E); 13366 bool Overflowed; 13367 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13368 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13369 return false; 13370 return Success(Negated, E); 13371 } 13372 case UO_LNot: { 13373 bool bres; 13374 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13375 return false; 13376 return Success(!bres, E); 13377 } 13378 } 13379 } 13380 13381 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13382 const Expr *SubExpr = E->getSubExpr(); 13383 QualType DestType = E->getType(); 13384 assert(DestType->isFixedPointType() && 13385 "Expected destination type to be a fixed point type"); 13386 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13387 13388 switch (E->getCastKind()) { 13389 case CK_FixedPointCast: { 13390 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13391 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13392 return false; 13393 bool Overflowed; 13394 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13395 if (Overflowed) { 13396 if (Info.checkingForUndefinedBehavior()) 13397 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13398 diag::warn_fixedpoint_constant_overflow) 13399 << Result.toString() << E->getType(); 13400 else if (!HandleOverflow(Info, E, Result, E->getType())) 13401 return false; 13402 } 13403 return Success(Result, E); 13404 } 13405 case CK_IntegralToFixedPoint: { 13406 APSInt Src; 13407 if (!EvaluateInteger(SubExpr, Src, Info)) 13408 return false; 13409 13410 bool Overflowed; 13411 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13412 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13413 13414 if (Overflowed) { 13415 if (Info.checkingForUndefinedBehavior()) 13416 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13417 diag::warn_fixedpoint_constant_overflow) 13418 << IntResult.toString() << E->getType(); 13419 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 13420 return false; 13421 } 13422 13423 return Success(IntResult, E); 13424 } 13425 case CK_FloatingToFixedPoint: { 13426 APFloat Src(0.0); 13427 if (!EvaluateFloat(SubExpr, Src, Info)) 13428 return false; 13429 13430 bool Overflowed; 13431 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13432 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13433 13434 if (Overflowed) { 13435 if (Info.checkingForUndefinedBehavior()) 13436 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13437 diag::warn_fixedpoint_constant_overflow) 13438 << Result.toString() << E->getType(); 13439 else if (!HandleOverflow(Info, E, Result, E->getType())) 13440 return false; 13441 } 13442 13443 return Success(Result, E); 13444 } 13445 case CK_NoOp: 13446 case CK_LValueToRValue: 13447 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13448 default: 13449 return Error(E); 13450 } 13451 } 13452 13453 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13454 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13455 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13456 13457 const Expr *LHS = E->getLHS(); 13458 const Expr *RHS = E->getRHS(); 13459 FixedPointSemantics ResultFXSema = 13460 Info.Ctx.getFixedPointSemantics(E->getType()); 13461 13462 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13463 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13464 return false; 13465 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13466 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13467 return false; 13468 13469 bool OpOverflow = false, ConversionOverflow = false; 13470 APFixedPoint Result(LHSFX.getSemantics()); 13471 switch (E->getOpcode()) { 13472 case BO_Add: { 13473 Result = LHSFX.add(RHSFX, &OpOverflow) 13474 .convert(ResultFXSema, &ConversionOverflow); 13475 break; 13476 } 13477 case BO_Sub: { 13478 Result = LHSFX.sub(RHSFX, &OpOverflow) 13479 .convert(ResultFXSema, &ConversionOverflow); 13480 break; 13481 } 13482 case BO_Mul: { 13483 Result = LHSFX.mul(RHSFX, &OpOverflow) 13484 .convert(ResultFXSema, &ConversionOverflow); 13485 break; 13486 } 13487 case BO_Div: { 13488 if (RHSFX.getValue() == 0) { 13489 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13490 return false; 13491 } 13492 Result = LHSFX.div(RHSFX, &OpOverflow) 13493 .convert(ResultFXSema, &ConversionOverflow); 13494 break; 13495 } 13496 case BO_Shl: 13497 case BO_Shr: { 13498 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13499 llvm::APSInt RHSVal = RHSFX.getValue(); 13500 13501 unsigned ShiftBW = 13502 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13503 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13504 // Embedded-C 4.1.6.2.2: 13505 // The right operand must be nonnegative and less than the total number 13506 // of (nonpadding) bits of the fixed-point operand ... 13507 if (RHSVal.isNegative()) 13508 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13509 else if (Amt != RHSVal) 13510 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13511 << RHSVal << E->getType() << ShiftBW; 13512 13513 if (E->getOpcode() == BO_Shl) 13514 Result = LHSFX.shl(Amt, &OpOverflow); 13515 else 13516 Result = LHSFX.shr(Amt, &OpOverflow); 13517 break; 13518 } 13519 default: 13520 return false; 13521 } 13522 if (OpOverflow || ConversionOverflow) { 13523 if (Info.checkingForUndefinedBehavior()) 13524 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13525 diag::warn_fixedpoint_constant_overflow) 13526 << Result.toString() << E->getType(); 13527 else if (!HandleOverflow(Info, E, Result, E->getType())) 13528 return false; 13529 } 13530 return Success(Result, E); 13531 } 13532 13533 //===----------------------------------------------------------------------===// 13534 // Float Evaluation 13535 //===----------------------------------------------------------------------===// 13536 13537 namespace { 13538 class FloatExprEvaluator 13539 : public ExprEvaluatorBase<FloatExprEvaluator> { 13540 APFloat &Result; 13541 public: 13542 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13543 : ExprEvaluatorBaseTy(info), Result(result) {} 13544 13545 bool Success(const APValue &V, const Expr *e) { 13546 Result = V.getFloat(); 13547 return true; 13548 } 13549 13550 bool ZeroInitialization(const Expr *E) { 13551 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13552 return true; 13553 } 13554 13555 bool VisitCallExpr(const CallExpr *E); 13556 13557 bool VisitUnaryOperator(const UnaryOperator *E); 13558 bool VisitBinaryOperator(const BinaryOperator *E); 13559 bool VisitFloatingLiteral(const FloatingLiteral *E); 13560 bool VisitCastExpr(const CastExpr *E); 13561 13562 bool VisitUnaryReal(const UnaryOperator *E); 13563 bool VisitUnaryImag(const UnaryOperator *E); 13564 13565 // FIXME: Missing: array subscript of vector, member of vector 13566 }; 13567 } // end anonymous namespace 13568 13569 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13570 assert(!E->isValueDependent()); 13571 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13572 return FloatExprEvaluator(Info, Result).Visit(E); 13573 } 13574 13575 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13576 QualType ResultTy, 13577 const Expr *Arg, 13578 bool SNaN, 13579 llvm::APFloat &Result) { 13580 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13581 if (!S) return false; 13582 13583 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13584 13585 llvm::APInt fill; 13586 13587 // Treat empty strings as if they were zero. 13588 if (S->getString().empty()) 13589 fill = llvm::APInt(32, 0); 13590 else if (S->getString().getAsInteger(0, fill)) 13591 return false; 13592 13593 if (Context.getTargetInfo().isNan2008()) { 13594 if (SNaN) 13595 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13596 else 13597 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13598 } else { 13599 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13600 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13601 // a different encoding to what became a standard in 2008, and for pre- 13602 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13603 // sNaN. This is now known as "legacy NaN" encoding. 13604 if (SNaN) 13605 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13606 else 13607 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13608 } 13609 13610 return true; 13611 } 13612 13613 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13614 switch (E->getBuiltinCallee()) { 13615 default: 13616 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13617 13618 case Builtin::BI__builtin_huge_val: 13619 case Builtin::BI__builtin_huge_valf: 13620 case Builtin::BI__builtin_huge_vall: 13621 case Builtin::BI__builtin_huge_valf128: 13622 case Builtin::BI__builtin_inf: 13623 case Builtin::BI__builtin_inff: 13624 case Builtin::BI__builtin_infl: 13625 case Builtin::BI__builtin_inff128: { 13626 const llvm::fltSemantics &Sem = 13627 Info.Ctx.getFloatTypeSemantics(E->getType()); 13628 Result = llvm::APFloat::getInf(Sem); 13629 return true; 13630 } 13631 13632 case Builtin::BI__builtin_nans: 13633 case Builtin::BI__builtin_nansf: 13634 case Builtin::BI__builtin_nansl: 13635 case Builtin::BI__builtin_nansf128: 13636 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13637 true, Result)) 13638 return Error(E); 13639 return true; 13640 13641 case Builtin::BI__builtin_nan: 13642 case Builtin::BI__builtin_nanf: 13643 case Builtin::BI__builtin_nanl: 13644 case Builtin::BI__builtin_nanf128: 13645 // If this is __builtin_nan() turn this into a nan, otherwise we 13646 // can't constant fold it. 13647 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13648 false, Result)) 13649 return Error(E); 13650 return true; 13651 13652 case Builtin::BI__builtin_fabs: 13653 case Builtin::BI__builtin_fabsf: 13654 case Builtin::BI__builtin_fabsl: 13655 case Builtin::BI__builtin_fabsf128: 13656 // The C standard says "fabs raises no floating-point exceptions, 13657 // even if x is a signaling NaN. The returned value is independent of 13658 // the current rounding direction mode." Therefore constant folding can 13659 // proceed without regard to the floating point settings. 13660 // Reference, WG14 N2478 F.10.4.3 13661 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13662 return false; 13663 13664 if (Result.isNegative()) 13665 Result.changeSign(); 13666 return true; 13667 13668 // FIXME: Builtin::BI__builtin_powi 13669 // FIXME: Builtin::BI__builtin_powif 13670 // FIXME: Builtin::BI__builtin_powil 13671 13672 case Builtin::BI__builtin_copysign: 13673 case Builtin::BI__builtin_copysignf: 13674 case Builtin::BI__builtin_copysignl: 13675 case Builtin::BI__builtin_copysignf128: { 13676 APFloat RHS(0.); 13677 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13678 !EvaluateFloat(E->getArg(1), RHS, Info)) 13679 return false; 13680 Result.copySign(RHS); 13681 return true; 13682 } 13683 } 13684 } 13685 13686 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13687 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13688 ComplexValue CV; 13689 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13690 return false; 13691 Result = CV.FloatReal; 13692 return true; 13693 } 13694 13695 return Visit(E->getSubExpr()); 13696 } 13697 13698 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13699 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13700 ComplexValue CV; 13701 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13702 return false; 13703 Result = CV.FloatImag; 13704 return true; 13705 } 13706 13707 VisitIgnoredValue(E->getSubExpr()); 13708 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13709 Result = llvm::APFloat::getZero(Sem); 13710 return true; 13711 } 13712 13713 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13714 switch (E->getOpcode()) { 13715 default: return Error(E); 13716 case UO_Plus: 13717 return EvaluateFloat(E->getSubExpr(), Result, Info); 13718 case UO_Minus: 13719 // In C standard, WG14 N2478 F.3 p4 13720 // "the unary - raises no floating point exceptions, 13721 // even if the operand is signalling." 13722 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13723 return false; 13724 Result.changeSign(); 13725 return true; 13726 } 13727 } 13728 13729 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13730 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13731 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13732 13733 APFloat RHS(0.0); 13734 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13735 if (!LHSOK && !Info.noteFailure()) 13736 return false; 13737 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13738 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13739 } 13740 13741 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13742 Result = E->getValue(); 13743 return true; 13744 } 13745 13746 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13747 const Expr* SubExpr = E->getSubExpr(); 13748 13749 switch (E->getCastKind()) { 13750 default: 13751 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13752 13753 case CK_IntegralToFloating: { 13754 APSInt IntResult; 13755 const FPOptions FPO = E->getFPFeaturesInEffect( 13756 Info.Ctx.getLangOpts()); 13757 return EvaluateInteger(SubExpr, IntResult, Info) && 13758 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13759 IntResult, E->getType(), Result); 13760 } 13761 13762 case CK_FixedPointToFloating: { 13763 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13764 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13765 return false; 13766 Result = 13767 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13768 return true; 13769 } 13770 13771 case CK_FloatingCast: { 13772 if (!Visit(SubExpr)) 13773 return false; 13774 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13775 Result); 13776 } 13777 13778 case CK_FloatingComplexToReal: { 13779 ComplexValue V; 13780 if (!EvaluateComplex(SubExpr, V, Info)) 13781 return false; 13782 Result = V.getComplexFloatReal(); 13783 return true; 13784 } 13785 } 13786 } 13787 13788 //===----------------------------------------------------------------------===// 13789 // Complex Evaluation (for float and integer) 13790 //===----------------------------------------------------------------------===// 13791 13792 namespace { 13793 class ComplexExprEvaluator 13794 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13795 ComplexValue &Result; 13796 13797 public: 13798 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13799 : ExprEvaluatorBaseTy(info), Result(Result) {} 13800 13801 bool Success(const APValue &V, const Expr *e) { 13802 Result.setFrom(V); 13803 return true; 13804 } 13805 13806 bool ZeroInitialization(const Expr *E); 13807 13808 //===--------------------------------------------------------------------===// 13809 // Visitor Methods 13810 //===--------------------------------------------------------------------===// 13811 13812 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13813 bool VisitCastExpr(const CastExpr *E); 13814 bool VisitBinaryOperator(const BinaryOperator *E); 13815 bool VisitUnaryOperator(const UnaryOperator *E); 13816 bool VisitInitListExpr(const InitListExpr *E); 13817 bool VisitCallExpr(const CallExpr *E); 13818 }; 13819 } // end anonymous namespace 13820 13821 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13822 EvalInfo &Info) { 13823 assert(!E->isValueDependent()); 13824 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13825 return ComplexExprEvaluator(Info, Result).Visit(E); 13826 } 13827 13828 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13829 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13830 if (ElemTy->isRealFloatingType()) { 13831 Result.makeComplexFloat(); 13832 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13833 Result.FloatReal = Zero; 13834 Result.FloatImag = Zero; 13835 } else { 13836 Result.makeComplexInt(); 13837 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13838 Result.IntReal = Zero; 13839 Result.IntImag = Zero; 13840 } 13841 return true; 13842 } 13843 13844 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13845 const Expr* SubExpr = E->getSubExpr(); 13846 13847 if (SubExpr->getType()->isRealFloatingType()) { 13848 Result.makeComplexFloat(); 13849 APFloat &Imag = Result.FloatImag; 13850 if (!EvaluateFloat(SubExpr, Imag, Info)) 13851 return false; 13852 13853 Result.FloatReal = APFloat(Imag.getSemantics()); 13854 return true; 13855 } else { 13856 assert(SubExpr->getType()->isIntegerType() && 13857 "Unexpected imaginary literal."); 13858 13859 Result.makeComplexInt(); 13860 APSInt &Imag = Result.IntImag; 13861 if (!EvaluateInteger(SubExpr, Imag, Info)) 13862 return false; 13863 13864 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13865 return true; 13866 } 13867 } 13868 13869 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13870 13871 switch (E->getCastKind()) { 13872 case CK_BitCast: 13873 case CK_BaseToDerived: 13874 case CK_DerivedToBase: 13875 case CK_UncheckedDerivedToBase: 13876 case CK_Dynamic: 13877 case CK_ToUnion: 13878 case CK_ArrayToPointerDecay: 13879 case CK_FunctionToPointerDecay: 13880 case CK_NullToPointer: 13881 case CK_NullToMemberPointer: 13882 case CK_BaseToDerivedMemberPointer: 13883 case CK_DerivedToBaseMemberPointer: 13884 case CK_MemberPointerToBoolean: 13885 case CK_ReinterpretMemberPointer: 13886 case CK_ConstructorConversion: 13887 case CK_IntegralToPointer: 13888 case CK_PointerToIntegral: 13889 case CK_PointerToBoolean: 13890 case CK_ToVoid: 13891 case CK_VectorSplat: 13892 case CK_IntegralCast: 13893 case CK_BooleanToSignedIntegral: 13894 case CK_IntegralToBoolean: 13895 case CK_IntegralToFloating: 13896 case CK_FloatingToIntegral: 13897 case CK_FloatingToBoolean: 13898 case CK_FloatingCast: 13899 case CK_CPointerToObjCPointerCast: 13900 case CK_BlockPointerToObjCPointerCast: 13901 case CK_AnyPointerToBlockPointerCast: 13902 case CK_ObjCObjectLValueCast: 13903 case CK_FloatingComplexToReal: 13904 case CK_FloatingComplexToBoolean: 13905 case CK_IntegralComplexToReal: 13906 case CK_IntegralComplexToBoolean: 13907 case CK_ARCProduceObject: 13908 case CK_ARCConsumeObject: 13909 case CK_ARCReclaimReturnedObject: 13910 case CK_ARCExtendBlockObject: 13911 case CK_CopyAndAutoreleaseBlockObject: 13912 case CK_BuiltinFnToFnPtr: 13913 case CK_ZeroToOCLOpaqueType: 13914 case CK_NonAtomicToAtomic: 13915 case CK_AddressSpaceConversion: 13916 case CK_IntToOCLSampler: 13917 case CK_FloatingToFixedPoint: 13918 case CK_FixedPointToFloating: 13919 case CK_FixedPointCast: 13920 case CK_FixedPointToBoolean: 13921 case CK_FixedPointToIntegral: 13922 case CK_IntegralToFixedPoint: 13923 llvm_unreachable("invalid cast kind for complex value"); 13924 13925 case CK_LValueToRValue: 13926 case CK_AtomicToNonAtomic: 13927 case CK_NoOp: 13928 case CK_LValueToRValueBitCast: 13929 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13930 13931 case CK_Dependent: 13932 case CK_LValueBitCast: 13933 case CK_UserDefinedConversion: 13934 return Error(E); 13935 13936 case CK_FloatingRealToComplex: { 13937 APFloat &Real = Result.FloatReal; 13938 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13939 return false; 13940 13941 Result.makeComplexFloat(); 13942 Result.FloatImag = APFloat(Real.getSemantics()); 13943 return true; 13944 } 13945 13946 case CK_FloatingComplexCast: { 13947 if (!Visit(E->getSubExpr())) 13948 return false; 13949 13950 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13951 QualType From 13952 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13953 13954 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13955 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13956 } 13957 13958 case CK_FloatingComplexToIntegralComplex: { 13959 if (!Visit(E->getSubExpr())) 13960 return false; 13961 13962 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13963 QualType From 13964 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13965 Result.makeComplexInt(); 13966 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13967 To, Result.IntReal) && 13968 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13969 To, Result.IntImag); 13970 } 13971 13972 case CK_IntegralRealToComplex: { 13973 APSInt &Real = Result.IntReal; 13974 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13975 return false; 13976 13977 Result.makeComplexInt(); 13978 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13979 return true; 13980 } 13981 13982 case CK_IntegralComplexCast: { 13983 if (!Visit(E->getSubExpr())) 13984 return false; 13985 13986 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13987 QualType From 13988 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13989 13990 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13991 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13992 return true; 13993 } 13994 13995 case CK_IntegralComplexToFloatingComplex: { 13996 if (!Visit(E->getSubExpr())) 13997 return false; 13998 13999 const FPOptions FPO = E->getFPFeaturesInEffect( 14000 Info.Ctx.getLangOpts()); 14001 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14002 QualType From 14003 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14004 Result.makeComplexFloat(); 14005 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14006 To, Result.FloatReal) && 14007 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14008 To, Result.FloatImag); 14009 } 14010 } 14011 14012 llvm_unreachable("unknown cast resulting in complex value"); 14013 } 14014 14015 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14016 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14017 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14018 14019 // Track whether the LHS or RHS is real at the type system level. When this is 14020 // the case we can simplify our evaluation strategy. 14021 bool LHSReal = false, RHSReal = false; 14022 14023 bool LHSOK; 14024 if (E->getLHS()->getType()->isRealFloatingType()) { 14025 LHSReal = true; 14026 APFloat &Real = Result.FloatReal; 14027 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14028 if (LHSOK) { 14029 Result.makeComplexFloat(); 14030 Result.FloatImag = APFloat(Real.getSemantics()); 14031 } 14032 } else { 14033 LHSOK = Visit(E->getLHS()); 14034 } 14035 if (!LHSOK && !Info.noteFailure()) 14036 return false; 14037 14038 ComplexValue RHS; 14039 if (E->getRHS()->getType()->isRealFloatingType()) { 14040 RHSReal = true; 14041 APFloat &Real = RHS.FloatReal; 14042 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14043 return false; 14044 RHS.makeComplexFloat(); 14045 RHS.FloatImag = APFloat(Real.getSemantics()); 14046 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14047 return false; 14048 14049 assert(!(LHSReal && RHSReal) && 14050 "Cannot have both operands of a complex operation be real."); 14051 switch (E->getOpcode()) { 14052 default: return Error(E); 14053 case BO_Add: 14054 if (Result.isComplexFloat()) { 14055 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14056 APFloat::rmNearestTiesToEven); 14057 if (LHSReal) 14058 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14059 else if (!RHSReal) 14060 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14061 APFloat::rmNearestTiesToEven); 14062 } else { 14063 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14064 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14065 } 14066 break; 14067 case BO_Sub: 14068 if (Result.isComplexFloat()) { 14069 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14070 APFloat::rmNearestTiesToEven); 14071 if (LHSReal) { 14072 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14073 Result.getComplexFloatImag().changeSign(); 14074 } else if (!RHSReal) { 14075 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14076 APFloat::rmNearestTiesToEven); 14077 } 14078 } else { 14079 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14080 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14081 } 14082 break; 14083 case BO_Mul: 14084 if (Result.isComplexFloat()) { 14085 // This is an implementation of complex multiplication according to the 14086 // constraints laid out in C11 Annex G. The implementation uses the 14087 // following naming scheme: 14088 // (a + ib) * (c + id) 14089 ComplexValue LHS = Result; 14090 APFloat &A = LHS.getComplexFloatReal(); 14091 APFloat &B = LHS.getComplexFloatImag(); 14092 APFloat &C = RHS.getComplexFloatReal(); 14093 APFloat &D = RHS.getComplexFloatImag(); 14094 APFloat &ResR = Result.getComplexFloatReal(); 14095 APFloat &ResI = Result.getComplexFloatImag(); 14096 if (LHSReal) { 14097 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14098 ResR = A * C; 14099 ResI = A * D; 14100 } else if (RHSReal) { 14101 ResR = C * A; 14102 ResI = C * B; 14103 } else { 14104 // In the fully general case, we need to handle NaNs and infinities 14105 // robustly. 14106 APFloat AC = A * C; 14107 APFloat BD = B * D; 14108 APFloat AD = A * D; 14109 APFloat BC = B * C; 14110 ResR = AC - BD; 14111 ResI = AD + BC; 14112 if (ResR.isNaN() && ResI.isNaN()) { 14113 bool Recalc = false; 14114 if (A.isInfinity() || B.isInfinity()) { 14115 A = APFloat::copySign( 14116 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14117 B = APFloat::copySign( 14118 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14119 if (C.isNaN()) 14120 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14121 if (D.isNaN()) 14122 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14123 Recalc = true; 14124 } 14125 if (C.isInfinity() || D.isInfinity()) { 14126 C = APFloat::copySign( 14127 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14128 D = APFloat::copySign( 14129 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14130 if (A.isNaN()) 14131 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14132 if (B.isNaN()) 14133 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14134 Recalc = true; 14135 } 14136 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14137 AD.isInfinity() || BC.isInfinity())) { 14138 if (A.isNaN()) 14139 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14140 if (B.isNaN()) 14141 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14142 if (C.isNaN()) 14143 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14144 if (D.isNaN()) 14145 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14146 Recalc = true; 14147 } 14148 if (Recalc) { 14149 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14150 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14151 } 14152 } 14153 } 14154 } else { 14155 ComplexValue LHS = Result; 14156 Result.getComplexIntReal() = 14157 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14158 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14159 Result.getComplexIntImag() = 14160 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14161 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14162 } 14163 break; 14164 case BO_Div: 14165 if (Result.isComplexFloat()) { 14166 // This is an implementation of complex division according to the 14167 // constraints laid out in C11 Annex G. The implementation uses the 14168 // following naming scheme: 14169 // (a + ib) / (c + id) 14170 ComplexValue LHS = Result; 14171 APFloat &A = LHS.getComplexFloatReal(); 14172 APFloat &B = LHS.getComplexFloatImag(); 14173 APFloat &C = RHS.getComplexFloatReal(); 14174 APFloat &D = RHS.getComplexFloatImag(); 14175 APFloat &ResR = Result.getComplexFloatReal(); 14176 APFloat &ResI = Result.getComplexFloatImag(); 14177 if (RHSReal) { 14178 ResR = A / C; 14179 ResI = B / C; 14180 } else { 14181 if (LHSReal) { 14182 // No real optimizations we can do here, stub out with zero. 14183 B = APFloat::getZero(A.getSemantics()); 14184 } 14185 int DenomLogB = 0; 14186 APFloat MaxCD = maxnum(abs(C), abs(D)); 14187 if (MaxCD.isFinite()) { 14188 DenomLogB = ilogb(MaxCD); 14189 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14190 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14191 } 14192 APFloat Denom = C * C + D * D; 14193 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14194 APFloat::rmNearestTiesToEven); 14195 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14196 APFloat::rmNearestTiesToEven); 14197 if (ResR.isNaN() && ResI.isNaN()) { 14198 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14199 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14200 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14201 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14202 D.isFinite()) { 14203 A = APFloat::copySign( 14204 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14205 B = APFloat::copySign( 14206 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14207 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14208 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14209 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14210 C = APFloat::copySign( 14211 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14212 D = APFloat::copySign( 14213 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14214 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14215 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14216 } 14217 } 14218 } 14219 } else { 14220 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14221 return Error(E, diag::note_expr_divide_by_zero); 14222 14223 ComplexValue LHS = Result; 14224 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14225 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14226 Result.getComplexIntReal() = 14227 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14228 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14229 Result.getComplexIntImag() = 14230 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14231 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14232 } 14233 break; 14234 } 14235 14236 return true; 14237 } 14238 14239 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14240 // Get the operand value into 'Result'. 14241 if (!Visit(E->getSubExpr())) 14242 return false; 14243 14244 switch (E->getOpcode()) { 14245 default: 14246 return Error(E); 14247 case UO_Extension: 14248 return true; 14249 case UO_Plus: 14250 // The result is always just the subexpr. 14251 return true; 14252 case UO_Minus: 14253 if (Result.isComplexFloat()) { 14254 Result.getComplexFloatReal().changeSign(); 14255 Result.getComplexFloatImag().changeSign(); 14256 } 14257 else { 14258 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14259 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14260 } 14261 return true; 14262 case UO_Not: 14263 if (Result.isComplexFloat()) 14264 Result.getComplexFloatImag().changeSign(); 14265 else 14266 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14267 return true; 14268 } 14269 } 14270 14271 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14272 if (E->getNumInits() == 2) { 14273 if (E->getType()->isComplexType()) { 14274 Result.makeComplexFloat(); 14275 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14276 return false; 14277 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14278 return false; 14279 } else { 14280 Result.makeComplexInt(); 14281 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14282 return false; 14283 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14284 return false; 14285 } 14286 return true; 14287 } 14288 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14289 } 14290 14291 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14292 switch (E->getBuiltinCallee()) { 14293 case Builtin::BI__builtin_complex: 14294 Result.makeComplexFloat(); 14295 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14296 return false; 14297 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14298 return false; 14299 return true; 14300 14301 default: 14302 break; 14303 } 14304 14305 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14306 } 14307 14308 //===----------------------------------------------------------------------===// 14309 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14310 // implicit conversion. 14311 //===----------------------------------------------------------------------===// 14312 14313 namespace { 14314 class AtomicExprEvaluator : 14315 public ExprEvaluatorBase<AtomicExprEvaluator> { 14316 const LValue *This; 14317 APValue &Result; 14318 public: 14319 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14320 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14321 14322 bool Success(const APValue &V, const Expr *E) { 14323 Result = V; 14324 return true; 14325 } 14326 14327 bool ZeroInitialization(const Expr *E) { 14328 ImplicitValueInitExpr VIE( 14329 E->getType()->castAs<AtomicType>()->getValueType()); 14330 // For atomic-qualified class (and array) types in C++, initialize the 14331 // _Atomic-wrapped subobject directly, in-place. 14332 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14333 : Evaluate(Result, Info, &VIE); 14334 } 14335 14336 bool VisitCastExpr(const CastExpr *E) { 14337 switch (E->getCastKind()) { 14338 default: 14339 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14340 case CK_NonAtomicToAtomic: 14341 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14342 : Evaluate(Result, Info, E->getSubExpr()); 14343 } 14344 } 14345 }; 14346 } // end anonymous namespace 14347 14348 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14349 EvalInfo &Info) { 14350 assert(!E->isValueDependent()); 14351 assert(E->isRValue() && E->getType()->isAtomicType()); 14352 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14353 } 14354 14355 //===----------------------------------------------------------------------===// 14356 // Void expression evaluation, primarily for a cast to void on the LHS of a 14357 // comma operator 14358 //===----------------------------------------------------------------------===// 14359 14360 namespace { 14361 class VoidExprEvaluator 14362 : public ExprEvaluatorBase<VoidExprEvaluator> { 14363 public: 14364 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14365 14366 bool Success(const APValue &V, const Expr *e) { return true; } 14367 14368 bool ZeroInitialization(const Expr *E) { return true; } 14369 14370 bool VisitCastExpr(const CastExpr *E) { 14371 switch (E->getCastKind()) { 14372 default: 14373 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14374 case CK_ToVoid: 14375 VisitIgnoredValue(E->getSubExpr()); 14376 return true; 14377 } 14378 } 14379 14380 bool VisitCallExpr(const CallExpr *E) { 14381 switch (E->getBuiltinCallee()) { 14382 case Builtin::BI__assume: 14383 case Builtin::BI__builtin_assume: 14384 // The argument is not evaluated! 14385 return true; 14386 14387 case Builtin::BI__builtin_operator_delete: 14388 return HandleOperatorDeleteCall(Info, E); 14389 14390 default: 14391 break; 14392 } 14393 14394 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14395 } 14396 14397 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14398 }; 14399 } // end anonymous namespace 14400 14401 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14402 // We cannot speculatively evaluate a delete expression. 14403 if (Info.SpeculativeEvaluationDepth) 14404 return false; 14405 14406 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14407 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14408 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14409 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14410 return false; 14411 } 14412 14413 const Expr *Arg = E->getArgument(); 14414 14415 LValue Pointer; 14416 if (!EvaluatePointer(Arg, Pointer, Info)) 14417 return false; 14418 if (Pointer.Designator.Invalid) 14419 return false; 14420 14421 // Deleting a null pointer has no effect. 14422 if (Pointer.isNullPointer()) { 14423 // This is the only case where we need to produce an extension warning: 14424 // the only other way we can succeed is if we find a dynamic allocation, 14425 // and we will have warned when we allocated it in that case. 14426 if (!Info.getLangOpts().CPlusPlus20) 14427 Info.CCEDiag(E, diag::note_constexpr_new); 14428 return true; 14429 } 14430 14431 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14432 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14433 if (!Alloc) 14434 return false; 14435 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14436 14437 // For the non-array case, the designator must be empty if the static type 14438 // does not have a virtual destructor. 14439 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14440 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14441 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14442 << Arg->getType()->getPointeeType() << AllocType; 14443 return false; 14444 } 14445 14446 // For a class type with a virtual destructor, the selected operator delete 14447 // is the one looked up when building the destructor. 14448 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14449 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14450 if (VirtualDelete && 14451 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14452 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14453 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14454 return false; 14455 } 14456 } 14457 14458 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14459 (*Alloc)->Value, AllocType)) 14460 return false; 14461 14462 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14463 // The element was already erased. This means the destructor call also 14464 // deleted the object. 14465 // FIXME: This probably results in undefined behavior before we get this 14466 // far, and should be diagnosed elsewhere first. 14467 Info.FFDiag(E, diag::note_constexpr_double_delete); 14468 return false; 14469 } 14470 14471 return true; 14472 } 14473 14474 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14475 assert(!E->isValueDependent()); 14476 assert(E->isRValue() && E->getType()->isVoidType()); 14477 return VoidExprEvaluator(Info).Visit(E); 14478 } 14479 14480 //===----------------------------------------------------------------------===// 14481 // Top level Expr::EvaluateAsRValue method. 14482 //===----------------------------------------------------------------------===// 14483 14484 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14485 assert(!E->isValueDependent()); 14486 // In C, function designators are not lvalues, but we evaluate them as if they 14487 // are. 14488 QualType T = E->getType(); 14489 if (E->isGLValue() || T->isFunctionType()) { 14490 LValue LV; 14491 if (!EvaluateLValue(E, LV, Info)) 14492 return false; 14493 LV.moveInto(Result); 14494 } else if (T->isVectorType()) { 14495 if (!EvaluateVector(E, Result, Info)) 14496 return false; 14497 } else if (T->isIntegralOrEnumerationType()) { 14498 if (!IntExprEvaluator(Info, Result).Visit(E)) 14499 return false; 14500 } else if (T->hasPointerRepresentation()) { 14501 LValue LV; 14502 if (!EvaluatePointer(E, LV, Info)) 14503 return false; 14504 LV.moveInto(Result); 14505 } else if (T->isRealFloatingType()) { 14506 llvm::APFloat F(0.0); 14507 if (!EvaluateFloat(E, F, Info)) 14508 return false; 14509 Result = APValue(F); 14510 } else if (T->isAnyComplexType()) { 14511 ComplexValue C; 14512 if (!EvaluateComplex(E, C, Info)) 14513 return false; 14514 C.moveInto(Result); 14515 } else if (T->isFixedPointType()) { 14516 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14517 } else if (T->isMemberPointerType()) { 14518 MemberPtr P; 14519 if (!EvaluateMemberPointer(E, P, Info)) 14520 return false; 14521 P.moveInto(Result); 14522 return true; 14523 } else if (T->isArrayType()) { 14524 LValue LV; 14525 APValue &Value = 14526 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14527 if (!EvaluateArray(E, LV, Value, Info)) 14528 return false; 14529 Result = Value; 14530 } else if (T->isRecordType()) { 14531 LValue LV; 14532 APValue &Value = 14533 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14534 if (!EvaluateRecord(E, LV, Value, Info)) 14535 return false; 14536 Result = Value; 14537 } else if (T->isVoidType()) { 14538 if (!Info.getLangOpts().CPlusPlus11) 14539 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14540 << E->getType(); 14541 if (!EvaluateVoid(E, Info)) 14542 return false; 14543 } else if (T->isAtomicType()) { 14544 QualType Unqual = T.getAtomicUnqualifiedType(); 14545 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14546 LValue LV; 14547 APValue &Value = Info.CurrentCall->createTemporary( 14548 E, Unqual, ScopeKind::FullExpression, LV); 14549 if (!EvaluateAtomic(E, &LV, Value, Info)) 14550 return false; 14551 } else { 14552 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14553 return false; 14554 } 14555 } else if (Info.getLangOpts().CPlusPlus11) { 14556 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14557 return false; 14558 } else { 14559 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14560 return false; 14561 } 14562 14563 return true; 14564 } 14565 14566 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14567 /// cases, the in-place evaluation is essential, since later initializers for 14568 /// an object can indirectly refer to subobjects which were initialized earlier. 14569 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14570 const Expr *E, bool AllowNonLiteralTypes) { 14571 assert(!E->isValueDependent()); 14572 14573 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14574 return false; 14575 14576 if (E->isRValue()) { 14577 // Evaluate arrays and record types in-place, so that later initializers can 14578 // refer to earlier-initialized members of the object. 14579 QualType T = E->getType(); 14580 if (T->isArrayType()) 14581 return EvaluateArray(E, This, Result, Info); 14582 else if (T->isRecordType()) 14583 return EvaluateRecord(E, This, Result, Info); 14584 else if (T->isAtomicType()) { 14585 QualType Unqual = T.getAtomicUnqualifiedType(); 14586 if (Unqual->isArrayType() || Unqual->isRecordType()) 14587 return EvaluateAtomic(E, &This, Result, Info); 14588 } 14589 } 14590 14591 // For any other type, in-place evaluation is unimportant. 14592 return Evaluate(Result, Info, E); 14593 } 14594 14595 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14596 /// lvalue-to-rvalue cast if it is an lvalue. 14597 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14598 assert(!E->isValueDependent()); 14599 if (Info.EnableNewConstInterp) { 14600 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14601 return false; 14602 } else { 14603 if (E->getType().isNull()) 14604 return false; 14605 14606 if (!CheckLiteralType(Info, E)) 14607 return false; 14608 14609 if (!::Evaluate(Result, Info, E)) 14610 return false; 14611 14612 if (E->isGLValue()) { 14613 LValue LV; 14614 LV.setFrom(Info.Ctx, Result); 14615 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14616 return false; 14617 } 14618 } 14619 14620 // Check this core constant expression is a constant expression. 14621 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14622 ConstantExprKind::Normal) && 14623 CheckMemoryLeaks(Info); 14624 } 14625 14626 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14627 const ASTContext &Ctx, bool &IsConst) { 14628 // Fast-path evaluations of integer literals, since we sometimes see files 14629 // containing vast quantities of these. 14630 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14631 Result.Val = APValue(APSInt(L->getValue(), 14632 L->getType()->isUnsignedIntegerType())); 14633 IsConst = true; 14634 return true; 14635 } 14636 14637 // This case should be rare, but we need to check it before we check on 14638 // the type below. 14639 if (Exp->getType().isNull()) { 14640 IsConst = false; 14641 return true; 14642 } 14643 14644 // FIXME: Evaluating values of large array and record types can cause 14645 // performance problems. Only do so in C++11 for now. 14646 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14647 Exp->getType()->isRecordType()) && 14648 !Ctx.getLangOpts().CPlusPlus11) { 14649 IsConst = false; 14650 return true; 14651 } 14652 return false; 14653 } 14654 14655 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14656 Expr::SideEffectsKind SEK) { 14657 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14658 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14659 } 14660 14661 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14662 const ASTContext &Ctx, EvalInfo &Info) { 14663 assert(!E->isValueDependent()); 14664 bool IsConst; 14665 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14666 return IsConst; 14667 14668 return EvaluateAsRValue(Info, E, Result.Val); 14669 } 14670 14671 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14672 const ASTContext &Ctx, 14673 Expr::SideEffectsKind AllowSideEffects, 14674 EvalInfo &Info) { 14675 assert(!E->isValueDependent()); 14676 if (!E->getType()->isIntegralOrEnumerationType()) 14677 return false; 14678 14679 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14680 !ExprResult.Val.isInt() || 14681 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14682 return false; 14683 14684 return true; 14685 } 14686 14687 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14688 const ASTContext &Ctx, 14689 Expr::SideEffectsKind AllowSideEffects, 14690 EvalInfo &Info) { 14691 assert(!E->isValueDependent()); 14692 if (!E->getType()->isFixedPointType()) 14693 return false; 14694 14695 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14696 return false; 14697 14698 if (!ExprResult.Val.isFixedPoint() || 14699 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14700 return false; 14701 14702 return true; 14703 } 14704 14705 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14706 /// any crazy technique (that has nothing to do with language standards) that 14707 /// we want to. If this function returns true, it returns the folded constant 14708 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14709 /// will be applied to the result. 14710 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14711 bool InConstantContext) const { 14712 assert(!isValueDependent() && 14713 "Expression evaluator can't be called on a dependent expression."); 14714 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14715 Info.InConstantContext = InConstantContext; 14716 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14717 } 14718 14719 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14720 bool InConstantContext) const { 14721 assert(!isValueDependent() && 14722 "Expression evaluator can't be called on a dependent expression."); 14723 EvalResult Scratch; 14724 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14725 HandleConversionToBool(Scratch.Val, Result); 14726 } 14727 14728 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14729 SideEffectsKind AllowSideEffects, 14730 bool InConstantContext) const { 14731 assert(!isValueDependent() && 14732 "Expression evaluator can't be called on a dependent expression."); 14733 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14734 Info.InConstantContext = InConstantContext; 14735 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14736 } 14737 14738 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14739 SideEffectsKind AllowSideEffects, 14740 bool InConstantContext) const { 14741 assert(!isValueDependent() && 14742 "Expression evaluator can't be called on a dependent expression."); 14743 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14744 Info.InConstantContext = InConstantContext; 14745 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14746 } 14747 14748 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14749 SideEffectsKind AllowSideEffects, 14750 bool InConstantContext) const { 14751 assert(!isValueDependent() && 14752 "Expression evaluator can't be called on a dependent expression."); 14753 14754 if (!getType()->isRealFloatingType()) 14755 return false; 14756 14757 EvalResult ExprResult; 14758 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14759 !ExprResult.Val.isFloat() || 14760 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14761 return false; 14762 14763 Result = ExprResult.Val.getFloat(); 14764 return true; 14765 } 14766 14767 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14768 bool InConstantContext) const { 14769 assert(!isValueDependent() && 14770 "Expression evaluator can't be called on a dependent expression."); 14771 14772 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14773 Info.InConstantContext = InConstantContext; 14774 LValue LV; 14775 CheckedTemporaries CheckedTemps; 14776 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14777 Result.HasSideEffects || 14778 !CheckLValueConstantExpression(Info, getExprLoc(), 14779 Ctx.getLValueReferenceType(getType()), LV, 14780 ConstantExprKind::Normal, CheckedTemps)) 14781 return false; 14782 14783 LV.moveInto(Result.Val); 14784 return true; 14785 } 14786 14787 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14788 APValue DestroyedValue, QualType Type, 14789 SourceLocation Loc, Expr::EvalStatus &EStatus) { 14790 EvalInfo Info(Ctx, EStatus, EvalInfo::EM_ConstantExpression); 14791 Info.setEvaluatingDecl(Base, DestroyedValue, 14792 EvalInfo::EvaluatingDeclKind::Dtor); 14793 Info.InConstantContext = true; 14794 14795 LValue LVal; 14796 LVal.set(Base); 14797 14798 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14799 EStatus.HasSideEffects) 14800 return false; 14801 14802 if (!Info.discardCleanups()) 14803 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14804 14805 return true; 14806 } 14807 14808 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14809 ConstantExprKind Kind) const { 14810 assert(!isValueDependent() && 14811 "Expression evaluator can't be called on a dependent expression."); 14812 14813 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14814 EvalInfo Info(Ctx, Result, EM); 14815 Info.InConstantContext = true; 14816 14817 // The type of the object we're initializing is 'const T' for a class NTTP. 14818 QualType T = getType(); 14819 if (Kind == ConstantExprKind::ClassTemplateArgument) 14820 T.addConst(); 14821 14822 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14823 // represent the result of the evaluation. CheckConstantExpression ensures 14824 // this doesn't escape. 14825 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14826 APValue::LValueBase Base(&BaseMTE); 14827 14828 Info.setEvaluatingDecl(Base, Result.Val); 14829 LValue LVal; 14830 LVal.set(Base); 14831 14832 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14833 return false; 14834 14835 if (!Info.discardCleanups()) 14836 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14837 14838 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14839 Result.Val, Kind)) 14840 return false; 14841 if (!CheckMemoryLeaks(Info)) 14842 return false; 14843 14844 // If this is a class template argument, it's required to have constant 14845 // destruction too. 14846 if (Kind == ConstantExprKind::ClassTemplateArgument && 14847 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result) || 14848 Result.HasSideEffects)) { 14849 // FIXME: Prefix a note to indicate that the problem is lack of constant 14850 // destruction. 14851 return false; 14852 } 14853 14854 return true; 14855 } 14856 14857 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14858 const VarDecl *VD, 14859 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14860 bool IsConstantInitialization) const { 14861 assert(!isValueDependent() && 14862 "Expression evaluator can't be called on a dependent expression."); 14863 14864 // FIXME: Evaluating initializers for large array and record types can cause 14865 // performance problems. Only do so in C++11 for now. 14866 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14867 !Ctx.getLangOpts().CPlusPlus11) 14868 return false; 14869 14870 Expr::EvalStatus EStatus; 14871 EStatus.Diag = &Notes; 14872 14873 EvalInfo Info(Ctx, EStatus, 14874 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14875 ? EvalInfo::EM_ConstantExpression 14876 : EvalInfo::EM_ConstantFold); 14877 Info.setEvaluatingDecl(VD, Value); 14878 Info.InConstantContext = IsConstantInitialization; 14879 14880 SourceLocation DeclLoc = VD->getLocation(); 14881 QualType DeclTy = VD->getType(); 14882 14883 if (Info.EnableNewConstInterp) { 14884 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14885 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14886 return false; 14887 } else { 14888 LValue LVal; 14889 LVal.set(VD); 14890 14891 if (!EvaluateInPlace(Value, Info, LVal, this, 14892 /*AllowNonLiteralTypes=*/true) || 14893 EStatus.HasSideEffects) 14894 return false; 14895 14896 // At this point, any lifetime-extended temporaries are completely 14897 // initialized. 14898 Info.performLifetimeExtension(); 14899 14900 if (!Info.discardCleanups()) 14901 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14902 } 14903 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 14904 ConstantExprKind::Normal) && 14905 CheckMemoryLeaks(Info); 14906 } 14907 14908 bool VarDecl::evaluateDestruction( 14909 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14910 Expr::EvalStatus EStatus; 14911 EStatus.Diag = &Notes; 14912 14913 // Make a copy of the value for the destructor to mutate, if we know it. 14914 // Otherwise, treat the value as default-initialized; if the destructor works 14915 // anyway, then the destruction is constant (and must be essentially empty). 14916 APValue DestroyedValue; 14917 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14918 DestroyedValue = *getEvaluatedValue(); 14919 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14920 return false; 14921 14922 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 14923 getType(), getLocation(), EStatus) || 14924 EStatus.HasSideEffects) 14925 return false; 14926 14927 ensureEvaluatedStmt()->HasConstantDestruction = true; 14928 return true; 14929 } 14930 14931 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14932 /// constant folded, but discard the result. 14933 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14934 assert(!isValueDependent() && 14935 "Expression evaluator can't be called on a dependent expression."); 14936 14937 EvalResult Result; 14938 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14939 !hasUnacceptableSideEffect(Result, SEK); 14940 } 14941 14942 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14943 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14944 assert(!isValueDependent() && 14945 "Expression evaluator can't be called on a dependent expression."); 14946 14947 EvalResult EVResult; 14948 EVResult.Diag = Diag; 14949 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14950 Info.InConstantContext = true; 14951 14952 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14953 (void)Result; 14954 assert(Result && "Could not evaluate expression"); 14955 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14956 14957 return EVResult.Val.getInt(); 14958 } 14959 14960 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14961 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14962 assert(!isValueDependent() && 14963 "Expression evaluator can't be called on a dependent expression."); 14964 14965 EvalResult EVResult; 14966 EVResult.Diag = Diag; 14967 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14968 Info.InConstantContext = true; 14969 Info.CheckingForUndefinedBehavior = true; 14970 14971 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14972 (void)Result; 14973 assert(Result && "Could not evaluate expression"); 14974 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14975 14976 return EVResult.Val.getInt(); 14977 } 14978 14979 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14980 assert(!isValueDependent() && 14981 "Expression evaluator can't be called on a dependent expression."); 14982 14983 bool IsConst; 14984 EvalResult EVResult; 14985 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14986 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14987 Info.CheckingForUndefinedBehavior = true; 14988 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14989 } 14990 } 14991 14992 bool Expr::EvalResult::isGlobalLValue() const { 14993 assert(Val.isLValue()); 14994 return IsGlobalLValue(Val.getLValueBase()); 14995 } 14996 14997 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14998 /// an integer constant expression. 14999 15000 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15001 /// comma, etc 15002 15003 // CheckICE - This function does the fundamental ICE checking: the returned 15004 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15005 // and a (possibly null) SourceLocation indicating the location of the problem. 15006 // 15007 // Note that to reduce code duplication, this helper does no evaluation 15008 // itself; the caller checks whether the expression is evaluatable, and 15009 // in the rare cases where CheckICE actually cares about the evaluated 15010 // value, it calls into Evaluate. 15011 15012 namespace { 15013 15014 enum ICEKind { 15015 /// This expression is an ICE. 15016 IK_ICE, 15017 /// This expression is not an ICE, but if it isn't evaluated, it's 15018 /// a legal subexpression for an ICE. This return value is used to handle 15019 /// the comma operator in C99 mode, and non-constant subexpressions. 15020 IK_ICEIfUnevaluated, 15021 /// This expression is not an ICE, and is not a legal subexpression for one. 15022 IK_NotICE 15023 }; 15024 15025 struct ICEDiag { 15026 ICEKind Kind; 15027 SourceLocation Loc; 15028 15029 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15030 }; 15031 15032 } 15033 15034 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15035 15036 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15037 15038 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15039 Expr::EvalResult EVResult; 15040 Expr::EvalStatus Status; 15041 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15042 15043 Info.InConstantContext = true; 15044 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15045 !EVResult.Val.isInt()) 15046 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15047 15048 return NoDiag(); 15049 } 15050 15051 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15052 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15053 if (!E->getType()->isIntegralOrEnumerationType()) 15054 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15055 15056 switch (E->getStmtClass()) { 15057 #define ABSTRACT_STMT(Node) 15058 #define STMT(Node, Base) case Expr::Node##Class: 15059 #define EXPR(Node, Base) 15060 #include "clang/AST/StmtNodes.inc" 15061 case Expr::PredefinedExprClass: 15062 case Expr::FloatingLiteralClass: 15063 case Expr::ImaginaryLiteralClass: 15064 case Expr::StringLiteralClass: 15065 case Expr::ArraySubscriptExprClass: 15066 case Expr::MatrixSubscriptExprClass: 15067 case Expr::OMPArraySectionExprClass: 15068 case Expr::OMPArrayShapingExprClass: 15069 case Expr::OMPIteratorExprClass: 15070 case Expr::MemberExprClass: 15071 case Expr::CompoundAssignOperatorClass: 15072 case Expr::CompoundLiteralExprClass: 15073 case Expr::ExtVectorElementExprClass: 15074 case Expr::DesignatedInitExprClass: 15075 case Expr::ArrayInitLoopExprClass: 15076 case Expr::ArrayInitIndexExprClass: 15077 case Expr::NoInitExprClass: 15078 case Expr::DesignatedInitUpdateExprClass: 15079 case Expr::ImplicitValueInitExprClass: 15080 case Expr::ParenListExprClass: 15081 case Expr::VAArgExprClass: 15082 case Expr::AddrLabelExprClass: 15083 case Expr::StmtExprClass: 15084 case Expr::CXXMemberCallExprClass: 15085 case Expr::CUDAKernelCallExprClass: 15086 case Expr::CXXAddrspaceCastExprClass: 15087 case Expr::CXXDynamicCastExprClass: 15088 case Expr::CXXTypeidExprClass: 15089 case Expr::CXXUuidofExprClass: 15090 case Expr::MSPropertyRefExprClass: 15091 case Expr::MSPropertySubscriptExprClass: 15092 case Expr::CXXNullPtrLiteralExprClass: 15093 case Expr::UserDefinedLiteralClass: 15094 case Expr::CXXThisExprClass: 15095 case Expr::CXXThrowExprClass: 15096 case Expr::CXXNewExprClass: 15097 case Expr::CXXDeleteExprClass: 15098 case Expr::CXXPseudoDestructorExprClass: 15099 case Expr::UnresolvedLookupExprClass: 15100 case Expr::TypoExprClass: 15101 case Expr::RecoveryExprClass: 15102 case Expr::DependentScopeDeclRefExprClass: 15103 case Expr::CXXConstructExprClass: 15104 case Expr::CXXInheritedCtorInitExprClass: 15105 case Expr::CXXStdInitializerListExprClass: 15106 case Expr::CXXBindTemporaryExprClass: 15107 case Expr::ExprWithCleanupsClass: 15108 case Expr::CXXTemporaryObjectExprClass: 15109 case Expr::CXXUnresolvedConstructExprClass: 15110 case Expr::CXXDependentScopeMemberExprClass: 15111 case Expr::UnresolvedMemberExprClass: 15112 case Expr::ObjCStringLiteralClass: 15113 case Expr::ObjCBoxedExprClass: 15114 case Expr::ObjCArrayLiteralClass: 15115 case Expr::ObjCDictionaryLiteralClass: 15116 case Expr::ObjCEncodeExprClass: 15117 case Expr::ObjCMessageExprClass: 15118 case Expr::ObjCSelectorExprClass: 15119 case Expr::ObjCProtocolExprClass: 15120 case Expr::ObjCIvarRefExprClass: 15121 case Expr::ObjCPropertyRefExprClass: 15122 case Expr::ObjCSubscriptRefExprClass: 15123 case Expr::ObjCIsaExprClass: 15124 case Expr::ObjCAvailabilityCheckExprClass: 15125 case Expr::ShuffleVectorExprClass: 15126 case Expr::ConvertVectorExprClass: 15127 case Expr::BlockExprClass: 15128 case Expr::NoStmtClass: 15129 case Expr::OpaqueValueExprClass: 15130 case Expr::PackExpansionExprClass: 15131 case Expr::SubstNonTypeTemplateParmPackExprClass: 15132 case Expr::FunctionParmPackExprClass: 15133 case Expr::AsTypeExprClass: 15134 case Expr::ObjCIndirectCopyRestoreExprClass: 15135 case Expr::MaterializeTemporaryExprClass: 15136 case Expr::PseudoObjectExprClass: 15137 case Expr::AtomicExprClass: 15138 case Expr::LambdaExprClass: 15139 case Expr::CXXFoldExprClass: 15140 case Expr::CoawaitExprClass: 15141 case Expr::DependentCoawaitExprClass: 15142 case Expr::CoyieldExprClass: 15143 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15144 15145 case Expr::InitListExprClass: { 15146 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15147 // form "T x = { a };" is equivalent to "T x = a;". 15148 // Unless we're initializing a reference, T is a scalar as it is known to be 15149 // of integral or enumeration type. 15150 if (E->isRValue()) 15151 if (cast<InitListExpr>(E)->getNumInits() == 1) 15152 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15153 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15154 } 15155 15156 case Expr::SizeOfPackExprClass: 15157 case Expr::GNUNullExprClass: 15158 case Expr::SourceLocExprClass: 15159 return NoDiag(); 15160 15161 case Expr::SubstNonTypeTemplateParmExprClass: 15162 return 15163 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15164 15165 case Expr::ConstantExprClass: 15166 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15167 15168 case Expr::ParenExprClass: 15169 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15170 case Expr::GenericSelectionExprClass: 15171 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15172 case Expr::IntegerLiteralClass: 15173 case Expr::FixedPointLiteralClass: 15174 case Expr::CharacterLiteralClass: 15175 case Expr::ObjCBoolLiteralExprClass: 15176 case Expr::CXXBoolLiteralExprClass: 15177 case Expr::CXXScalarValueInitExprClass: 15178 case Expr::TypeTraitExprClass: 15179 case Expr::ConceptSpecializationExprClass: 15180 case Expr::RequiresExprClass: 15181 case Expr::ArrayTypeTraitExprClass: 15182 case Expr::ExpressionTraitExprClass: 15183 case Expr::CXXNoexceptExprClass: 15184 return NoDiag(); 15185 case Expr::CallExprClass: 15186 case Expr::CXXOperatorCallExprClass: { 15187 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15188 // constant expressions, but they can never be ICEs because an ICE cannot 15189 // contain an operand of (pointer to) function type. 15190 const CallExpr *CE = cast<CallExpr>(E); 15191 if (CE->getBuiltinCallee()) 15192 return CheckEvalInICE(E, Ctx); 15193 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15194 } 15195 case Expr::CXXRewrittenBinaryOperatorClass: 15196 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15197 Ctx); 15198 case Expr::DeclRefExprClass: { 15199 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15200 if (isa<EnumConstantDecl>(D)) 15201 return NoDiag(); 15202 15203 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15204 // integer variables in constant expressions: 15205 // 15206 // C++ 7.1.5.1p2 15207 // A variable of non-volatile const-qualified integral or enumeration 15208 // type initialized by an ICE can be used in ICEs. 15209 // 15210 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15211 // that mode, use of reference variables should not be allowed. 15212 const VarDecl *VD = dyn_cast<VarDecl>(D); 15213 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15214 !VD->getType()->isReferenceType()) 15215 return NoDiag(); 15216 15217 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15218 } 15219 case Expr::UnaryOperatorClass: { 15220 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15221 switch (Exp->getOpcode()) { 15222 case UO_PostInc: 15223 case UO_PostDec: 15224 case UO_PreInc: 15225 case UO_PreDec: 15226 case UO_AddrOf: 15227 case UO_Deref: 15228 case UO_Coawait: 15229 // C99 6.6/3 allows increment and decrement within unevaluated 15230 // subexpressions of constant expressions, but they can never be ICEs 15231 // because an ICE cannot contain an lvalue operand. 15232 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15233 case UO_Extension: 15234 case UO_LNot: 15235 case UO_Plus: 15236 case UO_Minus: 15237 case UO_Not: 15238 case UO_Real: 15239 case UO_Imag: 15240 return CheckICE(Exp->getSubExpr(), Ctx); 15241 } 15242 llvm_unreachable("invalid unary operator class"); 15243 } 15244 case Expr::OffsetOfExprClass: { 15245 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15246 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15247 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15248 // compliance: we should warn earlier for offsetof expressions with 15249 // array subscripts that aren't ICEs, and if the array subscripts 15250 // are ICEs, the value of the offsetof must be an integer constant. 15251 return CheckEvalInICE(E, Ctx); 15252 } 15253 case Expr::UnaryExprOrTypeTraitExprClass: { 15254 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15255 if ((Exp->getKind() == UETT_SizeOf) && 15256 Exp->getTypeOfArgument()->isVariableArrayType()) 15257 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15258 return NoDiag(); 15259 } 15260 case Expr::BinaryOperatorClass: { 15261 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15262 switch (Exp->getOpcode()) { 15263 case BO_PtrMemD: 15264 case BO_PtrMemI: 15265 case BO_Assign: 15266 case BO_MulAssign: 15267 case BO_DivAssign: 15268 case BO_RemAssign: 15269 case BO_AddAssign: 15270 case BO_SubAssign: 15271 case BO_ShlAssign: 15272 case BO_ShrAssign: 15273 case BO_AndAssign: 15274 case BO_XorAssign: 15275 case BO_OrAssign: 15276 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15277 // constant expressions, but they can never be ICEs because an ICE cannot 15278 // contain an lvalue operand. 15279 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15280 15281 case BO_Mul: 15282 case BO_Div: 15283 case BO_Rem: 15284 case BO_Add: 15285 case BO_Sub: 15286 case BO_Shl: 15287 case BO_Shr: 15288 case BO_LT: 15289 case BO_GT: 15290 case BO_LE: 15291 case BO_GE: 15292 case BO_EQ: 15293 case BO_NE: 15294 case BO_And: 15295 case BO_Xor: 15296 case BO_Or: 15297 case BO_Comma: 15298 case BO_Cmp: { 15299 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15300 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15301 if (Exp->getOpcode() == BO_Div || 15302 Exp->getOpcode() == BO_Rem) { 15303 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15304 // we don't evaluate one. 15305 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15306 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15307 if (REval == 0) 15308 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15309 if (REval.isSigned() && REval.isAllOnesValue()) { 15310 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15311 if (LEval.isMinSignedValue()) 15312 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15313 } 15314 } 15315 } 15316 if (Exp->getOpcode() == BO_Comma) { 15317 if (Ctx.getLangOpts().C99) { 15318 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15319 // if it isn't evaluated. 15320 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15321 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15322 } else { 15323 // In both C89 and C++, commas in ICEs are illegal. 15324 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15325 } 15326 } 15327 return Worst(LHSResult, RHSResult); 15328 } 15329 case BO_LAnd: 15330 case BO_LOr: { 15331 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15332 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15333 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15334 // Rare case where the RHS has a comma "side-effect"; we need 15335 // to actually check the condition to see whether the side 15336 // with the comma is evaluated. 15337 if ((Exp->getOpcode() == BO_LAnd) != 15338 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15339 return RHSResult; 15340 return NoDiag(); 15341 } 15342 15343 return Worst(LHSResult, RHSResult); 15344 } 15345 } 15346 llvm_unreachable("invalid binary operator kind"); 15347 } 15348 case Expr::ImplicitCastExprClass: 15349 case Expr::CStyleCastExprClass: 15350 case Expr::CXXFunctionalCastExprClass: 15351 case Expr::CXXStaticCastExprClass: 15352 case Expr::CXXReinterpretCastExprClass: 15353 case Expr::CXXConstCastExprClass: 15354 case Expr::ObjCBridgedCastExprClass: { 15355 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15356 if (isa<ExplicitCastExpr>(E)) { 15357 if (const FloatingLiteral *FL 15358 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15359 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15360 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15361 APSInt IgnoredVal(DestWidth, !DestSigned); 15362 bool Ignored; 15363 // If the value does not fit in the destination type, the behavior is 15364 // undefined, so we are not required to treat it as a constant 15365 // expression. 15366 if (FL->getValue().convertToInteger(IgnoredVal, 15367 llvm::APFloat::rmTowardZero, 15368 &Ignored) & APFloat::opInvalidOp) 15369 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15370 return NoDiag(); 15371 } 15372 } 15373 switch (cast<CastExpr>(E)->getCastKind()) { 15374 case CK_LValueToRValue: 15375 case CK_AtomicToNonAtomic: 15376 case CK_NonAtomicToAtomic: 15377 case CK_NoOp: 15378 case CK_IntegralToBoolean: 15379 case CK_IntegralCast: 15380 return CheckICE(SubExpr, Ctx); 15381 default: 15382 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15383 } 15384 } 15385 case Expr::BinaryConditionalOperatorClass: { 15386 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15387 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15388 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15389 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15390 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15391 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15392 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15393 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15394 return FalseResult; 15395 } 15396 case Expr::ConditionalOperatorClass: { 15397 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15398 // If the condition (ignoring parens) is a __builtin_constant_p call, 15399 // then only the true side is actually considered in an integer constant 15400 // expression, and it is fully evaluated. This is an important GNU 15401 // extension. See GCC PR38377 for discussion. 15402 if (const CallExpr *CallCE 15403 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15404 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15405 return CheckEvalInICE(E, Ctx); 15406 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15407 if (CondResult.Kind == IK_NotICE) 15408 return CondResult; 15409 15410 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15411 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15412 15413 if (TrueResult.Kind == IK_NotICE) 15414 return TrueResult; 15415 if (FalseResult.Kind == IK_NotICE) 15416 return FalseResult; 15417 if (CondResult.Kind == IK_ICEIfUnevaluated) 15418 return CondResult; 15419 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15420 return NoDiag(); 15421 // Rare case where the diagnostics depend on which side is evaluated 15422 // Note that if we get here, CondResult is 0, and at least one of 15423 // TrueResult and FalseResult is non-zero. 15424 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15425 return FalseResult; 15426 return TrueResult; 15427 } 15428 case Expr::CXXDefaultArgExprClass: 15429 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15430 case Expr::CXXDefaultInitExprClass: 15431 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15432 case Expr::ChooseExprClass: { 15433 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15434 } 15435 case Expr::BuiltinBitCastExprClass: { 15436 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15437 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15438 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15439 } 15440 } 15441 15442 llvm_unreachable("Invalid StmtClass!"); 15443 } 15444 15445 /// Evaluate an expression as a C++11 integral constant expression. 15446 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15447 const Expr *E, 15448 llvm::APSInt *Value, 15449 SourceLocation *Loc) { 15450 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15451 if (Loc) *Loc = E->getExprLoc(); 15452 return false; 15453 } 15454 15455 APValue Result; 15456 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15457 return false; 15458 15459 if (!Result.isInt()) { 15460 if (Loc) *Loc = E->getExprLoc(); 15461 return false; 15462 } 15463 15464 if (Value) *Value = Result.getInt(); 15465 return true; 15466 } 15467 15468 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15469 SourceLocation *Loc) const { 15470 assert(!isValueDependent() && 15471 "Expression evaluator can't be called on a dependent expression."); 15472 15473 if (Ctx.getLangOpts().CPlusPlus11) 15474 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15475 15476 ICEDiag D = CheckICE(this, Ctx); 15477 if (D.Kind != IK_ICE) { 15478 if (Loc) *Loc = D.Loc; 15479 return false; 15480 } 15481 return true; 15482 } 15483 15484 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15485 SourceLocation *Loc, 15486 bool isEvaluated) const { 15487 assert(!isValueDependent() && 15488 "Expression evaluator can't be called on a dependent expression."); 15489 15490 APSInt Value; 15491 15492 if (Ctx.getLangOpts().CPlusPlus11) { 15493 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15494 return Value; 15495 return None; 15496 } 15497 15498 if (!isIntegerConstantExpr(Ctx, Loc)) 15499 return None; 15500 15501 // The only possible side-effects here are due to UB discovered in the 15502 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15503 // required to treat the expression as an ICE, so we produce the folded 15504 // value. 15505 EvalResult ExprResult; 15506 Expr::EvalStatus Status; 15507 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15508 Info.InConstantContext = true; 15509 15510 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15511 llvm_unreachable("ICE cannot be evaluated!"); 15512 15513 return ExprResult.Val.getInt(); 15514 } 15515 15516 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15517 assert(!isValueDependent() && 15518 "Expression evaluator can't be called on a dependent expression."); 15519 15520 return CheckICE(this, Ctx).Kind == IK_ICE; 15521 } 15522 15523 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15524 SourceLocation *Loc) const { 15525 assert(!isValueDependent() && 15526 "Expression evaluator can't be called on a dependent expression."); 15527 15528 // We support this checking in C++98 mode in order to diagnose compatibility 15529 // issues. 15530 assert(Ctx.getLangOpts().CPlusPlus); 15531 15532 // Build evaluation settings. 15533 Expr::EvalStatus Status; 15534 SmallVector<PartialDiagnosticAt, 8> Diags; 15535 Status.Diag = &Diags; 15536 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15537 15538 APValue Scratch; 15539 bool IsConstExpr = 15540 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15541 // FIXME: We don't produce a diagnostic for this, but the callers that 15542 // call us on arbitrary full-expressions should generally not care. 15543 Info.discardCleanups() && !Status.HasSideEffects; 15544 15545 if (!Diags.empty()) { 15546 IsConstExpr = false; 15547 if (Loc) *Loc = Diags[0].first; 15548 } else if (!IsConstExpr) { 15549 // FIXME: This shouldn't happen. 15550 if (Loc) *Loc = getExprLoc(); 15551 } 15552 15553 return IsConstExpr; 15554 } 15555 15556 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15557 const FunctionDecl *Callee, 15558 ArrayRef<const Expr*> Args, 15559 const Expr *This) const { 15560 assert(!isValueDependent() && 15561 "Expression evaluator can't be called on a dependent expression."); 15562 15563 Expr::EvalStatus Status; 15564 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15565 Info.InConstantContext = true; 15566 15567 LValue ThisVal; 15568 const LValue *ThisPtr = nullptr; 15569 if (This) { 15570 #ifndef NDEBUG 15571 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15572 assert(MD && "Don't provide `this` for non-methods."); 15573 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15574 #endif 15575 if (!This->isValueDependent() && 15576 EvaluateObjectArgument(Info, This, ThisVal) && 15577 !Info.EvalStatus.HasSideEffects) 15578 ThisPtr = &ThisVal; 15579 15580 // Ignore any side-effects from a failed evaluation. This is safe because 15581 // they can't interfere with any other argument evaluation. 15582 Info.EvalStatus.HasSideEffects = false; 15583 } 15584 15585 CallRef Call = Info.CurrentCall->createCall(Callee); 15586 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15587 I != E; ++I) { 15588 unsigned Idx = I - Args.begin(); 15589 if (Idx >= Callee->getNumParams()) 15590 break; 15591 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15592 if ((*I)->isValueDependent() || 15593 !EvaluateCallArg(PVD, *I, Call, Info) || 15594 Info.EvalStatus.HasSideEffects) { 15595 // If evaluation fails, throw away the argument entirely. 15596 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15597 *Slot = APValue(); 15598 } 15599 15600 // Ignore any side-effects from a failed evaluation. This is safe because 15601 // they can't interfere with any other argument evaluation. 15602 Info.EvalStatus.HasSideEffects = false; 15603 } 15604 15605 // Parameter cleanups happen in the caller and are not part of this 15606 // evaluation. 15607 Info.discardCleanups(); 15608 Info.EvalStatus.HasSideEffects = false; 15609 15610 // Build fake call to Callee. 15611 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15612 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15613 FullExpressionRAII Scope(Info); 15614 return Evaluate(Value, Info, this) && Scope.destroy() && 15615 !Info.EvalStatus.HasSideEffects; 15616 } 15617 15618 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15619 SmallVectorImpl< 15620 PartialDiagnosticAt> &Diags) { 15621 // FIXME: It would be useful to check constexpr function templates, but at the 15622 // moment the constant expression evaluator cannot cope with the non-rigorous 15623 // ASTs which we build for dependent expressions. 15624 if (FD->isDependentContext()) 15625 return true; 15626 15627 Expr::EvalStatus Status; 15628 Status.Diag = &Diags; 15629 15630 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15631 Info.InConstantContext = true; 15632 Info.CheckingPotentialConstantExpression = true; 15633 15634 // The constexpr VM attempts to compile all methods to bytecode here. 15635 if (Info.EnableNewConstInterp) { 15636 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15637 return Diags.empty(); 15638 } 15639 15640 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15641 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15642 15643 // Fabricate an arbitrary expression on the stack and pretend that it 15644 // is a temporary being used as the 'this' pointer. 15645 LValue This; 15646 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15647 This.set({&VIE, Info.CurrentCall->Index}); 15648 15649 ArrayRef<const Expr*> Args; 15650 15651 APValue Scratch; 15652 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15653 // Evaluate the call as a constant initializer, to allow the construction 15654 // of objects of non-literal types. 15655 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15656 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15657 } else { 15658 SourceLocation Loc = FD->getLocation(); 15659 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15660 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15661 } 15662 15663 return Diags.empty(); 15664 } 15665 15666 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15667 const FunctionDecl *FD, 15668 SmallVectorImpl< 15669 PartialDiagnosticAt> &Diags) { 15670 assert(!E->isValueDependent() && 15671 "Expression evaluator can't be called on a dependent expression."); 15672 15673 Expr::EvalStatus Status; 15674 Status.Diag = &Diags; 15675 15676 EvalInfo Info(FD->getASTContext(), Status, 15677 EvalInfo::EM_ConstantExpressionUnevaluated); 15678 Info.InConstantContext = true; 15679 Info.CheckingPotentialConstantExpression = true; 15680 15681 // Fabricate a call stack frame to give the arguments a plausible cover story. 15682 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15683 15684 APValue ResultScratch; 15685 Evaluate(ResultScratch, Info, E); 15686 return Diags.empty(); 15687 } 15688 15689 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15690 unsigned Type) const { 15691 if (!getType()->isPointerType()) 15692 return false; 15693 15694 Expr::EvalStatus Status; 15695 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15696 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15697 } 15698