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 if (!B) return QualType(); 83 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 84 // FIXME: It's unclear where we're supposed to take the type from, and 85 // this actually matters for arrays of unknown bound. Eg: 86 // 87 // extern int arr[]; void f() { extern int arr[3]; }; 88 // constexpr int *p = &arr[1]; // valid? 89 // 90 // For now, we take the array bound from the most recent declaration. 91 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 92 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 93 QualType T = Redecl->getType(); 94 if (!T->isIncompleteArrayType()) 95 return T; 96 } 97 return D->getType(); 98 } 99 100 if (B.is<TypeInfoLValue>()) 101 return B.getTypeInfoType(); 102 103 if (B.is<DynamicAllocLValue>()) 104 return B.getDynamicAllocType(); 105 106 const Expr *Base = B.get<const Expr*>(); 107 108 // For a materialized temporary, the type of the temporary we materialized 109 // may not be the type of the expression. 110 if (const MaterializeTemporaryExpr *MTE = 111 dyn_cast<MaterializeTemporaryExpr>(Base)) { 112 SmallVector<const Expr *, 2> CommaLHSs; 113 SmallVector<SubobjectAdjustment, 2> Adjustments; 114 const Expr *Temp = MTE->getSubExpr(); 115 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 116 Adjustments); 117 // Keep any cv-qualifiers from the reference if we generated a temporary 118 // for it directly. Otherwise use the type after adjustment. 119 if (!Adjustments.empty()) 120 return Inner->getType(); 121 } 122 123 return Base->getType(); 124 } 125 126 /// Get an LValue path entry, which is known to not be an array index, as a 127 /// field declaration. 128 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 129 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 130 } 131 /// Get an LValue path entry, which is known to not be an array index, as a 132 /// base class declaration. 133 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 134 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 135 } 136 /// Determine whether this LValue path entry for a base class names a virtual 137 /// base class. 138 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 139 return E.getAsBaseOrMember().getInt(); 140 } 141 142 /// Given an expression, determine the type used to store the result of 143 /// evaluating that expression. 144 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 145 if (E->isRValue()) 146 return E->getType(); 147 return Ctx.getLValueReferenceType(E->getType()); 148 } 149 150 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 151 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 152 const FunctionDecl *Callee = CE->getDirectCallee(); 153 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 154 } 155 156 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 157 /// This will look through a single cast. 158 /// 159 /// Returns null if we couldn't unwrap a function with alloc_size. 160 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 161 if (!E->getType()->isPointerType()) 162 return nullptr; 163 164 E = E->IgnoreParens(); 165 // If we're doing a variable assignment from e.g. malloc(N), there will 166 // probably be a cast of some kind. In exotic cases, we might also see a 167 // top-level ExprWithCleanups. Ignore them either way. 168 if (const auto *FE = dyn_cast<FullExpr>(E)) 169 E = FE->getSubExpr()->IgnoreParens(); 170 171 if (const auto *Cast = dyn_cast<CastExpr>(E)) 172 E = Cast->getSubExpr()->IgnoreParens(); 173 174 if (const auto *CE = dyn_cast<CallExpr>(E)) 175 return getAllocSizeAttr(CE) ? CE : nullptr; 176 return nullptr; 177 } 178 179 /// Determines whether or not the given Base contains a call to a function 180 /// with the alloc_size attribute. 181 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 182 const auto *E = Base.dyn_cast<const Expr *>(); 183 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 184 } 185 186 /// The bound to claim that an array of unknown bound has. 187 /// The value in MostDerivedArraySize is undefined in this case. So, set it 188 /// to an arbitrary value that's likely to loudly break things if it's used. 189 static const uint64_t AssumedSizeForUnsizedArray = 190 std::numeric_limits<uint64_t>::max() / 2; 191 192 /// Determines if an LValue with the given LValueBase will have an unsized 193 /// array in its designator. 194 /// Find the path length and type of the most-derived subobject in the given 195 /// path, and find the size of the containing array, if any. 196 static unsigned 197 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 198 ArrayRef<APValue::LValuePathEntry> Path, 199 uint64_t &ArraySize, QualType &Type, bool &IsArray, 200 bool &FirstEntryIsUnsizedArray) { 201 // This only accepts LValueBases from APValues, and APValues don't support 202 // arrays that lack size info. 203 assert(!isBaseAnAllocSizeCall(Base) && 204 "Unsized arrays shouldn't appear here"); 205 unsigned MostDerivedLength = 0; 206 Type = getType(Base); 207 208 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 209 if (Type->isArrayType()) { 210 const ArrayType *AT = Ctx.getAsArrayType(Type); 211 Type = AT->getElementType(); 212 MostDerivedLength = I + 1; 213 IsArray = true; 214 215 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 216 ArraySize = CAT->getSize().getZExtValue(); 217 } else { 218 assert(I == 0 && "unexpected unsized array designator"); 219 FirstEntryIsUnsizedArray = true; 220 ArraySize = AssumedSizeForUnsizedArray; 221 } 222 } else if (Type->isAnyComplexType()) { 223 const ComplexType *CT = Type->castAs<ComplexType>(); 224 Type = CT->getElementType(); 225 ArraySize = 2; 226 MostDerivedLength = I + 1; 227 IsArray = true; 228 } else if (const FieldDecl *FD = getAsField(Path[I])) { 229 Type = FD->getType(); 230 ArraySize = 0; 231 MostDerivedLength = I + 1; 232 IsArray = false; 233 } else { 234 // Path[I] describes a base class. 235 ArraySize = 0; 236 IsArray = false; 237 } 238 } 239 return MostDerivedLength; 240 } 241 242 /// A path from a glvalue to a subobject of that glvalue. 243 struct SubobjectDesignator { 244 /// True if the subobject was named in a manner not supported by C++11. Such 245 /// lvalues can still be folded, but they are not core constant expressions 246 /// and we cannot perform lvalue-to-rvalue conversions on them. 247 unsigned Invalid : 1; 248 249 /// Is this a pointer one past the end of an object? 250 unsigned IsOnePastTheEnd : 1; 251 252 /// Indicator of whether the first entry is an unsized array. 253 unsigned FirstEntryIsAnUnsizedArray : 1; 254 255 /// Indicator of whether the most-derived object is an array element. 256 unsigned MostDerivedIsArrayElement : 1; 257 258 /// The length of the path to the most-derived object of which this is a 259 /// subobject. 260 unsigned MostDerivedPathLength : 28; 261 262 /// The size of the array of which the most-derived object is an element. 263 /// This will always be 0 if the most-derived object is not an array 264 /// element. 0 is not an indicator of whether or not the most-derived object 265 /// is an array, however, because 0-length arrays are allowed. 266 /// 267 /// If the current array is an unsized array, the value of this is 268 /// undefined. 269 uint64_t MostDerivedArraySize; 270 271 /// The type of the most derived object referred to by this address. 272 QualType MostDerivedType; 273 274 typedef APValue::LValuePathEntry PathEntry; 275 276 /// The entries on the path from the glvalue to the designated subobject. 277 SmallVector<PathEntry, 8> Entries; 278 279 SubobjectDesignator() : Invalid(true) {} 280 281 explicit SubobjectDesignator(QualType T) 282 : Invalid(false), IsOnePastTheEnd(false), 283 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 284 MostDerivedPathLength(0), MostDerivedArraySize(0), 285 MostDerivedType(T) {} 286 287 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 288 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 289 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 290 MostDerivedPathLength(0), MostDerivedArraySize(0) { 291 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 292 if (!Invalid) { 293 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 294 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 295 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 296 if (V.getLValueBase()) { 297 bool IsArray = false; 298 bool FirstIsUnsizedArray = false; 299 MostDerivedPathLength = findMostDerivedSubobject( 300 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 301 MostDerivedType, IsArray, FirstIsUnsizedArray); 302 MostDerivedIsArrayElement = IsArray; 303 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 304 } 305 } 306 } 307 308 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 309 unsigned NewLength) { 310 if (Invalid) 311 return; 312 313 assert(Base && "cannot truncate path for null pointer"); 314 assert(NewLength <= Entries.size() && "not a truncation"); 315 316 if (NewLength == Entries.size()) 317 return; 318 Entries.resize(NewLength); 319 320 bool IsArray = false; 321 bool FirstIsUnsizedArray = false; 322 MostDerivedPathLength = findMostDerivedSubobject( 323 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 324 FirstIsUnsizedArray); 325 MostDerivedIsArrayElement = IsArray; 326 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 327 } 328 329 void setInvalid() { 330 Invalid = true; 331 Entries.clear(); 332 } 333 334 /// Determine whether the most derived subobject is an array without a 335 /// known bound. 336 bool isMostDerivedAnUnsizedArray() const { 337 assert(!Invalid && "Calling this makes no sense on invalid designators"); 338 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 339 } 340 341 /// Determine what the most derived array's size is. Results in an assertion 342 /// failure if the most derived array lacks a size. 343 uint64_t getMostDerivedArraySize() const { 344 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 345 return MostDerivedArraySize; 346 } 347 348 /// Determine whether this is a one-past-the-end pointer. 349 bool isOnePastTheEnd() const { 350 assert(!Invalid); 351 if (IsOnePastTheEnd) 352 return true; 353 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 354 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 355 MostDerivedArraySize) 356 return true; 357 return false; 358 } 359 360 /// Get the range of valid index adjustments in the form 361 /// {maximum value that can be subtracted from this pointer, 362 /// maximum value that can be added to this pointer} 363 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 364 if (Invalid || isMostDerivedAnUnsizedArray()) 365 return {0, 0}; 366 367 // [expr.add]p4: For the purposes of these operators, a pointer to a 368 // nonarray object behaves the same as a pointer to the first element of 369 // an array of length one with the type of the object as its element type. 370 bool IsArray = MostDerivedPathLength == Entries.size() && 371 MostDerivedIsArrayElement; 372 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 373 : (uint64_t)IsOnePastTheEnd; 374 uint64_t ArraySize = 375 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 376 return {ArrayIndex, ArraySize - ArrayIndex}; 377 } 378 379 /// Check that this refers to a valid subobject. 380 bool isValidSubobject() const { 381 if (Invalid) 382 return false; 383 return !isOnePastTheEnd(); 384 } 385 /// Check that this refers to a valid subobject, and if not, produce a 386 /// relevant diagnostic and set the designator as invalid. 387 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 388 389 /// Get the type of the designated object. 390 QualType getType(ASTContext &Ctx) const { 391 assert(!Invalid && "invalid designator has no subobject type"); 392 return MostDerivedPathLength == Entries.size() 393 ? MostDerivedType 394 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 395 } 396 397 /// Update this designator to refer to the first element within this array. 398 void addArrayUnchecked(const ConstantArrayType *CAT) { 399 Entries.push_back(PathEntry::ArrayIndex(0)); 400 401 // This is a most-derived object. 402 MostDerivedType = CAT->getElementType(); 403 MostDerivedIsArrayElement = true; 404 MostDerivedArraySize = CAT->getSize().getZExtValue(); 405 MostDerivedPathLength = Entries.size(); 406 } 407 /// Update this designator to refer to the first element within the array of 408 /// elements of type T. This is an array of unknown size. 409 void addUnsizedArrayUnchecked(QualType ElemTy) { 410 Entries.push_back(PathEntry::ArrayIndex(0)); 411 412 MostDerivedType = ElemTy; 413 MostDerivedIsArrayElement = true; 414 // The value in MostDerivedArraySize is undefined in this case. So, set it 415 // to an arbitrary value that's likely to loudly break things if it's 416 // used. 417 MostDerivedArraySize = AssumedSizeForUnsizedArray; 418 MostDerivedPathLength = Entries.size(); 419 } 420 /// Update this designator to refer to the given base or member of this 421 /// object. 422 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 423 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 424 425 // If this isn't a base class, it's a new most-derived object. 426 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 427 MostDerivedType = FD->getType(); 428 MostDerivedIsArrayElement = false; 429 MostDerivedArraySize = 0; 430 MostDerivedPathLength = Entries.size(); 431 } 432 } 433 /// Update this designator to refer to the given complex component. 434 void addComplexUnchecked(QualType EltTy, bool Imag) { 435 Entries.push_back(PathEntry::ArrayIndex(Imag)); 436 437 // This is technically a most-derived object, though in practice this 438 // is unlikely to matter. 439 MostDerivedType = EltTy; 440 MostDerivedIsArrayElement = true; 441 MostDerivedArraySize = 2; 442 MostDerivedPathLength = Entries.size(); 443 } 444 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 445 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 446 const APSInt &N); 447 /// Add N to the address of this subobject. 448 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 449 if (Invalid || !N) return; 450 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 451 if (isMostDerivedAnUnsizedArray()) { 452 diagnoseUnsizedArrayPointerArithmetic(Info, E); 453 // Can't verify -- trust that the user is doing the right thing (or if 454 // not, trust that the caller will catch the bad behavior). 455 // FIXME: Should we reject if this overflows, at least? 456 Entries.back() = PathEntry::ArrayIndex( 457 Entries.back().getAsArrayIndex() + TruncatedN); 458 return; 459 } 460 461 // [expr.add]p4: For the purposes of these operators, a pointer to a 462 // nonarray object behaves the same as a pointer to the first element of 463 // an array of length one with the type of the object as its element type. 464 bool IsArray = MostDerivedPathLength == Entries.size() && 465 MostDerivedIsArrayElement; 466 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 467 : (uint64_t)IsOnePastTheEnd; 468 uint64_t ArraySize = 469 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 470 471 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 472 // Calculate the actual index in a wide enough type, so we can include 473 // it in the note. 474 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 475 (llvm::APInt&)N += ArrayIndex; 476 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 477 diagnosePointerArithmetic(Info, E, N); 478 setInvalid(); 479 return; 480 } 481 482 ArrayIndex += TruncatedN; 483 assert(ArrayIndex <= ArraySize && 484 "bounds check succeeded for out-of-bounds index"); 485 486 if (IsArray) 487 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 488 else 489 IsOnePastTheEnd = (ArrayIndex != 0); 490 } 491 }; 492 493 /// A scope at the end of which an object can need to be destroyed. 494 enum class ScopeKind { 495 Block, 496 FullExpression, 497 Call 498 }; 499 500 /// A reference to a particular call and its arguments. 501 struct CallRef { 502 CallRef() : OrigCallee(), CallIndex(0), Version() {} 503 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 504 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 505 506 explicit operator bool() const { return OrigCallee; } 507 508 /// Get the parameter that the caller initialized, corresponding to the 509 /// given parameter in the callee. 510 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 511 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 512 : PVD; 513 } 514 515 /// The callee at the point where the arguments were evaluated. This might 516 /// be different from the actual callee (a different redeclaration, or a 517 /// virtual override), but this function's parameters are the ones that 518 /// appear in the parameter map. 519 const FunctionDecl *OrigCallee; 520 /// The call index of the frame that holds the argument values. 521 unsigned CallIndex; 522 /// The version of the parameters corresponding to this call. 523 unsigned Version; 524 }; 525 526 /// A stack frame in the constexpr call stack. 527 class CallStackFrame : public interp::Frame { 528 public: 529 EvalInfo &Info; 530 531 /// Parent - The caller of this stack frame. 532 CallStackFrame *Caller; 533 534 /// Callee - The function which was called. 535 const FunctionDecl *Callee; 536 537 /// This - The binding for the this pointer in this call, if any. 538 const LValue *This; 539 540 /// Information on how to find the arguments to this call. Our arguments 541 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 542 /// key and this value as the version. 543 CallRef Arguments; 544 545 /// Source location information about the default argument or default 546 /// initializer expression we're evaluating, if any. 547 CurrentSourceLocExprScope CurSourceLocExprScope; 548 549 // Note that we intentionally use std::map here so that references to 550 // values are stable. 551 typedef std::pair<const void *, unsigned> MapKeyTy; 552 typedef std::map<MapKeyTy, APValue> MapTy; 553 /// Temporaries - Temporary lvalues materialized within this stack frame. 554 MapTy Temporaries; 555 556 /// CallLoc - The location of the call expression for this call. 557 SourceLocation CallLoc; 558 559 /// Index - The call index of this call. 560 unsigned Index; 561 562 /// The stack of integers for tracking version numbers for temporaries. 563 SmallVector<unsigned, 2> TempVersionStack = {1}; 564 unsigned CurTempVersion = TempVersionStack.back(); 565 566 unsigned getTempVersion() const { return TempVersionStack.back(); } 567 568 void pushTempVersion() { 569 TempVersionStack.push_back(++CurTempVersion); 570 } 571 572 void popTempVersion() { 573 TempVersionStack.pop_back(); 574 } 575 576 CallRef createCall(const FunctionDecl *Callee) { 577 return {Callee, Index, ++CurTempVersion}; 578 } 579 580 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 581 // on the overall stack usage of deeply-recursing constexpr evaluations. 582 // (We should cache this map rather than recomputing it repeatedly.) 583 // But let's try this and see how it goes; we can look into caching the map 584 // as a later change. 585 586 /// LambdaCaptureFields - Mapping from captured variables/this to 587 /// corresponding data members in the closure class. 588 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 589 FieldDecl *LambdaThisCaptureField; 590 591 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 592 const FunctionDecl *Callee, const LValue *This, 593 CallRef Arguments); 594 ~CallStackFrame(); 595 596 // Return the temporary for Key whose version number is Version. 597 APValue *getTemporary(const void *Key, unsigned Version) { 598 MapKeyTy KV(Key, Version); 599 auto LB = Temporaries.lower_bound(KV); 600 if (LB != Temporaries.end() && LB->first == KV) 601 return &LB->second; 602 // Pair (Key,Version) wasn't found in the map. Check that no elements 603 // in the map have 'Key' as their key. 604 assert((LB == Temporaries.end() || LB->first.first != Key) && 605 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 606 "Element with key 'Key' found in map"); 607 return nullptr; 608 } 609 610 // Return the current temporary for Key in the map. 611 APValue *getCurrentTemporary(const void *Key) { 612 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 613 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 614 return &std::prev(UB)->second; 615 return nullptr; 616 } 617 618 // Return the version number of the current temporary for Key. 619 unsigned getCurrentTemporaryVersion(const void *Key) const { 620 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 621 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 622 return std::prev(UB)->first.second; 623 return 0; 624 } 625 626 /// Allocate storage for an object of type T in this stack frame. 627 /// Populates LV with a handle to the created object. Key identifies 628 /// the temporary within the stack frame, and must not be reused without 629 /// bumping the temporary version number. 630 template<typename KeyT> 631 APValue &createTemporary(const KeyT *Key, QualType T, 632 ScopeKind Scope, LValue &LV); 633 634 /// Allocate storage for a parameter of a function call made in this frame. 635 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 636 637 void describe(llvm::raw_ostream &OS) override; 638 639 Frame *getCaller() const override { return Caller; } 640 SourceLocation getCallLocation() const override { return CallLoc; } 641 const FunctionDecl *getCallee() const override { return Callee; } 642 643 bool isStdFunction() const { 644 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 645 if (DC->isStdNamespace()) 646 return true; 647 return false; 648 } 649 650 private: 651 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 652 ScopeKind Scope); 653 }; 654 655 /// Temporarily override 'this'. 656 class ThisOverrideRAII { 657 public: 658 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 659 : Frame(Frame), OldThis(Frame.This) { 660 if (Enable) 661 Frame.This = NewThis; 662 } 663 ~ThisOverrideRAII() { 664 Frame.This = OldThis; 665 } 666 private: 667 CallStackFrame &Frame; 668 const LValue *OldThis; 669 }; 670 } 671 672 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 673 const LValue &This, QualType ThisType); 674 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 675 APValue::LValueBase LVBase, APValue &Value, 676 QualType T); 677 678 namespace { 679 /// A cleanup, and a flag indicating whether it is lifetime-extended. 680 class Cleanup { 681 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 682 APValue::LValueBase Base; 683 QualType T; 684 685 public: 686 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 687 ScopeKind Scope) 688 : Value(Val, Scope), Base(Base), T(T) {} 689 690 /// Determine whether this cleanup should be performed at the end of the 691 /// given kind of scope. 692 bool isDestroyedAtEndOf(ScopeKind K) const { 693 return (int)Value.getInt() >= (int)K; 694 } 695 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 696 if (RunDestructors) { 697 SourceLocation Loc; 698 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 699 Loc = VD->getLocation(); 700 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 701 Loc = E->getExprLoc(); 702 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 703 } 704 *Value.getPointer() = APValue(); 705 return true; 706 } 707 708 bool hasSideEffect() { 709 return T.isDestructedType(); 710 } 711 }; 712 713 /// A reference to an object whose construction we are currently evaluating. 714 struct ObjectUnderConstruction { 715 APValue::LValueBase Base; 716 ArrayRef<APValue::LValuePathEntry> Path; 717 friend bool operator==(const ObjectUnderConstruction &LHS, 718 const ObjectUnderConstruction &RHS) { 719 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 720 } 721 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 722 return llvm::hash_combine(Obj.Base, Obj.Path); 723 } 724 }; 725 enum class ConstructionPhase { 726 None, 727 Bases, 728 AfterBases, 729 AfterFields, 730 Destroying, 731 DestroyingBases 732 }; 733 } 734 735 namespace llvm { 736 template<> struct DenseMapInfo<ObjectUnderConstruction> { 737 using Base = DenseMapInfo<APValue::LValueBase>; 738 static ObjectUnderConstruction getEmptyKey() { 739 return {Base::getEmptyKey(), {}}; } 740 static ObjectUnderConstruction getTombstoneKey() { 741 return {Base::getTombstoneKey(), {}}; 742 } 743 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 744 return hash_value(Object); 745 } 746 static bool isEqual(const ObjectUnderConstruction &LHS, 747 const ObjectUnderConstruction &RHS) { 748 return LHS == RHS; 749 } 750 }; 751 } 752 753 namespace { 754 /// A dynamically-allocated heap object. 755 struct DynAlloc { 756 /// The value of this heap-allocated object. 757 APValue Value; 758 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 759 /// or a CallExpr (the latter is for direct calls to operator new inside 760 /// std::allocator<T>::allocate). 761 const Expr *AllocExpr = nullptr; 762 763 enum Kind { 764 New, 765 ArrayNew, 766 StdAllocator 767 }; 768 769 /// Get the kind of the allocation. This must match between allocation 770 /// and deallocation. 771 Kind getKind() const { 772 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 773 return NE->isArray() ? ArrayNew : New; 774 assert(isa<CallExpr>(AllocExpr)); 775 return StdAllocator; 776 } 777 }; 778 779 struct DynAllocOrder { 780 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 781 return L.getIndex() < R.getIndex(); 782 } 783 }; 784 785 /// EvalInfo - This is a private struct used by the evaluator to capture 786 /// information about a subexpression as it is folded. It retains information 787 /// about the AST context, but also maintains information about the folded 788 /// expression. 789 /// 790 /// If an expression could be evaluated, it is still possible it is not a C 791 /// "integer constant expression" or constant expression. If not, this struct 792 /// captures information about how and why not. 793 /// 794 /// One bit of information passed *into* the request for constant folding 795 /// indicates whether the subexpression is "evaluated" or not according to C 796 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 797 /// evaluate the expression regardless of what the RHS is, but C only allows 798 /// certain things in certain situations. 799 class EvalInfo : public interp::State { 800 public: 801 ASTContext &Ctx; 802 803 /// EvalStatus - Contains information about the evaluation. 804 Expr::EvalStatus &EvalStatus; 805 806 /// CurrentCall - The top of the constexpr call stack. 807 CallStackFrame *CurrentCall; 808 809 /// CallStackDepth - The number of calls in the call stack right now. 810 unsigned CallStackDepth; 811 812 /// NextCallIndex - The next call index to assign. 813 unsigned NextCallIndex; 814 815 /// StepsLeft - The remaining number of evaluation steps we're permitted 816 /// to perform. This is essentially a limit for the number of statements 817 /// we will evaluate. 818 unsigned StepsLeft; 819 820 /// Enable the experimental new constant interpreter. If an expression is 821 /// not supported by the interpreter, an error is triggered. 822 bool EnableNewConstInterp; 823 824 /// BottomFrame - The frame in which evaluation started. This must be 825 /// initialized after CurrentCall and CallStackDepth. 826 CallStackFrame BottomFrame; 827 828 /// A stack of values whose lifetimes end at the end of some surrounding 829 /// evaluation frame. 830 llvm::SmallVector<Cleanup, 16> CleanupStack; 831 832 /// EvaluatingDecl - This is the declaration whose initializer is being 833 /// evaluated, if any. 834 APValue::LValueBase EvaluatingDecl; 835 836 enum class EvaluatingDeclKind { 837 None, 838 /// We're evaluating the construction of EvaluatingDecl. 839 Ctor, 840 /// We're evaluating the destruction of EvaluatingDecl. 841 Dtor, 842 }; 843 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 844 845 /// EvaluatingDeclValue - This is the value being constructed for the 846 /// declaration whose initializer is being evaluated, if any. 847 APValue *EvaluatingDeclValue; 848 849 /// Set of objects that are currently being constructed. 850 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 851 ObjectsUnderConstruction; 852 853 /// Current heap allocations, along with the location where each was 854 /// allocated. We use std::map here because we need stable addresses 855 /// for the stored APValues. 856 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 857 858 /// The number of heap allocations performed so far in this evaluation. 859 unsigned NumHeapAllocs = 0; 860 861 struct EvaluatingConstructorRAII { 862 EvalInfo &EI; 863 ObjectUnderConstruction Object; 864 bool DidInsert; 865 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 866 bool HasBases) 867 : EI(EI), Object(Object) { 868 DidInsert = 869 EI.ObjectsUnderConstruction 870 .insert({Object, HasBases ? ConstructionPhase::Bases 871 : ConstructionPhase::AfterBases}) 872 .second; 873 } 874 void finishedConstructingBases() { 875 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 876 } 877 void finishedConstructingFields() { 878 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 879 } 880 ~EvaluatingConstructorRAII() { 881 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 882 } 883 }; 884 885 struct EvaluatingDestructorRAII { 886 EvalInfo &EI; 887 ObjectUnderConstruction Object; 888 bool DidInsert; 889 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 890 : EI(EI), Object(Object) { 891 DidInsert = EI.ObjectsUnderConstruction 892 .insert({Object, ConstructionPhase::Destroying}) 893 .second; 894 } 895 void startedDestroyingBases() { 896 EI.ObjectsUnderConstruction[Object] = 897 ConstructionPhase::DestroyingBases; 898 } 899 ~EvaluatingDestructorRAII() { 900 if (DidInsert) 901 EI.ObjectsUnderConstruction.erase(Object); 902 } 903 }; 904 905 ConstructionPhase 906 isEvaluatingCtorDtor(APValue::LValueBase Base, 907 ArrayRef<APValue::LValuePathEntry> Path) { 908 return ObjectsUnderConstruction.lookup({Base, Path}); 909 } 910 911 /// If we're currently speculatively evaluating, the outermost call stack 912 /// depth at which we can mutate state, otherwise 0. 913 unsigned SpeculativeEvaluationDepth = 0; 914 915 /// The current array initialization index, if we're performing array 916 /// initialization. 917 uint64_t ArrayInitIndex = -1; 918 919 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 920 /// notes attached to it will also be stored, otherwise they will not be. 921 bool HasActiveDiagnostic; 922 923 /// Have we emitted a diagnostic explaining why we couldn't constant 924 /// fold (not just why it's not strictly a constant expression)? 925 bool HasFoldFailureDiagnostic; 926 927 /// Whether or not we're in a context where the front end requires a 928 /// constant value. 929 bool InConstantContext; 930 931 /// Whether we're checking that an expression is a potential constant 932 /// expression. If so, do not fail on constructs that could become constant 933 /// later on (such as a use of an undefined global). 934 bool CheckingPotentialConstantExpression = false; 935 936 /// Whether we're checking for an expression that has undefined behavior. 937 /// If so, we will produce warnings if we encounter an operation that is 938 /// always undefined. 939 bool CheckingForUndefinedBehavior = false; 940 941 enum EvaluationMode { 942 /// Evaluate as a constant expression. Stop if we find that the expression 943 /// is not a constant expression. 944 EM_ConstantExpression, 945 946 /// Evaluate as a constant expression. Stop if we find that the expression 947 /// is not a constant expression. Some expressions can be retried in the 948 /// optimizer if we don't constant fold them here, but in an unevaluated 949 /// context we try to fold them immediately since the optimizer never 950 /// gets a chance to look at it. 951 EM_ConstantExpressionUnevaluated, 952 953 /// Fold the expression to a constant. Stop if we hit a side-effect that 954 /// we can't model. 955 EM_ConstantFold, 956 957 /// Evaluate in any way we know how. Don't worry about side-effects that 958 /// can't be modeled. 959 EM_IgnoreSideEffects, 960 } EvalMode; 961 962 /// Are we checking whether the expression is a potential constant 963 /// expression? 964 bool checkingPotentialConstantExpression() const override { 965 return CheckingPotentialConstantExpression; 966 } 967 968 /// Are we checking an expression for overflow? 969 // FIXME: We should check for any kind of undefined or suspicious behavior 970 // in such constructs, not just overflow. 971 bool checkingForUndefinedBehavior() const override { 972 return CheckingForUndefinedBehavior; 973 } 974 975 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 976 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 977 CallStackDepth(0), NextCallIndex(1), 978 StepsLeft(C.getLangOpts().ConstexprStepLimit), 979 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 980 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 981 EvaluatingDecl((const ValueDecl *)nullptr), 982 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 983 HasFoldFailureDiagnostic(false), InConstantContext(false), 984 EvalMode(Mode) {} 985 986 ~EvalInfo() { 987 discardCleanups(); 988 } 989 990 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 991 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 992 EvaluatingDecl = Base; 993 IsEvaluatingDecl = EDK; 994 EvaluatingDeclValue = &Value; 995 } 996 997 bool CheckCallLimit(SourceLocation Loc) { 998 // Don't perform any constexpr calls (other than the call we're checking) 999 // when checking a potential constant expression. 1000 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 1001 return false; 1002 if (NextCallIndex == 0) { 1003 // NextCallIndex has wrapped around. 1004 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1005 return false; 1006 } 1007 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1008 return true; 1009 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1010 << getLangOpts().ConstexprCallDepth; 1011 return false; 1012 } 1013 1014 std::pair<CallStackFrame *, unsigned> 1015 getCallFrameAndDepth(unsigned CallIndex) { 1016 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1017 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1018 // be null in this loop. 1019 unsigned Depth = CallStackDepth; 1020 CallStackFrame *Frame = CurrentCall; 1021 while (Frame->Index > CallIndex) { 1022 Frame = Frame->Caller; 1023 --Depth; 1024 } 1025 if (Frame->Index == CallIndex) 1026 return {Frame, Depth}; 1027 return {nullptr, 0}; 1028 } 1029 1030 bool nextStep(const Stmt *S) { 1031 if (!StepsLeft) { 1032 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1033 return false; 1034 } 1035 --StepsLeft; 1036 return true; 1037 } 1038 1039 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1040 1041 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1042 Optional<DynAlloc*> Result; 1043 auto It = HeapAllocs.find(DA); 1044 if (It != HeapAllocs.end()) 1045 Result = &It->second; 1046 return Result; 1047 } 1048 1049 /// Get the allocated storage for the given parameter of the given call. 1050 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1051 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1052 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1053 : nullptr; 1054 } 1055 1056 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1057 struct StdAllocatorCaller { 1058 unsigned FrameIndex; 1059 QualType ElemType; 1060 explicit operator bool() const { return FrameIndex != 0; }; 1061 }; 1062 1063 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1064 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1065 Call = Call->Caller) { 1066 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1067 if (!MD) 1068 continue; 1069 const IdentifierInfo *FnII = MD->getIdentifier(); 1070 if (!FnII || !FnII->isStr(FnName)) 1071 continue; 1072 1073 const auto *CTSD = 1074 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1075 if (!CTSD) 1076 continue; 1077 1078 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1079 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1080 if (CTSD->isInStdNamespace() && ClassII && 1081 ClassII->isStr("allocator") && TAL.size() >= 1 && 1082 TAL[0].getKind() == TemplateArgument::Type) 1083 return {Call->Index, TAL[0].getAsType()}; 1084 } 1085 1086 return {}; 1087 } 1088 1089 void performLifetimeExtension() { 1090 // Disable the cleanups for lifetime-extended temporaries. 1091 CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1092 CleanupStack.end(), 1093 [](Cleanup &C) { 1094 return !C.isDestroyedAtEndOf( 1095 ScopeKind::FullExpression); 1096 }), 1097 CleanupStack.end()); 1098 } 1099 1100 /// Throw away any remaining cleanups at the end of evaluation. If any 1101 /// cleanups would have had a side-effect, note that as an unmodeled 1102 /// side-effect and return false. Otherwise, return true. 1103 bool discardCleanups() { 1104 for (Cleanup &C : CleanupStack) { 1105 if (C.hasSideEffect() && !noteSideEffect()) { 1106 CleanupStack.clear(); 1107 return false; 1108 } 1109 } 1110 CleanupStack.clear(); 1111 return true; 1112 } 1113 1114 private: 1115 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1116 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1117 1118 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1119 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1120 1121 void setFoldFailureDiagnostic(bool Flag) override { 1122 HasFoldFailureDiagnostic = Flag; 1123 } 1124 1125 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1126 1127 ASTContext &getCtx() const override { return Ctx; } 1128 1129 // If we have a prior diagnostic, it will be noting that the expression 1130 // isn't a constant expression. This diagnostic is more important, 1131 // unless we require this evaluation to produce a constant expression. 1132 // 1133 // FIXME: We might want to show both diagnostics to the user in 1134 // EM_ConstantFold mode. 1135 bool hasPriorDiagnostic() override { 1136 if (!EvalStatus.Diag->empty()) { 1137 switch (EvalMode) { 1138 case EM_ConstantFold: 1139 case EM_IgnoreSideEffects: 1140 if (!HasFoldFailureDiagnostic) 1141 break; 1142 // We've already failed to fold something. Keep that diagnostic. 1143 LLVM_FALLTHROUGH; 1144 case EM_ConstantExpression: 1145 case EM_ConstantExpressionUnevaluated: 1146 setActiveDiagnostic(false); 1147 return true; 1148 } 1149 } 1150 return false; 1151 } 1152 1153 unsigned getCallStackDepth() override { return CallStackDepth; } 1154 1155 public: 1156 /// Should we continue evaluation after encountering a side-effect that we 1157 /// couldn't model? 1158 bool keepEvaluatingAfterSideEffect() { 1159 switch (EvalMode) { 1160 case EM_IgnoreSideEffects: 1161 return true; 1162 1163 case EM_ConstantExpression: 1164 case EM_ConstantExpressionUnevaluated: 1165 case EM_ConstantFold: 1166 // By default, assume any side effect might be valid in some other 1167 // evaluation of this expression from a different context. 1168 return checkingPotentialConstantExpression() || 1169 checkingForUndefinedBehavior(); 1170 } 1171 llvm_unreachable("Missed EvalMode case"); 1172 } 1173 1174 /// Note that we have had a side-effect, and determine whether we should 1175 /// keep evaluating. 1176 bool noteSideEffect() { 1177 EvalStatus.HasSideEffects = true; 1178 return keepEvaluatingAfterSideEffect(); 1179 } 1180 1181 /// Should we continue evaluation after encountering undefined behavior? 1182 bool keepEvaluatingAfterUndefinedBehavior() { 1183 switch (EvalMode) { 1184 case EM_IgnoreSideEffects: 1185 case EM_ConstantFold: 1186 return true; 1187 1188 case EM_ConstantExpression: 1189 case EM_ConstantExpressionUnevaluated: 1190 return checkingForUndefinedBehavior(); 1191 } 1192 llvm_unreachable("Missed EvalMode case"); 1193 } 1194 1195 /// Note that we hit something that was technically undefined behavior, but 1196 /// that we can evaluate past it (such as signed overflow or floating-point 1197 /// division by zero.) 1198 bool noteUndefinedBehavior() override { 1199 EvalStatus.HasUndefinedBehavior = true; 1200 return keepEvaluatingAfterUndefinedBehavior(); 1201 } 1202 1203 /// Should we continue evaluation as much as possible after encountering a 1204 /// construct which can't be reduced to a value? 1205 bool keepEvaluatingAfterFailure() const override { 1206 if (!StepsLeft) 1207 return false; 1208 1209 switch (EvalMode) { 1210 case EM_ConstantExpression: 1211 case EM_ConstantExpressionUnevaluated: 1212 case EM_ConstantFold: 1213 case EM_IgnoreSideEffects: 1214 return checkingPotentialConstantExpression() || 1215 checkingForUndefinedBehavior(); 1216 } 1217 llvm_unreachable("Missed EvalMode case"); 1218 } 1219 1220 /// Notes that we failed to evaluate an expression that other expressions 1221 /// directly depend on, and determine if we should keep evaluating. This 1222 /// should only be called if we actually intend to keep evaluating. 1223 /// 1224 /// Call noteSideEffect() instead if we may be able to ignore the value that 1225 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1226 /// 1227 /// (Foo(), 1) // use noteSideEffect 1228 /// (Foo() || true) // use noteSideEffect 1229 /// Foo() + 1 // use noteFailure 1230 LLVM_NODISCARD bool noteFailure() { 1231 // Failure when evaluating some expression often means there is some 1232 // subexpression whose evaluation was skipped. Therefore, (because we 1233 // don't track whether we skipped an expression when unwinding after an 1234 // evaluation failure) every evaluation failure that bubbles up from a 1235 // subexpression implies that a side-effect has potentially happened. We 1236 // skip setting the HasSideEffects flag to true until we decide to 1237 // continue evaluating after that point, which happens here. 1238 bool KeepGoing = keepEvaluatingAfterFailure(); 1239 EvalStatus.HasSideEffects |= KeepGoing; 1240 return KeepGoing; 1241 } 1242 1243 class ArrayInitLoopIndex { 1244 EvalInfo &Info; 1245 uint64_t OuterIndex; 1246 1247 public: 1248 ArrayInitLoopIndex(EvalInfo &Info) 1249 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1250 Info.ArrayInitIndex = 0; 1251 } 1252 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1253 1254 operator uint64_t&() { return Info.ArrayInitIndex; } 1255 }; 1256 }; 1257 1258 /// Object used to treat all foldable expressions as constant expressions. 1259 struct FoldConstant { 1260 EvalInfo &Info; 1261 bool Enabled; 1262 bool HadNoPriorDiags; 1263 EvalInfo::EvaluationMode OldMode; 1264 1265 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1266 : Info(Info), 1267 Enabled(Enabled), 1268 HadNoPriorDiags(Info.EvalStatus.Diag && 1269 Info.EvalStatus.Diag->empty() && 1270 !Info.EvalStatus.HasSideEffects), 1271 OldMode(Info.EvalMode) { 1272 if (Enabled) 1273 Info.EvalMode = EvalInfo::EM_ConstantFold; 1274 } 1275 void keepDiagnostics() { Enabled = false; } 1276 ~FoldConstant() { 1277 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1278 !Info.EvalStatus.HasSideEffects) 1279 Info.EvalStatus.Diag->clear(); 1280 Info.EvalMode = OldMode; 1281 } 1282 }; 1283 1284 /// RAII object used to set the current evaluation mode to ignore 1285 /// side-effects. 1286 struct IgnoreSideEffectsRAII { 1287 EvalInfo &Info; 1288 EvalInfo::EvaluationMode OldMode; 1289 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1290 : Info(Info), OldMode(Info.EvalMode) { 1291 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1292 } 1293 1294 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1295 }; 1296 1297 /// RAII object used to optionally suppress diagnostics and side-effects from 1298 /// a speculative evaluation. 1299 class SpeculativeEvaluationRAII { 1300 EvalInfo *Info = nullptr; 1301 Expr::EvalStatus OldStatus; 1302 unsigned OldSpeculativeEvaluationDepth; 1303 1304 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1305 Info = Other.Info; 1306 OldStatus = Other.OldStatus; 1307 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1308 Other.Info = nullptr; 1309 } 1310 1311 void maybeRestoreState() { 1312 if (!Info) 1313 return; 1314 1315 Info->EvalStatus = OldStatus; 1316 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1317 } 1318 1319 public: 1320 SpeculativeEvaluationRAII() = default; 1321 1322 SpeculativeEvaluationRAII( 1323 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1324 : Info(&Info), OldStatus(Info.EvalStatus), 1325 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1326 Info.EvalStatus.Diag = NewDiag; 1327 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1328 } 1329 1330 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1331 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1332 moveFromAndCancel(std::move(Other)); 1333 } 1334 1335 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1336 maybeRestoreState(); 1337 moveFromAndCancel(std::move(Other)); 1338 return *this; 1339 } 1340 1341 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1342 }; 1343 1344 /// RAII object wrapping a full-expression or block scope, and handling 1345 /// the ending of the lifetime of temporaries created within it. 1346 template<ScopeKind Kind> 1347 class ScopeRAII { 1348 EvalInfo &Info; 1349 unsigned OldStackSize; 1350 public: 1351 ScopeRAII(EvalInfo &Info) 1352 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1353 // Push a new temporary version. This is needed to distinguish between 1354 // temporaries created in different iterations of a loop. 1355 Info.CurrentCall->pushTempVersion(); 1356 } 1357 bool destroy(bool RunDestructors = true) { 1358 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1359 OldStackSize = -1U; 1360 return OK; 1361 } 1362 ~ScopeRAII() { 1363 if (OldStackSize != -1U) 1364 destroy(false); 1365 // Body moved to a static method to encourage the compiler to inline away 1366 // instances of this class. 1367 Info.CurrentCall->popTempVersion(); 1368 } 1369 private: 1370 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1371 unsigned OldStackSize) { 1372 assert(OldStackSize <= Info.CleanupStack.size() && 1373 "running cleanups out of order?"); 1374 1375 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1376 // for a full-expression scope. 1377 bool Success = true; 1378 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1379 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1380 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1381 Success = false; 1382 break; 1383 } 1384 } 1385 } 1386 1387 // Compact any retained cleanups. 1388 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1389 if (Kind != ScopeKind::Block) 1390 NewEnd = 1391 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1392 return C.isDestroyedAtEndOf(Kind); 1393 }); 1394 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1395 return Success; 1396 } 1397 }; 1398 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1399 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1400 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1401 } 1402 1403 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1404 CheckSubobjectKind CSK) { 1405 if (Invalid) 1406 return false; 1407 if (isOnePastTheEnd()) { 1408 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1409 << CSK; 1410 setInvalid(); 1411 return false; 1412 } 1413 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1414 // must actually be at least one array element; even a VLA cannot have a 1415 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1416 return true; 1417 } 1418 1419 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1420 const Expr *E) { 1421 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1422 // Do not set the designator as invalid: we can represent this situation, 1423 // and correct handling of __builtin_object_size requires us to do so. 1424 } 1425 1426 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1427 const Expr *E, 1428 const APSInt &N) { 1429 // If we're complaining, we must be able to statically determine the size of 1430 // the most derived array. 1431 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1432 Info.CCEDiag(E, diag::note_constexpr_array_index) 1433 << N << /*array*/ 0 1434 << static_cast<unsigned>(getMostDerivedArraySize()); 1435 else 1436 Info.CCEDiag(E, diag::note_constexpr_array_index) 1437 << N << /*non-array*/ 1; 1438 setInvalid(); 1439 } 1440 1441 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1442 const FunctionDecl *Callee, const LValue *This, 1443 CallRef Call) 1444 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1445 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1446 Info.CurrentCall = this; 1447 ++Info.CallStackDepth; 1448 } 1449 1450 CallStackFrame::~CallStackFrame() { 1451 assert(Info.CurrentCall == this && "calls retired out of order"); 1452 --Info.CallStackDepth; 1453 Info.CurrentCall = Caller; 1454 } 1455 1456 static bool isRead(AccessKinds AK) { 1457 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1458 } 1459 1460 static bool isModification(AccessKinds AK) { 1461 switch (AK) { 1462 case AK_Read: 1463 case AK_ReadObjectRepresentation: 1464 case AK_MemberCall: 1465 case AK_DynamicCast: 1466 case AK_TypeId: 1467 return false; 1468 case AK_Assign: 1469 case AK_Increment: 1470 case AK_Decrement: 1471 case AK_Construct: 1472 case AK_Destroy: 1473 return true; 1474 } 1475 llvm_unreachable("unknown access kind"); 1476 } 1477 1478 static bool isAnyAccess(AccessKinds AK) { 1479 return isRead(AK) || isModification(AK); 1480 } 1481 1482 /// Is this an access per the C++ definition? 1483 static bool isFormalAccess(AccessKinds AK) { 1484 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1485 } 1486 1487 /// Is this kind of axcess valid on an indeterminate object value? 1488 static bool isValidIndeterminateAccess(AccessKinds AK) { 1489 switch (AK) { 1490 case AK_Read: 1491 case AK_Increment: 1492 case AK_Decrement: 1493 // These need the object's value. 1494 return false; 1495 1496 case AK_ReadObjectRepresentation: 1497 case AK_Assign: 1498 case AK_Construct: 1499 case AK_Destroy: 1500 // Construction and destruction don't need the value. 1501 return true; 1502 1503 case AK_MemberCall: 1504 case AK_DynamicCast: 1505 case AK_TypeId: 1506 // These aren't really meaningful on scalars. 1507 return true; 1508 } 1509 llvm_unreachable("unknown access kind"); 1510 } 1511 1512 namespace { 1513 struct ComplexValue { 1514 private: 1515 bool IsInt; 1516 1517 public: 1518 APSInt IntReal, IntImag; 1519 APFloat FloatReal, FloatImag; 1520 1521 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1522 1523 void makeComplexFloat() { IsInt = false; } 1524 bool isComplexFloat() const { return !IsInt; } 1525 APFloat &getComplexFloatReal() { return FloatReal; } 1526 APFloat &getComplexFloatImag() { return FloatImag; } 1527 1528 void makeComplexInt() { IsInt = true; } 1529 bool isComplexInt() const { return IsInt; } 1530 APSInt &getComplexIntReal() { return IntReal; } 1531 APSInt &getComplexIntImag() { return IntImag; } 1532 1533 void moveInto(APValue &v) const { 1534 if (isComplexFloat()) 1535 v = APValue(FloatReal, FloatImag); 1536 else 1537 v = APValue(IntReal, IntImag); 1538 } 1539 void setFrom(const APValue &v) { 1540 assert(v.isComplexFloat() || v.isComplexInt()); 1541 if (v.isComplexFloat()) { 1542 makeComplexFloat(); 1543 FloatReal = v.getComplexFloatReal(); 1544 FloatImag = v.getComplexFloatImag(); 1545 } else { 1546 makeComplexInt(); 1547 IntReal = v.getComplexIntReal(); 1548 IntImag = v.getComplexIntImag(); 1549 } 1550 } 1551 }; 1552 1553 struct LValue { 1554 APValue::LValueBase Base; 1555 CharUnits Offset; 1556 SubobjectDesignator Designator; 1557 bool IsNullPtr : 1; 1558 bool InvalidBase : 1; 1559 1560 const APValue::LValueBase getLValueBase() const { return Base; } 1561 CharUnits &getLValueOffset() { return Offset; } 1562 const CharUnits &getLValueOffset() const { return Offset; } 1563 SubobjectDesignator &getLValueDesignator() { return Designator; } 1564 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1565 bool isNullPointer() const { return IsNullPtr;} 1566 1567 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1568 unsigned getLValueVersion() const { return Base.getVersion(); } 1569 1570 void moveInto(APValue &V) const { 1571 if (Designator.Invalid) 1572 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1573 else { 1574 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1575 V = APValue(Base, Offset, Designator.Entries, 1576 Designator.IsOnePastTheEnd, IsNullPtr); 1577 } 1578 } 1579 void setFrom(ASTContext &Ctx, const APValue &V) { 1580 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1581 Base = V.getLValueBase(); 1582 Offset = V.getLValueOffset(); 1583 InvalidBase = false; 1584 Designator = SubobjectDesignator(Ctx, V); 1585 IsNullPtr = V.isNullPointer(); 1586 } 1587 1588 void set(APValue::LValueBase B, bool BInvalid = false) { 1589 #ifndef NDEBUG 1590 // We only allow a few types of invalid bases. Enforce that here. 1591 if (BInvalid) { 1592 const auto *E = B.get<const Expr *>(); 1593 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1594 "Unexpected type of invalid base"); 1595 } 1596 #endif 1597 1598 Base = B; 1599 Offset = CharUnits::fromQuantity(0); 1600 InvalidBase = BInvalid; 1601 Designator = SubobjectDesignator(getType(B)); 1602 IsNullPtr = false; 1603 } 1604 1605 void setNull(ASTContext &Ctx, QualType PointerTy) { 1606 Base = (Expr *)nullptr; 1607 Offset = 1608 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1609 InvalidBase = false; 1610 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1611 IsNullPtr = true; 1612 } 1613 1614 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1615 set(B, true); 1616 } 1617 1618 std::string toString(ASTContext &Ctx, QualType T) const { 1619 APValue Printable; 1620 moveInto(Printable); 1621 return Printable.getAsString(Ctx, T); 1622 } 1623 1624 private: 1625 // Check that this LValue is not based on a null pointer. If it is, produce 1626 // a diagnostic and mark the designator as invalid. 1627 template <typename GenDiagType> 1628 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1629 if (Designator.Invalid) 1630 return false; 1631 if (IsNullPtr) { 1632 GenDiag(); 1633 Designator.setInvalid(); 1634 return false; 1635 } 1636 return true; 1637 } 1638 1639 public: 1640 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1641 CheckSubobjectKind CSK) { 1642 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1643 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1644 }); 1645 } 1646 1647 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1648 AccessKinds AK) { 1649 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1650 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1651 }); 1652 } 1653 1654 // Check this LValue refers to an object. If not, set the designator to be 1655 // invalid and emit a diagnostic. 1656 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1657 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1658 Designator.checkSubobject(Info, E, CSK); 1659 } 1660 1661 void addDecl(EvalInfo &Info, const Expr *E, 1662 const Decl *D, bool Virtual = false) { 1663 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1664 Designator.addDeclUnchecked(D, Virtual); 1665 } 1666 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1667 if (!Designator.Entries.empty()) { 1668 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1669 Designator.setInvalid(); 1670 return; 1671 } 1672 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1673 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1674 Designator.FirstEntryIsAnUnsizedArray = true; 1675 Designator.addUnsizedArrayUnchecked(ElemTy); 1676 } 1677 } 1678 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1679 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1680 Designator.addArrayUnchecked(CAT); 1681 } 1682 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1683 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1684 Designator.addComplexUnchecked(EltTy, Imag); 1685 } 1686 void clearIsNullPointer() { 1687 IsNullPtr = false; 1688 } 1689 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1690 const APSInt &Index, CharUnits ElementSize) { 1691 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1692 // but we're not required to diagnose it and it's valid in C++.) 1693 if (!Index) 1694 return; 1695 1696 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1697 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1698 // offsets. 1699 uint64_t Offset64 = Offset.getQuantity(); 1700 uint64_t ElemSize64 = ElementSize.getQuantity(); 1701 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1702 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1703 1704 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1705 Designator.adjustIndex(Info, E, Index); 1706 clearIsNullPointer(); 1707 } 1708 void adjustOffset(CharUnits N) { 1709 Offset += N; 1710 if (N.getQuantity()) 1711 clearIsNullPointer(); 1712 } 1713 }; 1714 1715 struct MemberPtr { 1716 MemberPtr() {} 1717 explicit MemberPtr(const ValueDecl *Decl) : 1718 DeclAndIsDerivedMember(Decl, false), Path() {} 1719 1720 /// The member or (direct or indirect) field referred to by this member 1721 /// pointer, or 0 if this is a null member pointer. 1722 const ValueDecl *getDecl() const { 1723 return DeclAndIsDerivedMember.getPointer(); 1724 } 1725 /// Is this actually a member of some type derived from the relevant class? 1726 bool isDerivedMember() const { 1727 return DeclAndIsDerivedMember.getInt(); 1728 } 1729 /// Get the class which the declaration actually lives in. 1730 const CXXRecordDecl *getContainingRecord() const { 1731 return cast<CXXRecordDecl>( 1732 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1733 } 1734 1735 void moveInto(APValue &V) const { 1736 V = APValue(getDecl(), isDerivedMember(), Path); 1737 } 1738 void setFrom(const APValue &V) { 1739 assert(V.isMemberPointer()); 1740 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1741 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1742 Path.clear(); 1743 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1744 Path.insert(Path.end(), P.begin(), P.end()); 1745 } 1746 1747 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1748 /// whether the member is a member of some class derived from the class type 1749 /// of the member pointer. 1750 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1751 /// Path - The path of base/derived classes from the member declaration's 1752 /// class (exclusive) to the class type of the member pointer (inclusive). 1753 SmallVector<const CXXRecordDecl*, 4> Path; 1754 1755 /// Perform a cast towards the class of the Decl (either up or down the 1756 /// hierarchy). 1757 bool castBack(const CXXRecordDecl *Class) { 1758 assert(!Path.empty()); 1759 const CXXRecordDecl *Expected; 1760 if (Path.size() >= 2) 1761 Expected = Path[Path.size() - 2]; 1762 else 1763 Expected = getContainingRecord(); 1764 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1765 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1766 // if B does not contain the original member and is not a base or 1767 // derived class of the class containing the original member, the result 1768 // of the cast is undefined. 1769 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1770 // (D::*). We consider that to be a language defect. 1771 return false; 1772 } 1773 Path.pop_back(); 1774 return true; 1775 } 1776 /// Perform a base-to-derived member pointer cast. 1777 bool castToDerived(const CXXRecordDecl *Derived) { 1778 if (!getDecl()) 1779 return true; 1780 if (!isDerivedMember()) { 1781 Path.push_back(Derived); 1782 return true; 1783 } 1784 if (!castBack(Derived)) 1785 return false; 1786 if (Path.empty()) 1787 DeclAndIsDerivedMember.setInt(false); 1788 return true; 1789 } 1790 /// Perform a derived-to-base member pointer cast. 1791 bool castToBase(const CXXRecordDecl *Base) { 1792 if (!getDecl()) 1793 return true; 1794 if (Path.empty()) 1795 DeclAndIsDerivedMember.setInt(true); 1796 if (isDerivedMember()) { 1797 Path.push_back(Base); 1798 return true; 1799 } 1800 return castBack(Base); 1801 } 1802 }; 1803 1804 /// Compare two member pointers, which are assumed to be of the same type. 1805 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1806 if (!LHS.getDecl() || !RHS.getDecl()) 1807 return !LHS.getDecl() && !RHS.getDecl(); 1808 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1809 return false; 1810 return LHS.Path == RHS.Path; 1811 } 1812 } 1813 1814 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1815 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1816 const LValue &This, const Expr *E, 1817 bool AllowNonLiteralTypes = false); 1818 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1819 bool InvalidBaseOK = false); 1820 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1821 bool InvalidBaseOK = false); 1822 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1823 EvalInfo &Info); 1824 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1825 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1826 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1827 EvalInfo &Info); 1828 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1829 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1830 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1831 EvalInfo &Info); 1832 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1833 1834 /// Evaluate an integer or fixed point expression into an APResult. 1835 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1836 EvalInfo &Info); 1837 1838 /// Evaluate only a fixed point expression into an APResult. 1839 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1840 EvalInfo &Info); 1841 1842 //===----------------------------------------------------------------------===// 1843 // Misc utilities 1844 //===----------------------------------------------------------------------===// 1845 1846 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1847 /// preserving its value (by extending by up to one bit as needed). 1848 static void negateAsSigned(APSInt &Int) { 1849 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1850 Int = Int.extend(Int.getBitWidth() + 1); 1851 Int.setIsSigned(true); 1852 } 1853 Int = -Int; 1854 } 1855 1856 template<typename KeyT> 1857 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1858 ScopeKind Scope, LValue &LV) { 1859 unsigned Version = getTempVersion(); 1860 APValue::LValueBase Base(Key, Index, Version); 1861 LV.set(Base); 1862 return createLocal(Base, Key, T, Scope); 1863 } 1864 1865 /// Allocate storage for a parameter of a function call made in this frame. 1866 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1867 LValue &LV) { 1868 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1869 APValue::LValueBase Base(PVD, Index, Args.Version); 1870 LV.set(Base); 1871 // We always destroy parameters at the end of the call, even if we'd allow 1872 // them to live to the end of the full-expression at runtime, in order to 1873 // give portable results and match other compilers. 1874 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1875 } 1876 1877 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1878 QualType T, ScopeKind Scope) { 1879 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1880 unsigned Version = Base.getVersion(); 1881 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1882 assert(Result.isAbsent() && "local created multiple times"); 1883 1884 // If we're creating a local immediately in the operand of a speculative 1885 // evaluation, don't register a cleanup to be run outside the speculative 1886 // evaluation context, since we won't actually be able to initialize this 1887 // object. 1888 if (Index <= Info.SpeculativeEvaluationDepth) { 1889 if (T.isDestructedType()) 1890 Info.noteSideEffect(); 1891 } else { 1892 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1893 } 1894 return Result; 1895 } 1896 1897 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1898 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1899 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1900 return nullptr; 1901 } 1902 1903 DynamicAllocLValue DA(NumHeapAllocs++); 1904 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1905 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1906 std::forward_as_tuple(DA), std::tuple<>()); 1907 assert(Result.second && "reused a heap alloc index?"); 1908 Result.first->second.AllocExpr = E; 1909 return &Result.first->second.Value; 1910 } 1911 1912 /// Produce a string describing the given constexpr call. 1913 void CallStackFrame::describe(raw_ostream &Out) { 1914 unsigned ArgIndex = 0; 1915 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1916 !isa<CXXConstructorDecl>(Callee) && 1917 cast<CXXMethodDecl>(Callee)->isInstance(); 1918 1919 if (!IsMemberCall) 1920 Out << *Callee << '('; 1921 1922 if (This && IsMemberCall) { 1923 APValue Val; 1924 This->moveInto(Val); 1925 Val.printPretty(Out, Info.Ctx, 1926 This->Designator.MostDerivedType); 1927 // FIXME: Add parens around Val if needed. 1928 Out << "->" << *Callee << '('; 1929 IsMemberCall = false; 1930 } 1931 1932 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1933 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1934 if (ArgIndex > (unsigned)IsMemberCall) 1935 Out << ", "; 1936 1937 const ParmVarDecl *Param = *I; 1938 APValue *V = Info.getParamSlot(Arguments, Param); 1939 if (V) 1940 V->printPretty(Out, Info.Ctx, Param->getType()); 1941 else 1942 Out << "<...>"; 1943 1944 if (ArgIndex == 0 && IsMemberCall) 1945 Out << "->" << *Callee << '('; 1946 } 1947 1948 Out << ')'; 1949 } 1950 1951 /// Evaluate an expression to see if it had side-effects, and discard its 1952 /// result. 1953 /// \return \c true if the caller should keep evaluating. 1954 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1955 APValue Scratch; 1956 if (!Evaluate(Scratch, Info, E)) 1957 // We don't need the value, but we might have skipped a side effect here. 1958 return Info.noteSideEffect(); 1959 return true; 1960 } 1961 1962 /// Should this call expression be treated as a string literal? 1963 static bool IsStringLiteralCall(const CallExpr *E) { 1964 unsigned Builtin = E->getBuiltinCallee(); 1965 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1966 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1967 } 1968 1969 static bool IsGlobalLValue(APValue::LValueBase B) { 1970 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1971 // constant expression of pointer type that evaluates to... 1972 1973 // ... a null pointer value, or a prvalue core constant expression of type 1974 // std::nullptr_t. 1975 if (!B) return true; 1976 1977 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1978 // ... the address of an object with static storage duration, 1979 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1980 return VD->hasGlobalStorage(); 1981 // ... the address of a function, 1982 // ... the address of a GUID [MS extension], 1983 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1984 } 1985 1986 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1987 return true; 1988 1989 const Expr *E = B.get<const Expr*>(); 1990 switch (E->getStmtClass()) { 1991 default: 1992 return false; 1993 case Expr::CompoundLiteralExprClass: { 1994 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1995 return CLE->isFileScope() && CLE->isLValue(); 1996 } 1997 case Expr::MaterializeTemporaryExprClass: 1998 // A materialized temporary might have been lifetime-extended to static 1999 // storage duration. 2000 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 2001 // A string literal has static storage duration. 2002 case Expr::StringLiteralClass: 2003 case Expr::PredefinedExprClass: 2004 case Expr::ObjCStringLiteralClass: 2005 case Expr::ObjCEncodeExprClass: 2006 return true; 2007 case Expr::ObjCBoxedExprClass: 2008 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2009 case Expr::CallExprClass: 2010 return IsStringLiteralCall(cast<CallExpr>(E)); 2011 // For GCC compatibility, &&label has static storage duration. 2012 case Expr::AddrLabelExprClass: 2013 return true; 2014 // A Block literal expression may be used as the initialization value for 2015 // Block variables at global or local static scope. 2016 case Expr::BlockExprClass: 2017 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2018 case Expr::ImplicitValueInitExprClass: 2019 // FIXME: 2020 // We can never form an lvalue with an implicit value initialization as its 2021 // base through expression evaluation, so these only appear in one case: the 2022 // implicit variable declaration we invent when checking whether a constexpr 2023 // constructor can produce a constant expression. We must assume that such 2024 // an expression might be a global lvalue. 2025 return true; 2026 } 2027 } 2028 2029 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2030 return LVal.Base.dyn_cast<const ValueDecl*>(); 2031 } 2032 2033 static bool IsLiteralLValue(const LValue &Value) { 2034 if (Value.getLValueCallIndex()) 2035 return false; 2036 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2037 return E && !isa<MaterializeTemporaryExpr>(E); 2038 } 2039 2040 static bool IsWeakLValue(const LValue &Value) { 2041 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2042 return Decl && Decl->isWeak(); 2043 } 2044 2045 static bool isZeroSized(const LValue &Value) { 2046 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2047 if (Decl && isa<VarDecl>(Decl)) { 2048 QualType Ty = Decl->getType(); 2049 if (Ty->isArrayType()) 2050 return Ty->isIncompleteType() || 2051 Decl->getASTContext().getTypeSize(Ty) == 0; 2052 } 2053 return false; 2054 } 2055 2056 static bool HasSameBase(const LValue &A, const LValue &B) { 2057 if (!A.getLValueBase()) 2058 return !B.getLValueBase(); 2059 if (!B.getLValueBase()) 2060 return false; 2061 2062 if (A.getLValueBase().getOpaqueValue() != 2063 B.getLValueBase().getOpaqueValue()) 2064 return false; 2065 2066 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2067 A.getLValueVersion() == B.getLValueVersion(); 2068 } 2069 2070 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2071 assert(Base && "no location for a null lvalue"); 2072 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2073 2074 // For a parameter, find the corresponding call stack frame (if it still 2075 // exists), and point at the parameter of the function definition we actually 2076 // invoked. 2077 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2078 unsigned Idx = PVD->getFunctionScopeIndex(); 2079 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2080 if (F->Arguments.CallIndex == Base.getCallIndex() && 2081 F->Arguments.Version == Base.getVersion() && F->Callee && 2082 Idx < F->Callee->getNumParams()) { 2083 VD = F->Callee->getParamDecl(Idx); 2084 break; 2085 } 2086 } 2087 } 2088 2089 if (VD) 2090 Info.Note(VD->getLocation(), diag::note_declared_at); 2091 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2092 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2093 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2094 // FIXME: Produce a note for dangling pointers too. 2095 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2096 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2097 diag::note_constexpr_dynamic_alloc_here); 2098 } 2099 // We have no information to show for a typeid(T) object. 2100 } 2101 2102 enum class CheckEvaluationResultKind { 2103 ConstantExpression, 2104 FullyInitialized, 2105 }; 2106 2107 /// Materialized temporaries that we've already checked to determine if they're 2108 /// initializsed by a constant expression. 2109 using CheckedTemporaries = 2110 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2111 2112 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2113 EvalInfo &Info, SourceLocation DiagLoc, 2114 QualType Type, const APValue &Value, 2115 Expr::ConstExprUsage Usage, 2116 SourceLocation SubobjectLoc, 2117 CheckedTemporaries &CheckedTemps); 2118 2119 /// Check that this reference or pointer core constant expression is a valid 2120 /// value for an address or reference constant expression. Return true if we 2121 /// can fold this expression, whether or not it's a constant expression. 2122 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2123 QualType Type, const LValue &LVal, 2124 Expr::ConstExprUsage Usage, 2125 CheckedTemporaries &CheckedTemps) { 2126 bool IsReferenceType = Type->isReferenceType(); 2127 2128 APValue::LValueBase Base = LVal.getLValueBase(); 2129 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2130 2131 if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) { 2132 if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 2133 if (FD->isConsteval()) { 2134 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2135 << !Type->isAnyPointerType(); 2136 Info.Note(FD->getLocation(), diag::note_declared_at); 2137 return false; 2138 } 2139 } 2140 } 2141 2142 // Check that the object is a global. Note that the fake 'this' object we 2143 // manufacture when checking potential constant expressions is conservatively 2144 // assumed to be global here. 2145 if (!IsGlobalLValue(Base)) { 2146 if (Info.getLangOpts().CPlusPlus11) { 2147 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2148 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2149 << IsReferenceType << !Designator.Entries.empty() 2150 << !!VD << VD; 2151 2152 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2153 if (VarD && VarD->isConstexpr()) { 2154 // Non-static local constexpr variables have unintuitive semantics: 2155 // constexpr int a = 1; 2156 // constexpr const int *p = &a; 2157 // ... is invalid because the address of 'a' is not constant. Suggest 2158 // adding a 'static' in this case. 2159 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2160 << VarD 2161 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2162 } else { 2163 NoteLValueLocation(Info, Base); 2164 } 2165 } else { 2166 Info.FFDiag(Loc); 2167 } 2168 // Don't allow references to temporaries to escape. 2169 return false; 2170 } 2171 assert((Info.checkingPotentialConstantExpression() || 2172 LVal.getLValueCallIndex() == 0) && 2173 "have call index for global lvalue"); 2174 2175 if (Base.is<DynamicAllocLValue>()) { 2176 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2177 << IsReferenceType << !Designator.Entries.empty(); 2178 NoteLValueLocation(Info, Base); 2179 return false; 2180 } 2181 2182 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 2183 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 2184 // Check if this is a thread-local variable. 2185 if (Var->getTLSKind()) 2186 // FIXME: Diagnostic! 2187 return false; 2188 2189 // A dllimport variable never acts like a constant. 2190 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 2191 // FIXME: Diagnostic! 2192 return false; 2193 } 2194 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 2195 // __declspec(dllimport) must be handled very carefully: 2196 // We must never initialize an expression with the thunk in C++. 2197 // Doing otherwise would allow the same id-expression to yield 2198 // different addresses for the same function in different translation 2199 // units. However, this means that we must dynamically initialize the 2200 // expression with the contents of the import address table at runtime. 2201 // 2202 // The C language has no notion of ODR; furthermore, it has no notion of 2203 // dynamic initialization. This means that we are permitted to 2204 // perform initialization with the address of the thunk. 2205 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 2206 FD->hasAttr<DLLImportAttr>()) 2207 // FIXME: Diagnostic! 2208 return false; 2209 } 2210 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2211 Base.dyn_cast<const Expr *>())) { 2212 if (CheckedTemps.insert(MTE).second) { 2213 QualType TempType = getType(Base); 2214 if (TempType.isDestructedType()) { 2215 Info.FFDiag(MTE->getExprLoc(), 2216 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) 2217 << TempType; 2218 return false; 2219 } 2220 2221 APValue *V = MTE->getOrCreateValue(false); 2222 assert(V && "evasluation result refers to uninitialised temporary"); 2223 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2224 Info, MTE->getExprLoc(), TempType, *V, 2225 Usage, SourceLocation(), CheckedTemps)) 2226 return false; 2227 } 2228 } 2229 2230 // Allow address constant expressions to be past-the-end pointers. This is 2231 // an extension: the standard requires them to point to an object. 2232 if (!IsReferenceType) 2233 return true; 2234 2235 // A reference constant expression must refer to an object. 2236 if (!Base) { 2237 // FIXME: diagnostic 2238 Info.CCEDiag(Loc); 2239 return true; 2240 } 2241 2242 // Does this refer one past the end of some object? 2243 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2244 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2245 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2246 << !Designator.Entries.empty() << !!VD << VD; 2247 NoteLValueLocation(Info, Base); 2248 } 2249 2250 return true; 2251 } 2252 2253 /// Member pointers are constant expressions unless they point to a 2254 /// non-virtual dllimport member function. 2255 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2256 SourceLocation Loc, 2257 QualType Type, 2258 const APValue &Value, 2259 Expr::ConstExprUsage Usage) { 2260 const ValueDecl *Member = Value.getMemberPointerDecl(); 2261 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2262 if (!FD) 2263 return true; 2264 if (FD->isConsteval()) { 2265 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2266 Info.Note(FD->getLocation(), diag::note_declared_at); 2267 return false; 2268 } 2269 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2270 !FD->hasAttr<DLLImportAttr>(); 2271 } 2272 2273 /// Check that this core constant expression is of literal type, and if not, 2274 /// produce an appropriate diagnostic. 2275 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2276 const LValue *This = nullptr) { 2277 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2278 return true; 2279 2280 // C++1y: A constant initializer for an object o [...] may also invoke 2281 // constexpr constructors for o and its subobjects even if those objects 2282 // are of non-literal class types. 2283 // 2284 // C++11 missed this detail for aggregates, so classes like this: 2285 // struct foo_t { union { int i; volatile int j; } u; }; 2286 // are not (obviously) initializable like so: 2287 // __attribute__((__require_constant_initialization__)) 2288 // static const foo_t x = {{0}}; 2289 // because "i" is a subobject with non-literal initialization (due to the 2290 // volatile member of the union). See: 2291 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2292 // Therefore, we use the C++1y behavior. 2293 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2294 return true; 2295 2296 // Prvalue constant expressions must be of literal types. 2297 if (Info.getLangOpts().CPlusPlus11) 2298 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2299 << E->getType(); 2300 else 2301 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2302 return false; 2303 } 2304 2305 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2306 EvalInfo &Info, SourceLocation DiagLoc, 2307 QualType Type, const APValue &Value, 2308 Expr::ConstExprUsage Usage, 2309 SourceLocation SubobjectLoc, 2310 CheckedTemporaries &CheckedTemps) { 2311 if (!Value.hasValue()) { 2312 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2313 << true << Type; 2314 if (SubobjectLoc.isValid()) 2315 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2316 return false; 2317 } 2318 2319 // We allow _Atomic(T) to be initialized from anything that T can be 2320 // initialized from. 2321 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2322 Type = AT->getValueType(); 2323 2324 // Core issue 1454: For a literal constant expression of array or class type, 2325 // each subobject of its value shall have been initialized by a constant 2326 // expression. 2327 if (Value.isArray()) { 2328 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2329 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2330 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2331 Value.getArrayInitializedElt(I), Usage, 2332 SubobjectLoc, CheckedTemps)) 2333 return false; 2334 } 2335 if (!Value.hasArrayFiller()) 2336 return true; 2337 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2338 Value.getArrayFiller(), Usage, SubobjectLoc, 2339 CheckedTemps); 2340 } 2341 if (Value.isUnion() && Value.getUnionField()) { 2342 return CheckEvaluationResult( 2343 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2344 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2345 CheckedTemps); 2346 } 2347 if (Value.isStruct()) { 2348 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2349 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2350 unsigned BaseIndex = 0; 2351 for (const CXXBaseSpecifier &BS : CD->bases()) { 2352 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2353 Value.getStructBase(BaseIndex), Usage, 2354 BS.getBeginLoc(), CheckedTemps)) 2355 return false; 2356 ++BaseIndex; 2357 } 2358 } 2359 for (const auto *I : RD->fields()) { 2360 if (I->isUnnamedBitfield()) 2361 continue; 2362 2363 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2364 Value.getStructField(I->getFieldIndex()), 2365 Usage, I->getLocation(), CheckedTemps)) 2366 return false; 2367 } 2368 } 2369 2370 if (Value.isLValue() && 2371 CERK == CheckEvaluationResultKind::ConstantExpression) { 2372 LValue LVal; 2373 LVal.setFrom(Info.Ctx, Value); 2374 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2375 CheckedTemps); 2376 } 2377 2378 if (Value.isMemberPointer() && 2379 CERK == CheckEvaluationResultKind::ConstantExpression) 2380 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2381 2382 // Everything else is fine. 2383 return true; 2384 } 2385 2386 /// Check that this core constant expression value is a valid value for a 2387 /// constant expression. If not, report an appropriate diagnostic. Does not 2388 /// check that the expression is of literal type. 2389 static bool 2390 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2391 const APValue &Value, 2392 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2393 // Nothing to check for a constant expression of type 'cv void'. 2394 if (Type->isVoidType()) 2395 return true; 2396 2397 CheckedTemporaries CheckedTemps; 2398 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2399 Info, DiagLoc, Type, Value, Usage, 2400 SourceLocation(), CheckedTemps); 2401 } 2402 2403 /// Check that this evaluated value is fully-initialized and can be loaded by 2404 /// an lvalue-to-rvalue conversion. 2405 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2406 QualType Type, const APValue &Value) { 2407 CheckedTemporaries CheckedTemps; 2408 return CheckEvaluationResult( 2409 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2410 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2411 } 2412 2413 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2414 /// "the allocated storage is deallocated within the evaluation". 2415 static bool CheckMemoryLeaks(EvalInfo &Info) { 2416 if (!Info.HeapAllocs.empty()) { 2417 // We can still fold to a constant despite a compile-time memory leak, 2418 // so long as the heap allocation isn't referenced in the result (we check 2419 // that in CheckConstantExpression). 2420 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2421 diag::note_constexpr_memory_leak) 2422 << unsigned(Info.HeapAllocs.size() - 1); 2423 } 2424 return true; 2425 } 2426 2427 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2428 // A null base expression indicates a null pointer. These are always 2429 // evaluatable, and they are false unless the offset is zero. 2430 if (!Value.getLValueBase()) { 2431 Result = !Value.getLValueOffset().isZero(); 2432 return true; 2433 } 2434 2435 // We have a non-null base. These are generally known to be true, but if it's 2436 // a weak declaration it can be null at runtime. 2437 Result = true; 2438 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2439 return !Decl || !Decl->isWeak(); 2440 } 2441 2442 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2443 switch (Val.getKind()) { 2444 case APValue::None: 2445 case APValue::Indeterminate: 2446 return false; 2447 case APValue::Int: 2448 Result = Val.getInt().getBoolValue(); 2449 return true; 2450 case APValue::FixedPoint: 2451 Result = Val.getFixedPoint().getBoolValue(); 2452 return true; 2453 case APValue::Float: 2454 Result = !Val.getFloat().isZero(); 2455 return true; 2456 case APValue::ComplexInt: 2457 Result = Val.getComplexIntReal().getBoolValue() || 2458 Val.getComplexIntImag().getBoolValue(); 2459 return true; 2460 case APValue::ComplexFloat: 2461 Result = !Val.getComplexFloatReal().isZero() || 2462 !Val.getComplexFloatImag().isZero(); 2463 return true; 2464 case APValue::LValue: 2465 return EvalPointerValueAsBool(Val, Result); 2466 case APValue::MemberPointer: 2467 Result = Val.getMemberPointerDecl(); 2468 return true; 2469 case APValue::Vector: 2470 case APValue::Array: 2471 case APValue::Struct: 2472 case APValue::Union: 2473 case APValue::AddrLabelDiff: 2474 return false; 2475 } 2476 2477 llvm_unreachable("unknown APValue kind"); 2478 } 2479 2480 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2481 EvalInfo &Info) { 2482 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2483 APValue Val; 2484 if (!Evaluate(Val, Info, E)) 2485 return false; 2486 return HandleConversionToBool(Val, Result); 2487 } 2488 2489 template<typename T> 2490 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2491 const T &SrcValue, QualType DestType) { 2492 Info.CCEDiag(E, diag::note_constexpr_overflow) 2493 << SrcValue << DestType; 2494 return Info.noteUndefinedBehavior(); 2495 } 2496 2497 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2498 QualType SrcType, const APFloat &Value, 2499 QualType DestType, APSInt &Result) { 2500 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2501 // Determine whether we are converting to unsigned or signed. 2502 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2503 2504 Result = APSInt(DestWidth, !DestSigned); 2505 bool ignored; 2506 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2507 & APFloat::opInvalidOp) 2508 return HandleOverflow(Info, E, Value, DestType); 2509 return true; 2510 } 2511 2512 /// Get rounding mode used for evaluation of the specified expression. 2513 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2514 /// dynamic. 2515 /// If rounding mode is unknown at compile time, still try to evaluate the 2516 /// expression. If the result is exact, it does not depend on rounding mode. 2517 /// So return "tonearest" mode instead of "dynamic". 2518 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2519 bool &DynamicRM) { 2520 llvm::RoundingMode RM = 2521 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2522 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2523 if (DynamicRM) 2524 RM = llvm::RoundingMode::NearestTiesToEven; 2525 return RM; 2526 } 2527 2528 /// Check if the given evaluation result is allowed for constant evaluation. 2529 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2530 APFloat::opStatus St) { 2531 // In a constant context, assume that any dynamic rounding mode or FP 2532 // exception state matches the default floating-point environment. 2533 if (Info.InConstantContext) 2534 return true; 2535 2536 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2537 if ((St & APFloat::opInexact) && 2538 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2539 // Inexact result means that it depends on rounding mode. If the requested 2540 // mode is dynamic, the evaluation cannot be made in compile time. 2541 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2542 return false; 2543 } 2544 2545 if ((St & APFloat::opStatus::opInvalidOp) && 2546 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2547 // There is no usefully definable result. 2548 Info.FFDiag(E); 2549 return false; 2550 } 2551 2552 // FIXME: if: 2553 // - evaluation triggered other FP exception, and 2554 // - exception mode is not "ignore", and 2555 // - the expression being evaluated is not a part of global variable 2556 // initializer, 2557 // the evaluation probably need to be rejected. 2558 return true; 2559 } 2560 2561 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2562 QualType SrcType, QualType DestType, 2563 APFloat &Result) { 2564 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2565 bool DynamicRM; 2566 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2567 APFloat::opStatus St; 2568 APFloat Value = Result; 2569 bool ignored; 2570 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2571 return checkFloatingPointResult(Info, E, St); 2572 } 2573 2574 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2575 QualType DestType, QualType SrcType, 2576 const APSInt &Value) { 2577 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2578 // Figure out if this is a truncate, extend or noop cast. 2579 // If the input is signed, do a sign extend, noop, or truncate. 2580 APSInt Result = Value.extOrTrunc(DestWidth); 2581 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2582 if (DestType->isBooleanType()) 2583 Result = Value.getBoolValue(); 2584 return Result; 2585 } 2586 2587 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2588 QualType SrcType, const APSInt &Value, 2589 QualType DestType, APFloat &Result) { 2590 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2591 Result.convertFromAPInt(Value, Value.isSigned(), 2592 APFloat::rmNearestTiesToEven); 2593 return true; 2594 } 2595 2596 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2597 APValue &Value, const FieldDecl *FD) { 2598 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2599 2600 if (!Value.isInt()) { 2601 // Trying to store a pointer-cast-to-integer into a bitfield. 2602 // FIXME: In this case, we should provide the diagnostic for casting 2603 // a pointer to an integer. 2604 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2605 Info.FFDiag(E); 2606 return false; 2607 } 2608 2609 APSInt &Int = Value.getInt(); 2610 unsigned OldBitWidth = Int.getBitWidth(); 2611 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2612 if (NewBitWidth < OldBitWidth) 2613 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2614 return true; 2615 } 2616 2617 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2618 llvm::APInt &Res) { 2619 APValue SVal; 2620 if (!Evaluate(SVal, Info, E)) 2621 return false; 2622 if (SVal.isInt()) { 2623 Res = SVal.getInt(); 2624 return true; 2625 } 2626 if (SVal.isFloat()) { 2627 Res = SVal.getFloat().bitcastToAPInt(); 2628 return true; 2629 } 2630 if (SVal.isVector()) { 2631 QualType VecTy = E->getType(); 2632 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2633 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2634 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2635 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2636 Res = llvm::APInt::getNullValue(VecSize); 2637 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2638 APValue &Elt = SVal.getVectorElt(i); 2639 llvm::APInt EltAsInt; 2640 if (Elt.isInt()) { 2641 EltAsInt = Elt.getInt(); 2642 } else if (Elt.isFloat()) { 2643 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2644 } else { 2645 // Don't try to handle vectors of anything other than int or float 2646 // (not sure if it's possible to hit this case). 2647 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2648 return false; 2649 } 2650 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2651 if (BigEndian) 2652 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2653 else 2654 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2655 } 2656 return true; 2657 } 2658 // Give up if the input isn't an int, float, or vector. For example, we 2659 // reject "(v4i16)(intptr_t)&a". 2660 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2661 return false; 2662 } 2663 2664 /// Perform the given integer operation, which is known to need at most BitWidth 2665 /// bits, and check for overflow in the original type (if that type was not an 2666 /// unsigned type). 2667 template<typename Operation> 2668 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2669 const APSInt &LHS, const APSInt &RHS, 2670 unsigned BitWidth, Operation Op, 2671 APSInt &Result) { 2672 if (LHS.isUnsigned()) { 2673 Result = Op(LHS, RHS); 2674 return true; 2675 } 2676 2677 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2678 Result = Value.trunc(LHS.getBitWidth()); 2679 if (Result.extend(BitWidth) != Value) { 2680 if (Info.checkingForUndefinedBehavior()) 2681 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2682 diag::warn_integer_constant_overflow) 2683 << Result.toString(10) << E->getType(); 2684 else 2685 return HandleOverflow(Info, E, Value, E->getType()); 2686 } 2687 return true; 2688 } 2689 2690 /// Perform the given binary integer operation. 2691 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2692 BinaryOperatorKind Opcode, APSInt RHS, 2693 APSInt &Result) { 2694 switch (Opcode) { 2695 default: 2696 Info.FFDiag(E); 2697 return false; 2698 case BO_Mul: 2699 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2700 std::multiplies<APSInt>(), Result); 2701 case BO_Add: 2702 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2703 std::plus<APSInt>(), Result); 2704 case BO_Sub: 2705 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2706 std::minus<APSInt>(), Result); 2707 case BO_And: Result = LHS & RHS; return true; 2708 case BO_Xor: Result = LHS ^ RHS; return true; 2709 case BO_Or: Result = LHS | RHS; return true; 2710 case BO_Div: 2711 case BO_Rem: 2712 if (RHS == 0) { 2713 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2714 return false; 2715 } 2716 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2717 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2718 // this operation and gives the two's complement result. 2719 if (RHS.isNegative() && RHS.isAllOnesValue() && 2720 LHS.isSigned() && LHS.isMinSignedValue()) 2721 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2722 E->getType()); 2723 return true; 2724 case BO_Shl: { 2725 if (Info.getLangOpts().OpenCL) 2726 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2727 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2728 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2729 RHS.isUnsigned()); 2730 else if (RHS.isSigned() && RHS.isNegative()) { 2731 // During constant-folding, a negative shift is an opposite shift. Such 2732 // a shift is not a constant expression. 2733 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2734 RHS = -RHS; 2735 goto shift_right; 2736 } 2737 shift_left: 2738 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2739 // the shifted type. 2740 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2741 if (SA != RHS) { 2742 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2743 << RHS << E->getType() << LHS.getBitWidth(); 2744 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2745 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2746 // operand, and must not overflow the corresponding unsigned type. 2747 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2748 // E1 x 2^E2 module 2^N. 2749 if (LHS.isNegative()) 2750 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2751 else if (LHS.countLeadingZeros() < SA) 2752 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2753 } 2754 Result = LHS << SA; 2755 return true; 2756 } 2757 case BO_Shr: { 2758 if (Info.getLangOpts().OpenCL) 2759 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2760 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2761 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2762 RHS.isUnsigned()); 2763 else if (RHS.isSigned() && RHS.isNegative()) { 2764 // During constant-folding, a negative shift is an opposite shift. Such a 2765 // shift is not a constant expression. 2766 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2767 RHS = -RHS; 2768 goto shift_left; 2769 } 2770 shift_right: 2771 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2772 // shifted type. 2773 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2774 if (SA != RHS) 2775 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2776 << RHS << E->getType() << LHS.getBitWidth(); 2777 Result = LHS >> SA; 2778 return true; 2779 } 2780 2781 case BO_LT: Result = LHS < RHS; return true; 2782 case BO_GT: Result = LHS > RHS; return true; 2783 case BO_LE: Result = LHS <= RHS; return true; 2784 case BO_GE: Result = LHS >= RHS; return true; 2785 case BO_EQ: Result = LHS == RHS; return true; 2786 case BO_NE: Result = LHS != RHS; return true; 2787 case BO_Cmp: 2788 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2789 } 2790 } 2791 2792 /// Perform the given binary floating-point operation, in-place, on LHS. 2793 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2794 APFloat &LHS, BinaryOperatorKind Opcode, 2795 const APFloat &RHS) { 2796 bool DynamicRM; 2797 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2798 APFloat::opStatus St; 2799 switch (Opcode) { 2800 default: 2801 Info.FFDiag(E); 2802 return false; 2803 case BO_Mul: 2804 St = LHS.multiply(RHS, RM); 2805 break; 2806 case BO_Add: 2807 St = LHS.add(RHS, RM); 2808 break; 2809 case BO_Sub: 2810 St = LHS.subtract(RHS, RM); 2811 break; 2812 case BO_Div: 2813 // [expr.mul]p4: 2814 // If the second operand of / or % is zero the behavior is undefined. 2815 if (RHS.isZero()) 2816 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2817 St = LHS.divide(RHS, RM); 2818 break; 2819 } 2820 2821 // [expr.pre]p4: 2822 // If during the evaluation of an expression, the result is not 2823 // mathematically defined [...], the behavior is undefined. 2824 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2825 if (LHS.isNaN()) { 2826 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2827 return Info.noteUndefinedBehavior(); 2828 } 2829 2830 return checkFloatingPointResult(Info, E, St); 2831 } 2832 2833 static bool handleLogicalOpForVector(const APInt &LHSValue, 2834 BinaryOperatorKind Opcode, 2835 const APInt &RHSValue, APInt &Result) { 2836 bool LHS = (LHSValue != 0); 2837 bool RHS = (RHSValue != 0); 2838 2839 if (Opcode == BO_LAnd) 2840 Result = LHS && RHS; 2841 else 2842 Result = LHS || RHS; 2843 return true; 2844 } 2845 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2846 BinaryOperatorKind Opcode, 2847 const APFloat &RHSValue, APInt &Result) { 2848 bool LHS = !LHSValue.isZero(); 2849 bool RHS = !RHSValue.isZero(); 2850 2851 if (Opcode == BO_LAnd) 2852 Result = LHS && RHS; 2853 else 2854 Result = LHS || RHS; 2855 return true; 2856 } 2857 2858 static bool handleLogicalOpForVector(const APValue &LHSValue, 2859 BinaryOperatorKind Opcode, 2860 const APValue &RHSValue, APInt &Result) { 2861 // The result is always an int type, however operands match the first. 2862 if (LHSValue.getKind() == APValue::Int) 2863 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2864 RHSValue.getInt(), Result); 2865 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2866 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2867 RHSValue.getFloat(), Result); 2868 } 2869 2870 template <typename APTy> 2871 static bool 2872 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2873 const APTy &RHSValue, APInt &Result) { 2874 switch (Opcode) { 2875 default: 2876 llvm_unreachable("unsupported binary operator"); 2877 case BO_EQ: 2878 Result = (LHSValue == RHSValue); 2879 break; 2880 case BO_NE: 2881 Result = (LHSValue != RHSValue); 2882 break; 2883 case BO_LT: 2884 Result = (LHSValue < RHSValue); 2885 break; 2886 case BO_GT: 2887 Result = (LHSValue > RHSValue); 2888 break; 2889 case BO_LE: 2890 Result = (LHSValue <= RHSValue); 2891 break; 2892 case BO_GE: 2893 Result = (LHSValue >= RHSValue); 2894 break; 2895 } 2896 2897 return true; 2898 } 2899 2900 static bool handleCompareOpForVector(const APValue &LHSValue, 2901 BinaryOperatorKind Opcode, 2902 const APValue &RHSValue, APInt &Result) { 2903 // The result is always an int type, however operands match the first. 2904 if (LHSValue.getKind() == APValue::Int) 2905 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2906 RHSValue.getInt(), Result); 2907 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2908 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2909 RHSValue.getFloat(), Result); 2910 } 2911 2912 // Perform binary operations for vector types, in place on the LHS. 2913 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2914 BinaryOperatorKind Opcode, 2915 APValue &LHSValue, 2916 const APValue &RHSValue) { 2917 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2918 "Operation not supported on vector types"); 2919 2920 const auto *VT = E->getType()->castAs<VectorType>(); 2921 unsigned NumElements = VT->getNumElements(); 2922 QualType EltTy = VT->getElementType(); 2923 2924 // In the cases (typically C as I've observed) where we aren't evaluating 2925 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2926 // just give up. 2927 if (!LHSValue.isVector()) { 2928 assert(LHSValue.isLValue() && 2929 "A vector result that isn't a vector OR uncalculated LValue"); 2930 Info.FFDiag(E); 2931 return false; 2932 } 2933 2934 assert(LHSValue.getVectorLength() == NumElements && 2935 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2936 2937 SmallVector<APValue, 4> ResultElements; 2938 2939 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2940 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2941 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2942 2943 if (EltTy->isIntegerType()) { 2944 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2945 EltTy->isUnsignedIntegerType()}; 2946 bool Success = true; 2947 2948 if (BinaryOperator::isLogicalOp(Opcode)) 2949 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2950 else if (BinaryOperator::isComparisonOp(Opcode)) 2951 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2952 else 2953 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2954 RHSElt.getInt(), EltResult); 2955 2956 if (!Success) { 2957 Info.FFDiag(E); 2958 return false; 2959 } 2960 ResultElements.emplace_back(EltResult); 2961 2962 } else if (EltTy->isFloatingType()) { 2963 assert(LHSElt.getKind() == APValue::Float && 2964 RHSElt.getKind() == APValue::Float && 2965 "Mismatched LHS/RHS/Result Type"); 2966 APFloat LHSFloat = LHSElt.getFloat(); 2967 2968 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 2969 RHSElt.getFloat())) { 2970 Info.FFDiag(E); 2971 return false; 2972 } 2973 2974 ResultElements.emplace_back(LHSFloat); 2975 } 2976 } 2977 2978 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 2979 return true; 2980 } 2981 2982 /// Cast an lvalue referring to a base subobject to a derived class, by 2983 /// truncating the lvalue's path to the given length. 2984 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2985 const RecordDecl *TruncatedType, 2986 unsigned TruncatedElements) { 2987 SubobjectDesignator &D = Result.Designator; 2988 2989 // Check we actually point to a derived class object. 2990 if (TruncatedElements == D.Entries.size()) 2991 return true; 2992 assert(TruncatedElements >= D.MostDerivedPathLength && 2993 "not casting to a derived class"); 2994 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2995 return false; 2996 2997 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2998 const RecordDecl *RD = TruncatedType; 2999 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3000 if (RD->isInvalidDecl()) return false; 3001 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3002 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3003 if (isVirtualBaseClass(D.Entries[I])) 3004 Result.Offset -= Layout.getVBaseClassOffset(Base); 3005 else 3006 Result.Offset -= Layout.getBaseClassOffset(Base); 3007 RD = Base; 3008 } 3009 D.Entries.resize(TruncatedElements); 3010 return true; 3011 } 3012 3013 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3014 const CXXRecordDecl *Derived, 3015 const CXXRecordDecl *Base, 3016 const ASTRecordLayout *RL = nullptr) { 3017 if (!RL) { 3018 if (Derived->isInvalidDecl()) return false; 3019 RL = &Info.Ctx.getASTRecordLayout(Derived); 3020 } 3021 3022 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3023 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3024 return true; 3025 } 3026 3027 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3028 const CXXRecordDecl *DerivedDecl, 3029 const CXXBaseSpecifier *Base) { 3030 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3031 3032 if (!Base->isVirtual()) 3033 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3034 3035 SubobjectDesignator &D = Obj.Designator; 3036 if (D.Invalid) 3037 return false; 3038 3039 // Extract most-derived object and corresponding type. 3040 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3041 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3042 return false; 3043 3044 // Find the virtual base class. 3045 if (DerivedDecl->isInvalidDecl()) return false; 3046 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3047 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3048 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3049 return true; 3050 } 3051 3052 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3053 QualType Type, LValue &Result) { 3054 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3055 PathE = E->path_end(); 3056 PathI != PathE; ++PathI) { 3057 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3058 *PathI)) 3059 return false; 3060 Type = (*PathI)->getType(); 3061 } 3062 return true; 3063 } 3064 3065 /// Cast an lvalue referring to a derived class to a known base subobject. 3066 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3067 const CXXRecordDecl *DerivedRD, 3068 const CXXRecordDecl *BaseRD) { 3069 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3070 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3071 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3072 llvm_unreachable("Class must be derived from the passed in base class!"); 3073 3074 for (CXXBasePathElement &Elem : Paths.front()) 3075 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3076 return false; 3077 return true; 3078 } 3079 3080 /// Update LVal to refer to the given field, which must be a member of the type 3081 /// currently described by LVal. 3082 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3083 const FieldDecl *FD, 3084 const ASTRecordLayout *RL = nullptr) { 3085 if (!RL) { 3086 if (FD->getParent()->isInvalidDecl()) return false; 3087 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3088 } 3089 3090 unsigned I = FD->getFieldIndex(); 3091 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3092 LVal.addDecl(Info, E, FD); 3093 return true; 3094 } 3095 3096 /// Update LVal to refer to the given indirect field. 3097 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3098 LValue &LVal, 3099 const IndirectFieldDecl *IFD) { 3100 for (const auto *C : IFD->chain()) 3101 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3102 return false; 3103 return true; 3104 } 3105 3106 /// Get the size of the given type in char units. 3107 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3108 QualType Type, CharUnits &Size) { 3109 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3110 // extension. 3111 if (Type->isVoidType() || Type->isFunctionType()) { 3112 Size = CharUnits::One(); 3113 return true; 3114 } 3115 3116 if (Type->isDependentType()) { 3117 Info.FFDiag(Loc); 3118 return false; 3119 } 3120 3121 if (!Type->isConstantSizeType()) { 3122 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3123 // FIXME: Better diagnostic. 3124 Info.FFDiag(Loc); 3125 return false; 3126 } 3127 3128 Size = Info.Ctx.getTypeSizeInChars(Type); 3129 return true; 3130 } 3131 3132 /// Update a pointer value to model pointer arithmetic. 3133 /// \param Info - Information about the ongoing evaluation. 3134 /// \param E - The expression being evaluated, for diagnostic purposes. 3135 /// \param LVal - The pointer value to be updated. 3136 /// \param EltTy - The pointee type represented by LVal. 3137 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3138 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3139 LValue &LVal, QualType EltTy, 3140 APSInt Adjustment) { 3141 CharUnits SizeOfPointee; 3142 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3143 return false; 3144 3145 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3146 return true; 3147 } 3148 3149 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3150 LValue &LVal, QualType EltTy, 3151 int64_t Adjustment) { 3152 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3153 APSInt::get(Adjustment)); 3154 } 3155 3156 /// Update an lvalue to refer to a component of a complex number. 3157 /// \param Info - Information about the ongoing evaluation. 3158 /// \param LVal - The lvalue to be updated. 3159 /// \param EltTy - The complex number's component type. 3160 /// \param Imag - False for the real component, true for the imaginary. 3161 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3162 LValue &LVal, QualType EltTy, 3163 bool Imag) { 3164 if (Imag) { 3165 CharUnits SizeOfComponent; 3166 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3167 return false; 3168 LVal.Offset += SizeOfComponent; 3169 } 3170 LVal.addComplex(Info, E, EltTy, Imag); 3171 return true; 3172 } 3173 3174 /// Try to evaluate the initializer for a variable declaration. 3175 /// 3176 /// \param Info Information about the ongoing evaluation. 3177 /// \param E An expression to be used when printing diagnostics. 3178 /// \param VD The variable whose initializer should be obtained. 3179 /// \param Version The version of the variable within the frame. 3180 /// \param Frame The frame in which the variable was created. Must be null 3181 /// if this variable is not local to the evaluation. 3182 /// \param Result Filled in with a pointer to the value of the variable. 3183 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3184 const VarDecl *VD, CallStackFrame *Frame, 3185 unsigned Version, APValue *&Result) { 3186 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3187 3188 // If this is a local variable, dig out its value. 3189 if (Frame) { 3190 Result = Frame->getTemporary(VD, Version); 3191 if (Result) 3192 return true; 3193 3194 if (!isa<ParmVarDecl>(VD)) { 3195 // Assume variables referenced within a lambda's call operator that were 3196 // not declared within the call operator are captures and during checking 3197 // of a potential constant expression, assume they are unknown constant 3198 // expressions. 3199 assert(isLambdaCallOperator(Frame->Callee) && 3200 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3201 "missing value for local variable"); 3202 if (Info.checkingPotentialConstantExpression()) 3203 return false; 3204 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3205 // still reachable at all? 3206 Info.FFDiag(E->getBeginLoc(), 3207 diag::note_unimplemented_constexpr_lambda_feature_ast) 3208 << "captures not currently allowed"; 3209 return false; 3210 } 3211 } 3212 3213 if (isa<ParmVarDecl>(VD)) { 3214 // Assume parameters of a potential constant expression are usable in 3215 // constant expressions. 3216 if (!Info.checkingPotentialConstantExpression() || 3217 !Info.CurrentCall->Callee || 3218 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3219 if (Info.getLangOpts().CPlusPlus11) { 3220 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3221 << VD; 3222 NoteLValueLocation(Info, Base); 3223 } else { 3224 Info.FFDiag(E); 3225 } 3226 } 3227 return false; 3228 } 3229 3230 // Dig out the initializer, and use the declaration which it's attached to. 3231 // FIXME: We should eventually check whether the variable has a reachable 3232 // initializing declaration. 3233 const Expr *Init = VD->getAnyInitializer(VD); 3234 if (!Init) { 3235 // Don't diagnose during potential constant expression checking; an 3236 // initializer might be added later. 3237 if (!Info.checkingPotentialConstantExpression()) { 3238 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3239 << VD; 3240 NoteLValueLocation(Info, Base); 3241 } 3242 return false; 3243 } 3244 3245 if (Init->isValueDependent()) { 3246 // The DeclRefExpr is not value-dependent, but the variable it refers to 3247 // has a value-dependent initializer. This should only happen in 3248 // constant-folding cases, where the variable is not actually of a suitable 3249 // type for use in a constant expression (otherwise the DeclRefExpr would 3250 // have been value-dependent too), so diagnose that. 3251 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3252 if (!Info.checkingPotentialConstantExpression()) { 3253 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3254 ? diag::note_constexpr_ltor_non_constexpr 3255 : diag::note_constexpr_ltor_non_integral, 1) 3256 << VD << VD->getType(); 3257 NoteLValueLocation(Info, Base); 3258 } 3259 return false; 3260 } 3261 3262 // If we're currently evaluating the initializer of this declaration, use that 3263 // in-flight value. 3264 if (declaresSameEntity(Info.EvaluatingDecl.dyn_cast<const ValueDecl *>(), 3265 VD)) { 3266 Result = Info.EvaluatingDeclValue; 3267 return true; 3268 } 3269 3270 // Check that we can fold the initializer. In C++, we will have already done 3271 // this in the cases where it matters for conformance. 3272 if (!VD->evaluateValue()) { 3273 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3274 NoteLValueLocation(Info, Base); 3275 return false; 3276 } 3277 3278 // Check that the variable is actually usable in constant expressions. For a 3279 // const integral variable or a reference, we might have a non-constant 3280 // initializer that we can nonetheless evaluate the initializer for. Such 3281 // variables are not usable in constant expressions. In C++98, the 3282 // initializer also syntactically needs to be an ICE. 3283 // 3284 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3285 // expressions here; doing so would regress diagnostics for things like 3286 // reading from a volatile constexpr variable. 3287 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3288 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3289 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3290 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3291 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3292 NoteLValueLocation(Info, Base); 3293 } 3294 3295 // Never use the initializer of a weak variable, not even for constant 3296 // folding. We can't be sure that this is the definition that will be used. 3297 if (VD->isWeak()) { 3298 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3299 NoteLValueLocation(Info, Base); 3300 return false; 3301 } 3302 3303 Result = VD->getEvaluatedValue(); 3304 return true; 3305 } 3306 3307 /// Get the base index of the given base class within an APValue representing 3308 /// the given derived class. 3309 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3310 const CXXRecordDecl *Base) { 3311 Base = Base->getCanonicalDecl(); 3312 unsigned Index = 0; 3313 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3314 E = Derived->bases_end(); I != E; ++I, ++Index) { 3315 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3316 return Index; 3317 } 3318 3319 llvm_unreachable("base class missing from derived class's bases list"); 3320 } 3321 3322 /// Extract the value of a character from a string literal. 3323 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3324 uint64_t Index) { 3325 assert(!isa<SourceLocExpr>(Lit) && 3326 "SourceLocExpr should have already been converted to a StringLiteral"); 3327 3328 // FIXME: Support MakeStringConstant 3329 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3330 std::string Str; 3331 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3332 assert(Index <= Str.size() && "Index too large"); 3333 return APSInt::getUnsigned(Str.c_str()[Index]); 3334 } 3335 3336 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3337 Lit = PE->getFunctionName(); 3338 const StringLiteral *S = cast<StringLiteral>(Lit); 3339 const ConstantArrayType *CAT = 3340 Info.Ctx.getAsConstantArrayType(S->getType()); 3341 assert(CAT && "string literal isn't an array"); 3342 QualType CharType = CAT->getElementType(); 3343 assert(CharType->isIntegerType() && "unexpected character type"); 3344 3345 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3346 CharType->isUnsignedIntegerType()); 3347 if (Index < S->getLength()) 3348 Value = S->getCodeUnit(Index); 3349 return Value; 3350 } 3351 3352 // Expand a string literal into an array of characters. 3353 // 3354 // FIXME: This is inefficient; we should probably introduce something similar 3355 // to the LLVM ConstantDataArray to make this cheaper. 3356 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3357 APValue &Result, 3358 QualType AllocType = QualType()) { 3359 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3360 AllocType.isNull() ? S->getType() : AllocType); 3361 assert(CAT && "string literal isn't an array"); 3362 QualType CharType = CAT->getElementType(); 3363 assert(CharType->isIntegerType() && "unexpected character type"); 3364 3365 unsigned Elts = CAT->getSize().getZExtValue(); 3366 Result = APValue(APValue::UninitArray(), 3367 std::min(S->getLength(), Elts), Elts); 3368 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3369 CharType->isUnsignedIntegerType()); 3370 if (Result.hasArrayFiller()) 3371 Result.getArrayFiller() = APValue(Value); 3372 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3373 Value = S->getCodeUnit(I); 3374 Result.getArrayInitializedElt(I) = APValue(Value); 3375 } 3376 } 3377 3378 // Expand an array so that it has more than Index filled elements. 3379 static void expandArray(APValue &Array, unsigned Index) { 3380 unsigned Size = Array.getArraySize(); 3381 assert(Index < Size); 3382 3383 // Always at least double the number of elements for which we store a value. 3384 unsigned OldElts = Array.getArrayInitializedElts(); 3385 unsigned NewElts = std::max(Index+1, OldElts * 2); 3386 NewElts = std::min(Size, std::max(NewElts, 8u)); 3387 3388 // Copy the data across. 3389 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3390 for (unsigned I = 0; I != OldElts; ++I) 3391 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3392 for (unsigned I = OldElts; I != NewElts; ++I) 3393 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3394 if (NewValue.hasArrayFiller()) 3395 NewValue.getArrayFiller() = Array.getArrayFiller(); 3396 Array.swap(NewValue); 3397 } 3398 3399 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3400 /// conversion. If it's of class type, we may assume that the copy operation 3401 /// is trivial. Note that this is never true for a union type with fields 3402 /// (because the copy always "reads" the active member) and always true for 3403 /// a non-class type. 3404 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3405 static bool isReadByLvalueToRvalueConversion(QualType T) { 3406 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3407 return !RD || isReadByLvalueToRvalueConversion(RD); 3408 } 3409 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3410 // FIXME: A trivial copy of a union copies the object representation, even if 3411 // the union is empty. 3412 if (RD->isUnion()) 3413 return !RD->field_empty(); 3414 if (RD->isEmpty()) 3415 return false; 3416 3417 for (auto *Field : RD->fields()) 3418 if (!Field->isUnnamedBitfield() && 3419 isReadByLvalueToRvalueConversion(Field->getType())) 3420 return true; 3421 3422 for (auto &BaseSpec : RD->bases()) 3423 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3424 return true; 3425 3426 return false; 3427 } 3428 3429 /// Diagnose an attempt to read from any unreadable field within the specified 3430 /// type, which might be a class type. 3431 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3432 QualType T) { 3433 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3434 if (!RD) 3435 return false; 3436 3437 if (!RD->hasMutableFields()) 3438 return false; 3439 3440 for (auto *Field : RD->fields()) { 3441 // If we're actually going to read this field in some way, then it can't 3442 // be mutable. If we're in a union, then assigning to a mutable field 3443 // (even an empty one) can change the active member, so that's not OK. 3444 // FIXME: Add core issue number for the union case. 3445 if (Field->isMutable() && 3446 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3447 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3448 Info.Note(Field->getLocation(), diag::note_declared_at); 3449 return true; 3450 } 3451 3452 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3453 return true; 3454 } 3455 3456 for (auto &BaseSpec : RD->bases()) 3457 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3458 return true; 3459 3460 // All mutable fields were empty, and thus not actually read. 3461 return false; 3462 } 3463 3464 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3465 APValue::LValueBase Base, 3466 bool MutableSubobject = false) { 3467 // A temporary we created. 3468 if (Base.getCallIndex()) 3469 return true; 3470 3471 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3472 if (!Evaluating) 3473 return false; 3474 3475 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3476 3477 switch (Info.IsEvaluatingDecl) { 3478 case EvalInfo::EvaluatingDeclKind::None: 3479 return false; 3480 3481 case EvalInfo::EvaluatingDeclKind::Ctor: 3482 // The variable whose initializer we're evaluating. 3483 if (BaseD) 3484 return declaresSameEntity(Evaluating, BaseD); 3485 3486 // A temporary lifetime-extended by the variable whose initializer we're 3487 // evaluating. 3488 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3489 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3490 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3491 return false; 3492 3493 case EvalInfo::EvaluatingDeclKind::Dtor: 3494 // C++2a [expr.const]p6: 3495 // [during constant destruction] the lifetime of a and its non-mutable 3496 // subobjects (but not its mutable subobjects) [are] considered to start 3497 // within e. 3498 // 3499 // FIXME: We can meaningfully extend this to cover non-const objects, but 3500 // we will need special handling: we should be able to access only 3501 // subobjects of such objects that are themselves declared const. 3502 if (!BaseD || 3503 !(BaseD->getType().isConstQualified() || 3504 BaseD->getType()->isReferenceType()) || 3505 MutableSubobject) 3506 return false; 3507 return declaresSameEntity(Evaluating, BaseD); 3508 } 3509 3510 llvm_unreachable("unknown evaluating decl kind"); 3511 } 3512 3513 namespace { 3514 /// A handle to a complete object (an object that is not a subobject of 3515 /// another object). 3516 struct CompleteObject { 3517 /// The identity of the object. 3518 APValue::LValueBase Base; 3519 /// The value of the complete object. 3520 APValue *Value; 3521 /// The type of the complete object. 3522 QualType Type; 3523 3524 CompleteObject() : Value(nullptr) {} 3525 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3526 : Base(Base), Value(Value), Type(Type) {} 3527 3528 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3529 // If this isn't a "real" access (eg, if it's just accessing the type 3530 // info), allow it. We assume the type doesn't change dynamically for 3531 // subobjects of constexpr objects (even though we'd hit UB here if it 3532 // did). FIXME: Is this right? 3533 if (!isAnyAccess(AK)) 3534 return true; 3535 3536 // In C++14 onwards, it is permitted to read a mutable member whose 3537 // lifetime began within the evaluation. 3538 // FIXME: Should we also allow this in C++11? 3539 if (!Info.getLangOpts().CPlusPlus14) 3540 return false; 3541 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3542 } 3543 3544 explicit operator bool() const { return !Type.isNull(); } 3545 }; 3546 } // end anonymous namespace 3547 3548 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3549 bool IsMutable = false) { 3550 // C++ [basic.type.qualifier]p1: 3551 // - A const object is an object of type const T or a non-mutable subobject 3552 // of a const object. 3553 if (ObjType.isConstQualified() && !IsMutable) 3554 SubobjType.addConst(); 3555 // - A volatile object is an object of type const T or a subobject of a 3556 // volatile object. 3557 if (ObjType.isVolatileQualified()) 3558 SubobjType.addVolatile(); 3559 return SubobjType; 3560 } 3561 3562 /// Find the designated sub-object of an rvalue. 3563 template<typename SubobjectHandler> 3564 typename SubobjectHandler::result_type 3565 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3566 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3567 if (Sub.Invalid) 3568 // A diagnostic will have already been produced. 3569 return handler.failed(); 3570 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3571 if (Info.getLangOpts().CPlusPlus11) 3572 Info.FFDiag(E, Sub.isOnePastTheEnd() 3573 ? diag::note_constexpr_access_past_end 3574 : diag::note_constexpr_access_unsized_array) 3575 << handler.AccessKind; 3576 else 3577 Info.FFDiag(E); 3578 return handler.failed(); 3579 } 3580 3581 APValue *O = Obj.Value; 3582 QualType ObjType = Obj.Type; 3583 const FieldDecl *LastField = nullptr; 3584 const FieldDecl *VolatileField = nullptr; 3585 3586 // Walk the designator's path to find the subobject. 3587 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3588 // Reading an indeterminate value is undefined, but assigning over one is OK. 3589 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3590 (O->isIndeterminate() && 3591 !isValidIndeterminateAccess(handler.AccessKind))) { 3592 if (!Info.checkingPotentialConstantExpression()) 3593 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3594 << handler.AccessKind << O->isIndeterminate(); 3595 return handler.failed(); 3596 } 3597 3598 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3599 // const and volatile semantics are not applied on an object under 3600 // {con,de}struction. 3601 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3602 ObjType->isRecordType() && 3603 Info.isEvaluatingCtorDtor( 3604 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3605 Sub.Entries.begin() + I)) != 3606 ConstructionPhase::None) { 3607 ObjType = Info.Ctx.getCanonicalType(ObjType); 3608 ObjType.removeLocalConst(); 3609 ObjType.removeLocalVolatile(); 3610 } 3611 3612 // If this is our last pass, check that the final object type is OK. 3613 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3614 // Accesses to volatile objects are prohibited. 3615 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3616 if (Info.getLangOpts().CPlusPlus) { 3617 int DiagKind; 3618 SourceLocation Loc; 3619 const NamedDecl *Decl = nullptr; 3620 if (VolatileField) { 3621 DiagKind = 2; 3622 Loc = VolatileField->getLocation(); 3623 Decl = VolatileField; 3624 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3625 DiagKind = 1; 3626 Loc = VD->getLocation(); 3627 Decl = VD; 3628 } else { 3629 DiagKind = 0; 3630 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3631 Loc = E->getExprLoc(); 3632 } 3633 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3634 << handler.AccessKind << DiagKind << Decl; 3635 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3636 } else { 3637 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3638 } 3639 return handler.failed(); 3640 } 3641 3642 // If we are reading an object of class type, there may still be more 3643 // things we need to check: if there are any mutable subobjects, we 3644 // cannot perform this read. (This only happens when performing a trivial 3645 // copy or assignment.) 3646 if (ObjType->isRecordType() && 3647 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3648 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3649 return handler.failed(); 3650 } 3651 3652 if (I == N) { 3653 if (!handler.found(*O, ObjType)) 3654 return false; 3655 3656 // If we modified a bit-field, truncate it to the right width. 3657 if (isModification(handler.AccessKind) && 3658 LastField && LastField->isBitField() && 3659 !truncateBitfieldValue(Info, E, *O, LastField)) 3660 return false; 3661 3662 return true; 3663 } 3664 3665 LastField = nullptr; 3666 if (ObjType->isArrayType()) { 3667 // Next subobject is an array element. 3668 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3669 assert(CAT && "vla in literal type?"); 3670 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3671 if (CAT->getSize().ule(Index)) { 3672 // Note, it should not be possible to form a pointer with a valid 3673 // designator which points more than one past the end of the array. 3674 if (Info.getLangOpts().CPlusPlus11) 3675 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3676 << handler.AccessKind; 3677 else 3678 Info.FFDiag(E); 3679 return handler.failed(); 3680 } 3681 3682 ObjType = CAT->getElementType(); 3683 3684 if (O->getArrayInitializedElts() > Index) 3685 O = &O->getArrayInitializedElt(Index); 3686 else if (!isRead(handler.AccessKind)) { 3687 expandArray(*O, Index); 3688 O = &O->getArrayInitializedElt(Index); 3689 } else 3690 O = &O->getArrayFiller(); 3691 } else if (ObjType->isAnyComplexType()) { 3692 // Next subobject is a complex number. 3693 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3694 if (Index > 1) { 3695 if (Info.getLangOpts().CPlusPlus11) 3696 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3697 << handler.AccessKind; 3698 else 3699 Info.FFDiag(E); 3700 return handler.failed(); 3701 } 3702 3703 ObjType = getSubobjectType( 3704 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3705 3706 assert(I == N - 1 && "extracting subobject of scalar?"); 3707 if (O->isComplexInt()) { 3708 return handler.found(Index ? O->getComplexIntImag() 3709 : O->getComplexIntReal(), ObjType); 3710 } else { 3711 assert(O->isComplexFloat()); 3712 return handler.found(Index ? O->getComplexFloatImag() 3713 : O->getComplexFloatReal(), ObjType); 3714 } 3715 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3716 if (Field->isMutable() && 3717 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3718 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3719 << handler.AccessKind << Field; 3720 Info.Note(Field->getLocation(), diag::note_declared_at); 3721 return handler.failed(); 3722 } 3723 3724 // Next subobject is a class, struct or union field. 3725 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3726 if (RD->isUnion()) { 3727 const FieldDecl *UnionField = O->getUnionField(); 3728 if (!UnionField || 3729 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3730 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3731 // Placement new onto an inactive union member makes it active. 3732 O->setUnion(Field, APValue()); 3733 } else { 3734 // FIXME: If O->getUnionValue() is absent, report that there's no 3735 // active union member rather than reporting the prior active union 3736 // member. We'll need to fix nullptr_t to not use APValue() as its 3737 // representation first. 3738 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3739 << handler.AccessKind << Field << !UnionField << UnionField; 3740 return handler.failed(); 3741 } 3742 } 3743 O = &O->getUnionValue(); 3744 } else 3745 O = &O->getStructField(Field->getFieldIndex()); 3746 3747 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3748 LastField = Field; 3749 if (Field->getType().isVolatileQualified()) 3750 VolatileField = Field; 3751 } else { 3752 // Next subobject is a base class. 3753 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3754 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3755 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3756 3757 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3758 } 3759 } 3760 } 3761 3762 namespace { 3763 struct ExtractSubobjectHandler { 3764 EvalInfo &Info; 3765 const Expr *E; 3766 APValue &Result; 3767 const AccessKinds AccessKind; 3768 3769 typedef bool result_type; 3770 bool failed() { return false; } 3771 bool found(APValue &Subobj, QualType SubobjType) { 3772 Result = Subobj; 3773 if (AccessKind == AK_ReadObjectRepresentation) 3774 return true; 3775 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3776 } 3777 bool found(APSInt &Value, QualType SubobjType) { 3778 Result = APValue(Value); 3779 return true; 3780 } 3781 bool found(APFloat &Value, QualType SubobjType) { 3782 Result = APValue(Value); 3783 return true; 3784 } 3785 }; 3786 } // end anonymous namespace 3787 3788 /// Extract the designated sub-object of an rvalue. 3789 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3790 const CompleteObject &Obj, 3791 const SubobjectDesignator &Sub, APValue &Result, 3792 AccessKinds AK = AK_Read) { 3793 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3794 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3795 return findSubobject(Info, E, Obj, Sub, Handler); 3796 } 3797 3798 namespace { 3799 struct ModifySubobjectHandler { 3800 EvalInfo &Info; 3801 APValue &NewVal; 3802 const Expr *E; 3803 3804 typedef bool result_type; 3805 static const AccessKinds AccessKind = AK_Assign; 3806 3807 bool checkConst(QualType QT) { 3808 // Assigning to a const object has undefined behavior. 3809 if (QT.isConstQualified()) { 3810 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3811 return false; 3812 } 3813 return true; 3814 } 3815 3816 bool failed() { return false; } 3817 bool found(APValue &Subobj, QualType SubobjType) { 3818 if (!checkConst(SubobjType)) 3819 return false; 3820 // We've been given ownership of NewVal, so just swap it in. 3821 Subobj.swap(NewVal); 3822 return true; 3823 } 3824 bool found(APSInt &Value, QualType SubobjType) { 3825 if (!checkConst(SubobjType)) 3826 return false; 3827 if (!NewVal.isInt()) { 3828 // Maybe trying to write a cast pointer value into a complex? 3829 Info.FFDiag(E); 3830 return false; 3831 } 3832 Value = NewVal.getInt(); 3833 return true; 3834 } 3835 bool found(APFloat &Value, QualType SubobjType) { 3836 if (!checkConst(SubobjType)) 3837 return false; 3838 Value = NewVal.getFloat(); 3839 return true; 3840 } 3841 }; 3842 } // end anonymous namespace 3843 3844 const AccessKinds ModifySubobjectHandler::AccessKind; 3845 3846 /// Update the designated sub-object of an rvalue to the given value. 3847 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3848 const CompleteObject &Obj, 3849 const SubobjectDesignator &Sub, 3850 APValue &NewVal) { 3851 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3852 return findSubobject(Info, E, Obj, Sub, Handler); 3853 } 3854 3855 /// Find the position where two subobject designators diverge, or equivalently 3856 /// the length of the common initial subsequence. 3857 static unsigned FindDesignatorMismatch(QualType ObjType, 3858 const SubobjectDesignator &A, 3859 const SubobjectDesignator &B, 3860 bool &WasArrayIndex) { 3861 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3862 for (/**/; I != N; ++I) { 3863 if (!ObjType.isNull() && 3864 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3865 // Next subobject is an array element. 3866 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3867 WasArrayIndex = true; 3868 return I; 3869 } 3870 if (ObjType->isAnyComplexType()) 3871 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3872 else 3873 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3874 } else { 3875 if (A.Entries[I].getAsBaseOrMember() != 3876 B.Entries[I].getAsBaseOrMember()) { 3877 WasArrayIndex = false; 3878 return I; 3879 } 3880 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3881 // Next subobject is a field. 3882 ObjType = FD->getType(); 3883 else 3884 // Next subobject is a base class. 3885 ObjType = QualType(); 3886 } 3887 } 3888 WasArrayIndex = false; 3889 return I; 3890 } 3891 3892 /// Determine whether the given subobject designators refer to elements of the 3893 /// same array object. 3894 static bool AreElementsOfSameArray(QualType ObjType, 3895 const SubobjectDesignator &A, 3896 const SubobjectDesignator &B) { 3897 if (A.Entries.size() != B.Entries.size()) 3898 return false; 3899 3900 bool IsArray = A.MostDerivedIsArrayElement; 3901 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3902 // A is a subobject of the array element. 3903 return false; 3904 3905 // If A (and B) designates an array element, the last entry will be the array 3906 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3907 // of length 1' case, and the entire path must match. 3908 bool WasArrayIndex; 3909 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3910 return CommonLength >= A.Entries.size() - IsArray; 3911 } 3912 3913 /// Find the complete object to which an LValue refers. 3914 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3915 AccessKinds AK, const LValue &LVal, 3916 QualType LValType) { 3917 if (LVal.InvalidBase) { 3918 Info.FFDiag(E); 3919 return CompleteObject(); 3920 } 3921 3922 if (!LVal.Base) { 3923 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3924 return CompleteObject(); 3925 } 3926 3927 CallStackFrame *Frame = nullptr; 3928 unsigned Depth = 0; 3929 if (LVal.getLValueCallIndex()) { 3930 std::tie(Frame, Depth) = 3931 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3932 if (!Frame) { 3933 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3934 << AK << LVal.Base.is<const ValueDecl*>(); 3935 NoteLValueLocation(Info, LVal.Base); 3936 return CompleteObject(); 3937 } 3938 } 3939 3940 bool IsAccess = isAnyAccess(AK); 3941 3942 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3943 // is not a constant expression (even if the object is non-volatile). We also 3944 // apply this rule to C++98, in order to conform to the expected 'volatile' 3945 // semantics. 3946 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3947 if (Info.getLangOpts().CPlusPlus) 3948 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3949 << AK << LValType; 3950 else 3951 Info.FFDiag(E); 3952 return CompleteObject(); 3953 } 3954 3955 // Compute value storage location and type of base object. 3956 APValue *BaseVal = nullptr; 3957 QualType BaseType = getType(LVal.Base); 3958 3959 if (const ConstantExpr *CE = 3960 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) { 3961 /// Nested immediate invocation have been previously removed so if we found 3962 /// a ConstantExpr it can only be the EvaluatingDecl. 3963 assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl); 3964 (void)CE; 3965 BaseVal = Info.EvaluatingDeclValue; 3966 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3967 // Allow reading from a GUID declaration. 3968 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3969 if (isModification(AK)) { 3970 // All the remaining cases do not permit modification of the object. 3971 Info.FFDiag(E, diag::note_constexpr_modify_global); 3972 return CompleteObject(); 3973 } 3974 APValue &V = GD->getAsAPValue(); 3975 if (V.isAbsent()) { 3976 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3977 << GD->getType(); 3978 return CompleteObject(); 3979 } 3980 return CompleteObject(LVal.Base, &V, GD->getType()); 3981 } 3982 3983 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3984 // In C++11, constexpr, non-volatile variables initialized with constant 3985 // expressions are constant expressions too. Inside constexpr functions, 3986 // parameters are constant expressions even if they're non-const. 3987 // In C++1y, objects local to a constant expression (those with a Frame) are 3988 // both readable and writable inside constant expressions. 3989 // In C, such things can also be folded, although they are not ICEs. 3990 const VarDecl *VD = dyn_cast<VarDecl>(D); 3991 if (VD) { 3992 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3993 VD = VDef; 3994 } 3995 if (!VD || VD->isInvalidDecl()) { 3996 Info.FFDiag(E); 3997 return CompleteObject(); 3998 } 3999 4000 bool IsConstant = BaseType.isConstant(Info.Ctx); 4001 4002 // Unless we're looking at a local variable or argument in a constexpr call, 4003 // the variable we're reading must be const. 4004 if (!Frame) { 4005 if (IsAccess && isa<ParmVarDecl>(VD)) { 4006 // Access of a parameter that's not associated with a frame isn't going 4007 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4008 // suitable diagnostic. 4009 } else if (Info.getLangOpts().CPlusPlus14 && 4010 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4011 // OK, we can read and modify an object if we're in the process of 4012 // evaluating its initializer, because its lifetime began in this 4013 // evaluation. 4014 } else if (isModification(AK)) { 4015 // All the remaining cases do not permit modification of the object. 4016 Info.FFDiag(E, diag::note_constexpr_modify_global); 4017 return CompleteObject(); 4018 } else if (VD->isConstexpr()) { 4019 // OK, we can read this variable. 4020 } else if (BaseType->isIntegralOrEnumerationType()) { 4021 if (!IsConstant) { 4022 if (!IsAccess) 4023 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4024 if (Info.getLangOpts().CPlusPlus) { 4025 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4026 Info.Note(VD->getLocation(), diag::note_declared_at); 4027 } else { 4028 Info.FFDiag(E); 4029 } 4030 return CompleteObject(); 4031 } 4032 } else if (!IsAccess) { 4033 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4034 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4035 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4036 // This variable might end up being constexpr. Don't diagnose it yet. 4037 } else if (IsConstant) { 4038 // Keep evaluating to see what we can do. In particular, we support 4039 // folding of const floating-point types, in order to make static const 4040 // data members of such types (supported as an extension) more useful. 4041 if (Info.getLangOpts().CPlusPlus) { 4042 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4043 ? diag::note_constexpr_ltor_non_constexpr 4044 : diag::note_constexpr_ltor_non_integral, 1) 4045 << VD << BaseType; 4046 Info.Note(VD->getLocation(), diag::note_declared_at); 4047 } else { 4048 Info.CCEDiag(E); 4049 } 4050 } else { 4051 // Never allow reading a non-const value. 4052 if (Info.getLangOpts().CPlusPlus) { 4053 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4054 ? diag::note_constexpr_ltor_non_constexpr 4055 : diag::note_constexpr_ltor_non_integral, 1) 4056 << VD << BaseType; 4057 Info.Note(VD->getLocation(), diag::note_declared_at); 4058 } else { 4059 Info.FFDiag(E); 4060 } 4061 return CompleteObject(); 4062 } 4063 } 4064 4065 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4066 return CompleteObject(); 4067 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4068 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4069 if (!Alloc) { 4070 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4071 return CompleteObject(); 4072 } 4073 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4074 LVal.Base.getDynamicAllocType()); 4075 } else { 4076 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4077 4078 if (!Frame) { 4079 if (const MaterializeTemporaryExpr *MTE = 4080 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4081 assert(MTE->getStorageDuration() == SD_Static && 4082 "should have a frame for a non-global materialized temporary"); 4083 4084 // Per C++1y [expr.const]p2: 4085 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4086 // - a [...] glvalue of integral or enumeration type that refers to 4087 // a non-volatile const object [...] 4088 // [...] 4089 // - a [...] glvalue of literal type that refers to a non-volatile 4090 // object whose lifetime began within the evaluation of e. 4091 // 4092 // C++11 misses the 'began within the evaluation of e' check and 4093 // instead allows all temporaries, including things like: 4094 // int &&r = 1; 4095 // int x = ++r; 4096 // constexpr int k = r; 4097 // Therefore we use the C++14 rules in C++11 too. 4098 // 4099 // Note that temporaries whose lifetimes began while evaluating a 4100 // variable's constructor are not usable while evaluating the 4101 // corresponding destructor, not even if they're of const-qualified 4102 // types. 4103 if (!(BaseType.isConstQualified() && 4104 BaseType->isIntegralOrEnumerationType()) && 4105 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4106 if (!IsAccess) 4107 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4108 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4109 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4110 return CompleteObject(); 4111 } 4112 4113 BaseVal = MTE->getOrCreateValue(false); 4114 assert(BaseVal && "got reference to unevaluated temporary"); 4115 } else { 4116 if (!IsAccess) 4117 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4118 APValue Val; 4119 LVal.moveInto(Val); 4120 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4121 << AK 4122 << Val.getAsString(Info.Ctx, 4123 Info.Ctx.getLValueReferenceType(LValType)); 4124 NoteLValueLocation(Info, LVal.Base); 4125 return CompleteObject(); 4126 } 4127 } else { 4128 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4129 assert(BaseVal && "missing value for temporary"); 4130 } 4131 } 4132 4133 // In C++14, we can't safely access any mutable state when we might be 4134 // evaluating after an unmodeled side effect. Parameters are modeled as state 4135 // in the caller, but aren't visible once the call returns, so they can be 4136 // modified in a speculatively-evaluated call. 4137 // 4138 // FIXME: Not all local state is mutable. Allow local constant subobjects 4139 // to be read here (but take care with 'mutable' fields). 4140 unsigned VisibleDepth = Depth; 4141 if (llvm::isa_and_nonnull<ParmVarDecl>( 4142 LVal.Base.dyn_cast<const ValueDecl *>())) 4143 ++VisibleDepth; 4144 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4145 Info.EvalStatus.HasSideEffects) || 4146 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4147 return CompleteObject(); 4148 4149 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4150 } 4151 4152 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4153 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4154 /// glvalue referred to by an entity of reference type. 4155 /// 4156 /// \param Info - Information about the ongoing evaluation. 4157 /// \param Conv - The expression for which we are performing the conversion. 4158 /// Used for diagnostics. 4159 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4160 /// case of a non-class type). 4161 /// \param LVal - The glvalue on which we are attempting to perform this action. 4162 /// \param RVal - The produced value will be placed here. 4163 /// \param WantObjectRepresentation - If true, we're looking for the object 4164 /// representation rather than the value, and in particular, 4165 /// there is no requirement that the result be fully initialized. 4166 static bool 4167 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4168 const LValue &LVal, APValue &RVal, 4169 bool WantObjectRepresentation = false) { 4170 if (LVal.Designator.Invalid) 4171 return false; 4172 4173 // Check for special cases where there is no existing APValue to look at. 4174 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4175 4176 AccessKinds AK = 4177 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4178 4179 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4180 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4181 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4182 // initializer until now for such expressions. Such an expression can't be 4183 // an ICE in C, so this only matters for fold. 4184 if (Type.isVolatileQualified()) { 4185 Info.FFDiag(Conv); 4186 return false; 4187 } 4188 APValue Lit; 4189 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4190 return false; 4191 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4192 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4193 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4194 // Special-case character extraction so we don't have to construct an 4195 // APValue for the whole string. 4196 assert(LVal.Designator.Entries.size() <= 1 && 4197 "Can only read characters from string literals"); 4198 if (LVal.Designator.Entries.empty()) { 4199 // Fail for now for LValue to RValue conversion of an array. 4200 // (This shouldn't show up in C/C++, but it could be triggered by a 4201 // weird EvaluateAsRValue call from a tool.) 4202 Info.FFDiag(Conv); 4203 return false; 4204 } 4205 if (LVal.Designator.isOnePastTheEnd()) { 4206 if (Info.getLangOpts().CPlusPlus11) 4207 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4208 else 4209 Info.FFDiag(Conv); 4210 return false; 4211 } 4212 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4213 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4214 return true; 4215 } 4216 } 4217 4218 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4219 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4220 } 4221 4222 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4223 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4224 QualType LValType, APValue &Val) { 4225 if (LVal.Designator.Invalid) 4226 return false; 4227 4228 if (!Info.getLangOpts().CPlusPlus14) { 4229 Info.FFDiag(E); 4230 return false; 4231 } 4232 4233 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4234 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4235 } 4236 4237 namespace { 4238 struct CompoundAssignSubobjectHandler { 4239 EvalInfo &Info; 4240 const CompoundAssignOperator *E; 4241 QualType PromotedLHSType; 4242 BinaryOperatorKind Opcode; 4243 const APValue &RHS; 4244 4245 static const AccessKinds AccessKind = AK_Assign; 4246 4247 typedef bool result_type; 4248 4249 bool checkConst(QualType QT) { 4250 // Assigning to a const object has undefined behavior. 4251 if (QT.isConstQualified()) { 4252 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4253 return false; 4254 } 4255 return true; 4256 } 4257 4258 bool failed() { return false; } 4259 bool found(APValue &Subobj, QualType SubobjType) { 4260 switch (Subobj.getKind()) { 4261 case APValue::Int: 4262 return found(Subobj.getInt(), SubobjType); 4263 case APValue::Float: 4264 return found(Subobj.getFloat(), SubobjType); 4265 case APValue::ComplexInt: 4266 case APValue::ComplexFloat: 4267 // FIXME: Implement complex compound assignment. 4268 Info.FFDiag(E); 4269 return false; 4270 case APValue::LValue: 4271 return foundPointer(Subobj, SubobjType); 4272 case APValue::Vector: 4273 return foundVector(Subobj, SubobjType); 4274 default: 4275 // FIXME: can this happen? 4276 Info.FFDiag(E); 4277 return false; 4278 } 4279 } 4280 4281 bool foundVector(APValue &Value, QualType SubobjType) { 4282 if (!checkConst(SubobjType)) 4283 return false; 4284 4285 if (!SubobjType->isVectorType()) { 4286 Info.FFDiag(E); 4287 return false; 4288 } 4289 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4290 } 4291 4292 bool found(APSInt &Value, QualType SubobjType) { 4293 if (!checkConst(SubobjType)) 4294 return false; 4295 4296 if (!SubobjType->isIntegerType()) { 4297 // We don't support compound assignment on integer-cast-to-pointer 4298 // values. 4299 Info.FFDiag(E); 4300 return false; 4301 } 4302 4303 if (RHS.isInt()) { 4304 APSInt LHS = 4305 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4306 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4307 return false; 4308 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4309 return true; 4310 } else if (RHS.isFloat()) { 4311 APFloat FValue(0.0); 4312 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 4313 FValue) && 4314 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4315 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4316 Value); 4317 } 4318 4319 Info.FFDiag(E); 4320 return false; 4321 } 4322 bool found(APFloat &Value, QualType SubobjType) { 4323 return checkConst(SubobjType) && 4324 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4325 Value) && 4326 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4327 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4328 } 4329 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4330 if (!checkConst(SubobjType)) 4331 return false; 4332 4333 QualType PointeeType; 4334 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4335 PointeeType = PT->getPointeeType(); 4336 4337 if (PointeeType.isNull() || !RHS.isInt() || 4338 (Opcode != BO_Add && Opcode != BO_Sub)) { 4339 Info.FFDiag(E); 4340 return false; 4341 } 4342 4343 APSInt Offset = RHS.getInt(); 4344 if (Opcode == BO_Sub) 4345 negateAsSigned(Offset); 4346 4347 LValue LVal; 4348 LVal.setFrom(Info.Ctx, Subobj); 4349 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4350 return false; 4351 LVal.moveInto(Subobj); 4352 return true; 4353 } 4354 }; 4355 } // end anonymous namespace 4356 4357 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4358 4359 /// Perform a compound assignment of LVal <op>= RVal. 4360 static bool handleCompoundAssignment(EvalInfo &Info, 4361 const CompoundAssignOperator *E, 4362 const LValue &LVal, QualType LValType, 4363 QualType PromotedLValType, 4364 BinaryOperatorKind Opcode, 4365 const APValue &RVal) { 4366 if (LVal.Designator.Invalid) 4367 return false; 4368 4369 if (!Info.getLangOpts().CPlusPlus14) { 4370 Info.FFDiag(E); 4371 return false; 4372 } 4373 4374 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4375 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4376 RVal }; 4377 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4378 } 4379 4380 namespace { 4381 struct IncDecSubobjectHandler { 4382 EvalInfo &Info; 4383 const UnaryOperator *E; 4384 AccessKinds AccessKind; 4385 APValue *Old; 4386 4387 typedef bool result_type; 4388 4389 bool checkConst(QualType QT) { 4390 // Assigning to a const object has undefined behavior. 4391 if (QT.isConstQualified()) { 4392 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4393 return false; 4394 } 4395 return true; 4396 } 4397 4398 bool failed() { return false; } 4399 bool found(APValue &Subobj, QualType SubobjType) { 4400 // Stash the old value. Also clear Old, so we don't clobber it later 4401 // if we're post-incrementing a complex. 4402 if (Old) { 4403 *Old = Subobj; 4404 Old = nullptr; 4405 } 4406 4407 switch (Subobj.getKind()) { 4408 case APValue::Int: 4409 return found(Subobj.getInt(), SubobjType); 4410 case APValue::Float: 4411 return found(Subobj.getFloat(), SubobjType); 4412 case APValue::ComplexInt: 4413 return found(Subobj.getComplexIntReal(), 4414 SubobjType->castAs<ComplexType>()->getElementType() 4415 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4416 case APValue::ComplexFloat: 4417 return found(Subobj.getComplexFloatReal(), 4418 SubobjType->castAs<ComplexType>()->getElementType() 4419 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4420 case APValue::LValue: 4421 return foundPointer(Subobj, SubobjType); 4422 default: 4423 // FIXME: can this happen? 4424 Info.FFDiag(E); 4425 return false; 4426 } 4427 } 4428 bool found(APSInt &Value, QualType SubobjType) { 4429 if (!checkConst(SubobjType)) 4430 return false; 4431 4432 if (!SubobjType->isIntegerType()) { 4433 // We don't support increment / decrement on integer-cast-to-pointer 4434 // values. 4435 Info.FFDiag(E); 4436 return false; 4437 } 4438 4439 if (Old) *Old = APValue(Value); 4440 4441 // bool arithmetic promotes to int, and the conversion back to bool 4442 // doesn't reduce mod 2^n, so special-case it. 4443 if (SubobjType->isBooleanType()) { 4444 if (AccessKind == AK_Increment) 4445 Value = 1; 4446 else 4447 Value = !Value; 4448 return true; 4449 } 4450 4451 bool WasNegative = Value.isNegative(); 4452 if (AccessKind == AK_Increment) { 4453 ++Value; 4454 4455 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4456 APSInt ActualValue(Value, /*IsUnsigned*/true); 4457 return HandleOverflow(Info, E, ActualValue, SubobjType); 4458 } 4459 } else { 4460 --Value; 4461 4462 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4463 unsigned BitWidth = Value.getBitWidth(); 4464 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4465 ActualValue.setBit(BitWidth); 4466 return HandleOverflow(Info, E, ActualValue, SubobjType); 4467 } 4468 } 4469 return true; 4470 } 4471 bool found(APFloat &Value, QualType SubobjType) { 4472 if (!checkConst(SubobjType)) 4473 return false; 4474 4475 if (Old) *Old = APValue(Value); 4476 4477 APFloat One(Value.getSemantics(), 1); 4478 if (AccessKind == AK_Increment) 4479 Value.add(One, APFloat::rmNearestTiesToEven); 4480 else 4481 Value.subtract(One, APFloat::rmNearestTiesToEven); 4482 return true; 4483 } 4484 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4485 if (!checkConst(SubobjType)) 4486 return false; 4487 4488 QualType PointeeType; 4489 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4490 PointeeType = PT->getPointeeType(); 4491 else { 4492 Info.FFDiag(E); 4493 return false; 4494 } 4495 4496 LValue LVal; 4497 LVal.setFrom(Info.Ctx, Subobj); 4498 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4499 AccessKind == AK_Increment ? 1 : -1)) 4500 return false; 4501 LVal.moveInto(Subobj); 4502 return true; 4503 } 4504 }; 4505 } // end anonymous namespace 4506 4507 /// Perform an increment or decrement on LVal. 4508 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4509 QualType LValType, bool IsIncrement, APValue *Old) { 4510 if (LVal.Designator.Invalid) 4511 return false; 4512 4513 if (!Info.getLangOpts().CPlusPlus14) { 4514 Info.FFDiag(E); 4515 return false; 4516 } 4517 4518 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4519 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4520 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4521 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4522 } 4523 4524 /// Build an lvalue for the object argument of a member function call. 4525 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4526 LValue &This) { 4527 if (Object->getType()->isPointerType() && Object->isRValue()) 4528 return EvaluatePointer(Object, This, Info); 4529 4530 if (Object->isGLValue()) 4531 return EvaluateLValue(Object, This, Info); 4532 4533 if (Object->getType()->isLiteralType(Info.Ctx)) 4534 return EvaluateTemporary(Object, This, Info); 4535 4536 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4537 return false; 4538 } 4539 4540 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4541 /// lvalue referring to the result. 4542 /// 4543 /// \param Info - Information about the ongoing evaluation. 4544 /// \param LV - An lvalue referring to the base of the member pointer. 4545 /// \param RHS - The member pointer expression. 4546 /// \param IncludeMember - Specifies whether the member itself is included in 4547 /// the resulting LValue subobject designator. This is not possible when 4548 /// creating a bound member function. 4549 /// \return The field or method declaration to which the member pointer refers, 4550 /// or 0 if evaluation fails. 4551 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4552 QualType LVType, 4553 LValue &LV, 4554 const Expr *RHS, 4555 bool IncludeMember = true) { 4556 MemberPtr MemPtr; 4557 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4558 return nullptr; 4559 4560 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4561 // member value, the behavior is undefined. 4562 if (!MemPtr.getDecl()) { 4563 // FIXME: Specific diagnostic. 4564 Info.FFDiag(RHS); 4565 return nullptr; 4566 } 4567 4568 if (MemPtr.isDerivedMember()) { 4569 // This is a member of some derived class. Truncate LV appropriately. 4570 // The end of the derived-to-base path for the base object must match the 4571 // derived-to-base path for the member pointer. 4572 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4573 LV.Designator.Entries.size()) { 4574 Info.FFDiag(RHS); 4575 return nullptr; 4576 } 4577 unsigned PathLengthToMember = 4578 LV.Designator.Entries.size() - MemPtr.Path.size(); 4579 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4580 const CXXRecordDecl *LVDecl = getAsBaseClass( 4581 LV.Designator.Entries[PathLengthToMember + I]); 4582 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4583 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4584 Info.FFDiag(RHS); 4585 return nullptr; 4586 } 4587 } 4588 4589 // Truncate the lvalue to the appropriate derived class. 4590 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4591 PathLengthToMember)) 4592 return nullptr; 4593 } else if (!MemPtr.Path.empty()) { 4594 // Extend the LValue path with the member pointer's path. 4595 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4596 MemPtr.Path.size() + IncludeMember); 4597 4598 // Walk down to the appropriate base class. 4599 if (const PointerType *PT = LVType->getAs<PointerType>()) 4600 LVType = PT->getPointeeType(); 4601 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4602 assert(RD && "member pointer access on non-class-type expression"); 4603 // The first class in the path is that of the lvalue. 4604 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4605 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4606 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4607 return nullptr; 4608 RD = Base; 4609 } 4610 // Finally cast to the class containing the member. 4611 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4612 MemPtr.getContainingRecord())) 4613 return nullptr; 4614 } 4615 4616 // Add the member. Note that we cannot build bound member functions here. 4617 if (IncludeMember) { 4618 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4619 if (!HandleLValueMember(Info, RHS, LV, FD)) 4620 return nullptr; 4621 } else if (const IndirectFieldDecl *IFD = 4622 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4623 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4624 return nullptr; 4625 } else { 4626 llvm_unreachable("can't construct reference to bound member function"); 4627 } 4628 } 4629 4630 return MemPtr.getDecl(); 4631 } 4632 4633 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4634 const BinaryOperator *BO, 4635 LValue &LV, 4636 bool IncludeMember = true) { 4637 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4638 4639 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4640 if (Info.noteFailure()) { 4641 MemberPtr MemPtr; 4642 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4643 } 4644 return nullptr; 4645 } 4646 4647 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4648 BO->getRHS(), IncludeMember); 4649 } 4650 4651 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4652 /// the provided lvalue, which currently refers to the base object. 4653 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4654 LValue &Result) { 4655 SubobjectDesignator &D = Result.Designator; 4656 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4657 return false; 4658 4659 QualType TargetQT = E->getType(); 4660 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4661 TargetQT = PT->getPointeeType(); 4662 4663 // Check this cast lands within the final derived-to-base subobject path. 4664 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4665 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4666 << D.MostDerivedType << TargetQT; 4667 return false; 4668 } 4669 4670 // Check the type of the final cast. We don't need to check the path, 4671 // since a cast can only be formed if the path is unique. 4672 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4673 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4674 const CXXRecordDecl *FinalType; 4675 if (NewEntriesSize == D.MostDerivedPathLength) 4676 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4677 else 4678 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4679 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4680 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4681 << D.MostDerivedType << TargetQT; 4682 return false; 4683 } 4684 4685 // Truncate the lvalue to the appropriate derived class. 4686 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4687 } 4688 4689 /// Get the value to use for a default-initialized object of type T. 4690 /// Return false if it encounters something invalid. 4691 static bool getDefaultInitValue(QualType T, APValue &Result) { 4692 bool Success = true; 4693 if (auto *RD = T->getAsCXXRecordDecl()) { 4694 if (RD->isInvalidDecl()) { 4695 Result = APValue(); 4696 return false; 4697 } 4698 if (RD->isUnion()) { 4699 Result = APValue((const FieldDecl *)nullptr); 4700 return true; 4701 } 4702 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4703 std::distance(RD->field_begin(), RD->field_end())); 4704 4705 unsigned Index = 0; 4706 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4707 End = RD->bases_end(); 4708 I != End; ++I, ++Index) 4709 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4710 4711 for (const auto *I : RD->fields()) { 4712 if (I->isUnnamedBitfield()) 4713 continue; 4714 Success &= getDefaultInitValue(I->getType(), 4715 Result.getStructField(I->getFieldIndex())); 4716 } 4717 return Success; 4718 } 4719 4720 if (auto *AT = 4721 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4722 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4723 if (Result.hasArrayFiller()) 4724 Success &= 4725 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4726 4727 return Success; 4728 } 4729 4730 Result = APValue::IndeterminateValue(); 4731 return true; 4732 } 4733 4734 namespace { 4735 enum EvalStmtResult { 4736 /// Evaluation failed. 4737 ESR_Failed, 4738 /// Hit a 'return' statement. 4739 ESR_Returned, 4740 /// Evaluation succeeded. 4741 ESR_Succeeded, 4742 /// Hit a 'continue' statement. 4743 ESR_Continue, 4744 /// Hit a 'break' statement. 4745 ESR_Break, 4746 /// Still scanning for 'case' or 'default' statement. 4747 ESR_CaseNotFound 4748 }; 4749 } 4750 4751 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4752 // We don't need to evaluate the initializer for a static local. 4753 if (!VD->hasLocalStorage()) 4754 return true; 4755 4756 LValue Result; 4757 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4758 ScopeKind::Block, Result); 4759 4760 const Expr *InitE = VD->getInit(); 4761 if (!InitE) 4762 return getDefaultInitValue(VD->getType(), Val); 4763 4764 if (InitE->isValueDependent()) 4765 return false; 4766 4767 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4768 // Wipe out any partially-computed value, to allow tracking that this 4769 // evaluation failed. 4770 Val = APValue(); 4771 return false; 4772 } 4773 4774 return true; 4775 } 4776 4777 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4778 bool OK = true; 4779 4780 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4781 OK &= EvaluateVarDecl(Info, VD); 4782 4783 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4784 for (auto *BD : DD->bindings()) 4785 if (auto *VD = BD->getHoldingVar()) 4786 OK &= EvaluateDecl(Info, VD); 4787 4788 return OK; 4789 } 4790 4791 4792 /// Evaluate a condition (either a variable declaration or an expression). 4793 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4794 const Expr *Cond, bool &Result) { 4795 FullExpressionRAII Scope(Info); 4796 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4797 return false; 4798 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4799 return false; 4800 return Scope.destroy(); 4801 } 4802 4803 namespace { 4804 /// A location where the result (returned value) of evaluating a 4805 /// statement should be stored. 4806 struct StmtResult { 4807 /// The APValue that should be filled in with the returned value. 4808 APValue &Value; 4809 /// The location containing the result, if any (used to support RVO). 4810 const LValue *Slot; 4811 }; 4812 4813 struct TempVersionRAII { 4814 CallStackFrame &Frame; 4815 4816 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4817 Frame.pushTempVersion(); 4818 } 4819 4820 ~TempVersionRAII() { 4821 Frame.popTempVersion(); 4822 } 4823 }; 4824 4825 } 4826 4827 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4828 const Stmt *S, 4829 const SwitchCase *SC = nullptr); 4830 4831 /// Evaluate the body of a loop, and translate the result as appropriate. 4832 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4833 const Stmt *Body, 4834 const SwitchCase *Case = nullptr) { 4835 BlockScopeRAII Scope(Info); 4836 4837 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4838 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4839 ESR = ESR_Failed; 4840 4841 switch (ESR) { 4842 case ESR_Break: 4843 return ESR_Succeeded; 4844 case ESR_Succeeded: 4845 case ESR_Continue: 4846 return ESR_Continue; 4847 case ESR_Failed: 4848 case ESR_Returned: 4849 case ESR_CaseNotFound: 4850 return ESR; 4851 } 4852 llvm_unreachable("Invalid EvalStmtResult!"); 4853 } 4854 4855 /// Evaluate a switch statement. 4856 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4857 const SwitchStmt *SS) { 4858 BlockScopeRAII Scope(Info); 4859 4860 // Evaluate the switch condition. 4861 APSInt Value; 4862 { 4863 if (const Stmt *Init = SS->getInit()) { 4864 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4865 if (ESR != ESR_Succeeded) { 4866 if (ESR != ESR_Failed && !Scope.destroy()) 4867 ESR = ESR_Failed; 4868 return ESR; 4869 } 4870 } 4871 4872 FullExpressionRAII CondScope(Info); 4873 if (SS->getConditionVariable() && 4874 !EvaluateDecl(Info, SS->getConditionVariable())) 4875 return ESR_Failed; 4876 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4877 return ESR_Failed; 4878 if (!CondScope.destroy()) 4879 return ESR_Failed; 4880 } 4881 4882 // Find the switch case corresponding to the value of the condition. 4883 // FIXME: Cache this lookup. 4884 const SwitchCase *Found = nullptr; 4885 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4886 SC = SC->getNextSwitchCase()) { 4887 if (isa<DefaultStmt>(SC)) { 4888 Found = SC; 4889 continue; 4890 } 4891 4892 const CaseStmt *CS = cast<CaseStmt>(SC); 4893 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4894 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4895 : LHS; 4896 if (LHS <= Value && Value <= RHS) { 4897 Found = SC; 4898 break; 4899 } 4900 } 4901 4902 if (!Found) 4903 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4904 4905 // Search the switch body for the switch case and evaluate it from there. 4906 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4907 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4908 return ESR_Failed; 4909 4910 switch (ESR) { 4911 case ESR_Break: 4912 return ESR_Succeeded; 4913 case ESR_Succeeded: 4914 case ESR_Continue: 4915 case ESR_Failed: 4916 case ESR_Returned: 4917 return ESR; 4918 case ESR_CaseNotFound: 4919 // This can only happen if the switch case is nested within a statement 4920 // expression. We have no intention of supporting that. 4921 Info.FFDiag(Found->getBeginLoc(), 4922 diag::note_constexpr_stmt_expr_unsupported); 4923 return ESR_Failed; 4924 } 4925 llvm_unreachable("Invalid EvalStmtResult!"); 4926 } 4927 4928 // Evaluate a statement. 4929 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4930 const Stmt *S, const SwitchCase *Case) { 4931 if (!Info.nextStep(S)) 4932 return ESR_Failed; 4933 4934 // If we're hunting down a 'case' or 'default' label, recurse through 4935 // substatements until we hit the label. 4936 if (Case) { 4937 switch (S->getStmtClass()) { 4938 case Stmt::CompoundStmtClass: 4939 // FIXME: Precompute which substatement of a compound statement we 4940 // would jump to, and go straight there rather than performing a 4941 // linear scan each time. 4942 case Stmt::LabelStmtClass: 4943 case Stmt::AttributedStmtClass: 4944 case Stmt::DoStmtClass: 4945 break; 4946 4947 case Stmt::CaseStmtClass: 4948 case Stmt::DefaultStmtClass: 4949 if (Case == S) 4950 Case = nullptr; 4951 break; 4952 4953 case Stmt::IfStmtClass: { 4954 // FIXME: Precompute which side of an 'if' we would jump to, and go 4955 // straight there rather than scanning both sides. 4956 const IfStmt *IS = cast<IfStmt>(S); 4957 4958 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4959 // preceded by our switch label. 4960 BlockScopeRAII Scope(Info); 4961 4962 // Step into the init statement in case it brings an (uninitialized) 4963 // variable into scope. 4964 if (const Stmt *Init = IS->getInit()) { 4965 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4966 if (ESR != ESR_CaseNotFound) { 4967 assert(ESR != ESR_Succeeded); 4968 return ESR; 4969 } 4970 } 4971 4972 // Condition variable must be initialized if it exists. 4973 // FIXME: We can skip evaluating the body if there's a condition 4974 // variable, as there can't be any case labels within it. 4975 // (The same is true for 'for' statements.) 4976 4977 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4978 if (ESR == ESR_Failed) 4979 return ESR; 4980 if (ESR != ESR_CaseNotFound) 4981 return Scope.destroy() ? ESR : ESR_Failed; 4982 if (!IS->getElse()) 4983 return ESR_CaseNotFound; 4984 4985 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4986 if (ESR == ESR_Failed) 4987 return ESR; 4988 if (ESR != ESR_CaseNotFound) 4989 return Scope.destroy() ? ESR : ESR_Failed; 4990 return ESR_CaseNotFound; 4991 } 4992 4993 case Stmt::WhileStmtClass: { 4994 EvalStmtResult ESR = 4995 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4996 if (ESR != ESR_Continue) 4997 return ESR; 4998 break; 4999 } 5000 5001 case Stmt::ForStmtClass: { 5002 const ForStmt *FS = cast<ForStmt>(S); 5003 BlockScopeRAII Scope(Info); 5004 5005 // Step into the init statement in case it brings an (uninitialized) 5006 // variable into scope. 5007 if (const Stmt *Init = FS->getInit()) { 5008 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5009 if (ESR != ESR_CaseNotFound) { 5010 assert(ESR != ESR_Succeeded); 5011 return ESR; 5012 } 5013 } 5014 5015 EvalStmtResult ESR = 5016 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5017 if (ESR != ESR_Continue) 5018 return ESR; 5019 if (FS->getInc()) { 5020 FullExpressionRAII IncScope(Info); 5021 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5022 return ESR_Failed; 5023 } 5024 break; 5025 } 5026 5027 case Stmt::DeclStmtClass: { 5028 // Start the lifetime of any uninitialized variables we encounter. They 5029 // might be used by the selected branch of the switch. 5030 const DeclStmt *DS = cast<DeclStmt>(S); 5031 for (const auto *D : DS->decls()) { 5032 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5033 if (VD->hasLocalStorage() && !VD->getInit()) 5034 if (!EvaluateVarDecl(Info, VD)) 5035 return ESR_Failed; 5036 // FIXME: If the variable has initialization that can't be jumped 5037 // over, bail out of any immediately-surrounding compound-statement 5038 // too. There can't be any case labels here. 5039 } 5040 } 5041 return ESR_CaseNotFound; 5042 } 5043 5044 default: 5045 return ESR_CaseNotFound; 5046 } 5047 } 5048 5049 switch (S->getStmtClass()) { 5050 default: 5051 if (const Expr *E = dyn_cast<Expr>(S)) { 5052 // Don't bother evaluating beyond an expression-statement which couldn't 5053 // be evaluated. 5054 // FIXME: Do we need the FullExpressionRAII object here? 5055 // VisitExprWithCleanups should create one when necessary. 5056 FullExpressionRAII Scope(Info); 5057 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5058 return ESR_Failed; 5059 return ESR_Succeeded; 5060 } 5061 5062 Info.FFDiag(S->getBeginLoc()); 5063 return ESR_Failed; 5064 5065 case Stmt::NullStmtClass: 5066 return ESR_Succeeded; 5067 5068 case Stmt::DeclStmtClass: { 5069 const DeclStmt *DS = cast<DeclStmt>(S); 5070 for (const auto *D : DS->decls()) { 5071 // Each declaration initialization is its own full-expression. 5072 FullExpressionRAII Scope(Info); 5073 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5074 return ESR_Failed; 5075 if (!Scope.destroy()) 5076 return ESR_Failed; 5077 } 5078 return ESR_Succeeded; 5079 } 5080 5081 case Stmt::ReturnStmtClass: { 5082 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5083 FullExpressionRAII Scope(Info); 5084 if (RetExpr && 5085 !(Result.Slot 5086 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5087 : Evaluate(Result.Value, Info, RetExpr))) 5088 return ESR_Failed; 5089 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5090 } 5091 5092 case Stmt::CompoundStmtClass: { 5093 BlockScopeRAII Scope(Info); 5094 5095 const CompoundStmt *CS = cast<CompoundStmt>(S); 5096 for (const auto *BI : CS->body()) { 5097 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5098 if (ESR == ESR_Succeeded) 5099 Case = nullptr; 5100 else if (ESR != ESR_CaseNotFound) { 5101 if (ESR != ESR_Failed && !Scope.destroy()) 5102 return ESR_Failed; 5103 return ESR; 5104 } 5105 } 5106 if (Case) 5107 return ESR_CaseNotFound; 5108 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5109 } 5110 5111 case Stmt::IfStmtClass: { 5112 const IfStmt *IS = cast<IfStmt>(S); 5113 5114 // Evaluate the condition, as either a var decl or as an expression. 5115 BlockScopeRAII Scope(Info); 5116 if (const Stmt *Init = IS->getInit()) { 5117 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5118 if (ESR != ESR_Succeeded) { 5119 if (ESR != ESR_Failed && !Scope.destroy()) 5120 return ESR_Failed; 5121 return ESR; 5122 } 5123 } 5124 bool Cond; 5125 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5126 return ESR_Failed; 5127 5128 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5129 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5130 if (ESR != ESR_Succeeded) { 5131 if (ESR != ESR_Failed && !Scope.destroy()) 5132 return ESR_Failed; 5133 return ESR; 5134 } 5135 } 5136 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5137 } 5138 5139 case Stmt::WhileStmtClass: { 5140 const WhileStmt *WS = cast<WhileStmt>(S); 5141 while (true) { 5142 BlockScopeRAII Scope(Info); 5143 bool Continue; 5144 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5145 Continue)) 5146 return ESR_Failed; 5147 if (!Continue) 5148 break; 5149 5150 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5151 if (ESR != ESR_Continue) { 5152 if (ESR != ESR_Failed && !Scope.destroy()) 5153 return ESR_Failed; 5154 return ESR; 5155 } 5156 if (!Scope.destroy()) 5157 return ESR_Failed; 5158 } 5159 return ESR_Succeeded; 5160 } 5161 5162 case Stmt::DoStmtClass: { 5163 const DoStmt *DS = cast<DoStmt>(S); 5164 bool Continue; 5165 do { 5166 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5167 if (ESR != ESR_Continue) 5168 return ESR; 5169 Case = nullptr; 5170 5171 FullExpressionRAII CondScope(Info); 5172 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5173 !CondScope.destroy()) 5174 return ESR_Failed; 5175 } while (Continue); 5176 return ESR_Succeeded; 5177 } 5178 5179 case Stmt::ForStmtClass: { 5180 const ForStmt *FS = cast<ForStmt>(S); 5181 BlockScopeRAII ForScope(Info); 5182 if (FS->getInit()) { 5183 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5184 if (ESR != ESR_Succeeded) { 5185 if (ESR != ESR_Failed && !ForScope.destroy()) 5186 return ESR_Failed; 5187 return ESR; 5188 } 5189 } 5190 while (true) { 5191 BlockScopeRAII IterScope(Info); 5192 bool Continue = true; 5193 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5194 FS->getCond(), Continue)) 5195 return ESR_Failed; 5196 if (!Continue) 5197 break; 5198 5199 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5200 if (ESR != ESR_Continue) { 5201 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5202 return ESR_Failed; 5203 return ESR; 5204 } 5205 5206 if (FS->getInc()) { 5207 FullExpressionRAII IncScope(Info); 5208 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5209 return ESR_Failed; 5210 } 5211 5212 if (!IterScope.destroy()) 5213 return ESR_Failed; 5214 } 5215 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5216 } 5217 5218 case Stmt::CXXForRangeStmtClass: { 5219 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5220 BlockScopeRAII Scope(Info); 5221 5222 // Evaluate the init-statement if present. 5223 if (FS->getInit()) { 5224 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5225 if (ESR != ESR_Succeeded) { 5226 if (ESR != ESR_Failed && !Scope.destroy()) 5227 return ESR_Failed; 5228 return ESR; 5229 } 5230 } 5231 5232 // Initialize the __range variable. 5233 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5234 if (ESR != ESR_Succeeded) { 5235 if (ESR != ESR_Failed && !Scope.destroy()) 5236 return ESR_Failed; 5237 return ESR; 5238 } 5239 5240 // Create the __begin and __end iterators. 5241 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5242 if (ESR != ESR_Succeeded) { 5243 if (ESR != ESR_Failed && !Scope.destroy()) 5244 return ESR_Failed; 5245 return ESR; 5246 } 5247 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5248 if (ESR != ESR_Succeeded) { 5249 if (ESR != ESR_Failed && !Scope.destroy()) 5250 return ESR_Failed; 5251 return ESR; 5252 } 5253 5254 while (true) { 5255 // Condition: __begin != __end. 5256 { 5257 bool Continue = true; 5258 FullExpressionRAII CondExpr(Info); 5259 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5260 return ESR_Failed; 5261 if (!Continue) 5262 break; 5263 } 5264 5265 // User's variable declaration, initialized by *__begin. 5266 BlockScopeRAII InnerScope(Info); 5267 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5268 if (ESR != ESR_Succeeded) { 5269 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5270 return ESR_Failed; 5271 return ESR; 5272 } 5273 5274 // Loop body. 5275 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5276 if (ESR != ESR_Continue) { 5277 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5278 return ESR_Failed; 5279 return ESR; 5280 } 5281 5282 // Increment: ++__begin 5283 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5284 return ESR_Failed; 5285 5286 if (!InnerScope.destroy()) 5287 return ESR_Failed; 5288 } 5289 5290 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5291 } 5292 5293 case Stmt::SwitchStmtClass: 5294 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5295 5296 case Stmt::ContinueStmtClass: 5297 return ESR_Continue; 5298 5299 case Stmt::BreakStmtClass: 5300 return ESR_Break; 5301 5302 case Stmt::LabelStmtClass: 5303 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5304 5305 case Stmt::AttributedStmtClass: 5306 // As a general principle, C++11 attributes can be ignored without 5307 // any semantic impact. 5308 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5309 Case); 5310 5311 case Stmt::CaseStmtClass: 5312 case Stmt::DefaultStmtClass: 5313 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5314 case Stmt::CXXTryStmtClass: 5315 // Evaluate try blocks by evaluating all sub statements. 5316 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5317 } 5318 } 5319 5320 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5321 /// default constructor. If so, we'll fold it whether or not it's marked as 5322 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5323 /// so we need special handling. 5324 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5325 const CXXConstructorDecl *CD, 5326 bool IsValueInitialization) { 5327 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5328 return false; 5329 5330 // Value-initialization does not call a trivial default constructor, so such a 5331 // call is a core constant expression whether or not the constructor is 5332 // constexpr. 5333 if (!CD->isConstexpr() && !IsValueInitialization) { 5334 if (Info.getLangOpts().CPlusPlus11) { 5335 // FIXME: If DiagDecl is an implicitly-declared special member function, 5336 // we should be much more explicit about why it's not constexpr. 5337 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5338 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5339 Info.Note(CD->getLocation(), diag::note_declared_at); 5340 } else { 5341 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5342 } 5343 } 5344 return true; 5345 } 5346 5347 /// CheckConstexprFunction - Check that a function can be called in a constant 5348 /// expression. 5349 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5350 const FunctionDecl *Declaration, 5351 const FunctionDecl *Definition, 5352 const Stmt *Body) { 5353 // Potential constant expressions can contain calls to declared, but not yet 5354 // defined, constexpr functions. 5355 if (Info.checkingPotentialConstantExpression() && !Definition && 5356 Declaration->isConstexpr()) 5357 return false; 5358 5359 // Bail out if the function declaration itself is invalid. We will 5360 // have produced a relevant diagnostic while parsing it, so just 5361 // note the problematic sub-expression. 5362 if (Declaration->isInvalidDecl()) { 5363 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5364 return false; 5365 } 5366 5367 // DR1872: An instantiated virtual constexpr function can't be called in a 5368 // constant expression (prior to C++20). We can still constant-fold such a 5369 // call. 5370 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5371 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5372 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5373 5374 if (Definition && Definition->isInvalidDecl()) { 5375 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5376 return false; 5377 } 5378 5379 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) { 5380 for (const auto *InitExpr : CtorDecl->inits()) { 5381 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 5382 return false; 5383 } 5384 } 5385 5386 // Can we evaluate this function call? 5387 if (Definition && Definition->isConstexpr() && Body) 5388 return true; 5389 5390 if (Info.getLangOpts().CPlusPlus11) { 5391 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5392 5393 // If this function is not constexpr because it is an inherited 5394 // non-constexpr constructor, diagnose that directly. 5395 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5396 if (CD && CD->isInheritingConstructor()) { 5397 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5398 if (!Inherited->isConstexpr()) 5399 DiagDecl = CD = Inherited; 5400 } 5401 5402 // FIXME: If DiagDecl is an implicitly-declared special member function 5403 // or an inheriting constructor, we should be much more explicit about why 5404 // it's not constexpr. 5405 if (CD && CD->isInheritingConstructor()) 5406 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5407 << CD->getInheritedConstructor().getConstructor()->getParent(); 5408 else 5409 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5410 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5411 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5412 } else { 5413 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5414 } 5415 return false; 5416 } 5417 5418 namespace { 5419 struct CheckDynamicTypeHandler { 5420 AccessKinds AccessKind; 5421 typedef bool result_type; 5422 bool failed() { return false; } 5423 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5424 bool found(APSInt &Value, QualType SubobjType) { return true; } 5425 bool found(APFloat &Value, QualType SubobjType) { return true; } 5426 }; 5427 } // end anonymous namespace 5428 5429 /// Check that we can access the notional vptr of an object / determine its 5430 /// dynamic type. 5431 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5432 AccessKinds AK, bool Polymorphic) { 5433 if (This.Designator.Invalid) 5434 return false; 5435 5436 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5437 5438 if (!Obj) 5439 return false; 5440 5441 if (!Obj.Value) { 5442 // The object is not usable in constant expressions, so we can't inspect 5443 // its value to see if it's in-lifetime or what the active union members 5444 // are. We can still check for a one-past-the-end lvalue. 5445 if (This.Designator.isOnePastTheEnd() || 5446 This.Designator.isMostDerivedAnUnsizedArray()) { 5447 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5448 ? diag::note_constexpr_access_past_end 5449 : diag::note_constexpr_access_unsized_array) 5450 << AK; 5451 return false; 5452 } else if (Polymorphic) { 5453 // Conservatively refuse to perform a polymorphic operation if we would 5454 // not be able to read a notional 'vptr' value. 5455 APValue Val; 5456 This.moveInto(Val); 5457 QualType StarThisType = 5458 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5459 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5460 << AK << Val.getAsString(Info.Ctx, StarThisType); 5461 return false; 5462 } 5463 return true; 5464 } 5465 5466 CheckDynamicTypeHandler Handler{AK}; 5467 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5468 } 5469 5470 /// Check that the pointee of the 'this' pointer in a member function call is 5471 /// either within its lifetime or in its period of construction or destruction. 5472 static bool 5473 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5474 const LValue &This, 5475 const CXXMethodDecl *NamedMember) { 5476 return checkDynamicType( 5477 Info, E, This, 5478 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5479 } 5480 5481 struct DynamicType { 5482 /// The dynamic class type of the object. 5483 const CXXRecordDecl *Type; 5484 /// The corresponding path length in the lvalue. 5485 unsigned PathLength; 5486 }; 5487 5488 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5489 unsigned PathLength) { 5490 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5491 Designator.Entries.size() && "invalid path length"); 5492 return (PathLength == Designator.MostDerivedPathLength) 5493 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5494 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5495 } 5496 5497 /// Determine the dynamic type of an object. 5498 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5499 LValue &This, AccessKinds AK) { 5500 // If we don't have an lvalue denoting an object of class type, there is no 5501 // meaningful dynamic type. (We consider objects of non-class type to have no 5502 // dynamic type.) 5503 if (!checkDynamicType(Info, E, This, AK, true)) 5504 return None; 5505 5506 // Refuse to compute a dynamic type in the presence of virtual bases. This 5507 // shouldn't happen other than in constant-folding situations, since literal 5508 // types can't have virtual bases. 5509 // 5510 // Note that consumers of DynamicType assume that the type has no virtual 5511 // bases, and will need modifications if this restriction is relaxed. 5512 const CXXRecordDecl *Class = 5513 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5514 if (!Class || Class->getNumVBases()) { 5515 Info.FFDiag(E); 5516 return None; 5517 } 5518 5519 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5520 // binary search here instead. But the overwhelmingly common case is that 5521 // we're not in the middle of a constructor, so it probably doesn't matter 5522 // in practice. 5523 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5524 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5525 PathLength <= Path.size(); ++PathLength) { 5526 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5527 Path.slice(0, PathLength))) { 5528 case ConstructionPhase::Bases: 5529 case ConstructionPhase::DestroyingBases: 5530 // We're constructing or destroying a base class. This is not the dynamic 5531 // type. 5532 break; 5533 5534 case ConstructionPhase::None: 5535 case ConstructionPhase::AfterBases: 5536 case ConstructionPhase::AfterFields: 5537 case ConstructionPhase::Destroying: 5538 // We've finished constructing the base classes and not yet started 5539 // destroying them again, so this is the dynamic type. 5540 return DynamicType{getBaseClassType(This.Designator, PathLength), 5541 PathLength}; 5542 } 5543 } 5544 5545 // CWG issue 1517: we're constructing a base class of the object described by 5546 // 'This', so that object has not yet begun its period of construction and 5547 // any polymorphic operation on it results in undefined behavior. 5548 Info.FFDiag(E); 5549 return None; 5550 } 5551 5552 /// Perform virtual dispatch. 5553 static const CXXMethodDecl *HandleVirtualDispatch( 5554 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5555 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5556 Optional<DynamicType> DynType = ComputeDynamicType( 5557 Info, E, This, 5558 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5559 if (!DynType) 5560 return nullptr; 5561 5562 // Find the final overrider. It must be declared in one of the classes on the 5563 // path from the dynamic type to the static type. 5564 // FIXME: If we ever allow literal types to have virtual base classes, that 5565 // won't be true. 5566 const CXXMethodDecl *Callee = Found; 5567 unsigned PathLength = DynType->PathLength; 5568 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5569 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5570 const CXXMethodDecl *Overrider = 5571 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5572 if (Overrider) { 5573 Callee = Overrider; 5574 break; 5575 } 5576 } 5577 5578 // C++2a [class.abstract]p6: 5579 // the effect of making a virtual call to a pure virtual function [...] is 5580 // undefined 5581 if (Callee->isPure()) { 5582 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5583 Info.Note(Callee->getLocation(), diag::note_declared_at); 5584 return nullptr; 5585 } 5586 5587 // If necessary, walk the rest of the path to determine the sequence of 5588 // covariant adjustment steps to apply. 5589 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5590 Found->getReturnType())) { 5591 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5592 for (unsigned CovariantPathLength = PathLength + 1; 5593 CovariantPathLength != This.Designator.Entries.size(); 5594 ++CovariantPathLength) { 5595 const CXXRecordDecl *NextClass = 5596 getBaseClassType(This.Designator, CovariantPathLength); 5597 const CXXMethodDecl *Next = 5598 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5599 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5600 Next->getReturnType(), CovariantAdjustmentPath.back())) 5601 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5602 } 5603 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5604 CovariantAdjustmentPath.back())) 5605 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5606 } 5607 5608 // Perform 'this' adjustment. 5609 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5610 return nullptr; 5611 5612 return Callee; 5613 } 5614 5615 /// Perform the adjustment from a value returned by a virtual function to 5616 /// a value of the statically expected type, which may be a pointer or 5617 /// reference to a base class of the returned type. 5618 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5619 APValue &Result, 5620 ArrayRef<QualType> Path) { 5621 assert(Result.isLValue() && 5622 "unexpected kind of APValue for covariant return"); 5623 if (Result.isNullPointer()) 5624 return true; 5625 5626 LValue LVal; 5627 LVal.setFrom(Info.Ctx, Result); 5628 5629 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5630 for (unsigned I = 1; I != Path.size(); ++I) { 5631 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5632 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5633 if (OldClass != NewClass && 5634 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5635 return false; 5636 OldClass = NewClass; 5637 } 5638 5639 LVal.moveInto(Result); 5640 return true; 5641 } 5642 5643 /// Determine whether \p Base, which is known to be a direct base class of 5644 /// \p Derived, is a public base class. 5645 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5646 const CXXRecordDecl *Base) { 5647 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5648 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5649 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5650 return BaseSpec.getAccessSpecifier() == AS_public; 5651 } 5652 llvm_unreachable("Base is not a direct base of Derived"); 5653 } 5654 5655 /// Apply the given dynamic cast operation on the provided lvalue. 5656 /// 5657 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5658 /// to find a suitable target subobject. 5659 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5660 LValue &Ptr) { 5661 // We can't do anything with a non-symbolic pointer value. 5662 SubobjectDesignator &D = Ptr.Designator; 5663 if (D.Invalid) 5664 return false; 5665 5666 // C++ [expr.dynamic.cast]p6: 5667 // If v is a null pointer value, the result is a null pointer value. 5668 if (Ptr.isNullPointer() && !E->isGLValue()) 5669 return true; 5670 5671 // For all the other cases, we need the pointer to point to an object within 5672 // its lifetime / period of construction / destruction, and we need to know 5673 // its dynamic type. 5674 Optional<DynamicType> DynType = 5675 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5676 if (!DynType) 5677 return false; 5678 5679 // C++ [expr.dynamic.cast]p7: 5680 // If T is "pointer to cv void", then the result is a pointer to the most 5681 // derived object 5682 if (E->getType()->isVoidPointerType()) 5683 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5684 5685 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5686 assert(C && "dynamic_cast target is not void pointer nor class"); 5687 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5688 5689 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5690 // C++ [expr.dynamic.cast]p9: 5691 if (!E->isGLValue()) { 5692 // The value of a failed cast to pointer type is the null pointer value 5693 // of the required result type. 5694 Ptr.setNull(Info.Ctx, E->getType()); 5695 return true; 5696 } 5697 5698 // A failed cast to reference type throws [...] std::bad_cast. 5699 unsigned DiagKind; 5700 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5701 DynType->Type->isDerivedFrom(C))) 5702 DiagKind = 0; 5703 else if (!Paths || Paths->begin() == Paths->end()) 5704 DiagKind = 1; 5705 else if (Paths->isAmbiguous(CQT)) 5706 DiagKind = 2; 5707 else { 5708 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5709 DiagKind = 3; 5710 } 5711 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5712 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5713 << Info.Ctx.getRecordType(DynType->Type) 5714 << E->getType().getUnqualifiedType(); 5715 return false; 5716 }; 5717 5718 // Runtime check, phase 1: 5719 // Walk from the base subobject towards the derived object looking for the 5720 // target type. 5721 for (int PathLength = Ptr.Designator.Entries.size(); 5722 PathLength >= (int)DynType->PathLength; --PathLength) { 5723 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5724 if (declaresSameEntity(Class, C)) 5725 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5726 // We can only walk across public inheritance edges. 5727 if (PathLength > (int)DynType->PathLength && 5728 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5729 Class)) 5730 return RuntimeCheckFailed(nullptr); 5731 } 5732 5733 // Runtime check, phase 2: 5734 // Search the dynamic type for an unambiguous public base of type C. 5735 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5736 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5737 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5738 Paths.front().Access == AS_public) { 5739 // Downcast to the dynamic type... 5740 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5741 return false; 5742 // ... then upcast to the chosen base class subobject. 5743 for (CXXBasePathElement &Elem : Paths.front()) 5744 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5745 return false; 5746 return true; 5747 } 5748 5749 // Otherwise, the runtime check fails. 5750 return RuntimeCheckFailed(&Paths); 5751 } 5752 5753 namespace { 5754 struct StartLifetimeOfUnionMemberHandler { 5755 EvalInfo &Info; 5756 const Expr *LHSExpr; 5757 const FieldDecl *Field; 5758 bool DuringInit; 5759 bool Failed = false; 5760 static const AccessKinds AccessKind = AK_Assign; 5761 5762 typedef bool result_type; 5763 bool failed() { return Failed; } 5764 bool found(APValue &Subobj, QualType SubobjType) { 5765 // We are supposed to perform no initialization but begin the lifetime of 5766 // the object. We interpret that as meaning to do what default 5767 // initialization of the object would do if all constructors involved were 5768 // trivial: 5769 // * All base, non-variant member, and array element subobjects' lifetimes 5770 // begin 5771 // * No variant members' lifetimes begin 5772 // * All scalar subobjects whose lifetimes begin have indeterminate values 5773 assert(SubobjType->isUnionType()); 5774 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5775 // This union member is already active. If it's also in-lifetime, there's 5776 // nothing to do. 5777 if (Subobj.getUnionValue().hasValue()) 5778 return true; 5779 } else if (DuringInit) { 5780 // We're currently in the process of initializing a different union 5781 // member. If we carried on, that initialization would attempt to 5782 // store to an inactive union member, resulting in undefined behavior. 5783 Info.FFDiag(LHSExpr, 5784 diag::note_constexpr_union_member_change_during_init); 5785 return false; 5786 } 5787 APValue Result; 5788 Failed = !getDefaultInitValue(Field->getType(), Result); 5789 Subobj.setUnion(Field, Result); 5790 return true; 5791 } 5792 bool found(APSInt &Value, QualType SubobjType) { 5793 llvm_unreachable("wrong value kind for union object"); 5794 } 5795 bool found(APFloat &Value, QualType SubobjType) { 5796 llvm_unreachable("wrong value kind for union object"); 5797 } 5798 }; 5799 } // end anonymous namespace 5800 5801 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5802 5803 /// Handle a builtin simple-assignment or a call to a trivial assignment 5804 /// operator whose left-hand side might involve a union member access. If it 5805 /// does, implicitly start the lifetime of any accessed union elements per 5806 /// C++20 [class.union]5. 5807 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5808 const LValue &LHS) { 5809 if (LHS.InvalidBase || LHS.Designator.Invalid) 5810 return false; 5811 5812 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5813 // C++ [class.union]p5: 5814 // define the set S(E) of subexpressions of E as follows: 5815 unsigned PathLength = LHS.Designator.Entries.size(); 5816 for (const Expr *E = LHSExpr; E != nullptr;) { 5817 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5818 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5819 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5820 // Note that we can't implicitly start the lifetime of a reference, 5821 // so we don't need to proceed any further if we reach one. 5822 if (!FD || FD->getType()->isReferenceType()) 5823 break; 5824 5825 // ... and also contains A.B if B names a union member ... 5826 if (FD->getParent()->isUnion()) { 5827 // ... of a non-class, non-array type, or of a class type with a 5828 // trivial default constructor that is not deleted, or an array of 5829 // such types. 5830 auto *RD = 5831 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5832 if (!RD || RD->hasTrivialDefaultConstructor()) 5833 UnionPathLengths.push_back({PathLength - 1, FD}); 5834 } 5835 5836 E = ME->getBase(); 5837 --PathLength; 5838 assert(declaresSameEntity(FD, 5839 LHS.Designator.Entries[PathLength] 5840 .getAsBaseOrMember().getPointer())); 5841 5842 // -- If E is of the form A[B] and is interpreted as a built-in array 5843 // subscripting operator, S(E) is [S(the array operand, if any)]. 5844 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5845 // Step over an ArrayToPointerDecay implicit cast. 5846 auto *Base = ASE->getBase()->IgnoreImplicit(); 5847 if (!Base->getType()->isArrayType()) 5848 break; 5849 5850 E = Base; 5851 --PathLength; 5852 5853 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5854 // Step over a derived-to-base conversion. 5855 E = ICE->getSubExpr(); 5856 if (ICE->getCastKind() == CK_NoOp) 5857 continue; 5858 if (ICE->getCastKind() != CK_DerivedToBase && 5859 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5860 break; 5861 // Walk path backwards as we walk up from the base to the derived class. 5862 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5863 --PathLength; 5864 (void)Elt; 5865 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5866 LHS.Designator.Entries[PathLength] 5867 .getAsBaseOrMember().getPointer())); 5868 } 5869 5870 // -- Otherwise, S(E) is empty. 5871 } else { 5872 break; 5873 } 5874 } 5875 5876 // Common case: no unions' lifetimes are started. 5877 if (UnionPathLengths.empty()) 5878 return true; 5879 5880 // if modification of X [would access an inactive union member], an object 5881 // of the type of X is implicitly created 5882 CompleteObject Obj = 5883 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5884 if (!Obj) 5885 return false; 5886 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5887 llvm::reverse(UnionPathLengths)) { 5888 // Form a designator for the union object. 5889 SubobjectDesignator D = LHS.Designator; 5890 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5891 5892 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5893 ConstructionPhase::AfterBases; 5894 StartLifetimeOfUnionMemberHandler StartLifetime{ 5895 Info, LHSExpr, LengthAndField.second, DuringInit}; 5896 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5897 return false; 5898 } 5899 5900 return true; 5901 } 5902 5903 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5904 CallRef Call, EvalInfo &Info, 5905 bool NonNull = false) { 5906 LValue LV; 5907 // Create the parameter slot and register its destruction. For a vararg 5908 // argument, create a temporary. 5909 // FIXME: For calling conventions that destroy parameters in the callee, 5910 // should we consider performing destruction when the function returns 5911 // instead? 5912 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 5913 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 5914 ScopeKind::Call, LV); 5915 if (!EvaluateInPlace(V, Info, LV, Arg)) 5916 return false; 5917 5918 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 5919 // undefined behavior, so is non-constant. 5920 if (NonNull && V.isLValue() && V.isNullPointer()) { 5921 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 5922 return false; 5923 } 5924 5925 return true; 5926 } 5927 5928 /// Evaluate the arguments to a function call. 5929 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 5930 EvalInfo &Info, const FunctionDecl *Callee, 5931 bool RightToLeft = false) { 5932 bool Success = true; 5933 llvm::SmallBitVector ForbiddenNullArgs; 5934 if (Callee->hasAttr<NonNullAttr>()) { 5935 ForbiddenNullArgs.resize(Args.size()); 5936 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5937 if (!Attr->args_size()) { 5938 ForbiddenNullArgs.set(); 5939 break; 5940 } else 5941 for (auto Idx : Attr->args()) { 5942 unsigned ASTIdx = Idx.getASTIndex(); 5943 if (ASTIdx >= Args.size()) 5944 continue; 5945 ForbiddenNullArgs[ASTIdx] = 1; 5946 } 5947 } 5948 } 5949 for (unsigned I = 0; I < Args.size(); I++) { 5950 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 5951 const ParmVarDecl *PVD = 5952 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 5953 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 5954 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 5955 // If we're checking for a potential constant expression, evaluate all 5956 // initializers even if some of them fail. 5957 if (!Info.noteFailure()) 5958 return false; 5959 Success = false; 5960 } 5961 } 5962 return Success; 5963 } 5964 5965 /// Perform a trivial copy from Param, which is the parameter of a copy or move 5966 /// constructor or assignment operator. 5967 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 5968 const Expr *E, APValue &Result, 5969 bool CopyObjectRepresentation) { 5970 // Find the reference argument. 5971 CallStackFrame *Frame = Info.CurrentCall; 5972 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 5973 if (!RefValue) { 5974 Info.FFDiag(E); 5975 return false; 5976 } 5977 5978 // Copy out the contents of the RHS object. 5979 LValue RefLValue; 5980 RefLValue.setFrom(Info.Ctx, *RefValue); 5981 return handleLValueToRValueConversion( 5982 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 5983 CopyObjectRepresentation); 5984 } 5985 5986 /// Evaluate a function call. 5987 static bool HandleFunctionCall(SourceLocation CallLoc, 5988 const FunctionDecl *Callee, const LValue *This, 5989 ArrayRef<const Expr *> Args, CallRef Call, 5990 const Stmt *Body, EvalInfo &Info, 5991 APValue &Result, const LValue *ResultSlot) { 5992 if (!Info.CheckCallLimit(CallLoc)) 5993 return false; 5994 5995 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 5996 5997 // For a trivial copy or move assignment, perform an APValue copy. This is 5998 // essential for unions, where the operations performed by the assignment 5999 // operator cannot be represented as statements. 6000 // 6001 // Skip this for non-union classes with no fields; in that case, the defaulted 6002 // copy/move does not actually read the object. 6003 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6004 if (MD && MD->isDefaulted() && 6005 (MD->getParent()->isUnion() || 6006 (MD->isTrivial() && 6007 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6008 assert(This && 6009 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6010 APValue RHSValue; 6011 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6012 MD->getParent()->isUnion())) 6013 return false; 6014 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6015 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6016 return false; 6017 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6018 RHSValue)) 6019 return false; 6020 This->moveInto(Result); 6021 return true; 6022 } else if (MD && isLambdaCallOperator(MD)) { 6023 // We're in a lambda; determine the lambda capture field maps unless we're 6024 // just constexpr checking a lambda's call operator. constexpr checking is 6025 // done before the captures have been added to the closure object (unless 6026 // we're inferring constexpr-ness), so we don't have access to them in this 6027 // case. But since we don't need the captures to constexpr check, we can 6028 // just ignore them. 6029 if (!Info.checkingPotentialConstantExpression()) 6030 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6031 Frame.LambdaThisCaptureField); 6032 } 6033 6034 StmtResult Ret = {Result, ResultSlot}; 6035 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6036 if (ESR == ESR_Succeeded) { 6037 if (Callee->getReturnType()->isVoidType()) 6038 return true; 6039 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6040 } 6041 return ESR == ESR_Returned; 6042 } 6043 6044 /// Evaluate a constructor call. 6045 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6046 CallRef Call, 6047 const CXXConstructorDecl *Definition, 6048 EvalInfo &Info, APValue &Result) { 6049 SourceLocation CallLoc = E->getExprLoc(); 6050 if (!Info.CheckCallLimit(CallLoc)) 6051 return false; 6052 6053 const CXXRecordDecl *RD = Definition->getParent(); 6054 if (RD->getNumVBases()) { 6055 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6056 return false; 6057 } 6058 6059 EvalInfo::EvaluatingConstructorRAII EvalObj( 6060 Info, 6061 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6062 RD->getNumBases()); 6063 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6064 6065 // FIXME: Creating an APValue just to hold a nonexistent return value is 6066 // wasteful. 6067 APValue RetVal; 6068 StmtResult Ret = {RetVal, nullptr}; 6069 6070 // If it's a delegating constructor, delegate. 6071 if (Definition->isDelegatingConstructor()) { 6072 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6073 { 6074 FullExpressionRAII InitScope(Info); 6075 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6076 !InitScope.destroy()) 6077 return false; 6078 } 6079 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6080 } 6081 6082 // For a trivial copy or move constructor, perform an APValue copy. This is 6083 // essential for unions (or classes with anonymous union members), where the 6084 // operations performed by the constructor cannot be represented by 6085 // ctor-initializers. 6086 // 6087 // Skip this for empty non-union classes; we should not perform an 6088 // lvalue-to-rvalue conversion on them because their copy constructor does not 6089 // actually read them. 6090 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6091 (Definition->getParent()->isUnion() || 6092 (Definition->isTrivial() && 6093 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6094 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6095 Definition->getParent()->isUnion()); 6096 } 6097 6098 // Reserve space for the struct members. 6099 if (!Result.hasValue()) { 6100 if (!RD->isUnion()) 6101 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6102 std::distance(RD->field_begin(), RD->field_end())); 6103 else 6104 // A union starts with no active member. 6105 Result = APValue((const FieldDecl*)nullptr); 6106 } 6107 6108 if (RD->isInvalidDecl()) return false; 6109 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6110 6111 // A scope for temporaries lifetime-extended by reference members. 6112 BlockScopeRAII LifetimeExtendedScope(Info); 6113 6114 bool Success = true; 6115 unsigned BasesSeen = 0; 6116 #ifndef NDEBUG 6117 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6118 #endif 6119 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6120 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6121 // We might be initializing the same field again if this is an indirect 6122 // field initialization. 6123 if (FieldIt == RD->field_end() || 6124 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6125 assert(Indirect && "fields out of order?"); 6126 return; 6127 } 6128 6129 // Default-initialize any fields with no explicit initializer. 6130 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6131 assert(FieldIt != RD->field_end() && "missing field?"); 6132 if (!FieldIt->isUnnamedBitfield()) 6133 Success &= getDefaultInitValue( 6134 FieldIt->getType(), 6135 Result.getStructField(FieldIt->getFieldIndex())); 6136 } 6137 ++FieldIt; 6138 }; 6139 for (const auto *I : Definition->inits()) { 6140 LValue Subobject = This; 6141 LValue SubobjectParent = This; 6142 APValue *Value = &Result; 6143 6144 // Determine the subobject to initialize. 6145 FieldDecl *FD = nullptr; 6146 if (I->isBaseInitializer()) { 6147 QualType BaseType(I->getBaseClass(), 0); 6148 #ifndef NDEBUG 6149 // Non-virtual base classes are initialized in the order in the class 6150 // definition. We have already checked for virtual base classes. 6151 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6152 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6153 "base class initializers not in expected order"); 6154 ++BaseIt; 6155 #endif 6156 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6157 BaseType->getAsCXXRecordDecl(), &Layout)) 6158 return false; 6159 Value = &Result.getStructBase(BasesSeen++); 6160 } else if ((FD = I->getMember())) { 6161 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6162 return false; 6163 if (RD->isUnion()) { 6164 Result = APValue(FD); 6165 Value = &Result.getUnionValue(); 6166 } else { 6167 SkipToField(FD, false); 6168 Value = &Result.getStructField(FD->getFieldIndex()); 6169 } 6170 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6171 // Walk the indirect field decl's chain to find the object to initialize, 6172 // and make sure we've initialized every step along it. 6173 auto IndirectFieldChain = IFD->chain(); 6174 for (auto *C : IndirectFieldChain) { 6175 FD = cast<FieldDecl>(C); 6176 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6177 // Switch the union field if it differs. This happens if we had 6178 // preceding zero-initialization, and we're now initializing a union 6179 // subobject other than the first. 6180 // FIXME: In this case, the values of the other subobjects are 6181 // specified, since zero-initialization sets all padding bits to zero. 6182 if (!Value->hasValue() || 6183 (Value->isUnion() && Value->getUnionField() != FD)) { 6184 if (CD->isUnion()) 6185 *Value = APValue(FD); 6186 else 6187 // FIXME: This immediately starts the lifetime of all members of 6188 // an anonymous struct. It would be preferable to strictly start 6189 // member lifetime in initialization order. 6190 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6191 } 6192 // Store Subobject as its parent before updating it for the last element 6193 // in the chain. 6194 if (C == IndirectFieldChain.back()) 6195 SubobjectParent = Subobject; 6196 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6197 return false; 6198 if (CD->isUnion()) 6199 Value = &Value->getUnionValue(); 6200 else { 6201 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6202 SkipToField(FD, true); 6203 Value = &Value->getStructField(FD->getFieldIndex()); 6204 } 6205 } 6206 } else { 6207 llvm_unreachable("unknown base initializer kind"); 6208 } 6209 6210 // Need to override This for implicit field initializers as in this case 6211 // This refers to innermost anonymous struct/union containing initializer, 6212 // not to currently constructed class. 6213 const Expr *Init = I->getInit(); 6214 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6215 isa<CXXDefaultInitExpr>(Init)); 6216 FullExpressionRAII InitScope(Info); 6217 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6218 (FD && FD->isBitField() && 6219 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6220 // If we're checking for a potential constant expression, evaluate all 6221 // initializers even if some of them fail. 6222 if (!Info.noteFailure()) 6223 return false; 6224 Success = false; 6225 } 6226 6227 // This is the point at which the dynamic type of the object becomes this 6228 // class type. 6229 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6230 EvalObj.finishedConstructingBases(); 6231 } 6232 6233 // Default-initialize any remaining fields. 6234 if (!RD->isUnion()) { 6235 for (; FieldIt != RD->field_end(); ++FieldIt) { 6236 if (!FieldIt->isUnnamedBitfield()) 6237 Success &= getDefaultInitValue( 6238 FieldIt->getType(), 6239 Result.getStructField(FieldIt->getFieldIndex())); 6240 } 6241 } 6242 6243 EvalObj.finishedConstructingFields(); 6244 6245 return Success && 6246 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6247 LifetimeExtendedScope.destroy(); 6248 } 6249 6250 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6251 ArrayRef<const Expr*> Args, 6252 const CXXConstructorDecl *Definition, 6253 EvalInfo &Info, APValue &Result) { 6254 CallScopeRAII CallScope(Info); 6255 CallRef Call = Info.CurrentCall->createCall(Definition); 6256 if (!EvaluateArgs(Args, Call, Info, Definition)) 6257 return false; 6258 6259 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6260 CallScope.destroy(); 6261 } 6262 6263 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6264 const LValue &This, APValue &Value, 6265 QualType T) { 6266 // Objects can only be destroyed while they're within their lifetimes. 6267 // FIXME: We have no representation for whether an object of type nullptr_t 6268 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6269 // as indeterminate instead? 6270 if (Value.isAbsent() && !T->isNullPtrType()) { 6271 APValue Printable; 6272 This.moveInto(Printable); 6273 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6274 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6275 return false; 6276 } 6277 6278 // Invent an expression for location purposes. 6279 // FIXME: We shouldn't need to do this. 6280 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6281 6282 // For arrays, destroy elements right-to-left. 6283 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6284 uint64_t Size = CAT->getSize().getZExtValue(); 6285 QualType ElemT = CAT->getElementType(); 6286 6287 LValue ElemLV = This; 6288 ElemLV.addArray(Info, &LocE, CAT); 6289 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6290 return false; 6291 6292 // Ensure that we have actual array elements available to destroy; the 6293 // destructors might mutate the value, so we can't run them on the array 6294 // filler. 6295 if (Size && Size > Value.getArrayInitializedElts()) 6296 expandArray(Value, Value.getArraySize() - 1); 6297 6298 for (; Size != 0; --Size) { 6299 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6300 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6301 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6302 return false; 6303 } 6304 6305 // End the lifetime of this array now. 6306 Value = APValue(); 6307 return true; 6308 } 6309 6310 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6311 if (!RD) { 6312 if (T.isDestructedType()) { 6313 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6314 return false; 6315 } 6316 6317 Value = APValue(); 6318 return true; 6319 } 6320 6321 if (RD->getNumVBases()) { 6322 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6323 return false; 6324 } 6325 6326 const CXXDestructorDecl *DD = RD->getDestructor(); 6327 if (!DD && !RD->hasTrivialDestructor()) { 6328 Info.FFDiag(CallLoc); 6329 return false; 6330 } 6331 6332 if (!DD || DD->isTrivial() || 6333 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6334 // A trivial destructor just ends the lifetime of the object. Check for 6335 // this case before checking for a body, because we might not bother 6336 // building a body for a trivial destructor. Note that it doesn't matter 6337 // whether the destructor is constexpr in this case; all trivial 6338 // destructors are constexpr. 6339 // 6340 // If an anonymous union would be destroyed, some enclosing destructor must 6341 // have been explicitly defined, and the anonymous union destruction should 6342 // have no effect. 6343 Value = APValue(); 6344 return true; 6345 } 6346 6347 if (!Info.CheckCallLimit(CallLoc)) 6348 return false; 6349 6350 const FunctionDecl *Definition = nullptr; 6351 const Stmt *Body = DD->getBody(Definition); 6352 6353 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6354 return false; 6355 6356 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6357 6358 // We're now in the period of destruction of this object. 6359 unsigned BasesLeft = RD->getNumBases(); 6360 EvalInfo::EvaluatingDestructorRAII EvalObj( 6361 Info, 6362 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6363 if (!EvalObj.DidInsert) { 6364 // C++2a [class.dtor]p19: 6365 // the behavior is undefined if the destructor is invoked for an object 6366 // whose lifetime has ended 6367 // (Note that formally the lifetime ends when the period of destruction 6368 // begins, even though certain uses of the object remain valid until the 6369 // period of destruction ends.) 6370 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6371 return false; 6372 } 6373 6374 // FIXME: Creating an APValue just to hold a nonexistent return value is 6375 // wasteful. 6376 APValue RetVal; 6377 StmtResult Ret = {RetVal, nullptr}; 6378 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6379 return false; 6380 6381 // A union destructor does not implicitly destroy its members. 6382 if (RD->isUnion()) 6383 return true; 6384 6385 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6386 6387 // We don't have a good way to iterate fields in reverse, so collect all the 6388 // fields first and then walk them backwards. 6389 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6390 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6391 if (FD->isUnnamedBitfield()) 6392 continue; 6393 6394 LValue Subobject = This; 6395 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6396 return false; 6397 6398 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6399 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6400 FD->getType())) 6401 return false; 6402 } 6403 6404 if (BasesLeft != 0) 6405 EvalObj.startedDestroyingBases(); 6406 6407 // Destroy base classes in reverse order. 6408 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6409 --BasesLeft; 6410 6411 QualType BaseType = Base.getType(); 6412 LValue Subobject = This; 6413 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6414 BaseType->getAsCXXRecordDecl(), &Layout)) 6415 return false; 6416 6417 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6418 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6419 BaseType)) 6420 return false; 6421 } 6422 assert(BasesLeft == 0 && "NumBases was wrong?"); 6423 6424 // The period of destruction ends now. The object is gone. 6425 Value = APValue(); 6426 return true; 6427 } 6428 6429 namespace { 6430 struct DestroyObjectHandler { 6431 EvalInfo &Info; 6432 const Expr *E; 6433 const LValue &This; 6434 const AccessKinds AccessKind; 6435 6436 typedef bool result_type; 6437 bool failed() { return false; } 6438 bool found(APValue &Subobj, QualType SubobjType) { 6439 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6440 SubobjType); 6441 } 6442 bool found(APSInt &Value, QualType SubobjType) { 6443 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6444 return false; 6445 } 6446 bool found(APFloat &Value, QualType SubobjType) { 6447 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6448 return false; 6449 } 6450 }; 6451 } 6452 6453 /// Perform a destructor or pseudo-destructor call on the given object, which 6454 /// might in general not be a complete object. 6455 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6456 const LValue &This, QualType ThisType) { 6457 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6458 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6459 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6460 } 6461 6462 /// Destroy and end the lifetime of the given complete object. 6463 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6464 APValue::LValueBase LVBase, APValue &Value, 6465 QualType T) { 6466 // If we've had an unmodeled side-effect, we can't rely on mutable state 6467 // (such as the object we're about to destroy) being correct. 6468 if (Info.EvalStatus.HasSideEffects) 6469 return false; 6470 6471 LValue LV; 6472 LV.set({LVBase}); 6473 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6474 } 6475 6476 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6477 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6478 LValue &Result) { 6479 if (Info.checkingPotentialConstantExpression() || 6480 Info.SpeculativeEvaluationDepth) 6481 return false; 6482 6483 // This is permitted only within a call to std::allocator<T>::allocate. 6484 auto Caller = Info.getStdAllocatorCaller("allocate"); 6485 if (!Caller) { 6486 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6487 ? diag::note_constexpr_new_untyped 6488 : diag::note_constexpr_new); 6489 return false; 6490 } 6491 6492 QualType ElemType = Caller.ElemType; 6493 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6494 Info.FFDiag(E->getExprLoc(), 6495 diag::note_constexpr_new_not_complete_object_type) 6496 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6497 return false; 6498 } 6499 6500 APSInt ByteSize; 6501 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6502 return false; 6503 bool IsNothrow = false; 6504 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6505 EvaluateIgnoredValue(Info, E->getArg(I)); 6506 IsNothrow |= E->getType()->isNothrowT(); 6507 } 6508 6509 CharUnits ElemSize; 6510 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6511 return false; 6512 APInt Size, Remainder; 6513 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6514 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6515 if (Remainder != 0) { 6516 // This likely indicates a bug in the implementation of 'std::allocator'. 6517 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6518 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6519 return false; 6520 } 6521 6522 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6523 if (IsNothrow) { 6524 Result.setNull(Info.Ctx, E->getType()); 6525 return true; 6526 } 6527 6528 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6529 return false; 6530 } 6531 6532 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6533 ArrayType::Normal, 0); 6534 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6535 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6536 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6537 return true; 6538 } 6539 6540 static bool hasVirtualDestructor(QualType T) { 6541 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6542 if (CXXDestructorDecl *DD = RD->getDestructor()) 6543 return DD->isVirtual(); 6544 return false; 6545 } 6546 6547 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6548 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6549 if (CXXDestructorDecl *DD = RD->getDestructor()) 6550 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6551 return nullptr; 6552 } 6553 6554 /// Check that the given object is a suitable pointer to a heap allocation that 6555 /// still exists and is of the right kind for the purpose of a deletion. 6556 /// 6557 /// On success, returns the heap allocation to deallocate. On failure, produces 6558 /// a diagnostic and returns None. 6559 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6560 const LValue &Pointer, 6561 DynAlloc::Kind DeallocKind) { 6562 auto PointerAsString = [&] { 6563 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6564 }; 6565 6566 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6567 if (!DA) { 6568 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6569 << PointerAsString(); 6570 if (Pointer.Base) 6571 NoteLValueLocation(Info, Pointer.Base); 6572 return None; 6573 } 6574 6575 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6576 if (!Alloc) { 6577 Info.FFDiag(E, diag::note_constexpr_double_delete); 6578 return None; 6579 } 6580 6581 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6582 if (DeallocKind != (*Alloc)->getKind()) { 6583 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6584 << DeallocKind << (*Alloc)->getKind() << AllocType; 6585 NoteLValueLocation(Info, Pointer.Base); 6586 return None; 6587 } 6588 6589 bool Subobject = false; 6590 if (DeallocKind == DynAlloc::New) { 6591 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6592 Pointer.Designator.isOnePastTheEnd(); 6593 } else { 6594 Subobject = Pointer.Designator.Entries.size() != 1 || 6595 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6596 } 6597 if (Subobject) { 6598 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6599 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6600 return None; 6601 } 6602 6603 return Alloc; 6604 } 6605 6606 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6607 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6608 if (Info.checkingPotentialConstantExpression() || 6609 Info.SpeculativeEvaluationDepth) 6610 return false; 6611 6612 // This is permitted only within a call to std::allocator<T>::deallocate. 6613 if (!Info.getStdAllocatorCaller("deallocate")) { 6614 Info.FFDiag(E->getExprLoc()); 6615 return true; 6616 } 6617 6618 LValue Pointer; 6619 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6620 return false; 6621 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6622 EvaluateIgnoredValue(Info, E->getArg(I)); 6623 6624 if (Pointer.Designator.Invalid) 6625 return false; 6626 6627 // Deleting a null pointer has no effect. 6628 if (Pointer.isNullPointer()) 6629 return true; 6630 6631 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6632 return false; 6633 6634 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6635 return true; 6636 } 6637 6638 //===----------------------------------------------------------------------===// 6639 // Generic Evaluation 6640 //===----------------------------------------------------------------------===// 6641 namespace { 6642 6643 class BitCastBuffer { 6644 // FIXME: We're going to need bit-level granularity when we support 6645 // bit-fields. 6646 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6647 // we don't support a host or target where that is the case. Still, we should 6648 // use a more generic type in case we ever do. 6649 SmallVector<Optional<unsigned char>, 32> Bytes; 6650 6651 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6652 "Need at least 8 bit unsigned char"); 6653 6654 bool TargetIsLittleEndian; 6655 6656 public: 6657 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6658 : Bytes(Width.getQuantity()), 6659 TargetIsLittleEndian(TargetIsLittleEndian) {} 6660 6661 LLVM_NODISCARD 6662 bool readObject(CharUnits Offset, CharUnits Width, 6663 SmallVectorImpl<unsigned char> &Output) const { 6664 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6665 // If a byte of an integer is uninitialized, then the whole integer is 6666 // uninitalized. 6667 if (!Bytes[I.getQuantity()]) 6668 return false; 6669 Output.push_back(*Bytes[I.getQuantity()]); 6670 } 6671 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6672 std::reverse(Output.begin(), Output.end()); 6673 return true; 6674 } 6675 6676 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6677 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6678 std::reverse(Input.begin(), Input.end()); 6679 6680 size_t Index = 0; 6681 for (unsigned char Byte : Input) { 6682 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6683 Bytes[Offset.getQuantity() + Index] = Byte; 6684 ++Index; 6685 } 6686 } 6687 6688 size_t size() { return Bytes.size(); } 6689 }; 6690 6691 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6692 /// target would represent the value at runtime. 6693 class APValueToBufferConverter { 6694 EvalInfo &Info; 6695 BitCastBuffer Buffer; 6696 const CastExpr *BCE; 6697 6698 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6699 const CastExpr *BCE) 6700 : Info(Info), 6701 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6702 BCE(BCE) {} 6703 6704 bool visit(const APValue &Val, QualType Ty) { 6705 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6706 } 6707 6708 // Write out Val with type Ty into Buffer starting at Offset. 6709 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6710 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6711 6712 // As a special case, nullptr_t has an indeterminate value. 6713 if (Ty->isNullPtrType()) 6714 return true; 6715 6716 // Dig through Src to find the byte at SrcOffset. 6717 switch (Val.getKind()) { 6718 case APValue::Indeterminate: 6719 case APValue::None: 6720 return true; 6721 6722 case APValue::Int: 6723 return visitInt(Val.getInt(), Ty, Offset); 6724 case APValue::Float: 6725 return visitFloat(Val.getFloat(), Ty, Offset); 6726 case APValue::Array: 6727 return visitArray(Val, Ty, Offset); 6728 case APValue::Struct: 6729 return visitRecord(Val, Ty, Offset); 6730 6731 case APValue::ComplexInt: 6732 case APValue::ComplexFloat: 6733 case APValue::Vector: 6734 case APValue::FixedPoint: 6735 // FIXME: We should support these. 6736 6737 case APValue::Union: 6738 case APValue::MemberPointer: 6739 case APValue::AddrLabelDiff: { 6740 Info.FFDiag(BCE->getBeginLoc(), 6741 diag::note_constexpr_bit_cast_unsupported_type) 6742 << Ty; 6743 return false; 6744 } 6745 6746 case APValue::LValue: 6747 llvm_unreachable("LValue subobject in bit_cast?"); 6748 } 6749 llvm_unreachable("Unhandled APValue::ValueKind"); 6750 } 6751 6752 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6753 const RecordDecl *RD = Ty->getAsRecordDecl(); 6754 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6755 6756 // Visit the base classes. 6757 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6758 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6759 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6760 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6761 6762 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6763 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6764 return false; 6765 } 6766 } 6767 6768 // Visit the fields. 6769 unsigned FieldIdx = 0; 6770 for (FieldDecl *FD : RD->fields()) { 6771 if (FD->isBitField()) { 6772 Info.FFDiag(BCE->getBeginLoc(), 6773 diag::note_constexpr_bit_cast_unsupported_bitfield); 6774 return false; 6775 } 6776 6777 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6778 6779 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6780 "only bit-fields can have sub-char alignment"); 6781 CharUnits FieldOffset = 6782 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6783 QualType FieldTy = FD->getType(); 6784 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6785 return false; 6786 ++FieldIdx; 6787 } 6788 6789 return true; 6790 } 6791 6792 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6793 const auto *CAT = 6794 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6795 if (!CAT) 6796 return false; 6797 6798 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6799 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6800 unsigned ArraySize = Val.getArraySize(); 6801 // First, initialize the initialized elements. 6802 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6803 const APValue &SubObj = Val.getArrayInitializedElt(I); 6804 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6805 return false; 6806 } 6807 6808 // Next, initialize the rest of the array using the filler. 6809 if (Val.hasArrayFiller()) { 6810 const APValue &Filler = Val.getArrayFiller(); 6811 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6812 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6813 return false; 6814 } 6815 } 6816 6817 return true; 6818 } 6819 6820 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6821 APSInt AdjustedVal = Val; 6822 unsigned Width = AdjustedVal.getBitWidth(); 6823 if (Ty->isBooleanType()) { 6824 Width = Info.Ctx.getTypeSize(Ty); 6825 AdjustedVal = AdjustedVal.extend(Width); 6826 } 6827 6828 SmallVector<unsigned char, 8> Bytes(Width / 8); 6829 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6830 Buffer.writeObject(Offset, Bytes); 6831 return true; 6832 } 6833 6834 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6835 APSInt AsInt(Val.bitcastToAPInt()); 6836 return visitInt(AsInt, Ty, Offset); 6837 } 6838 6839 public: 6840 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6841 const CastExpr *BCE) { 6842 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6843 APValueToBufferConverter Converter(Info, DstSize, BCE); 6844 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6845 return None; 6846 return Converter.Buffer; 6847 } 6848 }; 6849 6850 /// Write an BitCastBuffer into an APValue. 6851 class BufferToAPValueConverter { 6852 EvalInfo &Info; 6853 const BitCastBuffer &Buffer; 6854 const CastExpr *BCE; 6855 6856 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6857 const CastExpr *BCE) 6858 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6859 6860 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6861 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6862 // Ideally this will be unreachable. 6863 llvm::NoneType unsupportedType(QualType Ty) { 6864 Info.FFDiag(BCE->getBeginLoc(), 6865 diag::note_constexpr_bit_cast_unsupported_type) 6866 << Ty; 6867 return None; 6868 } 6869 6870 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6871 Info.FFDiag(BCE->getBeginLoc(), 6872 diag::note_constexpr_bit_cast_unrepresentable_value) 6873 << Ty << Val.toString(/*Radix=*/10); 6874 return None; 6875 } 6876 6877 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6878 const EnumType *EnumSugar = nullptr) { 6879 if (T->isNullPtrType()) { 6880 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6881 return APValue((Expr *)nullptr, 6882 /*Offset=*/CharUnits::fromQuantity(NullValue), 6883 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6884 } 6885 6886 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6887 6888 // Work around floating point types that contain unused padding bytes. This 6889 // is really just `long double` on x86, which is the only fundamental type 6890 // with padding bytes. 6891 if (T->isRealFloatingType()) { 6892 const llvm::fltSemantics &Semantics = 6893 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6894 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6895 assert(NumBits % 8 == 0); 6896 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6897 if (NumBytes != SizeOf) 6898 SizeOf = NumBytes; 6899 } 6900 6901 SmallVector<uint8_t, 8> Bytes; 6902 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6903 // If this is std::byte or unsigned char, then its okay to store an 6904 // indeterminate value. 6905 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6906 bool IsUChar = 6907 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6908 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6909 if (!IsStdByte && !IsUChar) { 6910 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6911 Info.FFDiag(BCE->getExprLoc(), 6912 diag::note_constexpr_bit_cast_indet_dest) 6913 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6914 return None; 6915 } 6916 6917 return APValue::IndeterminateValue(); 6918 } 6919 6920 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6921 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6922 6923 if (T->isIntegralOrEnumerationType()) { 6924 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6925 6926 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 6927 if (IntWidth != Val.getBitWidth()) { 6928 APSInt Truncated = Val.trunc(IntWidth); 6929 if (Truncated.extend(Val.getBitWidth()) != Val) 6930 return unrepresentableValue(QualType(T, 0), Val); 6931 Val = Truncated; 6932 } 6933 6934 return APValue(Val); 6935 } 6936 6937 if (T->isRealFloatingType()) { 6938 const llvm::fltSemantics &Semantics = 6939 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6940 return APValue(APFloat(Semantics, Val)); 6941 } 6942 6943 return unsupportedType(QualType(T, 0)); 6944 } 6945 6946 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6947 const RecordDecl *RD = RTy->getAsRecordDecl(); 6948 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6949 6950 unsigned NumBases = 0; 6951 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6952 NumBases = CXXRD->getNumBases(); 6953 6954 APValue ResultVal(APValue::UninitStruct(), NumBases, 6955 std::distance(RD->field_begin(), RD->field_end())); 6956 6957 // Visit the base classes. 6958 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6959 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6960 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6961 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6962 if (BaseDecl->isEmpty() || 6963 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6964 continue; 6965 6966 Optional<APValue> SubObj = visitType( 6967 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6968 if (!SubObj) 6969 return None; 6970 ResultVal.getStructBase(I) = *SubObj; 6971 } 6972 } 6973 6974 // Visit the fields. 6975 unsigned FieldIdx = 0; 6976 for (FieldDecl *FD : RD->fields()) { 6977 // FIXME: We don't currently support bit-fields. A lot of the logic for 6978 // this is in CodeGen, so we need to factor it around. 6979 if (FD->isBitField()) { 6980 Info.FFDiag(BCE->getBeginLoc(), 6981 diag::note_constexpr_bit_cast_unsupported_bitfield); 6982 return None; 6983 } 6984 6985 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6986 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6987 6988 CharUnits FieldOffset = 6989 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6990 Offset; 6991 QualType FieldTy = FD->getType(); 6992 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6993 if (!SubObj) 6994 return None; 6995 ResultVal.getStructField(FieldIdx) = *SubObj; 6996 ++FieldIdx; 6997 } 6998 6999 return ResultVal; 7000 } 7001 7002 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7003 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7004 assert(!RepresentationType.isNull() && 7005 "enum forward decl should be caught by Sema"); 7006 const auto *AsBuiltin = 7007 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7008 // Recurse into the underlying type. Treat std::byte transparently as 7009 // unsigned char. 7010 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7011 } 7012 7013 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7014 size_t Size = Ty->getSize().getLimitedValue(); 7015 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7016 7017 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7018 for (size_t I = 0; I != Size; ++I) { 7019 Optional<APValue> ElementValue = 7020 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7021 if (!ElementValue) 7022 return None; 7023 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7024 } 7025 7026 return ArrayValue; 7027 } 7028 7029 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7030 return unsupportedType(QualType(Ty, 0)); 7031 } 7032 7033 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7034 QualType Can = Ty.getCanonicalType(); 7035 7036 switch (Can->getTypeClass()) { 7037 #define TYPE(Class, Base) \ 7038 case Type::Class: \ 7039 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7040 #define ABSTRACT_TYPE(Class, Base) 7041 #define NON_CANONICAL_TYPE(Class, Base) \ 7042 case Type::Class: \ 7043 llvm_unreachable("non-canonical type should be impossible!"); 7044 #define DEPENDENT_TYPE(Class, Base) \ 7045 case Type::Class: \ 7046 llvm_unreachable( \ 7047 "dependent types aren't supported in the constant evaluator!"); 7048 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7049 case Type::Class: \ 7050 llvm_unreachable("either dependent or not canonical!"); 7051 #include "clang/AST/TypeNodes.inc" 7052 } 7053 llvm_unreachable("Unhandled Type::TypeClass"); 7054 } 7055 7056 public: 7057 // Pull out a full value of type DstType. 7058 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7059 const CastExpr *BCE) { 7060 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7061 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7062 } 7063 }; 7064 7065 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7066 QualType Ty, EvalInfo *Info, 7067 const ASTContext &Ctx, 7068 bool CheckingDest) { 7069 Ty = Ty.getCanonicalType(); 7070 7071 auto diag = [&](int Reason) { 7072 if (Info) 7073 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7074 << CheckingDest << (Reason == 4) << Reason; 7075 return false; 7076 }; 7077 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7078 if (Info) 7079 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7080 << NoteTy << Construct << Ty; 7081 return false; 7082 }; 7083 7084 if (Ty->isUnionType()) 7085 return diag(0); 7086 if (Ty->isPointerType()) 7087 return diag(1); 7088 if (Ty->isMemberPointerType()) 7089 return diag(2); 7090 if (Ty.isVolatileQualified()) 7091 return diag(3); 7092 7093 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7094 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7095 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7096 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7097 CheckingDest)) 7098 return note(1, BS.getType(), BS.getBeginLoc()); 7099 } 7100 for (FieldDecl *FD : Record->fields()) { 7101 if (FD->getType()->isReferenceType()) 7102 return diag(4); 7103 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7104 CheckingDest)) 7105 return note(0, FD->getType(), FD->getBeginLoc()); 7106 } 7107 } 7108 7109 if (Ty->isArrayType() && 7110 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7111 Info, Ctx, CheckingDest)) 7112 return false; 7113 7114 return true; 7115 } 7116 7117 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7118 const ASTContext &Ctx, 7119 const CastExpr *BCE) { 7120 bool DestOK = checkBitCastConstexprEligibilityType( 7121 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7122 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7123 BCE->getBeginLoc(), 7124 BCE->getSubExpr()->getType(), Info, Ctx, false); 7125 return SourceOK; 7126 } 7127 7128 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7129 APValue &SourceValue, 7130 const CastExpr *BCE) { 7131 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7132 "no host or target supports non 8-bit chars"); 7133 assert(SourceValue.isLValue() && 7134 "LValueToRValueBitcast requires an lvalue operand!"); 7135 7136 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7137 return false; 7138 7139 LValue SourceLValue; 7140 APValue SourceRValue; 7141 SourceLValue.setFrom(Info.Ctx, SourceValue); 7142 if (!handleLValueToRValueConversion( 7143 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7144 SourceRValue, /*WantObjectRepresentation=*/true)) 7145 return false; 7146 7147 // Read out SourceValue into a char buffer. 7148 Optional<BitCastBuffer> Buffer = 7149 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7150 if (!Buffer) 7151 return false; 7152 7153 // Write out the buffer into a new APValue. 7154 Optional<APValue> MaybeDestValue = 7155 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7156 if (!MaybeDestValue) 7157 return false; 7158 7159 DestValue = std::move(*MaybeDestValue); 7160 return true; 7161 } 7162 7163 template <class Derived> 7164 class ExprEvaluatorBase 7165 : public ConstStmtVisitor<Derived, bool> { 7166 private: 7167 Derived &getDerived() { return static_cast<Derived&>(*this); } 7168 bool DerivedSuccess(const APValue &V, const Expr *E) { 7169 return getDerived().Success(V, E); 7170 } 7171 bool DerivedZeroInitialization(const Expr *E) { 7172 return getDerived().ZeroInitialization(E); 7173 } 7174 7175 // Check whether a conditional operator with a non-constant condition is a 7176 // potential constant expression. If neither arm is a potential constant 7177 // expression, then the conditional operator is not either. 7178 template<typename ConditionalOperator> 7179 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7180 assert(Info.checkingPotentialConstantExpression()); 7181 7182 // Speculatively evaluate both arms. 7183 SmallVector<PartialDiagnosticAt, 8> Diag; 7184 { 7185 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7186 StmtVisitorTy::Visit(E->getFalseExpr()); 7187 if (Diag.empty()) 7188 return; 7189 } 7190 7191 { 7192 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7193 Diag.clear(); 7194 StmtVisitorTy::Visit(E->getTrueExpr()); 7195 if (Diag.empty()) 7196 return; 7197 } 7198 7199 Error(E, diag::note_constexpr_conditional_never_const); 7200 } 7201 7202 7203 template<typename ConditionalOperator> 7204 bool HandleConditionalOperator(const ConditionalOperator *E) { 7205 bool BoolResult; 7206 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7207 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7208 CheckPotentialConstantConditional(E); 7209 return false; 7210 } 7211 if (Info.noteFailure()) { 7212 StmtVisitorTy::Visit(E->getTrueExpr()); 7213 StmtVisitorTy::Visit(E->getFalseExpr()); 7214 } 7215 return false; 7216 } 7217 7218 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7219 return StmtVisitorTy::Visit(EvalExpr); 7220 } 7221 7222 protected: 7223 EvalInfo &Info; 7224 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7225 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7226 7227 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7228 return Info.CCEDiag(E, D); 7229 } 7230 7231 bool ZeroInitialization(const Expr *E) { return Error(E); } 7232 7233 public: 7234 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7235 7236 EvalInfo &getEvalInfo() { return Info; } 7237 7238 /// Report an evaluation error. This should only be called when an error is 7239 /// first discovered. When propagating an error, just return false. 7240 bool Error(const Expr *E, diag::kind D) { 7241 Info.FFDiag(E, D); 7242 return false; 7243 } 7244 bool Error(const Expr *E) { 7245 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7246 } 7247 7248 bool VisitStmt(const Stmt *) { 7249 llvm_unreachable("Expression evaluator should not be called on stmts"); 7250 } 7251 bool VisitExpr(const Expr *E) { 7252 return Error(E); 7253 } 7254 7255 bool VisitConstantExpr(const ConstantExpr *E) { 7256 if (E->hasAPValueResult()) 7257 return DerivedSuccess(E->getAPValueResult(), E); 7258 7259 return StmtVisitorTy::Visit(E->getSubExpr()); 7260 } 7261 7262 bool VisitParenExpr(const ParenExpr *E) 7263 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7264 bool VisitUnaryExtension(const UnaryOperator *E) 7265 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7266 bool VisitUnaryPlus(const UnaryOperator *E) 7267 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7268 bool VisitChooseExpr(const ChooseExpr *E) 7269 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7270 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7271 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7272 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7273 { return StmtVisitorTy::Visit(E->getReplacement()); } 7274 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7275 TempVersionRAII RAII(*Info.CurrentCall); 7276 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7277 return StmtVisitorTy::Visit(E->getExpr()); 7278 } 7279 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7280 TempVersionRAII RAII(*Info.CurrentCall); 7281 // The initializer may not have been parsed yet, or might be erroneous. 7282 if (!E->getExpr()) 7283 return Error(E); 7284 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7285 return StmtVisitorTy::Visit(E->getExpr()); 7286 } 7287 7288 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7289 FullExpressionRAII Scope(Info); 7290 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7291 } 7292 7293 // Temporaries are registered when created, so we don't care about 7294 // CXXBindTemporaryExpr. 7295 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7296 return StmtVisitorTy::Visit(E->getSubExpr()); 7297 } 7298 7299 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7300 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7301 return static_cast<Derived*>(this)->VisitCastExpr(E); 7302 } 7303 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7304 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7305 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7306 return static_cast<Derived*>(this)->VisitCastExpr(E); 7307 } 7308 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7309 return static_cast<Derived*>(this)->VisitCastExpr(E); 7310 } 7311 7312 bool VisitBinaryOperator(const BinaryOperator *E) { 7313 switch (E->getOpcode()) { 7314 default: 7315 return Error(E); 7316 7317 case BO_Comma: 7318 VisitIgnoredValue(E->getLHS()); 7319 return StmtVisitorTy::Visit(E->getRHS()); 7320 7321 case BO_PtrMemD: 7322 case BO_PtrMemI: { 7323 LValue Obj; 7324 if (!HandleMemberPointerAccess(Info, E, Obj)) 7325 return false; 7326 APValue Result; 7327 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7328 return false; 7329 return DerivedSuccess(Result, E); 7330 } 7331 } 7332 } 7333 7334 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7335 return StmtVisitorTy::Visit(E->getSemanticForm()); 7336 } 7337 7338 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7339 // Evaluate and cache the common expression. We treat it as a temporary, 7340 // even though it's not quite the same thing. 7341 LValue CommonLV; 7342 if (!Evaluate(Info.CurrentCall->createTemporary( 7343 E->getOpaqueValue(), 7344 getStorageType(Info.Ctx, E->getOpaqueValue()), 7345 ScopeKind::FullExpression, CommonLV), 7346 Info, E->getCommon())) 7347 return false; 7348 7349 return HandleConditionalOperator(E); 7350 } 7351 7352 bool VisitConditionalOperator(const ConditionalOperator *E) { 7353 bool IsBcpCall = false; 7354 // If the condition (ignoring parens) is a __builtin_constant_p call, 7355 // the result is a constant expression if it can be folded without 7356 // side-effects. This is an important GNU extension. See GCC PR38377 7357 // for discussion. 7358 if (const CallExpr *CallCE = 7359 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7360 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7361 IsBcpCall = true; 7362 7363 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7364 // constant expression; we can't check whether it's potentially foldable. 7365 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7366 // it would return 'false' in this mode. 7367 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7368 return false; 7369 7370 FoldConstant Fold(Info, IsBcpCall); 7371 if (!HandleConditionalOperator(E)) { 7372 Fold.keepDiagnostics(); 7373 return false; 7374 } 7375 7376 return true; 7377 } 7378 7379 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7380 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7381 return DerivedSuccess(*Value, E); 7382 7383 const Expr *Source = E->getSourceExpr(); 7384 if (!Source) 7385 return Error(E); 7386 if (Source == E) { // sanity checking. 7387 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7388 return Error(E); 7389 } 7390 return StmtVisitorTy::Visit(Source); 7391 } 7392 7393 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7394 for (const Expr *SemE : E->semantics()) { 7395 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7396 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7397 // result expression: there could be two different LValues that would 7398 // refer to the same object in that case, and we can't model that. 7399 if (SemE == E->getResultExpr()) 7400 return Error(E); 7401 7402 // Unique OVEs get evaluated if and when we encounter them when 7403 // emitting the rest of the semantic form, rather than eagerly. 7404 if (OVE->isUnique()) 7405 continue; 7406 7407 LValue LV; 7408 if (!Evaluate(Info.CurrentCall->createTemporary( 7409 OVE, getStorageType(Info.Ctx, OVE), 7410 ScopeKind::FullExpression, LV), 7411 Info, OVE->getSourceExpr())) 7412 return false; 7413 } else if (SemE == E->getResultExpr()) { 7414 if (!StmtVisitorTy::Visit(SemE)) 7415 return false; 7416 } else { 7417 if (!EvaluateIgnoredValue(Info, SemE)) 7418 return false; 7419 } 7420 } 7421 return true; 7422 } 7423 7424 bool VisitCallExpr(const CallExpr *E) { 7425 APValue Result; 7426 if (!handleCallExpr(E, Result, nullptr)) 7427 return false; 7428 return DerivedSuccess(Result, E); 7429 } 7430 7431 bool handleCallExpr(const CallExpr *E, APValue &Result, 7432 const LValue *ResultSlot) { 7433 CallScopeRAII CallScope(Info); 7434 7435 const Expr *Callee = E->getCallee()->IgnoreParens(); 7436 QualType CalleeType = Callee->getType(); 7437 7438 const FunctionDecl *FD = nullptr; 7439 LValue *This = nullptr, ThisVal; 7440 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7441 bool HasQualifier = false; 7442 7443 CallRef Call; 7444 7445 // Extract function decl and 'this' pointer from the callee. 7446 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7447 const CXXMethodDecl *Member = nullptr; 7448 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7449 // Explicit bound member calls, such as x.f() or p->g(); 7450 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7451 return false; 7452 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7453 if (!Member) 7454 return Error(Callee); 7455 This = &ThisVal; 7456 HasQualifier = ME->hasQualifier(); 7457 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7458 // Indirect bound member calls ('.*' or '->*'). 7459 const ValueDecl *D = 7460 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7461 if (!D) 7462 return false; 7463 Member = dyn_cast<CXXMethodDecl>(D); 7464 if (!Member) 7465 return Error(Callee); 7466 This = &ThisVal; 7467 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7468 if (!Info.getLangOpts().CPlusPlus20) 7469 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7470 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7471 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7472 } else 7473 return Error(Callee); 7474 FD = Member; 7475 } else if (CalleeType->isFunctionPointerType()) { 7476 LValue CalleeLV; 7477 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7478 return false; 7479 7480 if (!CalleeLV.getLValueOffset().isZero()) 7481 return Error(Callee); 7482 FD = dyn_cast_or_null<FunctionDecl>( 7483 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7484 if (!FD) 7485 return Error(Callee); 7486 // Don't call function pointers which have been cast to some other type. 7487 // Per DR (no number yet), the caller and callee can differ in noexcept. 7488 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7489 CalleeType->getPointeeType(), FD->getType())) { 7490 return Error(E); 7491 } 7492 7493 // For an (overloaded) assignment expression, evaluate the RHS before the 7494 // LHS. 7495 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7496 if (OCE && OCE->isAssignmentOp()) { 7497 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7498 Call = Info.CurrentCall->createCall(FD); 7499 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7500 Info, FD, /*RightToLeft=*/true)) 7501 return false; 7502 } 7503 7504 // Overloaded operator calls to member functions are represented as normal 7505 // calls with '*this' as the first argument. 7506 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7507 if (MD && !MD->isStatic()) { 7508 // FIXME: When selecting an implicit conversion for an overloaded 7509 // operator delete, we sometimes try to evaluate calls to conversion 7510 // operators without a 'this' parameter! 7511 if (Args.empty()) 7512 return Error(E); 7513 7514 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7515 return false; 7516 This = &ThisVal; 7517 Args = Args.slice(1); 7518 } else if (MD && MD->isLambdaStaticInvoker()) { 7519 // Map the static invoker for the lambda back to the call operator. 7520 // Conveniently, we don't have to slice out the 'this' argument (as is 7521 // being done for the non-static case), since a static member function 7522 // doesn't have an implicit argument passed in. 7523 const CXXRecordDecl *ClosureClass = MD->getParent(); 7524 assert( 7525 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7526 "Number of captures must be zero for conversion to function-ptr"); 7527 7528 const CXXMethodDecl *LambdaCallOp = 7529 ClosureClass->getLambdaCallOperator(); 7530 7531 // Set 'FD', the function that will be called below, to the call 7532 // operator. If the closure object represents a generic lambda, find 7533 // the corresponding specialization of the call operator. 7534 7535 if (ClosureClass->isGenericLambda()) { 7536 assert(MD->isFunctionTemplateSpecialization() && 7537 "A generic lambda's static-invoker function must be a " 7538 "template specialization"); 7539 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7540 FunctionTemplateDecl *CallOpTemplate = 7541 LambdaCallOp->getDescribedFunctionTemplate(); 7542 void *InsertPos = nullptr; 7543 FunctionDecl *CorrespondingCallOpSpecialization = 7544 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7545 assert(CorrespondingCallOpSpecialization && 7546 "We must always have a function call operator specialization " 7547 "that corresponds to our static invoker specialization"); 7548 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7549 } else 7550 FD = LambdaCallOp; 7551 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7552 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7553 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7554 LValue Ptr; 7555 if (!HandleOperatorNewCall(Info, E, Ptr)) 7556 return false; 7557 Ptr.moveInto(Result); 7558 return CallScope.destroy(); 7559 } else { 7560 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7561 } 7562 } 7563 } else 7564 return Error(E); 7565 7566 // Evaluate the arguments now if we've not already done so. 7567 if (!Call) { 7568 Call = Info.CurrentCall->createCall(FD); 7569 if (!EvaluateArgs(Args, Call, Info, FD)) 7570 return false; 7571 } 7572 7573 SmallVector<QualType, 4> CovariantAdjustmentPath; 7574 if (This) { 7575 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7576 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7577 // Perform virtual dispatch, if necessary. 7578 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7579 CovariantAdjustmentPath); 7580 if (!FD) 7581 return false; 7582 } else { 7583 // Check that the 'this' pointer points to an object of the right type. 7584 // FIXME: If this is an assignment operator call, we may need to change 7585 // the active union member before we check this. 7586 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7587 return false; 7588 } 7589 } 7590 7591 // Destructor calls are different enough that they have their own codepath. 7592 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7593 assert(This && "no 'this' pointer for destructor call"); 7594 return HandleDestruction(Info, E, *This, 7595 Info.Ctx.getRecordType(DD->getParent())) && 7596 CallScope.destroy(); 7597 } 7598 7599 const FunctionDecl *Definition = nullptr; 7600 Stmt *Body = FD->getBody(Definition); 7601 7602 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7603 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7604 Body, Info, Result, ResultSlot)) 7605 return false; 7606 7607 if (!CovariantAdjustmentPath.empty() && 7608 !HandleCovariantReturnAdjustment(Info, E, Result, 7609 CovariantAdjustmentPath)) 7610 return false; 7611 7612 return CallScope.destroy(); 7613 } 7614 7615 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7616 return StmtVisitorTy::Visit(E->getInitializer()); 7617 } 7618 bool VisitInitListExpr(const InitListExpr *E) { 7619 if (E->getNumInits() == 0) 7620 return DerivedZeroInitialization(E); 7621 if (E->getNumInits() == 1) 7622 return StmtVisitorTy::Visit(E->getInit(0)); 7623 return Error(E); 7624 } 7625 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7626 return DerivedZeroInitialization(E); 7627 } 7628 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7629 return DerivedZeroInitialization(E); 7630 } 7631 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7632 return DerivedZeroInitialization(E); 7633 } 7634 7635 /// A member expression where the object is a prvalue is itself a prvalue. 7636 bool VisitMemberExpr(const MemberExpr *E) { 7637 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7638 "missing temporary materialization conversion"); 7639 assert(!E->isArrow() && "missing call to bound member function?"); 7640 7641 APValue Val; 7642 if (!Evaluate(Val, Info, E->getBase())) 7643 return false; 7644 7645 QualType BaseTy = E->getBase()->getType(); 7646 7647 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7648 if (!FD) return Error(E); 7649 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7650 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7651 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7652 7653 // Note: there is no lvalue base here. But this case should only ever 7654 // happen in C or in C++98, where we cannot be evaluating a constexpr 7655 // constructor, which is the only case the base matters. 7656 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7657 SubobjectDesignator Designator(BaseTy); 7658 Designator.addDeclUnchecked(FD); 7659 7660 APValue Result; 7661 return extractSubobject(Info, E, Obj, Designator, Result) && 7662 DerivedSuccess(Result, E); 7663 } 7664 7665 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7666 APValue Val; 7667 if (!Evaluate(Val, Info, E->getBase())) 7668 return false; 7669 7670 if (Val.isVector()) { 7671 SmallVector<uint32_t, 4> Indices; 7672 E->getEncodedElementAccess(Indices); 7673 if (Indices.size() == 1) { 7674 // Return scalar. 7675 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7676 } else { 7677 // Construct new APValue vector. 7678 SmallVector<APValue, 4> Elts; 7679 for (unsigned I = 0; I < Indices.size(); ++I) { 7680 Elts.push_back(Val.getVectorElt(Indices[I])); 7681 } 7682 APValue VecResult(Elts.data(), Indices.size()); 7683 return DerivedSuccess(VecResult, E); 7684 } 7685 } 7686 7687 return false; 7688 } 7689 7690 bool VisitCastExpr(const CastExpr *E) { 7691 switch (E->getCastKind()) { 7692 default: 7693 break; 7694 7695 case CK_AtomicToNonAtomic: { 7696 APValue AtomicVal; 7697 // This does not need to be done in place even for class/array types: 7698 // atomic-to-non-atomic conversion implies copying the object 7699 // representation. 7700 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7701 return false; 7702 return DerivedSuccess(AtomicVal, E); 7703 } 7704 7705 case CK_NoOp: 7706 case CK_UserDefinedConversion: 7707 return StmtVisitorTy::Visit(E->getSubExpr()); 7708 7709 case CK_LValueToRValue: { 7710 LValue LVal; 7711 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7712 return false; 7713 APValue RVal; 7714 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7715 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7716 LVal, RVal)) 7717 return false; 7718 return DerivedSuccess(RVal, E); 7719 } 7720 case CK_LValueToRValueBitCast: { 7721 APValue DestValue, SourceValue; 7722 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7723 return false; 7724 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7725 return false; 7726 return DerivedSuccess(DestValue, E); 7727 } 7728 7729 case CK_AddressSpaceConversion: { 7730 APValue Value; 7731 if (!Evaluate(Value, Info, E->getSubExpr())) 7732 return false; 7733 return DerivedSuccess(Value, E); 7734 } 7735 } 7736 7737 return Error(E); 7738 } 7739 7740 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7741 return VisitUnaryPostIncDec(UO); 7742 } 7743 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7744 return VisitUnaryPostIncDec(UO); 7745 } 7746 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7747 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7748 return Error(UO); 7749 7750 LValue LVal; 7751 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7752 return false; 7753 APValue RVal; 7754 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7755 UO->isIncrementOp(), &RVal)) 7756 return false; 7757 return DerivedSuccess(RVal, UO); 7758 } 7759 7760 bool VisitStmtExpr(const StmtExpr *E) { 7761 // We will have checked the full-expressions inside the statement expression 7762 // when they were completed, and don't need to check them again now. 7763 if (Info.checkingForUndefinedBehavior()) 7764 return Error(E); 7765 7766 const CompoundStmt *CS = E->getSubStmt(); 7767 if (CS->body_empty()) 7768 return true; 7769 7770 BlockScopeRAII Scope(Info); 7771 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7772 BE = CS->body_end(); 7773 /**/; ++BI) { 7774 if (BI + 1 == BE) { 7775 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7776 if (!FinalExpr) { 7777 Info.FFDiag((*BI)->getBeginLoc(), 7778 diag::note_constexpr_stmt_expr_unsupported); 7779 return false; 7780 } 7781 return this->Visit(FinalExpr) && Scope.destroy(); 7782 } 7783 7784 APValue ReturnValue; 7785 StmtResult Result = { ReturnValue, nullptr }; 7786 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7787 if (ESR != ESR_Succeeded) { 7788 // FIXME: If the statement-expression terminated due to 'return', 7789 // 'break', or 'continue', it would be nice to propagate that to 7790 // the outer statement evaluation rather than bailing out. 7791 if (ESR != ESR_Failed) 7792 Info.FFDiag((*BI)->getBeginLoc(), 7793 diag::note_constexpr_stmt_expr_unsupported); 7794 return false; 7795 } 7796 } 7797 7798 llvm_unreachable("Return from function from the loop above."); 7799 } 7800 7801 /// Visit a value which is evaluated, but whose value is ignored. 7802 void VisitIgnoredValue(const Expr *E) { 7803 EvaluateIgnoredValue(Info, E); 7804 } 7805 7806 /// Potentially visit a MemberExpr's base expression. 7807 void VisitIgnoredBaseExpression(const Expr *E) { 7808 // While MSVC doesn't evaluate the base expression, it does diagnose the 7809 // presence of side-effecting behavior. 7810 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7811 return; 7812 VisitIgnoredValue(E); 7813 } 7814 }; 7815 7816 } // namespace 7817 7818 //===----------------------------------------------------------------------===// 7819 // Common base class for lvalue and temporary evaluation. 7820 //===----------------------------------------------------------------------===// 7821 namespace { 7822 template<class Derived> 7823 class LValueExprEvaluatorBase 7824 : public ExprEvaluatorBase<Derived> { 7825 protected: 7826 LValue &Result; 7827 bool InvalidBaseOK; 7828 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7829 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7830 7831 bool Success(APValue::LValueBase B) { 7832 Result.set(B); 7833 return true; 7834 } 7835 7836 bool evaluatePointer(const Expr *E, LValue &Result) { 7837 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7838 } 7839 7840 public: 7841 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7842 : ExprEvaluatorBaseTy(Info), Result(Result), 7843 InvalidBaseOK(InvalidBaseOK) {} 7844 7845 bool Success(const APValue &V, const Expr *E) { 7846 Result.setFrom(this->Info.Ctx, V); 7847 return true; 7848 } 7849 7850 bool VisitMemberExpr(const MemberExpr *E) { 7851 // Handle non-static data members. 7852 QualType BaseTy; 7853 bool EvalOK; 7854 if (E->isArrow()) { 7855 EvalOK = evaluatePointer(E->getBase(), Result); 7856 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7857 } else if (E->getBase()->isRValue()) { 7858 assert(E->getBase()->getType()->isRecordType()); 7859 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7860 BaseTy = E->getBase()->getType(); 7861 } else { 7862 EvalOK = this->Visit(E->getBase()); 7863 BaseTy = E->getBase()->getType(); 7864 } 7865 if (!EvalOK) { 7866 if (!InvalidBaseOK) 7867 return false; 7868 Result.setInvalid(E); 7869 return true; 7870 } 7871 7872 const ValueDecl *MD = E->getMemberDecl(); 7873 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7874 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7875 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7876 (void)BaseTy; 7877 if (!HandleLValueMember(this->Info, E, Result, FD)) 7878 return false; 7879 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7880 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7881 return false; 7882 } else 7883 return this->Error(E); 7884 7885 if (MD->getType()->isReferenceType()) { 7886 APValue RefValue; 7887 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7888 RefValue)) 7889 return false; 7890 return Success(RefValue, E); 7891 } 7892 return true; 7893 } 7894 7895 bool VisitBinaryOperator(const BinaryOperator *E) { 7896 switch (E->getOpcode()) { 7897 default: 7898 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7899 7900 case BO_PtrMemD: 7901 case BO_PtrMemI: 7902 return HandleMemberPointerAccess(this->Info, E, Result); 7903 } 7904 } 7905 7906 bool VisitCastExpr(const CastExpr *E) { 7907 switch (E->getCastKind()) { 7908 default: 7909 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7910 7911 case CK_DerivedToBase: 7912 case CK_UncheckedDerivedToBase: 7913 if (!this->Visit(E->getSubExpr())) 7914 return false; 7915 7916 // Now figure out the necessary offset to add to the base LV to get from 7917 // the derived class to the base class. 7918 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7919 Result); 7920 } 7921 } 7922 }; 7923 } 7924 7925 //===----------------------------------------------------------------------===// 7926 // LValue Evaluation 7927 // 7928 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7929 // function designators (in C), decl references to void objects (in C), and 7930 // temporaries (if building with -Wno-address-of-temporary). 7931 // 7932 // LValue evaluation produces values comprising a base expression of one of the 7933 // following types: 7934 // - Declarations 7935 // * VarDecl 7936 // * FunctionDecl 7937 // - Literals 7938 // * CompoundLiteralExpr in C (and in global scope in C++) 7939 // * StringLiteral 7940 // * PredefinedExpr 7941 // * ObjCStringLiteralExpr 7942 // * ObjCEncodeExpr 7943 // * AddrLabelExpr 7944 // * BlockExpr 7945 // * CallExpr for a MakeStringConstant builtin 7946 // - typeid(T) expressions, as TypeInfoLValues 7947 // - Locals and temporaries 7948 // * MaterializeTemporaryExpr 7949 // * Any Expr, with a CallIndex indicating the function in which the temporary 7950 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7951 // from the AST (FIXME). 7952 // * A MaterializeTemporaryExpr that has static storage duration, with no 7953 // CallIndex, for a lifetime-extended temporary. 7954 // * The ConstantExpr that is currently being evaluated during evaluation of an 7955 // immediate invocation. 7956 // plus an offset in bytes. 7957 //===----------------------------------------------------------------------===// 7958 namespace { 7959 class LValueExprEvaluator 7960 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7961 public: 7962 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7963 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7964 7965 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7966 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7967 7968 bool VisitDeclRefExpr(const DeclRefExpr *E); 7969 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7970 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7971 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7972 bool VisitMemberExpr(const MemberExpr *E); 7973 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7974 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7975 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7976 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7977 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7978 bool VisitUnaryDeref(const UnaryOperator *E); 7979 bool VisitUnaryReal(const UnaryOperator *E); 7980 bool VisitUnaryImag(const UnaryOperator *E); 7981 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7982 return VisitUnaryPreIncDec(UO); 7983 } 7984 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7985 return VisitUnaryPreIncDec(UO); 7986 } 7987 bool VisitBinAssign(const BinaryOperator *BO); 7988 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7989 7990 bool VisitCastExpr(const CastExpr *E) { 7991 switch (E->getCastKind()) { 7992 default: 7993 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7994 7995 case CK_LValueBitCast: 7996 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7997 if (!Visit(E->getSubExpr())) 7998 return false; 7999 Result.Designator.setInvalid(); 8000 return true; 8001 8002 case CK_BaseToDerived: 8003 if (!Visit(E->getSubExpr())) 8004 return false; 8005 return HandleBaseToDerivedCast(Info, E, Result); 8006 8007 case CK_Dynamic: 8008 if (!Visit(E->getSubExpr())) 8009 return false; 8010 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8011 } 8012 } 8013 }; 8014 } // end anonymous namespace 8015 8016 /// Evaluate an expression as an lvalue. This can be legitimately called on 8017 /// expressions which are not glvalues, in three cases: 8018 /// * function designators in C, and 8019 /// * "extern void" objects 8020 /// * @selector() expressions in Objective-C 8021 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8022 bool InvalidBaseOK) { 8023 assert(E->isGLValue() || E->getType()->isFunctionType() || 8024 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8025 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8026 } 8027 8028 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8029 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 8030 return Success(FD); 8031 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 8032 return VisitVarDecl(E, VD); 8033 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 8034 return Visit(BD->getBinding()); 8035 if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl())) 8036 return Success(GD); 8037 return Error(E); 8038 } 8039 8040 8041 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8042 8043 // If we are within a lambda's call operator, check whether the 'VD' referred 8044 // to within 'E' actually represents a lambda-capture that maps to a 8045 // data-member/field within the closure object, and if so, evaluate to the 8046 // field or what the field refers to. 8047 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8048 isa<DeclRefExpr>(E) && 8049 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8050 // We don't always have a complete capture-map when checking or inferring if 8051 // the function call operator meets the requirements of a constexpr function 8052 // - but we don't need to evaluate the captures to determine constexprness 8053 // (dcl.constexpr C++17). 8054 if (Info.checkingPotentialConstantExpression()) 8055 return false; 8056 8057 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8058 // Start with 'Result' referring to the complete closure object... 8059 Result = *Info.CurrentCall->This; 8060 // ... then update it to refer to the field of the closure object 8061 // that represents the capture. 8062 if (!HandleLValueMember(Info, E, Result, FD)) 8063 return false; 8064 // And if the field is of reference type, update 'Result' to refer to what 8065 // the field refers to. 8066 if (FD->getType()->isReferenceType()) { 8067 APValue RVal; 8068 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8069 RVal)) 8070 return false; 8071 Result.setFrom(Info.Ctx, RVal); 8072 } 8073 return true; 8074 } 8075 } 8076 8077 CallStackFrame *Frame = nullptr; 8078 unsigned Version = 0; 8079 if (VD->hasLocalStorage()) { 8080 // Only if a local variable was declared in the function currently being 8081 // evaluated, do we expect to be able to find its value in the current 8082 // frame. (Otherwise it was likely declared in an enclosing context and 8083 // could either have a valid evaluatable value (for e.g. a constexpr 8084 // variable) or be ill-formed (and trigger an appropriate evaluation 8085 // diagnostic)). 8086 CallStackFrame *CurrFrame = Info.CurrentCall; 8087 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8088 // Function parameters are stored in some caller's frame. (Usually the 8089 // immediate caller, but for an inherited constructor they may be more 8090 // distant.) 8091 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8092 if (CurrFrame->Arguments) { 8093 VD = CurrFrame->Arguments.getOrigParam(PVD); 8094 Frame = 8095 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8096 Version = CurrFrame->Arguments.Version; 8097 } 8098 } else { 8099 Frame = CurrFrame; 8100 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8101 } 8102 } 8103 } 8104 8105 if (!VD->getType()->isReferenceType()) { 8106 if (Frame) { 8107 Result.set({VD, Frame->Index, Version}); 8108 return true; 8109 } 8110 return Success(VD); 8111 } 8112 8113 if (!Info.getLangOpts().CPlusPlus11) { 8114 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8115 << VD << VD->getType(); 8116 Info.Note(VD->getLocation(), diag::note_declared_at); 8117 } 8118 8119 APValue *V; 8120 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8121 return false; 8122 if (!V->hasValue()) { 8123 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8124 // adjust the diagnostic to say that. 8125 if (!Info.checkingPotentialConstantExpression()) 8126 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8127 return false; 8128 } 8129 return Success(*V, E); 8130 } 8131 8132 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8133 const MaterializeTemporaryExpr *E) { 8134 // Walk through the expression to find the materialized temporary itself. 8135 SmallVector<const Expr *, 2> CommaLHSs; 8136 SmallVector<SubobjectAdjustment, 2> Adjustments; 8137 const Expr *Inner = 8138 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8139 8140 // If we passed any comma operators, evaluate their LHSs. 8141 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8142 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8143 return false; 8144 8145 // A materialized temporary with static storage duration can appear within the 8146 // result of a constant expression evaluation, so we need to preserve its 8147 // value for use outside this evaluation. 8148 APValue *Value; 8149 if (E->getStorageDuration() == SD_Static) { 8150 // FIXME: What about SD_Thread? 8151 Value = E->getOrCreateValue(true); 8152 *Value = APValue(); 8153 Result.set(E); 8154 } else { 8155 Value = &Info.CurrentCall->createTemporary( 8156 E, E->getType(), 8157 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8158 : ScopeKind::Block, 8159 Result); 8160 } 8161 8162 QualType Type = Inner->getType(); 8163 8164 // Materialize the temporary itself. 8165 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8166 *Value = APValue(); 8167 return false; 8168 } 8169 8170 // Adjust our lvalue to refer to the desired subobject. 8171 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8172 --I; 8173 switch (Adjustments[I].Kind) { 8174 case SubobjectAdjustment::DerivedToBaseAdjustment: 8175 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8176 Type, Result)) 8177 return false; 8178 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8179 break; 8180 8181 case SubobjectAdjustment::FieldAdjustment: 8182 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8183 return false; 8184 Type = Adjustments[I].Field->getType(); 8185 break; 8186 8187 case SubobjectAdjustment::MemberPointerAdjustment: 8188 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8189 Adjustments[I].Ptr.RHS)) 8190 return false; 8191 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8192 break; 8193 } 8194 } 8195 8196 return true; 8197 } 8198 8199 bool 8200 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8201 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8202 "lvalue compound literal in c++?"); 8203 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8204 // only see this when folding in C, so there's no standard to follow here. 8205 return Success(E); 8206 } 8207 8208 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8209 TypeInfoLValue TypeInfo; 8210 8211 if (!E->isPotentiallyEvaluated()) { 8212 if (E->isTypeOperand()) 8213 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8214 else 8215 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8216 } else { 8217 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8218 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8219 << E->getExprOperand()->getType() 8220 << E->getExprOperand()->getSourceRange(); 8221 } 8222 8223 if (!Visit(E->getExprOperand())) 8224 return false; 8225 8226 Optional<DynamicType> DynType = 8227 ComputeDynamicType(Info, E, Result, AK_TypeId); 8228 if (!DynType) 8229 return false; 8230 8231 TypeInfo = 8232 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8233 } 8234 8235 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8236 } 8237 8238 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8239 return Success(E->getGuidDecl()); 8240 } 8241 8242 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8243 // Handle static data members. 8244 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8245 VisitIgnoredBaseExpression(E->getBase()); 8246 return VisitVarDecl(E, VD); 8247 } 8248 8249 // Handle static member functions. 8250 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8251 if (MD->isStatic()) { 8252 VisitIgnoredBaseExpression(E->getBase()); 8253 return Success(MD); 8254 } 8255 } 8256 8257 // Handle non-static data members. 8258 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8259 } 8260 8261 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8262 // FIXME: Deal with vectors as array subscript bases. 8263 if (E->getBase()->getType()->isVectorType()) 8264 return Error(E); 8265 8266 APSInt Index; 8267 bool Success = true; 8268 8269 // C++17's rules require us to evaluate the LHS first, regardless of which 8270 // side is the base. 8271 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8272 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8273 : !EvaluateInteger(SubExpr, Index, Info)) { 8274 if (!Info.noteFailure()) 8275 return false; 8276 Success = false; 8277 } 8278 } 8279 8280 return Success && 8281 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8282 } 8283 8284 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8285 return evaluatePointer(E->getSubExpr(), Result); 8286 } 8287 8288 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8289 if (!Visit(E->getSubExpr())) 8290 return false; 8291 // __real is a no-op on scalar lvalues. 8292 if (E->getSubExpr()->getType()->isAnyComplexType()) 8293 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8294 return true; 8295 } 8296 8297 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8298 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8299 "lvalue __imag__ on scalar?"); 8300 if (!Visit(E->getSubExpr())) 8301 return false; 8302 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8303 return true; 8304 } 8305 8306 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8307 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8308 return Error(UO); 8309 8310 if (!this->Visit(UO->getSubExpr())) 8311 return false; 8312 8313 return handleIncDec( 8314 this->Info, UO, Result, UO->getSubExpr()->getType(), 8315 UO->isIncrementOp(), nullptr); 8316 } 8317 8318 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8319 const CompoundAssignOperator *CAO) { 8320 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8321 return Error(CAO); 8322 8323 bool Success = true; 8324 8325 // C++17 onwards require that we evaluate the RHS first. 8326 APValue RHS; 8327 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8328 if (!Info.noteFailure()) 8329 return false; 8330 Success = false; 8331 } 8332 8333 // The overall lvalue result is the result of evaluating the LHS. 8334 if (!this->Visit(CAO->getLHS()) || !Success) 8335 return false; 8336 8337 return handleCompoundAssignment( 8338 this->Info, CAO, 8339 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8340 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8341 } 8342 8343 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8344 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8345 return Error(E); 8346 8347 bool Success = true; 8348 8349 // C++17 onwards require that we evaluate the RHS first. 8350 APValue NewVal; 8351 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8352 if (!Info.noteFailure()) 8353 return false; 8354 Success = false; 8355 } 8356 8357 if (!this->Visit(E->getLHS()) || !Success) 8358 return false; 8359 8360 if (Info.getLangOpts().CPlusPlus20 && 8361 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8362 return false; 8363 8364 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8365 NewVal); 8366 } 8367 8368 //===----------------------------------------------------------------------===// 8369 // Pointer Evaluation 8370 //===----------------------------------------------------------------------===// 8371 8372 /// Attempts to compute the number of bytes available at the pointer 8373 /// returned by a function with the alloc_size attribute. Returns true if we 8374 /// were successful. Places an unsigned number into `Result`. 8375 /// 8376 /// This expects the given CallExpr to be a call to a function with an 8377 /// alloc_size attribute. 8378 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8379 const CallExpr *Call, 8380 llvm::APInt &Result) { 8381 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8382 8383 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8384 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8385 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8386 if (Call->getNumArgs() <= SizeArgNo) 8387 return false; 8388 8389 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8390 Expr::EvalResult ExprResult; 8391 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8392 return false; 8393 Into = ExprResult.Val.getInt(); 8394 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8395 return false; 8396 Into = Into.zextOrSelf(BitsInSizeT); 8397 return true; 8398 }; 8399 8400 APSInt SizeOfElem; 8401 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8402 return false; 8403 8404 if (!AllocSize->getNumElemsParam().isValid()) { 8405 Result = std::move(SizeOfElem); 8406 return true; 8407 } 8408 8409 APSInt NumberOfElems; 8410 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8411 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8412 return false; 8413 8414 bool Overflow; 8415 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8416 if (Overflow) 8417 return false; 8418 8419 Result = std::move(BytesAvailable); 8420 return true; 8421 } 8422 8423 /// Convenience function. LVal's base must be a call to an alloc_size 8424 /// function. 8425 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8426 const LValue &LVal, 8427 llvm::APInt &Result) { 8428 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8429 "Can't get the size of a non alloc_size function"); 8430 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8431 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8432 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8433 } 8434 8435 /// Attempts to evaluate the given LValueBase as the result of a call to 8436 /// a function with the alloc_size attribute. If it was possible to do so, this 8437 /// function will return true, make Result's Base point to said function call, 8438 /// and mark Result's Base as invalid. 8439 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8440 LValue &Result) { 8441 if (Base.isNull()) 8442 return false; 8443 8444 // Because we do no form of static analysis, we only support const variables. 8445 // 8446 // Additionally, we can't support parameters, nor can we support static 8447 // variables (in the latter case, use-before-assign isn't UB; in the former, 8448 // we have no clue what they'll be assigned to). 8449 const auto *VD = 8450 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8451 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8452 return false; 8453 8454 const Expr *Init = VD->getAnyInitializer(); 8455 if (!Init) 8456 return false; 8457 8458 const Expr *E = Init->IgnoreParens(); 8459 if (!tryUnwrapAllocSizeCall(E)) 8460 return false; 8461 8462 // Store E instead of E unwrapped so that the type of the LValue's base is 8463 // what the user wanted. 8464 Result.setInvalid(E); 8465 8466 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8467 Result.addUnsizedArray(Info, E, Pointee); 8468 return true; 8469 } 8470 8471 namespace { 8472 class PointerExprEvaluator 8473 : public ExprEvaluatorBase<PointerExprEvaluator> { 8474 LValue &Result; 8475 bool InvalidBaseOK; 8476 8477 bool Success(const Expr *E) { 8478 Result.set(E); 8479 return true; 8480 } 8481 8482 bool evaluateLValue(const Expr *E, LValue &Result) { 8483 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8484 } 8485 8486 bool evaluatePointer(const Expr *E, LValue &Result) { 8487 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8488 } 8489 8490 bool visitNonBuiltinCallExpr(const CallExpr *E); 8491 public: 8492 8493 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8494 : ExprEvaluatorBaseTy(info), Result(Result), 8495 InvalidBaseOK(InvalidBaseOK) {} 8496 8497 bool Success(const APValue &V, const Expr *E) { 8498 Result.setFrom(Info.Ctx, V); 8499 return true; 8500 } 8501 bool ZeroInitialization(const Expr *E) { 8502 Result.setNull(Info.Ctx, E->getType()); 8503 return true; 8504 } 8505 8506 bool VisitBinaryOperator(const BinaryOperator *E); 8507 bool VisitCastExpr(const CastExpr* E); 8508 bool VisitUnaryAddrOf(const UnaryOperator *E); 8509 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8510 { return Success(E); } 8511 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8512 if (E->isExpressibleAsConstantInitializer()) 8513 return Success(E); 8514 if (Info.noteFailure()) 8515 EvaluateIgnoredValue(Info, E->getSubExpr()); 8516 return Error(E); 8517 } 8518 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8519 { return Success(E); } 8520 bool VisitCallExpr(const CallExpr *E); 8521 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8522 bool VisitBlockExpr(const BlockExpr *E) { 8523 if (!E->getBlockDecl()->hasCaptures()) 8524 return Success(E); 8525 return Error(E); 8526 } 8527 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8528 // Can't look at 'this' when checking a potential constant expression. 8529 if (Info.checkingPotentialConstantExpression()) 8530 return false; 8531 if (!Info.CurrentCall->This) { 8532 if (Info.getLangOpts().CPlusPlus11) 8533 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8534 else 8535 Info.FFDiag(E); 8536 return false; 8537 } 8538 Result = *Info.CurrentCall->This; 8539 // If we are inside a lambda's call operator, the 'this' expression refers 8540 // to the enclosing '*this' object (either by value or reference) which is 8541 // either copied into the closure object's field that represents the '*this' 8542 // or refers to '*this'. 8543 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8544 // Ensure we actually have captured 'this'. (an error will have 8545 // been previously reported if not). 8546 if (!Info.CurrentCall->LambdaThisCaptureField) 8547 return false; 8548 8549 // Update 'Result' to refer to the data member/field of the closure object 8550 // that represents the '*this' capture. 8551 if (!HandleLValueMember(Info, E, Result, 8552 Info.CurrentCall->LambdaThisCaptureField)) 8553 return false; 8554 // If we captured '*this' by reference, replace the field with its referent. 8555 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8556 ->isPointerType()) { 8557 APValue RVal; 8558 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8559 RVal)) 8560 return false; 8561 8562 Result.setFrom(Info.Ctx, RVal); 8563 } 8564 } 8565 return true; 8566 } 8567 8568 bool VisitCXXNewExpr(const CXXNewExpr *E); 8569 8570 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8571 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8572 APValue LValResult = E->EvaluateInContext( 8573 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8574 Result.setFrom(Info.Ctx, LValResult); 8575 return true; 8576 } 8577 8578 // FIXME: Missing: @protocol, @selector 8579 }; 8580 } // end anonymous namespace 8581 8582 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8583 bool InvalidBaseOK) { 8584 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8585 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8586 } 8587 8588 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8589 if (E->getOpcode() != BO_Add && 8590 E->getOpcode() != BO_Sub) 8591 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8592 8593 const Expr *PExp = E->getLHS(); 8594 const Expr *IExp = E->getRHS(); 8595 if (IExp->getType()->isPointerType()) 8596 std::swap(PExp, IExp); 8597 8598 bool EvalPtrOK = evaluatePointer(PExp, Result); 8599 if (!EvalPtrOK && !Info.noteFailure()) 8600 return false; 8601 8602 llvm::APSInt Offset; 8603 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8604 return false; 8605 8606 if (E->getOpcode() == BO_Sub) 8607 negateAsSigned(Offset); 8608 8609 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8610 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8611 } 8612 8613 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8614 return evaluateLValue(E->getSubExpr(), Result); 8615 } 8616 8617 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8618 const Expr *SubExpr = E->getSubExpr(); 8619 8620 switch (E->getCastKind()) { 8621 default: 8622 break; 8623 case CK_BitCast: 8624 case CK_CPointerToObjCPointerCast: 8625 case CK_BlockPointerToObjCPointerCast: 8626 case CK_AnyPointerToBlockPointerCast: 8627 case CK_AddressSpaceConversion: 8628 if (!Visit(SubExpr)) 8629 return false; 8630 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8631 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8632 // also static_casts, but we disallow them as a resolution to DR1312. 8633 if (!E->getType()->isVoidPointerType()) { 8634 if (!Result.InvalidBase && !Result.Designator.Invalid && 8635 !Result.IsNullPtr && 8636 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8637 E->getType()->getPointeeType()) && 8638 Info.getStdAllocatorCaller("allocate")) { 8639 // Inside a call to std::allocator::allocate and friends, we permit 8640 // casting from void* back to cv1 T* for a pointer that points to a 8641 // cv2 T. 8642 } else { 8643 Result.Designator.setInvalid(); 8644 if (SubExpr->getType()->isVoidPointerType()) 8645 CCEDiag(E, diag::note_constexpr_invalid_cast) 8646 << 3 << SubExpr->getType(); 8647 else 8648 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8649 } 8650 } 8651 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8652 ZeroInitialization(E); 8653 return true; 8654 8655 case CK_DerivedToBase: 8656 case CK_UncheckedDerivedToBase: 8657 if (!evaluatePointer(E->getSubExpr(), Result)) 8658 return false; 8659 if (!Result.Base && Result.Offset.isZero()) 8660 return true; 8661 8662 // Now figure out the necessary offset to add to the base LV to get from 8663 // the derived class to the base class. 8664 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8665 castAs<PointerType>()->getPointeeType(), 8666 Result); 8667 8668 case CK_BaseToDerived: 8669 if (!Visit(E->getSubExpr())) 8670 return false; 8671 if (!Result.Base && Result.Offset.isZero()) 8672 return true; 8673 return HandleBaseToDerivedCast(Info, E, Result); 8674 8675 case CK_Dynamic: 8676 if (!Visit(E->getSubExpr())) 8677 return false; 8678 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8679 8680 case CK_NullToPointer: 8681 VisitIgnoredValue(E->getSubExpr()); 8682 return ZeroInitialization(E); 8683 8684 case CK_IntegralToPointer: { 8685 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8686 8687 APValue Value; 8688 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8689 break; 8690 8691 if (Value.isInt()) { 8692 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8693 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8694 Result.Base = (Expr*)nullptr; 8695 Result.InvalidBase = false; 8696 Result.Offset = CharUnits::fromQuantity(N); 8697 Result.Designator.setInvalid(); 8698 Result.IsNullPtr = false; 8699 return true; 8700 } else { 8701 // Cast is of an lvalue, no need to change value. 8702 Result.setFrom(Info.Ctx, Value); 8703 return true; 8704 } 8705 } 8706 8707 case CK_ArrayToPointerDecay: { 8708 if (SubExpr->isGLValue()) { 8709 if (!evaluateLValue(SubExpr, Result)) 8710 return false; 8711 } else { 8712 APValue &Value = Info.CurrentCall->createTemporary( 8713 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8714 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8715 return false; 8716 } 8717 // The result is a pointer to the first element of the array. 8718 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8719 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8720 Result.addArray(Info, E, CAT); 8721 else 8722 Result.addUnsizedArray(Info, E, AT->getElementType()); 8723 return true; 8724 } 8725 8726 case CK_FunctionToPointerDecay: 8727 return evaluateLValue(SubExpr, Result); 8728 8729 case CK_LValueToRValue: { 8730 LValue LVal; 8731 if (!evaluateLValue(E->getSubExpr(), LVal)) 8732 return false; 8733 8734 APValue RVal; 8735 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8736 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8737 LVal, RVal)) 8738 return InvalidBaseOK && 8739 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8740 return Success(RVal, E); 8741 } 8742 } 8743 8744 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8745 } 8746 8747 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8748 UnaryExprOrTypeTrait ExprKind) { 8749 // C++ [expr.alignof]p3: 8750 // When alignof is applied to a reference type, the result is the 8751 // alignment of the referenced type. 8752 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8753 T = Ref->getPointeeType(); 8754 8755 if (T.getQualifiers().hasUnaligned()) 8756 return CharUnits::One(); 8757 8758 const bool AlignOfReturnsPreferred = 8759 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8760 8761 // __alignof is defined to return the preferred alignment. 8762 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8763 // as well. 8764 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8765 return Info.Ctx.toCharUnitsFromBits( 8766 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8767 // alignof and _Alignof are defined to return the ABI alignment. 8768 else if (ExprKind == UETT_AlignOf) 8769 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8770 else 8771 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8772 } 8773 8774 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8775 UnaryExprOrTypeTrait ExprKind) { 8776 E = E->IgnoreParens(); 8777 8778 // The kinds of expressions that we have special-case logic here for 8779 // should be kept up to date with the special checks for those 8780 // expressions in Sema. 8781 8782 // alignof decl is always accepted, even if it doesn't make sense: we default 8783 // to 1 in those cases. 8784 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8785 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8786 /*RefAsPointee*/true); 8787 8788 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8789 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8790 /*RefAsPointee*/true); 8791 8792 return GetAlignOfType(Info, E->getType(), ExprKind); 8793 } 8794 8795 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8796 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8797 return Info.Ctx.getDeclAlign(VD); 8798 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8799 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8800 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8801 } 8802 8803 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8804 /// __builtin_is_aligned and __builtin_assume_aligned. 8805 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8806 EvalInfo &Info, APSInt &Alignment) { 8807 if (!EvaluateInteger(E, Alignment, Info)) 8808 return false; 8809 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8810 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8811 return false; 8812 } 8813 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8814 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8815 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8816 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8817 << MaxValue << ForType << Alignment; 8818 return false; 8819 } 8820 // Ensure both alignment and source value have the same bit width so that we 8821 // don't assert when computing the resulting value. 8822 APSInt ExtAlignment = 8823 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8824 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8825 "Alignment should not be changed by ext/trunc"); 8826 Alignment = ExtAlignment; 8827 assert(Alignment.getBitWidth() == SrcWidth); 8828 return true; 8829 } 8830 8831 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8832 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8833 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8834 return true; 8835 8836 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8837 return false; 8838 8839 Result.setInvalid(E); 8840 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8841 Result.addUnsizedArray(Info, E, PointeeTy); 8842 return true; 8843 } 8844 8845 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8846 if (IsStringLiteralCall(E)) 8847 return Success(E); 8848 8849 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8850 return VisitBuiltinCallExpr(E, BuiltinOp); 8851 8852 return visitNonBuiltinCallExpr(E); 8853 } 8854 8855 // Determine if T is a character type for which we guarantee that 8856 // sizeof(T) == 1. 8857 static bool isOneByteCharacterType(QualType T) { 8858 return T->isCharType() || T->isChar8Type(); 8859 } 8860 8861 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8862 unsigned BuiltinOp) { 8863 switch (BuiltinOp) { 8864 case Builtin::BI__builtin_addressof: 8865 return evaluateLValue(E->getArg(0), Result); 8866 case Builtin::BI__builtin_assume_aligned: { 8867 // We need to be very careful here because: if the pointer does not have the 8868 // asserted alignment, then the behavior is undefined, and undefined 8869 // behavior is non-constant. 8870 if (!evaluatePointer(E->getArg(0), Result)) 8871 return false; 8872 8873 LValue OffsetResult(Result); 8874 APSInt Alignment; 8875 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8876 Alignment)) 8877 return false; 8878 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8879 8880 if (E->getNumArgs() > 2) { 8881 APSInt Offset; 8882 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8883 return false; 8884 8885 int64_t AdditionalOffset = -Offset.getZExtValue(); 8886 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8887 } 8888 8889 // If there is a base object, then it must have the correct alignment. 8890 if (OffsetResult.Base) { 8891 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8892 8893 if (BaseAlignment < Align) { 8894 Result.Designator.setInvalid(); 8895 // FIXME: Add support to Diagnostic for long / long long. 8896 CCEDiag(E->getArg(0), 8897 diag::note_constexpr_baa_insufficient_alignment) << 0 8898 << (unsigned)BaseAlignment.getQuantity() 8899 << (unsigned)Align.getQuantity(); 8900 return false; 8901 } 8902 } 8903 8904 // The offset must also have the correct alignment. 8905 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8906 Result.Designator.setInvalid(); 8907 8908 (OffsetResult.Base 8909 ? CCEDiag(E->getArg(0), 8910 diag::note_constexpr_baa_insufficient_alignment) << 1 8911 : CCEDiag(E->getArg(0), 8912 diag::note_constexpr_baa_value_insufficient_alignment)) 8913 << (int)OffsetResult.Offset.getQuantity() 8914 << (unsigned)Align.getQuantity(); 8915 return false; 8916 } 8917 8918 return true; 8919 } 8920 case Builtin::BI__builtin_align_up: 8921 case Builtin::BI__builtin_align_down: { 8922 if (!evaluatePointer(E->getArg(0), Result)) 8923 return false; 8924 APSInt Alignment; 8925 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8926 Alignment)) 8927 return false; 8928 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8929 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8930 // For align_up/align_down, we can return the same value if the alignment 8931 // is known to be greater or equal to the requested value. 8932 if (PtrAlign.getQuantity() >= Alignment) 8933 return true; 8934 8935 // The alignment could be greater than the minimum at run-time, so we cannot 8936 // infer much about the resulting pointer value. One case is possible: 8937 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8938 // can infer the correct index if the requested alignment is smaller than 8939 // the base alignment so we can perform the computation on the offset. 8940 if (BaseAlignment.getQuantity() >= Alignment) { 8941 assert(Alignment.getBitWidth() <= 64 && 8942 "Cannot handle > 64-bit address-space"); 8943 uint64_t Alignment64 = Alignment.getZExtValue(); 8944 CharUnits NewOffset = CharUnits::fromQuantity( 8945 BuiltinOp == Builtin::BI__builtin_align_down 8946 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8947 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8948 Result.adjustOffset(NewOffset - Result.Offset); 8949 // TODO: diagnose out-of-bounds values/only allow for arrays? 8950 return true; 8951 } 8952 // Otherwise, we cannot constant-evaluate the result. 8953 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8954 << Alignment; 8955 return false; 8956 } 8957 case Builtin::BI__builtin_operator_new: 8958 return HandleOperatorNewCall(Info, E, Result); 8959 case Builtin::BI__builtin_launder: 8960 return evaluatePointer(E->getArg(0), Result); 8961 case Builtin::BIstrchr: 8962 case Builtin::BIwcschr: 8963 case Builtin::BImemchr: 8964 case Builtin::BIwmemchr: 8965 if (Info.getLangOpts().CPlusPlus11) 8966 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8967 << /*isConstexpr*/0 << /*isConstructor*/0 8968 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8969 else 8970 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8971 LLVM_FALLTHROUGH; 8972 case Builtin::BI__builtin_strchr: 8973 case Builtin::BI__builtin_wcschr: 8974 case Builtin::BI__builtin_memchr: 8975 case Builtin::BI__builtin_char_memchr: 8976 case Builtin::BI__builtin_wmemchr: { 8977 if (!Visit(E->getArg(0))) 8978 return false; 8979 APSInt Desired; 8980 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8981 return false; 8982 uint64_t MaxLength = uint64_t(-1); 8983 if (BuiltinOp != Builtin::BIstrchr && 8984 BuiltinOp != Builtin::BIwcschr && 8985 BuiltinOp != Builtin::BI__builtin_strchr && 8986 BuiltinOp != Builtin::BI__builtin_wcschr) { 8987 APSInt N; 8988 if (!EvaluateInteger(E->getArg(2), N, Info)) 8989 return false; 8990 MaxLength = N.getExtValue(); 8991 } 8992 // We cannot find the value if there are no candidates to match against. 8993 if (MaxLength == 0u) 8994 return ZeroInitialization(E); 8995 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8996 Result.Designator.Invalid) 8997 return false; 8998 QualType CharTy = Result.Designator.getType(Info.Ctx); 8999 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9000 BuiltinOp == Builtin::BI__builtin_memchr; 9001 assert(IsRawByte || 9002 Info.Ctx.hasSameUnqualifiedType( 9003 CharTy, E->getArg(0)->getType()->getPointeeType())); 9004 // Pointers to const void may point to objects of incomplete type. 9005 if (IsRawByte && CharTy->isIncompleteType()) { 9006 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9007 return false; 9008 } 9009 // Give up on byte-oriented matching against multibyte elements. 9010 // FIXME: We can compare the bytes in the correct order. 9011 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9012 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9013 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9014 << CharTy; 9015 return false; 9016 } 9017 // Figure out what value we're actually looking for (after converting to 9018 // the corresponding unsigned type if necessary). 9019 uint64_t DesiredVal; 9020 bool StopAtNull = false; 9021 switch (BuiltinOp) { 9022 case Builtin::BIstrchr: 9023 case Builtin::BI__builtin_strchr: 9024 // strchr compares directly to the passed integer, and therefore 9025 // always fails if given an int that is not a char. 9026 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9027 E->getArg(1)->getType(), 9028 Desired), 9029 Desired)) 9030 return ZeroInitialization(E); 9031 StopAtNull = true; 9032 LLVM_FALLTHROUGH; 9033 case Builtin::BImemchr: 9034 case Builtin::BI__builtin_memchr: 9035 case Builtin::BI__builtin_char_memchr: 9036 // memchr compares by converting both sides to unsigned char. That's also 9037 // correct for strchr if we get this far (to cope with plain char being 9038 // unsigned in the strchr case). 9039 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9040 break; 9041 9042 case Builtin::BIwcschr: 9043 case Builtin::BI__builtin_wcschr: 9044 StopAtNull = true; 9045 LLVM_FALLTHROUGH; 9046 case Builtin::BIwmemchr: 9047 case Builtin::BI__builtin_wmemchr: 9048 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9049 DesiredVal = Desired.getZExtValue(); 9050 break; 9051 } 9052 9053 for (; MaxLength; --MaxLength) { 9054 APValue Char; 9055 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9056 !Char.isInt()) 9057 return false; 9058 if (Char.getInt().getZExtValue() == DesiredVal) 9059 return true; 9060 if (StopAtNull && !Char.getInt()) 9061 break; 9062 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9063 return false; 9064 } 9065 // Not found: return nullptr. 9066 return ZeroInitialization(E); 9067 } 9068 9069 case Builtin::BImemcpy: 9070 case Builtin::BImemmove: 9071 case Builtin::BIwmemcpy: 9072 case Builtin::BIwmemmove: 9073 if (Info.getLangOpts().CPlusPlus11) 9074 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9075 << /*isConstexpr*/0 << /*isConstructor*/0 9076 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9077 else 9078 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9079 LLVM_FALLTHROUGH; 9080 case Builtin::BI__builtin_memcpy: 9081 case Builtin::BI__builtin_memmove: 9082 case Builtin::BI__builtin_wmemcpy: 9083 case Builtin::BI__builtin_wmemmove: { 9084 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9085 BuiltinOp == Builtin::BIwmemmove || 9086 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9087 BuiltinOp == Builtin::BI__builtin_wmemmove; 9088 bool Move = BuiltinOp == Builtin::BImemmove || 9089 BuiltinOp == Builtin::BIwmemmove || 9090 BuiltinOp == Builtin::BI__builtin_memmove || 9091 BuiltinOp == Builtin::BI__builtin_wmemmove; 9092 9093 // The result of mem* is the first argument. 9094 if (!Visit(E->getArg(0))) 9095 return false; 9096 LValue Dest = Result; 9097 9098 LValue Src; 9099 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9100 return false; 9101 9102 APSInt N; 9103 if (!EvaluateInteger(E->getArg(2), N, Info)) 9104 return false; 9105 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9106 9107 // If the size is zero, we treat this as always being a valid no-op. 9108 // (Even if one of the src and dest pointers is null.) 9109 if (!N) 9110 return true; 9111 9112 // Otherwise, if either of the operands is null, we can't proceed. Don't 9113 // try to determine the type of the copied objects, because there aren't 9114 // any. 9115 if (!Src.Base || !Dest.Base) { 9116 APValue Val; 9117 (!Src.Base ? Src : Dest).moveInto(Val); 9118 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9119 << Move << WChar << !!Src.Base 9120 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9121 return false; 9122 } 9123 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9124 return false; 9125 9126 // We require that Src and Dest are both pointers to arrays of 9127 // trivially-copyable type. (For the wide version, the designator will be 9128 // invalid if the designated object is not a wchar_t.) 9129 QualType T = Dest.Designator.getType(Info.Ctx); 9130 QualType SrcT = Src.Designator.getType(Info.Ctx); 9131 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9132 // FIXME: Consider using our bit_cast implementation to support this. 9133 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9134 return false; 9135 } 9136 if (T->isIncompleteType()) { 9137 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9138 return false; 9139 } 9140 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9141 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9142 return false; 9143 } 9144 9145 // Figure out how many T's we're copying. 9146 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9147 if (!WChar) { 9148 uint64_t Remainder; 9149 llvm::APInt OrigN = N; 9150 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9151 if (Remainder) { 9152 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9153 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 9154 << (unsigned)TSize; 9155 return false; 9156 } 9157 } 9158 9159 // Check that the copying will remain within the arrays, just so that we 9160 // can give a more meaningful diagnostic. This implicitly also checks that 9161 // N fits into 64 bits. 9162 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9163 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9164 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9165 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9166 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9167 << N.toString(10, /*Signed*/false); 9168 return false; 9169 } 9170 uint64_t NElems = N.getZExtValue(); 9171 uint64_t NBytes = NElems * TSize; 9172 9173 // Check for overlap. 9174 int Direction = 1; 9175 if (HasSameBase(Src, Dest)) { 9176 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9177 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9178 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9179 // Dest is inside the source region. 9180 if (!Move) { 9181 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9182 return false; 9183 } 9184 // For memmove and friends, copy backwards. 9185 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9186 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9187 return false; 9188 Direction = -1; 9189 } else if (!Move && SrcOffset >= DestOffset && 9190 SrcOffset - DestOffset < NBytes) { 9191 // Src is inside the destination region for memcpy: invalid. 9192 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9193 return false; 9194 } 9195 } 9196 9197 while (true) { 9198 APValue Val; 9199 // FIXME: Set WantObjectRepresentation to true if we're copying a 9200 // char-like type? 9201 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9202 !handleAssignment(Info, E, Dest, T, Val)) 9203 return false; 9204 // Do not iterate past the last element; if we're copying backwards, that 9205 // might take us off the start of the array. 9206 if (--NElems == 0) 9207 return true; 9208 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9209 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9210 return false; 9211 } 9212 } 9213 9214 default: 9215 break; 9216 } 9217 9218 return visitNonBuiltinCallExpr(E); 9219 } 9220 9221 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9222 APValue &Result, const InitListExpr *ILE, 9223 QualType AllocType); 9224 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9225 APValue &Result, 9226 const CXXConstructExpr *CCE, 9227 QualType AllocType); 9228 9229 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9230 if (!Info.getLangOpts().CPlusPlus20) 9231 Info.CCEDiag(E, diag::note_constexpr_new); 9232 9233 // We cannot speculatively evaluate a delete expression. 9234 if (Info.SpeculativeEvaluationDepth) 9235 return false; 9236 9237 FunctionDecl *OperatorNew = E->getOperatorNew(); 9238 9239 bool IsNothrow = false; 9240 bool IsPlacement = false; 9241 if (OperatorNew->isReservedGlobalPlacementOperator() && 9242 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9243 // FIXME Support array placement new. 9244 assert(E->getNumPlacementArgs() == 1); 9245 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9246 return false; 9247 if (Result.Designator.Invalid) 9248 return false; 9249 IsPlacement = true; 9250 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9251 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9252 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9253 return false; 9254 } else if (E->getNumPlacementArgs()) { 9255 // The only new-placement list we support is of the form (std::nothrow). 9256 // 9257 // FIXME: There is no restriction on this, but it's not clear that any 9258 // other form makes any sense. We get here for cases such as: 9259 // 9260 // new (std::align_val_t{N}) X(int) 9261 // 9262 // (which should presumably be valid only if N is a multiple of 9263 // alignof(int), and in any case can't be deallocated unless N is 9264 // alignof(X) and X has new-extended alignment). 9265 if (E->getNumPlacementArgs() != 1 || 9266 !E->getPlacementArg(0)->getType()->isNothrowT()) 9267 return Error(E, diag::note_constexpr_new_placement); 9268 9269 LValue Nothrow; 9270 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9271 return false; 9272 IsNothrow = true; 9273 } 9274 9275 const Expr *Init = E->getInitializer(); 9276 const InitListExpr *ResizedArrayILE = nullptr; 9277 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9278 bool ValueInit = false; 9279 9280 QualType AllocType = E->getAllocatedType(); 9281 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9282 const Expr *Stripped = *ArraySize; 9283 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9284 Stripped = ICE->getSubExpr()) 9285 if (ICE->getCastKind() != CK_NoOp && 9286 ICE->getCastKind() != CK_IntegralCast) 9287 break; 9288 9289 llvm::APSInt ArrayBound; 9290 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9291 return false; 9292 9293 // C++ [expr.new]p9: 9294 // The expression is erroneous if: 9295 // -- [...] its value before converting to size_t [or] applying the 9296 // second standard conversion sequence is less than zero 9297 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9298 if (IsNothrow) 9299 return ZeroInitialization(E); 9300 9301 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9302 << ArrayBound << (*ArraySize)->getSourceRange(); 9303 return false; 9304 } 9305 9306 // -- its value is such that the size of the allocated object would 9307 // exceed the implementation-defined limit 9308 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9309 ArrayBound) > 9310 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9311 if (IsNothrow) 9312 return ZeroInitialization(E); 9313 9314 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9315 << ArrayBound << (*ArraySize)->getSourceRange(); 9316 return false; 9317 } 9318 9319 // -- the new-initializer is a braced-init-list and the number of 9320 // array elements for which initializers are provided [...] 9321 // exceeds the number of elements to initialize 9322 if (!Init) { 9323 // No initialization is performed. 9324 } else if (isa<CXXScalarValueInitExpr>(Init) || 9325 isa<ImplicitValueInitExpr>(Init)) { 9326 ValueInit = true; 9327 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9328 ResizedArrayCCE = CCE; 9329 } else { 9330 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9331 assert(CAT && "unexpected type for array initializer"); 9332 9333 unsigned Bits = 9334 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9335 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9336 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9337 if (InitBound.ugt(AllocBound)) { 9338 if (IsNothrow) 9339 return ZeroInitialization(E); 9340 9341 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9342 << AllocBound.toString(10, /*Signed=*/false) 9343 << InitBound.toString(10, /*Signed=*/false) 9344 << (*ArraySize)->getSourceRange(); 9345 return false; 9346 } 9347 9348 // If the sizes differ, we must have an initializer list, and we need 9349 // special handling for this case when we initialize. 9350 if (InitBound != AllocBound) 9351 ResizedArrayILE = cast<InitListExpr>(Init); 9352 } 9353 9354 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9355 ArrayType::Normal, 0); 9356 } else { 9357 assert(!AllocType->isArrayType() && 9358 "array allocation with non-array new"); 9359 } 9360 9361 APValue *Val; 9362 if (IsPlacement) { 9363 AccessKinds AK = AK_Construct; 9364 struct FindObjectHandler { 9365 EvalInfo &Info; 9366 const Expr *E; 9367 QualType AllocType; 9368 const AccessKinds AccessKind; 9369 APValue *Value; 9370 9371 typedef bool result_type; 9372 bool failed() { return false; } 9373 bool found(APValue &Subobj, QualType SubobjType) { 9374 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9375 // old name of the object to be used to name the new object. 9376 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9377 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9378 SubobjType << AllocType; 9379 return false; 9380 } 9381 Value = &Subobj; 9382 return true; 9383 } 9384 bool found(APSInt &Value, QualType SubobjType) { 9385 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9386 return false; 9387 } 9388 bool found(APFloat &Value, QualType SubobjType) { 9389 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9390 return false; 9391 } 9392 } Handler = {Info, E, AllocType, AK, nullptr}; 9393 9394 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9395 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9396 return false; 9397 9398 Val = Handler.Value; 9399 9400 // [basic.life]p1: 9401 // The lifetime of an object o of type T ends when [...] the storage 9402 // which the object occupies is [...] reused by an object that is not 9403 // nested within o (6.6.2). 9404 *Val = APValue(); 9405 } else { 9406 // Perform the allocation and obtain a pointer to the resulting object. 9407 Val = Info.createHeapAlloc(E, AllocType, Result); 9408 if (!Val) 9409 return false; 9410 } 9411 9412 if (ValueInit) { 9413 ImplicitValueInitExpr VIE(AllocType); 9414 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9415 return false; 9416 } else if (ResizedArrayILE) { 9417 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9418 AllocType)) 9419 return false; 9420 } else if (ResizedArrayCCE) { 9421 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9422 AllocType)) 9423 return false; 9424 } else if (Init) { 9425 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9426 return false; 9427 } else if (!getDefaultInitValue(AllocType, *Val)) { 9428 return false; 9429 } 9430 9431 // Array new returns a pointer to the first element, not a pointer to the 9432 // array. 9433 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9434 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9435 9436 return true; 9437 } 9438 //===----------------------------------------------------------------------===// 9439 // Member Pointer Evaluation 9440 //===----------------------------------------------------------------------===// 9441 9442 namespace { 9443 class MemberPointerExprEvaluator 9444 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9445 MemberPtr &Result; 9446 9447 bool Success(const ValueDecl *D) { 9448 Result = MemberPtr(D); 9449 return true; 9450 } 9451 public: 9452 9453 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9454 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9455 9456 bool Success(const APValue &V, const Expr *E) { 9457 Result.setFrom(V); 9458 return true; 9459 } 9460 bool ZeroInitialization(const Expr *E) { 9461 return Success((const ValueDecl*)nullptr); 9462 } 9463 9464 bool VisitCastExpr(const CastExpr *E); 9465 bool VisitUnaryAddrOf(const UnaryOperator *E); 9466 }; 9467 } // end anonymous namespace 9468 9469 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9470 EvalInfo &Info) { 9471 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9472 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9473 } 9474 9475 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9476 switch (E->getCastKind()) { 9477 default: 9478 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9479 9480 case CK_NullToMemberPointer: 9481 VisitIgnoredValue(E->getSubExpr()); 9482 return ZeroInitialization(E); 9483 9484 case CK_BaseToDerivedMemberPointer: { 9485 if (!Visit(E->getSubExpr())) 9486 return false; 9487 if (E->path_empty()) 9488 return true; 9489 // Base-to-derived member pointer casts store the path in derived-to-base 9490 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9491 // the wrong end of the derived->base arc, so stagger the path by one class. 9492 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9493 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9494 PathI != PathE; ++PathI) { 9495 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9496 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9497 if (!Result.castToDerived(Derived)) 9498 return Error(E); 9499 } 9500 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9501 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9502 return Error(E); 9503 return true; 9504 } 9505 9506 case CK_DerivedToBaseMemberPointer: 9507 if (!Visit(E->getSubExpr())) 9508 return false; 9509 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9510 PathE = E->path_end(); PathI != PathE; ++PathI) { 9511 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9512 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9513 if (!Result.castToBase(Base)) 9514 return Error(E); 9515 } 9516 return true; 9517 } 9518 } 9519 9520 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9521 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9522 // member can be formed. 9523 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9524 } 9525 9526 //===----------------------------------------------------------------------===// 9527 // Record Evaluation 9528 //===----------------------------------------------------------------------===// 9529 9530 namespace { 9531 class RecordExprEvaluator 9532 : public ExprEvaluatorBase<RecordExprEvaluator> { 9533 const LValue &This; 9534 APValue &Result; 9535 public: 9536 9537 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9538 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9539 9540 bool Success(const APValue &V, const Expr *E) { 9541 Result = V; 9542 return true; 9543 } 9544 bool ZeroInitialization(const Expr *E) { 9545 return ZeroInitialization(E, E->getType()); 9546 } 9547 bool ZeroInitialization(const Expr *E, QualType T); 9548 9549 bool VisitCallExpr(const CallExpr *E) { 9550 return handleCallExpr(E, Result, &This); 9551 } 9552 bool VisitCastExpr(const CastExpr *E); 9553 bool VisitInitListExpr(const InitListExpr *E); 9554 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9555 return VisitCXXConstructExpr(E, E->getType()); 9556 } 9557 bool VisitLambdaExpr(const LambdaExpr *E); 9558 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9559 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9560 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9561 bool VisitBinCmp(const BinaryOperator *E); 9562 }; 9563 } 9564 9565 /// Perform zero-initialization on an object of non-union class type. 9566 /// C++11 [dcl.init]p5: 9567 /// To zero-initialize an object or reference of type T means: 9568 /// [...] 9569 /// -- if T is a (possibly cv-qualified) non-union class type, 9570 /// each non-static data member and each base-class subobject is 9571 /// zero-initialized 9572 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9573 const RecordDecl *RD, 9574 const LValue &This, APValue &Result) { 9575 assert(!RD->isUnion() && "Expected non-union class type"); 9576 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9577 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9578 std::distance(RD->field_begin(), RD->field_end())); 9579 9580 if (RD->isInvalidDecl()) return false; 9581 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9582 9583 if (CD) { 9584 unsigned Index = 0; 9585 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9586 End = CD->bases_end(); I != End; ++I, ++Index) { 9587 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9588 LValue Subobject = This; 9589 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9590 return false; 9591 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9592 Result.getStructBase(Index))) 9593 return false; 9594 } 9595 } 9596 9597 for (const auto *I : RD->fields()) { 9598 // -- if T is a reference type, no initialization is performed. 9599 if (I->getType()->isReferenceType()) 9600 continue; 9601 9602 LValue Subobject = This; 9603 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9604 return false; 9605 9606 ImplicitValueInitExpr VIE(I->getType()); 9607 if (!EvaluateInPlace( 9608 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9609 return false; 9610 } 9611 9612 return true; 9613 } 9614 9615 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9616 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9617 if (RD->isInvalidDecl()) return false; 9618 if (RD->isUnion()) { 9619 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9620 // object's first non-static named data member is zero-initialized 9621 RecordDecl::field_iterator I = RD->field_begin(); 9622 if (I == RD->field_end()) { 9623 Result = APValue((const FieldDecl*)nullptr); 9624 return true; 9625 } 9626 9627 LValue Subobject = This; 9628 if (!HandleLValueMember(Info, E, Subobject, *I)) 9629 return false; 9630 Result = APValue(*I); 9631 ImplicitValueInitExpr VIE(I->getType()); 9632 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9633 } 9634 9635 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9636 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9637 return false; 9638 } 9639 9640 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9641 } 9642 9643 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9644 switch (E->getCastKind()) { 9645 default: 9646 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9647 9648 case CK_ConstructorConversion: 9649 return Visit(E->getSubExpr()); 9650 9651 case CK_DerivedToBase: 9652 case CK_UncheckedDerivedToBase: { 9653 APValue DerivedObject; 9654 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9655 return false; 9656 if (!DerivedObject.isStruct()) 9657 return Error(E->getSubExpr()); 9658 9659 // Derived-to-base rvalue conversion: just slice off the derived part. 9660 APValue *Value = &DerivedObject; 9661 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9662 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9663 PathE = E->path_end(); PathI != PathE; ++PathI) { 9664 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9665 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9666 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9667 RD = Base; 9668 } 9669 Result = *Value; 9670 return true; 9671 } 9672 } 9673 } 9674 9675 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9676 if (E->isTransparent()) 9677 return Visit(E->getInit(0)); 9678 9679 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9680 if (RD->isInvalidDecl()) return false; 9681 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9682 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9683 9684 EvalInfo::EvaluatingConstructorRAII EvalObj( 9685 Info, 9686 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9687 CXXRD && CXXRD->getNumBases()); 9688 9689 if (RD->isUnion()) { 9690 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9691 Result = APValue(Field); 9692 if (!Field) 9693 return true; 9694 9695 // If the initializer list for a union does not contain any elements, the 9696 // first element of the union is value-initialized. 9697 // FIXME: The element should be initialized from an initializer list. 9698 // Is this difference ever observable for initializer lists which 9699 // we don't build? 9700 ImplicitValueInitExpr VIE(Field->getType()); 9701 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9702 9703 LValue Subobject = This; 9704 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9705 return false; 9706 9707 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9708 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9709 isa<CXXDefaultInitExpr>(InitExpr)); 9710 9711 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9712 } 9713 9714 if (!Result.hasValue()) 9715 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9716 std::distance(RD->field_begin(), RD->field_end())); 9717 unsigned ElementNo = 0; 9718 bool Success = true; 9719 9720 // Initialize base classes. 9721 if (CXXRD && CXXRD->getNumBases()) { 9722 for (const auto &Base : CXXRD->bases()) { 9723 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9724 const Expr *Init = E->getInit(ElementNo); 9725 9726 LValue Subobject = This; 9727 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9728 return false; 9729 9730 APValue &FieldVal = Result.getStructBase(ElementNo); 9731 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9732 if (!Info.noteFailure()) 9733 return false; 9734 Success = false; 9735 } 9736 ++ElementNo; 9737 } 9738 9739 EvalObj.finishedConstructingBases(); 9740 } 9741 9742 // Initialize members. 9743 for (const auto *Field : RD->fields()) { 9744 // Anonymous bit-fields are not considered members of the class for 9745 // purposes of aggregate initialization. 9746 if (Field->isUnnamedBitfield()) 9747 continue; 9748 9749 LValue Subobject = This; 9750 9751 bool HaveInit = ElementNo < E->getNumInits(); 9752 9753 // FIXME: Diagnostics here should point to the end of the initializer 9754 // list, not the start. 9755 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9756 Subobject, Field, &Layout)) 9757 return false; 9758 9759 // Perform an implicit value-initialization for members beyond the end of 9760 // the initializer list. 9761 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9762 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9763 9764 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9765 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9766 isa<CXXDefaultInitExpr>(Init)); 9767 9768 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9769 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9770 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9771 FieldVal, Field))) { 9772 if (!Info.noteFailure()) 9773 return false; 9774 Success = false; 9775 } 9776 } 9777 9778 EvalObj.finishedConstructingFields(); 9779 9780 return Success; 9781 } 9782 9783 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9784 QualType T) { 9785 // Note that E's type is not necessarily the type of our class here; we might 9786 // be initializing an array element instead. 9787 const CXXConstructorDecl *FD = E->getConstructor(); 9788 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9789 9790 bool ZeroInit = E->requiresZeroInitialization(); 9791 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9792 // If we've already performed zero-initialization, we're already done. 9793 if (Result.hasValue()) 9794 return true; 9795 9796 if (ZeroInit) 9797 return ZeroInitialization(E, T); 9798 9799 return getDefaultInitValue(T, Result); 9800 } 9801 9802 const FunctionDecl *Definition = nullptr; 9803 auto Body = FD->getBody(Definition); 9804 9805 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9806 return false; 9807 9808 // Avoid materializing a temporary for an elidable copy/move constructor. 9809 if (E->isElidable() && !ZeroInit) 9810 if (const MaterializeTemporaryExpr *ME 9811 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9812 return Visit(ME->getSubExpr()); 9813 9814 if (ZeroInit && !ZeroInitialization(E, T)) 9815 return false; 9816 9817 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9818 return HandleConstructorCall(E, This, Args, 9819 cast<CXXConstructorDecl>(Definition), Info, 9820 Result); 9821 } 9822 9823 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9824 const CXXInheritedCtorInitExpr *E) { 9825 if (!Info.CurrentCall) { 9826 assert(Info.checkingPotentialConstantExpression()); 9827 return false; 9828 } 9829 9830 const CXXConstructorDecl *FD = E->getConstructor(); 9831 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9832 return false; 9833 9834 const FunctionDecl *Definition = nullptr; 9835 auto Body = FD->getBody(Definition); 9836 9837 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9838 return false; 9839 9840 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9841 cast<CXXConstructorDecl>(Definition), Info, 9842 Result); 9843 } 9844 9845 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9846 const CXXStdInitializerListExpr *E) { 9847 const ConstantArrayType *ArrayType = 9848 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9849 9850 LValue Array; 9851 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9852 return false; 9853 9854 // Get a pointer to the first element of the array. 9855 Array.addArray(Info, E, ArrayType); 9856 9857 auto InvalidType = [&] { 9858 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9859 << E->getType(); 9860 return false; 9861 }; 9862 9863 // FIXME: Perform the checks on the field types in SemaInit. 9864 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9865 RecordDecl::field_iterator Field = Record->field_begin(); 9866 if (Field == Record->field_end()) 9867 return InvalidType(); 9868 9869 // Start pointer. 9870 if (!Field->getType()->isPointerType() || 9871 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9872 ArrayType->getElementType())) 9873 return InvalidType(); 9874 9875 // FIXME: What if the initializer_list type has base classes, etc? 9876 Result = APValue(APValue::UninitStruct(), 0, 2); 9877 Array.moveInto(Result.getStructField(0)); 9878 9879 if (++Field == Record->field_end()) 9880 return InvalidType(); 9881 9882 if (Field->getType()->isPointerType() && 9883 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9884 ArrayType->getElementType())) { 9885 // End pointer. 9886 if (!HandleLValueArrayAdjustment(Info, E, Array, 9887 ArrayType->getElementType(), 9888 ArrayType->getSize().getZExtValue())) 9889 return false; 9890 Array.moveInto(Result.getStructField(1)); 9891 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9892 // Length. 9893 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9894 else 9895 return InvalidType(); 9896 9897 if (++Field != Record->field_end()) 9898 return InvalidType(); 9899 9900 return true; 9901 } 9902 9903 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9904 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9905 if (ClosureClass->isInvalidDecl()) 9906 return false; 9907 9908 const size_t NumFields = 9909 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9910 9911 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9912 E->capture_init_end()) && 9913 "The number of lambda capture initializers should equal the number of " 9914 "fields within the closure type"); 9915 9916 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9917 // Iterate through all the lambda's closure object's fields and initialize 9918 // them. 9919 auto *CaptureInitIt = E->capture_init_begin(); 9920 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9921 bool Success = true; 9922 for (const auto *Field : ClosureClass->fields()) { 9923 assert(CaptureInitIt != E->capture_init_end()); 9924 // Get the initializer for this field 9925 Expr *const CurFieldInit = *CaptureInitIt++; 9926 9927 // If there is no initializer, either this is a VLA or an error has 9928 // occurred. 9929 if (!CurFieldInit) 9930 return Error(E); 9931 9932 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9933 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9934 if (!Info.keepEvaluatingAfterFailure()) 9935 return false; 9936 Success = false; 9937 } 9938 ++CaptureIt; 9939 } 9940 return Success; 9941 } 9942 9943 static bool EvaluateRecord(const Expr *E, const LValue &This, 9944 APValue &Result, EvalInfo &Info) { 9945 assert(E->isRValue() && E->getType()->isRecordType() && 9946 "can't evaluate expression as a record rvalue"); 9947 return RecordExprEvaluator(Info, This, Result).Visit(E); 9948 } 9949 9950 //===----------------------------------------------------------------------===// 9951 // Temporary Evaluation 9952 // 9953 // Temporaries are represented in the AST as rvalues, but generally behave like 9954 // lvalues. The full-object of which the temporary is a subobject is implicitly 9955 // materialized so that a reference can bind to it. 9956 //===----------------------------------------------------------------------===// 9957 namespace { 9958 class TemporaryExprEvaluator 9959 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9960 public: 9961 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9962 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9963 9964 /// Visit an expression which constructs the value of this temporary. 9965 bool VisitConstructExpr(const Expr *E) { 9966 APValue &Value = Info.CurrentCall->createTemporary( 9967 E, E->getType(), ScopeKind::FullExpression, Result); 9968 return EvaluateInPlace(Value, Info, Result, E); 9969 } 9970 9971 bool VisitCastExpr(const CastExpr *E) { 9972 switch (E->getCastKind()) { 9973 default: 9974 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9975 9976 case CK_ConstructorConversion: 9977 return VisitConstructExpr(E->getSubExpr()); 9978 } 9979 } 9980 bool VisitInitListExpr(const InitListExpr *E) { 9981 return VisitConstructExpr(E); 9982 } 9983 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9984 return VisitConstructExpr(E); 9985 } 9986 bool VisitCallExpr(const CallExpr *E) { 9987 return VisitConstructExpr(E); 9988 } 9989 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9990 return VisitConstructExpr(E); 9991 } 9992 bool VisitLambdaExpr(const LambdaExpr *E) { 9993 return VisitConstructExpr(E); 9994 } 9995 }; 9996 } // end anonymous namespace 9997 9998 /// Evaluate an expression of record type as a temporary. 9999 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10000 assert(E->isRValue() && E->getType()->isRecordType()); 10001 return TemporaryExprEvaluator(Info, Result).Visit(E); 10002 } 10003 10004 //===----------------------------------------------------------------------===// 10005 // Vector Evaluation 10006 //===----------------------------------------------------------------------===// 10007 10008 namespace { 10009 class VectorExprEvaluator 10010 : public ExprEvaluatorBase<VectorExprEvaluator> { 10011 APValue &Result; 10012 public: 10013 10014 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10015 : ExprEvaluatorBaseTy(info), Result(Result) {} 10016 10017 bool Success(ArrayRef<APValue> V, const Expr *E) { 10018 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10019 // FIXME: remove this APValue copy. 10020 Result = APValue(V.data(), V.size()); 10021 return true; 10022 } 10023 bool Success(const APValue &V, const Expr *E) { 10024 assert(V.isVector()); 10025 Result = V; 10026 return true; 10027 } 10028 bool ZeroInitialization(const Expr *E); 10029 10030 bool VisitUnaryReal(const UnaryOperator *E) 10031 { return Visit(E->getSubExpr()); } 10032 bool VisitCastExpr(const CastExpr* E); 10033 bool VisitInitListExpr(const InitListExpr *E); 10034 bool VisitUnaryImag(const UnaryOperator *E); 10035 bool VisitBinaryOperator(const BinaryOperator *E); 10036 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10037 // conditional select), shufflevector, ExtVectorElementExpr 10038 }; 10039 } // end anonymous namespace 10040 10041 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10042 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 10043 return VectorExprEvaluator(Info, Result).Visit(E); 10044 } 10045 10046 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10047 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10048 unsigned NElts = VTy->getNumElements(); 10049 10050 const Expr *SE = E->getSubExpr(); 10051 QualType SETy = SE->getType(); 10052 10053 switch (E->getCastKind()) { 10054 case CK_VectorSplat: { 10055 APValue Val = APValue(); 10056 if (SETy->isIntegerType()) { 10057 APSInt IntResult; 10058 if (!EvaluateInteger(SE, IntResult, Info)) 10059 return false; 10060 Val = APValue(std::move(IntResult)); 10061 } else if (SETy->isRealFloatingType()) { 10062 APFloat FloatResult(0.0); 10063 if (!EvaluateFloat(SE, FloatResult, Info)) 10064 return false; 10065 Val = APValue(std::move(FloatResult)); 10066 } else { 10067 return Error(E); 10068 } 10069 10070 // Splat and create vector APValue. 10071 SmallVector<APValue, 4> Elts(NElts, Val); 10072 return Success(Elts, E); 10073 } 10074 case CK_BitCast: { 10075 // Evaluate the operand into an APInt we can extract from. 10076 llvm::APInt SValInt; 10077 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10078 return false; 10079 // Extract the elements 10080 QualType EltTy = VTy->getElementType(); 10081 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10082 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10083 SmallVector<APValue, 4> Elts; 10084 if (EltTy->isRealFloatingType()) { 10085 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10086 unsigned FloatEltSize = EltSize; 10087 if (&Sem == &APFloat::x87DoubleExtended()) 10088 FloatEltSize = 80; 10089 for (unsigned i = 0; i < NElts; i++) { 10090 llvm::APInt Elt; 10091 if (BigEndian) 10092 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10093 else 10094 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10095 Elts.push_back(APValue(APFloat(Sem, Elt))); 10096 } 10097 } else if (EltTy->isIntegerType()) { 10098 for (unsigned i = 0; i < NElts; i++) { 10099 llvm::APInt Elt; 10100 if (BigEndian) 10101 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10102 else 10103 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10104 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 10105 } 10106 } else { 10107 return Error(E); 10108 } 10109 return Success(Elts, E); 10110 } 10111 default: 10112 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10113 } 10114 } 10115 10116 bool 10117 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10118 const VectorType *VT = E->getType()->castAs<VectorType>(); 10119 unsigned NumInits = E->getNumInits(); 10120 unsigned NumElements = VT->getNumElements(); 10121 10122 QualType EltTy = VT->getElementType(); 10123 SmallVector<APValue, 4> Elements; 10124 10125 // The number of initializers can be less than the number of 10126 // vector elements. For OpenCL, this can be due to nested vector 10127 // initialization. For GCC compatibility, missing trailing elements 10128 // should be initialized with zeroes. 10129 unsigned CountInits = 0, CountElts = 0; 10130 while (CountElts < NumElements) { 10131 // Handle nested vector initialization. 10132 if (CountInits < NumInits 10133 && E->getInit(CountInits)->getType()->isVectorType()) { 10134 APValue v; 10135 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10136 return Error(E); 10137 unsigned vlen = v.getVectorLength(); 10138 for (unsigned j = 0; j < vlen; j++) 10139 Elements.push_back(v.getVectorElt(j)); 10140 CountElts += vlen; 10141 } else if (EltTy->isIntegerType()) { 10142 llvm::APSInt sInt(32); 10143 if (CountInits < NumInits) { 10144 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10145 return false; 10146 } else // trailing integer zero. 10147 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10148 Elements.push_back(APValue(sInt)); 10149 CountElts++; 10150 } else { 10151 llvm::APFloat f(0.0); 10152 if (CountInits < NumInits) { 10153 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10154 return false; 10155 } else // trailing float zero. 10156 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10157 Elements.push_back(APValue(f)); 10158 CountElts++; 10159 } 10160 CountInits++; 10161 } 10162 return Success(Elements, E); 10163 } 10164 10165 bool 10166 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10167 const auto *VT = E->getType()->castAs<VectorType>(); 10168 QualType EltTy = VT->getElementType(); 10169 APValue ZeroElement; 10170 if (EltTy->isIntegerType()) 10171 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10172 else 10173 ZeroElement = 10174 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10175 10176 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10177 return Success(Elements, E); 10178 } 10179 10180 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10181 VisitIgnoredValue(E->getSubExpr()); 10182 return ZeroInitialization(E); 10183 } 10184 10185 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10186 BinaryOperatorKind Op = E->getOpcode(); 10187 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10188 "Operation not supported on vector types"); 10189 10190 if (Op == BO_Comma) 10191 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10192 10193 Expr *LHS = E->getLHS(); 10194 Expr *RHS = E->getRHS(); 10195 10196 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10197 "Must both be vector types"); 10198 // Checking JUST the types are the same would be fine, except shifts don't 10199 // need to have their types be the same (since you always shift by an int). 10200 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10201 E->getType()->getAs<VectorType>()->getNumElements() && 10202 RHS->getType()->getAs<VectorType>()->getNumElements() == 10203 E->getType()->getAs<VectorType>()->getNumElements() && 10204 "All operands must be the same size."); 10205 10206 APValue LHSValue; 10207 APValue RHSValue; 10208 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10209 if (!LHSOK && !Info.noteFailure()) 10210 return false; 10211 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10212 return false; 10213 10214 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10215 return false; 10216 10217 return Success(LHSValue, E); 10218 } 10219 10220 //===----------------------------------------------------------------------===// 10221 // Array Evaluation 10222 //===----------------------------------------------------------------------===// 10223 10224 namespace { 10225 class ArrayExprEvaluator 10226 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10227 const LValue &This; 10228 APValue &Result; 10229 public: 10230 10231 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10232 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10233 10234 bool Success(const APValue &V, const Expr *E) { 10235 assert(V.isArray() && "expected array"); 10236 Result = V; 10237 return true; 10238 } 10239 10240 bool ZeroInitialization(const Expr *E) { 10241 const ConstantArrayType *CAT = 10242 Info.Ctx.getAsConstantArrayType(E->getType()); 10243 if (!CAT) { 10244 if (E->getType()->isIncompleteArrayType()) { 10245 // We can be asked to zero-initialize a flexible array member; this 10246 // is represented as an ImplicitValueInitExpr of incomplete array 10247 // type. In this case, the array has zero elements. 10248 Result = APValue(APValue::UninitArray(), 0, 0); 10249 return true; 10250 } 10251 // FIXME: We could handle VLAs here. 10252 return Error(E); 10253 } 10254 10255 Result = APValue(APValue::UninitArray(), 0, 10256 CAT->getSize().getZExtValue()); 10257 if (!Result.hasArrayFiller()) return true; 10258 10259 // Zero-initialize all elements. 10260 LValue Subobject = This; 10261 Subobject.addArray(Info, E, CAT); 10262 ImplicitValueInitExpr VIE(CAT->getElementType()); 10263 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10264 } 10265 10266 bool VisitCallExpr(const CallExpr *E) { 10267 return handleCallExpr(E, Result, &This); 10268 } 10269 bool VisitInitListExpr(const InitListExpr *E, 10270 QualType AllocType = QualType()); 10271 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10272 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10273 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10274 const LValue &Subobject, 10275 APValue *Value, QualType Type); 10276 bool VisitStringLiteral(const StringLiteral *E, 10277 QualType AllocType = QualType()) { 10278 expandStringLiteral(Info, E, Result, AllocType); 10279 return true; 10280 } 10281 }; 10282 } // end anonymous namespace 10283 10284 static bool EvaluateArray(const Expr *E, const LValue &This, 10285 APValue &Result, EvalInfo &Info) { 10286 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10287 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10288 } 10289 10290 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10291 APValue &Result, const InitListExpr *ILE, 10292 QualType AllocType) { 10293 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10294 "not an array rvalue"); 10295 return ArrayExprEvaluator(Info, This, Result) 10296 .VisitInitListExpr(ILE, AllocType); 10297 } 10298 10299 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10300 APValue &Result, 10301 const CXXConstructExpr *CCE, 10302 QualType AllocType) { 10303 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10304 "not an array rvalue"); 10305 return ArrayExprEvaluator(Info, This, Result) 10306 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10307 } 10308 10309 // Return true iff the given array filler may depend on the element index. 10310 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10311 // For now, just allow non-class value-initialization and initialization 10312 // lists comprised of them. 10313 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10314 return false; 10315 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10316 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10317 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10318 return true; 10319 } 10320 return false; 10321 } 10322 return true; 10323 } 10324 10325 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10326 QualType AllocType) { 10327 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10328 AllocType.isNull() ? E->getType() : AllocType); 10329 if (!CAT) 10330 return Error(E); 10331 10332 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10333 // an appropriately-typed string literal enclosed in braces. 10334 if (E->isStringLiteralInit()) { 10335 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10336 // FIXME: Support ObjCEncodeExpr here once we support it in 10337 // ArrayExprEvaluator generally. 10338 if (!SL) 10339 return Error(E); 10340 return VisitStringLiteral(SL, AllocType); 10341 } 10342 10343 bool Success = true; 10344 10345 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10346 "zero-initialized array shouldn't have any initialized elts"); 10347 APValue Filler; 10348 if (Result.isArray() && Result.hasArrayFiller()) 10349 Filler = Result.getArrayFiller(); 10350 10351 unsigned NumEltsToInit = E->getNumInits(); 10352 unsigned NumElts = CAT->getSize().getZExtValue(); 10353 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10354 10355 // If the initializer might depend on the array index, run it for each 10356 // array element. 10357 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10358 NumEltsToInit = NumElts; 10359 10360 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10361 << NumEltsToInit << ".\n"); 10362 10363 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10364 10365 // If the array was previously zero-initialized, preserve the 10366 // zero-initialized values. 10367 if (Filler.hasValue()) { 10368 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10369 Result.getArrayInitializedElt(I) = Filler; 10370 if (Result.hasArrayFiller()) 10371 Result.getArrayFiller() = Filler; 10372 } 10373 10374 LValue Subobject = This; 10375 Subobject.addArray(Info, E, CAT); 10376 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10377 const Expr *Init = 10378 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10379 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10380 Info, Subobject, Init) || 10381 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10382 CAT->getElementType(), 1)) { 10383 if (!Info.noteFailure()) 10384 return false; 10385 Success = false; 10386 } 10387 } 10388 10389 if (!Result.hasArrayFiller()) 10390 return Success; 10391 10392 // If we get here, we have a trivial filler, which we can just evaluate 10393 // once and splat over the rest of the array elements. 10394 assert(FillerExpr && "no array filler for incomplete init list"); 10395 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10396 FillerExpr) && Success; 10397 } 10398 10399 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10400 LValue CommonLV; 10401 if (E->getCommonExpr() && 10402 !Evaluate(Info.CurrentCall->createTemporary( 10403 E->getCommonExpr(), 10404 getStorageType(Info.Ctx, E->getCommonExpr()), 10405 ScopeKind::FullExpression, CommonLV), 10406 Info, E->getCommonExpr()->getSourceExpr())) 10407 return false; 10408 10409 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10410 10411 uint64_t Elements = CAT->getSize().getZExtValue(); 10412 Result = APValue(APValue::UninitArray(), Elements, Elements); 10413 10414 LValue Subobject = This; 10415 Subobject.addArray(Info, E, CAT); 10416 10417 bool Success = true; 10418 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10419 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10420 Info, Subobject, E->getSubExpr()) || 10421 !HandleLValueArrayAdjustment(Info, E, Subobject, 10422 CAT->getElementType(), 1)) { 10423 if (!Info.noteFailure()) 10424 return false; 10425 Success = false; 10426 } 10427 } 10428 10429 return Success; 10430 } 10431 10432 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10433 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10434 } 10435 10436 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10437 const LValue &Subobject, 10438 APValue *Value, 10439 QualType Type) { 10440 bool HadZeroInit = Value->hasValue(); 10441 10442 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10443 unsigned N = CAT->getSize().getZExtValue(); 10444 10445 // Preserve the array filler if we had prior zero-initialization. 10446 APValue Filler = 10447 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10448 : APValue(); 10449 10450 *Value = APValue(APValue::UninitArray(), N, N); 10451 10452 if (HadZeroInit) 10453 for (unsigned I = 0; I != N; ++I) 10454 Value->getArrayInitializedElt(I) = Filler; 10455 10456 // Initialize the elements. 10457 LValue ArrayElt = Subobject; 10458 ArrayElt.addArray(Info, E, CAT); 10459 for (unsigned I = 0; I != N; ++I) 10460 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10461 CAT->getElementType()) || 10462 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10463 CAT->getElementType(), 1)) 10464 return false; 10465 10466 return true; 10467 } 10468 10469 if (!Type->isRecordType()) 10470 return Error(E); 10471 10472 return RecordExprEvaluator(Info, Subobject, *Value) 10473 .VisitCXXConstructExpr(E, Type); 10474 } 10475 10476 //===----------------------------------------------------------------------===// 10477 // Integer Evaluation 10478 // 10479 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10480 // types and back in constant folding. Integer values are thus represented 10481 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10482 //===----------------------------------------------------------------------===// 10483 10484 namespace { 10485 class IntExprEvaluator 10486 : public ExprEvaluatorBase<IntExprEvaluator> { 10487 APValue &Result; 10488 public: 10489 IntExprEvaluator(EvalInfo &info, APValue &result) 10490 : ExprEvaluatorBaseTy(info), Result(result) {} 10491 10492 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10493 assert(E->getType()->isIntegralOrEnumerationType() && 10494 "Invalid evaluation result."); 10495 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10496 "Invalid evaluation result."); 10497 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10498 "Invalid evaluation result."); 10499 Result = APValue(SI); 10500 return true; 10501 } 10502 bool Success(const llvm::APSInt &SI, const Expr *E) { 10503 return Success(SI, E, Result); 10504 } 10505 10506 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10507 assert(E->getType()->isIntegralOrEnumerationType() && 10508 "Invalid evaluation result."); 10509 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10510 "Invalid evaluation result."); 10511 Result = APValue(APSInt(I)); 10512 Result.getInt().setIsUnsigned( 10513 E->getType()->isUnsignedIntegerOrEnumerationType()); 10514 return true; 10515 } 10516 bool Success(const llvm::APInt &I, const Expr *E) { 10517 return Success(I, E, Result); 10518 } 10519 10520 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10521 assert(E->getType()->isIntegralOrEnumerationType() && 10522 "Invalid evaluation result."); 10523 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10524 return true; 10525 } 10526 bool Success(uint64_t Value, const Expr *E) { 10527 return Success(Value, E, Result); 10528 } 10529 10530 bool Success(CharUnits Size, const Expr *E) { 10531 return Success(Size.getQuantity(), E); 10532 } 10533 10534 bool Success(const APValue &V, const Expr *E) { 10535 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10536 Result = V; 10537 return true; 10538 } 10539 return Success(V.getInt(), E); 10540 } 10541 10542 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10543 10544 //===--------------------------------------------------------------------===// 10545 // Visitor Methods 10546 //===--------------------------------------------------------------------===// 10547 10548 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10549 return Success(E->getValue(), E); 10550 } 10551 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10552 return Success(E->getValue(), E); 10553 } 10554 10555 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10556 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10557 if (CheckReferencedDecl(E, E->getDecl())) 10558 return true; 10559 10560 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10561 } 10562 bool VisitMemberExpr(const MemberExpr *E) { 10563 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10564 VisitIgnoredBaseExpression(E->getBase()); 10565 return true; 10566 } 10567 10568 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10569 } 10570 10571 bool VisitCallExpr(const CallExpr *E); 10572 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10573 bool VisitBinaryOperator(const BinaryOperator *E); 10574 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10575 bool VisitUnaryOperator(const UnaryOperator *E); 10576 10577 bool VisitCastExpr(const CastExpr* E); 10578 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10579 10580 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10581 return Success(E->getValue(), E); 10582 } 10583 10584 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10585 return Success(E->getValue(), E); 10586 } 10587 10588 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10589 if (Info.ArrayInitIndex == uint64_t(-1)) { 10590 // We were asked to evaluate this subexpression independent of the 10591 // enclosing ArrayInitLoopExpr. We can't do that. 10592 Info.FFDiag(E); 10593 return false; 10594 } 10595 return Success(Info.ArrayInitIndex, E); 10596 } 10597 10598 // Note, GNU defines __null as an integer, not a pointer. 10599 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10600 return ZeroInitialization(E); 10601 } 10602 10603 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10604 return Success(E->getValue(), E); 10605 } 10606 10607 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10608 return Success(E->getValue(), E); 10609 } 10610 10611 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10612 return Success(E->getValue(), E); 10613 } 10614 10615 bool VisitUnaryReal(const UnaryOperator *E); 10616 bool VisitUnaryImag(const UnaryOperator *E); 10617 10618 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10619 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10620 bool VisitSourceLocExpr(const SourceLocExpr *E); 10621 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10622 bool VisitRequiresExpr(const RequiresExpr *E); 10623 // FIXME: Missing: array subscript of vector, member of vector 10624 }; 10625 10626 class FixedPointExprEvaluator 10627 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10628 APValue &Result; 10629 10630 public: 10631 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10632 : ExprEvaluatorBaseTy(info), Result(result) {} 10633 10634 bool Success(const llvm::APInt &I, const Expr *E) { 10635 return Success( 10636 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10637 } 10638 10639 bool Success(uint64_t Value, const Expr *E) { 10640 return Success( 10641 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10642 } 10643 10644 bool Success(const APValue &V, const Expr *E) { 10645 return Success(V.getFixedPoint(), E); 10646 } 10647 10648 bool Success(const APFixedPoint &V, const Expr *E) { 10649 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10650 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10651 "Invalid evaluation result."); 10652 Result = APValue(V); 10653 return true; 10654 } 10655 10656 //===--------------------------------------------------------------------===// 10657 // Visitor Methods 10658 //===--------------------------------------------------------------------===// 10659 10660 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10661 return Success(E->getValue(), E); 10662 } 10663 10664 bool VisitCastExpr(const CastExpr *E); 10665 bool VisitUnaryOperator(const UnaryOperator *E); 10666 bool VisitBinaryOperator(const BinaryOperator *E); 10667 }; 10668 } // end anonymous namespace 10669 10670 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10671 /// produce either the integer value or a pointer. 10672 /// 10673 /// GCC has a heinous extension which folds casts between pointer types and 10674 /// pointer-sized integral types. We support this by allowing the evaluation of 10675 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10676 /// Some simple arithmetic on such values is supported (they are treated much 10677 /// like char*). 10678 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10679 EvalInfo &Info) { 10680 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10681 return IntExprEvaluator(Info, Result).Visit(E); 10682 } 10683 10684 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10685 APValue Val; 10686 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10687 return false; 10688 if (!Val.isInt()) { 10689 // FIXME: It would be better to produce the diagnostic for casting 10690 // a pointer to an integer. 10691 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10692 return false; 10693 } 10694 Result = Val.getInt(); 10695 return true; 10696 } 10697 10698 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10699 APValue Evaluated = E->EvaluateInContext( 10700 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10701 return Success(Evaluated, E); 10702 } 10703 10704 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10705 EvalInfo &Info) { 10706 if (E->getType()->isFixedPointType()) { 10707 APValue Val; 10708 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10709 return false; 10710 if (!Val.isFixedPoint()) 10711 return false; 10712 10713 Result = Val.getFixedPoint(); 10714 return true; 10715 } 10716 return false; 10717 } 10718 10719 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10720 EvalInfo &Info) { 10721 if (E->getType()->isIntegerType()) { 10722 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10723 APSInt Val; 10724 if (!EvaluateInteger(E, Val, Info)) 10725 return false; 10726 Result = APFixedPoint(Val, FXSema); 10727 return true; 10728 } else if (E->getType()->isFixedPointType()) { 10729 return EvaluateFixedPoint(E, Result, Info); 10730 } 10731 return false; 10732 } 10733 10734 /// Check whether the given declaration can be directly converted to an integral 10735 /// rvalue. If not, no diagnostic is produced; there are other things we can 10736 /// try. 10737 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10738 // Enums are integer constant exprs. 10739 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10740 // Check for signedness/width mismatches between E type and ECD value. 10741 bool SameSign = (ECD->getInitVal().isSigned() 10742 == E->getType()->isSignedIntegerOrEnumerationType()); 10743 bool SameWidth = (ECD->getInitVal().getBitWidth() 10744 == Info.Ctx.getIntWidth(E->getType())); 10745 if (SameSign && SameWidth) 10746 return Success(ECD->getInitVal(), E); 10747 else { 10748 // Get rid of mismatch (otherwise Success assertions will fail) 10749 // by computing a new value matching the type of E. 10750 llvm::APSInt Val = ECD->getInitVal(); 10751 if (!SameSign) 10752 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10753 if (!SameWidth) 10754 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10755 return Success(Val, E); 10756 } 10757 } 10758 return false; 10759 } 10760 10761 /// Values returned by __builtin_classify_type, chosen to match the values 10762 /// produced by GCC's builtin. 10763 enum class GCCTypeClass { 10764 None = -1, 10765 Void = 0, 10766 Integer = 1, 10767 // GCC reserves 2 for character types, but instead classifies them as 10768 // integers. 10769 Enum = 3, 10770 Bool = 4, 10771 Pointer = 5, 10772 // GCC reserves 6 for references, but appears to never use it (because 10773 // expressions never have reference type, presumably). 10774 PointerToDataMember = 7, 10775 RealFloat = 8, 10776 Complex = 9, 10777 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10778 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10779 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10780 // uses 12 for that purpose, same as for a class or struct. Maybe it 10781 // internally implements a pointer to member as a struct? Who knows. 10782 PointerToMemberFunction = 12, // Not a bug, see above. 10783 ClassOrStruct = 12, 10784 Union = 13, 10785 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10786 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10787 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10788 // literals. 10789 }; 10790 10791 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10792 /// as GCC. 10793 static GCCTypeClass 10794 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10795 assert(!T->isDependentType() && "unexpected dependent type"); 10796 10797 QualType CanTy = T.getCanonicalType(); 10798 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10799 10800 switch (CanTy->getTypeClass()) { 10801 #define TYPE(ID, BASE) 10802 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10803 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10804 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10805 #include "clang/AST/TypeNodes.inc" 10806 case Type::Auto: 10807 case Type::DeducedTemplateSpecialization: 10808 llvm_unreachable("unexpected non-canonical or dependent type"); 10809 10810 case Type::Builtin: 10811 switch (BT->getKind()) { 10812 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10813 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10814 case BuiltinType::ID: return GCCTypeClass::Integer; 10815 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10816 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10817 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10818 case BuiltinType::ID: break; 10819 #include "clang/AST/BuiltinTypes.def" 10820 case BuiltinType::Void: 10821 return GCCTypeClass::Void; 10822 10823 case BuiltinType::Bool: 10824 return GCCTypeClass::Bool; 10825 10826 case BuiltinType::Char_U: 10827 case BuiltinType::UChar: 10828 case BuiltinType::WChar_U: 10829 case BuiltinType::Char8: 10830 case BuiltinType::Char16: 10831 case BuiltinType::Char32: 10832 case BuiltinType::UShort: 10833 case BuiltinType::UInt: 10834 case BuiltinType::ULong: 10835 case BuiltinType::ULongLong: 10836 case BuiltinType::UInt128: 10837 return GCCTypeClass::Integer; 10838 10839 case BuiltinType::UShortAccum: 10840 case BuiltinType::UAccum: 10841 case BuiltinType::ULongAccum: 10842 case BuiltinType::UShortFract: 10843 case BuiltinType::UFract: 10844 case BuiltinType::ULongFract: 10845 case BuiltinType::SatUShortAccum: 10846 case BuiltinType::SatUAccum: 10847 case BuiltinType::SatULongAccum: 10848 case BuiltinType::SatUShortFract: 10849 case BuiltinType::SatUFract: 10850 case BuiltinType::SatULongFract: 10851 return GCCTypeClass::None; 10852 10853 case BuiltinType::NullPtr: 10854 10855 case BuiltinType::ObjCId: 10856 case BuiltinType::ObjCClass: 10857 case BuiltinType::ObjCSel: 10858 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10859 case BuiltinType::Id: 10860 #include "clang/Basic/OpenCLImageTypes.def" 10861 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10862 case BuiltinType::Id: 10863 #include "clang/Basic/OpenCLExtensionTypes.def" 10864 case BuiltinType::OCLSampler: 10865 case BuiltinType::OCLEvent: 10866 case BuiltinType::OCLClkEvent: 10867 case BuiltinType::OCLQueue: 10868 case BuiltinType::OCLReserveID: 10869 #define SVE_TYPE(Name, Id, SingletonId) \ 10870 case BuiltinType::Id: 10871 #include "clang/Basic/AArch64SVEACLETypes.def" 10872 return GCCTypeClass::None; 10873 10874 case BuiltinType::Dependent: 10875 llvm_unreachable("unexpected dependent type"); 10876 }; 10877 llvm_unreachable("unexpected placeholder type"); 10878 10879 case Type::Enum: 10880 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10881 10882 case Type::Pointer: 10883 case Type::ConstantArray: 10884 case Type::VariableArray: 10885 case Type::IncompleteArray: 10886 case Type::FunctionNoProto: 10887 case Type::FunctionProto: 10888 return GCCTypeClass::Pointer; 10889 10890 case Type::MemberPointer: 10891 return CanTy->isMemberDataPointerType() 10892 ? GCCTypeClass::PointerToDataMember 10893 : GCCTypeClass::PointerToMemberFunction; 10894 10895 case Type::Complex: 10896 return GCCTypeClass::Complex; 10897 10898 case Type::Record: 10899 return CanTy->isUnionType() ? GCCTypeClass::Union 10900 : GCCTypeClass::ClassOrStruct; 10901 10902 case Type::Atomic: 10903 // GCC classifies _Atomic T the same as T. 10904 return EvaluateBuiltinClassifyType( 10905 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10906 10907 case Type::BlockPointer: 10908 case Type::Vector: 10909 case Type::ExtVector: 10910 case Type::ConstantMatrix: 10911 case Type::ObjCObject: 10912 case Type::ObjCInterface: 10913 case Type::ObjCObjectPointer: 10914 case Type::Pipe: 10915 case Type::ExtInt: 10916 // GCC classifies vectors as None. We follow its lead and classify all 10917 // other types that don't fit into the regular classification the same way. 10918 return GCCTypeClass::None; 10919 10920 case Type::LValueReference: 10921 case Type::RValueReference: 10922 llvm_unreachable("invalid type for expression"); 10923 } 10924 10925 llvm_unreachable("unexpected type class"); 10926 } 10927 10928 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10929 /// as GCC. 10930 static GCCTypeClass 10931 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10932 // If no argument was supplied, default to None. This isn't 10933 // ideal, however it is what gcc does. 10934 if (E->getNumArgs() == 0) 10935 return GCCTypeClass::None; 10936 10937 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10938 // being an ICE, but still folds it to a constant using the type of the first 10939 // argument. 10940 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10941 } 10942 10943 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10944 /// __builtin_constant_p when applied to the given pointer. 10945 /// 10946 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10947 /// or it points to the first character of a string literal. 10948 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10949 APValue::LValueBase Base = LV.getLValueBase(); 10950 if (Base.isNull()) { 10951 // A null base is acceptable. 10952 return true; 10953 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10954 if (!isa<StringLiteral>(E)) 10955 return false; 10956 return LV.getLValueOffset().isZero(); 10957 } else if (Base.is<TypeInfoLValue>()) { 10958 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10959 // evaluate to true. 10960 return true; 10961 } else { 10962 // Any other base is not constant enough for GCC. 10963 return false; 10964 } 10965 } 10966 10967 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10968 /// GCC as we can manage. 10969 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10970 // This evaluation is not permitted to have side-effects, so evaluate it in 10971 // a speculative evaluation context. 10972 SpeculativeEvaluationRAII SpeculativeEval(Info); 10973 10974 // Constant-folding is always enabled for the operand of __builtin_constant_p 10975 // (even when the enclosing evaluation context otherwise requires a strict 10976 // language-specific constant expression). 10977 FoldConstant Fold(Info, true); 10978 10979 QualType ArgType = Arg->getType(); 10980 10981 // __builtin_constant_p always has one operand. The rules which gcc follows 10982 // are not precisely documented, but are as follows: 10983 // 10984 // - If the operand is of integral, floating, complex or enumeration type, 10985 // and can be folded to a known value of that type, it returns 1. 10986 // - If the operand can be folded to a pointer to the first character 10987 // of a string literal (or such a pointer cast to an integral type) 10988 // or to a null pointer or an integer cast to a pointer, it returns 1. 10989 // 10990 // Otherwise, it returns 0. 10991 // 10992 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10993 // its support for this did not work prior to GCC 9 and is not yet well 10994 // understood. 10995 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10996 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10997 ArgType->isNullPtrType()) { 10998 APValue V; 10999 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11000 Fold.keepDiagnostics(); 11001 return false; 11002 } 11003 11004 // For a pointer (possibly cast to integer), there are special rules. 11005 if (V.getKind() == APValue::LValue) 11006 return EvaluateBuiltinConstantPForLValue(V); 11007 11008 // Otherwise, any constant value is good enough. 11009 return V.hasValue(); 11010 } 11011 11012 // Anything else isn't considered to be sufficiently constant. 11013 return false; 11014 } 11015 11016 /// Retrieves the "underlying object type" of the given expression, 11017 /// as used by __builtin_object_size. 11018 static QualType getObjectType(APValue::LValueBase B) { 11019 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11020 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11021 return VD->getType(); 11022 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11023 if (isa<CompoundLiteralExpr>(E)) 11024 return E->getType(); 11025 } else if (B.is<TypeInfoLValue>()) { 11026 return B.getTypeInfoType(); 11027 } else if (B.is<DynamicAllocLValue>()) { 11028 return B.getDynamicAllocType(); 11029 } 11030 11031 return QualType(); 11032 } 11033 11034 /// A more selective version of E->IgnoreParenCasts for 11035 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11036 /// to change the type of E. 11037 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11038 /// 11039 /// Always returns an RValue with a pointer representation. 11040 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11041 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 11042 11043 auto *NoParens = E->IgnoreParens(); 11044 auto *Cast = dyn_cast<CastExpr>(NoParens); 11045 if (Cast == nullptr) 11046 return NoParens; 11047 11048 // We only conservatively allow a few kinds of casts, because this code is 11049 // inherently a simple solution that seeks to support the common case. 11050 auto CastKind = Cast->getCastKind(); 11051 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11052 CastKind != CK_AddressSpaceConversion) 11053 return NoParens; 11054 11055 auto *SubExpr = Cast->getSubExpr(); 11056 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 11057 return NoParens; 11058 return ignorePointerCastsAndParens(SubExpr); 11059 } 11060 11061 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11062 /// record layout. e.g. 11063 /// struct { struct { int a, b; } fst, snd; } obj; 11064 /// obj.fst // no 11065 /// obj.snd // yes 11066 /// obj.fst.a // no 11067 /// obj.fst.b // no 11068 /// obj.snd.a // no 11069 /// obj.snd.b // yes 11070 /// 11071 /// Please note: this function is specialized for how __builtin_object_size 11072 /// views "objects". 11073 /// 11074 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11075 /// correct result, it will always return true. 11076 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11077 assert(!LVal.Designator.Invalid); 11078 11079 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11080 const RecordDecl *Parent = FD->getParent(); 11081 Invalid = Parent->isInvalidDecl(); 11082 if (Invalid || Parent->isUnion()) 11083 return true; 11084 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11085 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11086 }; 11087 11088 auto &Base = LVal.getLValueBase(); 11089 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11090 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11091 bool Invalid; 11092 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11093 return Invalid; 11094 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11095 for (auto *FD : IFD->chain()) { 11096 bool Invalid; 11097 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11098 return Invalid; 11099 } 11100 } 11101 } 11102 11103 unsigned I = 0; 11104 QualType BaseType = getType(Base); 11105 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11106 // If we don't know the array bound, conservatively assume we're looking at 11107 // the final array element. 11108 ++I; 11109 if (BaseType->isIncompleteArrayType()) 11110 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11111 else 11112 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11113 } 11114 11115 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11116 const auto &Entry = LVal.Designator.Entries[I]; 11117 if (BaseType->isArrayType()) { 11118 // Because __builtin_object_size treats arrays as objects, we can ignore 11119 // the index iff this is the last array in the Designator. 11120 if (I + 1 == E) 11121 return true; 11122 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11123 uint64_t Index = Entry.getAsArrayIndex(); 11124 if (Index + 1 != CAT->getSize()) 11125 return false; 11126 BaseType = CAT->getElementType(); 11127 } else if (BaseType->isAnyComplexType()) { 11128 const auto *CT = BaseType->castAs<ComplexType>(); 11129 uint64_t Index = Entry.getAsArrayIndex(); 11130 if (Index != 1) 11131 return false; 11132 BaseType = CT->getElementType(); 11133 } else if (auto *FD = getAsField(Entry)) { 11134 bool Invalid; 11135 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11136 return Invalid; 11137 BaseType = FD->getType(); 11138 } else { 11139 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11140 return false; 11141 } 11142 } 11143 return true; 11144 } 11145 11146 /// Tests to see if the LValue has a user-specified designator (that isn't 11147 /// necessarily valid). Note that this always returns 'true' if the LValue has 11148 /// an unsized array as its first designator entry, because there's currently no 11149 /// way to tell if the user typed *foo or foo[0]. 11150 static bool refersToCompleteObject(const LValue &LVal) { 11151 if (LVal.Designator.Invalid) 11152 return false; 11153 11154 if (!LVal.Designator.Entries.empty()) 11155 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11156 11157 if (!LVal.InvalidBase) 11158 return true; 11159 11160 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11161 // the LValueBase. 11162 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11163 return !E || !isa<MemberExpr>(E); 11164 } 11165 11166 /// Attempts to detect a user writing into a piece of memory that's impossible 11167 /// to figure out the size of by just using types. 11168 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11169 const SubobjectDesignator &Designator = LVal.Designator; 11170 // Notes: 11171 // - Users can only write off of the end when we have an invalid base. Invalid 11172 // bases imply we don't know where the memory came from. 11173 // - We used to be a bit more aggressive here; we'd only be conservative if 11174 // the array at the end was flexible, or if it had 0 or 1 elements. This 11175 // broke some common standard library extensions (PR30346), but was 11176 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11177 // with some sort of list. OTOH, it seems that GCC is always 11178 // conservative with the last element in structs (if it's an array), so our 11179 // current behavior is more compatible than an explicit list approach would 11180 // be. 11181 return LVal.InvalidBase && 11182 Designator.Entries.size() == Designator.MostDerivedPathLength && 11183 Designator.MostDerivedIsArrayElement && 11184 isDesignatorAtObjectEnd(Ctx, LVal); 11185 } 11186 11187 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11188 /// Fails if the conversion would cause loss of precision. 11189 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11190 CharUnits &Result) { 11191 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11192 if (Int.ugt(CharUnitsMax)) 11193 return false; 11194 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11195 return true; 11196 } 11197 11198 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11199 /// determine how many bytes exist from the beginning of the object to either 11200 /// the end of the current subobject, or the end of the object itself, depending 11201 /// on what the LValue looks like + the value of Type. 11202 /// 11203 /// If this returns false, the value of Result is undefined. 11204 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11205 unsigned Type, const LValue &LVal, 11206 CharUnits &EndOffset) { 11207 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11208 11209 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11210 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11211 return false; 11212 return HandleSizeof(Info, ExprLoc, Ty, Result); 11213 }; 11214 11215 // We want to evaluate the size of the entire object. This is a valid fallback 11216 // for when Type=1 and the designator is invalid, because we're asked for an 11217 // upper-bound. 11218 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11219 // Type=3 wants a lower bound, so we can't fall back to this. 11220 if (Type == 3 && !DetermineForCompleteObject) 11221 return false; 11222 11223 llvm::APInt APEndOffset; 11224 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11225 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11226 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11227 11228 if (LVal.InvalidBase) 11229 return false; 11230 11231 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11232 return CheckedHandleSizeof(BaseTy, EndOffset); 11233 } 11234 11235 // We want to evaluate the size of a subobject. 11236 const SubobjectDesignator &Designator = LVal.Designator; 11237 11238 // The following is a moderately common idiom in C: 11239 // 11240 // struct Foo { int a; char c[1]; }; 11241 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11242 // strcpy(&F->c[0], Bar); 11243 // 11244 // In order to not break too much legacy code, we need to support it. 11245 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11246 // If we can resolve this to an alloc_size call, we can hand that back, 11247 // because we know for certain how many bytes there are to write to. 11248 llvm::APInt APEndOffset; 11249 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11250 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11251 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11252 11253 // If we cannot determine the size of the initial allocation, then we can't 11254 // given an accurate upper-bound. However, we are still able to give 11255 // conservative lower-bounds for Type=3. 11256 if (Type == 1) 11257 return false; 11258 } 11259 11260 CharUnits BytesPerElem; 11261 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11262 return false; 11263 11264 // According to the GCC documentation, we want the size of the subobject 11265 // denoted by the pointer. But that's not quite right -- what we actually 11266 // want is the size of the immediately-enclosing array, if there is one. 11267 int64_t ElemsRemaining; 11268 if (Designator.MostDerivedIsArrayElement && 11269 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11270 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11271 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11272 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11273 } else { 11274 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11275 } 11276 11277 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11278 return true; 11279 } 11280 11281 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11282 /// returns true and stores the result in @p Size. 11283 /// 11284 /// If @p WasError is non-null, this will report whether the failure to evaluate 11285 /// is to be treated as an Error in IntExprEvaluator. 11286 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11287 EvalInfo &Info, uint64_t &Size) { 11288 // Determine the denoted object. 11289 LValue LVal; 11290 { 11291 // The operand of __builtin_object_size is never evaluated for side-effects. 11292 // If there are any, but we can determine the pointed-to object anyway, then 11293 // ignore the side-effects. 11294 SpeculativeEvaluationRAII SpeculativeEval(Info); 11295 IgnoreSideEffectsRAII Fold(Info); 11296 11297 if (E->isGLValue()) { 11298 // It's possible for us to be given GLValues if we're called via 11299 // Expr::tryEvaluateObjectSize. 11300 APValue RVal; 11301 if (!EvaluateAsRValue(Info, E, RVal)) 11302 return false; 11303 LVal.setFrom(Info.Ctx, RVal); 11304 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11305 /*InvalidBaseOK=*/true)) 11306 return false; 11307 } 11308 11309 // If we point to before the start of the object, there are no accessible 11310 // bytes. 11311 if (LVal.getLValueOffset().isNegative()) { 11312 Size = 0; 11313 return true; 11314 } 11315 11316 CharUnits EndOffset; 11317 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11318 return false; 11319 11320 // If we've fallen outside of the end offset, just pretend there's nothing to 11321 // write to/read from. 11322 if (EndOffset <= LVal.getLValueOffset()) 11323 Size = 0; 11324 else 11325 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11326 return true; 11327 } 11328 11329 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11330 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11331 return VisitBuiltinCallExpr(E, BuiltinOp); 11332 11333 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11334 } 11335 11336 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11337 APValue &Val, APSInt &Alignment) { 11338 QualType SrcTy = E->getArg(0)->getType(); 11339 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11340 return false; 11341 // Even though we are evaluating integer expressions we could get a pointer 11342 // argument for the __builtin_is_aligned() case. 11343 if (SrcTy->isPointerType()) { 11344 LValue Ptr; 11345 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11346 return false; 11347 Ptr.moveInto(Val); 11348 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11349 Info.FFDiag(E->getArg(0)); 11350 return false; 11351 } else { 11352 APSInt SrcInt; 11353 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11354 return false; 11355 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11356 "Bit widths must be the same"); 11357 Val = APValue(SrcInt); 11358 } 11359 assert(Val.hasValue()); 11360 return true; 11361 } 11362 11363 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11364 unsigned BuiltinOp) { 11365 switch (BuiltinOp) { 11366 default: 11367 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11368 11369 case Builtin::BI__builtin_dynamic_object_size: 11370 case Builtin::BI__builtin_object_size: { 11371 // The type was checked when we built the expression. 11372 unsigned Type = 11373 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11374 assert(Type <= 3 && "unexpected type"); 11375 11376 uint64_t Size; 11377 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11378 return Success(Size, E); 11379 11380 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11381 return Success((Type & 2) ? 0 : -1, E); 11382 11383 // Expression had no side effects, but we couldn't statically determine the 11384 // size of the referenced object. 11385 switch (Info.EvalMode) { 11386 case EvalInfo::EM_ConstantExpression: 11387 case EvalInfo::EM_ConstantFold: 11388 case EvalInfo::EM_IgnoreSideEffects: 11389 // Leave it to IR generation. 11390 return Error(E); 11391 case EvalInfo::EM_ConstantExpressionUnevaluated: 11392 // Reduce it to a constant now. 11393 return Success((Type & 2) ? 0 : -1, E); 11394 } 11395 11396 llvm_unreachable("unexpected EvalMode"); 11397 } 11398 11399 case Builtin::BI__builtin_os_log_format_buffer_size: { 11400 analyze_os_log::OSLogBufferLayout Layout; 11401 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11402 return Success(Layout.size().getQuantity(), E); 11403 } 11404 11405 case Builtin::BI__builtin_is_aligned: { 11406 APValue Src; 11407 APSInt Alignment; 11408 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11409 return false; 11410 if (Src.isLValue()) { 11411 // If we evaluated a pointer, check the minimum known alignment. 11412 LValue Ptr; 11413 Ptr.setFrom(Info.Ctx, Src); 11414 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11415 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11416 // We can return true if the known alignment at the computed offset is 11417 // greater than the requested alignment. 11418 assert(PtrAlign.isPowerOfTwo()); 11419 assert(Alignment.isPowerOf2()); 11420 if (PtrAlign.getQuantity() >= Alignment) 11421 return Success(1, E); 11422 // If the alignment is not known to be sufficient, some cases could still 11423 // be aligned at run time. However, if the requested alignment is less or 11424 // equal to the base alignment and the offset is not aligned, we know that 11425 // the run-time value can never be aligned. 11426 if (BaseAlignment.getQuantity() >= Alignment && 11427 PtrAlign.getQuantity() < Alignment) 11428 return Success(0, E); 11429 // Otherwise we can't infer whether the value is sufficiently aligned. 11430 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11431 // in cases where we can't fully evaluate the pointer. 11432 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11433 << Alignment; 11434 return false; 11435 } 11436 assert(Src.isInt()); 11437 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11438 } 11439 case Builtin::BI__builtin_align_up: { 11440 APValue Src; 11441 APSInt Alignment; 11442 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11443 return false; 11444 if (!Src.isInt()) 11445 return Error(E); 11446 APSInt AlignedVal = 11447 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11448 Src.getInt().isUnsigned()); 11449 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11450 return Success(AlignedVal, E); 11451 } 11452 case Builtin::BI__builtin_align_down: { 11453 APValue Src; 11454 APSInt Alignment; 11455 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11456 return false; 11457 if (!Src.isInt()) 11458 return Error(E); 11459 APSInt AlignedVal = 11460 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11461 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11462 return Success(AlignedVal, E); 11463 } 11464 11465 case Builtin::BI__builtin_bitreverse8: 11466 case Builtin::BI__builtin_bitreverse16: 11467 case Builtin::BI__builtin_bitreverse32: 11468 case Builtin::BI__builtin_bitreverse64: { 11469 APSInt Val; 11470 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11471 return false; 11472 11473 return Success(Val.reverseBits(), E); 11474 } 11475 11476 case Builtin::BI__builtin_bswap16: 11477 case Builtin::BI__builtin_bswap32: 11478 case Builtin::BI__builtin_bswap64: { 11479 APSInt Val; 11480 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11481 return false; 11482 11483 return Success(Val.byteSwap(), E); 11484 } 11485 11486 case Builtin::BI__builtin_classify_type: 11487 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11488 11489 case Builtin::BI__builtin_clrsb: 11490 case Builtin::BI__builtin_clrsbl: 11491 case Builtin::BI__builtin_clrsbll: { 11492 APSInt Val; 11493 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11494 return false; 11495 11496 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11497 } 11498 11499 case Builtin::BI__builtin_clz: 11500 case Builtin::BI__builtin_clzl: 11501 case Builtin::BI__builtin_clzll: 11502 case Builtin::BI__builtin_clzs: { 11503 APSInt Val; 11504 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11505 return false; 11506 if (!Val) 11507 return Error(E); 11508 11509 return Success(Val.countLeadingZeros(), E); 11510 } 11511 11512 case Builtin::BI__builtin_constant_p: { 11513 const Expr *Arg = E->getArg(0); 11514 if (EvaluateBuiltinConstantP(Info, Arg)) 11515 return Success(true, E); 11516 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11517 // Outside a constant context, eagerly evaluate to false in the presence 11518 // of side-effects in order to avoid -Wunsequenced false-positives in 11519 // a branch on __builtin_constant_p(expr). 11520 return Success(false, E); 11521 } 11522 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11523 return false; 11524 } 11525 11526 case Builtin::BI__builtin_is_constant_evaluated: { 11527 const auto *Callee = Info.CurrentCall->getCallee(); 11528 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11529 (Info.CallStackDepth == 1 || 11530 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11531 Callee->getIdentifier() && 11532 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11533 // FIXME: Find a better way to avoid duplicated diagnostics. 11534 if (Info.EvalStatus.Diag) 11535 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11536 : Info.CurrentCall->CallLoc, 11537 diag::warn_is_constant_evaluated_always_true_constexpr) 11538 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11539 : "std::is_constant_evaluated"); 11540 } 11541 11542 return Success(Info.InConstantContext, E); 11543 } 11544 11545 case Builtin::BI__builtin_ctz: 11546 case Builtin::BI__builtin_ctzl: 11547 case Builtin::BI__builtin_ctzll: 11548 case Builtin::BI__builtin_ctzs: { 11549 APSInt Val; 11550 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11551 return false; 11552 if (!Val) 11553 return Error(E); 11554 11555 return Success(Val.countTrailingZeros(), E); 11556 } 11557 11558 case Builtin::BI__builtin_eh_return_data_regno: { 11559 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11560 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11561 return Success(Operand, E); 11562 } 11563 11564 case Builtin::BI__builtin_expect: 11565 case Builtin::BI__builtin_expect_with_probability: 11566 return Visit(E->getArg(0)); 11567 11568 case Builtin::BI__builtin_ffs: 11569 case Builtin::BI__builtin_ffsl: 11570 case Builtin::BI__builtin_ffsll: { 11571 APSInt Val; 11572 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11573 return false; 11574 11575 unsigned N = Val.countTrailingZeros(); 11576 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11577 } 11578 11579 case Builtin::BI__builtin_fpclassify: { 11580 APFloat Val(0.0); 11581 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11582 return false; 11583 unsigned Arg; 11584 switch (Val.getCategory()) { 11585 case APFloat::fcNaN: Arg = 0; break; 11586 case APFloat::fcInfinity: Arg = 1; break; 11587 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11588 case APFloat::fcZero: Arg = 4; break; 11589 } 11590 return Visit(E->getArg(Arg)); 11591 } 11592 11593 case Builtin::BI__builtin_isinf_sign: { 11594 APFloat Val(0.0); 11595 return EvaluateFloat(E->getArg(0), Val, Info) && 11596 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11597 } 11598 11599 case Builtin::BI__builtin_isinf: { 11600 APFloat Val(0.0); 11601 return EvaluateFloat(E->getArg(0), Val, Info) && 11602 Success(Val.isInfinity() ? 1 : 0, E); 11603 } 11604 11605 case Builtin::BI__builtin_isfinite: { 11606 APFloat Val(0.0); 11607 return EvaluateFloat(E->getArg(0), Val, Info) && 11608 Success(Val.isFinite() ? 1 : 0, E); 11609 } 11610 11611 case Builtin::BI__builtin_isnan: { 11612 APFloat Val(0.0); 11613 return EvaluateFloat(E->getArg(0), Val, Info) && 11614 Success(Val.isNaN() ? 1 : 0, E); 11615 } 11616 11617 case Builtin::BI__builtin_isnormal: { 11618 APFloat Val(0.0); 11619 return EvaluateFloat(E->getArg(0), Val, Info) && 11620 Success(Val.isNormal() ? 1 : 0, E); 11621 } 11622 11623 case Builtin::BI__builtin_parity: 11624 case Builtin::BI__builtin_parityl: 11625 case Builtin::BI__builtin_parityll: { 11626 APSInt Val; 11627 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11628 return false; 11629 11630 return Success(Val.countPopulation() % 2, E); 11631 } 11632 11633 case Builtin::BI__builtin_popcount: 11634 case Builtin::BI__builtin_popcountl: 11635 case Builtin::BI__builtin_popcountll: { 11636 APSInt Val; 11637 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11638 return false; 11639 11640 return Success(Val.countPopulation(), E); 11641 } 11642 11643 case Builtin::BI__builtin_rotateleft8: 11644 case Builtin::BI__builtin_rotateleft16: 11645 case Builtin::BI__builtin_rotateleft32: 11646 case Builtin::BI__builtin_rotateleft64: 11647 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11648 case Builtin::BI_rotl16: 11649 case Builtin::BI_rotl: 11650 case Builtin::BI_lrotl: 11651 case Builtin::BI_rotl64: { 11652 APSInt Val, Amt; 11653 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11654 !EvaluateInteger(E->getArg(1), Amt, Info)) 11655 return false; 11656 11657 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11658 } 11659 11660 case Builtin::BI__builtin_rotateright8: 11661 case Builtin::BI__builtin_rotateright16: 11662 case Builtin::BI__builtin_rotateright32: 11663 case Builtin::BI__builtin_rotateright64: 11664 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11665 case Builtin::BI_rotr16: 11666 case Builtin::BI_rotr: 11667 case Builtin::BI_lrotr: 11668 case Builtin::BI_rotr64: { 11669 APSInt Val, Amt; 11670 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11671 !EvaluateInteger(E->getArg(1), Amt, Info)) 11672 return false; 11673 11674 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11675 } 11676 11677 case Builtin::BIstrlen: 11678 case Builtin::BIwcslen: 11679 // A call to strlen is not a constant expression. 11680 if (Info.getLangOpts().CPlusPlus11) 11681 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11682 << /*isConstexpr*/0 << /*isConstructor*/0 11683 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11684 else 11685 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11686 LLVM_FALLTHROUGH; 11687 case Builtin::BI__builtin_strlen: 11688 case Builtin::BI__builtin_wcslen: { 11689 // As an extension, we support __builtin_strlen() as a constant expression, 11690 // and support folding strlen() to a constant. 11691 LValue String; 11692 if (!EvaluatePointer(E->getArg(0), String, Info)) 11693 return false; 11694 11695 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11696 11697 // Fast path: if it's a string literal, search the string value. 11698 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11699 String.getLValueBase().dyn_cast<const Expr *>())) { 11700 // The string literal may have embedded null characters. Find the first 11701 // one and truncate there. 11702 StringRef Str = S->getBytes(); 11703 int64_t Off = String.Offset.getQuantity(); 11704 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11705 S->getCharByteWidth() == 1 && 11706 // FIXME: Add fast-path for wchar_t too. 11707 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11708 Str = Str.substr(Off); 11709 11710 StringRef::size_type Pos = Str.find(0); 11711 if (Pos != StringRef::npos) 11712 Str = Str.substr(0, Pos); 11713 11714 return Success(Str.size(), E); 11715 } 11716 11717 // Fall through to slow path to issue appropriate diagnostic. 11718 } 11719 11720 // Slow path: scan the bytes of the string looking for the terminating 0. 11721 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11722 APValue Char; 11723 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11724 !Char.isInt()) 11725 return false; 11726 if (!Char.getInt()) 11727 return Success(Strlen, E); 11728 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11729 return false; 11730 } 11731 } 11732 11733 case Builtin::BIstrcmp: 11734 case Builtin::BIwcscmp: 11735 case Builtin::BIstrncmp: 11736 case Builtin::BIwcsncmp: 11737 case Builtin::BImemcmp: 11738 case Builtin::BIbcmp: 11739 case Builtin::BIwmemcmp: 11740 // A call to strlen is not a constant expression. 11741 if (Info.getLangOpts().CPlusPlus11) 11742 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11743 << /*isConstexpr*/0 << /*isConstructor*/0 11744 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11745 else 11746 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11747 LLVM_FALLTHROUGH; 11748 case Builtin::BI__builtin_strcmp: 11749 case Builtin::BI__builtin_wcscmp: 11750 case Builtin::BI__builtin_strncmp: 11751 case Builtin::BI__builtin_wcsncmp: 11752 case Builtin::BI__builtin_memcmp: 11753 case Builtin::BI__builtin_bcmp: 11754 case Builtin::BI__builtin_wmemcmp: { 11755 LValue String1, String2; 11756 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11757 !EvaluatePointer(E->getArg(1), String2, Info)) 11758 return false; 11759 11760 uint64_t MaxLength = uint64_t(-1); 11761 if (BuiltinOp != Builtin::BIstrcmp && 11762 BuiltinOp != Builtin::BIwcscmp && 11763 BuiltinOp != Builtin::BI__builtin_strcmp && 11764 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11765 APSInt N; 11766 if (!EvaluateInteger(E->getArg(2), N, Info)) 11767 return false; 11768 MaxLength = N.getExtValue(); 11769 } 11770 11771 // Empty substrings compare equal by definition. 11772 if (MaxLength == 0u) 11773 return Success(0, E); 11774 11775 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11776 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11777 String1.Designator.Invalid || String2.Designator.Invalid) 11778 return false; 11779 11780 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11781 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11782 11783 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11784 BuiltinOp == Builtin::BIbcmp || 11785 BuiltinOp == Builtin::BI__builtin_memcmp || 11786 BuiltinOp == Builtin::BI__builtin_bcmp; 11787 11788 assert(IsRawByte || 11789 (Info.Ctx.hasSameUnqualifiedType( 11790 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11791 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11792 11793 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11794 // 'char8_t', but no other types. 11795 if (IsRawByte && 11796 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11797 // FIXME: Consider using our bit_cast implementation to support this. 11798 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11799 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11800 << CharTy1 << CharTy2; 11801 return false; 11802 } 11803 11804 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11805 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11806 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11807 Char1.isInt() && Char2.isInt(); 11808 }; 11809 const auto &AdvanceElems = [&] { 11810 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11811 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11812 }; 11813 11814 bool StopAtNull = 11815 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11816 BuiltinOp != Builtin::BIwmemcmp && 11817 BuiltinOp != Builtin::BI__builtin_memcmp && 11818 BuiltinOp != Builtin::BI__builtin_bcmp && 11819 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11820 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11821 BuiltinOp == Builtin::BIwcsncmp || 11822 BuiltinOp == Builtin::BIwmemcmp || 11823 BuiltinOp == Builtin::BI__builtin_wcscmp || 11824 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11825 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11826 11827 for (; MaxLength; --MaxLength) { 11828 APValue Char1, Char2; 11829 if (!ReadCurElems(Char1, Char2)) 11830 return false; 11831 if (Char1.getInt().ne(Char2.getInt())) { 11832 if (IsWide) // wmemcmp compares with wchar_t signedness. 11833 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11834 // memcmp always compares unsigned chars. 11835 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11836 } 11837 if (StopAtNull && !Char1.getInt()) 11838 return Success(0, E); 11839 assert(!(StopAtNull && !Char2.getInt())); 11840 if (!AdvanceElems()) 11841 return false; 11842 } 11843 // We hit the strncmp / memcmp limit. 11844 return Success(0, E); 11845 } 11846 11847 case Builtin::BI__atomic_always_lock_free: 11848 case Builtin::BI__atomic_is_lock_free: 11849 case Builtin::BI__c11_atomic_is_lock_free: { 11850 APSInt SizeVal; 11851 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11852 return false; 11853 11854 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11855 // of two less than or equal to the maximum inline atomic width, we know it 11856 // is lock-free. If the size isn't a power of two, or greater than the 11857 // maximum alignment where we promote atomics, we know it is not lock-free 11858 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11859 // the answer can only be determined at runtime; for example, 16-byte 11860 // atomics have lock-free implementations on some, but not all, 11861 // x86-64 processors. 11862 11863 // Check power-of-two. 11864 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11865 if (Size.isPowerOfTwo()) { 11866 // Check against inlining width. 11867 unsigned InlineWidthBits = 11868 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11869 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11870 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11871 Size == CharUnits::One() || 11872 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11873 Expr::NPC_NeverValueDependent)) 11874 // OK, we will inline appropriately-aligned operations of this size, 11875 // and _Atomic(T) is appropriately-aligned. 11876 return Success(1, E); 11877 11878 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11879 castAs<PointerType>()->getPointeeType(); 11880 if (!PointeeType->isIncompleteType() && 11881 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11882 // OK, we will inline operations on this object. 11883 return Success(1, E); 11884 } 11885 } 11886 } 11887 11888 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11889 Success(0, E) : Error(E); 11890 } 11891 case Builtin::BIomp_is_initial_device: 11892 // We can decide statically which value the runtime would return if called. 11893 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11894 case Builtin::BI__builtin_add_overflow: 11895 case Builtin::BI__builtin_sub_overflow: 11896 case Builtin::BI__builtin_mul_overflow: 11897 case Builtin::BI__builtin_sadd_overflow: 11898 case Builtin::BI__builtin_uadd_overflow: 11899 case Builtin::BI__builtin_uaddl_overflow: 11900 case Builtin::BI__builtin_uaddll_overflow: 11901 case Builtin::BI__builtin_usub_overflow: 11902 case Builtin::BI__builtin_usubl_overflow: 11903 case Builtin::BI__builtin_usubll_overflow: 11904 case Builtin::BI__builtin_umul_overflow: 11905 case Builtin::BI__builtin_umull_overflow: 11906 case Builtin::BI__builtin_umulll_overflow: 11907 case Builtin::BI__builtin_saddl_overflow: 11908 case Builtin::BI__builtin_saddll_overflow: 11909 case Builtin::BI__builtin_ssub_overflow: 11910 case Builtin::BI__builtin_ssubl_overflow: 11911 case Builtin::BI__builtin_ssubll_overflow: 11912 case Builtin::BI__builtin_smul_overflow: 11913 case Builtin::BI__builtin_smull_overflow: 11914 case Builtin::BI__builtin_smulll_overflow: { 11915 LValue ResultLValue; 11916 APSInt LHS, RHS; 11917 11918 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11919 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11920 !EvaluateInteger(E->getArg(1), RHS, Info) || 11921 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11922 return false; 11923 11924 APSInt Result; 11925 bool DidOverflow = false; 11926 11927 // If the types don't have to match, enlarge all 3 to the largest of them. 11928 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11929 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11930 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11931 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11932 ResultType->isSignedIntegerOrEnumerationType(); 11933 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11934 ResultType->isSignedIntegerOrEnumerationType(); 11935 uint64_t LHSSize = LHS.getBitWidth(); 11936 uint64_t RHSSize = RHS.getBitWidth(); 11937 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11938 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11939 11940 // Add an additional bit if the signedness isn't uniformly agreed to. We 11941 // could do this ONLY if there is a signed and an unsigned that both have 11942 // MaxBits, but the code to check that is pretty nasty. The issue will be 11943 // caught in the shrink-to-result later anyway. 11944 if (IsSigned && !AllSigned) 11945 ++MaxBits; 11946 11947 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11948 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11949 Result = APSInt(MaxBits, !IsSigned); 11950 } 11951 11952 // Find largest int. 11953 switch (BuiltinOp) { 11954 default: 11955 llvm_unreachable("Invalid value for BuiltinOp"); 11956 case Builtin::BI__builtin_add_overflow: 11957 case Builtin::BI__builtin_sadd_overflow: 11958 case Builtin::BI__builtin_saddl_overflow: 11959 case Builtin::BI__builtin_saddll_overflow: 11960 case Builtin::BI__builtin_uadd_overflow: 11961 case Builtin::BI__builtin_uaddl_overflow: 11962 case Builtin::BI__builtin_uaddll_overflow: 11963 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11964 : LHS.uadd_ov(RHS, DidOverflow); 11965 break; 11966 case Builtin::BI__builtin_sub_overflow: 11967 case Builtin::BI__builtin_ssub_overflow: 11968 case Builtin::BI__builtin_ssubl_overflow: 11969 case Builtin::BI__builtin_ssubll_overflow: 11970 case Builtin::BI__builtin_usub_overflow: 11971 case Builtin::BI__builtin_usubl_overflow: 11972 case Builtin::BI__builtin_usubll_overflow: 11973 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11974 : LHS.usub_ov(RHS, DidOverflow); 11975 break; 11976 case Builtin::BI__builtin_mul_overflow: 11977 case Builtin::BI__builtin_smul_overflow: 11978 case Builtin::BI__builtin_smull_overflow: 11979 case Builtin::BI__builtin_smulll_overflow: 11980 case Builtin::BI__builtin_umul_overflow: 11981 case Builtin::BI__builtin_umull_overflow: 11982 case Builtin::BI__builtin_umulll_overflow: 11983 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11984 : LHS.umul_ov(RHS, DidOverflow); 11985 break; 11986 } 11987 11988 // In the case where multiple sizes are allowed, truncate and see if 11989 // the values are the same. 11990 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11991 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11992 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11993 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11994 // since it will give us the behavior of a TruncOrSelf in the case where 11995 // its parameter <= its size. We previously set Result to be at least the 11996 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11997 // will work exactly like TruncOrSelf. 11998 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11999 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12000 12001 if (!APSInt::isSameValue(Temp, Result)) 12002 DidOverflow = true; 12003 Result = Temp; 12004 } 12005 12006 APValue APV{Result}; 12007 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12008 return false; 12009 return Success(DidOverflow, E); 12010 } 12011 } 12012 } 12013 12014 /// Determine whether this is a pointer past the end of the complete 12015 /// object referred to by the lvalue. 12016 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12017 const LValue &LV) { 12018 // A null pointer can be viewed as being "past the end" but we don't 12019 // choose to look at it that way here. 12020 if (!LV.getLValueBase()) 12021 return false; 12022 12023 // If the designator is valid and refers to a subobject, we're not pointing 12024 // past the end. 12025 if (!LV.getLValueDesignator().Invalid && 12026 !LV.getLValueDesignator().isOnePastTheEnd()) 12027 return false; 12028 12029 // A pointer to an incomplete type might be past-the-end if the type's size is 12030 // zero. We cannot tell because the type is incomplete. 12031 QualType Ty = getType(LV.getLValueBase()); 12032 if (Ty->isIncompleteType()) 12033 return true; 12034 12035 // We're a past-the-end pointer if we point to the byte after the object, 12036 // no matter what our type or path is. 12037 auto Size = Ctx.getTypeSizeInChars(Ty); 12038 return LV.getLValueOffset() == Size; 12039 } 12040 12041 namespace { 12042 12043 /// Data recursive integer evaluator of certain binary operators. 12044 /// 12045 /// We use a data recursive algorithm for binary operators so that we are able 12046 /// to handle extreme cases of chained binary operators without causing stack 12047 /// overflow. 12048 class DataRecursiveIntBinOpEvaluator { 12049 struct EvalResult { 12050 APValue Val; 12051 bool Failed; 12052 12053 EvalResult() : Failed(false) { } 12054 12055 void swap(EvalResult &RHS) { 12056 Val.swap(RHS.Val); 12057 Failed = RHS.Failed; 12058 RHS.Failed = false; 12059 } 12060 }; 12061 12062 struct Job { 12063 const Expr *E; 12064 EvalResult LHSResult; // meaningful only for binary operator expression. 12065 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12066 12067 Job() = default; 12068 Job(Job &&) = default; 12069 12070 void startSpeculativeEval(EvalInfo &Info) { 12071 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12072 } 12073 12074 private: 12075 SpeculativeEvaluationRAII SpecEvalRAII; 12076 }; 12077 12078 SmallVector<Job, 16> Queue; 12079 12080 IntExprEvaluator &IntEval; 12081 EvalInfo &Info; 12082 APValue &FinalResult; 12083 12084 public: 12085 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12086 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12087 12088 /// True if \param E is a binary operator that we are going to handle 12089 /// data recursively. 12090 /// We handle binary operators that are comma, logical, or that have operands 12091 /// with integral or enumeration type. 12092 static bool shouldEnqueue(const BinaryOperator *E) { 12093 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12094 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 12095 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12096 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12097 } 12098 12099 bool Traverse(const BinaryOperator *E) { 12100 enqueue(E); 12101 EvalResult PrevResult; 12102 while (!Queue.empty()) 12103 process(PrevResult); 12104 12105 if (PrevResult.Failed) return false; 12106 12107 FinalResult.swap(PrevResult.Val); 12108 return true; 12109 } 12110 12111 private: 12112 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12113 return IntEval.Success(Value, E, Result); 12114 } 12115 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12116 return IntEval.Success(Value, E, Result); 12117 } 12118 bool Error(const Expr *E) { 12119 return IntEval.Error(E); 12120 } 12121 bool Error(const Expr *E, diag::kind D) { 12122 return IntEval.Error(E, D); 12123 } 12124 12125 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12126 return Info.CCEDiag(E, D); 12127 } 12128 12129 // Returns true if visiting the RHS is necessary, false otherwise. 12130 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12131 bool &SuppressRHSDiags); 12132 12133 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12134 const BinaryOperator *E, APValue &Result); 12135 12136 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12137 Result.Failed = !Evaluate(Result.Val, Info, E); 12138 if (Result.Failed) 12139 Result.Val = APValue(); 12140 } 12141 12142 void process(EvalResult &Result); 12143 12144 void enqueue(const Expr *E) { 12145 E = E->IgnoreParens(); 12146 Queue.resize(Queue.size()+1); 12147 Queue.back().E = E; 12148 Queue.back().Kind = Job::AnyExprKind; 12149 } 12150 }; 12151 12152 } 12153 12154 bool DataRecursiveIntBinOpEvaluator:: 12155 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12156 bool &SuppressRHSDiags) { 12157 if (E->getOpcode() == BO_Comma) { 12158 // Ignore LHS but note if we could not evaluate it. 12159 if (LHSResult.Failed) 12160 return Info.noteSideEffect(); 12161 return true; 12162 } 12163 12164 if (E->isLogicalOp()) { 12165 bool LHSAsBool; 12166 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12167 // We were able to evaluate the LHS, see if we can get away with not 12168 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12169 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12170 Success(LHSAsBool, E, LHSResult.Val); 12171 return false; // Ignore RHS 12172 } 12173 } else { 12174 LHSResult.Failed = true; 12175 12176 // Since we weren't able to evaluate the left hand side, it 12177 // might have had side effects. 12178 if (!Info.noteSideEffect()) 12179 return false; 12180 12181 // We can't evaluate the LHS; however, sometimes the result 12182 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12183 // Don't ignore RHS and suppress diagnostics from this arm. 12184 SuppressRHSDiags = true; 12185 } 12186 12187 return true; 12188 } 12189 12190 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12191 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12192 12193 if (LHSResult.Failed && !Info.noteFailure()) 12194 return false; // Ignore RHS; 12195 12196 return true; 12197 } 12198 12199 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12200 bool IsSub) { 12201 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12202 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12203 // offsets. 12204 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12205 CharUnits &Offset = LVal.getLValueOffset(); 12206 uint64_t Offset64 = Offset.getQuantity(); 12207 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12208 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12209 : Offset64 + Index64); 12210 } 12211 12212 bool DataRecursiveIntBinOpEvaluator:: 12213 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12214 const BinaryOperator *E, APValue &Result) { 12215 if (E->getOpcode() == BO_Comma) { 12216 if (RHSResult.Failed) 12217 return false; 12218 Result = RHSResult.Val; 12219 return true; 12220 } 12221 12222 if (E->isLogicalOp()) { 12223 bool lhsResult, rhsResult; 12224 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12225 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12226 12227 if (LHSIsOK) { 12228 if (RHSIsOK) { 12229 if (E->getOpcode() == BO_LOr) 12230 return Success(lhsResult || rhsResult, E, Result); 12231 else 12232 return Success(lhsResult && rhsResult, E, Result); 12233 } 12234 } else { 12235 if (RHSIsOK) { 12236 // We can't evaluate the LHS; however, sometimes the result 12237 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12238 if (rhsResult == (E->getOpcode() == BO_LOr)) 12239 return Success(rhsResult, E, Result); 12240 } 12241 } 12242 12243 return false; 12244 } 12245 12246 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12247 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12248 12249 if (LHSResult.Failed || RHSResult.Failed) 12250 return false; 12251 12252 const APValue &LHSVal = LHSResult.Val; 12253 const APValue &RHSVal = RHSResult.Val; 12254 12255 // Handle cases like (unsigned long)&a + 4. 12256 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12257 Result = LHSVal; 12258 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12259 return true; 12260 } 12261 12262 // Handle cases like 4 + (unsigned long)&a 12263 if (E->getOpcode() == BO_Add && 12264 RHSVal.isLValue() && LHSVal.isInt()) { 12265 Result = RHSVal; 12266 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12267 return true; 12268 } 12269 12270 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12271 // Handle (intptr_t)&&A - (intptr_t)&&B. 12272 if (!LHSVal.getLValueOffset().isZero() || 12273 !RHSVal.getLValueOffset().isZero()) 12274 return false; 12275 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12276 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12277 if (!LHSExpr || !RHSExpr) 12278 return false; 12279 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12280 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12281 if (!LHSAddrExpr || !RHSAddrExpr) 12282 return false; 12283 // Make sure both labels come from the same function. 12284 if (LHSAddrExpr->getLabel()->getDeclContext() != 12285 RHSAddrExpr->getLabel()->getDeclContext()) 12286 return false; 12287 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12288 return true; 12289 } 12290 12291 // All the remaining cases expect both operands to be an integer 12292 if (!LHSVal.isInt() || !RHSVal.isInt()) 12293 return Error(E); 12294 12295 // Set up the width and signedness manually, in case it can't be deduced 12296 // from the operation we're performing. 12297 // FIXME: Don't do this in the cases where we can deduce it. 12298 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12299 E->getType()->isUnsignedIntegerOrEnumerationType()); 12300 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12301 RHSVal.getInt(), Value)) 12302 return false; 12303 return Success(Value, E, Result); 12304 } 12305 12306 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12307 Job &job = Queue.back(); 12308 12309 switch (job.Kind) { 12310 case Job::AnyExprKind: { 12311 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12312 if (shouldEnqueue(Bop)) { 12313 job.Kind = Job::BinOpKind; 12314 enqueue(Bop->getLHS()); 12315 return; 12316 } 12317 } 12318 12319 EvaluateExpr(job.E, Result); 12320 Queue.pop_back(); 12321 return; 12322 } 12323 12324 case Job::BinOpKind: { 12325 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12326 bool SuppressRHSDiags = false; 12327 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12328 Queue.pop_back(); 12329 return; 12330 } 12331 if (SuppressRHSDiags) 12332 job.startSpeculativeEval(Info); 12333 job.LHSResult.swap(Result); 12334 job.Kind = Job::BinOpVisitedLHSKind; 12335 enqueue(Bop->getRHS()); 12336 return; 12337 } 12338 12339 case Job::BinOpVisitedLHSKind: { 12340 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12341 EvalResult RHS; 12342 RHS.swap(Result); 12343 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12344 Queue.pop_back(); 12345 return; 12346 } 12347 } 12348 12349 llvm_unreachable("Invalid Job::Kind!"); 12350 } 12351 12352 namespace { 12353 /// Used when we determine that we should fail, but can keep evaluating prior to 12354 /// noting that we had a failure. 12355 class DelayedNoteFailureRAII { 12356 EvalInfo &Info; 12357 bool NoteFailure; 12358 12359 public: 12360 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12361 : Info(Info), NoteFailure(NoteFailure) {} 12362 ~DelayedNoteFailureRAII() { 12363 if (NoteFailure) { 12364 bool ContinueAfterFailure = Info.noteFailure(); 12365 (void)ContinueAfterFailure; 12366 assert(ContinueAfterFailure && 12367 "Shouldn't have kept evaluating on failure."); 12368 } 12369 } 12370 }; 12371 12372 enum class CmpResult { 12373 Unequal, 12374 Less, 12375 Equal, 12376 Greater, 12377 Unordered, 12378 }; 12379 } 12380 12381 template <class SuccessCB, class AfterCB> 12382 static bool 12383 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12384 SuccessCB &&Success, AfterCB &&DoAfter) { 12385 assert(E->isComparisonOp() && "expected comparison operator"); 12386 assert((E->getOpcode() == BO_Cmp || 12387 E->getType()->isIntegralOrEnumerationType()) && 12388 "unsupported binary expression evaluation"); 12389 auto Error = [&](const Expr *E) { 12390 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12391 return false; 12392 }; 12393 12394 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12395 bool IsEquality = E->isEqualityOp(); 12396 12397 QualType LHSTy = E->getLHS()->getType(); 12398 QualType RHSTy = E->getRHS()->getType(); 12399 12400 if (LHSTy->isIntegralOrEnumerationType() && 12401 RHSTy->isIntegralOrEnumerationType()) { 12402 APSInt LHS, RHS; 12403 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12404 if (!LHSOK && !Info.noteFailure()) 12405 return false; 12406 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12407 return false; 12408 if (LHS < RHS) 12409 return Success(CmpResult::Less, E); 12410 if (LHS > RHS) 12411 return Success(CmpResult::Greater, E); 12412 return Success(CmpResult::Equal, E); 12413 } 12414 12415 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12416 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12417 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12418 12419 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12420 if (!LHSOK && !Info.noteFailure()) 12421 return false; 12422 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12423 return false; 12424 if (LHSFX < RHSFX) 12425 return Success(CmpResult::Less, E); 12426 if (LHSFX > RHSFX) 12427 return Success(CmpResult::Greater, E); 12428 return Success(CmpResult::Equal, E); 12429 } 12430 12431 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12432 ComplexValue LHS, RHS; 12433 bool LHSOK; 12434 if (E->isAssignmentOp()) { 12435 LValue LV; 12436 EvaluateLValue(E->getLHS(), LV, Info); 12437 LHSOK = false; 12438 } else if (LHSTy->isRealFloatingType()) { 12439 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12440 if (LHSOK) { 12441 LHS.makeComplexFloat(); 12442 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12443 } 12444 } else { 12445 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12446 } 12447 if (!LHSOK && !Info.noteFailure()) 12448 return false; 12449 12450 if (E->getRHS()->getType()->isRealFloatingType()) { 12451 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12452 return false; 12453 RHS.makeComplexFloat(); 12454 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12455 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12456 return false; 12457 12458 if (LHS.isComplexFloat()) { 12459 APFloat::cmpResult CR_r = 12460 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12461 APFloat::cmpResult CR_i = 12462 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12463 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12464 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12465 } else { 12466 assert(IsEquality && "invalid complex comparison"); 12467 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12468 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12469 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12470 } 12471 } 12472 12473 if (LHSTy->isRealFloatingType() && 12474 RHSTy->isRealFloatingType()) { 12475 APFloat RHS(0.0), LHS(0.0); 12476 12477 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12478 if (!LHSOK && !Info.noteFailure()) 12479 return false; 12480 12481 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12482 return false; 12483 12484 assert(E->isComparisonOp() && "Invalid binary operator!"); 12485 auto GetCmpRes = [&]() { 12486 switch (LHS.compare(RHS)) { 12487 case APFloat::cmpEqual: 12488 return CmpResult::Equal; 12489 case APFloat::cmpLessThan: 12490 return CmpResult::Less; 12491 case APFloat::cmpGreaterThan: 12492 return CmpResult::Greater; 12493 case APFloat::cmpUnordered: 12494 return CmpResult::Unordered; 12495 } 12496 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12497 }; 12498 return Success(GetCmpRes(), E); 12499 } 12500 12501 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12502 LValue LHSValue, RHSValue; 12503 12504 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12505 if (!LHSOK && !Info.noteFailure()) 12506 return false; 12507 12508 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12509 return false; 12510 12511 // Reject differing bases from the normal codepath; we special-case 12512 // comparisons to null. 12513 if (!HasSameBase(LHSValue, RHSValue)) { 12514 // Inequalities and subtractions between unrelated pointers have 12515 // unspecified or undefined behavior. 12516 if (!IsEquality) { 12517 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12518 return false; 12519 } 12520 // A constant address may compare equal to the address of a symbol. 12521 // The one exception is that address of an object cannot compare equal 12522 // to a null pointer constant. 12523 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12524 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12525 return Error(E); 12526 // It's implementation-defined whether distinct literals will have 12527 // distinct addresses. In clang, the result of such a comparison is 12528 // unspecified, so it is not a constant expression. However, we do know 12529 // that the address of a literal will be non-null. 12530 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12531 LHSValue.Base && RHSValue.Base) 12532 return Error(E); 12533 // We can't tell whether weak symbols will end up pointing to the same 12534 // object. 12535 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12536 return Error(E); 12537 // We can't compare the address of the start of one object with the 12538 // past-the-end address of another object, per C++ DR1652. 12539 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12540 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12541 (RHSValue.Base && RHSValue.Offset.isZero() && 12542 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12543 return Error(E); 12544 // We can't tell whether an object is at the same address as another 12545 // zero sized object. 12546 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12547 (LHSValue.Base && isZeroSized(RHSValue))) 12548 return Error(E); 12549 return Success(CmpResult::Unequal, E); 12550 } 12551 12552 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12553 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12554 12555 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12556 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12557 12558 // C++11 [expr.rel]p3: 12559 // Pointers to void (after pointer conversions) can be compared, with a 12560 // result defined as follows: If both pointers represent the same 12561 // address or are both the null pointer value, the result is true if the 12562 // operator is <= or >= and false otherwise; otherwise the result is 12563 // unspecified. 12564 // We interpret this as applying to pointers to *cv* void. 12565 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12566 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12567 12568 // C++11 [expr.rel]p2: 12569 // - If two pointers point to non-static data members of the same object, 12570 // or to subobjects or array elements fo such members, recursively, the 12571 // pointer to the later declared member compares greater provided the 12572 // two members have the same access control and provided their class is 12573 // not a union. 12574 // [...] 12575 // - Otherwise pointer comparisons are unspecified. 12576 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12577 bool WasArrayIndex; 12578 unsigned Mismatch = FindDesignatorMismatch( 12579 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12580 // At the point where the designators diverge, the comparison has a 12581 // specified value if: 12582 // - we are comparing array indices 12583 // - we are comparing fields of a union, or fields with the same access 12584 // Otherwise, the result is unspecified and thus the comparison is not a 12585 // constant expression. 12586 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12587 Mismatch < RHSDesignator.Entries.size()) { 12588 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12589 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12590 if (!LF && !RF) 12591 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12592 else if (!LF) 12593 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12594 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12595 << RF->getParent() << RF; 12596 else if (!RF) 12597 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12598 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12599 << LF->getParent() << LF; 12600 else if (!LF->getParent()->isUnion() && 12601 LF->getAccess() != RF->getAccess()) 12602 Info.CCEDiag(E, 12603 diag::note_constexpr_pointer_comparison_differing_access) 12604 << LF << LF->getAccess() << RF << RF->getAccess() 12605 << LF->getParent(); 12606 } 12607 } 12608 12609 // The comparison here must be unsigned, and performed with the same 12610 // width as the pointer. 12611 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12612 uint64_t CompareLHS = LHSOffset.getQuantity(); 12613 uint64_t CompareRHS = RHSOffset.getQuantity(); 12614 assert(PtrSize <= 64 && "Unexpected pointer width"); 12615 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12616 CompareLHS &= Mask; 12617 CompareRHS &= Mask; 12618 12619 // If there is a base and this is a relational operator, we can only 12620 // compare pointers within the object in question; otherwise, the result 12621 // depends on where the object is located in memory. 12622 if (!LHSValue.Base.isNull() && IsRelational) { 12623 QualType BaseTy = getType(LHSValue.Base); 12624 if (BaseTy->isIncompleteType()) 12625 return Error(E); 12626 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12627 uint64_t OffsetLimit = Size.getQuantity(); 12628 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12629 return Error(E); 12630 } 12631 12632 if (CompareLHS < CompareRHS) 12633 return Success(CmpResult::Less, E); 12634 if (CompareLHS > CompareRHS) 12635 return Success(CmpResult::Greater, E); 12636 return Success(CmpResult::Equal, E); 12637 } 12638 12639 if (LHSTy->isMemberPointerType()) { 12640 assert(IsEquality && "unexpected member pointer operation"); 12641 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12642 12643 MemberPtr LHSValue, RHSValue; 12644 12645 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12646 if (!LHSOK && !Info.noteFailure()) 12647 return false; 12648 12649 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12650 return false; 12651 12652 // C++11 [expr.eq]p2: 12653 // If both operands are null, they compare equal. Otherwise if only one is 12654 // null, they compare unequal. 12655 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12656 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12657 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12658 } 12659 12660 // Otherwise if either is a pointer to a virtual member function, the 12661 // result is unspecified. 12662 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12663 if (MD->isVirtual()) 12664 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12665 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12666 if (MD->isVirtual()) 12667 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12668 12669 // Otherwise they compare equal if and only if they would refer to the 12670 // same member of the same most derived object or the same subobject if 12671 // they were dereferenced with a hypothetical object of the associated 12672 // class type. 12673 bool Equal = LHSValue == RHSValue; 12674 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12675 } 12676 12677 if (LHSTy->isNullPtrType()) { 12678 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12679 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12680 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12681 // are compared, the result is true of the operator is <=, >= or ==, and 12682 // false otherwise. 12683 return Success(CmpResult::Equal, E); 12684 } 12685 12686 return DoAfter(); 12687 } 12688 12689 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12690 if (!CheckLiteralType(Info, E)) 12691 return false; 12692 12693 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12694 ComparisonCategoryResult CCR; 12695 switch (CR) { 12696 case CmpResult::Unequal: 12697 llvm_unreachable("should never produce Unequal for three-way comparison"); 12698 case CmpResult::Less: 12699 CCR = ComparisonCategoryResult::Less; 12700 break; 12701 case CmpResult::Equal: 12702 CCR = ComparisonCategoryResult::Equal; 12703 break; 12704 case CmpResult::Greater: 12705 CCR = ComparisonCategoryResult::Greater; 12706 break; 12707 case CmpResult::Unordered: 12708 CCR = ComparisonCategoryResult::Unordered; 12709 break; 12710 } 12711 // Evaluation succeeded. Lookup the information for the comparison category 12712 // type and fetch the VarDecl for the result. 12713 const ComparisonCategoryInfo &CmpInfo = 12714 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12715 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12716 // Check and evaluate the result as a constant expression. 12717 LValue LV; 12718 LV.set(VD); 12719 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12720 return false; 12721 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12722 }; 12723 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12724 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12725 }); 12726 } 12727 12728 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12729 // We don't call noteFailure immediately because the assignment happens after 12730 // we evaluate LHS and RHS. 12731 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12732 return Error(E); 12733 12734 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12735 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12736 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12737 12738 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12739 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12740 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12741 12742 if (E->isComparisonOp()) { 12743 // Evaluate builtin binary comparisons by evaluating them as three-way 12744 // comparisons and then translating the result. 12745 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12746 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12747 "should only produce Unequal for equality comparisons"); 12748 bool IsEqual = CR == CmpResult::Equal, 12749 IsLess = CR == CmpResult::Less, 12750 IsGreater = CR == CmpResult::Greater; 12751 auto Op = E->getOpcode(); 12752 switch (Op) { 12753 default: 12754 llvm_unreachable("unsupported binary operator"); 12755 case BO_EQ: 12756 case BO_NE: 12757 return Success(IsEqual == (Op == BO_EQ), E); 12758 case BO_LT: 12759 return Success(IsLess, E); 12760 case BO_GT: 12761 return Success(IsGreater, E); 12762 case BO_LE: 12763 return Success(IsEqual || IsLess, E); 12764 case BO_GE: 12765 return Success(IsEqual || IsGreater, E); 12766 } 12767 }; 12768 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12769 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12770 }); 12771 } 12772 12773 QualType LHSTy = E->getLHS()->getType(); 12774 QualType RHSTy = E->getRHS()->getType(); 12775 12776 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12777 E->getOpcode() == BO_Sub) { 12778 LValue LHSValue, RHSValue; 12779 12780 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12781 if (!LHSOK && !Info.noteFailure()) 12782 return false; 12783 12784 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12785 return false; 12786 12787 // Reject differing bases from the normal codepath; we special-case 12788 // comparisons to null. 12789 if (!HasSameBase(LHSValue, RHSValue)) { 12790 // Handle &&A - &&B. 12791 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12792 return Error(E); 12793 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12794 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12795 if (!LHSExpr || !RHSExpr) 12796 return Error(E); 12797 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12798 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12799 if (!LHSAddrExpr || !RHSAddrExpr) 12800 return Error(E); 12801 // Make sure both labels come from the same function. 12802 if (LHSAddrExpr->getLabel()->getDeclContext() != 12803 RHSAddrExpr->getLabel()->getDeclContext()) 12804 return Error(E); 12805 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12806 } 12807 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12808 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12809 12810 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12811 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12812 12813 // C++11 [expr.add]p6: 12814 // Unless both pointers point to elements of the same array object, or 12815 // one past the last element of the array object, the behavior is 12816 // undefined. 12817 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12818 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12819 RHSDesignator)) 12820 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12821 12822 QualType Type = E->getLHS()->getType(); 12823 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12824 12825 CharUnits ElementSize; 12826 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12827 return false; 12828 12829 // As an extension, a type may have zero size (empty struct or union in 12830 // C, array of zero length). Pointer subtraction in such cases has 12831 // undefined behavior, so is not constant. 12832 if (ElementSize.isZero()) { 12833 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12834 << ElementType; 12835 return false; 12836 } 12837 12838 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12839 // and produce incorrect results when it overflows. Such behavior 12840 // appears to be non-conforming, but is common, so perhaps we should 12841 // assume the standard intended for such cases to be undefined behavior 12842 // and check for them. 12843 12844 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12845 // overflow in the final conversion to ptrdiff_t. 12846 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12847 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12848 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12849 false); 12850 APSInt TrueResult = (LHS - RHS) / ElemSize; 12851 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12852 12853 if (Result.extend(65) != TrueResult && 12854 !HandleOverflow(Info, E, TrueResult, E->getType())) 12855 return false; 12856 return Success(Result, E); 12857 } 12858 12859 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12860 } 12861 12862 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12863 /// a result as the expression's type. 12864 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12865 const UnaryExprOrTypeTraitExpr *E) { 12866 switch(E->getKind()) { 12867 case UETT_PreferredAlignOf: 12868 case UETT_AlignOf: { 12869 if (E->isArgumentType()) 12870 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12871 E); 12872 else 12873 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12874 E); 12875 } 12876 12877 case UETT_VecStep: { 12878 QualType Ty = E->getTypeOfArgument(); 12879 12880 if (Ty->isVectorType()) { 12881 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12882 12883 // The vec_step built-in functions that take a 3-component 12884 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12885 if (n == 3) 12886 n = 4; 12887 12888 return Success(n, E); 12889 } else 12890 return Success(1, E); 12891 } 12892 12893 case UETT_SizeOf: { 12894 QualType SrcTy = E->getTypeOfArgument(); 12895 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12896 // the result is the size of the referenced type." 12897 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12898 SrcTy = Ref->getPointeeType(); 12899 12900 CharUnits Sizeof; 12901 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12902 return false; 12903 return Success(Sizeof, E); 12904 } 12905 case UETT_OpenMPRequiredSimdAlign: 12906 assert(E->isArgumentType()); 12907 return Success( 12908 Info.Ctx.toCharUnitsFromBits( 12909 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12910 .getQuantity(), 12911 E); 12912 } 12913 12914 llvm_unreachable("unknown expr/type trait"); 12915 } 12916 12917 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12918 CharUnits Result; 12919 unsigned n = OOE->getNumComponents(); 12920 if (n == 0) 12921 return Error(OOE); 12922 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12923 for (unsigned i = 0; i != n; ++i) { 12924 OffsetOfNode ON = OOE->getComponent(i); 12925 switch (ON.getKind()) { 12926 case OffsetOfNode::Array: { 12927 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12928 APSInt IdxResult; 12929 if (!EvaluateInteger(Idx, IdxResult, Info)) 12930 return false; 12931 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12932 if (!AT) 12933 return Error(OOE); 12934 CurrentType = AT->getElementType(); 12935 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12936 Result += IdxResult.getSExtValue() * ElementSize; 12937 break; 12938 } 12939 12940 case OffsetOfNode::Field: { 12941 FieldDecl *MemberDecl = ON.getField(); 12942 const RecordType *RT = CurrentType->getAs<RecordType>(); 12943 if (!RT) 12944 return Error(OOE); 12945 RecordDecl *RD = RT->getDecl(); 12946 if (RD->isInvalidDecl()) return false; 12947 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12948 unsigned i = MemberDecl->getFieldIndex(); 12949 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12950 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12951 CurrentType = MemberDecl->getType().getNonReferenceType(); 12952 break; 12953 } 12954 12955 case OffsetOfNode::Identifier: 12956 llvm_unreachable("dependent __builtin_offsetof"); 12957 12958 case OffsetOfNode::Base: { 12959 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12960 if (BaseSpec->isVirtual()) 12961 return Error(OOE); 12962 12963 // Find the layout of the class whose base we are looking into. 12964 const RecordType *RT = CurrentType->getAs<RecordType>(); 12965 if (!RT) 12966 return Error(OOE); 12967 RecordDecl *RD = RT->getDecl(); 12968 if (RD->isInvalidDecl()) return false; 12969 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12970 12971 // Find the base class itself. 12972 CurrentType = BaseSpec->getType(); 12973 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12974 if (!BaseRT) 12975 return Error(OOE); 12976 12977 // Add the offset to the base. 12978 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12979 break; 12980 } 12981 } 12982 } 12983 return Success(Result, OOE); 12984 } 12985 12986 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12987 switch (E->getOpcode()) { 12988 default: 12989 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12990 // See C99 6.6p3. 12991 return Error(E); 12992 case UO_Extension: 12993 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12994 // If so, we could clear the diagnostic ID. 12995 return Visit(E->getSubExpr()); 12996 case UO_Plus: 12997 // The result is just the value. 12998 return Visit(E->getSubExpr()); 12999 case UO_Minus: { 13000 if (!Visit(E->getSubExpr())) 13001 return false; 13002 if (!Result.isInt()) return Error(E); 13003 const APSInt &Value = Result.getInt(); 13004 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13005 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13006 E->getType())) 13007 return false; 13008 return Success(-Value, E); 13009 } 13010 case UO_Not: { 13011 if (!Visit(E->getSubExpr())) 13012 return false; 13013 if (!Result.isInt()) return Error(E); 13014 return Success(~Result.getInt(), E); 13015 } 13016 case UO_LNot: { 13017 bool bres; 13018 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13019 return false; 13020 return Success(!bres, E); 13021 } 13022 } 13023 } 13024 13025 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13026 /// result type is integer. 13027 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13028 const Expr *SubExpr = E->getSubExpr(); 13029 QualType DestType = E->getType(); 13030 QualType SrcType = SubExpr->getType(); 13031 13032 switch (E->getCastKind()) { 13033 case CK_BaseToDerived: 13034 case CK_DerivedToBase: 13035 case CK_UncheckedDerivedToBase: 13036 case CK_Dynamic: 13037 case CK_ToUnion: 13038 case CK_ArrayToPointerDecay: 13039 case CK_FunctionToPointerDecay: 13040 case CK_NullToPointer: 13041 case CK_NullToMemberPointer: 13042 case CK_BaseToDerivedMemberPointer: 13043 case CK_DerivedToBaseMemberPointer: 13044 case CK_ReinterpretMemberPointer: 13045 case CK_ConstructorConversion: 13046 case CK_IntegralToPointer: 13047 case CK_ToVoid: 13048 case CK_VectorSplat: 13049 case CK_IntegralToFloating: 13050 case CK_FloatingCast: 13051 case CK_CPointerToObjCPointerCast: 13052 case CK_BlockPointerToObjCPointerCast: 13053 case CK_AnyPointerToBlockPointerCast: 13054 case CK_ObjCObjectLValueCast: 13055 case CK_FloatingRealToComplex: 13056 case CK_FloatingComplexToReal: 13057 case CK_FloatingComplexCast: 13058 case CK_FloatingComplexToIntegralComplex: 13059 case CK_IntegralRealToComplex: 13060 case CK_IntegralComplexCast: 13061 case CK_IntegralComplexToFloatingComplex: 13062 case CK_BuiltinFnToFnPtr: 13063 case CK_ZeroToOCLOpaqueType: 13064 case CK_NonAtomicToAtomic: 13065 case CK_AddressSpaceConversion: 13066 case CK_IntToOCLSampler: 13067 case CK_FloatingToFixedPoint: 13068 case CK_FixedPointToFloating: 13069 case CK_FixedPointCast: 13070 case CK_IntegralToFixedPoint: 13071 llvm_unreachable("invalid cast kind for integral value"); 13072 13073 case CK_BitCast: 13074 case CK_Dependent: 13075 case CK_LValueBitCast: 13076 case CK_ARCProduceObject: 13077 case CK_ARCConsumeObject: 13078 case CK_ARCReclaimReturnedObject: 13079 case CK_ARCExtendBlockObject: 13080 case CK_CopyAndAutoreleaseBlockObject: 13081 return Error(E); 13082 13083 case CK_UserDefinedConversion: 13084 case CK_LValueToRValue: 13085 case CK_AtomicToNonAtomic: 13086 case CK_NoOp: 13087 case CK_LValueToRValueBitCast: 13088 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13089 13090 case CK_MemberPointerToBoolean: 13091 case CK_PointerToBoolean: 13092 case CK_IntegralToBoolean: 13093 case CK_FloatingToBoolean: 13094 case CK_BooleanToSignedIntegral: 13095 case CK_FloatingComplexToBoolean: 13096 case CK_IntegralComplexToBoolean: { 13097 bool BoolResult; 13098 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13099 return false; 13100 uint64_t IntResult = BoolResult; 13101 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13102 IntResult = (uint64_t)-1; 13103 return Success(IntResult, E); 13104 } 13105 13106 case CK_FixedPointToIntegral: { 13107 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13108 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13109 return false; 13110 bool Overflowed; 13111 llvm::APSInt Result = Src.convertToInt( 13112 Info.Ctx.getIntWidth(DestType), 13113 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13114 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13115 return false; 13116 return Success(Result, E); 13117 } 13118 13119 case CK_FixedPointToBoolean: { 13120 // Unsigned padding does not affect this. 13121 APValue Val; 13122 if (!Evaluate(Val, Info, SubExpr)) 13123 return false; 13124 return Success(Val.getFixedPoint().getBoolValue(), E); 13125 } 13126 13127 case CK_IntegralCast: { 13128 if (!Visit(SubExpr)) 13129 return false; 13130 13131 if (!Result.isInt()) { 13132 // Allow casts of address-of-label differences if they are no-ops 13133 // or narrowing. (The narrowing case isn't actually guaranteed to 13134 // be constant-evaluatable except in some narrow cases which are hard 13135 // to detect here. We let it through on the assumption the user knows 13136 // what they are doing.) 13137 if (Result.isAddrLabelDiff()) 13138 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13139 // Only allow casts of lvalues if they are lossless. 13140 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13141 } 13142 13143 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13144 Result.getInt()), E); 13145 } 13146 13147 case CK_PointerToIntegral: { 13148 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13149 13150 LValue LV; 13151 if (!EvaluatePointer(SubExpr, LV, Info)) 13152 return false; 13153 13154 if (LV.getLValueBase()) { 13155 // Only allow based lvalue casts if they are lossless. 13156 // FIXME: Allow a larger integer size than the pointer size, and allow 13157 // narrowing back down to pointer width in subsequent integral casts. 13158 // FIXME: Check integer type's active bits, not its type size. 13159 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13160 return Error(E); 13161 13162 LV.Designator.setInvalid(); 13163 LV.moveInto(Result); 13164 return true; 13165 } 13166 13167 APSInt AsInt; 13168 APValue V; 13169 LV.moveInto(V); 13170 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13171 llvm_unreachable("Can't cast this!"); 13172 13173 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13174 } 13175 13176 case CK_IntegralComplexToReal: { 13177 ComplexValue C; 13178 if (!EvaluateComplex(SubExpr, C, Info)) 13179 return false; 13180 return Success(C.getComplexIntReal(), E); 13181 } 13182 13183 case CK_FloatingToIntegral: { 13184 APFloat F(0.0); 13185 if (!EvaluateFloat(SubExpr, F, Info)) 13186 return false; 13187 13188 APSInt Value; 13189 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13190 return false; 13191 return Success(Value, E); 13192 } 13193 } 13194 13195 llvm_unreachable("unknown cast resulting in integral value"); 13196 } 13197 13198 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13199 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13200 ComplexValue LV; 13201 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13202 return false; 13203 if (!LV.isComplexInt()) 13204 return Error(E); 13205 return Success(LV.getComplexIntReal(), E); 13206 } 13207 13208 return Visit(E->getSubExpr()); 13209 } 13210 13211 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13212 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13213 ComplexValue LV; 13214 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13215 return false; 13216 if (!LV.isComplexInt()) 13217 return Error(E); 13218 return Success(LV.getComplexIntImag(), E); 13219 } 13220 13221 VisitIgnoredValue(E->getSubExpr()); 13222 return Success(0, E); 13223 } 13224 13225 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13226 return Success(E->getPackLength(), E); 13227 } 13228 13229 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13230 return Success(E->getValue(), E); 13231 } 13232 13233 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13234 const ConceptSpecializationExpr *E) { 13235 return Success(E->isSatisfied(), E); 13236 } 13237 13238 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13239 return Success(E->isSatisfied(), E); 13240 } 13241 13242 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13243 switch (E->getOpcode()) { 13244 default: 13245 // Invalid unary operators 13246 return Error(E); 13247 case UO_Plus: 13248 // The result is just the value. 13249 return Visit(E->getSubExpr()); 13250 case UO_Minus: { 13251 if (!Visit(E->getSubExpr())) return false; 13252 if (!Result.isFixedPoint()) 13253 return Error(E); 13254 bool Overflowed; 13255 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13256 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13257 return false; 13258 return Success(Negated, E); 13259 } 13260 case UO_LNot: { 13261 bool bres; 13262 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13263 return false; 13264 return Success(!bres, E); 13265 } 13266 } 13267 } 13268 13269 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13270 const Expr *SubExpr = E->getSubExpr(); 13271 QualType DestType = E->getType(); 13272 assert(DestType->isFixedPointType() && 13273 "Expected destination type to be a fixed point type"); 13274 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13275 13276 switch (E->getCastKind()) { 13277 case CK_FixedPointCast: { 13278 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13279 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13280 return false; 13281 bool Overflowed; 13282 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13283 if (Overflowed) { 13284 if (Info.checkingForUndefinedBehavior()) 13285 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13286 diag::warn_fixedpoint_constant_overflow) 13287 << Result.toString() << E->getType(); 13288 else if (!HandleOverflow(Info, E, Result, E->getType())) 13289 return false; 13290 } 13291 return Success(Result, E); 13292 } 13293 case CK_IntegralToFixedPoint: { 13294 APSInt Src; 13295 if (!EvaluateInteger(SubExpr, Src, Info)) 13296 return false; 13297 13298 bool Overflowed; 13299 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13300 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13301 13302 if (Overflowed) { 13303 if (Info.checkingForUndefinedBehavior()) 13304 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13305 diag::warn_fixedpoint_constant_overflow) 13306 << IntResult.toString() << E->getType(); 13307 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 13308 return false; 13309 } 13310 13311 return Success(IntResult, E); 13312 } 13313 case CK_FloatingToFixedPoint: { 13314 APFloat Src(0.0); 13315 if (!EvaluateFloat(SubExpr, Src, Info)) 13316 return false; 13317 13318 bool Overflowed; 13319 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13320 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13321 13322 if (Overflowed) { 13323 if (Info.checkingForUndefinedBehavior()) 13324 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13325 diag::warn_fixedpoint_constant_overflow) 13326 << Result.toString() << E->getType(); 13327 else if (!HandleOverflow(Info, E, Result, E->getType())) 13328 return false; 13329 } 13330 13331 return Success(Result, E); 13332 } 13333 case CK_NoOp: 13334 case CK_LValueToRValue: 13335 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13336 default: 13337 return Error(E); 13338 } 13339 } 13340 13341 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13342 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13343 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13344 13345 const Expr *LHS = E->getLHS(); 13346 const Expr *RHS = E->getRHS(); 13347 FixedPointSemantics ResultFXSema = 13348 Info.Ctx.getFixedPointSemantics(E->getType()); 13349 13350 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13351 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13352 return false; 13353 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13354 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13355 return false; 13356 13357 bool OpOverflow = false, ConversionOverflow = false; 13358 APFixedPoint Result(LHSFX.getSemantics()); 13359 switch (E->getOpcode()) { 13360 case BO_Add: { 13361 Result = LHSFX.add(RHSFX, &OpOverflow) 13362 .convert(ResultFXSema, &ConversionOverflow); 13363 break; 13364 } 13365 case BO_Sub: { 13366 Result = LHSFX.sub(RHSFX, &OpOverflow) 13367 .convert(ResultFXSema, &ConversionOverflow); 13368 break; 13369 } 13370 case BO_Mul: { 13371 Result = LHSFX.mul(RHSFX, &OpOverflow) 13372 .convert(ResultFXSema, &ConversionOverflow); 13373 break; 13374 } 13375 case BO_Div: { 13376 if (RHSFX.getValue() == 0) { 13377 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13378 return false; 13379 } 13380 Result = LHSFX.div(RHSFX, &OpOverflow) 13381 .convert(ResultFXSema, &ConversionOverflow); 13382 break; 13383 } 13384 case BO_Shl: 13385 case BO_Shr: { 13386 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13387 llvm::APSInt RHSVal = RHSFX.getValue(); 13388 13389 unsigned ShiftBW = 13390 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13391 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13392 // Embedded-C 4.1.6.2.2: 13393 // The right operand must be nonnegative and less than the total number 13394 // of (nonpadding) bits of the fixed-point operand ... 13395 if (RHSVal.isNegative()) 13396 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13397 else if (Amt != RHSVal) 13398 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13399 << RHSVal << E->getType() << ShiftBW; 13400 13401 if (E->getOpcode() == BO_Shl) 13402 Result = LHSFX.shl(Amt, &OpOverflow); 13403 else 13404 Result = LHSFX.shr(Amt, &OpOverflow); 13405 break; 13406 } 13407 default: 13408 return false; 13409 } 13410 if (OpOverflow || ConversionOverflow) { 13411 if (Info.checkingForUndefinedBehavior()) 13412 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13413 diag::warn_fixedpoint_constant_overflow) 13414 << Result.toString() << E->getType(); 13415 else if (!HandleOverflow(Info, E, Result, E->getType())) 13416 return false; 13417 } 13418 return Success(Result, E); 13419 } 13420 13421 //===----------------------------------------------------------------------===// 13422 // Float Evaluation 13423 //===----------------------------------------------------------------------===// 13424 13425 namespace { 13426 class FloatExprEvaluator 13427 : public ExprEvaluatorBase<FloatExprEvaluator> { 13428 APFloat &Result; 13429 public: 13430 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13431 : ExprEvaluatorBaseTy(info), Result(result) {} 13432 13433 bool Success(const APValue &V, const Expr *e) { 13434 Result = V.getFloat(); 13435 return true; 13436 } 13437 13438 bool ZeroInitialization(const Expr *E) { 13439 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13440 return true; 13441 } 13442 13443 bool VisitCallExpr(const CallExpr *E); 13444 13445 bool VisitUnaryOperator(const UnaryOperator *E); 13446 bool VisitBinaryOperator(const BinaryOperator *E); 13447 bool VisitFloatingLiteral(const FloatingLiteral *E); 13448 bool VisitCastExpr(const CastExpr *E); 13449 13450 bool VisitUnaryReal(const UnaryOperator *E); 13451 bool VisitUnaryImag(const UnaryOperator *E); 13452 13453 // FIXME: Missing: array subscript of vector, member of vector 13454 }; 13455 } // end anonymous namespace 13456 13457 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13458 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13459 return FloatExprEvaluator(Info, Result).Visit(E); 13460 } 13461 13462 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13463 QualType ResultTy, 13464 const Expr *Arg, 13465 bool SNaN, 13466 llvm::APFloat &Result) { 13467 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13468 if (!S) return false; 13469 13470 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13471 13472 llvm::APInt fill; 13473 13474 // Treat empty strings as if they were zero. 13475 if (S->getString().empty()) 13476 fill = llvm::APInt(32, 0); 13477 else if (S->getString().getAsInteger(0, fill)) 13478 return false; 13479 13480 if (Context.getTargetInfo().isNan2008()) { 13481 if (SNaN) 13482 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13483 else 13484 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13485 } else { 13486 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13487 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13488 // a different encoding to what became a standard in 2008, and for pre- 13489 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13490 // sNaN. This is now known as "legacy NaN" encoding. 13491 if (SNaN) 13492 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13493 else 13494 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13495 } 13496 13497 return true; 13498 } 13499 13500 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13501 switch (E->getBuiltinCallee()) { 13502 default: 13503 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13504 13505 case Builtin::BI__builtin_huge_val: 13506 case Builtin::BI__builtin_huge_valf: 13507 case Builtin::BI__builtin_huge_vall: 13508 case Builtin::BI__builtin_huge_valf128: 13509 case Builtin::BI__builtin_inf: 13510 case Builtin::BI__builtin_inff: 13511 case Builtin::BI__builtin_infl: 13512 case Builtin::BI__builtin_inff128: { 13513 const llvm::fltSemantics &Sem = 13514 Info.Ctx.getFloatTypeSemantics(E->getType()); 13515 Result = llvm::APFloat::getInf(Sem); 13516 return true; 13517 } 13518 13519 case Builtin::BI__builtin_nans: 13520 case Builtin::BI__builtin_nansf: 13521 case Builtin::BI__builtin_nansl: 13522 case Builtin::BI__builtin_nansf128: 13523 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13524 true, Result)) 13525 return Error(E); 13526 return true; 13527 13528 case Builtin::BI__builtin_nan: 13529 case Builtin::BI__builtin_nanf: 13530 case Builtin::BI__builtin_nanl: 13531 case Builtin::BI__builtin_nanf128: 13532 // If this is __builtin_nan() turn this into a nan, otherwise we 13533 // can't constant fold it. 13534 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13535 false, Result)) 13536 return Error(E); 13537 return true; 13538 13539 case Builtin::BI__builtin_fabs: 13540 case Builtin::BI__builtin_fabsf: 13541 case Builtin::BI__builtin_fabsl: 13542 case Builtin::BI__builtin_fabsf128: 13543 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13544 return false; 13545 13546 if (Result.isNegative()) 13547 Result.changeSign(); 13548 return true; 13549 13550 // FIXME: Builtin::BI__builtin_powi 13551 // FIXME: Builtin::BI__builtin_powif 13552 // FIXME: Builtin::BI__builtin_powil 13553 13554 case Builtin::BI__builtin_copysign: 13555 case Builtin::BI__builtin_copysignf: 13556 case Builtin::BI__builtin_copysignl: 13557 case Builtin::BI__builtin_copysignf128: { 13558 APFloat RHS(0.); 13559 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13560 !EvaluateFloat(E->getArg(1), RHS, Info)) 13561 return false; 13562 Result.copySign(RHS); 13563 return true; 13564 } 13565 } 13566 } 13567 13568 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13569 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13570 ComplexValue CV; 13571 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13572 return false; 13573 Result = CV.FloatReal; 13574 return true; 13575 } 13576 13577 return Visit(E->getSubExpr()); 13578 } 13579 13580 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13581 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13582 ComplexValue CV; 13583 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13584 return false; 13585 Result = CV.FloatImag; 13586 return true; 13587 } 13588 13589 VisitIgnoredValue(E->getSubExpr()); 13590 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13591 Result = llvm::APFloat::getZero(Sem); 13592 return true; 13593 } 13594 13595 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13596 switch (E->getOpcode()) { 13597 default: return Error(E); 13598 case UO_Plus: 13599 return EvaluateFloat(E->getSubExpr(), Result, Info); 13600 case UO_Minus: 13601 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13602 return false; 13603 Result.changeSign(); 13604 return true; 13605 } 13606 } 13607 13608 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13609 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13610 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13611 13612 APFloat RHS(0.0); 13613 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13614 if (!LHSOK && !Info.noteFailure()) 13615 return false; 13616 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13617 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13618 } 13619 13620 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13621 Result = E->getValue(); 13622 return true; 13623 } 13624 13625 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13626 const Expr* SubExpr = E->getSubExpr(); 13627 13628 switch (E->getCastKind()) { 13629 default: 13630 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13631 13632 case CK_IntegralToFloating: { 13633 APSInt IntResult; 13634 return EvaluateInteger(SubExpr, IntResult, Info) && 13635 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 13636 E->getType(), Result); 13637 } 13638 13639 case CK_FixedPointToFloating: { 13640 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13641 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13642 return false; 13643 Result = 13644 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13645 return true; 13646 } 13647 13648 case CK_FloatingCast: { 13649 if (!Visit(SubExpr)) 13650 return false; 13651 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13652 Result); 13653 } 13654 13655 case CK_FloatingComplexToReal: { 13656 ComplexValue V; 13657 if (!EvaluateComplex(SubExpr, V, Info)) 13658 return false; 13659 Result = V.getComplexFloatReal(); 13660 return true; 13661 } 13662 } 13663 } 13664 13665 //===----------------------------------------------------------------------===// 13666 // Complex Evaluation (for float and integer) 13667 //===----------------------------------------------------------------------===// 13668 13669 namespace { 13670 class ComplexExprEvaluator 13671 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13672 ComplexValue &Result; 13673 13674 public: 13675 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13676 : ExprEvaluatorBaseTy(info), Result(Result) {} 13677 13678 bool Success(const APValue &V, const Expr *e) { 13679 Result.setFrom(V); 13680 return true; 13681 } 13682 13683 bool ZeroInitialization(const Expr *E); 13684 13685 //===--------------------------------------------------------------------===// 13686 // Visitor Methods 13687 //===--------------------------------------------------------------------===// 13688 13689 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13690 bool VisitCastExpr(const CastExpr *E); 13691 bool VisitBinaryOperator(const BinaryOperator *E); 13692 bool VisitUnaryOperator(const UnaryOperator *E); 13693 bool VisitInitListExpr(const InitListExpr *E); 13694 bool VisitCallExpr(const CallExpr *E); 13695 }; 13696 } // end anonymous namespace 13697 13698 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13699 EvalInfo &Info) { 13700 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13701 return ComplexExprEvaluator(Info, Result).Visit(E); 13702 } 13703 13704 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13705 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13706 if (ElemTy->isRealFloatingType()) { 13707 Result.makeComplexFloat(); 13708 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13709 Result.FloatReal = Zero; 13710 Result.FloatImag = Zero; 13711 } else { 13712 Result.makeComplexInt(); 13713 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13714 Result.IntReal = Zero; 13715 Result.IntImag = Zero; 13716 } 13717 return true; 13718 } 13719 13720 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13721 const Expr* SubExpr = E->getSubExpr(); 13722 13723 if (SubExpr->getType()->isRealFloatingType()) { 13724 Result.makeComplexFloat(); 13725 APFloat &Imag = Result.FloatImag; 13726 if (!EvaluateFloat(SubExpr, Imag, Info)) 13727 return false; 13728 13729 Result.FloatReal = APFloat(Imag.getSemantics()); 13730 return true; 13731 } else { 13732 assert(SubExpr->getType()->isIntegerType() && 13733 "Unexpected imaginary literal."); 13734 13735 Result.makeComplexInt(); 13736 APSInt &Imag = Result.IntImag; 13737 if (!EvaluateInteger(SubExpr, Imag, Info)) 13738 return false; 13739 13740 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13741 return true; 13742 } 13743 } 13744 13745 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13746 13747 switch (E->getCastKind()) { 13748 case CK_BitCast: 13749 case CK_BaseToDerived: 13750 case CK_DerivedToBase: 13751 case CK_UncheckedDerivedToBase: 13752 case CK_Dynamic: 13753 case CK_ToUnion: 13754 case CK_ArrayToPointerDecay: 13755 case CK_FunctionToPointerDecay: 13756 case CK_NullToPointer: 13757 case CK_NullToMemberPointer: 13758 case CK_BaseToDerivedMemberPointer: 13759 case CK_DerivedToBaseMemberPointer: 13760 case CK_MemberPointerToBoolean: 13761 case CK_ReinterpretMemberPointer: 13762 case CK_ConstructorConversion: 13763 case CK_IntegralToPointer: 13764 case CK_PointerToIntegral: 13765 case CK_PointerToBoolean: 13766 case CK_ToVoid: 13767 case CK_VectorSplat: 13768 case CK_IntegralCast: 13769 case CK_BooleanToSignedIntegral: 13770 case CK_IntegralToBoolean: 13771 case CK_IntegralToFloating: 13772 case CK_FloatingToIntegral: 13773 case CK_FloatingToBoolean: 13774 case CK_FloatingCast: 13775 case CK_CPointerToObjCPointerCast: 13776 case CK_BlockPointerToObjCPointerCast: 13777 case CK_AnyPointerToBlockPointerCast: 13778 case CK_ObjCObjectLValueCast: 13779 case CK_FloatingComplexToReal: 13780 case CK_FloatingComplexToBoolean: 13781 case CK_IntegralComplexToReal: 13782 case CK_IntegralComplexToBoolean: 13783 case CK_ARCProduceObject: 13784 case CK_ARCConsumeObject: 13785 case CK_ARCReclaimReturnedObject: 13786 case CK_ARCExtendBlockObject: 13787 case CK_CopyAndAutoreleaseBlockObject: 13788 case CK_BuiltinFnToFnPtr: 13789 case CK_ZeroToOCLOpaqueType: 13790 case CK_NonAtomicToAtomic: 13791 case CK_AddressSpaceConversion: 13792 case CK_IntToOCLSampler: 13793 case CK_FloatingToFixedPoint: 13794 case CK_FixedPointToFloating: 13795 case CK_FixedPointCast: 13796 case CK_FixedPointToBoolean: 13797 case CK_FixedPointToIntegral: 13798 case CK_IntegralToFixedPoint: 13799 llvm_unreachable("invalid cast kind for complex value"); 13800 13801 case CK_LValueToRValue: 13802 case CK_AtomicToNonAtomic: 13803 case CK_NoOp: 13804 case CK_LValueToRValueBitCast: 13805 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13806 13807 case CK_Dependent: 13808 case CK_LValueBitCast: 13809 case CK_UserDefinedConversion: 13810 return Error(E); 13811 13812 case CK_FloatingRealToComplex: { 13813 APFloat &Real = Result.FloatReal; 13814 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13815 return false; 13816 13817 Result.makeComplexFloat(); 13818 Result.FloatImag = APFloat(Real.getSemantics()); 13819 return true; 13820 } 13821 13822 case CK_FloatingComplexCast: { 13823 if (!Visit(E->getSubExpr())) 13824 return false; 13825 13826 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13827 QualType From 13828 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13829 13830 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13831 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13832 } 13833 13834 case CK_FloatingComplexToIntegralComplex: { 13835 if (!Visit(E->getSubExpr())) 13836 return false; 13837 13838 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13839 QualType From 13840 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13841 Result.makeComplexInt(); 13842 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13843 To, Result.IntReal) && 13844 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13845 To, Result.IntImag); 13846 } 13847 13848 case CK_IntegralRealToComplex: { 13849 APSInt &Real = Result.IntReal; 13850 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13851 return false; 13852 13853 Result.makeComplexInt(); 13854 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13855 return true; 13856 } 13857 13858 case CK_IntegralComplexCast: { 13859 if (!Visit(E->getSubExpr())) 13860 return false; 13861 13862 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13863 QualType From 13864 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13865 13866 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13867 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13868 return true; 13869 } 13870 13871 case CK_IntegralComplexToFloatingComplex: { 13872 if (!Visit(E->getSubExpr())) 13873 return false; 13874 13875 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13876 QualType From 13877 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13878 Result.makeComplexFloat(); 13879 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13880 To, Result.FloatReal) && 13881 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13882 To, Result.FloatImag); 13883 } 13884 } 13885 13886 llvm_unreachable("unknown cast resulting in complex value"); 13887 } 13888 13889 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13890 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13891 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13892 13893 // Track whether the LHS or RHS is real at the type system level. When this is 13894 // the case we can simplify our evaluation strategy. 13895 bool LHSReal = false, RHSReal = false; 13896 13897 bool LHSOK; 13898 if (E->getLHS()->getType()->isRealFloatingType()) { 13899 LHSReal = true; 13900 APFloat &Real = Result.FloatReal; 13901 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13902 if (LHSOK) { 13903 Result.makeComplexFloat(); 13904 Result.FloatImag = APFloat(Real.getSemantics()); 13905 } 13906 } else { 13907 LHSOK = Visit(E->getLHS()); 13908 } 13909 if (!LHSOK && !Info.noteFailure()) 13910 return false; 13911 13912 ComplexValue RHS; 13913 if (E->getRHS()->getType()->isRealFloatingType()) { 13914 RHSReal = true; 13915 APFloat &Real = RHS.FloatReal; 13916 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13917 return false; 13918 RHS.makeComplexFloat(); 13919 RHS.FloatImag = APFloat(Real.getSemantics()); 13920 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13921 return false; 13922 13923 assert(!(LHSReal && RHSReal) && 13924 "Cannot have both operands of a complex operation be real."); 13925 switch (E->getOpcode()) { 13926 default: return Error(E); 13927 case BO_Add: 13928 if (Result.isComplexFloat()) { 13929 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13930 APFloat::rmNearestTiesToEven); 13931 if (LHSReal) 13932 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13933 else if (!RHSReal) 13934 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13935 APFloat::rmNearestTiesToEven); 13936 } else { 13937 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13938 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13939 } 13940 break; 13941 case BO_Sub: 13942 if (Result.isComplexFloat()) { 13943 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13944 APFloat::rmNearestTiesToEven); 13945 if (LHSReal) { 13946 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13947 Result.getComplexFloatImag().changeSign(); 13948 } else if (!RHSReal) { 13949 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13950 APFloat::rmNearestTiesToEven); 13951 } 13952 } else { 13953 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13954 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13955 } 13956 break; 13957 case BO_Mul: 13958 if (Result.isComplexFloat()) { 13959 // This is an implementation of complex multiplication according to the 13960 // constraints laid out in C11 Annex G. The implementation uses the 13961 // following naming scheme: 13962 // (a + ib) * (c + id) 13963 ComplexValue LHS = Result; 13964 APFloat &A = LHS.getComplexFloatReal(); 13965 APFloat &B = LHS.getComplexFloatImag(); 13966 APFloat &C = RHS.getComplexFloatReal(); 13967 APFloat &D = RHS.getComplexFloatImag(); 13968 APFloat &ResR = Result.getComplexFloatReal(); 13969 APFloat &ResI = Result.getComplexFloatImag(); 13970 if (LHSReal) { 13971 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13972 ResR = A * C; 13973 ResI = A * D; 13974 } else if (RHSReal) { 13975 ResR = C * A; 13976 ResI = C * B; 13977 } else { 13978 // In the fully general case, we need to handle NaNs and infinities 13979 // robustly. 13980 APFloat AC = A * C; 13981 APFloat BD = B * D; 13982 APFloat AD = A * D; 13983 APFloat BC = B * C; 13984 ResR = AC - BD; 13985 ResI = AD + BC; 13986 if (ResR.isNaN() && ResI.isNaN()) { 13987 bool Recalc = false; 13988 if (A.isInfinity() || B.isInfinity()) { 13989 A = APFloat::copySign( 13990 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13991 B = APFloat::copySign( 13992 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13993 if (C.isNaN()) 13994 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13995 if (D.isNaN()) 13996 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13997 Recalc = true; 13998 } 13999 if (C.isInfinity() || D.isInfinity()) { 14000 C = APFloat::copySign( 14001 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14002 D = APFloat::copySign( 14003 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14004 if (A.isNaN()) 14005 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14006 if (B.isNaN()) 14007 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14008 Recalc = true; 14009 } 14010 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14011 AD.isInfinity() || BC.isInfinity())) { 14012 if (A.isNaN()) 14013 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14014 if (B.isNaN()) 14015 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14016 if (C.isNaN()) 14017 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14018 if (D.isNaN()) 14019 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14020 Recalc = true; 14021 } 14022 if (Recalc) { 14023 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14024 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14025 } 14026 } 14027 } 14028 } else { 14029 ComplexValue LHS = Result; 14030 Result.getComplexIntReal() = 14031 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14032 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14033 Result.getComplexIntImag() = 14034 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14035 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14036 } 14037 break; 14038 case BO_Div: 14039 if (Result.isComplexFloat()) { 14040 // This is an implementation of complex division according to the 14041 // constraints laid out in C11 Annex G. The implementation uses the 14042 // following naming scheme: 14043 // (a + ib) / (c + id) 14044 ComplexValue LHS = Result; 14045 APFloat &A = LHS.getComplexFloatReal(); 14046 APFloat &B = LHS.getComplexFloatImag(); 14047 APFloat &C = RHS.getComplexFloatReal(); 14048 APFloat &D = RHS.getComplexFloatImag(); 14049 APFloat &ResR = Result.getComplexFloatReal(); 14050 APFloat &ResI = Result.getComplexFloatImag(); 14051 if (RHSReal) { 14052 ResR = A / C; 14053 ResI = B / C; 14054 } else { 14055 if (LHSReal) { 14056 // No real optimizations we can do here, stub out with zero. 14057 B = APFloat::getZero(A.getSemantics()); 14058 } 14059 int DenomLogB = 0; 14060 APFloat MaxCD = maxnum(abs(C), abs(D)); 14061 if (MaxCD.isFinite()) { 14062 DenomLogB = ilogb(MaxCD); 14063 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14064 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14065 } 14066 APFloat Denom = C * C + D * D; 14067 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14068 APFloat::rmNearestTiesToEven); 14069 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14070 APFloat::rmNearestTiesToEven); 14071 if (ResR.isNaN() && ResI.isNaN()) { 14072 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14073 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14074 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14075 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14076 D.isFinite()) { 14077 A = APFloat::copySign( 14078 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14079 B = APFloat::copySign( 14080 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14081 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14082 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14083 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14084 C = APFloat::copySign( 14085 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14086 D = APFloat::copySign( 14087 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14088 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14089 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14090 } 14091 } 14092 } 14093 } else { 14094 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14095 return Error(E, diag::note_expr_divide_by_zero); 14096 14097 ComplexValue LHS = Result; 14098 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14099 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14100 Result.getComplexIntReal() = 14101 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14102 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14103 Result.getComplexIntImag() = 14104 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14105 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14106 } 14107 break; 14108 } 14109 14110 return true; 14111 } 14112 14113 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14114 // Get the operand value into 'Result'. 14115 if (!Visit(E->getSubExpr())) 14116 return false; 14117 14118 switch (E->getOpcode()) { 14119 default: 14120 return Error(E); 14121 case UO_Extension: 14122 return true; 14123 case UO_Plus: 14124 // The result is always just the subexpr. 14125 return true; 14126 case UO_Minus: 14127 if (Result.isComplexFloat()) { 14128 Result.getComplexFloatReal().changeSign(); 14129 Result.getComplexFloatImag().changeSign(); 14130 } 14131 else { 14132 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14133 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14134 } 14135 return true; 14136 case UO_Not: 14137 if (Result.isComplexFloat()) 14138 Result.getComplexFloatImag().changeSign(); 14139 else 14140 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14141 return true; 14142 } 14143 } 14144 14145 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14146 if (E->getNumInits() == 2) { 14147 if (E->getType()->isComplexType()) { 14148 Result.makeComplexFloat(); 14149 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14150 return false; 14151 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14152 return false; 14153 } else { 14154 Result.makeComplexInt(); 14155 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14156 return false; 14157 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14158 return false; 14159 } 14160 return true; 14161 } 14162 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14163 } 14164 14165 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14166 switch (E->getBuiltinCallee()) { 14167 case Builtin::BI__builtin_complex: 14168 Result.makeComplexFloat(); 14169 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14170 return false; 14171 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14172 return false; 14173 return true; 14174 14175 default: 14176 break; 14177 } 14178 14179 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14180 } 14181 14182 //===----------------------------------------------------------------------===// 14183 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14184 // implicit conversion. 14185 //===----------------------------------------------------------------------===// 14186 14187 namespace { 14188 class AtomicExprEvaluator : 14189 public ExprEvaluatorBase<AtomicExprEvaluator> { 14190 const LValue *This; 14191 APValue &Result; 14192 public: 14193 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14194 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14195 14196 bool Success(const APValue &V, const Expr *E) { 14197 Result = V; 14198 return true; 14199 } 14200 14201 bool ZeroInitialization(const Expr *E) { 14202 ImplicitValueInitExpr VIE( 14203 E->getType()->castAs<AtomicType>()->getValueType()); 14204 // For atomic-qualified class (and array) types in C++, initialize the 14205 // _Atomic-wrapped subobject directly, in-place. 14206 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14207 : Evaluate(Result, Info, &VIE); 14208 } 14209 14210 bool VisitCastExpr(const CastExpr *E) { 14211 switch (E->getCastKind()) { 14212 default: 14213 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14214 case CK_NonAtomicToAtomic: 14215 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14216 : Evaluate(Result, Info, E->getSubExpr()); 14217 } 14218 } 14219 }; 14220 } // end anonymous namespace 14221 14222 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14223 EvalInfo &Info) { 14224 assert(E->isRValue() && E->getType()->isAtomicType()); 14225 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14226 } 14227 14228 //===----------------------------------------------------------------------===// 14229 // Void expression evaluation, primarily for a cast to void on the LHS of a 14230 // comma operator 14231 //===----------------------------------------------------------------------===// 14232 14233 namespace { 14234 class VoidExprEvaluator 14235 : public ExprEvaluatorBase<VoidExprEvaluator> { 14236 public: 14237 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14238 14239 bool Success(const APValue &V, const Expr *e) { return true; } 14240 14241 bool ZeroInitialization(const Expr *E) { return true; } 14242 14243 bool VisitCastExpr(const CastExpr *E) { 14244 switch (E->getCastKind()) { 14245 default: 14246 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14247 case CK_ToVoid: 14248 VisitIgnoredValue(E->getSubExpr()); 14249 return true; 14250 } 14251 } 14252 14253 bool VisitCallExpr(const CallExpr *E) { 14254 switch (E->getBuiltinCallee()) { 14255 case Builtin::BI__assume: 14256 case Builtin::BI__builtin_assume: 14257 // The argument is not evaluated! 14258 return true; 14259 14260 case Builtin::BI__builtin_operator_delete: 14261 return HandleOperatorDeleteCall(Info, E); 14262 14263 default: 14264 break; 14265 } 14266 14267 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14268 } 14269 14270 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14271 }; 14272 } // end anonymous namespace 14273 14274 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14275 // We cannot speculatively evaluate a delete expression. 14276 if (Info.SpeculativeEvaluationDepth) 14277 return false; 14278 14279 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14280 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14281 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14282 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14283 return false; 14284 } 14285 14286 const Expr *Arg = E->getArgument(); 14287 14288 LValue Pointer; 14289 if (!EvaluatePointer(Arg, Pointer, Info)) 14290 return false; 14291 if (Pointer.Designator.Invalid) 14292 return false; 14293 14294 // Deleting a null pointer has no effect. 14295 if (Pointer.isNullPointer()) { 14296 // This is the only case where we need to produce an extension warning: 14297 // the only other way we can succeed is if we find a dynamic allocation, 14298 // and we will have warned when we allocated it in that case. 14299 if (!Info.getLangOpts().CPlusPlus20) 14300 Info.CCEDiag(E, diag::note_constexpr_new); 14301 return true; 14302 } 14303 14304 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14305 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14306 if (!Alloc) 14307 return false; 14308 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14309 14310 // For the non-array case, the designator must be empty if the static type 14311 // does not have a virtual destructor. 14312 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14313 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14314 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14315 << Arg->getType()->getPointeeType() << AllocType; 14316 return false; 14317 } 14318 14319 // For a class type with a virtual destructor, the selected operator delete 14320 // is the one looked up when building the destructor. 14321 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14322 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14323 if (VirtualDelete && 14324 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14325 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14326 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14327 return false; 14328 } 14329 } 14330 14331 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14332 (*Alloc)->Value, AllocType)) 14333 return false; 14334 14335 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14336 // The element was already erased. This means the destructor call also 14337 // deleted the object. 14338 // FIXME: This probably results in undefined behavior before we get this 14339 // far, and should be diagnosed elsewhere first. 14340 Info.FFDiag(E, diag::note_constexpr_double_delete); 14341 return false; 14342 } 14343 14344 return true; 14345 } 14346 14347 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14348 assert(E->isRValue() && E->getType()->isVoidType()); 14349 return VoidExprEvaluator(Info).Visit(E); 14350 } 14351 14352 //===----------------------------------------------------------------------===// 14353 // Top level Expr::EvaluateAsRValue method. 14354 //===----------------------------------------------------------------------===// 14355 14356 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14357 // In C, function designators are not lvalues, but we evaluate them as if they 14358 // are. 14359 QualType T = E->getType(); 14360 if (E->isGLValue() || T->isFunctionType()) { 14361 LValue LV; 14362 if (!EvaluateLValue(E, LV, Info)) 14363 return false; 14364 LV.moveInto(Result); 14365 } else if (T->isVectorType()) { 14366 if (!EvaluateVector(E, Result, Info)) 14367 return false; 14368 } else if (T->isIntegralOrEnumerationType()) { 14369 if (!IntExprEvaluator(Info, Result).Visit(E)) 14370 return false; 14371 } else if (T->hasPointerRepresentation()) { 14372 LValue LV; 14373 if (!EvaluatePointer(E, LV, Info)) 14374 return false; 14375 LV.moveInto(Result); 14376 } else if (T->isRealFloatingType()) { 14377 llvm::APFloat F(0.0); 14378 if (!EvaluateFloat(E, F, Info)) 14379 return false; 14380 Result = APValue(F); 14381 } else if (T->isAnyComplexType()) { 14382 ComplexValue C; 14383 if (!EvaluateComplex(E, C, Info)) 14384 return false; 14385 C.moveInto(Result); 14386 } else if (T->isFixedPointType()) { 14387 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14388 } else if (T->isMemberPointerType()) { 14389 MemberPtr P; 14390 if (!EvaluateMemberPointer(E, P, Info)) 14391 return false; 14392 P.moveInto(Result); 14393 return true; 14394 } else if (T->isArrayType()) { 14395 LValue LV; 14396 APValue &Value = 14397 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14398 if (!EvaluateArray(E, LV, Value, Info)) 14399 return false; 14400 Result = Value; 14401 } else if (T->isRecordType()) { 14402 LValue LV; 14403 APValue &Value = 14404 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14405 if (!EvaluateRecord(E, LV, Value, Info)) 14406 return false; 14407 Result = Value; 14408 } else if (T->isVoidType()) { 14409 if (!Info.getLangOpts().CPlusPlus11) 14410 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14411 << E->getType(); 14412 if (!EvaluateVoid(E, Info)) 14413 return false; 14414 } else if (T->isAtomicType()) { 14415 QualType Unqual = T.getAtomicUnqualifiedType(); 14416 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14417 LValue LV; 14418 APValue &Value = Info.CurrentCall->createTemporary( 14419 E, Unqual, ScopeKind::FullExpression, LV); 14420 if (!EvaluateAtomic(E, &LV, Value, Info)) 14421 return false; 14422 } else { 14423 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14424 return false; 14425 } 14426 } else if (Info.getLangOpts().CPlusPlus11) { 14427 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14428 return false; 14429 } else { 14430 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14431 return false; 14432 } 14433 14434 return true; 14435 } 14436 14437 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14438 /// cases, the in-place evaluation is essential, since later initializers for 14439 /// an object can indirectly refer to subobjects which were initialized earlier. 14440 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14441 const Expr *E, bool AllowNonLiteralTypes) { 14442 assert(!E->isValueDependent()); 14443 14444 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14445 return false; 14446 14447 if (E->isRValue()) { 14448 // Evaluate arrays and record types in-place, so that later initializers can 14449 // refer to earlier-initialized members of the object. 14450 QualType T = E->getType(); 14451 if (T->isArrayType()) 14452 return EvaluateArray(E, This, Result, Info); 14453 else if (T->isRecordType()) 14454 return EvaluateRecord(E, This, Result, Info); 14455 else if (T->isAtomicType()) { 14456 QualType Unqual = T.getAtomicUnqualifiedType(); 14457 if (Unqual->isArrayType() || Unqual->isRecordType()) 14458 return EvaluateAtomic(E, &This, Result, Info); 14459 } 14460 } 14461 14462 // For any other type, in-place evaluation is unimportant. 14463 return Evaluate(Result, Info, E); 14464 } 14465 14466 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14467 /// lvalue-to-rvalue cast if it is an lvalue. 14468 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14469 if (Info.EnableNewConstInterp) { 14470 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14471 return false; 14472 } else { 14473 if (E->getType().isNull()) 14474 return false; 14475 14476 if (!CheckLiteralType(Info, E)) 14477 return false; 14478 14479 if (!::Evaluate(Result, Info, E)) 14480 return false; 14481 14482 if (E->isGLValue()) { 14483 LValue LV; 14484 LV.setFrom(Info.Ctx, Result); 14485 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14486 return false; 14487 } 14488 } 14489 14490 // Check this core constant expression is a constant expression. 14491 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 14492 CheckMemoryLeaks(Info); 14493 } 14494 14495 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14496 const ASTContext &Ctx, bool &IsConst) { 14497 // Fast-path evaluations of integer literals, since we sometimes see files 14498 // containing vast quantities of these. 14499 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14500 Result.Val = APValue(APSInt(L->getValue(), 14501 L->getType()->isUnsignedIntegerType())); 14502 IsConst = true; 14503 return true; 14504 } 14505 14506 // This case should be rare, but we need to check it before we check on 14507 // the type below. 14508 if (Exp->getType().isNull()) { 14509 IsConst = false; 14510 return true; 14511 } 14512 14513 // FIXME: Evaluating values of large array and record types can cause 14514 // performance problems. Only do so in C++11 for now. 14515 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14516 Exp->getType()->isRecordType()) && 14517 !Ctx.getLangOpts().CPlusPlus11) { 14518 IsConst = false; 14519 return true; 14520 } 14521 return false; 14522 } 14523 14524 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14525 Expr::SideEffectsKind SEK) { 14526 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14527 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14528 } 14529 14530 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14531 const ASTContext &Ctx, EvalInfo &Info) { 14532 bool IsConst; 14533 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14534 return IsConst; 14535 14536 return EvaluateAsRValue(Info, E, Result.Val); 14537 } 14538 14539 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14540 const ASTContext &Ctx, 14541 Expr::SideEffectsKind AllowSideEffects, 14542 EvalInfo &Info) { 14543 if (!E->getType()->isIntegralOrEnumerationType()) 14544 return false; 14545 14546 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14547 !ExprResult.Val.isInt() || 14548 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14549 return false; 14550 14551 return true; 14552 } 14553 14554 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14555 const ASTContext &Ctx, 14556 Expr::SideEffectsKind AllowSideEffects, 14557 EvalInfo &Info) { 14558 if (!E->getType()->isFixedPointType()) 14559 return false; 14560 14561 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14562 return false; 14563 14564 if (!ExprResult.Val.isFixedPoint() || 14565 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14566 return false; 14567 14568 return true; 14569 } 14570 14571 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14572 /// any crazy technique (that has nothing to do with language standards) that 14573 /// we want to. If this function returns true, it returns the folded constant 14574 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14575 /// will be applied to the result. 14576 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14577 bool InConstantContext) const { 14578 assert(!isValueDependent() && 14579 "Expression evaluator can't be called on a dependent expression."); 14580 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14581 Info.InConstantContext = InConstantContext; 14582 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14583 } 14584 14585 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14586 bool InConstantContext) const { 14587 assert(!isValueDependent() && 14588 "Expression evaluator can't be called on a dependent expression."); 14589 EvalResult Scratch; 14590 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14591 HandleConversionToBool(Scratch.Val, Result); 14592 } 14593 14594 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14595 SideEffectsKind AllowSideEffects, 14596 bool InConstantContext) const { 14597 assert(!isValueDependent() && 14598 "Expression evaluator can't be called on a dependent expression."); 14599 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14600 Info.InConstantContext = InConstantContext; 14601 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14602 } 14603 14604 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14605 SideEffectsKind AllowSideEffects, 14606 bool InConstantContext) const { 14607 assert(!isValueDependent() && 14608 "Expression evaluator can't be called on a dependent expression."); 14609 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14610 Info.InConstantContext = InConstantContext; 14611 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14612 } 14613 14614 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14615 SideEffectsKind AllowSideEffects, 14616 bool InConstantContext) const { 14617 assert(!isValueDependent() && 14618 "Expression evaluator can't be called on a dependent expression."); 14619 14620 if (!getType()->isRealFloatingType()) 14621 return false; 14622 14623 EvalResult ExprResult; 14624 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14625 !ExprResult.Val.isFloat() || 14626 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14627 return false; 14628 14629 Result = ExprResult.Val.getFloat(); 14630 return true; 14631 } 14632 14633 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14634 bool InConstantContext) const { 14635 assert(!isValueDependent() && 14636 "Expression evaluator can't be called on a dependent expression."); 14637 14638 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14639 Info.InConstantContext = InConstantContext; 14640 LValue LV; 14641 CheckedTemporaries CheckedTemps; 14642 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14643 Result.HasSideEffects || 14644 !CheckLValueConstantExpression(Info, getExprLoc(), 14645 Ctx.getLValueReferenceType(getType()), LV, 14646 Expr::EvaluateForCodeGen, CheckedTemps)) 14647 return false; 14648 14649 LV.moveInto(Result.Val); 14650 return true; 14651 } 14652 14653 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 14654 const ASTContext &Ctx, bool InPlace) const { 14655 assert(!isValueDependent() && 14656 "Expression evaluator can't be called on a dependent expression."); 14657 14658 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14659 EvalInfo Info(Ctx, Result, EM); 14660 Info.InConstantContext = true; 14661 14662 if (InPlace) { 14663 Info.setEvaluatingDecl(this, Result.Val); 14664 LValue LVal; 14665 LVal.set(this); 14666 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 14667 Result.HasSideEffects) 14668 return false; 14669 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 14670 return false; 14671 14672 if (!Info.discardCleanups()) 14673 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14674 14675 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14676 Result.Val, Usage) && 14677 CheckMemoryLeaks(Info); 14678 } 14679 14680 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14681 const VarDecl *VD, 14682 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14683 bool IsConstantInitialization) const { 14684 assert(!isValueDependent() && 14685 "Expression evaluator can't be called on a dependent expression."); 14686 14687 // FIXME: Evaluating initializers for large array and record types can cause 14688 // performance problems. Only do so in C++11 for now. 14689 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14690 !Ctx.getLangOpts().CPlusPlus11) 14691 return false; 14692 14693 Expr::EvalStatus EStatus; 14694 EStatus.Diag = &Notes; 14695 14696 EvalInfo Info(Ctx, EStatus, 14697 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14698 ? EvalInfo::EM_ConstantExpression 14699 : EvalInfo::EM_ConstantFold); 14700 Info.setEvaluatingDecl(VD, Value); 14701 Info.InConstantContext = IsConstantInitialization; 14702 14703 SourceLocation DeclLoc = VD->getLocation(); 14704 QualType DeclTy = VD->getType(); 14705 14706 if (Info.EnableNewConstInterp) { 14707 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14708 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14709 return false; 14710 } else { 14711 LValue LVal; 14712 LVal.set(VD); 14713 14714 if (!EvaluateInPlace(Value, Info, LVal, this, 14715 /*AllowNonLiteralTypes=*/true) || 14716 EStatus.HasSideEffects) 14717 return false; 14718 14719 // At this point, any lifetime-extended temporaries are completely 14720 // initialized. 14721 Info.performLifetimeExtension(); 14722 14723 if (!Info.discardCleanups()) 14724 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14725 } 14726 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 14727 CheckMemoryLeaks(Info); 14728 } 14729 14730 bool VarDecl::evaluateDestruction( 14731 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14732 Expr::EvalStatus EStatus; 14733 EStatus.Diag = &Notes; 14734 14735 // Make a copy of the value for the destructor to mutate, if we know it. 14736 // Otherwise, treat the value as default-initialized; if the destructor works 14737 // anyway, then the destruction is constant (and must be essentially empty). 14738 APValue DestroyedValue; 14739 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14740 DestroyedValue = *getEvaluatedValue(); 14741 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14742 return false; 14743 14744 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 14745 Info.setEvaluatingDecl(this, DestroyedValue, 14746 EvalInfo::EvaluatingDeclKind::Dtor); 14747 Info.InConstantContext = true; 14748 14749 SourceLocation DeclLoc = getLocation(); 14750 QualType DeclTy = getType(); 14751 14752 LValue LVal; 14753 LVal.set(this); 14754 14755 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 14756 EStatus.HasSideEffects) 14757 return false; 14758 14759 if (!Info.discardCleanups()) 14760 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14761 14762 ensureEvaluatedStmt()->HasConstantDestruction = true; 14763 return true; 14764 } 14765 14766 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14767 /// constant folded, but discard the result. 14768 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14769 assert(!isValueDependent() && 14770 "Expression evaluator can't be called on a dependent expression."); 14771 14772 EvalResult Result; 14773 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14774 !hasUnacceptableSideEffect(Result, SEK); 14775 } 14776 14777 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14778 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14779 assert(!isValueDependent() && 14780 "Expression evaluator can't be called on a dependent expression."); 14781 14782 EvalResult EVResult; 14783 EVResult.Diag = Diag; 14784 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14785 Info.InConstantContext = true; 14786 14787 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14788 (void)Result; 14789 assert(Result && "Could not evaluate expression"); 14790 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14791 14792 return EVResult.Val.getInt(); 14793 } 14794 14795 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14796 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14797 assert(!isValueDependent() && 14798 "Expression evaluator can't be called on a dependent expression."); 14799 14800 EvalResult EVResult; 14801 EVResult.Diag = Diag; 14802 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14803 Info.InConstantContext = true; 14804 Info.CheckingForUndefinedBehavior = true; 14805 14806 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14807 (void)Result; 14808 assert(Result && "Could not evaluate expression"); 14809 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14810 14811 return EVResult.Val.getInt(); 14812 } 14813 14814 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14815 assert(!isValueDependent() && 14816 "Expression evaluator can't be called on a dependent expression."); 14817 14818 bool IsConst; 14819 EvalResult EVResult; 14820 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14821 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14822 Info.CheckingForUndefinedBehavior = true; 14823 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14824 } 14825 } 14826 14827 bool Expr::EvalResult::isGlobalLValue() const { 14828 assert(Val.isLValue()); 14829 return IsGlobalLValue(Val.getLValueBase()); 14830 } 14831 14832 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14833 /// an integer constant expression. 14834 14835 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14836 /// comma, etc 14837 14838 // CheckICE - This function does the fundamental ICE checking: the returned 14839 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14840 // and a (possibly null) SourceLocation indicating the location of the problem. 14841 // 14842 // Note that to reduce code duplication, this helper does no evaluation 14843 // itself; the caller checks whether the expression is evaluatable, and 14844 // in the rare cases where CheckICE actually cares about the evaluated 14845 // value, it calls into Evaluate. 14846 14847 namespace { 14848 14849 enum ICEKind { 14850 /// This expression is an ICE. 14851 IK_ICE, 14852 /// This expression is not an ICE, but if it isn't evaluated, it's 14853 /// a legal subexpression for an ICE. This return value is used to handle 14854 /// the comma operator in C99 mode, and non-constant subexpressions. 14855 IK_ICEIfUnevaluated, 14856 /// This expression is not an ICE, and is not a legal subexpression for one. 14857 IK_NotICE 14858 }; 14859 14860 struct ICEDiag { 14861 ICEKind Kind; 14862 SourceLocation Loc; 14863 14864 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14865 }; 14866 14867 } 14868 14869 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14870 14871 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14872 14873 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14874 Expr::EvalResult EVResult; 14875 Expr::EvalStatus Status; 14876 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14877 14878 Info.InConstantContext = true; 14879 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14880 !EVResult.Val.isInt()) 14881 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14882 14883 return NoDiag(); 14884 } 14885 14886 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14887 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14888 if (!E->getType()->isIntegralOrEnumerationType()) 14889 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14890 14891 switch (E->getStmtClass()) { 14892 #define ABSTRACT_STMT(Node) 14893 #define STMT(Node, Base) case Expr::Node##Class: 14894 #define EXPR(Node, Base) 14895 #include "clang/AST/StmtNodes.inc" 14896 case Expr::PredefinedExprClass: 14897 case Expr::FloatingLiteralClass: 14898 case Expr::ImaginaryLiteralClass: 14899 case Expr::StringLiteralClass: 14900 case Expr::ArraySubscriptExprClass: 14901 case Expr::MatrixSubscriptExprClass: 14902 case Expr::OMPArraySectionExprClass: 14903 case Expr::OMPArrayShapingExprClass: 14904 case Expr::OMPIteratorExprClass: 14905 case Expr::MemberExprClass: 14906 case Expr::CompoundAssignOperatorClass: 14907 case Expr::CompoundLiteralExprClass: 14908 case Expr::ExtVectorElementExprClass: 14909 case Expr::DesignatedInitExprClass: 14910 case Expr::ArrayInitLoopExprClass: 14911 case Expr::ArrayInitIndexExprClass: 14912 case Expr::NoInitExprClass: 14913 case Expr::DesignatedInitUpdateExprClass: 14914 case Expr::ImplicitValueInitExprClass: 14915 case Expr::ParenListExprClass: 14916 case Expr::VAArgExprClass: 14917 case Expr::AddrLabelExprClass: 14918 case Expr::StmtExprClass: 14919 case Expr::CXXMemberCallExprClass: 14920 case Expr::CUDAKernelCallExprClass: 14921 case Expr::CXXAddrspaceCastExprClass: 14922 case Expr::CXXDynamicCastExprClass: 14923 case Expr::CXXTypeidExprClass: 14924 case Expr::CXXUuidofExprClass: 14925 case Expr::MSPropertyRefExprClass: 14926 case Expr::MSPropertySubscriptExprClass: 14927 case Expr::CXXNullPtrLiteralExprClass: 14928 case Expr::UserDefinedLiteralClass: 14929 case Expr::CXXThisExprClass: 14930 case Expr::CXXThrowExprClass: 14931 case Expr::CXXNewExprClass: 14932 case Expr::CXXDeleteExprClass: 14933 case Expr::CXXPseudoDestructorExprClass: 14934 case Expr::UnresolvedLookupExprClass: 14935 case Expr::TypoExprClass: 14936 case Expr::RecoveryExprClass: 14937 case Expr::DependentScopeDeclRefExprClass: 14938 case Expr::CXXConstructExprClass: 14939 case Expr::CXXInheritedCtorInitExprClass: 14940 case Expr::CXXStdInitializerListExprClass: 14941 case Expr::CXXBindTemporaryExprClass: 14942 case Expr::ExprWithCleanupsClass: 14943 case Expr::CXXTemporaryObjectExprClass: 14944 case Expr::CXXUnresolvedConstructExprClass: 14945 case Expr::CXXDependentScopeMemberExprClass: 14946 case Expr::UnresolvedMemberExprClass: 14947 case Expr::ObjCStringLiteralClass: 14948 case Expr::ObjCBoxedExprClass: 14949 case Expr::ObjCArrayLiteralClass: 14950 case Expr::ObjCDictionaryLiteralClass: 14951 case Expr::ObjCEncodeExprClass: 14952 case Expr::ObjCMessageExprClass: 14953 case Expr::ObjCSelectorExprClass: 14954 case Expr::ObjCProtocolExprClass: 14955 case Expr::ObjCIvarRefExprClass: 14956 case Expr::ObjCPropertyRefExprClass: 14957 case Expr::ObjCSubscriptRefExprClass: 14958 case Expr::ObjCIsaExprClass: 14959 case Expr::ObjCAvailabilityCheckExprClass: 14960 case Expr::ShuffleVectorExprClass: 14961 case Expr::ConvertVectorExprClass: 14962 case Expr::BlockExprClass: 14963 case Expr::NoStmtClass: 14964 case Expr::OpaqueValueExprClass: 14965 case Expr::PackExpansionExprClass: 14966 case Expr::SubstNonTypeTemplateParmPackExprClass: 14967 case Expr::FunctionParmPackExprClass: 14968 case Expr::AsTypeExprClass: 14969 case Expr::ObjCIndirectCopyRestoreExprClass: 14970 case Expr::MaterializeTemporaryExprClass: 14971 case Expr::PseudoObjectExprClass: 14972 case Expr::AtomicExprClass: 14973 case Expr::LambdaExprClass: 14974 case Expr::CXXFoldExprClass: 14975 case Expr::CoawaitExprClass: 14976 case Expr::DependentCoawaitExprClass: 14977 case Expr::CoyieldExprClass: 14978 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14979 14980 case Expr::InitListExprClass: { 14981 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14982 // form "T x = { a };" is equivalent to "T x = a;". 14983 // Unless we're initializing a reference, T is a scalar as it is known to be 14984 // of integral or enumeration type. 14985 if (E->isRValue()) 14986 if (cast<InitListExpr>(E)->getNumInits() == 1) 14987 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 14988 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14989 } 14990 14991 case Expr::SizeOfPackExprClass: 14992 case Expr::GNUNullExprClass: 14993 case Expr::SourceLocExprClass: 14994 return NoDiag(); 14995 14996 case Expr::SubstNonTypeTemplateParmExprClass: 14997 return 14998 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 14999 15000 case Expr::ConstantExprClass: 15001 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15002 15003 case Expr::ParenExprClass: 15004 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15005 case Expr::GenericSelectionExprClass: 15006 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15007 case Expr::IntegerLiteralClass: 15008 case Expr::FixedPointLiteralClass: 15009 case Expr::CharacterLiteralClass: 15010 case Expr::ObjCBoolLiteralExprClass: 15011 case Expr::CXXBoolLiteralExprClass: 15012 case Expr::CXXScalarValueInitExprClass: 15013 case Expr::TypeTraitExprClass: 15014 case Expr::ConceptSpecializationExprClass: 15015 case Expr::RequiresExprClass: 15016 case Expr::ArrayTypeTraitExprClass: 15017 case Expr::ExpressionTraitExprClass: 15018 case Expr::CXXNoexceptExprClass: 15019 return NoDiag(); 15020 case Expr::CallExprClass: 15021 case Expr::CXXOperatorCallExprClass: { 15022 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15023 // constant expressions, but they can never be ICEs because an ICE cannot 15024 // contain an operand of (pointer to) function type. 15025 const CallExpr *CE = cast<CallExpr>(E); 15026 if (CE->getBuiltinCallee()) 15027 return CheckEvalInICE(E, Ctx); 15028 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15029 } 15030 case Expr::CXXRewrittenBinaryOperatorClass: 15031 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15032 Ctx); 15033 case Expr::DeclRefExprClass: { 15034 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15035 if (isa<EnumConstantDecl>(D)) 15036 return NoDiag(); 15037 15038 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15039 // integer variables in constant expressions: 15040 // 15041 // C++ 7.1.5.1p2 15042 // A variable of non-volatile const-qualified integral or enumeration 15043 // type initialized by an ICE can be used in ICEs. 15044 const VarDecl *VD = dyn_cast<VarDecl>(D); 15045 if (VD && VD->isUsableInConstantExpressions(Ctx)) 15046 return NoDiag(); 15047 15048 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15049 } 15050 case Expr::UnaryOperatorClass: { 15051 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15052 switch (Exp->getOpcode()) { 15053 case UO_PostInc: 15054 case UO_PostDec: 15055 case UO_PreInc: 15056 case UO_PreDec: 15057 case UO_AddrOf: 15058 case UO_Deref: 15059 case UO_Coawait: 15060 // C99 6.6/3 allows increment and decrement within unevaluated 15061 // subexpressions of constant expressions, but they can never be ICEs 15062 // because an ICE cannot contain an lvalue operand. 15063 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15064 case UO_Extension: 15065 case UO_LNot: 15066 case UO_Plus: 15067 case UO_Minus: 15068 case UO_Not: 15069 case UO_Real: 15070 case UO_Imag: 15071 return CheckICE(Exp->getSubExpr(), Ctx); 15072 } 15073 llvm_unreachable("invalid unary operator class"); 15074 } 15075 case Expr::OffsetOfExprClass: { 15076 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15077 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15078 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15079 // compliance: we should warn earlier for offsetof expressions with 15080 // array subscripts that aren't ICEs, and if the array subscripts 15081 // are ICEs, the value of the offsetof must be an integer constant. 15082 return CheckEvalInICE(E, Ctx); 15083 } 15084 case Expr::UnaryExprOrTypeTraitExprClass: { 15085 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15086 if ((Exp->getKind() == UETT_SizeOf) && 15087 Exp->getTypeOfArgument()->isVariableArrayType()) 15088 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15089 return NoDiag(); 15090 } 15091 case Expr::BinaryOperatorClass: { 15092 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15093 switch (Exp->getOpcode()) { 15094 case BO_PtrMemD: 15095 case BO_PtrMemI: 15096 case BO_Assign: 15097 case BO_MulAssign: 15098 case BO_DivAssign: 15099 case BO_RemAssign: 15100 case BO_AddAssign: 15101 case BO_SubAssign: 15102 case BO_ShlAssign: 15103 case BO_ShrAssign: 15104 case BO_AndAssign: 15105 case BO_XorAssign: 15106 case BO_OrAssign: 15107 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15108 // constant expressions, but they can never be ICEs because an ICE cannot 15109 // contain an lvalue operand. 15110 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15111 15112 case BO_Mul: 15113 case BO_Div: 15114 case BO_Rem: 15115 case BO_Add: 15116 case BO_Sub: 15117 case BO_Shl: 15118 case BO_Shr: 15119 case BO_LT: 15120 case BO_GT: 15121 case BO_LE: 15122 case BO_GE: 15123 case BO_EQ: 15124 case BO_NE: 15125 case BO_And: 15126 case BO_Xor: 15127 case BO_Or: 15128 case BO_Comma: 15129 case BO_Cmp: { 15130 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15131 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15132 if (Exp->getOpcode() == BO_Div || 15133 Exp->getOpcode() == BO_Rem) { 15134 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15135 // we don't evaluate one. 15136 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15137 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15138 if (REval == 0) 15139 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15140 if (REval.isSigned() && REval.isAllOnesValue()) { 15141 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15142 if (LEval.isMinSignedValue()) 15143 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15144 } 15145 } 15146 } 15147 if (Exp->getOpcode() == BO_Comma) { 15148 if (Ctx.getLangOpts().C99) { 15149 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15150 // if it isn't evaluated. 15151 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15152 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15153 } else { 15154 // In both C89 and C++, commas in ICEs are illegal. 15155 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15156 } 15157 } 15158 return Worst(LHSResult, RHSResult); 15159 } 15160 case BO_LAnd: 15161 case BO_LOr: { 15162 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15163 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15164 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15165 // Rare case where the RHS has a comma "side-effect"; we need 15166 // to actually check the condition to see whether the side 15167 // with the comma is evaluated. 15168 if ((Exp->getOpcode() == BO_LAnd) != 15169 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15170 return RHSResult; 15171 return NoDiag(); 15172 } 15173 15174 return Worst(LHSResult, RHSResult); 15175 } 15176 } 15177 llvm_unreachable("invalid binary operator kind"); 15178 } 15179 case Expr::ImplicitCastExprClass: 15180 case Expr::CStyleCastExprClass: 15181 case Expr::CXXFunctionalCastExprClass: 15182 case Expr::CXXStaticCastExprClass: 15183 case Expr::CXXReinterpretCastExprClass: 15184 case Expr::CXXConstCastExprClass: 15185 case Expr::ObjCBridgedCastExprClass: { 15186 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15187 if (isa<ExplicitCastExpr>(E)) { 15188 if (const FloatingLiteral *FL 15189 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15190 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15191 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15192 APSInt IgnoredVal(DestWidth, !DestSigned); 15193 bool Ignored; 15194 // If the value does not fit in the destination type, the behavior is 15195 // undefined, so we are not required to treat it as a constant 15196 // expression. 15197 if (FL->getValue().convertToInteger(IgnoredVal, 15198 llvm::APFloat::rmTowardZero, 15199 &Ignored) & APFloat::opInvalidOp) 15200 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15201 return NoDiag(); 15202 } 15203 } 15204 switch (cast<CastExpr>(E)->getCastKind()) { 15205 case CK_LValueToRValue: 15206 case CK_AtomicToNonAtomic: 15207 case CK_NonAtomicToAtomic: 15208 case CK_NoOp: 15209 case CK_IntegralToBoolean: 15210 case CK_IntegralCast: 15211 return CheckICE(SubExpr, Ctx); 15212 default: 15213 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15214 } 15215 } 15216 case Expr::BinaryConditionalOperatorClass: { 15217 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15218 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15219 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15220 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15221 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15222 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15223 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15224 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15225 return FalseResult; 15226 } 15227 case Expr::ConditionalOperatorClass: { 15228 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15229 // If the condition (ignoring parens) is a __builtin_constant_p call, 15230 // then only the true side is actually considered in an integer constant 15231 // expression, and it is fully evaluated. This is an important GNU 15232 // extension. See GCC PR38377 for discussion. 15233 if (const CallExpr *CallCE 15234 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15235 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15236 return CheckEvalInICE(E, Ctx); 15237 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15238 if (CondResult.Kind == IK_NotICE) 15239 return CondResult; 15240 15241 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15242 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15243 15244 if (TrueResult.Kind == IK_NotICE) 15245 return TrueResult; 15246 if (FalseResult.Kind == IK_NotICE) 15247 return FalseResult; 15248 if (CondResult.Kind == IK_ICEIfUnevaluated) 15249 return CondResult; 15250 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15251 return NoDiag(); 15252 // Rare case where the diagnostics depend on which side is evaluated 15253 // Note that if we get here, CondResult is 0, and at least one of 15254 // TrueResult and FalseResult is non-zero. 15255 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15256 return FalseResult; 15257 return TrueResult; 15258 } 15259 case Expr::CXXDefaultArgExprClass: 15260 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15261 case Expr::CXXDefaultInitExprClass: 15262 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15263 case Expr::ChooseExprClass: { 15264 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15265 } 15266 case Expr::BuiltinBitCastExprClass: { 15267 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15268 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15269 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15270 } 15271 } 15272 15273 llvm_unreachable("Invalid StmtClass!"); 15274 } 15275 15276 /// Evaluate an expression as a C++11 integral constant expression. 15277 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15278 const Expr *E, 15279 llvm::APSInt *Value, 15280 SourceLocation *Loc) { 15281 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15282 if (Loc) *Loc = E->getExprLoc(); 15283 return false; 15284 } 15285 15286 APValue Result; 15287 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15288 return false; 15289 15290 if (!Result.isInt()) { 15291 if (Loc) *Loc = E->getExprLoc(); 15292 return false; 15293 } 15294 15295 if (Value) *Value = Result.getInt(); 15296 return true; 15297 } 15298 15299 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15300 SourceLocation *Loc) const { 15301 assert(!isValueDependent() && 15302 "Expression evaluator can't be called on a dependent expression."); 15303 15304 if (Ctx.getLangOpts().CPlusPlus11) 15305 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15306 15307 ICEDiag D = CheckICE(this, Ctx); 15308 if (D.Kind != IK_ICE) { 15309 if (Loc) *Loc = D.Loc; 15310 return false; 15311 } 15312 return true; 15313 } 15314 15315 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15316 SourceLocation *Loc, 15317 bool isEvaluated) const { 15318 assert(!isValueDependent() && 15319 "Expression evaluator can't be called on a dependent expression."); 15320 15321 APSInt Value; 15322 15323 if (Ctx.getLangOpts().CPlusPlus11) { 15324 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15325 return Value; 15326 return None; 15327 } 15328 15329 if (!isIntegerConstantExpr(Ctx, Loc)) 15330 return None; 15331 15332 // The only possible side-effects here are due to UB discovered in the 15333 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15334 // required to treat the expression as an ICE, so we produce the folded 15335 // value. 15336 EvalResult ExprResult; 15337 Expr::EvalStatus Status; 15338 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15339 Info.InConstantContext = true; 15340 15341 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15342 llvm_unreachable("ICE cannot be evaluated!"); 15343 15344 return ExprResult.Val.getInt(); 15345 } 15346 15347 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15348 assert(!isValueDependent() && 15349 "Expression evaluator can't be called on a dependent expression."); 15350 15351 return CheckICE(this, Ctx).Kind == IK_ICE; 15352 } 15353 15354 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15355 SourceLocation *Loc) const { 15356 assert(!isValueDependent() && 15357 "Expression evaluator can't be called on a dependent expression."); 15358 15359 // We support this checking in C++98 mode in order to diagnose compatibility 15360 // issues. 15361 assert(Ctx.getLangOpts().CPlusPlus); 15362 15363 // Build evaluation settings. 15364 Expr::EvalStatus Status; 15365 SmallVector<PartialDiagnosticAt, 8> Diags; 15366 Status.Diag = &Diags; 15367 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15368 15369 APValue Scratch; 15370 bool IsConstExpr = 15371 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15372 // FIXME: We don't produce a diagnostic for this, but the callers that 15373 // call us on arbitrary full-expressions should generally not care. 15374 Info.discardCleanups() && !Status.HasSideEffects; 15375 15376 if (!Diags.empty()) { 15377 IsConstExpr = false; 15378 if (Loc) *Loc = Diags[0].first; 15379 } else if (!IsConstExpr) { 15380 // FIXME: This shouldn't happen. 15381 if (Loc) *Loc = getExprLoc(); 15382 } 15383 15384 return IsConstExpr; 15385 } 15386 15387 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15388 const FunctionDecl *Callee, 15389 ArrayRef<const Expr*> Args, 15390 const Expr *This) const { 15391 assert(!isValueDependent() && 15392 "Expression evaluator can't be called on a dependent expression."); 15393 15394 Expr::EvalStatus Status; 15395 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15396 Info.InConstantContext = true; 15397 15398 LValue ThisVal; 15399 const LValue *ThisPtr = nullptr; 15400 if (This) { 15401 #ifndef NDEBUG 15402 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15403 assert(MD && "Don't provide `this` for non-methods."); 15404 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15405 #endif 15406 if (!This->isValueDependent() && 15407 EvaluateObjectArgument(Info, This, ThisVal) && 15408 !Info.EvalStatus.HasSideEffects) 15409 ThisPtr = &ThisVal; 15410 15411 // Ignore any side-effects from a failed evaluation. This is safe because 15412 // they can't interfere with any other argument evaluation. 15413 Info.EvalStatus.HasSideEffects = false; 15414 } 15415 15416 CallRef Call = Info.CurrentCall->createCall(Callee); 15417 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15418 I != E; ++I) { 15419 unsigned Idx = I - Args.begin(); 15420 if (Idx >= Callee->getNumParams()) 15421 break; 15422 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15423 if ((*I)->isValueDependent() || 15424 !EvaluateCallArg(PVD, *I, Call, Info) || 15425 Info.EvalStatus.HasSideEffects) { 15426 // If evaluation fails, throw away the argument entirely. 15427 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15428 *Slot = APValue(); 15429 } 15430 15431 // Ignore any side-effects from a failed evaluation. This is safe because 15432 // they can't interfere with any other argument evaluation. 15433 Info.EvalStatus.HasSideEffects = false; 15434 } 15435 15436 // Parameter cleanups happen in the caller and are not part of this 15437 // evaluation. 15438 Info.discardCleanups(); 15439 Info.EvalStatus.HasSideEffects = false; 15440 15441 // Build fake call to Callee. 15442 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15443 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15444 FullExpressionRAII Scope(Info); 15445 return Evaluate(Value, Info, this) && Scope.destroy() && 15446 !Info.EvalStatus.HasSideEffects; 15447 } 15448 15449 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15450 SmallVectorImpl< 15451 PartialDiagnosticAt> &Diags) { 15452 // FIXME: It would be useful to check constexpr function templates, but at the 15453 // moment the constant expression evaluator cannot cope with the non-rigorous 15454 // ASTs which we build for dependent expressions. 15455 if (FD->isDependentContext()) 15456 return true; 15457 15458 // Bail out if a constexpr constructor has an initializer that contains an 15459 // error. We deliberately don't produce a diagnostic, as we have produced a 15460 // relevant diagnostic when parsing the error initializer. 15461 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15462 for (const auto *InitExpr : Ctor->inits()) { 15463 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 15464 return false; 15465 } 15466 } 15467 Expr::EvalStatus Status; 15468 Status.Diag = &Diags; 15469 15470 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15471 Info.InConstantContext = true; 15472 Info.CheckingPotentialConstantExpression = true; 15473 15474 // The constexpr VM attempts to compile all methods to bytecode here. 15475 if (Info.EnableNewConstInterp) { 15476 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15477 return Diags.empty(); 15478 } 15479 15480 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15481 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15482 15483 // Fabricate an arbitrary expression on the stack and pretend that it 15484 // is a temporary being used as the 'this' pointer. 15485 LValue This; 15486 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15487 This.set({&VIE, Info.CurrentCall->Index}); 15488 15489 ArrayRef<const Expr*> Args; 15490 15491 APValue Scratch; 15492 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15493 // Evaluate the call as a constant initializer, to allow the construction 15494 // of objects of non-literal types. 15495 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15496 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15497 } else { 15498 SourceLocation Loc = FD->getLocation(); 15499 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15500 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15501 } 15502 15503 return Diags.empty(); 15504 } 15505 15506 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15507 const FunctionDecl *FD, 15508 SmallVectorImpl< 15509 PartialDiagnosticAt> &Diags) { 15510 assert(!E->isValueDependent() && 15511 "Expression evaluator can't be called on a dependent expression."); 15512 15513 Expr::EvalStatus Status; 15514 Status.Diag = &Diags; 15515 15516 EvalInfo Info(FD->getASTContext(), Status, 15517 EvalInfo::EM_ConstantExpressionUnevaluated); 15518 Info.InConstantContext = true; 15519 Info.CheckingPotentialConstantExpression = true; 15520 15521 // Fabricate a call stack frame to give the arguments a plausible cover story. 15522 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15523 15524 APValue ResultScratch; 15525 Evaluate(ResultScratch, Info, E); 15526 return Diags.empty(); 15527 } 15528 15529 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15530 unsigned Type) const { 15531 if (!getType()->isPointerType()) 15532 return false; 15533 15534 Expr::EvalStatus Status; 15535 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15536 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15537 } 15538