1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 return B.getType(); 83 } 84 85 /// Get an LValue path entry, which is known to not be an array index, as a 86 /// field declaration. 87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 89 } 90 /// Get an LValue path entry, which is known to not be an array index, as a 91 /// base class declaration. 92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 94 } 95 /// Determine whether this LValue path entry for a base class names a virtual 96 /// base class. 97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 98 return E.getAsBaseOrMember().getInt(); 99 } 100 101 /// Given an expression, determine the type used to store the result of 102 /// evaluating that expression. 103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 104 if (E->isRValue()) 105 return E->getType(); 106 return Ctx.getLValueReferenceType(E->getType()); 107 } 108 109 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 111 const FunctionDecl *Callee = CE->getDirectCallee(); 112 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 113 } 114 115 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 116 /// This will look through a single cast. 117 /// 118 /// Returns null if we couldn't unwrap a function with alloc_size. 119 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 120 if (!E->getType()->isPointerType()) 121 return nullptr; 122 123 E = E->IgnoreParens(); 124 // If we're doing a variable assignment from e.g. malloc(N), there will 125 // probably be a cast of some kind. In exotic cases, we might also see a 126 // top-level ExprWithCleanups. Ignore them either way. 127 if (const auto *FE = dyn_cast<FullExpr>(E)) 128 E = FE->getSubExpr()->IgnoreParens(); 129 130 if (const auto *Cast = dyn_cast<CastExpr>(E)) 131 E = Cast->getSubExpr()->IgnoreParens(); 132 133 if (const auto *CE = dyn_cast<CallExpr>(E)) 134 return getAllocSizeAttr(CE) ? CE : nullptr; 135 return nullptr; 136 } 137 138 /// Determines whether or not the given Base contains a call to a function 139 /// with the alloc_size attribute. 140 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 141 const auto *E = Base.dyn_cast<const Expr *>(); 142 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 143 } 144 145 /// Determines whether the given kind of constant expression is only ever 146 /// used for name mangling. If so, it's permitted to reference things that we 147 /// can't generate code for (in particular, dllimported functions). 148 static bool isForManglingOnly(ConstantExprKind Kind) { 149 switch (Kind) { 150 case ConstantExprKind::Normal: 151 case ConstantExprKind::ClassTemplateArgument: 152 case ConstantExprKind::ImmediateInvocation: 153 // Note that non-type template arguments of class type are emitted as 154 // template parameter objects. 155 return false; 156 157 case ConstantExprKind::NonClassTemplateArgument: 158 return true; 159 } 160 llvm_unreachable("unknown ConstantExprKind"); 161 } 162 163 static bool isTemplateArgument(ConstantExprKind Kind) { 164 switch (Kind) { 165 case ConstantExprKind::Normal: 166 case ConstantExprKind::ImmediateInvocation: 167 return false; 168 169 case ConstantExprKind::ClassTemplateArgument: 170 case ConstantExprKind::NonClassTemplateArgument: 171 return true; 172 } 173 llvm_unreachable("unknown ConstantExprKind"); 174 } 175 176 /// The bound to claim that an array of unknown bound has. 177 /// The value in MostDerivedArraySize is undefined in this case. So, set it 178 /// to an arbitrary value that's likely to loudly break things if it's used. 179 static const uint64_t AssumedSizeForUnsizedArray = 180 std::numeric_limits<uint64_t>::max() / 2; 181 182 /// Determines if an LValue with the given LValueBase will have an unsized 183 /// array in its designator. 184 /// Find the path length and type of the most-derived subobject in the given 185 /// path, and find the size of the containing array, if any. 186 static unsigned 187 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 188 ArrayRef<APValue::LValuePathEntry> Path, 189 uint64_t &ArraySize, QualType &Type, bool &IsArray, 190 bool &FirstEntryIsUnsizedArray) { 191 // This only accepts LValueBases from APValues, and APValues don't support 192 // arrays that lack size info. 193 assert(!isBaseAnAllocSizeCall(Base) && 194 "Unsized arrays shouldn't appear here"); 195 unsigned MostDerivedLength = 0; 196 Type = getType(Base); 197 198 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 199 if (Type->isArrayType()) { 200 const ArrayType *AT = Ctx.getAsArrayType(Type); 201 Type = AT->getElementType(); 202 MostDerivedLength = I + 1; 203 IsArray = true; 204 205 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 206 ArraySize = CAT->getSize().getZExtValue(); 207 } else { 208 assert(I == 0 && "unexpected unsized array designator"); 209 FirstEntryIsUnsizedArray = true; 210 ArraySize = AssumedSizeForUnsizedArray; 211 } 212 } else if (Type->isAnyComplexType()) { 213 const ComplexType *CT = Type->castAs<ComplexType>(); 214 Type = CT->getElementType(); 215 ArraySize = 2; 216 MostDerivedLength = I + 1; 217 IsArray = true; 218 } else if (const FieldDecl *FD = getAsField(Path[I])) { 219 Type = FD->getType(); 220 ArraySize = 0; 221 MostDerivedLength = I + 1; 222 IsArray = false; 223 } else { 224 // Path[I] describes a base class. 225 ArraySize = 0; 226 IsArray = false; 227 } 228 } 229 return MostDerivedLength; 230 } 231 232 /// A path from a glvalue to a subobject of that glvalue. 233 struct SubobjectDesignator { 234 /// True if the subobject was named in a manner not supported by C++11. Such 235 /// lvalues can still be folded, but they are not core constant expressions 236 /// and we cannot perform lvalue-to-rvalue conversions on them. 237 unsigned Invalid : 1; 238 239 /// Is this a pointer one past the end of an object? 240 unsigned IsOnePastTheEnd : 1; 241 242 /// Indicator of whether the first entry is an unsized array. 243 unsigned FirstEntryIsAnUnsizedArray : 1; 244 245 /// Indicator of whether the most-derived object is an array element. 246 unsigned MostDerivedIsArrayElement : 1; 247 248 /// The length of the path to the most-derived object of which this is a 249 /// subobject. 250 unsigned MostDerivedPathLength : 28; 251 252 /// The size of the array of which the most-derived object is an element. 253 /// This will always be 0 if the most-derived object is not an array 254 /// element. 0 is not an indicator of whether or not the most-derived object 255 /// is an array, however, because 0-length arrays are allowed. 256 /// 257 /// If the current array is an unsized array, the value of this is 258 /// undefined. 259 uint64_t MostDerivedArraySize; 260 261 /// The type of the most derived object referred to by this address. 262 QualType MostDerivedType; 263 264 typedef APValue::LValuePathEntry PathEntry; 265 266 /// The entries on the path from the glvalue to the designated subobject. 267 SmallVector<PathEntry, 8> Entries; 268 269 SubobjectDesignator() : Invalid(true) {} 270 271 explicit SubobjectDesignator(QualType T) 272 : Invalid(false), IsOnePastTheEnd(false), 273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 274 MostDerivedPathLength(0), MostDerivedArraySize(0), 275 MostDerivedType(T) {} 276 277 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 278 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 280 MostDerivedPathLength(0), MostDerivedArraySize(0) { 281 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 282 if (!Invalid) { 283 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 284 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 285 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 286 if (V.getLValueBase()) { 287 bool IsArray = false; 288 bool FirstIsUnsizedArray = false; 289 MostDerivedPathLength = findMostDerivedSubobject( 290 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 291 MostDerivedType, IsArray, FirstIsUnsizedArray); 292 MostDerivedIsArrayElement = IsArray; 293 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 294 } 295 } 296 } 297 298 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 299 unsigned NewLength) { 300 if (Invalid) 301 return; 302 303 assert(Base && "cannot truncate path for null pointer"); 304 assert(NewLength <= Entries.size() && "not a truncation"); 305 306 if (NewLength == Entries.size()) 307 return; 308 Entries.resize(NewLength); 309 310 bool IsArray = false; 311 bool FirstIsUnsizedArray = false; 312 MostDerivedPathLength = findMostDerivedSubobject( 313 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 314 FirstIsUnsizedArray); 315 MostDerivedIsArrayElement = IsArray; 316 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 317 } 318 319 void setInvalid() { 320 Invalid = true; 321 Entries.clear(); 322 } 323 324 /// Determine whether the most derived subobject is an array without a 325 /// known bound. 326 bool isMostDerivedAnUnsizedArray() const { 327 assert(!Invalid && "Calling this makes no sense on invalid designators"); 328 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 329 } 330 331 /// Determine what the most derived array's size is. Results in an assertion 332 /// failure if the most derived array lacks a size. 333 uint64_t getMostDerivedArraySize() const { 334 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 335 return MostDerivedArraySize; 336 } 337 338 /// Determine whether this is a one-past-the-end pointer. 339 bool isOnePastTheEnd() const { 340 assert(!Invalid); 341 if (IsOnePastTheEnd) 342 return true; 343 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 344 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 345 MostDerivedArraySize) 346 return true; 347 return false; 348 } 349 350 /// Get the range of valid index adjustments in the form 351 /// {maximum value that can be subtracted from this pointer, 352 /// maximum value that can be added to this pointer} 353 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 354 if (Invalid || isMostDerivedAnUnsizedArray()) 355 return {0, 0}; 356 357 // [expr.add]p4: For the purposes of these operators, a pointer to a 358 // nonarray object behaves the same as a pointer to the first element of 359 // an array of length one with the type of the object as its element type. 360 bool IsArray = MostDerivedPathLength == Entries.size() && 361 MostDerivedIsArrayElement; 362 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 363 : (uint64_t)IsOnePastTheEnd; 364 uint64_t ArraySize = 365 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 366 return {ArrayIndex, ArraySize - ArrayIndex}; 367 } 368 369 /// Check that this refers to a valid subobject. 370 bool isValidSubobject() const { 371 if (Invalid) 372 return false; 373 return !isOnePastTheEnd(); 374 } 375 /// Check that this refers to a valid subobject, and if not, produce a 376 /// relevant diagnostic and set the designator as invalid. 377 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 378 379 /// Get the type of the designated object. 380 QualType getType(ASTContext &Ctx) const { 381 assert(!Invalid && "invalid designator has no subobject type"); 382 return MostDerivedPathLength == Entries.size() 383 ? MostDerivedType 384 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 385 } 386 387 /// Update this designator to refer to the first element within this array. 388 void addArrayUnchecked(const ConstantArrayType *CAT) { 389 Entries.push_back(PathEntry::ArrayIndex(0)); 390 391 // This is a most-derived object. 392 MostDerivedType = CAT->getElementType(); 393 MostDerivedIsArrayElement = true; 394 MostDerivedArraySize = CAT->getSize().getZExtValue(); 395 MostDerivedPathLength = Entries.size(); 396 } 397 /// Update this designator to refer to the first element within the array of 398 /// elements of type T. This is an array of unknown size. 399 void addUnsizedArrayUnchecked(QualType ElemTy) { 400 Entries.push_back(PathEntry::ArrayIndex(0)); 401 402 MostDerivedType = ElemTy; 403 MostDerivedIsArrayElement = true; 404 // The value in MostDerivedArraySize is undefined in this case. So, set it 405 // to an arbitrary value that's likely to loudly break things if it's 406 // used. 407 MostDerivedArraySize = AssumedSizeForUnsizedArray; 408 MostDerivedPathLength = Entries.size(); 409 } 410 /// Update this designator to refer to the given base or member of this 411 /// object. 412 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 413 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 414 415 // If this isn't a base class, it's a new most-derived object. 416 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 417 MostDerivedType = FD->getType(); 418 MostDerivedIsArrayElement = false; 419 MostDerivedArraySize = 0; 420 MostDerivedPathLength = Entries.size(); 421 } 422 } 423 /// Update this designator to refer to the given complex component. 424 void addComplexUnchecked(QualType EltTy, bool Imag) { 425 Entries.push_back(PathEntry::ArrayIndex(Imag)); 426 427 // This is technically a most-derived object, though in practice this 428 // is unlikely to matter. 429 MostDerivedType = EltTy; 430 MostDerivedIsArrayElement = true; 431 MostDerivedArraySize = 2; 432 MostDerivedPathLength = Entries.size(); 433 } 434 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 435 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 436 const APSInt &N); 437 /// Add N to the address of this subobject. 438 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 439 if (Invalid || !N) return; 440 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 441 if (isMostDerivedAnUnsizedArray()) { 442 diagnoseUnsizedArrayPointerArithmetic(Info, E); 443 // Can't verify -- trust that the user is doing the right thing (or if 444 // not, trust that the caller will catch the bad behavior). 445 // FIXME: Should we reject if this overflows, at least? 446 Entries.back() = PathEntry::ArrayIndex( 447 Entries.back().getAsArrayIndex() + TruncatedN); 448 return; 449 } 450 451 // [expr.add]p4: For the purposes of these operators, a pointer to a 452 // nonarray object behaves the same as a pointer to the first element of 453 // an array of length one with the type of the object as its element type. 454 bool IsArray = MostDerivedPathLength == Entries.size() && 455 MostDerivedIsArrayElement; 456 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 457 : (uint64_t)IsOnePastTheEnd; 458 uint64_t ArraySize = 459 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 460 461 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 462 // Calculate the actual index in a wide enough type, so we can include 463 // it in the note. 464 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 465 (llvm::APInt&)N += ArrayIndex; 466 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 467 diagnosePointerArithmetic(Info, E, N); 468 setInvalid(); 469 return; 470 } 471 472 ArrayIndex += TruncatedN; 473 assert(ArrayIndex <= ArraySize && 474 "bounds check succeeded for out-of-bounds index"); 475 476 if (IsArray) 477 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 478 else 479 IsOnePastTheEnd = (ArrayIndex != 0); 480 } 481 }; 482 483 /// A scope at the end of which an object can need to be destroyed. 484 enum class ScopeKind { 485 Block, 486 FullExpression, 487 Call 488 }; 489 490 /// A reference to a particular call and its arguments. 491 struct CallRef { 492 CallRef() : OrigCallee(), CallIndex(0), Version() {} 493 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 494 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 495 496 explicit operator bool() const { return OrigCallee; } 497 498 /// Get the parameter that the caller initialized, corresponding to the 499 /// given parameter in the callee. 500 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 501 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 502 : PVD; 503 } 504 505 /// The callee at the point where the arguments were evaluated. This might 506 /// be different from the actual callee (a different redeclaration, or a 507 /// virtual override), but this function's parameters are the ones that 508 /// appear in the parameter map. 509 const FunctionDecl *OrigCallee; 510 /// The call index of the frame that holds the argument values. 511 unsigned CallIndex; 512 /// The version of the parameters corresponding to this call. 513 unsigned Version; 514 }; 515 516 /// A stack frame in the constexpr call stack. 517 class CallStackFrame : public interp::Frame { 518 public: 519 EvalInfo &Info; 520 521 /// Parent - The caller of this stack frame. 522 CallStackFrame *Caller; 523 524 /// Callee - The function which was called. 525 const FunctionDecl *Callee; 526 527 /// This - The binding for the this pointer in this call, if any. 528 const LValue *This; 529 530 /// Information on how to find the arguments to this call. Our arguments 531 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 532 /// key and this value as the version. 533 CallRef Arguments; 534 535 /// Source location information about the default argument or default 536 /// initializer expression we're evaluating, if any. 537 CurrentSourceLocExprScope CurSourceLocExprScope; 538 539 // Note that we intentionally use std::map here so that references to 540 // values are stable. 541 typedef std::pair<const void *, unsigned> MapKeyTy; 542 typedef std::map<MapKeyTy, APValue> MapTy; 543 /// Temporaries - Temporary lvalues materialized within this stack frame. 544 MapTy Temporaries; 545 546 /// CallLoc - The location of the call expression for this call. 547 SourceLocation CallLoc; 548 549 /// Index - The call index of this call. 550 unsigned Index; 551 552 /// The stack of integers for tracking version numbers for temporaries. 553 SmallVector<unsigned, 2> TempVersionStack = {1}; 554 unsigned CurTempVersion = TempVersionStack.back(); 555 556 unsigned getTempVersion() const { return TempVersionStack.back(); } 557 558 void pushTempVersion() { 559 TempVersionStack.push_back(++CurTempVersion); 560 } 561 562 void popTempVersion() { 563 TempVersionStack.pop_back(); 564 } 565 566 CallRef createCall(const FunctionDecl *Callee) { 567 return {Callee, Index, ++CurTempVersion}; 568 } 569 570 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 571 // on the overall stack usage of deeply-recursing constexpr evaluations. 572 // (We should cache this map rather than recomputing it repeatedly.) 573 // But let's try this and see how it goes; we can look into caching the map 574 // as a later change. 575 576 /// LambdaCaptureFields - Mapping from captured variables/this to 577 /// corresponding data members in the closure class. 578 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 579 FieldDecl *LambdaThisCaptureField; 580 581 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 582 const FunctionDecl *Callee, const LValue *This, 583 CallRef Arguments); 584 ~CallStackFrame(); 585 586 // Return the temporary for Key whose version number is Version. 587 APValue *getTemporary(const void *Key, unsigned Version) { 588 MapKeyTy KV(Key, Version); 589 auto LB = Temporaries.lower_bound(KV); 590 if (LB != Temporaries.end() && LB->first == KV) 591 return &LB->second; 592 // Pair (Key,Version) wasn't found in the map. Check that no elements 593 // in the map have 'Key' as their key. 594 assert((LB == Temporaries.end() || LB->first.first != Key) && 595 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 596 "Element with key 'Key' found in map"); 597 return nullptr; 598 } 599 600 // Return the current temporary for Key in the map. 601 APValue *getCurrentTemporary(const void *Key) { 602 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 603 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 604 return &std::prev(UB)->second; 605 return nullptr; 606 } 607 608 // Return the version number of the current temporary for Key. 609 unsigned getCurrentTemporaryVersion(const void *Key) const { 610 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 611 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 612 return std::prev(UB)->first.second; 613 return 0; 614 } 615 616 /// Allocate storage for an object of type T in this stack frame. 617 /// Populates LV with a handle to the created object. Key identifies 618 /// the temporary within the stack frame, and must not be reused without 619 /// bumping the temporary version number. 620 template<typename KeyT> 621 APValue &createTemporary(const KeyT *Key, QualType T, 622 ScopeKind Scope, LValue &LV); 623 624 /// Allocate storage for a parameter of a function call made in this frame. 625 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 626 627 void describe(llvm::raw_ostream &OS) override; 628 629 Frame *getCaller() const override { return Caller; } 630 SourceLocation getCallLocation() const override { return CallLoc; } 631 const FunctionDecl *getCallee() const override { return Callee; } 632 633 bool isStdFunction() const { 634 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 635 if (DC->isStdNamespace()) 636 return true; 637 return false; 638 } 639 640 private: 641 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 642 ScopeKind Scope); 643 }; 644 645 /// Temporarily override 'this'. 646 class ThisOverrideRAII { 647 public: 648 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 649 : Frame(Frame), OldThis(Frame.This) { 650 if (Enable) 651 Frame.This = NewThis; 652 } 653 ~ThisOverrideRAII() { 654 Frame.This = OldThis; 655 } 656 private: 657 CallStackFrame &Frame; 658 const LValue *OldThis; 659 }; 660 } 661 662 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 663 const LValue &This, QualType ThisType); 664 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 665 APValue::LValueBase LVBase, APValue &Value, 666 QualType T); 667 668 namespace { 669 /// A cleanup, and a flag indicating whether it is lifetime-extended. 670 class Cleanup { 671 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 672 APValue::LValueBase Base; 673 QualType T; 674 675 public: 676 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 677 ScopeKind Scope) 678 : Value(Val, Scope), Base(Base), T(T) {} 679 680 /// Determine whether this cleanup should be performed at the end of the 681 /// given kind of scope. 682 bool isDestroyedAtEndOf(ScopeKind K) const { 683 return (int)Value.getInt() >= (int)K; 684 } 685 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 686 if (RunDestructors) { 687 SourceLocation Loc; 688 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 689 Loc = VD->getLocation(); 690 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 691 Loc = E->getExprLoc(); 692 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 693 } 694 *Value.getPointer() = APValue(); 695 return true; 696 } 697 698 bool hasSideEffect() { 699 return T.isDestructedType(); 700 } 701 }; 702 703 /// A reference to an object whose construction we are currently evaluating. 704 struct ObjectUnderConstruction { 705 APValue::LValueBase Base; 706 ArrayRef<APValue::LValuePathEntry> Path; 707 friend bool operator==(const ObjectUnderConstruction &LHS, 708 const ObjectUnderConstruction &RHS) { 709 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 710 } 711 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 712 return llvm::hash_combine(Obj.Base, Obj.Path); 713 } 714 }; 715 enum class ConstructionPhase { 716 None, 717 Bases, 718 AfterBases, 719 AfterFields, 720 Destroying, 721 DestroyingBases 722 }; 723 } 724 725 namespace llvm { 726 template<> struct DenseMapInfo<ObjectUnderConstruction> { 727 using Base = DenseMapInfo<APValue::LValueBase>; 728 static ObjectUnderConstruction getEmptyKey() { 729 return {Base::getEmptyKey(), {}}; } 730 static ObjectUnderConstruction getTombstoneKey() { 731 return {Base::getTombstoneKey(), {}}; 732 } 733 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 734 return hash_value(Object); 735 } 736 static bool isEqual(const ObjectUnderConstruction &LHS, 737 const ObjectUnderConstruction &RHS) { 738 return LHS == RHS; 739 } 740 }; 741 } 742 743 namespace { 744 /// A dynamically-allocated heap object. 745 struct DynAlloc { 746 /// The value of this heap-allocated object. 747 APValue Value; 748 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 749 /// or a CallExpr (the latter is for direct calls to operator new inside 750 /// std::allocator<T>::allocate). 751 const Expr *AllocExpr = nullptr; 752 753 enum Kind { 754 New, 755 ArrayNew, 756 StdAllocator 757 }; 758 759 /// Get the kind of the allocation. This must match between allocation 760 /// and deallocation. 761 Kind getKind() const { 762 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 763 return NE->isArray() ? ArrayNew : New; 764 assert(isa<CallExpr>(AllocExpr)); 765 return StdAllocator; 766 } 767 }; 768 769 struct DynAllocOrder { 770 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 771 return L.getIndex() < R.getIndex(); 772 } 773 }; 774 775 /// EvalInfo - This is a private struct used by the evaluator to capture 776 /// information about a subexpression as it is folded. It retains information 777 /// about the AST context, but also maintains information about the folded 778 /// expression. 779 /// 780 /// If an expression could be evaluated, it is still possible it is not a C 781 /// "integer constant expression" or constant expression. If not, this struct 782 /// captures information about how and why not. 783 /// 784 /// One bit of information passed *into* the request for constant folding 785 /// indicates whether the subexpression is "evaluated" or not according to C 786 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 787 /// evaluate the expression regardless of what the RHS is, but C only allows 788 /// certain things in certain situations. 789 class EvalInfo : public interp::State { 790 public: 791 ASTContext &Ctx; 792 793 /// EvalStatus - Contains information about the evaluation. 794 Expr::EvalStatus &EvalStatus; 795 796 /// CurrentCall - The top of the constexpr call stack. 797 CallStackFrame *CurrentCall; 798 799 /// CallStackDepth - The number of calls in the call stack right now. 800 unsigned CallStackDepth; 801 802 /// NextCallIndex - The next call index to assign. 803 unsigned NextCallIndex; 804 805 /// StepsLeft - The remaining number of evaluation steps we're permitted 806 /// to perform. This is essentially a limit for the number of statements 807 /// we will evaluate. 808 unsigned StepsLeft; 809 810 /// Enable the experimental new constant interpreter. If an expression is 811 /// not supported by the interpreter, an error is triggered. 812 bool EnableNewConstInterp; 813 814 /// BottomFrame - The frame in which evaluation started. This must be 815 /// initialized after CurrentCall and CallStackDepth. 816 CallStackFrame BottomFrame; 817 818 /// A stack of values whose lifetimes end at the end of some surrounding 819 /// evaluation frame. 820 llvm::SmallVector<Cleanup, 16> CleanupStack; 821 822 /// EvaluatingDecl - This is the declaration whose initializer is being 823 /// evaluated, if any. 824 APValue::LValueBase EvaluatingDecl; 825 826 enum class EvaluatingDeclKind { 827 None, 828 /// We're evaluating the construction of EvaluatingDecl. 829 Ctor, 830 /// We're evaluating the destruction of EvaluatingDecl. 831 Dtor, 832 }; 833 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 834 835 /// EvaluatingDeclValue - This is the value being constructed for the 836 /// declaration whose initializer is being evaluated, if any. 837 APValue *EvaluatingDeclValue; 838 839 /// Set of objects that are currently being constructed. 840 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 841 ObjectsUnderConstruction; 842 843 /// Current heap allocations, along with the location where each was 844 /// allocated. We use std::map here because we need stable addresses 845 /// for the stored APValues. 846 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 847 848 /// The number of heap allocations performed so far in this evaluation. 849 unsigned NumHeapAllocs = 0; 850 851 struct EvaluatingConstructorRAII { 852 EvalInfo &EI; 853 ObjectUnderConstruction Object; 854 bool DidInsert; 855 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 856 bool HasBases) 857 : EI(EI), Object(Object) { 858 DidInsert = 859 EI.ObjectsUnderConstruction 860 .insert({Object, HasBases ? ConstructionPhase::Bases 861 : ConstructionPhase::AfterBases}) 862 .second; 863 } 864 void finishedConstructingBases() { 865 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 866 } 867 void finishedConstructingFields() { 868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 869 } 870 ~EvaluatingConstructorRAII() { 871 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 872 } 873 }; 874 875 struct EvaluatingDestructorRAII { 876 EvalInfo &EI; 877 ObjectUnderConstruction Object; 878 bool DidInsert; 879 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 880 : EI(EI), Object(Object) { 881 DidInsert = EI.ObjectsUnderConstruction 882 .insert({Object, ConstructionPhase::Destroying}) 883 .second; 884 } 885 void startedDestroyingBases() { 886 EI.ObjectsUnderConstruction[Object] = 887 ConstructionPhase::DestroyingBases; 888 } 889 ~EvaluatingDestructorRAII() { 890 if (DidInsert) 891 EI.ObjectsUnderConstruction.erase(Object); 892 } 893 }; 894 895 ConstructionPhase 896 isEvaluatingCtorDtor(APValue::LValueBase Base, 897 ArrayRef<APValue::LValuePathEntry> Path) { 898 return ObjectsUnderConstruction.lookup({Base, Path}); 899 } 900 901 /// If we're currently speculatively evaluating, the outermost call stack 902 /// depth at which we can mutate state, otherwise 0. 903 unsigned SpeculativeEvaluationDepth = 0; 904 905 /// The current array initialization index, if we're performing array 906 /// initialization. 907 uint64_t ArrayInitIndex = -1; 908 909 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 910 /// notes attached to it will also be stored, otherwise they will not be. 911 bool HasActiveDiagnostic; 912 913 /// Have we emitted a diagnostic explaining why we couldn't constant 914 /// fold (not just why it's not strictly a constant expression)? 915 bool HasFoldFailureDiagnostic; 916 917 /// Whether or not we're in a context where the front end requires a 918 /// constant value. 919 bool InConstantContext; 920 921 /// Whether we're checking that an expression is a potential constant 922 /// expression. If so, do not fail on constructs that could become constant 923 /// later on (such as a use of an undefined global). 924 bool CheckingPotentialConstantExpression = false; 925 926 /// Whether we're checking for an expression that has undefined behavior. 927 /// If so, we will produce warnings if we encounter an operation that is 928 /// always undefined. 929 /// 930 /// Note that we still need to evaluate the expression normally when this 931 /// is set; this is used when evaluating ICEs in C. 932 bool CheckingForUndefinedBehavior = false; 933 934 enum EvaluationMode { 935 /// Evaluate as a constant expression. Stop if we find that the expression 936 /// is not a constant expression. 937 EM_ConstantExpression, 938 939 /// Evaluate as a constant expression. Stop if we find that the expression 940 /// is not a constant expression. Some expressions can be retried in the 941 /// optimizer if we don't constant fold them here, but in an unevaluated 942 /// context we try to fold them immediately since the optimizer never 943 /// gets a chance to look at it. 944 EM_ConstantExpressionUnevaluated, 945 946 /// Fold the expression to a constant. Stop if we hit a side-effect that 947 /// we can't model. 948 EM_ConstantFold, 949 950 /// Evaluate in any way we know how. Don't worry about side-effects that 951 /// can't be modeled. 952 EM_IgnoreSideEffects, 953 } EvalMode; 954 955 /// Are we checking whether the expression is a potential constant 956 /// expression? 957 bool checkingPotentialConstantExpression() const override { 958 return CheckingPotentialConstantExpression; 959 } 960 961 /// Are we checking an expression for overflow? 962 // FIXME: We should check for any kind of undefined or suspicious behavior 963 // in such constructs, not just overflow. 964 bool checkingForUndefinedBehavior() const override { 965 return CheckingForUndefinedBehavior; 966 } 967 968 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 969 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 970 CallStackDepth(0), NextCallIndex(1), 971 StepsLeft(C.getLangOpts().ConstexprStepLimit), 972 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 973 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 974 EvaluatingDecl((const ValueDecl *)nullptr), 975 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 976 HasFoldFailureDiagnostic(false), InConstantContext(false), 977 EvalMode(Mode) {} 978 979 ~EvalInfo() { 980 discardCleanups(); 981 } 982 983 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 984 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 985 EvaluatingDecl = Base; 986 IsEvaluatingDecl = EDK; 987 EvaluatingDeclValue = &Value; 988 } 989 990 bool CheckCallLimit(SourceLocation Loc) { 991 // Don't perform any constexpr calls (other than the call we're checking) 992 // when checking a potential constant expression. 993 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 994 return false; 995 if (NextCallIndex == 0) { 996 // NextCallIndex has wrapped around. 997 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 998 return false; 999 } 1000 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1001 return true; 1002 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1003 << getLangOpts().ConstexprCallDepth; 1004 return false; 1005 } 1006 1007 std::pair<CallStackFrame *, unsigned> 1008 getCallFrameAndDepth(unsigned CallIndex) { 1009 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1010 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1011 // be null in this loop. 1012 unsigned Depth = CallStackDepth; 1013 CallStackFrame *Frame = CurrentCall; 1014 while (Frame->Index > CallIndex) { 1015 Frame = Frame->Caller; 1016 --Depth; 1017 } 1018 if (Frame->Index == CallIndex) 1019 return {Frame, Depth}; 1020 return {nullptr, 0}; 1021 } 1022 1023 bool nextStep(const Stmt *S) { 1024 if (!StepsLeft) { 1025 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1026 return false; 1027 } 1028 --StepsLeft; 1029 return true; 1030 } 1031 1032 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1033 1034 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1035 Optional<DynAlloc*> Result; 1036 auto It = HeapAllocs.find(DA); 1037 if (It != HeapAllocs.end()) 1038 Result = &It->second; 1039 return Result; 1040 } 1041 1042 /// Get the allocated storage for the given parameter of the given call. 1043 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1044 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1045 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1046 : nullptr; 1047 } 1048 1049 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1050 struct StdAllocatorCaller { 1051 unsigned FrameIndex; 1052 QualType ElemType; 1053 explicit operator bool() const { return FrameIndex != 0; }; 1054 }; 1055 1056 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1057 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1058 Call = Call->Caller) { 1059 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1060 if (!MD) 1061 continue; 1062 const IdentifierInfo *FnII = MD->getIdentifier(); 1063 if (!FnII || !FnII->isStr(FnName)) 1064 continue; 1065 1066 const auto *CTSD = 1067 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1068 if (!CTSD) 1069 continue; 1070 1071 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1072 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1073 if (CTSD->isInStdNamespace() && ClassII && 1074 ClassII->isStr("allocator") && TAL.size() >= 1 && 1075 TAL[0].getKind() == TemplateArgument::Type) 1076 return {Call->Index, TAL[0].getAsType()}; 1077 } 1078 1079 return {}; 1080 } 1081 1082 void performLifetimeExtension() { 1083 // Disable the cleanups for lifetime-extended temporaries. 1084 CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1085 CleanupStack.end(), 1086 [](Cleanup &C) { 1087 return !C.isDestroyedAtEndOf( 1088 ScopeKind::FullExpression); 1089 }), 1090 CleanupStack.end()); 1091 } 1092 1093 /// Throw away any remaining cleanups at the end of evaluation. If any 1094 /// cleanups would have had a side-effect, note that as an unmodeled 1095 /// side-effect and return false. Otherwise, return true. 1096 bool discardCleanups() { 1097 for (Cleanup &C : CleanupStack) { 1098 if (C.hasSideEffect() && !noteSideEffect()) { 1099 CleanupStack.clear(); 1100 return false; 1101 } 1102 } 1103 CleanupStack.clear(); 1104 return true; 1105 } 1106 1107 private: 1108 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1109 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1110 1111 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1112 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1113 1114 void setFoldFailureDiagnostic(bool Flag) override { 1115 HasFoldFailureDiagnostic = Flag; 1116 } 1117 1118 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1119 1120 ASTContext &getCtx() const override { return Ctx; } 1121 1122 // If we have a prior diagnostic, it will be noting that the expression 1123 // isn't a constant expression. This diagnostic is more important, 1124 // unless we require this evaluation to produce a constant expression. 1125 // 1126 // FIXME: We might want to show both diagnostics to the user in 1127 // EM_ConstantFold mode. 1128 bool hasPriorDiagnostic() override { 1129 if (!EvalStatus.Diag->empty()) { 1130 switch (EvalMode) { 1131 case EM_ConstantFold: 1132 case EM_IgnoreSideEffects: 1133 if (!HasFoldFailureDiagnostic) 1134 break; 1135 // We've already failed to fold something. Keep that diagnostic. 1136 LLVM_FALLTHROUGH; 1137 case EM_ConstantExpression: 1138 case EM_ConstantExpressionUnevaluated: 1139 setActiveDiagnostic(false); 1140 return true; 1141 } 1142 } 1143 return false; 1144 } 1145 1146 unsigned getCallStackDepth() override { return CallStackDepth; } 1147 1148 public: 1149 /// Should we continue evaluation after encountering a side-effect that we 1150 /// couldn't model? 1151 bool keepEvaluatingAfterSideEffect() { 1152 switch (EvalMode) { 1153 case EM_IgnoreSideEffects: 1154 return true; 1155 1156 case EM_ConstantExpression: 1157 case EM_ConstantExpressionUnevaluated: 1158 case EM_ConstantFold: 1159 // By default, assume any side effect might be valid in some other 1160 // evaluation of this expression from a different context. 1161 return checkingPotentialConstantExpression() || 1162 checkingForUndefinedBehavior(); 1163 } 1164 llvm_unreachable("Missed EvalMode case"); 1165 } 1166 1167 /// Note that we have had a side-effect, and determine whether we should 1168 /// keep evaluating. 1169 bool noteSideEffect() { 1170 EvalStatus.HasSideEffects = true; 1171 return keepEvaluatingAfterSideEffect(); 1172 } 1173 1174 /// Should we continue evaluation after encountering undefined behavior? 1175 bool keepEvaluatingAfterUndefinedBehavior() { 1176 switch (EvalMode) { 1177 case EM_IgnoreSideEffects: 1178 case EM_ConstantFold: 1179 return true; 1180 1181 case EM_ConstantExpression: 1182 case EM_ConstantExpressionUnevaluated: 1183 return checkingForUndefinedBehavior(); 1184 } 1185 llvm_unreachable("Missed EvalMode case"); 1186 } 1187 1188 /// Note that we hit something that was technically undefined behavior, but 1189 /// that we can evaluate past it (such as signed overflow or floating-point 1190 /// division by zero.) 1191 bool noteUndefinedBehavior() override { 1192 EvalStatus.HasUndefinedBehavior = true; 1193 return keepEvaluatingAfterUndefinedBehavior(); 1194 } 1195 1196 /// Should we continue evaluation as much as possible after encountering a 1197 /// construct which can't be reduced to a value? 1198 bool keepEvaluatingAfterFailure() const override { 1199 if (!StepsLeft) 1200 return false; 1201 1202 switch (EvalMode) { 1203 case EM_ConstantExpression: 1204 case EM_ConstantExpressionUnevaluated: 1205 case EM_ConstantFold: 1206 case EM_IgnoreSideEffects: 1207 return checkingPotentialConstantExpression() || 1208 checkingForUndefinedBehavior(); 1209 } 1210 llvm_unreachable("Missed EvalMode case"); 1211 } 1212 1213 /// Notes that we failed to evaluate an expression that other expressions 1214 /// directly depend on, and determine if we should keep evaluating. This 1215 /// should only be called if we actually intend to keep evaluating. 1216 /// 1217 /// Call noteSideEffect() instead if we may be able to ignore the value that 1218 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1219 /// 1220 /// (Foo(), 1) // use noteSideEffect 1221 /// (Foo() || true) // use noteSideEffect 1222 /// Foo() + 1 // use noteFailure 1223 LLVM_NODISCARD bool noteFailure() { 1224 // Failure when evaluating some expression often means there is some 1225 // subexpression whose evaluation was skipped. Therefore, (because we 1226 // don't track whether we skipped an expression when unwinding after an 1227 // evaluation failure) every evaluation failure that bubbles up from a 1228 // subexpression implies that a side-effect has potentially happened. We 1229 // skip setting the HasSideEffects flag to true until we decide to 1230 // continue evaluating after that point, which happens here. 1231 bool KeepGoing = keepEvaluatingAfterFailure(); 1232 EvalStatus.HasSideEffects |= KeepGoing; 1233 return KeepGoing; 1234 } 1235 1236 class ArrayInitLoopIndex { 1237 EvalInfo &Info; 1238 uint64_t OuterIndex; 1239 1240 public: 1241 ArrayInitLoopIndex(EvalInfo &Info) 1242 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1243 Info.ArrayInitIndex = 0; 1244 } 1245 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1246 1247 operator uint64_t&() { return Info.ArrayInitIndex; } 1248 }; 1249 }; 1250 1251 /// Object used to treat all foldable expressions as constant expressions. 1252 struct FoldConstant { 1253 EvalInfo &Info; 1254 bool Enabled; 1255 bool HadNoPriorDiags; 1256 EvalInfo::EvaluationMode OldMode; 1257 1258 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1259 : Info(Info), 1260 Enabled(Enabled), 1261 HadNoPriorDiags(Info.EvalStatus.Diag && 1262 Info.EvalStatus.Diag->empty() && 1263 !Info.EvalStatus.HasSideEffects), 1264 OldMode(Info.EvalMode) { 1265 if (Enabled) 1266 Info.EvalMode = EvalInfo::EM_ConstantFold; 1267 } 1268 void keepDiagnostics() { Enabled = false; } 1269 ~FoldConstant() { 1270 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1271 !Info.EvalStatus.HasSideEffects) 1272 Info.EvalStatus.Diag->clear(); 1273 Info.EvalMode = OldMode; 1274 } 1275 }; 1276 1277 /// RAII object used to set the current evaluation mode to ignore 1278 /// side-effects. 1279 struct IgnoreSideEffectsRAII { 1280 EvalInfo &Info; 1281 EvalInfo::EvaluationMode OldMode; 1282 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1283 : Info(Info), OldMode(Info.EvalMode) { 1284 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1285 } 1286 1287 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1288 }; 1289 1290 /// RAII object used to optionally suppress diagnostics and side-effects from 1291 /// a speculative evaluation. 1292 class SpeculativeEvaluationRAII { 1293 EvalInfo *Info = nullptr; 1294 Expr::EvalStatus OldStatus; 1295 unsigned OldSpeculativeEvaluationDepth; 1296 1297 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1298 Info = Other.Info; 1299 OldStatus = Other.OldStatus; 1300 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1301 Other.Info = nullptr; 1302 } 1303 1304 void maybeRestoreState() { 1305 if (!Info) 1306 return; 1307 1308 Info->EvalStatus = OldStatus; 1309 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1310 } 1311 1312 public: 1313 SpeculativeEvaluationRAII() = default; 1314 1315 SpeculativeEvaluationRAII( 1316 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1317 : Info(&Info), OldStatus(Info.EvalStatus), 1318 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1319 Info.EvalStatus.Diag = NewDiag; 1320 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1321 } 1322 1323 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1324 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1325 moveFromAndCancel(std::move(Other)); 1326 } 1327 1328 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1329 maybeRestoreState(); 1330 moveFromAndCancel(std::move(Other)); 1331 return *this; 1332 } 1333 1334 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1335 }; 1336 1337 /// RAII object wrapping a full-expression or block scope, and handling 1338 /// the ending of the lifetime of temporaries created within it. 1339 template<ScopeKind Kind> 1340 class ScopeRAII { 1341 EvalInfo &Info; 1342 unsigned OldStackSize; 1343 public: 1344 ScopeRAII(EvalInfo &Info) 1345 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1346 // Push a new temporary version. This is needed to distinguish between 1347 // temporaries created in different iterations of a loop. 1348 Info.CurrentCall->pushTempVersion(); 1349 } 1350 bool destroy(bool RunDestructors = true) { 1351 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1352 OldStackSize = -1U; 1353 return OK; 1354 } 1355 ~ScopeRAII() { 1356 if (OldStackSize != -1U) 1357 destroy(false); 1358 // Body moved to a static method to encourage the compiler to inline away 1359 // instances of this class. 1360 Info.CurrentCall->popTempVersion(); 1361 } 1362 private: 1363 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1364 unsigned OldStackSize) { 1365 assert(OldStackSize <= Info.CleanupStack.size() && 1366 "running cleanups out of order?"); 1367 1368 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1369 // for a full-expression scope. 1370 bool Success = true; 1371 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1372 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1373 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1374 Success = false; 1375 break; 1376 } 1377 } 1378 } 1379 1380 // Compact any retained cleanups. 1381 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1382 if (Kind != ScopeKind::Block) 1383 NewEnd = 1384 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1385 return C.isDestroyedAtEndOf(Kind); 1386 }); 1387 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1388 return Success; 1389 } 1390 }; 1391 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1392 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1393 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1394 } 1395 1396 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1397 CheckSubobjectKind CSK) { 1398 if (Invalid) 1399 return false; 1400 if (isOnePastTheEnd()) { 1401 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1402 << CSK; 1403 setInvalid(); 1404 return false; 1405 } 1406 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1407 // must actually be at least one array element; even a VLA cannot have a 1408 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1409 return true; 1410 } 1411 1412 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1413 const Expr *E) { 1414 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1415 // Do not set the designator as invalid: we can represent this situation, 1416 // and correct handling of __builtin_object_size requires us to do so. 1417 } 1418 1419 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1420 const Expr *E, 1421 const APSInt &N) { 1422 // If we're complaining, we must be able to statically determine the size of 1423 // the most derived array. 1424 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1425 Info.CCEDiag(E, diag::note_constexpr_array_index) 1426 << N << /*array*/ 0 1427 << static_cast<unsigned>(getMostDerivedArraySize()); 1428 else 1429 Info.CCEDiag(E, diag::note_constexpr_array_index) 1430 << N << /*non-array*/ 1; 1431 setInvalid(); 1432 } 1433 1434 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1435 const FunctionDecl *Callee, const LValue *This, 1436 CallRef Call) 1437 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1438 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1439 Info.CurrentCall = this; 1440 ++Info.CallStackDepth; 1441 } 1442 1443 CallStackFrame::~CallStackFrame() { 1444 assert(Info.CurrentCall == this && "calls retired out of order"); 1445 --Info.CallStackDepth; 1446 Info.CurrentCall = Caller; 1447 } 1448 1449 static bool isRead(AccessKinds AK) { 1450 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1451 } 1452 1453 static bool isModification(AccessKinds AK) { 1454 switch (AK) { 1455 case AK_Read: 1456 case AK_ReadObjectRepresentation: 1457 case AK_MemberCall: 1458 case AK_DynamicCast: 1459 case AK_TypeId: 1460 return false; 1461 case AK_Assign: 1462 case AK_Increment: 1463 case AK_Decrement: 1464 case AK_Construct: 1465 case AK_Destroy: 1466 return true; 1467 } 1468 llvm_unreachable("unknown access kind"); 1469 } 1470 1471 static bool isAnyAccess(AccessKinds AK) { 1472 return isRead(AK) || isModification(AK); 1473 } 1474 1475 /// Is this an access per the C++ definition? 1476 static bool isFormalAccess(AccessKinds AK) { 1477 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1478 } 1479 1480 /// Is this kind of axcess valid on an indeterminate object value? 1481 static bool isValidIndeterminateAccess(AccessKinds AK) { 1482 switch (AK) { 1483 case AK_Read: 1484 case AK_Increment: 1485 case AK_Decrement: 1486 // These need the object's value. 1487 return false; 1488 1489 case AK_ReadObjectRepresentation: 1490 case AK_Assign: 1491 case AK_Construct: 1492 case AK_Destroy: 1493 // Construction and destruction don't need the value. 1494 return true; 1495 1496 case AK_MemberCall: 1497 case AK_DynamicCast: 1498 case AK_TypeId: 1499 // These aren't really meaningful on scalars. 1500 return true; 1501 } 1502 llvm_unreachable("unknown access kind"); 1503 } 1504 1505 namespace { 1506 struct ComplexValue { 1507 private: 1508 bool IsInt; 1509 1510 public: 1511 APSInt IntReal, IntImag; 1512 APFloat FloatReal, FloatImag; 1513 1514 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1515 1516 void makeComplexFloat() { IsInt = false; } 1517 bool isComplexFloat() const { return !IsInt; } 1518 APFloat &getComplexFloatReal() { return FloatReal; } 1519 APFloat &getComplexFloatImag() { return FloatImag; } 1520 1521 void makeComplexInt() { IsInt = true; } 1522 bool isComplexInt() const { return IsInt; } 1523 APSInt &getComplexIntReal() { return IntReal; } 1524 APSInt &getComplexIntImag() { return IntImag; } 1525 1526 void moveInto(APValue &v) const { 1527 if (isComplexFloat()) 1528 v = APValue(FloatReal, FloatImag); 1529 else 1530 v = APValue(IntReal, IntImag); 1531 } 1532 void setFrom(const APValue &v) { 1533 assert(v.isComplexFloat() || v.isComplexInt()); 1534 if (v.isComplexFloat()) { 1535 makeComplexFloat(); 1536 FloatReal = v.getComplexFloatReal(); 1537 FloatImag = v.getComplexFloatImag(); 1538 } else { 1539 makeComplexInt(); 1540 IntReal = v.getComplexIntReal(); 1541 IntImag = v.getComplexIntImag(); 1542 } 1543 } 1544 }; 1545 1546 struct LValue { 1547 APValue::LValueBase Base; 1548 CharUnits Offset; 1549 SubobjectDesignator Designator; 1550 bool IsNullPtr : 1; 1551 bool InvalidBase : 1; 1552 1553 const APValue::LValueBase getLValueBase() const { return Base; } 1554 CharUnits &getLValueOffset() { return Offset; } 1555 const CharUnits &getLValueOffset() const { return Offset; } 1556 SubobjectDesignator &getLValueDesignator() { return Designator; } 1557 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1558 bool isNullPointer() const { return IsNullPtr;} 1559 1560 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1561 unsigned getLValueVersion() const { return Base.getVersion(); } 1562 1563 void moveInto(APValue &V) const { 1564 if (Designator.Invalid) 1565 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1566 else { 1567 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1568 V = APValue(Base, Offset, Designator.Entries, 1569 Designator.IsOnePastTheEnd, IsNullPtr); 1570 } 1571 } 1572 void setFrom(ASTContext &Ctx, const APValue &V) { 1573 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1574 Base = V.getLValueBase(); 1575 Offset = V.getLValueOffset(); 1576 InvalidBase = false; 1577 Designator = SubobjectDesignator(Ctx, V); 1578 IsNullPtr = V.isNullPointer(); 1579 } 1580 1581 void set(APValue::LValueBase B, bool BInvalid = false) { 1582 #ifndef NDEBUG 1583 // We only allow a few types of invalid bases. Enforce that here. 1584 if (BInvalid) { 1585 const auto *E = B.get<const Expr *>(); 1586 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1587 "Unexpected type of invalid base"); 1588 } 1589 #endif 1590 1591 Base = B; 1592 Offset = CharUnits::fromQuantity(0); 1593 InvalidBase = BInvalid; 1594 Designator = SubobjectDesignator(getType(B)); 1595 IsNullPtr = false; 1596 } 1597 1598 void setNull(ASTContext &Ctx, QualType PointerTy) { 1599 Base = (const ValueDecl *)nullptr; 1600 Offset = 1601 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1602 InvalidBase = false; 1603 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1604 IsNullPtr = true; 1605 } 1606 1607 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1608 set(B, true); 1609 } 1610 1611 std::string toString(ASTContext &Ctx, QualType T) const { 1612 APValue Printable; 1613 moveInto(Printable); 1614 return Printable.getAsString(Ctx, T); 1615 } 1616 1617 private: 1618 // Check that this LValue is not based on a null pointer. If it is, produce 1619 // a diagnostic and mark the designator as invalid. 1620 template <typename GenDiagType> 1621 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1622 if (Designator.Invalid) 1623 return false; 1624 if (IsNullPtr) { 1625 GenDiag(); 1626 Designator.setInvalid(); 1627 return false; 1628 } 1629 return true; 1630 } 1631 1632 public: 1633 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1634 CheckSubobjectKind CSK) { 1635 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1636 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1637 }); 1638 } 1639 1640 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1641 AccessKinds AK) { 1642 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1643 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1644 }); 1645 } 1646 1647 // Check this LValue refers to an object. If not, set the designator to be 1648 // invalid and emit a diagnostic. 1649 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1650 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1651 Designator.checkSubobject(Info, E, CSK); 1652 } 1653 1654 void addDecl(EvalInfo &Info, const Expr *E, 1655 const Decl *D, bool Virtual = false) { 1656 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1657 Designator.addDeclUnchecked(D, Virtual); 1658 } 1659 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1660 if (!Designator.Entries.empty()) { 1661 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1662 Designator.setInvalid(); 1663 return; 1664 } 1665 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1666 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1667 Designator.FirstEntryIsAnUnsizedArray = true; 1668 Designator.addUnsizedArrayUnchecked(ElemTy); 1669 } 1670 } 1671 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1672 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1673 Designator.addArrayUnchecked(CAT); 1674 } 1675 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1676 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1677 Designator.addComplexUnchecked(EltTy, Imag); 1678 } 1679 void clearIsNullPointer() { 1680 IsNullPtr = false; 1681 } 1682 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1683 const APSInt &Index, CharUnits ElementSize) { 1684 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1685 // but we're not required to diagnose it and it's valid in C++.) 1686 if (!Index) 1687 return; 1688 1689 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1690 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1691 // offsets. 1692 uint64_t Offset64 = Offset.getQuantity(); 1693 uint64_t ElemSize64 = ElementSize.getQuantity(); 1694 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1695 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1696 1697 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1698 Designator.adjustIndex(Info, E, Index); 1699 clearIsNullPointer(); 1700 } 1701 void adjustOffset(CharUnits N) { 1702 Offset += N; 1703 if (N.getQuantity()) 1704 clearIsNullPointer(); 1705 } 1706 }; 1707 1708 struct MemberPtr { 1709 MemberPtr() {} 1710 explicit MemberPtr(const ValueDecl *Decl) : 1711 DeclAndIsDerivedMember(Decl, false), Path() {} 1712 1713 /// The member or (direct or indirect) field referred to by this member 1714 /// pointer, or 0 if this is a null member pointer. 1715 const ValueDecl *getDecl() const { 1716 return DeclAndIsDerivedMember.getPointer(); 1717 } 1718 /// Is this actually a member of some type derived from the relevant class? 1719 bool isDerivedMember() const { 1720 return DeclAndIsDerivedMember.getInt(); 1721 } 1722 /// Get the class which the declaration actually lives in. 1723 const CXXRecordDecl *getContainingRecord() const { 1724 return cast<CXXRecordDecl>( 1725 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1726 } 1727 1728 void moveInto(APValue &V) const { 1729 V = APValue(getDecl(), isDerivedMember(), Path); 1730 } 1731 void setFrom(const APValue &V) { 1732 assert(V.isMemberPointer()); 1733 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1734 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1735 Path.clear(); 1736 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1737 Path.insert(Path.end(), P.begin(), P.end()); 1738 } 1739 1740 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1741 /// whether the member is a member of some class derived from the class type 1742 /// of the member pointer. 1743 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1744 /// Path - The path of base/derived classes from the member declaration's 1745 /// class (exclusive) to the class type of the member pointer (inclusive). 1746 SmallVector<const CXXRecordDecl*, 4> Path; 1747 1748 /// Perform a cast towards the class of the Decl (either up or down the 1749 /// hierarchy). 1750 bool castBack(const CXXRecordDecl *Class) { 1751 assert(!Path.empty()); 1752 const CXXRecordDecl *Expected; 1753 if (Path.size() >= 2) 1754 Expected = Path[Path.size() - 2]; 1755 else 1756 Expected = getContainingRecord(); 1757 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1758 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1759 // if B does not contain the original member and is not a base or 1760 // derived class of the class containing the original member, the result 1761 // of the cast is undefined. 1762 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1763 // (D::*). We consider that to be a language defect. 1764 return false; 1765 } 1766 Path.pop_back(); 1767 return true; 1768 } 1769 /// Perform a base-to-derived member pointer cast. 1770 bool castToDerived(const CXXRecordDecl *Derived) { 1771 if (!getDecl()) 1772 return true; 1773 if (!isDerivedMember()) { 1774 Path.push_back(Derived); 1775 return true; 1776 } 1777 if (!castBack(Derived)) 1778 return false; 1779 if (Path.empty()) 1780 DeclAndIsDerivedMember.setInt(false); 1781 return true; 1782 } 1783 /// Perform a derived-to-base member pointer cast. 1784 bool castToBase(const CXXRecordDecl *Base) { 1785 if (!getDecl()) 1786 return true; 1787 if (Path.empty()) 1788 DeclAndIsDerivedMember.setInt(true); 1789 if (isDerivedMember()) { 1790 Path.push_back(Base); 1791 return true; 1792 } 1793 return castBack(Base); 1794 } 1795 }; 1796 1797 /// Compare two member pointers, which are assumed to be of the same type. 1798 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1799 if (!LHS.getDecl() || !RHS.getDecl()) 1800 return !LHS.getDecl() && !RHS.getDecl(); 1801 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1802 return false; 1803 return LHS.Path == RHS.Path; 1804 } 1805 } 1806 1807 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1808 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1809 const LValue &This, const Expr *E, 1810 bool AllowNonLiteralTypes = false); 1811 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1812 bool InvalidBaseOK = false); 1813 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1814 bool InvalidBaseOK = false); 1815 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1816 EvalInfo &Info); 1817 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1818 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1819 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1820 EvalInfo &Info); 1821 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1822 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1823 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1824 EvalInfo &Info); 1825 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1826 1827 /// Evaluate an integer or fixed point expression into an APResult. 1828 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1829 EvalInfo &Info); 1830 1831 /// Evaluate only a fixed point expression into an APResult. 1832 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1833 EvalInfo &Info); 1834 1835 //===----------------------------------------------------------------------===// 1836 // Misc utilities 1837 //===----------------------------------------------------------------------===// 1838 1839 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1840 /// preserving its value (by extending by up to one bit as needed). 1841 static void negateAsSigned(APSInt &Int) { 1842 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1843 Int = Int.extend(Int.getBitWidth() + 1); 1844 Int.setIsSigned(true); 1845 } 1846 Int = -Int; 1847 } 1848 1849 template<typename KeyT> 1850 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1851 ScopeKind Scope, LValue &LV) { 1852 unsigned Version = getTempVersion(); 1853 APValue::LValueBase Base(Key, Index, Version); 1854 LV.set(Base); 1855 return createLocal(Base, Key, T, Scope); 1856 } 1857 1858 /// Allocate storage for a parameter of a function call made in this frame. 1859 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1860 LValue &LV) { 1861 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1862 APValue::LValueBase Base(PVD, Index, Args.Version); 1863 LV.set(Base); 1864 // We always destroy parameters at the end of the call, even if we'd allow 1865 // them to live to the end of the full-expression at runtime, in order to 1866 // give portable results and match other compilers. 1867 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1868 } 1869 1870 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1871 QualType T, ScopeKind Scope) { 1872 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1873 unsigned Version = Base.getVersion(); 1874 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1875 assert(Result.isAbsent() && "local created multiple times"); 1876 1877 // If we're creating a local immediately in the operand of a speculative 1878 // evaluation, don't register a cleanup to be run outside the speculative 1879 // evaluation context, since we won't actually be able to initialize this 1880 // object. 1881 if (Index <= Info.SpeculativeEvaluationDepth) { 1882 if (T.isDestructedType()) 1883 Info.noteSideEffect(); 1884 } else { 1885 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1886 } 1887 return Result; 1888 } 1889 1890 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1891 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1892 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1893 return nullptr; 1894 } 1895 1896 DynamicAllocLValue DA(NumHeapAllocs++); 1897 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1898 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1899 std::forward_as_tuple(DA), std::tuple<>()); 1900 assert(Result.second && "reused a heap alloc index?"); 1901 Result.first->second.AllocExpr = E; 1902 return &Result.first->second.Value; 1903 } 1904 1905 /// Produce a string describing the given constexpr call. 1906 void CallStackFrame::describe(raw_ostream &Out) { 1907 unsigned ArgIndex = 0; 1908 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1909 !isa<CXXConstructorDecl>(Callee) && 1910 cast<CXXMethodDecl>(Callee)->isInstance(); 1911 1912 if (!IsMemberCall) 1913 Out << *Callee << '('; 1914 1915 if (This && IsMemberCall) { 1916 APValue Val; 1917 This->moveInto(Val); 1918 Val.printPretty(Out, Info.Ctx, 1919 This->Designator.MostDerivedType); 1920 // FIXME: Add parens around Val if needed. 1921 Out << "->" << *Callee << '('; 1922 IsMemberCall = false; 1923 } 1924 1925 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1926 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1927 if (ArgIndex > (unsigned)IsMemberCall) 1928 Out << ", "; 1929 1930 const ParmVarDecl *Param = *I; 1931 APValue *V = Info.getParamSlot(Arguments, Param); 1932 if (V) 1933 V->printPretty(Out, Info.Ctx, Param->getType()); 1934 else 1935 Out << "<...>"; 1936 1937 if (ArgIndex == 0 && IsMemberCall) 1938 Out << "->" << *Callee << '('; 1939 } 1940 1941 Out << ')'; 1942 } 1943 1944 /// Evaluate an expression to see if it had side-effects, and discard its 1945 /// result. 1946 /// \return \c true if the caller should keep evaluating. 1947 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1948 assert(!E->isValueDependent()); 1949 APValue Scratch; 1950 if (!Evaluate(Scratch, Info, E)) 1951 // We don't need the value, but we might have skipped a side effect here. 1952 return Info.noteSideEffect(); 1953 return true; 1954 } 1955 1956 /// Should this call expression be treated as a string literal? 1957 static bool IsStringLiteralCall(const CallExpr *E) { 1958 unsigned Builtin = E->getBuiltinCallee(); 1959 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1960 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1961 } 1962 1963 static bool IsGlobalLValue(APValue::LValueBase B) { 1964 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1965 // constant expression of pointer type that evaluates to... 1966 1967 // ... a null pointer value, or a prvalue core constant expression of type 1968 // std::nullptr_t. 1969 if (!B) return true; 1970 1971 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1972 // ... the address of an object with static storage duration, 1973 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1974 return VD->hasGlobalStorage(); 1975 if (isa<TemplateParamObjectDecl>(D)) 1976 return true; 1977 // ... the address of a function, 1978 // ... the address of a GUID [MS extension], 1979 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1980 } 1981 1982 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1983 return true; 1984 1985 const Expr *E = B.get<const Expr*>(); 1986 switch (E->getStmtClass()) { 1987 default: 1988 return false; 1989 case Expr::CompoundLiteralExprClass: { 1990 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1991 return CLE->isFileScope() && CLE->isLValue(); 1992 } 1993 case Expr::MaterializeTemporaryExprClass: 1994 // A materialized temporary might have been lifetime-extended to static 1995 // storage duration. 1996 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1997 // A string literal has static storage duration. 1998 case Expr::StringLiteralClass: 1999 case Expr::PredefinedExprClass: 2000 case Expr::ObjCStringLiteralClass: 2001 case Expr::ObjCEncodeExprClass: 2002 return true; 2003 case Expr::ObjCBoxedExprClass: 2004 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2005 case Expr::CallExprClass: 2006 return IsStringLiteralCall(cast<CallExpr>(E)); 2007 // For GCC compatibility, &&label has static storage duration. 2008 case Expr::AddrLabelExprClass: 2009 return true; 2010 // A Block literal expression may be used as the initialization value for 2011 // Block variables at global or local static scope. 2012 case Expr::BlockExprClass: 2013 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2014 case Expr::ImplicitValueInitExprClass: 2015 // FIXME: 2016 // We can never form an lvalue with an implicit value initialization as its 2017 // base through expression evaluation, so these only appear in one case: the 2018 // implicit variable declaration we invent when checking whether a constexpr 2019 // constructor can produce a constant expression. We must assume that such 2020 // an expression might be a global lvalue. 2021 return true; 2022 } 2023 } 2024 2025 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2026 return LVal.Base.dyn_cast<const ValueDecl*>(); 2027 } 2028 2029 static bool IsLiteralLValue(const LValue &Value) { 2030 if (Value.getLValueCallIndex()) 2031 return false; 2032 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2033 return E && !isa<MaterializeTemporaryExpr>(E); 2034 } 2035 2036 static bool IsWeakLValue(const LValue &Value) { 2037 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2038 return Decl && Decl->isWeak(); 2039 } 2040 2041 static bool isZeroSized(const LValue &Value) { 2042 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2043 if (Decl && isa<VarDecl>(Decl)) { 2044 QualType Ty = Decl->getType(); 2045 if (Ty->isArrayType()) 2046 return Ty->isIncompleteType() || 2047 Decl->getASTContext().getTypeSize(Ty) == 0; 2048 } 2049 return false; 2050 } 2051 2052 static bool HasSameBase(const LValue &A, const LValue &B) { 2053 if (!A.getLValueBase()) 2054 return !B.getLValueBase(); 2055 if (!B.getLValueBase()) 2056 return false; 2057 2058 if (A.getLValueBase().getOpaqueValue() != 2059 B.getLValueBase().getOpaqueValue()) 2060 return false; 2061 2062 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2063 A.getLValueVersion() == B.getLValueVersion(); 2064 } 2065 2066 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2067 assert(Base && "no location for a null lvalue"); 2068 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2069 2070 // For a parameter, find the corresponding call stack frame (if it still 2071 // exists), and point at the parameter of the function definition we actually 2072 // invoked. 2073 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2074 unsigned Idx = PVD->getFunctionScopeIndex(); 2075 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2076 if (F->Arguments.CallIndex == Base.getCallIndex() && 2077 F->Arguments.Version == Base.getVersion() && F->Callee && 2078 Idx < F->Callee->getNumParams()) { 2079 VD = F->Callee->getParamDecl(Idx); 2080 break; 2081 } 2082 } 2083 } 2084 2085 if (VD) 2086 Info.Note(VD->getLocation(), diag::note_declared_at); 2087 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2088 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2089 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2090 // FIXME: Produce a note for dangling pointers too. 2091 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2092 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2093 diag::note_constexpr_dynamic_alloc_here); 2094 } 2095 // We have no information to show for a typeid(T) object. 2096 } 2097 2098 enum class CheckEvaluationResultKind { 2099 ConstantExpression, 2100 FullyInitialized, 2101 }; 2102 2103 /// Materialized temporaries that we've already checked to determine if they're 2104 /// initializsed by a constant expression. 2105 using CheckedTemporaries = 2106 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2107 2108 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2109 EvalInfo &Info, SourceLocation DiagLoc, 2110 QualType Type, const APValue &Value, 2111 ConstantExprKind Kind, 2112 SourceLocation SubobjectLoc, 2113 CheckedTemporaries &CheckedTemps); 2114 2115 /// Check that this reference or pointer core constant expression is a valid 2116 /// value for an address or reference constant expression. Return true if we 2117 /// can fold this expression, whether or not it's a constant expression. 2118 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2119 QualType Type, const LValue &LVal, 2120 ConstantExprKind Kind, 2121 CheckedTemporaries &CheckedTemps) { 2122 bool IsReferenceType = Type->isReferenceType(); 2123 2124 APValue::LValueBase Base = LVal.getLValueBase(); 2125 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2126 2127 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2128 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2129 2130 // Additional restrictions apply in a template argument. We only enforce the 2131 // C++20 restrictions here; additional syntactic and semantic restrictions 2132 // are applied elsewhere. 2133 if (isTemplateArgument(Kind)) { 2134 int InvalidBaseKind = -1; 2135 StringRef Ident; 2136 if (Base.is<TypeInfoLValue>()) 2137 InvalidBaseKind = 0; 2138 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2139 InvalidBaseKind = 1; 2140 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2141 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2142 InvalidBaseKind = 2; 2143 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2144 InvalidBaseKind = 3; 2145 Ident = PE->getIdentKindName(); 2146 } 2147 2148 if (InvalidBaseKind != -1) { 2149 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2150 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2151 << Ident; 2152 return false; 2153 } 2154 } 2155 2156 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2157 if (FD->isConsteval()) { 2158 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2159 << !Type->isAnyPointerType(); 2160 Info.Note(FD->getLocation(), diag::note_declared_at); 2161 return false; 2162 } 2163 } 2164 2165 // Check that the object is a global. Note that the fake 'this' object we 2166 // manufacture when checking potential constant expressions is conservatively 2167 // assumed to be global here. 2168 if (!IsGlobalLValue(Base)) { 2169 if (Info.getLangOpts().CPlusPlus11) { 2170 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2171 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2172 << IsReferenceType << !Designator.Entries.empty() 2173 << !!VD << VD; 2174 2175 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2176 if (VarD && VarD->isConstexpr()) { 2177 // Non-static local constexpr variables have unintuitive semantics: 2178 // constexpr int a = 1; 2179 // constexpr const int *p = &a; 2180 // ... is invalid because the address of 'a' is not constant. Suggest 2181 // adding a 'static' in this case. 2182 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2183 << VarD 2184 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2185 } else { 2186 NoteLValueLocation(Info, Base); 2187 } 2188 } else { 2189 Info.FFDiag(Loc); 2190 } 2191 // Don't allow references to temporaries to escape. 2192 return false; 2193 } 2194 assert((Info.checkingPotentialConstantExpression() || 2195 LVal.getLValueCallIndex() == 0) && 2196 "have call index for global lvalue"); 2197 2198 if (Base.is<DynamicAllocLValue>()) { 2199 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2200 << IsReferenceType << !Designator.Entries.empty(); 2201 NoteLValueLocation(Info, Base); 2202 return false; 2203 } 2204 2205 if (BaseVD) { 2206 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2207 // Check if this is a thread-local variable. 2208 if (Var->getTLSKind()) 2209 // FIXME: Diagnostic! 2210 return false; 2211 2212 // A dllimport variable never acts like a constant, unless we're 2213 // evaluating a value for use only in name mangling. 2214 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2215 // FIXME: Diagnostic! 2216 return false; 2217 } 2218 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2219 // __declspec(dllimport) must be handled very carefully: 2220 // We must never initialize an expression with the thunk in C++. 2221 // Doing otherwise would allow the same id-expression to yield 2222 // different addresses for the same function in different translation 2223 // units. However, this means that we must dynamically initialize the 2224 // expression with the contents of the import address table at runtime. 2225 // 2226 // The C language has no notion of ODR; furthermore, it has no notion of 2227 // dynamic initialization. This means that we are permitted to 2228 // perform initialization with the address of the thunk. 2229 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2230 FD->hasAttr<DLLImportAttr>()) 2231 // FIXME: Diagnostic! 2232 return false; 2233 } 2234 } else if (const auto *MTE = 2235 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2236 if (CheckedTemps.insert(MTE).second) { 2237 QualType TempType = getType(Base); 2238 if (TempType.isDestructedType()) { 2239 Info.FFDiag(MTE->getExprLoc(), 2240 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2241 << TempType; 2242 return false; 2243 } 2244 2245 APValue *V = MTE->getOrCreateValue(false); 2246 assert(V && "evasluation result refers to uninitialised temporary"); 2247 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2248 Info, MTE->getExprLoc(), TempType, *V, 2249 Kind, SourceLocation(), CheckedTemps)) 2250 return false; 2251 } 2252 } 2253 2254 // Allow address constant expressions to be past-the-end pointers. This is 2255 // an extension: the standard requires them to point to an object. 2256 if (!IsReferenceType) 2257 return true; 2258 2259 // A reference constant expression must refer to an object. 2260 if (!Base) { 2261 // FIXME: diagnostic 2262 Info.CCEDiag(Loc); 2263 return true; 2264 } 2265 2266 // Does this refer one past the end of some object? 2267 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2268 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2269 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2270 NoteLValueLocation(Info, Base); 2271 } 2272 2273 return true; 2274 } 2275 2276 /// Member pointers are constant expressions unless they point to a 2277 /// non-virtual dllimport member function. 2278 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2279 SourceLocation Loc, 2280 QualType Type, 2281 const APValue &Value, 2282 ConstantExprKind Kind) { 2283 const ValueDecl *Member = Value.getMemberPointerDecl(); 2284 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2285 if (!FD) 2286 return true; 2287 if (FD->isConsteval()) { 2288 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2289 Info.Note(FD->getLocation(), diag::note_declared_at); 2290 return false; 2291 } 2292 return isForManglingOnly(Kind) || FD->isVirtual() || 2293 !FD->hasAttr<DLLImportAttr>(); 2294 } 2295 2296 /// Check that this core constant expression is of literal type, and if not, 2297 /// produce an appropriate diagnostic. 2298 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2299 const LValue *This = nullptr) { 2300 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2301 return true; 2302 2303 // C++1y: A constant initializer for an object o [...] may also invoke 2304 // constexpr constructors for o and its subobjects even if those objects 2305 // are of non-literal class types. 2306 // 2307 // C++11 missed this detail for aggregates, so classes like this: 2308 // struct foo_t { union { int i; volatile int j; } u; }; 2309 // are not (obviously) initializable like so: 2310 // __attribute__((__require_constant_initialization__)) 2311 // static const foo_t x = {{0}}; 2312 // because "i" is a subobject with non-literal initialization (due to the 2313 // volatile member of the union). See: 2314 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2315 // Therefore, we use the C++1y behavior. 2316 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2317 return true; 2318 2319 // Prvalue constant expressions must be of literal types. 2320 if (Info.getLangOpts().CPlusPlus11) 2321 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2322 << E->getType(); 2323 else 2324 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2325 return false; 2326 } 2327 2328 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2329 EvalInfo &Info, SourceLocation DiagLoc, 2330 QualType Type, const APValue &Value, 2331 ConstantExprKind Kind, 2332 SourceLocation SubobjectLoc, 2333 CheckedTemporaries &CheckedTemps) { 2334 if (!Value.hasValue()) { 2335 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2336 << true << Type; 2337 if (SubobjectLoc.isValid()) 2338 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2339 return false; 2340 } 2341 2342 // We allow _Atomic(T) to be initialized from anything that T can be 2343 // initialized from. 2344 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2345 Type = AT->getValueType(); 2346 2347 // Core issue 1454: For a literal constant expression of array or class type, 2348 // each subobject of its value shall have been initialized by a constant 2349 // expression. 2350 if (Value.isArray()) { 2351 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2352 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2353 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2354 Value.getArrayInitializedElt(I), Kind, 2355 SubobjectLoc, CheckedTemps)) 2356 return false; 2357 } 2358 if (!Value.hasArrayFiller()) 2359 return true; 2360 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2361 Value.getArrayFiller(), Kind, SubobjectLoc, 2362 CheckedTemps); 2363 } 2364 if (Value.isUnion() && Value.getUnionField()) { 2365 return CheckEvaluationResult( 2366 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2367 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2368 CheckedTemps); 2369 } 2370 if (Value.isStruct()) { 2371 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2372 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2373 unsigned BaseIndex = 0; 2374 for (const CXXBaseSpecifier &BS : CD->bases()) { 2375 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2376 Value.getStructBase(BaseIndex), Kind, 2377 BS.getBeginLoc(), CheckedTemps)) 2378 return false; 2379 ++BaseIndex; 2380 } 2381 } 2382 for (const auto *I : RD->fields()) { 2383 if (I->isUnnamedBitfield()) 2384 continue; 2385 2386 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2387 Value.getStructField(I->getFieldIndex()), 2388 Kind, I->getLocation(), CheckedTemps)) 2389 return false; 2390 } 2391 } 2392 2393 if (Value.isLValue() && 2394 CERK == CheckEvaluationResultKind::ConstantExpression) { 2395 LValue LVal; 2396 LVal.setFrom(Info.Ctx, Value); 2397 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2398 CheckedTemps); 2399 } 2400 2401 if (Value.isMemberPointer() && 2402 CERK == CheckEvaluationResultKind::ConstantExpression) 2403 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2404 2405 // Everything else is fine. 2406 return true; 2407 } 2408 2409 /// Check that this core constant expression value is a valid value for a 2410 /// constant expression. If not, report an appropriate diagnostic. Does not 2411 /// check that the expression is of literal type. 2412 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2413 QualType Type, const APValue &Value, 2414 ConstantExprKind Kind) { 2415 // Nothing to check for a constant expression of type 'cv void'. 2416 if (Type->isVoidType()) 2417 return true; 2418 2419 CheckedTemporaries CheckedTemps; 2420 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2421 Info, DiagLoc, Type, Value, Kind, 2422 SourceLocation(), CheckedTemps); 2423 } 2424 2425 /// Check that this evaluated value is fully-initialized and can be loaded by 2426 /// an lvalue-to-rvalue conversion. 2427 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2428 QualType Type, const APValue &Value) { 2429 CheckedTemporaries CheckedTemps; 2430 return CheckEvaluationResult( 2431 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2432 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2433 } 2434 2435 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2436 /// "the allocated storage is deallocated within the evaluation". 2437 static bool CheckMemoryLeaks(EvalInfo &Info) { 2438 if (!Info.HeapAllocs.empty()) { 2439 // We can still fold to a constant despite a compile-time memory leak, 2440 // so long as the heap allocation isn't referenced in the result (we check 2441 // that in CheckConstantExpression). 2442 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2443 diag::note_constexpr_memory_leak) 2444 << unsigned(Info.HeapAllocs.size() - 1); 2445 } 2446 return true; 2447 } 2448 2449 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2450 // A null base expression indicates a null pointer. These are always 2451 // evaluatable, and they are false unless the offset is zero. 2452 if (!Value.getLValueBase()) { 2453 Result = !Value.getLValueOffset().isZero(); 2454 return true; 2455 } 2456 2457 // We have a non-null base. These are generally known to be true, but if it's 2458 // a weak declaration it can be null at runtime. 2459 Result = true; 2460 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2461 return !Decl || !Decl->isWeak(); 2462 } 2463 2464 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2465 switch (Val.getKind()) { 2466 case APValue::None: 2467 case APValue::Indeterminate: 2468 return false; 2469 case APValue::Int: 2470 Result = Val.getInt().getBoolValue(); 2471 return true; 2472 case APValue::FixedPoint: 2473 Result = Val.getFixedPoint().getBoolValue(); 2474 return true; 2475 case APValue::Float: 2476 Result = !Val.getFloat().isZero(); 2477 return true; 2478 case APValue::ComplexInt: 2479 Result = Val.getComplexIntReal().getBoolValue() || 2480 Val.getComplexIntImag().getBoolValue(); 2481 return true; 2482 case APValue::ComplexFloat: 2483 Result = !Val.getComplexFloatReal().isZero() || 2484 !Val.getComplexFloatImag().isZero(); 2485 return true; 2486 case APValue::LValue: 2487 return EvalPointerValueAsBool(Val, Result); 2488 case APValue::MemberPointer: 2489 Result = Val.getMemberPointerDecl(); 2490 return true; 2491 case APValue::Vector: 2492 case APValue::Array: 2493 case APValue::Struct: 2494 case APValue::Union: 2495 case APValue::AddrLabelDiff: 2496 return false; 2497 } 2498 2499 llvm_unreachable("unknown APValue kind"); 2500 } 2501 2502 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2503 EvalInfo &Info) { 2504 assert(!E->isValueDependent()); 2505 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2506 APValue Val; 2507 if (!Evaluate(Val, Info, E)) 2508 return false; 2509 return HandleConversionToBool(Val, Result); 2510 } 2511 2512 template<typename T> 2513 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2514 const T &SrcValue, QualType DestType) { 2515 Info.CCEDiag(E, diag::note_constexpr_overflow) 2516 << SrcValue << DestType; 2517 return Info.noteUndefinedBehavior(); 2518 } 2519 2520 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2521 QualType SrcType, const APFloat &Value, 2522 QualType DestType, APSInt &Result) { 2523 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2524 // Determine whether we are converting to unsigned or signed. 2525 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2526 2527 Result = APSInt(DestWidth, !DestSigned); 2528 bool ignored; 2529 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2530 & APFloat::opInvalidOp) 2531 return HandleOverflow(Info, E, Value, DestType); 2532 return true; 2533 } 2534 2535 /// Get rounding mode used for evaluation of the specified expression. 2536 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2537 /// dynamic. 2538 /// If rounding mode is unknown at compile time, still try to evaluate the 2539 /// expression. If the result is exact, it does not depend on rounding mode. 2540 /// So return "tonearest" mode instead of "dynamic". 2541 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2542 bool &DynamicRM) { 2543 llvm::RoundingMode RM = 2544 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2545 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2546 if (DynamicRM) 2547 RM = llvm::RoundingMode::NearestTiesToEven; 2548 return RM; 2549 } 2550 2551 /// Check if the given evaluation result is allowed for constant evaluation. 2552 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2553 APFloat::opStatus St) { 2554 // In a constant context, assume that any dynamic rounding mode or FP 2555 // exception state matches the default floating-point environment. 2556 if (Info.InConstantContext) 2557 return true; 2558 2559 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2560 if ((St & APFloat::opInexact) && 2561 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2562 // Inexact result means that it depends on rounding mode. If the requested 2563 // mode is dynamic, the evaluation cannot be made in compile time. 2564 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2565 return false; 2566 } 2567 2568 if ((St != APFloat::opOK) && 2569 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2570 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2571 FPO.getAllowFEnvAccess())) { 2572 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2573 return false; 2574 } 2575 2576 if ((St & APFloat::opStatus::opInvalidOp) && 2577 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2578 // There is no usefully definable result. 2579 Info.FFDiag(E); 2580 return false; 2581 } 2582 2583 // FIXME: if: 2584 // - evaluation triggered other FP exception, and 2585 // - exception mode is not "ignore", and 2586 // - the expression being evaluated is not a part of global variable 2587 // initializer, 2588 // the evaluation probably need to be rejected. 2589 return true; 2590 } 2591 2592 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2593 QualType SrcType, QualType DestType, 2594 APFloat &Result) { 2595 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2596 bool DynamicRM; 2597 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2598 APFloat::opStatus St; 2599 APFloat Value = Result; 2600 bool ignored; 2601 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2602 return checkFloatingPointResult(Info, E, St); 2603 } 2604 2605 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2606 QualType DestType, QualType SrcType, 2607 const APSInt &Value) { 2608 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2609 // Figure out if this is a truncate, extend or noop cast. 2610 // If the input is signed, do a sign extend, noop, or truncate. 2611 APSInt Result = Value.extOrTrunc(DestWidth); 2612 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2613 if (DestType->isBooleanType()) 2614 Result = Value.getBoolValue(); 2615 return Result; 2616 } 2617 2618 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2619 const FPOptions FPO, 2620 QualType SrcType, const APSInt &Value, 2621 QualType DestType, APFloat &Result) { 2622 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2623 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2624 APFloat::rmNearestTiesToEven); 2625 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2626 FPO.isFPConstrained()) { 2627 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2628 return false; 2629 } 2630 return true; 2631 } 2632 2633 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2634 APValue &Value, const FieldDecl *FD) { 2635 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2636 2637 if (!Value.isInt()) { 2638 // Trying to store a pointer-cast-to-integer into a bitfield. 2639 // FIXME: In this case, we should provide the diagnostic for casting 2640 // a pointer to an integer. 2641 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2642 Info.FFDiag(E); 2643 return false; 2644 } 2645 2646 APSInt &Int = Value.getInt(); 2647 unsigned OldBitWidth = Int.getBitWidth(); 2648 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2649 if (NewBitWidth < OldBitWidth) 2650 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2651 return true; 2652 } 2653 2654 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2655 llvm::APInt &Res) { 2656 APValue SVal; 2657 if (!Evaluate(SVal, Info, E)) 2658 return false; 2659 if (SVal.isInt()) { 2660 Res = SVal.getInt(); 2661 return true; 2662 } 2663 if (SVal.isFloat()) { 2664 Res = SVal.getFloat().bitcastToAPInt(); 2665 return true; 2666 } 2667 if (SVal.isVector()) { 2668 QualType VecTy = E->getType(); 2669 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2670 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2671 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2672 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2673 Res = llvm::APInt::getNullValue(VecSize); 2674 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2675 APValue &Elt = SVal.getVectorElt(i); 2676 llvm::APInt EltAsInt; 2677 if (Elt.isInt()) { 2678 EltAsInt = Elt.getInt(); 2679 } else if (Elt.isFloat()) { 2680 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2681 } else { 2682 // Don't try to handle vectors of anything other than int or float 2683 // (not sure if it's possible to hit this case). 2684 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2685 return false; 2686 } 2687 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2688 if (BigEndian) 2689 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2690 else 2691 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2692 } 2693 return true; 2694 } 2695 // Give up if the input isn't an int, float, or vector. For example, we 2696 // reject "(v4i16)(intptr_t)&a". 2697 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2698 return false; 2699 } 2700 2701 /// Perform the given integer operation, which is known to need at most BitWidth 2702 /// bits, and check for overflow in the original type (if that type was not an 2703 /// unsigned type). 2704 template<typename Operation> 2705 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2706 const APSInt &LHS, const APSInt &RHS, 2707 unsigned BitWidth, Operation Op, 2708 APSInt &Result) { 2709 if (LHS.isUnsigned()) { 2710 Result = Op(LHS, RHS); 2711 return true; 2712 } 2713 2714 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2715 Result = Value.trunc(LHS.getBitWidth()); 2716 if (Result.extend(BitWidth) != Value) { 2717 if (Info.checkingForUndefinedBehavior()) 2718 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2719 diag::warn_integer_constant_overflow) 2720 << Result.toString(10) << E->getType(); 2721 return HandleOverflow(Info, E, Value, E->getType()); 2722 } 2723 return true; 2724 } 2725 2726 /// Perform the given binary integer operation. 2727 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2728 BinaryOperatorKind Opcode, APSInt RHS, 2729 APSInt &Result) { 2730 switch (Opcode) { 2731 default: 2732 Info.FFDiag(E); 2733 return false; 2734 case BO_Mul: 2735 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2736 std::multiplies<APSInt>(), Result); 2737 case BO_Add: 2738 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2739 std::plus<APSInt>(), Result); 2740 case BO_Sub: 2741 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2742 std::minus<APSInt>(), Result); 2743 case BO_And: Result = LHS & RHS; return true; 2744 case BO_Xor: Result = LHS ^ RHS; return true; 2745 case BO_Or: Result = LHS | RHS; return true; 2746 case BO_Div: 2747 case BO_Rem: 2748 if (RHS == 0) { 2749 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2750 return false; 2751 } 2752 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2753 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2754 // this operation and gives the two's complement result. 2755 if (RHS.isNegative() && RHS.isAllOnesValue() && 2756 LHS.isSigned() && LHS.isMinSignedValue()) 2757 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2758 E->getType()); 2759 return true; 2760 case BO_Shl: { 2761 if (Info.getLangOpts().OpenCL) 2762 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2763 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2764 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2765 RHS.isUnsigned()); 2766 else if (RHS.isSigned() && RHS.isNegative()) { 2767 // During constant-folding, a negative shift is an opposite shift. Such 2768 // a shift is not a constant expression. 2769 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2770 RHS = -RHS; 2771 goto shift_right; 2772 } 2773 shift_left: 2774 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2775 // the shifted type. 2776 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2777 if (SA != RHS) { 2778 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2779 << RHS << E->getType() << LHS.getBitWidth(); 2780 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2781 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2782 // operand, and must not overflow the corresponding unsigned type. 2783 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2784 // E1 x 2^E2 module 2^N. 2785 if (LHS.isNegative()) 2786 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2787 else if (LHS.countLeadingZeros() < SA) 2788 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2789 } 2790 Result = LHS << SA; 2791 return true; 2792 } 2793 case BO_Shr: { 2794 if (Info.getLangOpts().OpenCL) 2795 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2796 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2797 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2798 RHS.isUnsigned()); 2799 else if (RHS.isSigned() && RHS.isNegative()) { 2800 // During constant-folding, a negative shift is an opposite shift. Such a 2801 // shift is not a constant expression. 2802 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2803 RHS = -RHS; 2804 goto shift_left; 2805 } 2806 shift_right: 2807 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2808 // shifted type. 2809 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2810 if (SA != RHS) 2811 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2812 << RHS << E->getType() << LHS.getBitWidth(); 2813 Result = LHS >> SA; 2814 return true; 2815 } 2816 2817 case BO_LT: Result = LHS < RHS; return true; 2818 case BO_GT: Result = LHS > RHS; return true; 2819 case BO_LE: Result = LHS <= RHS; return true; 2820 case BO_GE: Result = LHS >= RHS; return true; 2821 case BO_EQ: Result = LHS == RHS; return true; 2822 case BO_NE: Result = LHS != RHS; return true; 2823 case BO_Cmp: 2824 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2825 } 2826 } 2827 2828 /// Perform the given binary floating-point operation, in-place, on LHS. 2829 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2830 APFloat &LHS, BinaryOperatorKind Opcode, 2831 const APFloat &RHS) { 2832 bool DynamicRM; 2833 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2834 APFloat::opStatus St; 2835 switch (Opcode) { 2836 default: 2837 Info.FFDiag(E); 2838 return false; 2839 case BO_Mul: 2840 St = LHS.multiply(RHS, RM); 2841 break; 2842 case BO_Add: 2843 St = LHS.add(RHS, RM); 2844 break; 2845 case BO_Sub: 2846 St = LHS.subtract(RHS, RM); 2847 break; 2848 case BO_Div: 2849 // [expr.mul]p4: 2850 // If the second operand of / or % is zero the behavior is undefined. 2851 if (RHS.isZero()) 2852 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2853 St = LHS.divide(RHS, RM); 2854 break; 2855 } 2856 2857 // [expr.pre]p4: 2858 // If during the evaluation of an expression, the result is not 2859 // mathematically defined [...], the behavior is undefined. 2860 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2861 if (LHS.isNaN()) { 2862 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2863 return Info.noteUndefinedBehavior(); 2864 } 2865 2866 return checkFloatingPointResult(Info, E, St); 2867 } 2868 2869 static bool handleLogicalOpForVector(const APInt &LHSValue, 2870 BinaryOperatorKind Opcode, 2871 const APInt &RHSValue, APInt &Result) { 2872 bool LHS = (LHSValue != 0); 2873 bool RHS = (RHSValue != 0); 2874 2875 if (Opcode == BO_LAnd) 2876 Result = LHS && RHS; 2877 else 2878 Result = LHS || RHS; 2879 return true; 2880 } 2881 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2882 BinaryOperatorKind Opcode, 2883 const APFloat &RHSValue, APInt &Result) { 2884 bool LHS = !LHSValue.isZero(); 2885 bool RHS = !RHSValue.isZero(); 2886 2887 if (Opcode == BO_LAnd) 2888 Result = LHS && RHS; 2889 else 2890 Result = LHS || RHS; 2891 return true; 2892 } 2893 2894 static bool handleLogicalOpForVector(const APValue &LHSValue, 2895 BinaryOperatorKind Opcode, 2896 const APValue &RHSValue, APInt &Result) { 2897 // The result is always an int type, however operands match the first. 2898 if (LHSValue.getKind() == APValue::Int) 2899 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2900 RHSValue.getInt(), Result); 2901 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2902 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2903 RHSValue.getFloat(), Result); 2904 } 2905 2906 template <typename APTy> 2907 static bool 2908 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2909 const APTy &RHSValue, APInt &Result) { 2910 switch (Opcode) { 2911 default: 2912 llvm_unreachable("unsupported binary operator"); 2913 case BO_EQ: 2914 Result = (LHSValue == RHSValue); 2915 break; 2916 case BO_NE: 2917 Result = (LHSValue != RHSValue); 2918 break; 2919 case BO_LT: 2920 Result = (LHSValue < RHSValue); 2921 break; 2922 case BO_GT: 2923 Result = (LHSValue > RHSValue); 2924 break; 2925 case BO_LE: 2926 Result = (LHSValue <= RHSValue); 2927 break; 2928 case BO_GE: 2929 Result = (LHSValue >= RHSValue); 2930 break; 2931 } 2932 2933 return true; 2934 } 2935 2936 static bool handleCompareOpForVector(const APValue &LHSValue, 2937 BinaryOperatorKind Opcode, 2938 const APValue &RHSValue, APInt &Result) { 2939 // The result is always an int type, however operands match the first. 2940 if (LHSValue.getKind() == APValue::Int) 2941 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2942 RHSValue.getInt(), Result); 2943 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2944 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2945 RHSValue.getFloat(), Result); 2946 } 2947 2948 // Perform binary operations for vector types, in place on the LHS. 2949 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2950 BinaryOperatorKind Opcode, 2951 APValue &LHSValue, 2952 const APValue &RHSValue) { 2953 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2954 "Operation not supported on vector types"); 2955 2956 const auto *VT = E->getType()->castAs<VectorType>(); 2957 unsigned NumElements = VT->getNumElements(); 2958 QualType EltTy = VT->getElementType(); 2959 2960 // In the cases (typically C as I've observed) where we aren't evaluating 2961 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2962 // just give up. 2963 if (!LHSValue.isVector()) { 2964 assert(LHSValue.isLValue() && 2965 "A vector result that isn't a vector OR uncalculated LValue"); 2966 Info.FFDiag(E); 2967 return false; 2968 } 2969 2970 assert(LHSValue.getVectorLength() == NumElements && 2971 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2972 2973 SmallVector<APValue, 4> ResultElements; 2974 2975 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2976 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2977 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2978 2979 if (EltTy->isIntegerType()) { 2980 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2981 EltTy->isUnsignedIntegerType()}; 2982 bool Success = true; 2983 2984 if (BinaryOperator::isLogicalOp(Opcode)) 2985 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2986 else if (BinaryOperator::isComparisonOp(Opcode)) 2987 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2988 else 2989 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2990 RHSElt.getInt(), EltResult); 2991 2992 if (!Success) { 2993 Info.FFDiag(E); 2994 return false; 2995 } 2996 ResultElements.emplace_back(EltResult); 2997 2998 } else if (EltTy->isFloatingType()) { 2999 assert(LHSElt.getKind() == APValue::Float && 3000 RHSElt.getKind() == APValue::Float && 3001 "Mismatched LHS/RHS/Result Type"); 3002 APFloat LHSFloat = LHSElt.getFloat(); 3003 3004 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3005 RHSElt.getFloat())) { 3006 Info.FFDiag(E); 3007 return false; 3008 } 3009 3010 ResultElements.emplace_back(LHSFloat); 3011 } 3012 } 3013 3014 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3015 return true; 3016 } 3017 3018 /// Cast an lvalue referring to a base subobject to a derived class, by 3019 /// truncating the lvalue's path to the given length. 3020 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3021 const RecordDecl *TruncatedType, 3022 unsigned TruncatedElements) { 3023 SubobjectDesignator &D = Result.Designator; 3024 3025 // Check we actually point to a derived class object. 3026 if (TruncatedElements == D.Entries.size()) 3027 return true; 3028 assert(TruncatedElements >= D.MostDerivedPathLength && 3029 "not casting to a derived class"); 3030 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3031 return false; 3032 3033 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3034 const RecordDecl *RD = TruncatedType; 3035 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3036 if (RD->isInvalidDecl()) return false; 3037 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3038 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3039 if (isVirtualBaseClass(D.Entries[I])) 3040 Result.Offset -= Layout.getVBaseClassOffset(Base); 3041 else 3042 Result.Offset -= Layout.getBaseClassOffset(Base); 3043 RD = Base; 3044 } 3045 D.Entries.resize(TruncatedElements); 3046 return true; 3047 } 3048 3049 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3050 const CXXRecordDecl *Derived, 3051 const CXXRecordDecl *Base, 3052 const ASTRecordLayout *RL = nullptr) { 3053 if (!RL) { 3054 if (Derived->isInvalidDecl()) return false; 3055 RL = &Info.Ctx.getASTRecordLayout(Derived); 3056 } 3057 3058 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3059 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3060 return true; 3061 } 3062 3063 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3064 const CXXRecordDecl *DerivedDecl, 3065 const CXXBaseSpecifier *Base) { 3066 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3067 3068 if (!Base->isVirtual()) 3069 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3070 3071 SubobjectDesignator &D = Obj.Designator; 3072 if (D.Invalid) 3073 return false; 3074 3075 // Extract most-derived object and corresponding type. 3076 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3077 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3078 return false; 3079 3080 // Find the virtual base class. 3081 if (DerivedDecl->isInvalidDecl()) return false; 3082 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3083 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3084 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3085 return true; 3086 } 3087 3088 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3089 QualType Type, LValue &Result) { 3090 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3091 PathE = E->path_end(); 3092 PathI != PathE; ++PathI) { 3093 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3094 *PathI)) 3095 return false; 3096 Type = (*PathI)->getType(); 3097 } 3098 return true; 3099 } 3100 3101 /// Cast an lvalue referring to a derived class to a known base subobject. 3102 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3103 const CXXRecordDecl *DerivedRD, 3104 const CXXRecordDecl *BaseRD) { 3105 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3106 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3107 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3108 llvm_unreachable("Class must be derived from the passed in base class!"); 3109 3110 for (CXXBasePathElement &Elem : Paths.front()) 3111 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3112 return false; 3113 return true; 3114 } 3115 3116 /// Update LVal to refer to the given field, which must be a member of the type 3117 /// currently described by LVal. 3118 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3119 const FieldDecl *FD, 3120 const ASTRecordLayout *RL = nullptr) { 3121 if (!RL) { 3122 if (FD->getParent()->isInvalidDecl()) return false; 3123 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3124 } 3125 3126 unsigned I = FD->getFieldIndex(); 3127 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3128 LVal.addDecl(Info, E, FD); 3129 return true; 3130 } 3131 3132 /// Update LVal to refer to the given indirect field. 3133 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3134 LValue &LVal, 3135 const IndirectFieldDecl *IFD) { 3136 for (const auto *C : IFD->chain()) 3137 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3138 return false; 3139 return true; 3140 } 3141 3142 /// Get the size of the given type in char units. 3143 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3144 QualType Type, CharUnits &Size) { 3145 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3146 // extension. 3147 if (Type->isVoidType() || Type->isFunctionType()) { 3148 Size = CharUnits::One(); 3149 return true; 3150 } 3151 3152 if (Type->isDependentType()) { 3153 Info.FFDiag(Loc); 3154 return false; 3155 } 3156 3157 if (!Type->isConstantSizeType()) { 3158 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3159 // FIXME: Better diagnostic. 3160 Info.FFDiag(Loc); 3161 return false; 3162 } 3163 3164 Size = Info.Ctx.getTypeSizeInChars(Type); 3165 return true; 3166 } 3167 3168 /// Update a pointer value to model pointer arithmetic. 3169 /// \param Info - Information about the ongoing evaluation. 3170 /// \param E - The expression being evaluated, for diagnostic purposes. 3171 /// \param LVal - The pointer value to be updated. 3172 /// \param EltTy - The pointee type represented by LVal. 3173 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3174 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3175 LValue &LVal, QualType EltTy, 3176 APSInt Adjustment) { 3177 CharUnits SizeOfPointee; 3178 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3179 return false; 3180 3181 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3182 return true; 3183 } 3184 3185 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3186 LValue &LVal, QualType EltTy, 3187 int64_t Adjustment) { 3188 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3189 APSInt::get(Adjustment)); 3190 } 3191 3192 /// Update an lvalue to refer to a component of a complex number. 3193 /// \param Info - Information about the ongoing evaluation. 3194 /// \param LVal - The lvalue to be updated. 3195 /// \param EltTy - The complex number's component type. 3196 /// \param Imag - False for the real component, true for the imaginary. 3197 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3198 LValue &LVal, QualType EltTy, 3199 bool Imag) { 3200 if (Imag) { 3201 CharUnits SizeOfComponent; 3202 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3203 return false; 3204 LVal.Offset += SizeOfComponent; 3205 } 3206 LVal.addComplex(Info, E, EltTy, Imag); 3207 return true; 3208 } 3209 3210 /// Try to evaluate the initializer for a variable declaration. 3211 /// 3212 /// \param Info Information about the ongoing evaluation. 3213 /// \param E An expression to be used when printing diagnostics. 3214 /// \param VD The variable whose initializer should be obtained. 3215 /// \param Version The version of the variable within the frame. 3216 /// \param Frame The frame in which the variable was created. Must be null 3217 /// if this variable is not local to the evaluation. 3218 /// \param Result Filled in with a pointer to the value of the variable. 3219 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3220 const VarDecl *VD, CallStackFrame *Frame, 3221 unsigned Version, APValue *&Result) { 3222 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3223 3224 // If this is a local variable, dig out its value. 3225 if (Frame) { 3226 Result = Frame->getTemporary(VD, Version); 3227 if (Result) 3228 return true; 3229 3230 if (!isa<ParmVarDecl>(VD)) { 3231 // Assume variables referenced within a lambda's call operator that were 3232 // not declared within the call operator are captures and during checking 3233 // of a potential constant expression, assume they are unknown constant 3234 // expressions. 3235 assert(isLambdaCallOperator(Frame->Callee) && 3236 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3237 "missing value for local variable"); 3238 if (Info.checkingPotentialConstantExpression()) 3239 return false; 3240 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3241 // still reachable at all? 3242 Info.FFDiag(E->getBeginLoc(), 3243 diag::note_unimplemented_constexpr_lambda_feature_ast) 3244 << "captures not currently allowed"; 3245 return false; 3246 } 3247 } 3248 3249 // If we're currently evaluating the initializer of this declaration, use that 3250 // in-flight value. 3251 if (Info.EvaluatingDecl == Base) { 3252 Result = Info.EvaluatingDeclValue; 3253 return true; 3254 } 3255 3256 if (isa<ParmVarDecl>(VD)) { 3257 // Assume parameters of a potential constant expression are usable in 3258 // constant expressions. 3259 if (!Info.checkingPotentialConstantExpression() || 3260 !Info.CurrentCall->Callee || 3261 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3262 if (Info.getLangOpts().CPlusPlus11) { 3263 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3264 << VD; 3265 NoteLValueLocation(Info, Base); 3266 } else { 3267 Info.FFDiag(E); 3268 } 3269 } 3270 return false; 3271 } 3272 3273 // Dig out the initializer, and use the declaration which it's attached to. 3274 // FIXME: We should eventually check whether the variable has a reachable 3275 // initializing declaration. 3276 const Expr *Init = VD->getAnyInitializer(VD); 3277 if (!Init) { 3278 // Don't diagnose during potential constant expression checking; an 3279 // initializer might be added later. 3280 if (!Info.checkingPotentialConstantExpression()) { 3281 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3282 << VD; 3283 NoteLValueLocation(Info, Base); 3284 } 3285 return false; 3286 } 3287 3288 if (Init->isValueDependent()) { 3289 // The DeclRefExpr is not value-dependent, but the variable it refers to 3290 // has a value-dependent initializer. This should only happen in 3291 // constant-folding cases, where the variable is not actually of a suitable 3292 // type for use in a constant expression (otherwise the DeclRefExpr would 3293 // have been value-dependent too), so diagnose that. 3294 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3295 if (!Info.checkingPotentialConstantExpression()) { 3296 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3297 ? diag::note_constexpr_ltor_non_constexpr 3298 : diag::note_constexpr_ltor_non_integral, 1) 3299 << VD << VD->getType(); 3300 NoteLValueLocation(Info, Base); 3301 } 3302 return false; 3303 } 3304 3305 // Check that we can fold the initializer. In C++, we will have already done 3306 // this in the cases where it matters for conformance. 3307 if (!VD->evaluateValue()) { 3308 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3309 NoteLValueLocation(Info, Base); 3310 return false; 3311 } 3312 3313 // Check that the variable is actually usable in constant expressions. For a 3314 // const integral variable or a reference, we might have a non-constant 3315 // initializer that we can nonetheless evaluate the initializer for. Such 3316 // variables are not usable in constant expressions. In C++98, the 3317 // initializer also syntactically needs to be an ICE. 3318 // 3319 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3320 // expressions here; doing so would regress diagnostics for things like 3321 // reading from a volatile constexpr variable. 3322 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3323 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3324 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3325 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3326 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3327 NoteLValueLocation(Info, Base); 3328 } 3329 3330 // Never use the initializer of a weak variable, not even for constant 3331 // folding. We can't be sure that this is the definition that will be used. 3332 if (VD->isWeak()) { 3333 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3334 NoteLValueLocation(Info, Base); 3335 return false; 3336 } 3337 3338 Result = VD->getEvaluatedValue(); 3339 return true; 3340 } 3341 3342 /// Get the base index of the given base class within an APValue representing 3343 /// the given derived class. 3344 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3345 const CXXRecordDecl *Base) { 3346 Base = Base->getCanonicalDecl(); 3347 unsigned Index = 0; 3348 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3349 E = Derived->bases_end(); I != E; ++I, ++Index) { 3350 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3351 return Index; 3352 } 3353 3354 llvm_unreachable("base class missing from derived class's bases list"); 3355 } 3356 3357 /// Extract the value of a character from a string literal. 3358 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3359 uint64_t Index) { 3360 assert(!isa<SourceLocExpr>(Lit) && 3361 "SourceLocExpr should have already been converted to a StringLiteral"); 3362 3363 // FIXME: Support MakeStringConstant 3364 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3365 std::string Str; 3366 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3367 assert(Index <= Str.size() && "Index too large"); 3368 return APSInt::getUnsigned(Str.c_str()[Index]); 3369 } 3370 3371 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3372 Lit = PE->getFunctionName(); 3373 const StringLiteral *S = cast<StringLiteral>(Lit); 3374 const ConstantArrayType *CAT = 3375 Info.Ctx.getAsConstantArrayType(S->getType()); 3376 assert(CAT && "string literal isn't an array"); 3377 QualType CharType = CAT->getElementType(); 3378 assert(CharType->isIntegerType() && "unexpected character type"); 3379 3380 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3381 CharType->isUnsignedIntegerType()); 3382 if (Index < S->getLength()) 3383 Value = S->getCodeUnit(Index); 3384 return Value; 3385 } 3386 3387 // Expand a string literal into an array of characters. 3388 // 3389 // FIXME: This is inefficient; we should probably introduce something similar 3390 // to the LLVM ConstantDataArray to make this cheaper. 3391 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3392 APValue &Result, 3393 QualType AllocType = QualType()) { 3394 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3395 AllocType.isNull() ? S->getType() : AllocType); 3396 assert(CAT && "string literal isn't an array"); 3397 QualType CharType = CAT->getElementType(); 3398 assert(CharType->isIntegerType() && "unexpected character type"); 3399 3400 unsigned Elts = CAT->getSize().getZExtValue(); 3401 Result = APValue(APValue::UninitArray(), 3402 std::min(S->getLength(), Elts), Elts); 3403 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3404 CharType->isUnsignedIntegerType()); 3405 if (Result.hasArrayFiller()) 3406 Result.getArrayFiller() = APValue(Value); 3407 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3408 Value = S->getCodeUnit(I); 3409 Result.getArrayInitializedElt(I) = APValue(Value); 3410 } 3411 } 3412 3413 // Expand an array so that it has more than Index filled elements. 3414 static void expandArray(APValue &Array, unsigned Index) { 3415 unsigned Size = Array.getArraySize(); 3416 assert(Index < Size); 3417 3418 // Always at least double the number of elements for which we store a value. 3419 unsigned OldElts = Array.getArrayInitializedElts(); 3420 unsigned NewElts = std::max(Index+1, OldElts * 2); 3421 NewElts = std::min(Size, std::max(NewElts, 8u)); 3422 3423 // Copy the data across. 3424 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3425 for (unsigned I = 0; I != OldElts; ++I) 3426 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3427 for (unsigned I = OldElts; I != NewElts; ++I) 3428 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3429 if (NewValue.hasArrayFiller()) 3430 NewValue.getArrayFiller() = Array.getArrayFiller(); 3431 Array.swap(NewValue); 3432 } 3433 3434 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3435 /// conversion. If it's of class type, we may assume that the copy operation 3436 /// is trivial. Note that this is never true for a union type with fields 3437 /// (because the copy always "reads" the active member) and always true for 3438 /// a non-class type. 3439 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3440 static bool isReadByLvalueToRvalueConversion(QualType T) { 3441 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3442 return !RD || isReadByLvalueToRvalueConversion(RD); 3443 } 3444 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3445 // FIXME: A trivial copy of a union copies the object representation, even if 3446 // the union is empty. 3447 if (RD->isUnion()) 3448 return !RD->field_empty(); 3449 if (RD->isEmpty()) 3450 return false; 3451 3452 for (auto *Field : RD->fields()) 3453 if (!Field->isUnnamedBitfield() && 3454 isReadByLvalueToRvalueConversion(Field->getType())) 3455 return true; 3456 3457 for (auto &BaseSpec : RD->bases()) 3458 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3459 return true; 3460 3461 return false; 3462 } 3463 3464 /// Diagnose an attempt to read from any unreadable field within the specified 3465 /// type, which might be a class type. 3466 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3467 QualType T) { 3468 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3469 if (!RD) 3470 return false; 3471 3472 if (!RD->hasMutableFields()) 3473 return false; 3474 3475 for (auto *Field : RD->fields()) { 3476 // If we're actually going to read this field in some way, then it can't 3477 // be mutable. If we're in a union, then assigning to a mutable field 3478 // (even an empty one) can change the active member, so that's not OK. 3479 // FIXME: Add core issue number for the union case. 3480 if (Field->isMutable() && 3481 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3482 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3483 Info.Note(Field->getLocation(), diag::note_declared_at); 3484 return true; 3485 } 3486 3487 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3488 return true; 3489 } 3490 3491 for (auto &BaseSpec : RD->bases()) 3492 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3493 return true; 3494 3495 // All mutable fields were empty, and thus not actually read. 3496 return false; 3497 } 3498 3499 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3500 APValue::LValueBase Base, 3501 bool MutableSubobject = false) { 3502 // A temporary or transient heap allocation we created. 3503 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3504 return true; 3505 3506 switch (Info.IsEvaluatingDecl) { 3507 case EvalInfo::EvaluatingDeclKind::None: 3508 return false; 3509 3510 case EvalInfo::EvaluatingDeclKind::Ctor: 3511 // The variable whose initializer we're evaluating. 3512 if (Info.EvaluatingDecl == Base) 3513 return true; 3514 3515 // A temporary lifetime-extended by the variable whose initializer we're 3516 // evaluating. 3517 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3518 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3519 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3520 return false; 3521 3522 case EvalInfo::EvaluatingDeclKind::Dtor: 3523 // C++2a [expr.const]p6: 3524 // [during constant destruction] the lifetime of a and its non-mutable 3525 // subobjects (but not its mutable subobjects) [are] considered to start 3526 // within e. 3527 if (MutableSubobject || Base != Info.EvaluatingDecl) 3528 return false; 3529 // FIXME: We can meaningfully extend this to cover non-const objects, but 3530 // we will need special handling: we should be able to access only 3531 // subobjects of such objects that are themselves declared const. 3532 QualType T = getType(Base); 3533 return T.isConstQualified() || T->isReferenceType(); 3534 } 3535 3536 llvm_unreachable("unknown evaluating decl kind"); 3537 } 3538 3539 namespace { 3540 /// A handle to a complete object (an object that is not a subobject of 3541 /// another object). 3542 struct CompleteObject { 3543 /// The identity of the object. 3544 APValue::LValueBase Base; 3545 /// The value of the complete object. 3546 APValue *Value; 3547 /// The type of the complete object. 3548 QualType Type; 3549 3550 CompleteObject() : Value(nullptr) {} 3551 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3552 : Base(Base), Value(Value), Type(Type) {} 3553 3554 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3555 // If this isn't a "real" access (eg, if it's just accessing the type 3556 // info), allow it. We assume the type doesn't change dynamically for 3557 // subobjects of constexpr objects (even though we'd hit UB here if it 3558 // did). FIXME: Is this right? 3559 if (!isAnyAccess(AK)) 3560 return true; 3561 3562 // In C++14 onwards, it is permitted to read a mutable member whose 3563 // lifetime began within the evaluation. 3564 // FIXME: Should we also allow this in C++11? 3565 if (!Info.getLangOpts().CPlusPlus14) 3566 return false; 3567 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3568 } 3569 3570 explicit operator bool() const { return !Type.isNull(); } 3571 }; 3572 } // end anonymous namespace 3573 3574 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3575 bool IsMutable = false) { 3576 // C++ [basic.type.qualifier]p1: 3577 // - A const object is an object of type const T or a non-mutable subobject 3578 // of a const object. 3579 if (ObjType.isConstQualified() && !IsMutable) 3580 SubobjType.addConst(); 3581 // - A volatile object is an object of type const T or a subobject of a 3582 // volatile object. 3583 if (ObjType.isVolatileQualified()) 3584 SubobjType.addVolatile(); 3585 return SubobjType; 3586 } 3587 3588 /// Find the designated sub-object of an rvalue. 3589 template<typename SubobjectHandler> 3590 typename SubobjectHandler::result_type 3591 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3592 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3593 if (Sub.Invalid) 3594 // A diagnostic will have already been produced. 3595 return handler.failed(); 3596 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3597 if (Info.getLangOpts().CPlusPlus11) 3598 Info.FFDiag(E, Sub.isOnePastTheEnd() 3599 ? diag::note_constexpr_access_past_end 3600 : diag::note_constexpr_access_unsized_array) 3601 << handler.AccessKind; 3602 else 3603 Info.FFDiag(E); 3604 return handler.failed(); 3605 } 3606 3607 APValue *O = Obj.Value; 3608 QualType ObjType = Obj.Type; 3609 const FieldDecl *LastField = nullptr; 3610 const FieldDecl *VolatileField = nullptr; 3611 3612 // Walk the designator's path to find the subobject. 3613 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3614 // Reading an indeterminate value is undefined, but assigning over one is OK. 3615 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3616 (O->isIndeterminate() && 3617 !isValidIndeterminateAccess(handler.AccessKind))) { 3618 if (!Info.checkingPotentialConstantExpression()) 3619 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3620 << handler.AccessKind << O->isIndeterminate(); 3621 return handler.failed(); 3622 } 3623 3624 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3625 // const and volatile semantics are not applied on an object under 3626 // {con,de}struction. 3627 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3628 ObjType->isRecordType() && 3629 Info.isEvaluatingCtorDtor( 3630 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3631 Sub.Entries.begin() + I)) != 3632 ConstructionPhase::None) { 3633 ObjType = Info.Ctx.getCanonicalType(ObjType); 3634 ObjType.removeLocalConst(); 3635 ObjType.removeLocalVolatile(); 3636 } 3637 3638 // If this is our last pass, check that the final object type is OK. 3639 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3640 // Accesses to volatile objects are prohibited. 3641 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3642 if (Info.getLangOpts().CPlusPlus) { 3643 int DiagKind; 3644 SourceLocation Loc; 3645 const NamedDecl *Decl = nullptr; 3646 if (VolatileField) { 3647 DiagKind = 2; 3648 Loc = VolatileField->getLocation(); 3649 Decl = VolatileField; 3650 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3651 DiagKind = 1; 3652 Loc = VD->getLocation(); 3653 Decl = VD; 3654 } else { 3655 DiagKind = 0; 3656 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3657 Loc = E->getExprLoc(); 3658 } 3659 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3660 << handler.AccessKind << DiagKind << Decl; 3661 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3662 } else { 3663 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3664 } 3665 return handler.failed(); 3666 } 3667 3668 // If we are reading an object of class type, there may still be more 3669 // things we need to check: if there are any mutable subobjects, we 3670 // cannot perform this read. (This only happens when performing a trivial 3671 // copy or assignment.) 3672 if (ObjType->isRecordType() && 3673 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3674 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3675 return handler.failed(); 3676 } 3677 3678 if (I == N) { 3679 if (!handler.found(*O, ObjType)) 3680 return false; 3681 3682 // If we modified a bit-field, truncate it to the right width. 3683 if (isModification(handler.AccessKind) && 3684 LastField && LastField->isBitField() && 3685 !truncateBitfieldValue(Info, E, *O, LastField)) 3686 return false; 3687 3688 return true; 3689 } 3690 3691 LastField = nullptr; 3692 if (ObjType->isArrayType()) { 3693 // Next subobject is an array element. 3694 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3695 assert(CAT && "vla in literal type?"); 3696 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3697 if (CAT->getSize().ule(Index)) { 3698 // Note, it should not be possible to form a pointer with a valid 3699 // designator which points more than one past the end of the array. 3700 if (Info.getLangOpts().CPlusPlus11) 3701 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3702 << handler.AccessKind; 3703 else 3704 Info.FFDiag(E); 3705 return handler.failed(); 3706 } 3707 3708 ObjType = CAT->getElementType(); 3709 3710 if (O->getArrayInitializedElts() > Index) 3711 O = &O->getArrayInitializedElt(Index); 3712 else if (!isRead(handler.AccessKind)) { 3713 expandArray(*O, Index); 3714 O = &O->getArrayInitializedElt(Index); 3715 } else 3716 O = &O->getArrayFiller(); 3717 } else if (ObjType->isAnyComplexType()) { 3718 // Next subobject is a complex number. 3719 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3720 if (Index > 1) { 3721 if (Info.getLangOpts().CPlusPlus11) 3722 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3723 << handler.AccessKind; 3724 else 3725 Info.FFDiag(E); 3726 return handler.failed(); 3727 } 3728 3729 ObjType = getSubobjectType( 3730 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3731 3732 assert(I == N - 1 && "extracting subobject of scalar?"); 3733 if (O->isComplexInt()) { 3734 return handler.found(Index ? O->getComplexIntImag() 3735 : O->getComplexIntReal(), ObjType); 3736 } else { 3737 assert(O->isComplexFloat()); 3738 return handler.found(Index ? O->getComplexFloatImag() 3739 : O->getComplexFloatReal(), ObjType); 3740 } 3741 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3742 if (Field->isMutable() && 3743 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3744 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3745 << handler.AccessKind << Field; 3746 Info.Note(Field->getLocation(), diag::note_declared_at); 3747 return handler.failed(); 3748 } 3749 3750 // Next subobject is a class, struct or union field. 3751 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3752 if (RD->isUnion()) { 3753 const FieldDecl *UnionField = O->getUnionField(); 3754 if (!UnionField || 3755 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3756 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3757 // Placement new onto an inactive union member makes it active. 3758 O->setUnion(Field, APValue()); 3759 } else { 3760 // FIXME: If O->getUnionValue() is absent, report that there's no 3761 // active union member rather than reporting the prior active union 3762 // member. We'll need to fix nullptr_t to not use APValue() as its 3763 // representation first. 3764 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3765 << handler.AccessKind << Field << !UnionField << UnionField; 3766 return handler.failed(); 3767 } 3768 } 3769 O = &O->getUnionValue(); 3770 } else 3771 O = &O->getStructField(Field->getFieldIndex()); 3772 3773 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3774 LastField = Field; 3775 if (Field->getType().isVolatileQualified()) 3776 VolatileField = Field; 3777 } else { 3778 // Next subobject is a base class. 3779 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3780 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3781 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3782 3783 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3784 } 3785 } 3786 } 3787 3788 namespace { 3789 struct ExtractSubobjectHandler { 3790 EvalInfo &Info; 3791 const Expr *E; 3792 APValue &Result; 3793 const AccessKinds AccessKind; 3794 3795 typedef bool result_type; 3796 bool failed() { return false; } 3797 bool found(APValue &Subobj, QualType SubobjType) { 3798 Result = Subobj; 3799 if (AccessKind == AK_ReadObjectRepresentation) 3800 return true; 3801 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3802 } 3803 bool found(APSInt &Value, QualType SubobjType) { 3804 Result = APValue(Value); 3805 return true; 3806 } 3807 bool found(APFloat &Value, QualType SubobjType) { 3808 Result = APValue(Value); 3809 return true; 3810 } 3811 }; 3812 } // end anonymous namespace 3813 3814 /// Extract the designated sub-object of an rvalue. 3815 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3816 const CompleteObject &Obj, 3817 const SubobjectDesignator &Sub, APValue &Result, 3818 AccessKinds AK = AK_Read) { 3819 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3820 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3821 return findSubobject(Info, E, Obj, Sub, Handler); 3822 } 3823 3824 namespace { 3825 struct ModifySubobjectHandler { 3826 EvalInfo &Info; 3827 APValue &NewVal; 3828 const Expr *E; 3829 3830 typedef bool result_type; 3831 static const AccessKinds AccessKind = AK_Assign; 3832 3833 bool checkConst(QualType QT) { 3834 // Assigning to a const object has undefined behavior. 3835 if (QT.isConstQualified()) { 3836 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3837 return false; 3838 } 3839 return true; 3840 } 3841 3842 bool failed() { return false; } 3843 bool found(APValue &Subobj, QualType SubobjType) { 3844 if (!checkConst(SubobjType)) 3845 return false; 3846 // We've been given ownership of NewVal, so just swap it in. 3847 Subobj.swap(NewVal); 3848 return true; 3849 } 3850 bool found(APSInt &Value, QualType SubobjType) { 3851 if (!checkConst(SubobjType)) 3852 return false; 3853 if (!NewVal.isInt()) { 3854 // Maybe trying to write a cast pointer value into a complex? 3855 Info.FFDiag(E); 3856 return false; 3857 } 3858 Value = NewVal.getInt(); 3859 return true; 3860 } 3861 bool found(APFloat &Value, QualType SubobjType) { 3862 if (!checkConst(SubobjType)) 3863 return false; 3864 Value = NewVal.getFloat(); 3865 return true; 3866 } 3867 }; 3868 } // end anonymous namespace 3869 3870 const AccessKinds ModifySubobjectHandler::AccessKind; 3871 3872 /// Update the designated sub-object of an rvalue to the given value. 3873 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3874 const CompleteObject &Obj, 3875 const SubobjectDesignator &Sub, 3876 APValue &NewVal) { 3877 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3878 return findSubobject(Info, E, Obj, Sub, Handler); 3879 } 3880 3881 /// Find the position where two subobject designators diverge, or equivalently 3882 /// the length of the common initial subsequence. 3883 static unsigned FindDesignatorMismatch(QualType ObjType, 3884 const SubobjectDesignator &A, 3885 const SubobjectDesignator &B, 3886 bool &WasArrayIndex) { 3887 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3888 for (/**/; I != N; ++I) { 3889 if (!ObjType.isNull() && 3890 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3891 // Next subobject is an array element. 3892 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3893 WasArrayIndex = true; 3894 return I; 3895 } 3896 if (ObjType->isAnyComplexType()) 3897 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3898 else 3899 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3900 } else { 3901 if (A.Entries[I].getAsBaseOrMember() != 3902 B.Entries[I].getAsBaseOrMember()) { 3903 WasArrayIndex = false; 3904 return I; 3905 } 3906 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3907 // Next subobject is a field. 3908 ObjType = FD->getType(); 3909 else 3910 // Next subobject is a base class. 3911 ObjType = QualType(); 3912 } 3913 } 3914 WasArrayIndex = false; 3915 return I; 3916 } 3917 3918 /// Determine whether the given subobject designators refer to elements of the 3919 /// same array object. 3920 static bool AreElementsOfSameArray(QualType ObjType, 3921 const SubobjectDesignator &A, 3922 const SubobjectDesignator &B) { 3923 if (A.Entries.size() != B.Entries.size()) 3924 return false; 3925 3926 bool IsArray = A.MostDerivedIsArrayElement; 3927 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3928 // A is a subobject of the array element. 3929 return false; 3930 3931 // If A (and B) designates an array element, the last entry will be the array 3932 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3933 // of length 1' case, and the entire path must match. 3934 bool WasArrayIndex; 3935 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3936 return CommonLength >= A.Entries.size() - IsArray; 3937 } 3938 3939 /// Find the complete object to which an LValue refers. 3940 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3941 AccessKinds AK, const LValue &LVal, 3942 QualType LValType) { 3943 if (LVal.InvalidBase) { 3944 Info.FFDiag(E); 3945 return CompleteObject(); 3946 } 3947 3948 if (!LVal.Base) { 3949 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3950 return CompleteObject(); 3951 } 3952 3953 CallStackFrame *Frame = nullptr; 3954 unsigned Depth = 0; 3955 if (LVal.getLValueCallIndex()) { 3956 std::tie(Frame, Depth) = 3957 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3958 if (!Frame) { 3959 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3960 << AK << LVal.Base.is<const ValueDecl*>(); 3961 NoteLValueLocation(Info, LVal.Base); 3962 return CompleteObject(); 3963 } 3964 } 3965 3966 bool IsAccess = isAnyAccess(AK); 3967 3968 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3969 // is not a constant expression (even if the object is non-volatile). We also 3970 // apply this rule to C++98, in order to conform to the expected 'volatile' 3971 // semantics. 3972 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3973 if (Info.getLangOpts().CPlusPlus) 3974 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3975 << AK << LValType; 3976 else 3977 Info.FFDiag(E); 3978 return CompleteObject(); 3979 } 3980 3981 // Compute value storage location and type of base object. 3982 APValue *BaseVal = nullptr; 3983 QualType BaseType = getType(LVal.Base); 3984 3985 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3986 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3987 // This is the object whose initializer we're evaluating, so its lifetime 3988 // started in the current evaluation. 3989 BaseVal = Info.EvaluatingDeclValue; 3990 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3991 // Allow reading from a GUID declaration. 3992 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3993 if (isModification(AK)) { 3994 // All the remaining cases do not permit modification of the object. 3995 Info.FFDiag(E, diag::note_constexpr_modify_global); 3996 return CompleteObject(); 3997 } 3998 APValue &V = GD->getAsAPValue(); 3999 if (V.isAbsent()) { 4000 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4001 << GD->getType(); 4002 return CompleteObject(); 4003 } 4004 return CompleteObject(LVal.Base, &V, GD->getType()); 4005 } 4006 4007 // Allow reading from template parameter objects. 4008 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4009 if (isModification(AK)) { 4010 Info.FFDiag(E, diag::note_constexpr_modify_global); 4011 return CompleteObject(); 4012 } 4013 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4014 TPO->getType()); 4015 } 4016 4017 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4018 // In C++11, constexpr, non-volatile variables initialized with constant 4019 // expressions are constant expressions too. Inside constexpr functions, 4020 // parameters are constant expressions even if they're non-const. 4021 // In C++1y, objects local to a constant expression (those with a Frame) are 4022 // both readable and writable inside constant expressions. 4023 // In C, such things can also be folded, although they are not ICEs. 4024 const VarDecl *VD = dyn_cast<VarDecl>(D); 4025 if (VD) { 4026 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4027 VD = VDef; 4028 } 4029 if (!VD || VD->isInvalidDecl()) { 4030 Info.FFDiag(E); 4031 return CompleteObject(); 4032 } 4033 4034 bool IsConstant = BaseType.isConstant(Info.Ctx); 4035 4036 // Unless we're looking at a local variable or argument in a constexpr call, 4037 // the variable we're reading must be const. 4038 if (!Frame) { 4039 if (IsAccess && isa<ParmVarDecl>(VD)) { 4040 // Access of a parameter that's not associated with a frame isn't going 4041 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4042 // suitable diagnostic. 4043 } else if (Info.getLangOpts().CPlusPlus14 && 4044 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4045 // OK, we can read and modify an object if we're in the process of 4046 // evaluating its initializer, because its lifetime began in this 4047 // evaluation. 4048 } else if (isModification(AK)) { 4049 // All the remaining cases do not permit modification of the object. 4050 Info.FFDiag(E, diag::note_constexpr_modify_global); 4051 return CompleteObject(); 4052 } else if (VD->isConstexpr()) { 4053 // OK, we can read this variable. 4054 } else if (BaseType->isIntegralOrEnumerationType()) { 4055 if (!IsConstant) { 4056 if (!IsAccess) 4057 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4058 if (Info.getLangOpts().CPlusPlus) { 4059 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4060 Info.Note(VD->getLocation(), diag::note_declared_at); 4061 } else { 4062 Info.FFDiag(E); 4063 } 4064 return CompleteObject(); 4065 } 4066 } else if (!IsAccess) { 4067 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4068 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4069 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4070 // This variable might end up being constexpr. Don't diagnose it yet. 4071 } else if (IsConstant) { 4072 // Keep evaluating to see what we can do. In particular, we support 4073 // folding of const floating-point types, in order to make static const 4074 // data members of such types (supported as an extension) more useful. 4075 if (Info.getLangOpts().CPlusPlus) { 4076 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4077 ? diag::note_constexpr_ltor_non_constexpr 4078 : diag::note_constexpr_ltor_non_integral, 1) 4079 << VD << BaseType; 4080 Info.Note(VD->getLocation(), diag::note_declared_at); 4081 } else { 4082 Info.CCEDiag(E); 4083 } 4084 } else { 4085 // Never allow reading a non-const value. 4086 if (Info.getLangOpts().CPlusPlus) { 4087 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4088 ? diag::note_constexpr_ltor_non_constexpr 4089 : diag::note_constexpr_ltor_non_integral, 1) 4090 << VD << BaseType; 4091 Info.Note(VD->getLocation(), diag::note_declared_at); 4092 } else { 4093 Info.FFDiag(E); 4094 } 4095 return CompleteObject(); 4096 } 4097 } 4098 4099 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4100 return CompleteObject(); 4101 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4102 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4103 if (!Alloc) { 4104 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4105 return CompleteObject(); 4106 } 4107 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4108 LVal.Base.getDynamicAllocType()); 4109 } else { 4110 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4111 4112 if (!Frame) { 4113 if (const MaterializeTemporaryExpr *MTE = 4114 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4115 assert(MTE->getStorageDuration() == SD_Static && 4116 "should have a frame for a non-global materialized temporary"); 4117 4118 // C++20 [expr.const]p4: [DR2126] 4119 // An object or reference is usable in constant expressions if it is 4120 // - a temporary object of non-volatile const-qualified literal type 4121 // whose lifetime is extended to that of a variable that is usable 4122 // in constant expressions 4123 // 4124 // C++20 [expr.const]p5: 4125 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4126 // - a non-volatile glvalue that refers to an object that is usable 4127 // in constant expressions, or 4128 // - a non-volatile glvalue of literal type that refers to a 4129 // non-volatile object whose lifetime began within the evaluation 4130 // of E; 4131 // 4132 // C++11 misses the 'began within the evaluation of e' check and 4133 // instead allows all temporaries, including things like: 4134 // int &&r = 1; 4135 // int x = ++r; 4136 // constexpr int k = r; 4137 // Therefore we use the C++14-onwards rules in C++11 too. 4138 // 4139 // Note that temporaries whose lifetimes began while evaluating a 4140 // variable's constructor are not usable while evaluating the 4141 // corresponding destructor, not even if they're of const-qualified 4142 // types. 4143 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4144 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4145 if (!IsAccess) 4146 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4147 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4148 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4149 return CompleteObject(); 4150 } 4151 4152 BaseVal = MTE->getOrCreateValue(false); 4153 assert(BaseVal && "got reference to unevaluated temporary"); 4154 } else { 4155 if (!IsAccess) 4156 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4157 APValue Val; 4158 LVal.moveInto(Val); 4159 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4160 << AK 4161 << Val.getAsString(Info.Ctx, 4162 Info.Ctx.getLValueReferenceType(LValType)); 4163 NoteLValueLocation(Info, LVal.Base); 4164 return CompleteObject(); 4165 } 4166 } else { 4167 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4168 assert(BaseVal && "missing value for temporary"); 4169 } 4170 } 4171 4172 // In C++14, we can't safely access any mutable state when we might be 4173 // evaluating after an unmodeled side effect. Parameters are modeled as state 4174 // in the caller, but aren't visible once the call returns, so they can be 4175 // modified in a speculatively-evaluated call. 4176 // 4177 // FIXME: Not all local state is mutable. Allow local constant subobjects 4178 // to be read here (but take care with 'mutable' fields). 4179 unsigned VisibleDepth = Depth; 4180 if (llvm::isa_and_nonnull<ParmVarDecl>( 4181 LVal.Base.dyn_cast<const ValueDecl *>())) 4182 ++VisibleDepth; 4183 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4184 Info.EvalStatus.HasSideEffects) || 4185 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4186 return CompleteObject(); 4187 4188 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4189 } 4190 4191 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4192 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4193 /// glvalue referred to by an entity of reference type. 4194 /// 4195 /// \param Info - Information about the ongoing evaluation. 4196 /// \param Conv - The expression for which we are performing the conversion. 4197 /// Used for diagnostics. 4198 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4199 /// case of a non-class type). 4200 /// \param LVal - The glvalue on which we are attempting to perform this action. 4201 /// \param RVal - The produced value will be placed here. 4202 /// \param WantObjectRepresentation - If true, we're looking for the object 4203 /// representation rather than the value, and in particular, 4204 /// there is no requirement that the result be fully initialized. 4205 static bool 4206 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4207 const LValue &LVal, APValue &RVal, 4208 bool WantObjectRepresentation = false) { 4209 if (LVal.Designator.Invalid) 4210 return false; 4211 4212 // Check for special cases where there is no existing APValue to look at. 4213 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4214 4215 AccessKinds AK = 4216 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4217 4218 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4219 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4220 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4221 // initializer until now for such expressions. Such an expression can't be 4222 // an ICE in C, so this only matters for fold. 4223 if (Type.isVolatileQualified()) { 4224 Info.FFDiag(Conv); 4225 return false; 4226 } 4227 APValue Lit; 4228 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4229 return false; 4230 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4231 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4232 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4233 // Special-case character extraction so we don't have to construct an 4234 // APValue for the whole string. 4235 assert(LVal.Designator.Entries.size() <= 1 && 4236 "Can only read characters from string literals"); 4237 if (LVal.Designator.Entries.empty()) { 4238 // Fail for now for LValue to RValue conversion of an array. 4239 // (This shouldn't show up in C/C++, but it could be triggered by a 4240 // weird EvaluateAsRValue call from a tool.) 4241 Info.FFDiag(Conv); 4242 return false; 4243 } 4244 if (LVal.Designator.isOnePastTheEnd()) { 4245 if (Info.getLangOpts().CPlusPlus11) 4246 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4247 else 4248 Info.FFDiag(Conv); 4249 return false; 4250 } 4251 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4252 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4253 return true; 4254 } 4255 } 4256 4257 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4258 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4259 } 4260 4261 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4262 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4263 QualType LValType, APValue &Val) { 4264 if (LVal.Designator.Invalid) 4265 return false; 4266 4267 if (!Info.getLangOpts().CPlusPlus14) { 4268 Info.FFDiag(E); 4269 return false; 4270 } 4271 4272 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4273 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4274 } 4275 4276 namespace { 4277 struct CompoundAssignSubobjectHandler { 4278 EvalInfo &Info; 4279 const CompoundAssignOperator *E; 4280 QualType PromotedLHSType; 4281 BinaryOperatorKind Opcode; 4282 const APValue &RHS; 4283 4284 static const AccessKinds AccessKind = AK_Assign; 4285 4286 typedef bool result_type; 4287 4288 bool checkConst(QualType QT) { 4289 // Assigning to a const object has undefined behavior. 4290 if (QT.isConstQualified()) { 4291 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4292 return false; 4293 } 4294 return true; 4295 } 4296 4297 bool failed() { return false; } 4298 bool found(APValue &Subobj, QualType SubobjType) { 4299 switch (Subobj.getKind()) { 4300 case APValue::Int: 4301 return found(Subobj.getInt(), SubobjType); 4302 case APValue::Float: 4303 return found(Subobj.getFloat(), SubobjType); 4304 case APValue::ComplexInt: 4305 case APValue::ComplexFloat: 4306 // FIXME: Implement complex compound assignment. 4307 Info.FFDiag(E); 4308 return false; 4309 case APValue::LValue: 4310 return foundPointer(Subobj, SubobjType); 4311 case APValue::Vector: 4312 return foundVector(Subobj, SubobjType); 4313 default: 4314 // FIXME: can this happen? 4315 Info.FFDiag(E); 4316 return false; 4317 } 4318 } 4319 4320 bool foundVector(APValue &Value, QualType SubobjType) { 4321 if (!checkConst(SubobjType)) 4322 return false; 4323 4324 if (!SubobjType->isVectorType()) { 4325 Info.FFDiag(E); 4326 return false; 4327 } 4328 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4329 } 4330 4331 bool found(APSInt &Value, QualType SubobjType) { 4332 if (!checkConst(SubobjType)) 4333 return false; 4334 4335 if (!SubobjType->isIntegerType()) { 4336 // We don't support compound assignment on integer-cast-to-pointer 4337 // values. 4338 Info.FFDiag(E); 4339 return false; 4340 } 4341 4342 if (RHS.isInt()) { 4343 APSInt LHS = 4344 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4345 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4346 return false; 4347 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4348 return true; 4349 } else if (RHS.isFloat()) { 4350 const FPOptions FPO = E->getFPFeaturesInEffect( 4351 Info.Ctx.getLangOpts()); 4352 APFloat FValue(0.0); 4353 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4354 PromotedLHSType, FValue) && 4355 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4356 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4357 Value); 4358 } 4359 4360 Info.FFDiag(E); 4361 return false; 4362 } 4363 bool found(APFloat &Value, QualType SubobjType) { 4364 return checkConst(SubobjType) && 4365 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4366 Value) && 4367 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4368 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4369 } 4370 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4371 if (!checkConst(SubobjType)) 4372 return false; 4373 4374 QualType PointeeType; 4375 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4376 PointeeType = PT->getPointeeType(); 4377 4378 if (PointeeType.isNull() || !RHS.isInt() || 4379 (Opcode != BO_Add && Opcode != BO_Sub)) { 4380 Info.FFDiag(E); 4381 return false; 4382 } 4383 4384 APSInt Offset = RHS.getInt(); 4385 if (Opcode == BO_Sub) 4386 negateAsSigned(Offset); 4387 4388 LValue LVal; 4389 LVal.setFrom(Info.Ctx, Subobj); 4390 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4391 return false; 4392 LVal.moveInto(Subobj); 4393 return true; 4394 } 4395 }; 4396 } // end anonymous namespace 4397 4398 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4399 4400 /// Perform a compound assignment of LVal <op>= RVal. 4401 static bool handleCompoundAssignment(EvalInfo &Info, 4402 const CompoundAssignOperator *E, 4403 const LValue &LVal, QualType LValType, 4404 QualType PromotedLValType, 4405 BinaryOperatorKind Opcode, 4406 const APValue &RVal) { 4407 if (LVal.Designator.Invalid) 4408 return false; 4409 4410 if (!Info.getLangOpts().CPlusPlus14) { 4411 Info.FFDiag(E); 4412 return false; 4413 } 4414 4415 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4416 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4417 RVal }; 4418 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4419 } 4420 4421 namespace { 4422 struct IncDecSubobjectHandler { 4423 EvalInfo &Info; 4424 const UnaryOperator *E; 4425 AccessKinds AccessKind; 4426 APValue *Old; 4427 4428 typedef bool result_type; 4429 4430 bool checkConst(QualType QT) { 4431 // Assigning to a const object has undefined behavior. 4432 if (QT.isConstQualified()) { 4433 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4434 return false; 4435 } 4436 return true; 4437 } 4438 4439 bool failed() { return false; } 4440 bool found(APValue &Subobj, QualType SubobjType) { 4441 // Stash the old value. Also clear Old, so we don't clobber it later 4442 // if we're post-incrementing a complex. 4443 if (Old) { 4444 *Old = Subobj; 4445 Old = nullptr; 4446 } 4447 4448 switch (Subobj.getKind()) { 4449 case APValue::Int: 4450 return found(Subobj.getInt(), SubobjType); 4451 case APValue::Float: 4452 return found(Subobj.getFloat(), SubobjType); 4453 case APValue::ComplexInt: 4454 return found(Subobj.getComplexIntReal(), 4455 SubobjType->castAs<ComplexType>()->getElementType() 4456 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4457 case APValue::ComplexFloat: 4458 return found(Subobj.getComplexFloatReal(), 4459 SubobjType->castAs<ComplexType>()->getElementType() 4460 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4461 case APValue::LValue: 4462 return foundPointer(Subobj, SubobjType); 4463 default: 4464 // FIXME: can this happen? 4465 Info.FFDiag(E); 4466 return false; 4467 } 4468 } 4469 bool found(APSInt &Value, QualType SubobjType) { 4470 if (!checkConst(SubobjType)) 4471 return false; 4472 4473 if (!SubobjType->isIntegerType()) { 4474 // We don't support increment / decrement on integer-cast-to-pointer 4475 // values. 4476 Info.FFDiag(E); 4477 return false; 4478 } 4479 4480 if (Old) *Old = APValue(Value); 4481 4482 // bool arithmetic promotes to int, and the conversion back to bool 4483 // doesn't reduce mod 2^n, so special-case it. 4484 if (SubobjType->isBooleanType()) { 4485 if (AccessKind == AK_Increment) 4486 Value = 1; 4487 else 4488 Value = !Value; 4489 return true; 4490 } 4491 4492 bool WasNegative = Value.isNegative(); 4493 if (AccessKind == AK_Increment) { 4494 ++Value; 4495 4496 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4497 APSInt ActualValue(Value, /*IsUnsigned*/true); 4498 return HandleOverflow(Info, E, ActualValue, SubobjType); 4499 } 4500 } else { 4501 --Value; 4502 4503 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4504 unsigned BitWidth = Value.getBitWidth(); 4505 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4506 ActualValue.setBit(BitWidth); 4507 return HandleOverflow(Info, E, ActualValue, SubobjType); 4508 } 4509 } 4510 return true; 4511 } 4512 bool found(APFloat &Value, QualType SubobjType) { 4513 if (!checkConst(SubobjType)) 4514 return false; 4515 4516 if (Old) *Old = APValue(Value); 4517 4518 APFloat One(Value.getSemantics(), 1); 4519 if (AccessKind == AK_Increment) 4520 Value.add(One, APFloat::rmNearestTiesToEven); 4521 else 4522 Value.subtract(One, APFloat::rmNearestTiesToEven); 4523 return true; 4524 } 4525 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4526 if (!checkConst(SubobjType)) 4527 return false; 4528 4529 QualType PointeeType; 4530 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4531 PointeeType = PT->getPointeeType(); 4532 else { 4533 Info.FFDiag(E); 4534 return false; 4535 } 4536 4537 LValue LVal; 4538 LVal.setFrom(Info.Ctx, Subobj); 4539 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4540 AccessKind == AK_Increment ? 1 : -1)) 4541 return false; 4542 LVal.moveInto(Subobj); 4543 return true; 4544 } 4545 }; 4546 } // end anonymous namespace 4547 4548 /// Perform an increment or decrement on LVal. 4549 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4550 QualType LValType, bool IsIncrement, APValue *Old) { 4551 if (LVal.Designator.Invalid) 4552 return false; 4553 4554 if (!Info.getLangOpts().CPlusPlus14) { 4555 Info.FFDiag(E); 4556 return false; 4557 } 4558 4559 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4560 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4561 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4562 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4563 } 4564 4565 /// Build an lvalue for the object argument of a member function call. 4566 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4567 LValue &This) { 4568 if (Object->getType()->isPointerType() && Object->isRValue()) 4569 return EvaluatePointer(Object, This, Info); 4570 4571 if (Object->isGLValue()) 4572 return EvaluateLValue(Object, This, Info); 4573 4574 if (Object->getType()->isLiteralType(Info.Ctx)) 4575 return EvaluateTemporary(Object, This, Info); 4576 4577 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4578 return false; 4579 } 4580 4581 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4582 /// lvalue referring to the result. 4583 /// 4584 /// \param Info - Information about the ongoing evaluation. 4585 /// \param LV - An lvalue referring to the base of the member pointer. 4586 /// \param RHS - The member pointer expression. 4587 /// \param IncludeMember - Specifies whether the member itself is included in 4588 /// the resulting LValue subobject designator. This is not possible when 4589 /// creating a bound member function. 4590 /// \return The field or method declaration to which the member pointer refers, 4591 /// or 0 if evaluation fails. 4592 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4593 QualType LVType, 4594 LValue &LV, 4595 const Expr *RHS, 4596 bool IncludeMember = true) { 4597 MemberPtr MemPtr; 4598 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4599 return nullptr; 4600 4601 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4602 // member value, the behavior is undefined. 4603 if (!MemPtr.getDecl()) { 4604 // FIXME: Specific diagnostic. 4605 Info.FFDiag(RHS); 4606 return nullptr; 4607 } 4608 4609 if (MemPtr.isDerivedMember()) { 4610 // This is a member of some derived class. Truncate LV appropriately. 4611 // The end of the derived-to-base path for the base object must match the 4612 // derived-to-base path for the member pointer. 4613 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4614 LV.Designator.Entries.size()) { 4615 Info.FFDiag(RHS); 4616 return nullptr; 4617 } 4618 unsigned PathLengthToMember = 4619 LV.Designator.Entries.size() - MemPtr.Path.size(); 4620 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4621 const CXXRecordDecl *LVDecl = getAsBaseClass( 4622 LV.Designator.Entries[PathLengthToMember + I]); 4623 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4624 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4625 Info.FFDiag(RHS); 4626 return nullptr; 4627 } 4628 } 4629 4630 // Truncate the lvalue to the appropriate derived class. 4631 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4632 PathLengthToMember)) 4633 return nullptr; 4634 } else if (!MemPtr.Path.empty()) { 4635 // Extend the LValue path with the member pointer's path. 4636 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4637 MemPtr.Path.size() + IncludeMember); 4638 4639 // Walk down to the appropriate base class. 4640 if (const PointerType *PT = LVType->getAs<PointerType>()) 4641 LVType = PT->getPointeeType(); 4642 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4643 assert(RD && "member pointer access on non-class-type expression"); 4644 // The first class in the path is that of the lvalue. 4645 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4646 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4647 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4648 return nullptr; 4649 RD = Base; 4650 } 4651 // Finally cast to the class containing the member. 4652 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4653 MemPtr.getContainingRecord())) 4654 return nullptr; 4655 } 4656 4657 // Add the member. Note that we cannot build bound member functions here. 4658 if (IncludeMember) { 4659 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4660 if (!HandleLValueMember(Info, RHS, LV, FD)) 4661 return nullptr; 4662 } else if (const IndirectFieldDecl *IFD = 4663 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4664 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4665 return nullptr; 4666 } else { 4667 llvm_unreachable("can't construct reference to bound member function"); 4668 } 4669 } 4670 4671 return MemPtr.getDecl(); 4672 } 4673 4674 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4675 const BinaryOperator *BO, 4676 LValue &LV, 4677 bool IncludeMember = true) { 4678 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4679 4680 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4681 if (Info.noteFailure()) { 4682 MemberPtr MemPtr; 4683 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4684 } 4685 return nullptr; 4686 } 4687 4688 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4689 BO->getRHS(), IncludeMember); 4690 } 4691 4692 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4693 /// the provided lvalue, which currently refers to the base object. 4694 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4695 LValue &Result) { 4696 SubobjectDesignator &D = Result.Designator; 4697 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4698 return false; 4699 4700 QualType TargetQT = E->getType(); 4701 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4702 TargetQT = PT->getPointeeType(); 4703 4704 // Check this cast lands within the final derived-to-base subobject path. 4705 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4706 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4707 << D.MostDerivedType << TargetQT; 4708 return false; 4709 } 4710 4711 // Check the type of the final cast. We don't need to check the path, 4712 // since a cast can only be formed if the path is unique. 4713 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4714 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4715 const CXXRecordDecl *FinalType; 4716 if (NewEntriesSize == D.MostDerivedPathLength) 4717 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4718 else 4719 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4720 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4721 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4722 << D.MostDerivedType << TargetQT; 4723 return false; 4724 } 4725 4726 // Truncate the lvalue to the appropriate derived class. 4727 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4728 } 4729 4730 /// Get the value to use for a default-initialized object of type T. 4731 /// Return false if it encounters something invalid. 4732 static bool getDefaultInitValue(QualType T, APValue &Result) { 4733 bool Success = true; 4734 if (auto *RD = T->getAsCXXRecordDecl()) { 4735 if (RD->isInvalidDecl()) { 4736 Result = APValue(); 4737 return false; 4738 } 4739 if (RD->isUnion()) { 4740 Result = APValue((const FieldDecl *)nullptr); 4741 return true; 4742 } 4743 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4744 std::distance(RD->field_begin(), RD->field_end())); 4745 4746 unsigned Index = 0; 4747 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4748 End = RD->bases_end(); 4749 I != End; ++I, ++Index) 4750 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4751 4752 for (const auto *I : RD->fields()) { 4753 if (I->isUnnamedBitfield()) 4754 continue; 4755 Success &= getDefaultInitValue(I->getType(), 4756 Result.getStructField(I->getFieldIndex())); 4757 } 4758 return Success; 4759 } 4760 4761 if (auto *AT = 4762 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4763 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4764 if (Result.hasArrayFiller()) 4765 Success &= 4766 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4767 4768 return Success; 4769 } 4770 4771 Result = APValue::IndeterminateValue(); 4772 return true; 4773 } 4774 4775 namespace { 4776 enum EvalStmtResult { 4777 /// Evaluation failed. 4778 ESR_Failed, 4779 /// Hit a 'return' statement. 4780 ESR_Returned, 4781 /// Evaluation succeeded. 4782 ESR_Succeeded, 4783 /// Hit a 'continue' statement. 4784 ESR_Continue, 4785 /// Hit a 'break' statement. 4786 ESR_Break, 4787 /// Still scanning for 'case' or 'default' statement. 4788 ESR_CaseNotFound 4789 }; 4790 } 4791 4792 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4793 // We don't need to evaluate the initializer for a static local. 4794 if (!VD->hasLocalStorage()) 4795 return true; 4796 4797 LValue Result; 4798 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4799 ScopeKind::Block, Result); 4800 4801 const Expr *InitE = VD->getInit(); 4802 if (!InitE) { 4803 if (VD->getType()->isDependentType()) 4804 return Info.noteSideEffect(); 4805 return getDefaultInitValue(VD->getType(), Val); 4806 } 4807 if (InitE->isValueDependent()) 4808 return false; 4809 4810 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4811 // Wipe out any partially-computed value, to allow tracking that this 4812 // evaluation failed. 4813 Val = APValue(); 4814 return false; 4815 } 4816 4817 return true; 4818 } 4819 4820 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4821 bool OK = true; 4822 4823 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4824 OK &= EvaluateVarDecl(Info, VD); 4825 4826 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4827 for (auto *BD : DD->bindings()) 4828 if (auto *VD = BD->getHoldingVar()) 4829 OK &= EvaluateDecl(Info, VD); 4830 4831 return OK; 4832 } 4833 4834 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4835 assert(E->isValueDependent()); 4836 if (Info.noteSideEffect()) 4837 return true; 4838 assert(E->containsErrors() && "valid value-dependent expression should never " 4839 "reach invalid code path."); 4840 return false; 4841 } 4842 4843 /// Evaluate a condition (either a variable declaration or an expression). 4844 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4845 const Expr *Cond, bool &Result) { 4846 if (Cond->isValueDependent()) 4847 return false; 4848 FullExpressionRAII Scope(Info); 4849 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4850 return false; 4851 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4852 return false; 4853 return Scope.destroy(); 4854 } 4855 4856 namespace { 4857 /// A location where the result (returned value) of evaluating a 4858 /// statement should be stored. 4859 struct StmtResult { 4860 /// The APValue that should be filled in with the returned value. 4861 APValue &Value; 4862 /// The location containing the result, if any (used to support RVO). 4863 const LValue *Slot; 4864 }; 4865 4866 struct TempVersionRAII { 4867 CallStackFrame &Frame; 4868 4869 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4870 Frame.pushTempVersion(); 4871 } 4872 4873 ~TempVersionRAII() { 4874 Frame.popTempVersion(); 4875 } 4876 }; 4877 4878 } 4879 4880 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4881 const Stmt *S, 4882 const SwitchCase *SC = nullptr); 4883 4884 /// Evaluate the body of a loop, and translate the result as appropriate. 4885 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4886 const Stmt *Body, 4887 const SwitchCase *Case = nullptr) { 4888 BlockScopeRAII Scope(Info); 4889 4890 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4891 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4892 ESR = ESR_Failed; 4893 4894 switch (ESR) { 4895 case ESR_Break: 4896 return ESR_Succeeded; 4897 case ESR_Succeeded: 4898 case ESR_Continue: 4899 return ESR_Continue; 4900 case ESR_Failed: 4901 case ESR_Returned: 4902 case ESR_CaseNotFound: 4903 return ESR; 4904 } 4905 llvm_unreachable("Invalid EvalStmtResult!"); 4906 } 4907 4908 /// Evaluate a switch statement. 4909 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4910 const SwitchStmt *SS) { 4911 BlockScopeRAII Scope(Info); 4912 4913 // Evaluate the switch condition. 4914 APSInt Value; 4915 { 4916 if (const Stmt *Init = SS->getInit()) { 4917 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4918 if (ESR != ESR_Succeeded) { 4919 if (ESR != ESR_Failed && !Scope.destroy()) 4920 ESR = ESR_Failed; 4921 return ESR; 4922 } 4923 } 4924 4925 FullExpressionRAII CondScope(Info); 4926 if (SS->getConditionVariable() && 4927 !EvaluateDecl(Info, SS->getConditionVariable())) 4928 return ESR_Failed; 4929 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4930 return ESR_Failed; 4931 if (!CondScope.destroy()) 4932 return ESR_Failed; 4933 } 4934 4935 // Find the switch case corresponding to the value of the condition. 4936 // FIXME: Cache this lookup. 4937 const SwitchCase *Found = nullptr; 4938 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4939 SC = SC->getNextSwitchCase()) { 4940 if (isa<DefaultStmt>(SC)) { 4941 Found = SC; 4942 continue; 4943 } 4944 4945 const CaseStmt *CS = cast<CaseStmt>(SC); 4946 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4947 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4948 : LHS; 4949 if (LHS <= Value && Value <= RHS) { 4950 Found = SC; 4951 break; 4952 } 4953 } 4954 4955 if (!Found) 4956 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4957 4958 // Search the switch body for the switch case and evaluate it from there. 4959 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4960 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4961 return ESR_Failed; 4962 4963 switch (ESR) { 4964 case ESR_Break: 4965 return ESR_Succeeded; 4966 case ESR_Succeeded: 4967 case ESR_Continue: 4968 case ESR_Failed: 4969 case ESR_Returned: 4970 return ESR; 4971 case ESR_CaseNotFound: 4972 // This can only happen if the switch case is nested within a statement 4973 // expression. We have no intention of supporting that. 4974 Info.FFDiag(Found->getBeginLoc(), 4975 diag::note_constexpr_stmt_expr_unsupported); 4976 return ESR_Failed; 4977 } 4978 llvm_unreachable("Invalid EvalStmtResult!"); 4979 } 4980 4981 // Evaluate a statement. 4982 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4983 const Stmt *S, const SwitchCase *Case) { 4984 if (!Info.nextStep(S)) 4985 return ESR_Failed; 4986 4987 // If we're hunting down a 'case' or 'default' label, recurse through 4988 // substatements until we hit the label. 4989 if (Case) { 4990 switch (S->getStmtClass()) { 4991 case Stmt::CompoundStmtClass: 4992 // FIXME: Precompute which substatement of a compound statement we 4993 // would jump to, and go straight there rather than performing a 4994 // linear scan each time. 4995 case Stmt::LabelStmtClass: 4996 case Stmt::AttributedStmtClass: 4997 case Stmt::DoStmtClass: 4998 break; 4999 5000 case Stmt::CaseStmtClass: 5001 case Stmt::DefaultStmtClass: 5002 if (Case == S) 5003 Case = nullptr; 5004 break; 5005 5006 case Stmt::IfStmtClass: { 5007 // FIXME: Precompute which side of an 'if' we would jump to, and go 5008 // straight there rather than scanning both sides. 5009 const IfStmt *IS = cast<IfStmt>(S); 5010 5011 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5012 // preceded by our switch label. 5013 BlockScopeRAII Scope(Info); 5014 5015 // Step into the init statement in case it brings an (uninitialized) 5016 // variable into scope. 5017 if (const Stmt *Init = IS->getInit()) { 5018 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5019 if (ESR != ESR_CaseNotFound) { 5020 assert(ESR != ESR_Succeeded); 5021 return ESR; 5022 } 5023 } 5024 5025 // Condition variable must be initialized if it exists. 5026 // FIXME: We can skip evaluating the body if there's a condition 5027 // variable, as there can't be any case labels within it. 5028 // (The same is true for 'for' statements.) 5029 5030 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5031 if (ESR == ESR_Failed) 5032 return ESR; 5033 if (ESR != ESR_CaseNotFound) 5034 return Scope.destroy() ? ESR : ESR_Failed; 5035 if (!IS->getElse()) 5036 return ESR_CaseNotFound; 5037 5038 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5039 if (ESR == ESR_Failed) 5040 return ESR; 5041 if (ESR != ESR_CaseNotFound) 5042 return Scope.destroy() ? ESR : ESR_Failed; 5043 return ESR_CaseNotFound; 5044 } 5045 5046 case Stmt::WhileStmtClass: { 5047 EvalStmtResult ESR = 5048 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5049 if (ESR != ESR_Continue) 5050 return ESR; 5051 break; 5052 } 5053 5054 case Stmt::ForStmtClass: { 5055 const ForStmt *FS = cast<ForStmt>(S); 5056 BlockScopeRAII Scope(Info); 5057 5058 // Step into the init statement in case it brings an (uninitialized) 5059 // variable into scope. 5060 if (const Stmt *Init = FS->getInit()) { 5061 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5062 if (ESR != ESR_CaseNotFound) { 5063 assert(ESR != ESR_Succeeded); 5064 return ESR; 5065 } 5066 } 5067 5068 EvalStmtResult ESR = 5069 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5070 if (ESR != ESR_Continue) 5071 return ESR; 5072 if (const auto *Inc = FS->getInc()) { 5073 if (Inc->isValueDependent()) { 5074 if (!EvaluateDependentExpr(Inc, Info)) 5075 return ESR_Failed; 5076 } else { 5077 FullExpressionRAII IncScope(Info); 5078 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5079 return ESR_Failed; 5080 } 5081 } 5082 break; 5083 } 5084 5085 case Stmt::DeclStmtClass: { 5086 // Start the lifetime of any uninitialized variables we encounter. They 5087 // might be used by the selected branch of the switch. 5088 const DeclStmt *DS = cast<DeclStmt>(S); 5089 for (const auto *D : DS->decls()) { 5090 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5091 if (VD->hasLocalStorage() && !VD->getInit()) 5092 if (!EvaluateVarDecl(Info, VD)) 5093 return ESR_Failed; 5094 // FIXME: If the variable has initialization that can't be jumped 5095 // over, bail out of any immediately-surrounding compound-statement 5096 // too. There can't be any case labels here. 5097 } 5098 } 5099 return ESR_CaseNotFound; 5100 } 5101 5102 default: 5103 return ESR_CaseNotFound; 5104 } 5105 } 5106 5107 switch (S->getStmtClass()) { 5108 default: 5109 if (const Expr *E = dyn_cast<Expr>(S)) { 5110 if (E->isValueDependent()) { 5111 if (!EvaluateDependentExpr(E, Info)) 5112 return ESR_Failed; 5113 } else { 5114 // Don't bother evaluating beyond an expression-statement which couldn't 5115 // be evaluated. 5116 // FIXME: Do we need the FullExpressionRAII object here? 5117 // VisitExprWithCleanups should create one when necessary. 5118 FullExpressionRAII Scope(Info); 5119 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5120 return ESR_Failed; 5121 } 5122 return ESR_Succeeded; 5123 } 5124 5125 Info.FFDiag(S->getBeginLoc()); 5126 return ESR_Failed; 5127 5128 case Stmt::NullStmtClass: 5129 return ESR_Succeeded; 5130 5131 case Stmt::DeclStmtClass: { 5132 const DeclStmt *DS = cast<DeclStmt>(S); 5133 for (const auto *D : DS->decls()) { 5134 // Each declaration initialization is its own full-expression. 5135 FullExpressionRAII Scope(Info); 5136 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5137 return ESR_Failed; 5138 if (!Scope.destroy()) 5139 return ESR_Failed; 5140 } 5141 return ESR_Succeeded; 5142 } 5143 5144 case Stmt::ReturnStmtClass: { 5145 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5146 FullExpressionRAII Scope(Info); 5147 if (RetExpr && RetExpr->isValueDependent()) { 5148 EvaluateDependentExpr(RetExpr, Info); 5149 // We know we returned, but we don't know what the value is. 5150 return ESR_Failed; 5151 } 5152 if (RetExpr && 5153 !(Result.Slot 5154 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5155 : Evaluate(Result.Value, Info, RetExpr))) 5156 return ESR_Failed; 5157 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5158 } 5159 5160 case Stmt::CompoundStmtClass: { 5161 BlockScopeRAII Scope(Info); 5162 5163 const CompoundStmt *CS = cast<CompoundStmt>(S); 5164 for (const auto *BI : CS->body()) { 5165 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5166 if (ESR == ESR_Succeeded) 5167 Case = nullptr; 5168 else if (ESR != ESR_CaseNotFound) { 5169 if (ESR != ESR_Failed && !Scope.destroy()) 5170 return ESR_Failed; 5171 return ESR; 5172 } 5173 } 5174 if (Case) 5175 return ESR_CaseNotFound; 5176 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5177 } 5178 5179 case Stmt::IfStmtClass: { 5180 const IfStmt *IS = cast<IfStmt>(S); 5181 5182 // Evaluate the condition, as either a var decl or as an expression. 5183 BlockScopeRAII Scope(Info); 5184 if (const Stmt *Init = IS->getInit()) { 5185 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5186 if (ESR != ESR_Succeeded) { 5187 if (ESR != ESR_Failed && !Scope.destroy()) 5188 return ESR_Failed; 5189 return ESR; 5190 } 5191 } 5192 bool Cond; 5193 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5194 return ESR_Failed; 5195 5196 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5197 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5198 if (ESR != ESR_Succeeded) { 5199 if (ESR != ESR_Failed && !Scope.destroy()) 5200 return ESR_Failed; 5201 return ESR; 5202 } 5203 } 5204 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5205 } 5206 5207 case Stmt::WhileStmtClass: { 5208 const WhileStmt *WS = cast<WhileStmt>(S); 5209 while (true) { 5210 BlockScopeRAII Scope(Info); 5211 bool Continue; 5212 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5213 Continue)) 5214 return ESR_Failed; 5215 if (!Continue) 5216 break; 5217 5218 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5219 if (ESR != ESR_Continue) { 5220 if (ESR != ESR_Failed && !Scope.destroy()) 5221 return ESR_Failed; 5222 return ESR; 5223 } 5224 if (!Scope.destroy()) 5225 return ESR_Failed; 5226 } 5227 return ESR_Succeeded; 5228 } 5229 5230 case Stmt::DoStmtClass: { 5231 const DoStmt *DS = cast<DoStmt>(S); 5232 bool Continue; 5233 do { 5234 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5235 if (ESR != ESR_Continue) 5236 return ESR; 5237 Case = nullptr; 5238 5239 if (DS->getCond()->isValueDependent()) { 5240 EvaluateDependentExpr(DS->getCond(), Info); 5241 // Bailout as we don't know whether to keep going or terminate the loop. 5242 return ESR_Failed; 5243 } 5244 FullExpressionRAII CondScope(Info); 5245 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5246 !CondScope.destroy()) 5247 return ESR_Failed; 5248 } while (Continue); 5249 return ESR_Succeeded; 5250 } 5251 5252 case Stmt::ForStmtClass: { 5253 const ForStmt *FS = cast<ForStmt>(S); 5254 BlockScopeRAII ForScope(Info); 5255 if (FS->getInit()) { 5256 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5257 if (ESR != ESR_Succeeded) { 5258 if (ESR != ESR_Failed && !ForScope.destroy()) 5259 return ESR_Failed; 5260 return ESR; 5261 } 5262 } 5263 while (true) { 5264 BlockScopeRAII IterScope(Info); 5265 bool Continue = true; 5266 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5267 FS->getCond(), Continue)) 5268 return ESR_Failed; 5269 if (!Continue) 5270 break; 5271 5272 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5273 if (ESR != ESR_Continue) { 5274 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5275 return ESR_Failed; 5276 return ESR; 5277 } 5278 5279 if (const auto *Inc = FS->getInc()) { 5280 if (Inc->isValueDependent()) { 5281 if (!EvaluateDependentExpr(Inc, Info)) 5282 return ESR_Failed; 5283 } else { 5284 FullExpressionRAII IncScope(Info); 5285 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5286 return ESR_Failed; 5287 } 5288 } 5289 5290 if (!IterScope.destroy()) 5291 return ESR_Failed; 5292 } 5293 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5294 } 5295 5296 case Stmt::CXXForRangeStmtClass: { 5297 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5298 BlockScopeRAII Scope(Info); 5299 5300 // Evaluate the init-statement if present. 5301 if (FS->getInit()) { 5302 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5303 if (ESR != ESR_Succeeded) { 5304 if (ESR != ESR_Failed && !Scope.destroy()) 5305 return ESR_Failed; 5306 return ESR; 5307 } 5308 } 5309 5310 // Initialize the __range variable. 5311 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5312 if (ESR != ESR_Succeeded) { 5313 if (ESR != ESR_Failed && !Scope.destroy()) 5314 return ESR_Failed; 5315 return ESR; 5316 } 5317 5318 // Create the __begin and __end iterators. 5319 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5320 if (ESR != ESR_Succeeded) { 5321 if (ESR != ESR_Failed && !Scope.destroy()) 5322 return ESR_Failed; 5323 return ESR; 5324 } 5325 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5326 if (ESR != ESR_Succeeded) { 5327 if (ESR != ESR_Failed && !Scope.destroy()) 5328 return ESR_Failed; 5329 return ESR; 5330 } 5331 5332 while (true) { 5333 // Condition: __begin != __end. 5334 { 5335 if (FS->getCond()->isValueDependent()) { 5336 EvaluateDependentExpr(FS->getCond(), Info); 5337 // We don't know whether to keep going or terminate the loop. 5338 return ESR_Failed; 5339 } 5340 bool Continue = true; 5341 FullExpressionRAII CondExpr(Info); 5342 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5343 return ESR_Failed; 5344 if (!Continue) 5345 break; 5346 } 5347 5348 // User's variable declaration, initialized by *__begin. 5349 BlockScopeRAII InnerScope(Info); 5350 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5351 if (ESR != ESR_Succeeded) { 5352 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5353 return ESR_Failed; 5354 return ESR; 5355 } 5356 5357 // Loop body. 5358 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5359 if (ESR != ESR_Continue) { 5360 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5361 return ESR_Failed; 5362 return ESR; 5363 } 5364 if (FS->getInc()->isValueDependent()) { 5365 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5366 return ESR_Failed; 5367 } else { 5368 // Increment: ++__begin 5369 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5370 return ESR_Failed; 5371 } 5372 5373 if (!InnerScope.destroy()) 5374 return ESR_Failed; 5375 } 5376 5377 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5378 } 5379 5380 case Stmt::SwitchStmtClass: 5381 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5382 5383 case Stmt::ContinueStmtClass: 5384 return ESR_Continue; 5385 5386 case Stmt::BreakStmtClass: 5387 return ESR_Break; 5388 5389 case Stmt::LabelStmtClass: 5390 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5391 5392 case Stmt::AttributedStmtClass: 5393 // As a general principle, C++11 attributes can be ignored without 5394 // any semantic impact. 5395 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5396 Case); 5397 5398 case Stmt::CaseStmtClass: 5399 case Stmt::DefaultStmtClass: 5400 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5401 case Stmt::CXXTryStmtClass: 5402 // Evaluate try blocks by evaluating all sub statements. 5403 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5404 } 5405 } 5406 5407 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5408 /// default constructor. If so, we'll fold it whether or not it's marked as 5409 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5410 /// so we need special handling. 5411 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5412 const CXXConstructorDecl *CD, 5413 bool IsValueInitialization) { 5414 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5415 return false; 5416 5417 // Value-initialization does not call a trivial default constructor, so such a 5418 // call is a core constant expression whether or not the constructor is 5419 // constexpr. 5420 if (!CD->isConstexpr() && !IsValueInitialization) { 5421 if (Info.getLangOpts().CPlusPlus11) { 5422 // FIXME: If DiagDecl is an implicitly-declared special member function, 5423 // we should be much more explicit about why it's not constexpr. 5424 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5425 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5426 Info.Note(CD->getLocation(), diag::note_declared_at); 5427 } else { 5428 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5429 } 5430 } 5431 return true; 5432 } 5433 5434 /// CheckConstexprFunction - Check that a function can be called in a constant 5435 /// expression. 5436 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5437 const FunctionDecl *Declaration, 5438 const FunctionDecl *Definition, 5439 const Stmt *Body) { 5440 // Potential constant expressions can contain calls to declared, but not yet 5441 // defined, constexpr functions. 5442 if (Info.checkingPotentialConstantExpression() && !Definition && 5443 Declaration->isConstexpr()) 5444 return false; 5445 5446 // Bail out if the function declaration itself is invalid. We will 5447 // have produced a relevant diagnostic while parsing it, so just 5448 // note the problematic sub-expression. 5449 if (Declaration->isInvalidDecl()) { 5450 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5451 return false; 5452 } 5453 5454 // DR1872: An instantiated virtual constexpr function can't be called in a 5455 // constant expression (prior to C++20). We can still constant-fold such a 5456 // call. 5457 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5458 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5459 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5460 5461 if (Definition && Definition->isInvalidDecl()) { 5462 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5463 return false; 5464 } 5465 5466 // Can we evaluate this function call? 5467 if (Definition && Definition->isConstexpr() && Body) 5468 return true; 5469 5470 if (Info.getLangOpts().CPlusPlus11) { 5471 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5472 5473 // If this function is not constexpr because it is an inherited 5474 // non-constexpr constructor, diagnose that directly. 5475 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5476 if (CD && CD->isInheritingConstructor()) { 5477 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5478 if (!Inherited->isConstexpr()) 5479 DiagDecl = CD = Inherited; 5480 } 5481 5482 // FIXME: If DiagDecl is an implicitly-declared special member function 5483 // or an inheriting constructor, we should be much more explicit about why 5484 // it's not constexpr. 5485 if (CD && CD->isInheritingConstructor()) 5486 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5487 << CD->getInheritedConstructor().getConstructor()->getParent(); 5488 else 5489 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5490 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5491 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5492 } else { 5493 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5494 } 5495 return false; 5496 } 5497 5498 namespace { 5499 struct CheckDynamicTypeHandler { 5500 AccessKinds AccessKind; 5501 typedef bool result_type; 5502 bool failed() { return false; } 5503 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5504 bool found(APSInt &Value, QualType SubobjType) { return true; } 5505 bool found(APFloat &Value, QualType SubobjType) { return true; } 5506 }; 5507 } // end anonymous namespace 5508 5509 /// Check that we can access the notional vptr of an object / determine its 5510 /// dynamic type. 5511 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5512 AccessKinds AK, bool Polymorphic) { 5513 if (This.Designator.Invalid) 5514 return false; 5515 5516 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5517 5518 if (!Obj) 5519 return false; 5520 5521 if (!Obj.Value) { 5522 // The object is not usable in constant expressions, so we can't inspect 5523 // its value to see if it's in-lifetime or what the active union members 5524 // are. We can still check for a one-past-the-end lvalue. 5525 if (This.Designator.isOnePastTheEnd() || 5526 This.Designator.isMostDerivedAnUnsizedArray()) { 5527 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5528 ? diag::note_constexpr_access_past_end 5529 : diag::note_constexpr_access_unsized_array) 5530 << AK; 5531 return false; 5532 } else if (Polymorphic) { 5533 // Conservatively refuse to perform a polymorphic operation if we would 5534 // not be able to read a notional 'vptr' value. 5535 APValue Val; 5536 This.moveInto(Val); 5537 QualType StarThisType = 5538 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5539 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5540 << AK << Val.getAsString(Info.Ctx, StarThisType); 5541 return false; 5542 } 5543 return true; 5544 } 5545 5546 CheckDynamicTypeHandler Handler{AK}; 5547 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5548 } 5549 5550 /// Check that the pointee of the 'this' pointer in a member function call is 5551 /// either within its lifetime or in its period of construction or destruction. 5552 static bool 5553 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5554 const LValue &This, 5555 const CXXMethodDecl *NamedMember) { 5556 return checkDynamicType( 5557 Info, E, This, 5558 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5559 } 5560 5561 struct DynamicType { 5562 /// The dynamic class type of the object. 5563 const CXXRecordDecl *Type; 5564 /// The corresponding path length in the lvalue. 5565 unsigned PathLength; 5566 }; 5567 5568 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5569 unsigned PathLength) { 5570 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5571 Designator.Entries.size() && "invalid path length"); 5572 return (PathLength == Designator.MostDerivedPathLength) 5573 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5574 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5575 } 5576 5577 /// Determine the dynamic type of an object. 5578 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5579 LValue &This, AccessKinds AK) { 5580 // If we don't have an lvalue denoting an object of class type, there is no 5581 // meaningful dynamic type. (We consider objects of non-class type to have no 5582 // dynamic type.) 5583 if (!checkDynamicType(Info, E, This, AK, true)) 5584 return None; 5585 5586 // Refuse to compute a dynamic type in the presence of virtual bases. This 5587 // shouldn't happen other than in constant-folding situations, since literal 5588 // types can't have virtual bases. 5589 // 5590 // Note that consumers of DynamicType assume that the type has no virtual 5591 // bases, and will need modifications if this restriction is relaxed. 5592 const CXXRecordDecl *Class = 5593 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5594 if (!Class || Class->getNumVBases()) { 5595 Info.FFDiag(E); 5596 return None; 5597 } 5598 5599 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5600 // binary search here instead. But the overwhelmingly common case is that 5601 // we're not in the middle of a constructor, so it probably doesn't matter 5602 // in practice. 5603 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5604 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5605 PathLength <= Path.size(); ++PathLength) { 5606 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5607 Path.slice(0, PathLength))) { 5608 case ConstructionPhase::Bases: 5609 case ConstructionPhase::DestroyingBases: 5610 // We're constructing or destroying a base class. This is not the dynamic 5611 // type. 5612 break; 5613 5614 case ConstructionPhase::None: 5615 case ConstructionPhase::AfterBases: 5616 case ConstructionPhase::AfterFields: 5617 case ConstructionPhase::Destroying: 5618 // We've finished constructing the base classes and not yet started 5619 // destroying them again, so this is the dynamic type. 5620 return DynamicType{getBaseClassType(This.Designator, PathLength), 5621 PathLength}; 5622 } 5623 } 5624 5625 // CWG issue 1517: we're constructing a base class of the object described by 5626 // 'This', so that object has not yet begun its period of construction and 5627 // any polymorphic operation on it results in undefined behavior. 5628 Info.FFDiag(E); 5629 return None; 5630 } 5631 5632 /// Perform virtual dispatch. 5633 static const CXXMethodDecl *HandleVirtualDispatch( 5634 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5635 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5636 Optional<DynamicType> DynType = ComputeDynamicType( 5637 Info, E, This, 5638 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5639 if (!DynType) 5640 return nullptr; 5641 5642 // Find the final overrider. It must be declared in one of the classes on the 5643 // path from the dynamic type to the static type. 5644 // FIXME: If we ever allow literal types to have virtual base classes, that 5645 // won't be true. 5646 const CXXMethodDecl *Callee = Found; 5647 unsigned PathLength = DynType->PathLength; 5648 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5649 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5650 const CXXMethodDecl *Overrider = 5651 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5652 if (Overrider) { 5653 Callee = Overrider; 5654 break; 5655 } 5656 } 5657 5658 // C++2a [class.abstract]p6: 5659 // the effect of making a virtual call to a pure virtual function [...] is 5660 // undefined 5661 if (Callee->isPure()) { 5662 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5663 Info.Note(Callee->getLocation(), diag::note_declared_at); 5664 return nullptr; 5665 } 5666 5667 // If necessary, walk the rest of the path to determine the sequence of 5668 // covariant adjustment steps to apply. 5669 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5670 Found->getReturnType())) { 5671 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5672 for (unsigned CovariantPathLength = PathLength + 1; 5673 CovariantPathLength != This.Designator.Entries.size(); 5674 ++CovariantPathLength) { 5675 const CXXRecordDecl *NextClass = 5676 getBaseClassType(This.Designator, CovariantPathLength); 5677 const CXXMethodDecl *Next = 5678 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5679 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5680 Next->getReturnType(), CovariantAdjustmentPath.back())) 5681 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5682 } 5683 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5684 CovariantAdjustmentPath.back())) 5685 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5686 } 5687 5688 // Perform 'this' adjustment. 5689 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5690 return nullptr; 5691 5692 return Callee; 5693 } 5694 5695 /// Perform the adjustment from a value returned by a virtual function to 5696 /// a value of the statically expected type, which may be a pointer or 5697 /// reference to a base class of the returned type. 5698 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5699 APValue &Result, 5700 ArrayRef<QualType> Path) { 5701 assert(Result.isLValue() && 5702 "unexpected kind of APValue for covariant return"); 5703 if (Result.isNullPointer()) 5704 return true; 5705 5706 LValue LVal; 5707 LVal.setFrom(Info.Ctx, Result); 5708 5709 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5710 for (unsigned I = 1; I != Path.size(); ++I) { 5711 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5712 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5713 if (OldClass != NewClass && 5714 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5715 return false; 5716 OldClass = NewClass; 5717 } 5718 5719 LVal.moveInto(Result); 5720 return true; 5721 } 5722 5723 /// Determine whether \p Base, which is known to be a direct base class of 5724 /// \p Derived, is a public base class. 5725 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5726 const CXXRecordDecl *Base) { 5727 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5728 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5729 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5730 return BaseSpec.getAccessSpecifier() == AS_public; 5731 } 5732 llvm_unreachable("Base is not a direct base of Derived"); 5733 } 5734 5735 /// Apply the given dynamic cast operation on the provided lvalue. 5736 /// 5737 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5738 /// to find a suitable target subobject. 5739 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5740 LValue &Ptr) { 5741 // We can't do anything with a non-symbolic pointer value. 5742 SubobjectDesignator &D = Ptr.Designator; 5743 if (D.Invalid) 5744 return false; 5745 5746 // C++ [expr.dynamic.cast]p6: 5747 // If v is a null pointer value, the result is a null pointer value. 5748 if (Ptr.isNullPointer() && !E->isGLValue()) 5749 return true; 5750 5751 // For all the other cases, we need the pointer to point to an object within 5752 // its lifetime / period of construction / destruction, and we need to know 5753 // its dynamic type. 5754 Optional<DynamicType> DynType = 5755 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5756 if (!DynType) 5757 return false; 5758 5759 // C++ [expr.dynamic.cast]p7: 5760 // If T is "pointer to cv void", then the result is a pointer to the most 5761 // derived object 5762 if (E->getType()->isVoidPointerType()) 5763 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5764 5765 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5766 assert(C && "dynamic_cast target is not void pointer nor class"); 5767 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5768 5769 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5770 // C++ [expr.dynamic.cast]p9: 5771 if (!E->isGLValue()) { 5772 // The value of a failed cast to pointer type is the null pointer value 5773 // of the required result type. 5774 Ptr.setNull(Info.Ctx, E->getType()); 5775 return true; 5776 } 5777 5778 // A failed cast to reference type throws [...] std::bad_cast. 5779 unsigned DiagKind; 5780 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5781 DynType->Type->isDerivedFrom(C))) 5782 DiagKind = 0; 5783 else if (!Paths || Paths->begin() == Paths->end()) 5784 DiagKind = 1; 5785 else if (Paths->isAmbiguous(CQT)) 5786 DiagKind = 2; 5787 else { 5788 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5789 DiagKind = 3; 5790 } 5791 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5792 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5793 << Info.Ctx.getRecordType(DynType->Type) 5794 << E->getType().getUnqualifiedType(); 5795 return false; 5796 }; 5797 5798 // Runtime check, phase 1: 5799 // Walk from the base subobject towards the derived object looking for the 5800 // target type. 5801 for (int PathLength = Ptr.Designator.Entries.size(); 5802 PathLength >= (int)DynType->PathLength; --PathLength) { 5803 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5804 if (declaresSameEntity(Class, C)) 5805 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5806 // We can only walk across public inheritance edges. 5807 if (PathLength > (int)DynType->PathLength && 5808 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5809 Class)) 5810 return RuntimeCheckFailed(nullptr); 5811 } 5812 5813 // Runtime check, phase 2: 5814 // Search the dynamic type for an unambiguous public base of type C. 5815 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5816 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5817 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5818 Paths.front().Access == AS_public) { 5819 // Downcast to the dynamic type... 5820 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5821 return false; 5822 // ... then upcast to the chosen base class subobject. 5823 for (CXXBasePathElement &Elem : Paths.front()) 5824 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5825 return false; 5826 return true; 5827 } 5828 5829 // Otherwise, the runtime check fails. 5830 return RuntimeCheckFailed(&Paths); 5831 } 5832 5833 namespace { 5834 struct StartLifetimeOfUnionMemberHandler { 5835 EvalInfo &Info; 5836 const Expr *LHSExpr; 5837 const FieldDecl *Field; 5838 bool DuringInit; 5839 bool Failed = false; 5840 static const AccessKinds AccessKind = AK_Assign; 5841 5842 typedef bool result_type; 5843 bool failed() { return Failed; } 5844 bool found(APValue &Subobj, QualType SubobjType) { 5845 // We are supposed to perform no initialization but begin the lifetime of 5846 // the object. We interpret that as meaning to do what default 5847 // initialization of the object would do if all constructors involved were 5848 // trivial: 5849 // * All base, non-variant member, and array element subobjects' lifetimes 5850 // begin 5851 // * No variant members' lifetimes begin 5852 // * All scalar subobjects whose lifetimes begin have indeterminate values 5853 assert(SubobjType->isUnionType()); 5854 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5855 // This union member is already active. If it's also in-lifetime, there's 5856 // nothing to do. 5857 if (Subobj.getUnionValue().hasValue()) 5858 return true; 5859 } else if (DuringInit) { 5860 // We're currently in the process of initializing a different union 5861 // member. If we carried on, that initialization would attempt to 5862 // store to an inactive union member, resulting in undefined behavior. 5863 Info.FFDiag(LHSExpr, 5864 diag::note_constexpr_union_member_change_during_init); 5865 return false; 5866 } 5867 APValue Result; 5868 Failed = !getDefaultInitValue(Field->getType(), Result); 5869 Subobj.setUnion(Field, Result); 5870 return true; 5871 } 5872 bool found(APSInt &Value, QualType SubobjType) { 5873 llvm_unreachable("wrong value kind for union object"); 5874 } 5875 bool found(APFloat &Value, QualType SubobjType) { 5876 llvm_unreachable("wrong value kind for union object"); 5877 } 5878 }; 5879 } // end anonymous namespace 5880 5881 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5882 5883 /// Handle a builtin simple-assignment or a call to a trivial assignment 5884 /// operator whose left-hand side might involve a union member access. If it 5885 /// does, implicitly start the lifetime of any accessed union elements per 5886 /// C++20 [class.union]5. 5887 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5888 const LValue &LHS) { 5889 if (LHS.InvalidBase || LHS.Designator.Invalid) 5890 return false; 5891 5892 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5893 // C++ [class.union]p5: 5894 // define the set S(E) of subexpressions of E as follows: 5895 unsigned PathLength = LHS.Designator.Entries.size(); 5896 for (const Expr *E = LHSExpr; E != nullptr;) { 5897 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5898 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5899 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5900 // Note that we can't implicitly start the lifetime of a reference, 5901 // so we don't need to proceed any further if we reach one. 5902 if (!FD || FD->getType()->isReferenceType()) 5903 break; 5904 5905 // ... and also contains A.B if B names a union member ... 5906 if (FD->getParent()->isUnion()) { 5907 // ... of a non-class, non-array type, or of a class type with a 5908 // trivial default constructor that is not deleted, or an array of 5909 // such types. 5910 auto *RD = 5911 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5912 if (!RD || RD->hasTrivialDefaultConstructor()) 5913 UnionPathLengths.push_back({PathLength - 1, FD}); 5914 } 5915 5916 E = ME->getBase(); 5917 --PathLength; 5918 assert(declaresSameEntity(FD, 5919 LHS.Designator.Entries[PathLength] 5920 .getAsBaseOrMember().getPointer())); 5921 5922 // -- If E is of the form A[B] and is interpreted as a built-in array 5923 // subscripting operator, S(E) is [S(the array operand, if any)]. 5924 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5925 // Step over an ArrayToPointerDecay implicit cast. 5926 auto *Base = ASE->getBase()->IgnoreImplicit(); 5927 if (!Base->getType()->isArrayType()) 5928 break; 5929 5930 E = Base; 5931 --PathLength; 5932 5933 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5934 // Step over a derived-to-base conversion. 5935 E = ICE->getSubExpr(); 5936 if (ICE->getCastKind() == CK_NoOp) 5937 continue; 5938 if (ICE->getCastKind() != CK_DerivedToBase && 5939 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5940 break; 5941 // Walk path backwards as we walk up from the base to the derived class. 5942 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5943 --PathLength; 5944 (void)Elt; 5945 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5946 LHS.Designator.Entries[PathLength] 5947 .getAsBaseOrMember().getPointer())); 5948 } 5949 5950 // -- Otherwise, S(E) is empty. 5951 } else { 5952 break; 5953 } 5954 } 5955 5956 // Common case: no unions' lifetimes are started. 5957 if (UnionPathLengths.empty()) 5958 return true; 5959 5960 // if modification of X [would access an inactive union member], an object 5961 // of the type of X is implicitly created 5962 CompleteObject Obj = 5963 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5964 if (!Obj) 5965 return false; 5966 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5967 llvm::reverse(UnionPathLengths)) { 5968 // Form a designator for the union object. 5969 SubobjectDesignator D = LHS.Designator; 5970 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5971 5972 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5973 ConstructionPhase::AfterBases; 5974 StartLifetimeOfUnionMemberHandler StartLifetime{ 5975 Info, LHSExpr, LengthAndField.second, DuringInit}; 5976 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5977 return false; 5978 } 5979 5980 return true; 5981 } 5982 5983 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5984 CallRef Call, EvalInfo &Info, 5985 bool NonNull = false) { 5986 LValue LV; 5987 // Create the parameter slot and register its destruction. For a vararg 5988 // argument, create a temporary. 5989 // FIXME: For calling conventions that destroy parameters in the callee, 5990 // should we consider performing destruction when the function returns 5991 // instead? 5992 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 5993 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 5994 ScopeKind::Call, LV); 5995 if (!EvaluateInPlace(V, Info, LV, Arg)) 5996 return false; 5997 5998 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 5999 // undefined behavior, so is non-constant. 6000 if (NonNull && V.isLValue() && V.isNullPointer()) { 6001 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6002 return false; 6003 } 6004 6005 return true; 6006 } 6007 6008 /// Evaluate the arguments to a function call. 6009 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6010 EvalInfo &Info, const FunctionDecl *Callee, 6011 bool RightToLeft = false) { 6012 bool Success = true; 6013 llvm::SmallBitVector ForbiddenNullArgs; 6014 if (Callee->hasAttr<NonNullAttr>()) { 6015 ForbiddenNullArgs.resize(Args.size()); 6016 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6017 if (!Attr->args_size()) { 6018 ForbiddenNullArgs.set(); 6019 break; 6020 } else 6021 for (auto Idx : Attr->args()) { 6022 unsigned ASTIdx = Idx.getASTIndex(); 6023 if (ASTIdx >= Args.size()) 6024 continue; 6025 ForbiddenNullArgs[ASTIdx] = 1; 6026 } 6027 } 6028 } 6029 for (unsigned I = 0; I < Args.size(); I++) { 6030 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6031 const ParmVarDecl *PVD = 6032 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6033 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6034 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6035 // If we're checking for a potential constant expression, evaluate all 6036 // initializers even if some of them fail. 6037 if (!Info.noteFailure()) 6038 return false; 6039 Success = false; 6040 } 6041 } 6042 return Success; 6043 } 6044 6045 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6046 /// constructor or assignment operator. 6047 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6048 const Expr *E, APValue &Result, 6049 bool CopyObjectRepresentation) { 6050 // Find the reference argument. 6051 CallStackFrame *Frame = Info.CurrentCall; 6052 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6053 if (!RefValue) { 6054 Info.FFDiag(E); 6055 return false; 6056 } 6057 6058 // Copy out the contents of the RHS object. 6059 LValue RefLValue; 6060 RefLValue.setFrom(Info.Ctx, *RefValue); 6061 return handleLValueToRValueConversion( 6062 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6063 CopyObjectRepresentation); 6064 } 6065 6066 /// Evaluate a function call. 6067 static bool HandleFunctionCall(SourceLocation CallLoc, 6068 const FunctionDecl *Callee, const LValue *This, 6069 ArrayRef<const Expr *> Args, CallRef Call, 6070 const Stmt *Body, EvalInfo &Info, 6071 APValue &Result, const LValue *ResultSlot) { 6072 if (!Info.CheckCallLimit(CallLoc)) 6073 return false; 6074 6075 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6076 6077 // For a trivial copy or move assignment, perform an APValue copy. This is 6078 // essential for unions, where the operations performed by the assignment 6079 // operator cannot be represented as statements. 6080 // 6081 // Skip this for non-union classes with no fields; in that case, the defaulted 6082 // copy/move does not actually read the object. 6083 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6084 if (MD && MD->isDefaulted() && 6085 (MD->getParent()->isUnion() || 6086 (MD->isTrivial() && 6087 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6088 assert(This && 6089 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6090 APValue RHSValue; 6091 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6092 MD->getParent()->isUnion())) 6093 return false; 6094 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6095 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6096 return false; 6097 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6098 RHSValue)) 6099 return false; 6100 This->moveInto(Result); 6101 return true; 6102 } else if (MD && isLambdaCallOperator(MD)) { 6103 // We're in a lambda; determine the lambda capture field maps unless we're 6104 // just constexpr checking a lambda's call operator. constexpr checking is 6105 // done before the captures have been added to the closure object (unless 6106 // we're inferring constexpr-ness), so we don't have access to them in this 6107 // case. But since we don't need the captures to constexpr check, we can 6108 // just ignore them. 6109 if (!Info.checkingPotentialConstantExpression()) 6110 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6111 Frame.LambdaThisCaptureField); 6112 } 6113 6114 StmtResult Ret = {Result, ResultSlot}; 6115 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6116 if (ESR == ESR_Succeeded) { 6117 if (Callee->getReturnType()->isVoidType()) 6118 return true; 6119 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6120 } 6121 return ESR == ESR_Returned; 6122 } 6123 6124 /// Evaluate a constructor call. 6125 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6126 CallRef Call, 6127 const CXXConstructorDecl *Definition, 6128 EvalInfo &Info, APValue &Result) { 6129 SourceLocation CallLoc = E->getExprLoc(); 6130 if (!Info.CheckCallLimit(CallLoc)) 6131 return false; 6132 6133 const CXXRecordDecl *RD = Definition->getParent(); 6134 if (RD->getNumVBases()) { 6135 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6136 return false; 6137 } 6138 6139 EvalInfo::EvaluatingConstructorRAII EvalObj( 6140 Info, 6141 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6142 RD->getNumBases()); 6143 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6144 6145 // FIXME: Creating an APValue just to hold a nonexistent return value is 6146 // wasteful. 6147 APValue RetVal; 6148 StmtResult Ret = {RetVal, nullptr}; 6149 6150 // If it's a delegating constructor, delegate. 6151 if (Definition->isDelegatingConstructor()) { 6152 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6153 if ((*I)->getInit()->isValueDependent()) { 6154 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6155 return false; 6156 } else { 6157 FullExpressionRAII InitScope(Info); 6158 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6159 !InitScope.destroy()) 6160 return false; 6161 } 6162 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6163 } 6164 6165 // For a trivial copy or move constructor, perform an APValue copy. This is 6166 // essential for unions (or classes with anonymous union members), where the 6167 // operations performed by the constructor cannot be represented by 6168 // ctor-initializers. 6169 // 6170 // Skip this for empty non-union classes; we should not perform an 6171 // lvalue-to-rvalue conversion on them because their copy constructor does not 6172 // actually read them. 6173 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6174 (Definition->getParent()->isUnion() || 6175 (Definition->isTrivial() && 6176 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6177 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6178 Definition->getParent()->isUnion()); 6179 } 6180 6181 // Reserve space for the struct members. 6182 if (!Result.hasValue()) { 6183 if (!RD->isUnion()) 6184 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6185 std::distance(RD->field_begin(), RD->field_end())); 6186 else 6187 // A union starts with no active member. 6188 Result = APValue((const FieldDecl*)nullptr); 6189 } 6190 6191 if (RD->isInvalidDecl()) return false; 6192 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6193 6194 // A scope for temporaries lifetime-extended by reference members. 6195 BlockScopeRAII LifetimeExtendedScope(Info); 6196 6197 bool Success = true; 6198 unsigned BasesSeen = 0; 6199 #ifndef NDEBUG 6200 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6201 #endif 6202 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6203 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6204 // We might be initializing the same field again if this is an indirect 6205 // field initialization. 6206 if (FieldIt == RD->field_end() || 6207 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6208 assert(Indirect && "fields out of order?"); 6209 return; 6210 } 6211 6212 // Default-initialize any fields with no explicit initializer. 6213 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6214 assert(FieldIt != RD->field_end() && "missing field?"); 6215 if (!FieldIt->isUnnamedBitfield()) 6216 Success &= getDefaultInitValue( 6217 FieldIt->getType(), 6218 Result.getStructField(FieldIt->getFieldIndex())); 6219 } 6220 ++FieldIt; 6221 }; 6222 for (const auto *I : Definition->inits()) { 6223 LValue Subobject = This; 6224 LValue SubobjectParent = This; 6225 APValue *Value = &Result; 6226 6227 // Determine the subobject to initialize. 6228 FieldDecl *FD = nullptr; 6229 if (I->isBaseInitializer()) { 6230 QualType BaseType(I->getBaseClass(), 0); 6231 #ifndef NDEBUG 6232 // Non-virtual base classes are initialized in the order in the class 6233 // definition. We have already checked for virtual base classes. 6234 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6235 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6236 "base class initializers not in expected order"); 6237 ++BaseIt; 6238 #endif 6239 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6240 BaseType->getAsCXXRecordDecl(), &Layout)) 6241 return false; 6242 Value = &Result.getStructBase(BasesSeen++); 6243 } else if ((FD = I->getMember())) { 6244 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6245 return false; 6246 if (RD->isUnion()) { 6247 Result = APValue(FD); 6248 Value = &Result.getUnionValue(); 6249 } else { 6250 SkipToField(FD, false); 6251 Value = &Result.getStructField(FD->getFieldIndex()); 6252 } 6253 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6254 // Walk the indirect field decl's chain to find the object to initialize, 6255 // and make sure we've initialized every step along it. 6256 auto IndirectFieldChain = IFD->chain(); 6257 for (auto *C : IndirectFieldChain) { 6258 FD = cast<FieldDecl>(C); 6259 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6260 // Switch the union field if it differs. This happens if we had 6261 // preceding zero-initialization, and we're now initializing a union 6262 // subobject other than the first. 6263 // FIXME: In this case, the values of the other subobjects are 6264 // specified, since zero-initialization sets all padding bits to zero. 6265 if (!Value->hasValue() || 6266 (Value->isUnion() && Value->getUnionField() != FD)) { 6267 if (CD->isUnion()) 6268 *Value = APValue(FD); 6269 else 6270 // FIXME: This immediately starts the lifetime of all members of 6271 // an anonymous struct. It would be preferable to strictly start 6272 // member lifetime in initialization order. 6273 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6274 } 6275 // Store Subobject as its parent before updating it for the last element 6276 // in the chain. 6277 if (C == IndirectFieldChain.back()) 6278 SubobjectParent = Subobject; 6279 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6280 return false; 6281 if (CD->isUnion()) 6282 Value = &Value->getUnionValue(); 6283 else { 6284 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6285 SkipToField(FD, true); 6286 Value = &Value->getStructField(FD->getFieldIndex()); 6287 } 6288 } 6289 } else { 6290 llvm_unreachable("unknown base initializer kind"); 6291 } 6292 6293 // Need to override This for implicit field initializers as in this case 6294 // This refers to innermost anonymous struct/union containing initializer, 6295 // not to currently constructed class. 6296 const Expr *Init = I->getInit(); 6297 if (Init->isValueDependent()) { 6298 if (!EvaluateDependentExpr(Init, Info)) 6299 return false; 6300 } else { 6301 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6302 isa<CXXDefaultInitExpr>(Init)); 6303 FullExpressionRAII InitScope(Info); 6304 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6305 (FD && FD->isBitField() && 6306 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6307 // If we're checking for a potential constant expression, evaluate all 6308 // initializers even if some of them fail. 6309 if (!Info.noteFailure()) 6310 return false; 6311 Success = false; 6312 } 6313 } 6314 6315 // This is the point at which the dynamic type of the object becomes this 6316 // class type. 6317 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6318 EvalObj.finishedConstructingBases(); 6319 } 6320 6321 // Default-initialize any remaining fields. 6322 if (!RD->isUnion()) { 6323 for (; FieldIt != RD->field_end(); ++FieldIt) { 6324 if (!FieldIt->isUnnamedBitfield()) 6325 Success &= getDefaultInitValue( 6326 FieldIt->getType(), 6327 Result.getStructField(FieldIt->getFieldIndex())); 6328 } 6329 } 6330 6331 EvalObj.finishedConstructingFields(); 6332 6333 return Success && 6334 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6335 LifetimeExtendedScope.destroy(); 6336 } 6337 6338 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6339 ArrayRef<const Expr*> Args, 6340 const CXXConstructorDecl *Definition, 6341 EvalInfo &Info, APValue &Result) { 6342 CallScopeRAII CallScope(Info); 6343 CallRef Call = Info.CurrentCall->createCall(Definition); 6344 if (!EvaluateArgs(Args, Call, Info, Definition)) 6345 return false; 6346 6347 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6348 CallScope.destroy(); 6349 } 6350 6351 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6352 const LValue &This, APValue &Value, 6353 QualType T) { 6354 // Objects can only be destroyed while they're within their lifetimes. 6355 // FIXME: We have no representation for whether an object of type nullptr_t 6356 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6357 // as indeterminate instead? 6358 if (Value.isAbsent() && !T->isNullPtrType()) { 6359 APValue Printable; 6360 This.moveInto(Printable); 6361 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6362 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6363 return false; 6364 } 6365 6366 // Invent an expression for location purposes. 6367 // FIXME: We shouldn't need to do this. 6368 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6369 6370 // For arrays, destroy elements right-to-left. 6371 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6372 uint64_t Size = CAT->getSize().getZExtValue(); 6373 QualType ElemT = CAT->getElementType(); 6374 6375 LValue ElemLV = This; 6376 ElemLV.addArray(Info, &LocE, CAT); 6377 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6378 return false; 6379 6380 // Ensure that we have actual array elements available to destroy; the 6381 // destructors might mutate the value, so we can't run them on the array 6382 // filler. 6383 if (Size && Size > Value.getArrayInitializedElts()) 6384 expandArray(Value, Value.getArraySize() - 1); 6385 6386 for (; Size != 0; --Size) { 6387 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6388 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6389 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6390 return false; 6391 } 6392 6393 // End the lifetime of this array now. 6394 Value = APValue(); 6395 return true; 6396 } 6397 6398 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6399 if (!RD) { 6400 if (T.isDestructedType()) { 6401 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6402 return false; 6403 } 6404 6405 Value = APValue(); 6406 return true; 6407 } 6408 6409 if (RD->getNumVBases()) { 6410 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6411 return false; 6412 } 6413 6414 const CXXDestructorDecl *DD = RD->getDestructor(); 6415 if (!DD && !RD->hasTrivialDestructor()) { 6416 Info.FFDiag(CallLoc); 6417 return false; 6418 } 6419 6420 if (!DD || DD->isTrivial() || 6421 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6422 // A trivial destructor just ends the lifetime of the object. Check for 6423 // this case before checking for a body, because we might not bother 6424 // building a body for a trivial destructor. Note that it doesn't matter 6425 // whether the destructor is constexpr in this case; all trivial 6426 // destructors are constexpr. 6427 // 6428 // If an anonymous union would be destroyed, some enclosing destructor must 6429 // have been explicitly defined, and the anonymous union destruction should 6430 // have no effect. 6431 Value = APValue(); 6432 return true; 6433 } 6434 6435 if (!Info.CheckCallLimit(CallLoc)) 6436 return false; 6437 6438 const FunctionDecl *Definition = nullptr; 6439 const Stmt *Body = DD->getBody(Definition); 6440 6441 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6442 return false; 6443 6444 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6445 6446 // We're now in the period of destruction of this object. 6447 unsigned BasesLeft = RD->getNumBases(); 6448 EvalInfo::EvaluatingDestructorRAII EvalObj( 6449 Info, 6450 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6451 if (!EvalObj.DidInsert) { 6452 // C++2a [class.dtor]p19: 6453 // the behavior is undefined if the destructor is invoked for an object 6454 // whose lifetime has ended 6455 // (Note that formally the lifetime ends when the period of destruction 6456 // begins, even though certain uses of the object remain valid until the 6457 // period of destruction ends.) 6458 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6459 return false; 6460 } 6461 6462 // FIXME: Creating an APValue just to hold a nonexistent return value is 6463 // wasteful. 6464 APValue RetVal; 6465 StmtResult Ret = {RetVal, nullptr}; 6466 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6467 return false; 6468 6469 // A union destructor does not implicitly destroy its members. 6470 if (RD->isUnion()) 6471 return true; 6472 6473 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6474 6475 // We don't have a good way to iterate fields in reverse, so collect all the 6476 // fields first and then walk them backwards. 6477 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6478 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6479 if (FD->isUnnamedBitfield()) 6480 continue; 6481 6482 LValue Subobject = This; 6483 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6484 return false; 6485 6486 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6487 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6488 FD->getType())) 6489 return false; 6490 } 6491 6492 if (BasesLeft != 0) 6493 EvalObj.startedDestroyingBases(); 6494 6495 // Destroy base classes in reverse order. 6496 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6497 --BasesLeft; 6498 6499 QualType BaseType = Base.getType(); 6500 LValue Subobject = This; 6501 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6502 BaseType->getAsCXXRecordDecl(), &Layout)) 6503 return false; 6504 6505 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6506 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6507 BaseType)) 6508 return false; 6509 } 6510 assert(BasesLeft == 0 && "NumBases was wrong?"); 6511 6512 // The period of destruction ends now. The object is gone. 6513 Value = APValue(); 6514 return true; 6515 } 6516 6517 namespace { 6518 struct DestroyObjectHandler { 6519 EvalInfo &Info; 6520 const Expr *E; 6521 const LValue &This; 6522 const AccessKinds AccessKind; 6523 6524 typedef bool result_type; 6525 bool failed() { return false; } 6526 bool found(APValue &Subobj, QualType SubobjType) { 6527 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6528 SubobjType); 6529 } 6530 bool found(APSInt &Value, QualType SubobjType) { 6531 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6532 return false; 6533 } 6534 bool found(APFloat &Value, QualType SubobjType) { 6535 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6536 return false; 6537 } 6538 }; 6539 } 6540 6541 /// Perform a destructor or pseudo-destructor call on the given object, which 6542 /// might in general not be a complete object. 6543 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6544 const LValue &This, QualType ThisType) { 6545 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6546 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6547 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6548 } 6549 6550 /// Destroy and end the lifetime of the given complete object. 6551 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6552 APValue::LValueBase LVBase, APValue &Value, 6553 QualType T) { 6554 // If we've had an unmodeled side-effect, we can't rely on mutable state 6555 // (such as the object we're about to destroy) being correct. 6556 if (Info.EvalStatus.HasSideEffects) 6557 return false; 6558 6559 LValue LV; 6560 LV.set({LVBase}); 6561 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6562 } 6563 6564 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6565 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6566 LValue &Result) { 6567 if (Info.checkingPotentialConstantExpression() || 6568 Info.SpeculativeEvaluationDepth) 6569 return false; 6570 6571 // This is permitted only within a call to std::allocator<T>::allocate. 6572 auto Caller = Info.getStdAllocatorCaller("allocate"); 6573 if (!Caller) { 6574 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6575 ? diag::note_constexpr_new_untyped 6576 : diag::note_constexpr_new); 6577 return false; 6578 } 6579 6580 QualType ElemType = Caller.ElemType; 6581 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6582 Info.FFDiag(E->getExprLoc(), 6583 diag::note_constexpr_new_not_complete_object_type) 6584 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6585 return false; 6586 } 6587 6588 APSInt ByteSize; 6589 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6590 return false; 6591 bool IsNothrow = false; 6592 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6593 EvaluateIgnoredValue(Info, E->getArg(I)); 6594 IsNothrow |= E->getType()->isNothrowT(); 6595 } 6596 6597 CharUnits ElemSize; 6598 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6599 return false; 6600 APInt Size, Remainder; 6601 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6602 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6603 if (Remainder != 0) { 6604 // This likely indicates a bug in the implementation of 'std::allocator'. 6605 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6606 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6607 return false; 6608 } 6609 6610 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6611 if (IsNothrow) { 6612 Result.setNull(Info.Ctx, E->getType()); 6613 return true; 6614 } 6615 6616 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6617 return false; 6618 } 6619 6620 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6621 ArrayType::Normal, 0); 6622 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6623 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6624 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6625 return true; 6626 } 6627 6628 static bool hasVirtualDestructor(QualType T) { 6629 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6630 if (CXXDestructorDecl *DD = RD->getDestructor()) 6631 return DD->isVirtual(); 6632 return false; 6633 } 6634 6635 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6636 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6637 if (CXXDestructorDecl *DD = RD->getDestructor()) 6638 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6639 return nullptr; 6640 } 6641 6642 /// Check that the given object is a suitable pointer to a heap allocation that 6643 /// still exists and is of the right kind for the purpose of a deletion. 6644 /// 6645 /// On success, returns the heap allocation to deallocate. On failure, produces 6646 /// a diagnostic and returns None. 6647 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6648 const LValue &Pointer, 6649 DynAlloc::Kind DeallocKind) { 6650 auto PointerAsString = [&] { 6651 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6652 }; 6653 6654 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6655 if (!DA) { 6656 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6657 << PointerAsString(); 6658 if (Pointer.Base) 6659 NoteLValueLocation(Info, Pointer.Base); 6660 return None; 6661 } 6662 6663 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6664 if (!Alloc) { 6665 Info.FFDiag(E, diag::note_constexpr_double_delete); 6666 return None; 6667 } 6668 6669 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6670 if (DeallocKind != (*Alloc)->getKind()) { 6671 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6672 << DeallocKind << (*Alloc)->getKind() << AllocType; 6673 NoteLValueLocation(Info, Pointer.Base); 6674 return None; 6675 } 6676 6677 bool Subobject = false; 6678 if (DeallocKind == DynAlloc::New) { 6679 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6680 Pointer.Designator.isOnePastTheEnd(); 6681 } else { 6682 Subobject = Pointer.Designator.Entries.size() != 1 || 6683 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6684 } 6685 if (Subobject) { 6686 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6687 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6688 return None; 6689 } 6690 6691 return Alloc; 6692 } 6693 6694 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6695 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6696 if (Info.checkingPotentialConstantExpression() || 6697 Info.SpeculativeEvaluationDepth) 6698 return false; 6699 6700 // This is permitted only within a call to std::allocator<T>::deallocate. 6701 if (!Info.getStdAllocatorCaller("deallocate")) { 6702 Info.FFDiag(E->getExprLoc()); 6703 return true; 6704 } 6705 6706 LValue Pointer; 6707 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6708 return false; 6709 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6710 EvaluateIgnoredValue(Info, E->getArg(I)); 6711 6712 if (Pointer.Designator.Invalid) 6713 return false; 6714 6715 // Deleting a null pointer would have no effect, but it's not permitted by 6716 // std::allocator<T>::deallocate's contract. 6717 if (Pointer.isNullPointer()) { 6718 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6719 return true; 6720 } 6721 6722 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6723 return false; 6724 6725 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6726 return true; 6727 } 6728 6729 //===----------------------------------------------------------------------===// 6730 // Generic Evaluation 6731 //===----------------------------------------------------------------------===// 6732 namespace { 6733 6734 class BitCastBuffer { 6735 // FIXME: We're going to need bit-level granularity when we support 6736 // bit-fields. 6737 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6738 // we don't support a host or target where that is the case. Still, we should 6739 // use a more generic type in case we ever do. 6740 SmallVector<Optional<unsigned char>, 32> Bytes; 6741 6742 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6743 "Need at least 8 bit unsigned char"); 6744 6745 bool TargetIsLittleEndian; 6746 6747 public: 6748 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6749 : Bytes(Width.getQuantity()), 6750 TargetIsLittleEndian(TargetIsLittleEndian) {} 6751 6752 LLVM_NODISCARD 6753 bool readObject(CharUnits Offset, CharUnits Width, 6754 SmallVectorImpl<unsigned char> &Output) const { 6755 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6756 // If a byte of an integer is uninitialized, then the whole integer is 6757 // uninitalized. 6758 if (!Bytes[I.getQuantity()]) 6759 return false; 6760 Output.push_back(*Bytes[I.getQuantity()]); 6761 } 6762 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6763 std::reverse(Output.begin(), Output.end()); 6764 return true; 6765 } 6766 6767 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6768 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6769 std::reverse(Input.begin(), Input.end()); 6770 6771 size_t Index = 0; 6772 for (unsigned char Byte : Input) { 6773 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6774 Bytes[Offset.getQuantity() + Index] = Byte; 6775 ++Index; 6776 } 6777 } 6778 6779 size_t size() { return Bytes.size(); } 6780 }; 6781 6782 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6783 /// target would represent the value at runtime. 6784 class APValueToBufferConverter { 6785 EvalInfo &Info; 6786 BitCastBuffer Buffer; 6787 const CastExpr *BCE; 6788 6789 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6790 const CastExpr *BCE) 6791 : Info(Info), 6792 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6793 BCE(BCE) {} 6794 6795 bool visit(const APValue &Val, QualType Ty) { 6796 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6797 } 6798 6799 // Write out Val with type Ty into Buffer starting at Offset. 6800 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6801 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6802 6803 // As a special case, nullptr_t has an indeterminate value. 6804 if (Ty->isNullPtrType()) 6805 return true; 6806 6807 // Dig through Src to find the byte at SrcOffset. 6808 switch (Val.getKind()) { 6809 case APValue::Indeterminate: 6810 case APValue::None: 6811 return true; 6812 6813 case APValue::Int: 6814 return visitInt(Val.getInt(), Ty, Offset); 6815 case APValue::Float: 6816 return visitFloat(Val.getFloat(), Ty, Offset); 6817 case APValue::Array: 6818 return visitArray(Val, Ty, Offset); 6819 case APValue::Struct: 6820 return visitRecord(Val, Ty, Offset); 6821 6822 case APValue::ComplexInt: 6823 case APValue::ComplexFloat: 6824 case APValue::Vector: 6825 case APValue::FixedPoint: 6826 // FIXME: We should support these. 6827 6828 case APValue::Union: 6829 case APValue::MemberPointer: 6830 case APValue::AddrLabelDiff: { 6831 Info.FFDiag(BCE->getBeginLoc(), 6832 diag::note_constexpr_bit_cast_unsupported_type) 6833 << Ty; 6834 return false; 6835 } 6836 6837 case APValue::LValue: 6838 llvm_unreachable("LValue subobject in bit_cast?"); 6839 } 6840 llvm_unreachable("Unhandled APValue::ValueKind"); 6841 } 6842 6843 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6844 const RecordDecl *RD = Ty->getAsRecordDecl(); 6845 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6846 6847 // Visit the base classes. 6848 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6849 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6850 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6851 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6852 6853 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6854 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6855 return false; 6856 } 6857 } 6858 6859 // Visit the fields. 6860 unsigned FieldIdx = 0; 6861 for (FieldDecl *FD : RD->fields()) { 6862 if (FD->isBitField()) { 6863 Info.FFDiag(BCE->getBeginLoc(), 6864 diag::note_constexpr_bit_cast_unsupported_bitfield); 6865 return false; 6866 } 6867 6868 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6869 6870 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6871 "only bit-fields can have sub-char alignment"); 6872 CharUnits FieldOffset = 6873 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6874 QualType FieldTy = FD->getType(); 6875 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6876 return false; 6877 ++FieldIdx; 6878 } 6879 6880 return true; 6881 } 6882 6883 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6884 const auto *CAT = 6885 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6886 if (!CAT) 6887 return false; 6888 6889 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6890 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6891 unsigned ArraySize = Val.getArraySize(); 6892 // First, initialize the initialized elements. 6893 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6894 const APValue &SubObj = Val.getArrayInitializedElt(I); 6895 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6896 return false; 6897 } 6898 6899 // Next, initialize the rest of the array using the filler. 6900 if (Val.hasArrayFiller()) { 6901 const APValue &Filler = Val.getArrayFiller(); 6902 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6903 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6904 return false; 6905 } 6906 } 6907 6908 return true; 6909 } 6910 6911 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6912 APSInt AdjustedVal = Val; 6913 unsigned Width = AdjustedVal.getBitWidth(); 6914 if (Ty->isBooleanType()) { 6915 Width = Info.Ctx.getTypeSize(Ty); 6916 AdjustedVal = AdjustedVal.extend(Width); 6917 } 6918 6919 SmallVector<unsigned char, 8> Bytes(Width / 8); 6920 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6921 Buffer.writeObject(Offset, Bytes); 6922 return true; 6923 } 6924 6925 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6926 APSInt AsInt(Val.bitcastToAPInt()); 6927 return visitInt(AsInt, Ty, Offset); 6928 } 6929 6930 public: 6931 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6932 const CastExpr *BCE) { 6933 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6934 APValueToBufferConverter Converter(Info, DstSize, BCE); 6935 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6936 return None; 6937 return Converter.Buffer; 6938 } 6939 }; 6940 6941 /// Write an BitCastBuffer into an APValue. 6942 class BufferToAPValueConverter { 6943 EvalInfo &Info; 6944 const BitCastBuffer &Buffer; 6945 const CastExpr *BCE; 6946 6947 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6948 const CastExpr *BCE) 6949 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6950 6951 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6952 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6953 // Ideally this will be unreachable. 6954 llvm::NoneType unsupportedType(QualType Ty) { 6955 Info.FFDiag(BCE->getBeginLoc(), 6956 diag::note_constexpr_bit_cast_unsupported_type) 6957 << Ty; 6958 return None; 6959 } 6960 6961 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6962 Info.FFDiag(BCE->getBeginLoc(), 6963 diag::note_constexpr_bit_cast_unrepresentable_value) 6964 << Ty << Val.toString(/*Radix=*/10); 6965 return None; 6966 } 6967 6968 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6969 const EnumType *EnumSugar = nullptr) { 6970 if (T->isNullPtrType()) { 6971 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6972 return APValue((Expr *)nullptr, 6973 /*Offset=*/CharUnits::fromQuantity(NullValue), 6974 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6975 } 6976 6977 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6978 6979 // Work around floating point types that contain unused padding bytes. This 6980 // is really just `long double` on x86, which is the only fundamental type 6981 // with padding bytes. 6982 if (T->isRealFloatingType()) { 6983 const llvm::fltSemantics &Semantics = 6984 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6985 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6986 assert(NumBits % 8 == 0); 6987 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6988 if (NumBytes != SizeOf) 6989 SizeOf = NumBytes; 6990 } 6991 6992 SmallVector<uint8_t, 8> Bytes; 6993 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6994 // If this is std::byte or unsigned char, then its okay to store an 6995 // indeterminate value. 6996 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6997 bool IsUChar = 6998 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6999 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7000 if (!IsStdByte && !IsUChar) { 7001 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7002 Info.FFDiag(BCE->getExprLoc(), 7003 diag::note_constexpr_bit_cast_indet_dest) 7004 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7005 return None; 7006 } 7007 7008 return APValue::IndeterminateValue(); 7009 } 7010 7011 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7012 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7013 7014 if (T->isIntegralOrEnumerationType()) { 7015 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7016 7017 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7018 if (IntWidth != Val.getBitWidth()) { 7019 APSInt Truncated = Val.trunc(IntWidth); 7020 if (Truncated.extend(Val.getBitWidth()) != Val) 7021 return unrepresentableValue(QualType(T, 0), Val); 7022 Val = Truncated; 7023 } 7024 7025 return APValue(Val); 7026 } 7027 7028 if (T->isRealFloatingType()) { 7029 const llvm::fltSemantics &Semantics = 7030 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7031 return APValue(APFloat(Semantics, Val)); 7032 } 7033 7034 return unsupportedType(QualType(T, 0)); 7035 } 7036 7037 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7038 const RecordDecl *RD = RTy->getAsRecordDecl(); 7039 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7040 7041 unsigned NumBases = 0; 7042 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7043 NumBases = CXXRD->getNumBases(); 7044 7045 APValue ResultVal(APValue::UninitStruct(), NumBases, 7046 std::distance(RD->field_begin(), RD->field_end())); 7047 7048 // Visit the base classes. 7049 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7050 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7051 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7052 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7053 if (BaseDecl->isEmpty() || 7054 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7055 continue; 7056 7057 Optional<APValue> SubObj = visitType( 7058 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7059 if (!SubObj) 7060 return None; 7061 ResultVal.getStructBase(I) = *SubObj; 7062 } 7063 } 7064 7065 // Visit the fields. 7066 unsigned FieldIdx = 0; 7067 for (FieldDecl *FD : RD->fields()) { 7068 // FIXME: We don't currently support bit-fields. A lot of the logic for 7069 // this is in CodeGen, so we need to factor it around. 7070 if (FD->isBitField()) { 7071 Info.FFDiag(BCE->getBeginLoc(), 7072 diag::note_constexpr_bit_cast_unsupported_bitfield); 7073 return None; 7074 } 7075 7076 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7077 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7078 7079 CharUnits FieldOffset = 7080 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7081 Offset; 7082 QualType FieldTy = FD->getType(); 7083 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7084 if (!SubObj) 7085 return None; 7086 ResultVal.getStructField(FieldIdx) = *SubObj; 7087 ++FieldIdx; 7088 } 7089 7090 return ResultVal; 7091 } 7092 7093 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7094 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7095 assert(!RepresentationType.isNull() && 7096 "enum forward decl should be caught by Sema"); 7097 const auto *AsBuiltin = 7098 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7099 // Recurse into the underlying type. Treat std::byte transparently as 7100 // unsigned char. 7101 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7102 } 7103 7104 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7105 size_t Size = Ty->getSize().getLimitedValue(); 7106 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7107 7108 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7109 for (size_t I = 0; I != Size; ++I) { 7110 Optional<APValue> ElementValue = 7111 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7112 if (!ElementValue) 7113 return None; 7114 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7115 } 7116 7117 return ArrayValue; 7118 } 7119 7120 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7121 return unsupportedType(QualType(Ty, 0)); 7122 } 7123 7124 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7125 QualType Can = Ty.getCanonicalType(); 7126 7127 switch (Can->getTypeClass()) { 7128 #define TYPE(Class, Base) \ 7129 case Type::Class: \ 7130 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7131 #define ABSTRACT_TYPE(Class, Base) 7132 #define NON_CANONICAL_TYPE(Class, Base) \ 7133 case Type::Class: \ 7134 llvm_unreachable("non-canonical type should be impossible!"); 7135 #define DEPENDENT_TYPE(Class, Base) \ 7136 case Type::Class: \ 7137 llvm_unreachable( \ 7138 "dependent types aren't supported in the constant evaluator!"); 7139 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7140 case Type::Class: \ 7141 llvm_unreachable("either dependent or not canonical!"); 7142 #include "clang/AST/TypeNodes.inc" 7143 } 7144 llvm_unreachable("Unhandled Type::TypeClass"); 7145 } 7146 7147 public: 7148 // Pull out a full value of type DstType. 7149 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7150 const CastExpr *BCE) { 7151 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7152 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7153 } 7154 }; 7155 7156 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7157 QualType Ty, EvalInfo *Info, 7158 const ASTContext &Ctx, 7159 bool CheckingDest) { 7160 Ty = Ty.getCanonicalType(); 7161 7162 auto diag = [&](int Reason) { 7163 if (Info) 7164 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7165 << CheckingDest << (Reason == 4) << Reason; 7166 return false; 7167 }; 7168 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7169 if (Info) 7170 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7171 << NoteTy << Construct << Ty; 7172 return false; 7173 }; 7174 7175 if (Ty->isUnionType()) 7176 return diag(0); 7177 if (Ty->isPointerType()) 7178 return diag(1); 7179 if (Ty->isMemberPointerType()) 7180 return diag(2); 7181 if (Ty.isVolatileQualified()) 7182 return diag(3); 7183 7184 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7185 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7186 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7187 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7188 CheckingDest)) 7189 return note(1, BS.getType(), BS.getBeginLoc()); 7190 } 7191 for (FieldDecl *FD : Record->fields()) { 7192 if (FD->getType()->isReferenceType()) 7193 return diag(4); 7194 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7195 CheckingDest)) 7196 return note(0, FD->getType(), FD->getBeginLoc()); 7197 } 7198 } 7199 7200 if (Ty->isArrayType() && 7201 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7202 Info, Ctx, CheckingDest)) 7203 return false; 7204 7205 return true; 7206 } 7207 7208 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7209 const ASTContext &Ctx, 7210 const CastExpr *BCE) { 7211 bool DestOK = checkBitCastConstexprEligibilityType( 7212 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7213 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7214 BCE->getBeginLoc(), 7215 BCE->getSubExpr()->getType(), Info, Ctx, false); 7216 return SourceOK; 7217 } 7218 7219 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7220 APValue &SourceValue, 7221 const CastExpr *BCE) { 7222 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7223 "no host or target supports non 8-bit chars"); 7224 assert(SourceValue.isLValue() && 7225 "LValueToRValueBitcast requires an lvalue operand!"); 7226 7227 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7228 return false; 7229 7230 LValue SourceLValue; 7231 APValue SourceRValue; 7232 SourceLValue.setFrom(Info.Ctx, SourceValue); 7233 if (!handleLValueToRValueConversion( 7234 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7235 SourceRValue, /*WantObjectRepresentation=*/true)) 7236 return false; 7237 7238 // Read out SourceValue into a char buffer. 7239 Optional<BitCastBuffer> Buffer = 7240 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7241 if (!Buffer) 7242 return false; 7243 7244 // Write out the buffer into a new APValue. 7245 Optional<APValue> MaybeDestValue = 7246 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7247 if (!MaybeDestValue) 7248 return false; 7249 7250 DestValue = std::move(*MaybeDestValue); 7251 return true; 7252 } 7253 7254 template <class Derived> 7255 class ExprEvaluatorBase 7256 : public ConstStmtVisitor<Derived, bool> { 7257 private: 7258 Derived &getDerived() { return static_cast<Derived&>(*this); } 7259 bool DerivedSuccess(const APValue &V, const Expr *E) { 7260 return getDerived().Success(V, E); 7261 } 7262 bool DerivedZeroInitialization(const Expr *E) { 7263 return getDerived().ZeroInitialization(E); 7264 } 7265 7266 // Check whether a conditional operator with a non-constant condition is a 7267 // potential constant expression. If neither arm is a potential constant 7268 // expression, then the conditional operator is not either. 7269 template<typename ConditionalOperator> 7270 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7271 assert(Info.checkingPotentialConstantExpression()); 7272 7273 // Speculatively evaluate both arms. 7274 SmallVector<PartialDiagnosticAt, 8> Diag; 7275 { 7276 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7277 StmtVisitorTy::Visit(E->getFalseExpr()); 7278 if (Diag.empty()) 7279 return; 7280 } 7281 7282 { 7283 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7284 Diag.clear(); 7285 StmtVisitorTy::Visit(E->getTrueExpr()); 7286 if (Diag.empty()) 7287 return; 7288 } 7289 7290 Error(E, diag::note_constexpr_conditional_never_const); 7291 } 7292 7293 7294 template<typename ConditionalOperator> 7295 bool HandleConditionalOperator(const ConditionalOperator *E) { 7296 bool BoolResult; 7297 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7298 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7299 CheckPotentialConstantConditional(E); 7300 return false; 7301 } 7302 if (Info.noteFailure()) { 7303 StmtVisitorTy::Visit(E->getTrueExpr()); 7304 StmtVisitorTy::Visit(E->getFalseExpr()); 7305 } 7306 return false; 7307 } 7308 7309 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7310 return StmtVisitorTy::Visit(EvalExpr); 7311 } 7312 7313 protected: 7314 EvalInfo &Info; 7315 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7316 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7317 7318 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7319 return Info.CCEDiag(E, D); 7320 } 7321 7322 bool ZeroInitialization(const Expr *E) { return Error(E); } 7323 7324 public: 7325 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7326 7327 EvalInfo &getEvalInfo() { return Info; } 7328 7329 /// Report an evaluation error. This should only be called when an error is 7330 /// first discovered. When propagating an error, just return false. 7331 bool Error(const Expr *E, diag::kind D) { 7332 Info.FFDiag(E, D); 7333 return false; 7334 } 7335 bool Error(const Expr *E) { 7336 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7337 } 7338 7339 bool VisitStmt(const Stmt *) { 7340 llvm_unreachable("Expression evaluator should not be called on stmts"); 7341 } 7342 bool VisitExpr(const Expr *E) { 7343 return Error(E); 7344 } 7345 7346 bool VisitConstantExpr(const ConstantExpr *E) { 7347 if (E->hasAPValueResult()) 7348 return DerivedSuccess(E->getAPValueResult(), E); 7349 7350 return StmtVisitorTy::Visit(E->getSubExpr()); 7351 } 7352 7353 bool VisitParenExpr(const ParenExpr *E) 7354 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7355 bool VisitUnaryExtension(const UnaryOperator *E) 7356 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7357 bool VisitUnaryPlus(const UnaryOperator *E) 7358 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7359 bool VisitChooseExpr(const ChooseExpr *E) 7360 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7361 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7362 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7363 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7364 { return StmtVisitorTy::Visit(E->getReplacement()); } 7365 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7366 TempVersionRAII RAII(*Info.CurrentCall); 7367 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7368 return StmtVisitorTy::Visit(E->getExpr()); 7369 } 7370 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7371 TempVersionRAII RAII(*Info.CurrentCall); 7372 // The initializer may not have been parsed yet, or might be erroneous. 7373 if (!E->getExpr()) 7374 return Error(E); 7375 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7376 return StmtVisitorTy::Visit(E->getExpr()); 7377 } 7378 7379 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7380 FullExpressionRAII Scope(Info); 7381 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7382 } 7383 7384 // Temporaries are registered when created, so we don't care about 7385 // CXXBindTemporaryExpr. 7386 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7387 return StmtVisitorTy::Visit(E->getSubExpr()); 7388 } 7389 7390 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7391 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7392 return static_cast<Derived*>(this)->VisitCastExpr(E); 7393 } 7394 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7395 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7396 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7397 return static_cast<Derived*>(this)->VisitCastExpr(E); 7398 } 7399 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7400 return static_cast<Derived*>(this)->VisitCastExpr(E); 7401 } 7402 7403 bool VisitBinaryOperator(const BinaryOperator *E) { 7404 switch (E->getOpcode()) { 7405 default: 7406 return Error(E); 7407 7408 case BO_Comma: 7409 VisitIgnoredValue(E->getLHS()); 7410 return StmtVisitorTy::Visit(E->getRHS()); 7411 7412 case BO_PtrMemD: 7413 case BO_PtrMemI: { 7414 LValue Obj; 7415 if (!HandleMemberPointerAccess(Info, E, Obj)) 7416 return false; 7417 APValue Result; 7418 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7419 return false; 7420 return DerivedSuccess(Result, E); 7421 } 7422 } 7423 } 7424 7425 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7426 return StmtVisitorTy::Visit(E->getSemanticForm()); 7427 } 7428 7429 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7430 // Evaluate and cache the common expression. We treat it as a temporary, 7431 // even though it's not quite the same thing. 7432 LValue CommonLV; 7433 if (!Evaluate(Info.CurrentCall->createTemporary( 7434 E->getOpaqueValue(), 7435 getStorageType(Info.Ctx, E->getOpaqueValue()), 7436 ScopeKind::FullExpression, CommonLV), 7437 Info, E->getCommon())) 7438 return false; 7439 7440 return HandleConditionalOperator(E); 7441 } 7442 7443 bool VisitConditionalOperator(const ConditionalOperator *E) { 7444 bool IsBcpCall = false; 7445 // If the condition (ignoring parens) is a __builtin_constant_p call, 7446 // the result is a constant expression if it can be folded without 7447 // side-effects. This is an important GNU extension. See GCC PR38377 7448 // for discussion. 7449 if (const CallExpr *CallCE = 7450 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7451 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7452 IsBcpCall = true; 7453 7454 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7455 // constant expression; we can't check whether it's potentially foldable. 7456 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7457 // it would return 'false' in this mode. 7458 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7459 return false; 7460 7461 FoldConstant Fold(Info, IsBcpCall); 7462 if (!HandleConditionalOperator(E)) { 7463 Fold.keepDiagnostics(); 7464 return false; 7465 } 7466 7467 return true; 7468 } 7469 7470 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7471 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7472 return DerivedSuccess(*Value, E); 7473 7474 const Expr *Source = E->getSourceExpr(); 7475 if (!Source) 7476 return Error(E); 7477 if (Source == E) { // sanity checking. 7478 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7479 return Error(E); 7480 } 7481 return StmtVisitorTy::Visit(Source); 7482 } 7483 7484 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7485 for (const Expr *SemE : E->semantics()) { 7486 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7487 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7488 // result expression: there could be two different LValues that would 7489 // refer to the same object in that case, and we can't model that. 7490 if (SemE == E->getResultExpr()) 7491 return Error(E); 7492 7493 // Unique OVEs get evaluated if and when we encounter them when 7494 // emitting the rest of the semantic form, rather than eagerly. 7495 if (OVE->isUnique()) 7496 continue; 7497 7498 LValue LV; 7499 if (!Evaluate(Info.CurrentCall->createTemporary( 7500 OVE, getStorageType(Info.Ctx, OVE), 7501 ScopeKind::FullExpression, LV), 7502 Info, OVE->getSourceExpr())) 7503 return false; 7504 } else if (SemE == E->getResultExpr()) { 7505 if (!StmtVisitorTy::Visit(SemE)) 7506 return false; 7507 } else { 7508 if (!EvaluateIgnoredValue(Info, SemE)) 7509 return false; 7510 } 7511 } 7512 return true; 7513 } 7514 7515 bool VisitCallExpr(const CallExpr *E) { 7516 APValue Result; 7517 if (!handleCallExpr(E, Result, nullptr)) 7518 return false; 7519 return DerivedSuccess(Result, E); 7520 } 7521 7522 bool handleCallExpr(const CallExpr *E, APValue &Result, 7523 const LValue *ResultSlot) { 7524 CallScopeRAII CallScope(Info); 7525 7526 const Expr *Callee = E->getCallee()->IgnoreParens(); 7527 QualType CalleeType = Callee->getType(); 7528 7529 const FunctionDecl *FD = nullptr; 7530 LValue *This = nullptr, ThisVal; 7531 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7532 bool HasQualifier = false; 7533 7534 CallRef Call; 7535 7536 // Extract function decl and 'this' pointer from the callee. 7537 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7538 const CXXMethodDecl *Member = nullptr; 7539 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7540 // Explicit bound member calls, such as x.f() or p->g(); 7541 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7542 return false; 7543 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7544 if (!Member) 7545 return Error(Callee); 7546 This = &ThisVal; 7547 HasQualifier = ME->hasQualifier(); 7548 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7549 // Indirect bound member calls ('.*' or '->*'). 7550 const ValueDecl *D = 7551 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7552 if (!D) 7553 return false; 7554 Member = dyn_cast<CXXMethodDecl>(D); 7555 if (!Member) 7556 return Error(Callee); 7557 This = &ThisVal; 7558 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7559 if (!Info.getLangOpts().CPlusPlus20) 7560 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7561 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7562 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7563 } else 7564 return Error(Callee); 7565 FD = Member; 7566 } else if (CalleeType->isFunctionPointerType()) { 7567 LValue CalleeLV; 7568 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7569 return false; 7570 7571 if (!CalleeLV.getLValueOffset().isZero()) 7572 return Error(Callee); 7573 FD = dyn_cast_or_null<FunctionDecl>( 7574 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7575 if (!FD) 7576 return Error(Callee); 7577 // Don't call function pointers which have been cast to some other type. 7578 // Per DR (no number yet), the caller and callee can differ in noexcept. 7579 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7580 CalleeType->getPointeeType(), FD->getType())) { 7581 return Error(E); 7582 } 7583 7584 // For an (overloaded) assignment expression, evaluate the RHS before the 7585 // LHS. 7586 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7587 if (OCE && OCE->isAssignmentOp()) { 7588 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7589 Call = Info.CurrentCall->createCall(FD); 7590 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7591 Info, FD, /*RightToLeft=*/true)) 7592 return false; 7593 } 7594 7595 // Overloaded operator calls to member functions are represented as normal 7596 // calls with '*this' as the first argument. 7597 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7598 if (MD && !MD->isStatic()) { 7599 // FIXME: When selecting an implicit conversion for an overloaded 7600 // operator delete, we sometimes try to evaluate calls to conversion 7601 // operators without a 'this' parameter! 7602 if (Args.empty()) 7603 return Error(E); 7604 7605 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7606 return false; 7607 This = &ThisVal; 7608 Args = Args.slice(1); 7609 } else if (MD && MD->isLambdaStaticInvoker()) { 7610 // Map the static invoker for the lambda back to the call operator. 7611 // Conveniently, we don't have to slice out the 'this' argument (as is 7612 // being done for the non-static case), since a static member function 7613 // doesn't have an implicit argument passed in. 7614 const CXXRecordDecl *ClosureClass = MD->getParent(); 7615 assert( 7616 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7617 "Number of captures must be zero for conversion to function-ptr"); 7618 7619 const CXXMethodDecl *LambdaCallOp = 7620 ClosureClass->getLambdaCallOperator(); 7621 7622 // Set 'FD', the function that will be called below, to the call 7623 // operator. If the closure object represents a generic lambda, find 7624 // the corresponding specialization of the call operator. 7625 7626 if (ClosureClass->isGenericLambda()) { 7627 assert(MD->isFunctionTemplateSpecialization() && 7628 "A generic lambda's static-invoker function must be a " 7629 "template specialization"); 7630 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7631 FunctionTemplateDecl *CallOpTemplate = 7632 LambdaCallOp->getDescribedFunctionTemplate(); 7633 void *InsertPos = nullptr; 7634 FunctionDecl *CorrespondingCallOpSpecialization = 7635 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7636 assert(CorrespondingCallOpSpecialization && 7637 "We must always have a function call operator specialization " 7638 "that corresponds to our static invoker specialization"); 7639 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7640 } else 7641 FD = LambdaCallOp; 7642 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7643 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7644 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7645 LValue Ptr; 7646 if (!HandleOperatorNewCall(Info, E, Ptr)) 7647 return false; 7648 Ptr.moveInto(Result); 7649 return CallScope.destroy(); 7650 } else { 7651 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7652 } 7653 } 7654 } else 7655 return Error(E); 7656 7657 // Evaluate the arguments now if we've not already done so. 7658 if (!Call) { 7659 Call = Info.CurrentCall->createCall(FD); 7660 if (!EvaluateArgs(Args, Call, Info, FD)) 7661 return false; 7662 } 7663 7664 SmallVector<QualType, 4> CovariantAdjustmentPath; 7665 if (This) { 7666 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7667 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7668 // Perform virtual dispatch, if necessary. 7669 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7670 CovariantAdjustmentPath); 7671 if (!FD) 7672 return false; 7673 } else { 7674 // Check that the 'this' pointer points to an object of the right type. 7675 // FIXME: If this is an assignment operator call, we may need to change 7676 // the active union member before we check this. 7677 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7678 return false; 7679 } 7680 } 7681 7682 // Destructor calls are different enough that they have their own codepath. 7683 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7684 assert(This && "no 'this' pointer for destructor call"); 7685 return HandleDestruction(Info, E, *This, 7686 Info.Ctx.getRecordType(DD->getParent())) && 7687 CallScope.destroy(); 7688 } 7689 7690 const FunctionDecl *Definition = nullptr; 7691 Stmt *Body = FD->getBody(Definition); 7692 7693 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7694 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7695 Body, Info, Result, ResultSlot)) 7696 return false; 7697 7698 if (!CovariantAdjustmentPath.empty() && 7699 !HandleCovariantReturnAdjustment(Info, E, Result, 7700 CovariantAdjustmentPath)) 7701 return false; 7702 7703 return CallScope.destroy(); 7704 } 7705 7706 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7707 return StmtVisitorTy::Visit(E->getInitializer()); 7708 } 7709 bool VisitInitListExpr(const InitListExpr *E) { 7710 if (E->getNumInits() == 0) 7711 return DerivedZeroInitialization(E); 7712 if (E->getNumInits() == 1) 7713 return StmtVisitorTy::Visit(E->getInit(0)); 7714 return Error(E); 7715 } 7716 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7717 return DerivedZeroInitialization(E); 7718 } 7719 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7720 return DerivedZeroInitialization(E); 7721 } 7722 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7723 return DerivedZeroInitialization(E); 7724 } 7725 7726 /// A member expression where the object is a prvalue is itself a prvalue. 7727 bool VisitMemberExpr(const MemberExpr *E) { 7728 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7729 "missing temporary materialization conversion"); 7730 assert(!E->isArrow() && "missing call to bound member function?"); 7731 7732 APValue Val; 7733 if (!Evaluate(Val, Info, E->getBase())) 7734 return false; 7735 7736 QualType BaseTy = E->getBase()->getType(); 7737 7738 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7739 if (!FD) return Error(E); 7740 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7741 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7742 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7743 7744 // Note: there is no lvalue base here. But this case should only ever 7745 // happen in C or in C++98, where we cannot be evaluating a constexpr 7746 // constructor, which is the only case the base matters. 7747 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7748 SubobjectDesignator Designator(BaseTy); 7749 Designator.addDeclUnchecked(FD); 7750 7751 APValue Result; 7752 return extractSubobject(Info, E, Obj, Designator, Result) && 7753 DerivedSuccess(Result, E); 7754 } 7755 7756 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7757 APValue Val; 7758 if (!Evaluate(Val, Info, E->getBase())) 7759 return false; 7760 7761 if (Val.isVector()) { 7762 SmallVector<uint32_t, 4> Indices; 7763 E->getEncodedElementAccess(Indices); 7764 if (Indices.size() == 1) { 7765 // Return scalar. 7766 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7767 } else { 7768 // Construct new APValue vector. 7769 SmallVector<APValue, 4> Elts; 7770 for (unsigned I = 0; I < Indices.size(); ++I) { 7771 Elts.push_back(Val.getVectorElt(Indices[I])); 7772 } 7773 APValue VecResult(Elts.data(), Indices.size()); 7774 return DerivedSuccess(VecResult, E); 7775 } 7776 } 7777 7778 return false; 7779 } 7780 7781 bool VisitCastExpr(const CastExpr *E) { 7782 switch (E->getCastKind()) { 7783 default: 7784 break; 7785 7786 case CK_AtomicToNonAtomic: { 7787 APValue AtomicVal; 7788 // This does not need to be done in place even for class/array types: 7789 // atomic-to-non-atomic conversion implies copying the object 7790 // representation. 7791 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7792 return false; 7793 return DerivedSuccess(AtomicVal, E); 7794 } 7795 7796 case CK_NoOp: 7797 case CK_UserDefinedConversion: 7798 return StmtVisitorTy::Visit(E->getSubExpr()); 7799 7800 case CK_LValueToRValue: { 7801 LValue LVal; 7802 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7803 return false; 7804 APValue RVal; 7805 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7806 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7807 LVal, RVal)) 7808 return false; 7809 return DerivedSuccess(RVal, E); 7810 } 7811 case CK_LValueToRValueBitCast: { 7812 APValue DestValue, SourceValue; 7813 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7814 return false; 7815 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7816 return false; 7817 return DerivedSuccess(DestValue, E); 7818 } 7819 7820 case CK_AddressSpaceConversion: { 7821 APValue Value; 7822 if (!Evaluate(Value, Info, E->getSubExpr())) 7823 return false; 7824 return DerivedSuccess(Value, E); 7825 } 7826 } 7827 7828 return Error(E); 7829 } 7830 7831 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7832 return VisitUnaryPostIncDec(UO); 7833 } 7834 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7835 return VisitUnaryPostIncDec(UO); 7836 } 7837 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7838 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7839 return Error(UO); 7840 7841 LValue LVal; 7842 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7843 return false; 7844 APValue RVal; 7845 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7846 UO->isIncrementOp(), &RVal)) 7847 return false; 7848 return DerivedSuccess(RVal, UO); 7849 } 7850 7851 bool VisitStmtExpr(const StmtExpr *E) { 7852 // We will have checked the full-expressions inside the statement expression 7853 // when they were completed, and don't need to check them again now. 7854 llvm::SaveAndRestore<bool> NotCheckingForUB( 7855 Info.CheckingForUndefinedBehavior, false); 7856 7857 const CompoundStmt *CS = E->getSubStmt(); 7858 if (CS->body_empty()) 7859 return true; 7860 7861 BlockScopeRAII Scope(Info); 7862 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7863 BE = CS->body_end(); 7864 /**/; ++BI) { 7865 if (BI + 1 == BE) { 7866 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7867 if (!FinalExpr) { 7868 Info.FFDiag((*BI)->getBeginLoc(), 7869 diag::note_constexpr_stmt_expr_unsupported); 7870 return false; 7871 } 7872 return this->Visit(FinalExpr) && Scope.destroy(); 7873 } 7874 7875 APValue ReturnValue; 7876 StmtResult Result = { ReturnValue, nullptr }; 7877 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7878 if (ESR != ESR_Succeeded) { 7879 // FIXME: If the statement-expression terminated due to 'return', 7880 // 'break', or 'continue', it would be nice to propagate that to 7881 // the outer statement evaluation rather than bailing out. 7882 if (ESR != ESR_Failed) 7883 Info.FFDiag((*BI)->getBeginLoc(), 7884 diag::note_constexpr_stmt_expr_unsupported); 7885 return false; 7886 } 7887 } 7888 7889 llvm_unreachable("Return from function from the loop above."); 7890 } 7891 7892 /// Visit a value which is evaluated, but whose value is ignored. 7893 void VisitIgnoredValue(const Expr *E) { 7894 EvaluateIgnoredValue(Info, E); 7895 } 7896 7897 /// Potentially visit a MemberExpr's base expression. 7898 void VisitIgnoredBaseExpression(const Expr *E) { 7899 // While MSVC doesn't evaluate the base expression, it does diagnose the 7900 // presence of side-effecting behavior. 7901 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7902 return; 7903 VisitIgnoredValue(E); 7904 } 7905 }; 7906 7907 } // namespace 7908 7909 //===----------------------------------------------------------------------===// 7910 // Common base class for lvalue and temporary evaluation. 7911 //===----------------------------------------------------------------------===// 7912 namespace { 7913 template<class Derived> 7914 class LValueExprEvaluatorBase 7915 : public ExprEvaluatorBase<Derived> { 7916 protected: 7917 LValue &Result; 7918 bool InvalidBaseOK; 7919 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7920 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7921 7922 bool Success(APValue::LValueBase B) { 7923 Result.set(B); 7924 return true; 7925 } 7926 7927 bool evaluatePointer(const Expr *E, LValue &Result) { 7928 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7929 } 7930 7931 public: 7932 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7933 : ExprEvaluatorBaseTy(Info), Result(Result), 7934 InvalidBaseOK(InvalidBaseOK) {} 7935 7936 bool Success(const APValue &V, const Expr *E) { 7937 Result.setFrom(this->Info.Ctx, V); 7938 return true; 7939 } 7940 7941 bool VisitMemberExpr(const MemberExpr *E) { 7942 // Handle non-static data members. 7943 QualType BaseTy; 7944 bool EvalOK; 7945 if (E->isArrow()) { 7946 EvalOK = evaluatePointer(E->getBase(), Result); 7947 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7948 } else if (E->getBase()->isRValue()) { 7949 assert(E->getBase()->getType()->isRecordType()); 7950 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7951 BaseTy = E->getBase()->getType(); 7952 } else { 7953 EvalOK = this->Visit(E->getBase()); 7954 BaseTy = E->getBase()->getType(); 7955 } 7956 if (!EvalOK) { 7957 if (!InvalidBaseOK) 7958 return false; 7959 Result.setInvalid(E); 7960 return true; 7961 } 7962 7963 const ValueDecl *MD = E->getMemberDecl(); 7964 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7965 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7966 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7967 (void)BaseTy; 7968 if (!HandleLValueMember(this->Info, E, Result, FD)) 7969 return false; 7970 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7971 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7972 return false; 7973 } else 7974 return this->Error(E); 7975 7976 if (MD->getType()->isReferenceType()) { 7977 APValue RefValue; 7978 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7979 RefValue)) 7980 return false; 7981 return Success(RefValue, E); 7982 } 7983 return true; 7984 } 7985 7986 bool VisitBinaryOperator(const BinaryOperator *E) { 7987 switch (E->getOpcode()) { 7988 default: 7989 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7990 7991 case BO_PtrMemD: 7992 case BO_PtrMemI: 7993 return HandleMemberPointerAccess(this->Info, E, Result); 7994 } 7995 } 7996 7997 bool VisitCastExpr(const CastExpr *E) { 7998 switch (E->getCastKind()) { 7999 default: 8000 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8001 8002 case CK_DerivedToBase: 8003 case CK_UncheckedDerivedToBase: 8004 if (!this->Visit(E->getSubExpr())) 8005 return false; 8006 8007 // Now figure out the necessary offset to add to the base LV to get from 8008 // the derived class to the base class. 8009 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8010 Result); 8011 } 8012 } 8013 }; 8014 } 8015 8016 //===----------------------------------------------------------------------===// 8017 // LValue Evaluation 8018 // 8019 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8020 // function designators (in C), decl references to void objects (in C), and 8021 // temporaries (if building with -Wno-address-of-temporary). 8022 // 8023 // LValue evaluation produces values comprising a base expression of one of the 8024 // following types: 8025 // - Declarations 8026 // * VarDecl 8027 // * FunctionDecl 8028 // - Literals 8029 // * CompoundLiteralExpr in C (and in global scope in C++) 8030 // * StringLiteral 8031 // * PredefinedExpr 8032 // * ObjCStringLiteralExpr 8033 // * ObjCEncodeExpr 8034 // * AddrLabelExpr 8035 // * BlockExpr 8036 // * CallExpr for a MakeStringConstant builtin 8037 // - typeid(T) expressions, as TypeInfoLValues 8038 // - Locals and temporaries 8039 // * MaterializeTemporaryExpr 8040 // * Any Expr, with a CallIndex indicating the function in which the temporary 8041 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8042 // from the AST (FIXME). 8043 // * A MaterializeTemporaryExpr that has static storage duration, with no 8044 // CallIndex, for a lifetime-extended temporary. 8045 // * The ConstantExpr that is currently being evaluated during evaluation of an 8046 // immediate invocation. 8047 // plus an offset in bytes. 8048 //===----------------------------------------------------------------------===// 8049 namespace { 8050 class LValueExprEvaluator 8051 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8052 public: 8053 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8054 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8055 8056 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8057 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8058 8059 bool VisitDeclRefExpr(const DeclRefExpr *E); 8060 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8061 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8062 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8063 bool VisitMemberExpr(const MemberExpr *E); 8064 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8065 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8066 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8067 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8068 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8069 bool VisitUnaryDeref(const UnaryOperator *E); 8070 bool VisitUnaryReal(const UnaryOperator *E); 8071 bool VisitUnaryImag(const UnaryOperator *E); 8072 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8073 return VisitUnaryPreIncDec(UO); 8074 } 8075 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8076 return VisitUnaryPreIncDec(UO); 8077 } 8078 bool VisitBinAssign(const BinaryOperator *BO); 8079 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8080 8081 bool VisitCastExpr(const CastExpr *E) { 8082 switch (E->getCastKind()) { 8083 default: 8084 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8085 8086 case CK_LValueBitCast: 8087 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8088 if (!Visit(E->getSubExpr())) 8089 return false; 8090 Result.Designator.setInvalid(); 8091 return true; 8092 8093 case CK_BaseToDerived: 8094 if (!Visit(E->getSubExpr())) 8095 return false; 8096 return HandleBaseToDerivedCast(Info, E, Result); 8097 8098 case CK_Dynamic: 8099 if (!Visit(E->getSubExpr())) 8100 return false; 8101 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8102 } 8103 } 8104 }; 8105 } // end anonymous namespace 8106 8107 /// Evaluate an expression as an lvalue. This can be legitimately called on 8108 /// expressions which are not glvalues, in three cases: 8109 /// * function designators in C, and 8110 /// * "extern void" objects 8111 /// * @selector() expressions in Objective-C 8112 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8113 bool InvalidBaseOK) { 8114 assert(!E->isValueDependent()); 8115 assert(E->isGLValue() || E->getType()->isFunctionType() || 8116 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8117 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8118 } 8119 8120 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8121 const NamedDecl *D = E->getDecl(); 8122 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8123 return Success(cast<ValueDecl>(D)); 8124 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8125 return VisitVarDecl(E, VD); 8126 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8127 return Visit(BD->getBinding()); 8128 return Error(E); 8129 } 8130 8131 8132 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8133 8134 // If we are within a lambda's call operator, check whether the 'VD' referred 8135 // to within 'E' actually represents a lambda-capture that maps to a 8136 // data-member/field within the closure object, and if so, evaluate to the 8137 // field or what the field refers to. 8138 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8139 isa<DeclRefExpr>(E) && 8140 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8141 // We don't always have a complete capture-map when checking or inferring if 8142 // the function call operator meets the requirements of a constexpr function 8143 // - but we don't need to evaluate the captures to determine constexprness 8144 // (dcl.constexpr C++17). 8145 if (Info.checkingPotentialConstantExpression()) 8146 return false; 8147 8148 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8149 // Start with 'Result' referring to the complete closure object... 8150 Result = *Info.CurrentCall->This; 8151 // ... then update it to refer to the field of the closure object 8152 // that represents the capture. 8153 if (!HandleLValueMember(Info, E, Result, FD)) 8154 return false; 8155 // And if the field is of reference type, update 'Result' to refer to what 8156 // the field refers to. 8157 if (FD->getType()->isReferenceType()) { 8158 APValue RVal; 8159 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8160 RVal)) 8161 return false; 8162 Result.setFrom(Info.Ctx, RVal); 8163 } 8164 return true; 8165 } 8166 } 8167 8168 CallStackFrame *Frame = nullptr; 8169 unsigned Version = 0; 8170 if (VD->hasLocalStorage()) { 8171 // Only if a local variable was declared in the function currently being 8172 // evaluated, do we expect to be able to find its value in the current 8173 // frame. (Otherwise it was likely declared in an enclosing context and 8174 // could either have a valid evaluatable value (for e.g. a constexpr 8175 // variable) or be ill-formed (and trigger an appropriate evaluation 8176 // diagnostic)). 8177 CallStackFrame *CurrFrame = Info.CurrentCall; 8178 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8179 // Function parameters are stored in some caller's frame. (Usually the 8180 // immediate caller, but for an inherited constructor they may be more 8181 // distant.) 8182 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8183 if (CurrFrame->Arguments) { 8184 VD = CurrFrame->Arguments.getOrigParam(PVD); 8185 Frame = 8186 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8187 Version = CurrFrame->Arguments.Version; 8188 } 8189 } else { 8190 Frame = CurrFrame; 8191 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8192 } 8193 } 8194 } 8195 8196 if (!VD->getType()->isReferenceType()) { 8197 if (Frame) { 8198 Result.set({VD, Frame->Index, Version}); 8199 return true; 8200 } 8201 return Success(VD); 8202 } 8203 8204 if (!Info.getLangOpts().CPlusPlus11) { 8205 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8206 << VD << VD->getType(); 8207 Info.Note(VD->getLocation(), diag::note_declared_at); 8208 } 8209 8210 APValue *V; 8211 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8212 return false; 8213 if (!V->hasValue()) { 8214 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8215 // adjust the diagnostic to say that. 8216 if (!Info.checkingPotentialConstantExpression()) 8217 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8218 return false; 8219 } 8220 return Success(*V, E); 8221 } 8222 8223 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8224 const MaterializeTemporaryExpr *E) { 8225 // Walk through the expression to find the materialized temporary itself. 8226 SmallVector<const Expr *, 2> CommaLHSs; 8227 SmallVector<SubobjectAdjustment, 2> Adjustments; 8228 const Expr *Inner = 8229 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8230 8231 // If we passed any comma operators, evaluate their LHSs. 8232 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8233 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8234 return false; 8235 8236 // A materialized temporary with static storage duration can appear within the 8237 // result of a constant expression evaluation, so we need to preserve its 8238 // value for use outside this evaluation. 8239 APValue *Value; 8240 if (E->getStorageDuration() == SD_Static) { 8241 // FIXME: What about SD_Thread? 8242 Value = E->getOrCreateValue(true); 8243 *Value = APValue(); 8244 Result.set(E); 8245 } else { 8246 Value = &Info.CurrentCall->createTemporary( 8247 E, E->getType(), 8248 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8249 : ScopeKind::Block, 8250 Result); 8251 } 8252 8253 QualType Type = Inner->getType(); 8254 8255 // Materialize the temporary itself. 8256 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8257 *Value = APValue(); 8258 return false; 8259 } 8260 8261 // Adjust our lvalue to refer to the desired subobject. 8262 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8263 --I; 8264 switch (Adjustments[I].Kind) { 8265 case SubobjectAdjustment::DerivedToBaseAdjustment: 8266 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8267 Type, Result)) 8268 return false; 8269 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8270 break; 8271 8272 case SubobjectAdjustment::FieldAdjustment: 8273 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8274 return false; 8275 Type = Adjustments[I].Field->getType(); 8276 break; 8277 8278 case SubobjectAdjustment::MemberPointerAdjustment: 8279 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8280 Adjustments[I].Ptr.RHS)) 8281 return false; 8282 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8283 break; 8284 } 8285 } 8286 8287 return true; 8288 } 8289 8290 bool 8291 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8292 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8293 "lvalue compound literal in c++?"); 8294 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8295 // only see this when folding in C, so there's no standard to follow here. 8296 return Success(E); 8297 } 8298 8299 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8300 TypeInfoLValue TypeInfo; 8301 8302 if (!E->isPotentiallyEvaluated()) { 8303 if (E->isTypeOperand()) 8304 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8305 else 8306 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8307 } else { 8308 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8309 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8310 << E->getExprOperand()->getType() 8311 << E->getExprOperand()->getSourceRange(); 8312 } 8313 8314 if (!Visit(E->getExprOperand())) 8315 return false; 8316 8317 Optional<DynamicType> DynType = 8318 ComputeDynamicType(Info, E, Result, AK_TypeId); 8319 if (!DynType) 8320 return false; 8321 8322 TypeInfo = 8323 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8324 } 8325 8326 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8327 } 8328 8329 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8330 return Success(E->getGuidDecl()); 8331 } 8332 8333 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8334 // Handle static data members. 8335 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8336 VisitIgnoredBaseExpression(E->getBase()); 8337 return VisitVarDecl(E, VD); 8338 } 8339 8340 // Handle static member functions. 8341 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8342 if (MD->isStatic()) { 8343 VisitIgnoredBaseExpression(E->getBase()); 8344 return Success(MD); 8345 } 8346 } 8347 8348 // Handle non-static data members. 8349 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8350 } 8351 8352 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8353 // FIXME: Deal with vectors as array subscript bases. 8354 if (E->getBase()->getType()->isVectorType()) 8355 return Error(E); 8356 8357 APSInt Index; 8358 bool Success = true; 8359 8360 // C++17's rules require us to evaluate the LHS first, regardless of which 8361 // side is the base. 8362 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8363 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8364 : !EvaluateInteger(SubExpr, Index, Info)) { 8365 if (!Info.noteFailure()) 8366 return false; 8367 Success = false; 8368 } 8369 } 8370 8371 return Success && 8372 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8373 } 8374 8375 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8376 return evaluatePointer(E->getSubExpr(), Result); 8377 } 8378 8379 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8380 if (!Visit(E->getSubExpr())) 8381 return false; 8382 // __real is a no-op on scalar lvalues. 8383 if (E->getSubExpr()->getType()->isAnyComplexType()) 8384 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8385 return true; 8386 } 8387 8388 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8389 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8390 "lvalue __imag__ on scalar?"); 8391 if (!Visit(E->getSubExpr())) 8392 return false; 8393 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8394 return true; 8395 } 8396 8397 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8398 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8399 return Error(UO); 8400 8401 if (!this->Visit(UO->getSubExpr())) 8402 return false; 8403 8404 return handleIncDec( 8405 this->Info, UO, Result, UO->getSubExpr()->getType(), 8406 UO->isIncrementOp(), nullptr); 8407 } 8408 8409 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8410 const CompoundAssignOperator *CAO) { 8411 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8412 return Error(CAO); 8413 8414 bool Success = true; 8415 8416 // C++17 onwards require that we evaluate the RHS first. 8417 APValue RHS; 8418 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8419 if (!Info.noteFailure()) 8420 return false; 8421 Success = false; 8422 } 8423 8424 // The overall lvalue result is the result of evaluating the LHS. 8425 if (!this->Visit(CAO->getLHS()) || !Success) 8426 return false; 8427 8428 return handleCompoundAssignment( 8429 this->Info, CAO, 8430 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8431 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8432 } 8433 8434 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8435 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8436 return Error(E); 8437 8438 bool Success = true; 8439 8440 // C++17 onwards require that we evaluate the RHS first. 8441 APValue NewVal; 8442 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8443 if (!Info.noteFailure()) 8444 return false; 8445 Success = false; 8446 } 8447 8448 if (!this->Visit(E->getLHS()) || !Success) 8449 return false; 8450 8451 if (Info.getLangOpts().CPlusPlus20 && 8452 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8453 return false; 8454 8455 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8456 NewVal); 8457 } 8458 8459 //===----------------------------------------------------------------------===// 8460 // Pointer Evaluation 8461 //===----------------------------------------------------------------------===// 8462 8463 /// Attempts to compute the number of bytes available at the pointer 8464 /// returned by a function with the alloc_size attribute. Returns true if we 8465 /// were successful. Places an unsigned number into `Result`. 8466 /// 8467 /// This expects the given CallExpr to be a call to a function with an 8468 /// alloc_size attribute. 8469 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8470 const CallExpr *Call, 8471 llvm::APInt &Result) { 8472 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8473 8474 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8475 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8476 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8477 if (Call->getNumArgs() <= SizeArgNo) 8478 return false; 8479 8480 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8481 Expr::EvalResult ExprResult; 8482 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8483 return false; 8484 Into = ExprResult.Val.getInt(); 8485 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8486 return false; 8487 Into = Into.zextOrSelf(BitsInSizeT); 8488 return true; 8489 }; 8490 8491 APSInt SizeOfElem; 8492 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8493 return false; 8494 8495 if (!AllocSize->getNumElemsParam().isValid()) { 8496 Result = std::move(SizeOfElem); 8497 return true; 8498 } 8499 8500 APSInt NumberOfElems; 8501 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8502 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8503 return false; 8504 8505 bool Overflow; 8506 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8507 if (Overflow) 8508 return false; 8509 8510 Result = std::move(BytesAvailable); 8511 return true; 8512 } 8513 8514 /// Convenience function. LVal's base must be a call to an alloc_size 8515 /// function. 8516 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8517 const LValue &LVal, 8518 llvm::APInt &Result) { 8519 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8520 "Can't get the size of a non alloc_size function"); 8521 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8522 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8523 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8524 } 8525 8526 /// Attempts to evaluate the given LValueBase as the result of a call to 8527 /// a function with the alloc_size attribute. If it was possible to do so, this 8528 /// function will return true, make Result's Base point to said function call, 8529 /// and mark Result's Base as invalid. 8530 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8531 LValue &Result) { 8532 if (Base.isNull()) 8533 return false; 8534 8535 // Because we do no form of static analysis, we only support const variables. 8536 // 8537 // Additionally, we can't support parameters, nor can we support static 8538 // variables (in the latter case, use-before-assign isn't UB; in the former, 8539 // we have no clue what they'll be assigned to). 8540 const auto *VD = 8541 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8542 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8543 return false; 8544 8545 const Expr *Init = VD->getAnyInitializer(); 8546 if (!Init) 8547 return false; 8548 8549 const Expr *E = Init->IgnoreParens(); 8550 if (!tryUnwrapAllocSizeCall(E)) 8551 return false; 8552 8553 // Store E instead of E unwrapped so that the type of the LValue's base is 8554 // what the user wanted. 8555 Result.setInvalid(E); 8556 8557 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8558 Result.addUnsizedArray(Info, E, Pointee); 8559 return true; 8560 } 8561 8562 namespace { 8563 class PointerExprEvaluator 8564 : public ExprEvaluatorBase<PointerExprEvaluator> { 8565 LValue &Result; 8566 bool InvalidBaseOK; 8567 8568 bool Success(const Expr *E) { 8569 Result.set(E); 8570 return true; 8571 } 8572 8573 bool evaluateLValue(const Expr *E, LValue &Result) { 8574 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8575 } 8576 8577 bool evaluatePointer(const Expr *E, LValue &Result) { 8578 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8579 } 8580 8581 bool visitNonBuiltinCallExpr(const CallExpr *E); 8582 public: 8583 8584 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8585 : ExprEvaluatorBaseTy(info), Result(Result), 8586 InvalidBaseOK(InvalidBaseOK) {} 8587 8588 bool Success(const APValue &V, const Expr *E) { 8589 Result.setFrom(Info.Ctx, V); 8590 return true; 8591 } 8592 bool ZeroInitialization(const Expr *E) { 8593 Result.setNull(Info.Ctx, E->getType()); 8594 return true; 8595 } 8596 8597 bool VisitBinaryOperator(const BinaryOperator *E); 8598 bool VisitCastExpr(const CastExpr* E); 8599 bool VisitUnaryAddrOf(const UnaryOperator *E); 8600 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8601 { return Success(E); } 8602 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8603 if (E->isExpressibleAsConstantInitializer()) 8604 return Success(E); 8605 if (Info.noteFailure()) 8606 EvaluateIgnoredValue(Info, E->getSubExpr()); 8607 return Error(E); 8608 } 8609 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8610 { return Success(E); } 8611 bool VisitCallExpr(const CallExpr *E); 8612 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8613 bool VisitBlockExpr(const BlockExpr *E) { 8614 if (!E->getBlockDecl()->hasCaptures()) 8615 return Success(E); 8616 return Error(E); 8617 } 8618 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8619 // Can't look at 'this' when checking a potential constant expression. 8620 if (Info.checkingPotentialConstantExpression()) 8621 return false; 8622 if (!Info.CurrentCall->This) { 8623 if (Info.getLangOpts().CPlusPlus11) 8624 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8625 else 8626 Info.FFDiag(E); 8627 return false; 8628 } 8629 Result = *Info.CurrentCall->This; 8630 // If we are inside a lambda's call operator, the 'this' expression refers 8631 // to the enclosing '*this' object (either by value or reference) which is 8632 // either copied into the closure object's field that represents the '*this' 8633 // or refers to '*this'. 8634 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8635 // Ensure we actually have captured 'this'. (an error will have 8636 // been previously reported if not). 8637 if (!Info.CurrentCall->LambdaThisCaptureField) 8638 return false; 8639 8640 // Update 'Result' to refer to the data member/field of the closure object 8641 // that represents the '*this' capture. 8642 if (!HandleLValueMember(Info, E, Result, 8643 Info.CurrentCall->LambdaThisCaptureField)) 8644 return false; 8645 // If we captured '*this' by reference, replace the field with its referent. 8646 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8647 ->isPointerType()) { 8648 APValue RVal; 8649 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8650 RVal)) 8651 return false; 8652 8653 Result.setFrom(Info.Ctx, RVal); 8654 } 8655 } 8656 return true; 8657 } 8658 8659 bool VisitCXXNewExpr(const CXXNewExpr *E); 8660 8661 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8662 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8663 APValue LValResult = E->EvaluateInContext( 8664 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8665 Result.setFrom(Info.Ctx, LValResult); 8666 return true; 8667 } 8668 8669 // FIXME: Missing: @protocol, @selector 8670 }; 8671 } // end anonymous namespace 8672 8673 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8674 bool InvalidBaseOK) { 8675 assert(!E->isValueDependent()); 8676 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8677 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8678 } 8679 8680 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8681 if (E->getOpcode() != BO_Add && 8682 E->getOpcode() != BO_Sub) 8683 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8684 8685 const Expr *PExp = E->getLHS(); 8686 const Expr *IExp = E->getRHS(); 8687 if (IExp->getType()->isPointerType()) 8688 std::swap(PExp, IExp); 8689 8690 bool EvalPtrOK = evaluatePointer(PExp, Result); 8691 if (!EvalPtrOK && !Info.noteFailure()) 8692 return false; 8693 8694 llvm::APSInt Offset; 8695 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8696 return false; 8697 8698 if (E->getOpcode() == BO_Sub) 8699 negateAsSigned(Offset); 8700 8701 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8702 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8703 } 8704 8705 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8706 return evaluateLValue(E->getSubExpr(), Result); 8707 } 8708 8709 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8710 const Expr *SubExpr = E->getSubExpr(); 8711 8712 switch (E->getCastKind()) { 8713 default: 8714 break; 8715 case CK_BitCast: 8716 case CK_CPointerToObjCPointerCast: 8717 case CK_BlockPointerToObjCPointerCast: 8718 case CK_AnyPointerToBlockPointerCast: 8719 case CK_AddressSpaceConversion: 8720 if (!Visit(SubExpr)) 8721 return false; 8722 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8723 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8724 // also static_casts, but we disallow them as a resolution to DR1312. 8725 if (!E->getType()->isVoidPointerType()) { 8726 if (!Result.InvalidBase && !Result.Designator.Invalid && 8727 !Result.IsNullPtr && 8728 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8729 E->getType()->getPointeeType()) && 8730 Info.getStdAllocatorCaller("allocate")) { 8731 // Inside a call to std::allocator::allocate and friends, we permit 8732 // casting from void* back to cv1 T* for a pointer that points to a 8733 // cv2 T. 8734 } else { 8735 Result.Designator.setInvalid(); 8736 if (SubExpr->getType()->isVoidPointerType()) 8737 CCEDiag(E, diag::note_constexpr_invalid_cast) 8738 << 3 << SubExpr->getType(); 8739 else 8740 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8741 } 8742 } 8743 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8744 ZeroInitialization(E); 8745 return true; 8746 8747 case CK_DerivedToBase: 8748 case CK_UncheckedDerivedToBase: 8749 if (!evaluatePointer(E->getSubExpr(), Result)) 8750 return false; 8751 if (!Result.Base && Result.Offset.isZero()) 8752 return true; 8753 8754 // Now figure out the necessary offset to add to the base LV to get from 8755 // the derived class to the base class. 8756 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8757 castAs<PointerType>()->getPointeeType(), 8758 Result); 8759 8760 case CK_BaseToDerived: 8761 if (!Visit(E->getSubExpr())) 8762 return false; 8763 if (!Result.Base && Result.Offset.isZero()) 8764 return true; 8765 return HandleBaseToDerivedCast(Info, E, Result); 8766 8767 case CK_Dynamic: 8768 if (!Visit(E->getSubExpr())) 8769 return false; 8770 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8771 8772 case CK_NullToPointer: 8773 VisitIgnoredValue(E->getSubExpr()); 8774 return ZeroInitialization(E); 8775 8776 case CK_IntegralToPointer: { 8777 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8778 8779 APValue Value; 8780 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8781 break; 8782 8783 if (Value.isInt()) { 8784 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8785 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8786 Result.Base = (Expr*)nullptr; 8787 Result.InvalidBase = false; 8788 Result.Offset = CharUnits::fromQuantity(N); 8789 Result.Designator.setInvalid(); 8790 Result.IsNullPtr = false; 8791 return true; 8792 } else { 8793 // Cast is of an lvalue, no need to change value. 8794 Result.setFrom(Info.Ctx, Value); 8795 return true; 8796 } 8797 } 8798 8799 case CK_ArrayToPointerDecay: { 8800 if (SubExpr->isGLValue()) { 8801 if (!evaluateLValue(SubExpr, Result)) 8802 return false; 8803 } else { 8804 APValue &Value = Info.CurrentCall->createTemporary( 8805 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8806 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8807 return false; 8808 } 8809 // The result is a pointer to the first element of the array. 8810 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8811 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8812 Result.addArray(Info, E, CAT); 8813 else 8814 Result.addUnsizedArray(Info, E, AT->getElementType()); 8815 return true; 8816 } 8817 8818 case CK_FunctionToPointerDecay: 8819 return evaluateLValue(SubExpr, Result); 8820 8821 case CK_LValueToRValue: { 8822 LValue LVal; 8823 if (!evaluateLValue(E->getSubExpr(), LVal)) 8824 return false; 8825 8826 APValue RVal; 8827 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8828 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8829 LVal, RVal)) 8830 return InvalidBaseOK && 8831 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8832 return Success(RVal, E); 8833 } 8834 } 8835 8836 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8837 } 8838 8839 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8840 UnaryExprOrTypeTrait ExprKind) { 8841 // C++ [expr.alignof]p3: 8842 // When alignof is applied to a reference type, the result is the 8843 // alignment of the referenced type. 8844 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8845 T = Ref->getPointeeType(); 8846 8847 if (T.getQualifiers().hasUnaligned()) 8848 return CharUnits::One(); 8849 8850 const bool AlignOfReturnsPreferred = 8851 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8852 8853 // __alignof is defined to return the preferred alignment. 8854 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8855 // as well. 8856 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8857 return Info.Ctx.toCharUnitsFromBits( 8858 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8859 // alignof and _Alignof are defined to return the ABI alignment. 8860 else if (ExprKind == UETT_AlignOf) 8861 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8862 else 8863 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8864 } 8865 8866 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8867 UnaryExprOrTypeTrait ExprKind) { 8868 E = E->IgnoreParens(); 8869 8870 // The kinds of expressions that we have special-case logic here for 8871 // should be kept up to date with the special checks for those 8872 // expressions in Sema. 8873 8874 // alignof decl is always accepted, even if it doesn't make sense: we default 8875 // to 1 in those cases. 8876 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8877 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8878 /*RefAsPointee*/true); 8879 8880 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8881 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8882 /*RefAsPointee*/true); 8883 8884 return GetAlignOfType(Info, E->getType(), ExprKind); 8885 } 8886 8887 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8888 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8889 return Info.Ctx.getDeclAlign(VD); 8890 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8891 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8892 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8893 } 8894 8895 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8896 /// __builtin_is_aligned and __builtin_assume_aligned. 8897 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8898 EvalInfo &Info, APSInt &Alignment) { 8899 if (!EvaluateInteger(E, Alignment, Info)) 8900 return false; 8901 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8902 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8903 return false; 8904 } 8905 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8906 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8907 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8908 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8909 << MaxValue << ForType << Alignment; 8910 return false; 8911 } 8912 // Ensure both alignment and source value have the same bit width so that we 8913 // don't assert when computing the resulting value. 8914 APSInt ExtAlignment = 8915 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8916 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8917 "Alignment should not be changed by ext/trunc"); 8918 Alignment = ExtAlignment; 8919 assert(Alignment.getBitWidth() == SrcWidth); 8920 return true; 8921 } 8922 8923 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8924 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8925 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8926 return true; 8927 8928 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8929 return false; 8930 8931 Result.setInvalid(E); 8932 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8933 Result.addUnsizedArray(Info, E, PointeeTy); 8934 return true; 8935 } 8936 8937 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8938 if (IsStringLiteralCall(E)) 8939 return Success(E); 8940 8941 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8942 return VisitBuiltinCallExpr(E, BuiltinOp); 8943 8944 return visitNonBuiltinCallExpr(E); 8945 } 8946 8947 // Determine if T is a character type for which we guarantee that 8948 // sizeof(T) == 1. 8949 static bool isOneByteCharacterType(QualType T) { 8950 return T->isCharType() || T->isChar8Type(); 8951 } 8952 8953 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8954 unsigned BuiltinOp) { 8955 switch (BuiltinOp) { 8956 case Builtin::BI__builtin_addressof: 8957 return evaluateLValue(E->getArg(0), Result); 8958 case Builtin::BI__builtin_assume_aligned: { 8959 // We need to be very careful here because: if the pointer does not have the 8960 // asserted alignment, then the behavior is undefined, and undefined 8961 // behavior is non-constant. 8962 if (!evaluatePointer(E->getArg(0), Result)) 8963 return false; 8964 8965 LValue OffsetResult(Result); 8966 APSInt Alignment; 8967 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8968 Alignment)) 8969 return false; 8970 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8971 8972 if (E->getNumArgs() > 2) { 8973 APSInt Offset; 8974 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8975 return false; 8976 8977 int64_t AdditionalOffset = -Offset.getZExtValue(); 8978 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8979 } 8980 8981 // If there is a base object, then it must have the correct alignment. 8982 if (OffsetResult.Base) { 8983 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8984 8985 if (BaseAlignment < Align) { 8986 Result.Designator.setInvalid(); 8987 // FIXME: Add support to Diagnostic for long / long long. 8988 CCEDiag(E->getArg(0), 8989 diag::note_constexpr_baa_insufficient_alignment) << 0 8990 << (unsigned)BaseAlignment.getQuantity() 8991 << (unsigned)Align.getQuantity(); 8992 return false; 8993 } 8994 } 8995 8996 // The offset must also have the correct alignment. 8997 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8998 Result.Designator.setInvalid(); 8999 9000 (OffsetResult.Base 9001 ? CCEDiag(E->getArg(0), 9002 diag::note_constexpr_baa_insufficient_alignment) << 1 9003 : CCEDiag(E->getArg(0), 9004 diag::note_constexpr_baa_value_insufficient_alignment)) 9005 << (int)OffsetResult.Offset.getQuantity() 9006 << (unsigned)Align.getQuantity(); 9007 return false; 9008 } 9009 9010 return true; 9011 } 9012 case Builtin::BI__builtin_align_up: 9013 case Builtin::BI__builtin_align_down: { 9014 if (!evaluatePointer(E->getArg(0), Result)) 9015 return false; 9016 APSInt Alignment; 9017 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9018 Alignment)) 9019 return false; 9020 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9021 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9022 // For align_up/align_down, we can return the same value if the alignment 9023 // is known to be greater or equal to the requested value. 9024 if (PtrAlign.getQuantity() >= Alignment) 9025 return true; 9026 9027 // The alignment could be greater than the minimum at run-time, so we cannot 9028 // infer much about the resulting pointer value. One case is possible: 9029 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9030 // can infer the correct index if the requested alignment is smaller than 9031 // the base alignment so we can perform the computation on the offset. 9032 if (BaseAlignment.getQuantity() >= Alignment) { 9033 assert(Alignment.getBitWidth() <= 64 && 9034 "Cannot handle > 64-bit address-space"); 9035 uint64_t Alignment64 = Alignment.getZExtValue(); 9036 CharUnits NewOffset = CharUnits::fromQuantity( 9037 BuiltinOp == Builtin::BI__builtin_align_down 9038 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9039 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9040 Result.adjustOffset(NewOffset - Result.Offset); 9041 // TODO: diagnose out-of-bounds values/only allow for arrays? 9042 return true; 9043 } 9044 // Otherwise, we cannot constant-evaluate the result. 9045 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9046 << Alignment; 9047 return false; 9048 } 9049 case Builtin::BI__builtin_operator_new: 9050 return HandleOperatorNewCall(Info, E, Result); 9051 case Builtin::BI__builtin_launder: 9052 return evaluatePointer(E->getArg(0), Result); 9053 case Builtin::BIstrchr: 9054 case Builtin::BIwcschr: 9055 case Builtin::BImemchr: 9056 case Builtin::BIwmemchr: 9057 if (Info.getLangOpts().CPlusPlus11) 9058 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9059 << /*isConstexpr*/0 << /*isConstructor*/0 9060 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9061 else 9062 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9063 LLVM_FALLTHROUGH; 9064 case Builtin::BI__builtin_strchr: 9065 case Builtin::BI__builtin_wcschr: 9066 case Builtin::BI__builtin_memchr: 9067 case Builtin::BI__builtin_char_memchr: 9068 case Builtin::BI__builtin_wmemchr: { 9069 if (!Visit(E->getArg(0))) 9070 return false; 9071 APSInt Desired; 9072 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9073 return false; 9074 uint64_t MaxLength = uint64_t(-1); 9075 if (BuiltinOp != Builtin::BIstrchr && 9076 BuiltinOp != Builtin::BIwcschr && 9077 BuiltinOp != Builtin::BI__builtin_strchr && 9078 BuiltinOp != Builtin::BI__builtin_wcschr) { 9079 APSInt N; 9080 if (!EvaluateInteger(E->getArg(2), N, Info)) 9081 return false; 9082 MaxLength = N.getExtValue(); 9083 } 9084 // We cannot find the value if there are no candidates to match against. 9085 if (MaxLength == 0u) 9086 return ZeroInitialization(E); 9087 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9088 Result.Designator.Invalid) 9089 return false; 9090 QualType CharTy = Result.Designator.getType(Info.Ctx); 9091 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9092 BuiltinOp == Builtin::BI__builtin_memchr; 9093 assert(IsRawByte || 9094 Info.Ctx.hasSameUnqualifiedType( 9095 CharTy, E->getArg(0)->getType()->getPointeeType())); 9096 // Pointers to const void may point to objects of incomplete type. 9097 if (IsRawByte && CharTy->isIncompleteType()) { 9098 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9099 return false; 9100 } 9101 // Give up on byte-oriented matching against multibyte elements. 9102 // FIXME: We can compare the bytes in the correct order. 9103 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9104 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9105 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9106 << CharTy; 9107 return false; 9108 } 9109 // Figure out what value we're actually looking for (after converting to 9110 // the corresponding unsigned type if necessary). 9111 uint64_t DesiredVal; 9112 bool StopAtNull = false; 9113 switch (BuiltinOp) { 9114 case Builtin::BIstrchr: 9115 case Builtin::BI__builtin_strchr: 9116 // strchr compares directly to the passed integer, and therefore 9117 // always fails if given an int that is not a char. 9118 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9119 E->getArg(1)->getType(), 9120 Desired), 9121 Desired)) 9122 return ZeroInitialization(E); 9123 StopAtNull = true; 9124 LLVM_FALLTHROUGH; 9125 case Builtin::BImemchr: 9126 case Builtin::BI__builtin_memchr: 9127 case Builtin::BI__builtin_char_memchr: 9128 // memchr compares by converting both sides to unsigned char. That's also 9129 // correct for strchr if we get this far (to cope with plain char being 9130 // unsigned in the strchr case). 9131 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9132 break; 9133 9134 case Builtin::BIwcschr: 9135 case Builtin::BI__builtin_wcschr: 9136 StopAtNull = true; 9137 LLVM_FALLTHROUGH; 9138 case Builtin::BIwmemchr: 9139 case Builtin::BI__builtin_wmemchr: 9140 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9141 DesiredVal = Desired.getZExtValue(); 9142 break; 9143 } 9144 9145 for (; MaxLength; --MaxLength) { 9146 APValue Char; 9147 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9148 !Char.isInt()) 9149 return false; 9150 if (Char.getInt().getZExtValue() == DesiredVal) 9151 return true; 9152 if (StopAtNull && !Char.getInt()) 9153 break; 9154 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9155 return false; 9156 } 9157 // Not found: return nullptr. 9158 return ZeroInitialization(E); 9159 } 9160 9161 case Builtin::BImemcpy: 9162 case Builtin::BImemmove: 9163 case Builtin::BIwmemcpy: 9164 case Builtin::BIwmemmove: 9165 if (Info.getLangOpts().CPlusPlus11) 9166 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9167 << /*isConstexpr*/0 << /*isConstructor*/0 9168 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9169 else 9170 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9171 LLVM_FALLTHROUGH; 9172 case Builtin::BI__builtin_memcpy: 9173 case Builtin::BI__builtin_memmove: 9174 case Builtin::BI__builtin_wmemcpy: 9175 case Builtin::BI__builtin_wmemmove: { 9176 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9177 BuiltinOp == Builtin::BIwmemmove || 9178 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9179 BuiltinOp == Builtin::BI__builtin_wmemmove; 9180 bool Move = BuiltinOp == Builtin::BImemmove || 9181 BuiltinOp == Builtin::BIwmemmove || 9182 BuiltinOp == Builtin::BI__builtin_memmove || 9183 BuiltinOp == Builtin::BI__builtin_wmemmove; 9184 9185 // The result of mem* is the first argument. 9186 if (!Visit(E->getArg(0))) 9187 return false; 9188 LValue Dest = Result; 9189 9190 LValue Src; 9191 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9192 return false; 9193 9194 APSInt N; 9195 if (!EvaluateInteger(E->getArg(2), N, Info)) 9196 return false; 9197 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9198 9199 // If the size is zero, we treat this as always being a valid no-op. 9200 // (Even if one of the src and dest pointers is null.) 9201 if (!N) 9202 return true; 9203 9204 // Otherwise, if either of the operands is null, we can't proceed. Don't 9205 // try to determine the type of the copied objects, because there aren't 9206 // any. 9207 if (!Src.Base || !Dest.Base) { 9208 APValue Val; 9209 (!Src.Base ? Src : Dest).moveInto(Val); 9210 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9211 << Move << WChar << !!Src.Base 9212 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9213 return false; 9214 } 9215 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9216 return false; 9217 9218 // We require that Src and Dest are both pointers to arrays of 9219 // trivially-copyable type. (For the wide version, the designator will be 9220 // invalid if the designated object is not a wchar_t.) 9221 QualType T = Dest.Designator.getType(Info.Ctx); 9222 QualType SrcT = Src.Designator.getType(Info.Ctx); 9223 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9224 // FIXME: Consider using our bit_cast implementation to support this. 9225 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9226 return false; 9227 } 9228 if (T->isIncompleteType()) { 9229 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9230 return false; 9231 } 9232 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9233 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9234 return false; 9235 } 9236 9237 // Figure out how many T's we're copying. 9238 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9239 if (!WChar) { 9240 uint64_t Remainder; 9241 llvm::APInt OrigN = N; 9242 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9243 if (Remainder) { 9244 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9245 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 9246 << (unsigned)TSize; 9247 return false; 9248 } 9249 } 9250 9251 // Check that the copying will remain within the arrays, just so that we 9252 // can give a more meaningful diagnostic. This implicitly also checks that 9253 // N fits into 64 bits. 9254 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9255 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9256 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9257 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9258 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9259 << N.toString(10, /*Signed*/false); 9260 return false; 9261 } 9262 uint64_t NElems = N.getZExtValue(); 9263 uint64_t NBytes = NElems * TSize; 9264 9265 // Check for overlap. 9266 int Direction = 1; 9267 if (HasSameBase(Src, Dest)) { 9268 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9269 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9270 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9271 // Dest is inside the source region. 9272 if (!Move) { 9273 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9274 return false; 9275 } 9276 // For memmove and friends, copy backwards. 9277 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9278 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9279 return false; 9280 Direction = -1; 9281 } else if (!Move && SrcOffset >= DestOffset && 9282 SrcOffset - DestOffset < NBytes) { 9283 // Src is inside the destination region for memcpy: invalid. 9284 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9285 return false; 9286 } 9287 } 9288 9289 while (true) { 9290 APValue Val; 9291 // FIXME: Set WantObjectRepresentation to true if we're copying a 9292 // char-like type? 9293 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9294 !handleAssignment(Info, E, Dest, T, Val)) 9295 return false; 9296 // Do not iterate past the last element; if we're copying backwards, that 9297 // might take us off the start of the array. 9298 if (--NElems == 0) 9299 return true; 9300 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9301 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9302 return false; 9303 } 9304 } 9305 9306 default: 9307 break; 9308 } 9309 9310 return visitNonBuiltinCallExpr(E); 9311 } 9312 9313 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9314 APValue &Result, const InitListExpr *ILE, 9315 QualType AllocType); 9316 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9317 APValue &Result, 9318 const CXXConstructExpr *CCE, 9319 QualType AllocType); 9320 9321 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9322 if (!Info.getLangOpts().CPlusPlus20) 9323 Info.CCEDiag(E, diag::note_constexpr_new); 9324 9325 // We cannot speculatively evaluate a delete expression. 9326 if (Info.SpeculativeEvaluationDepth) 9327 return false; 9328 9329 FunctionDecl *OperatorNew = E->getOperatorNew(); 9330 9331 bool IsNothrow = false; 9332 bool IsPlacement = false; 9333 if (OperatorNew->isReservedGlobalPlacementOperator() && 9334 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9335 // FIXME Support array placement new. 9336 assert(E->getNumPlacementArgs() == 1); 9337 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9338 return false; 9339 if (Result.Designator.Invalid) 9340 return false; 9341 IsPlacement = true; 9342 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9343 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9344 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9345 return false; 9346 } else if (E->getNumPlacementArgs()) { 9347 // The only new-placement list we support is of the form (std::nothrow). 9348 // 9349 // FIXME: There is no restriction on this, but it's not clear that any 9350 // other form makes any sense. We get here for cases such as: 9351 // 9352 // new (std::align_val_t{N}) X(int) 9353 // 9354 // (which should presumably be valid only if N is a multiple of 9355 // alignof(int), and in any case can't be deallocated unless N is 9356 // alignof(X) and X has new-extended alignment). 9357 if (E->getNumPlacementArgs() != 1 || 9358 !E->getPlacementArg(0)->getType()->isNothrowT()) 9359 return Error(E, diag::note_constexpr_new_placement); 9360 9361 LValue Nothrow; 9362 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9363 return false; 9364 IsNothrow = true; 9365 } 9366 9367 const Expr *Init = E->getInitializer(); 9368 const InitListExpr *ResizedArrayILE = nullptr; 9369 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9370 bool ValueInit = false; 9371 9372 QualType AllocType = E->getAllocatedType(); 9373 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9374 const Expr *Stripped = *ArraySize; 9375 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9376 Stripped = ICE->getSubExpr()) 9377 if (ICE->getCastKind() != CK_NoOp && 9378 ICE->getCastKind() != CK_IntegralCast) 9379 break; 9380 9381 llvm::APSInt ArrayBound; 9382 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9383 return false; 9384 9385 // C++ [expr.new]p9: 9386 // The expression is erroneous if: 9387 // -- [...] its value before converting to size_t [or] applying the 9388 // second standard conversion sequence is less than zero 9389 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9390 if (IsNothrow) 9391 return ZeroInitialization(E); 9392 9393 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9394 << ArrayBound << (*ArraySize)->getSourceRange(); 9395 return false; 9396 } 9397 9398 // -- its value is such that the size of the allocated object would 9399 // exceed the implementation-defined limit 9400 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9401 ArrayBound) > 9402 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9403 if (IsNothrow) 9404 return ZeroInitialization(E); 9405 9406 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9407 << ArrayBound << (*ArraySize)->getSourceRange(); 9408 return false; 9409 } 9410 9411 // -- the new-initializer is a braced-init-list and the number of 9412 // array elements for which initializers are provided [...] 9413 // exceeds the number of elements to initialize 9414 if (!Init) { 9415 // No initialization is performed. 9416 } else if (isa<CXXScalarValueInitExpr>(Init) || 9417 isa<ImplicitValueInitExpr>(Init)) { 9418 ValueInit = true; 9419 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9420 ResizedArrayCCE = CCE; 9421 } else { 9422 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9423 assert(CAT && "unexpected type for array initializer"); 9424 9425 unsigned Bits = 9426 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9427 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9428 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9429 if (InitBound.ugt(AllocBound)) { 9430 if (IsNothrow) 9431 return ZeroInitialization(E); 9432 9433 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9434 << AllocBound.toString(10, /*Signed=*/false) 9435 << InitBound.toString(10, /*Signed=*/false) 9436 << (*ArraySize)->getSourceRange(); 9437 return false; 9438 } 9439 9440 // If the sizes differ, we must have an initializer list, and we need 9441 // special handling for this case when we initialize. 9442 if (InitBound != AllocBound) 9443 ResizedArrayILE = cast<InitListExpr>(Init); 9444 } 9445 9446 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9447 ArrayType::Normal, 0); 9448 } else { 9449 assert(!AllocType->isArrayType() && 9450 "array allocation with non-array new"); 9451 } 9452 9453 APValue *Val; 9454 if (IsPlacement) { 9455 AccessKinds AK = AK_Construct; 9456 struct FindObjectHandler { 9457 EvalInfo &Info; 9458 const Expr *E; 9459 QualType AllocType; 9460 const AccessKinds AccessKind; 9461 APValue *Value; 9462 9463 typedef bool result_type; 9464 bool failed() { return false; } 9465 bool found(APValue &Subobj, QualType SubobjType) { 9466 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9467 // old name of the object to be used to name the new object. 9468 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9469 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9470 SubobjType << AllocType; 9471 return false; 9472 } 9473 Value = &Subobj; 9474 return true; 9475 } 9476 bool found(APSInt &Value, QualType SubobjType) { 9477 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9478 return false; 9479 } 9480 bool found(APFloat &Value, QualType SubobjType) { 9481 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9482 return false; 9483 } 9484 } Handler = {Info, E, AllocType, AK, nullptr}; 9485 9486 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9487 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9488 return false; 9489 9490 Val = Handler.Value; 9491 9492 // [basic.life]p1: 9493 // The lifetime of an object o of type T ends when [...] the storage 9494 // which the object occupies is [...] reused by an object that is not 9495 // nested within o (6.6.2). 9496 *Val = APValue(); 9497 } else { 9498 // Perform the allocation and obtain a pointer to the resulting object. 9499 Val = Info.createHeapAlloc(E, AllocType, Result); 9500 if (!Val) 9501 return false; 9502 } 9503 9504 if (ValueInit) { 9505 ImplicitValueInitExpr VIE(AllocType); 9506 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9507 return false; 9508 } else if (ResizedArrayILE) { 9509 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9510 AllocType)) 9511 return false; 9512 } else if (ResizedArrayCCE) { 9513 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9514 AllocType)) 9515 return false; 9516 } else if (Init) { 9517 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9518 return false; 9519 } else if (!getDefaultInitValue(AllocType, *Val)) { 9520 return false; 9521 } 9522 9523 // Array new returns a pointer to the first element, not a pointer to the 9524 // array. 9525 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9526 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9527 9528 return true; 9529 } 9530 //===----------------------------------------------------------------------===// 9531 // Member Pointer Evaluation 9532 //===----------------------------------------------------------------------===// 9533 9534 namespace { 9535 class MemberPointerExprEvaluator 9536 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9537 MemberPtr &Result; 9538 9539 bool Success(const ValueDecl *D) { 9540 Result = MemberPtr(D); 9541 return true; 9542 } 9543 public: 9544 9545 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9546 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9547 9548 bool Success(const APValue &V, const Expr *E) { 9549 Result.setFrom(V); 9550 return true; 9551 } 9552 bool ZeroInitialization(const Expr *E) { 9553 return Success((const ValueDecl*)nullptr); 9554 } 9555 9556 bool VisitCastExpr(const CastExpr *E); 9557 bool VisitUnaryAddrOf(const UnaryOperator *E); 9558 }; 9559 } // end anonymous namespace 9560 9561 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9562 EvalInfo &Info) { 9563 assert(!E->isValueDependent()); 9564 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9565 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9566 } 9567 9568 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9569 switch (E->getCastKind()) { 9570 default: 9571 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9572 9573 case CK_NullToMemberPointer: 9574 VisitIgnoredValue(E->getSubExpr()); 9575 return ZeroInitialization(E); 9576 9577 case CK_BaseToDerivedMemberPointer: { 9578 if (!Visit(E->getSubExpr())) 9579 return false; 9580 if (E->path_empty()) 9581 return true; 9582 // Base-to-derived member pointer casts store the path in derived-to-base 9583 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9584 // the wrong end of the derived->base arc, so stagger the path by one class. 9585 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9586 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9587 PathI != PathE; ++PathI) { 9588 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9589 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9590 if (!Result.castToDerived(Derived)) 9591 return Error(E); 9592 } 9593 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9594 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9595 return Error(E); 9596 return true; 9597 } 9598 9599 case CK_DerivedToBaseMemberPointer: 9600 if (!Visit(E->getSubExpr())) 9601 return false; 9602 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9603 PathE = E->path_end(); PathI != PathE; ++PathI) { 9604 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9605 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9606 if (!Result.castToBase(Base)) 9607 return Error(E); 9608 } 9609 return true; 9610 } 9611 } 9612 9613 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9614 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9615 // member can be formed. 9616 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9617 } 9618 9619 //===----------------------------------------------------------------------===// 9620 // Record Evaluation 9621 //===----------------------------------------------------------------------===// 9622 9623 namespace { 9624 class RecordExprEvaluator 9625 : public ExprEvaluatorBase<RecordExprEvaluator> { 9626 const LValue &This; 9627 APValue &Result; 9628 public: 9629 9630 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9631 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9632 9633 bool Success(const APValue &V, const Expr *E) { 9634 Result = V; 9635 return true; 9636 } 9637 bool ZeroInitialization(const Expr *E) { 9638 return ZeroInitialization(E, E->getType()); 9639 } 9640 bool ZeroInitialization(const Expr *E, QualType T); 9641 9642 bool VisitCallExpr(const CallExpr *E) { 9643 return handleCallExpr(E, Result, &This); 9644 } 9645 bool VisitCastExpr(const CastExpr *E); 9646 bool VisitInitListExpr(const InitListExpr *E); 9647 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9648 return VisitCXXConstructExpr(E, E->getType()); 9649 } 9650 bool VisitLambdaExpr(const LambdaExpr *E); 9651 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9652 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9653 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9654 bool VisitBinCmp(const BinaryOperator *E); 9655 }; 9656 } 9657 9658 /// Perform zero-initialization on an object of non-union class type. 9659 /// C++11 [dcl.init]p5: 9660 /// To zero-initialize an object or reference of type T means: 9661 /// [...] 9662 /// -- if T is a (possibly cv-qualified) non-union class type, 9663 /// each non-static data member and each base-class subobject is 9664 /// zero-initialized 9665 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9666 const RecordDecl *RD, 9667 const LValue &This, APValue &Result) { 9668 assert(!RD->isUnion() && "Expected non-union class type"); 9669 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9670 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9671 std::distance(RD->field_begin(), RD->field_end())); 9672 9673 if (RD->isInvalidDecl()) return false; 9674 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9675 9676 if (CD) { 9677 unsigned Index = 0; 9678 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9679 End = CD->bases_end(); I != End; ++I, ++Index) { 9680 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9681 LValue Subobject = This; 9682 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9683 return false; 9684 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9685 Result.getStructBase(Index))) 9686 return false; 9687 } 9688 } 9689 9690 for (const auto *I : RD->fields()) { 9691 // -- if T is a reference type, no initialization is performed. 9692 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9693 continue; 9694 9695 LValue Subobject = This; 9696 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9697 return false; 9698 9699 ImplicitValueInitExpr VIE(I->getType()); 9700 if (!EvaluateInPlace( 9701 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9702 return false; 9703 } 9704 9705 return true; 9706 } 9707 9708 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9709 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9710 if (RD->isInvalidDecl()) return false; 9711 if (RD->isUnion()) { 9712 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9713 // object's first non-static named data member is zero-initialized 9714 RecordDecl::field_iterator I = RD->field_begin(); 9715 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9716 ++I; 9717 if (I == RD->field_end()) { 9718 Result = APValue((const FieldDecl*)nullptr); 9719 return true; 9720 } 9721 9722 LValue Subobject = This; 9723 if (!HandleLValueMember(Info, E, Subobject, *I)) 9724 return false; 9725 Result = APValue(*I); 9726 ImplicitValueInitExpr VIE(I->getType()); 9727 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9728 } 9729 9730 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9731 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9732 return false; 9733 } 9734 9735 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9736 } 9737 9738 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9739 switch (E->getCastKind()) { 9740 default: 9741 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9742 9743 case CK_ConstructorConversion: 9744 return Visit(E->getSubExpr()); 9745 9746 case CK_DerivedToBase: 9747 case CK_UncheckedDerivedToBase: { 9748 APValue DerivedObject; 9749 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9750 return false; 9751 if (!DerivedObject.isStruct()) 9752 return Error(E->getSubExpr()); 9753 9754 // Derived-to-base rvalue conversion: just slice off the derived part. 9755 APValue *Value = &DerivedObject; 9756 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9757 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9758 PathE = E->path_end(); PathI != PathE; ++PathI) { 9759 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9760 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9761 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9762 RD = Base; 9763 } 9764 Result = *Value; 9765 return true; 9766 } 9767 } 9768 } 9769 9770 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9771 if (E->isTransparent()) 9772 return Visit(E->getInit(0)); 9773 9774 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9775 if (RD->isInvalidDecl()) return false; 9776 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9777 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9778 9779 EvalInfo::EvaluatingConstructorRAII EvalObj( 9780 Info, 9781 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9782 CXXRD && CXXRD->getNumBases()); 9783 9784 if (RD->isUnion()) { 9785 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9786 Result = APValue(Field); 9787 if (!Field) 9788 return true; 9789 9790 // If the initializer list for a union does not contain any elements, the 9791 // first element of the union is value-initialized. 9792 // FIXME: The element should be initialized from an initializer list. 9793 // Is this difference ever observable for initializer lists which 9794 // we don't build? 9795 ImplicitValueInitExpr VIE(Field->getType()); 9796 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9797 9798 LValue Subobject = This; 9799 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9800 return false; 9801 9802 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9803 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9804 isa<CXXDefaultInitExpr>(InitExpr)); 9805 9806 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9807 if (Field->isBitField()) 9808 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9809 Field); 9810 return true; 9811 } 9812 9813 return false; 9814 } 9815 9816 if (!Result.hasValue()) 9817 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9818 std::distance(RD->field_begin(), RD->field_end())); 9819 unsigned ElementNo = 0; 9820 bool Success = true; 9821 9822 // Initialize base classes. 9823 if (CXXRD && CXXRD->getNumBases()) { 9824 for (const auto &Base : CXXRD->bases()) { 9825 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9826 const Expr *Init = E->getInit(ElementNo); 9827 9828 LValue Subobject = This; 9829 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9830 return false; 9831 9832 APValue &FieldVal = Result.getStructBase(ElementNo); 9833 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9834 if (!Info.noteFailure()) 9835 return false; 9836 Success = false; 9837 } 9838 ++ElementNo; 9839 } 9840 9841 EvalObj.finishedConstructingBases(); 9842 } 9843 9844 // Initialize members. 9845 for (const auto *Field : RD->fields()) { 9846 // Anonymous bit-fields are not considered members of the class for 9847 // purposes of aggregate initialization. 9848 if (Field->isUnnamedBitfield()) 9849 continue; 9850 9851 LValue Subobject = This; 9852 9853 bool HaveInit = ElementNo < E->getNumInits(); 9854 9855 // FIXME: Diagnostics here should point to the end of the initializer 9856 // list, not the start. 9857 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9858 Subobject, Field, &Layout)) 9859 return false; 9860 9861 // Perform an implicit value-initialization for members beyond the end of 9862 // the initializer list. 9863 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9864 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9865 9866 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9867 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9868 isa<CXXDefaultInitExpr>(Init)); 9869 9870 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9871 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9872 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9873 FieldVal, Field))) { 9874 if (!Info.noteFailure()) 9875 return false; 9876 Success = false; 9877 } 9878 } 9879 9880 EvalObj.finishedConstructingFields(); 9881 9882 return Success; 9883 } 9884 9885 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9886 QualType T) { 9887 // Note that E's type is not necessarily the type of our class here; we might 9888 // be initializing an array element instead. 9889 const CXXConstructorDecl *FD = E->getConstructor(); 9890 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9891 9892 bool ZeroInit = E->requiresZeroInitialization(); 9893 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9894 // If we've already performed zero-initialization, we're already done. 9895 if (Result.hasValue()) 9896 return true; 9897 9898 if (ZeroInit) 9899 return ZeroInitialization(E, T); 9900 9901 return getDefaultInitValue(T, Result); 9902 } 9903 9904 const FunctionDecl *Definition = nullptr; 9905 auto Body = FD->getBody(Definition); 9906 9907 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9908 return false; 9909 9910 // Avoid materializing a temporary for an elidable copy/move constructor. 9911 if (E->isElidable() && !ZeroInit) 9912 if (const MaterializeTemporaryExpr *ME 9913 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9914 return Visit(ME->getSubExpr()); 9915 9916 if (ZeroInit && !ZeroInitialization(E, T)) 9917 return false; 9918 9919 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9920 return HandleConstructorCall(E, This, Args, 9921 cast<CXXConstructorDecl>(Definition), Info, 9922 Result); 9923 } 9924 9925 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9926 const CXXInheritedCtorInitExpr *E) { 9927 if (!Info.CurrentCall) { 9928 assert(Info.checkingPotentialConstantExpression()); 9929 return false; 9930 } 9931 9932 const CXXConstructorDecl *FD = E->getConstructor(); 9933 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9934 return false; 9935 9936 const FunctionDecl *Definition = nullptr; 9937 auto Body = FD->getBody(Definition); 9938 9939 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9940 return false; 9941 9942 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9943 cast<CXXConstructorDecl>(Definition), Info, 9944 Result); 9945 } 9946 9947 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9948 const CXXStdInitializerListExpr *E) { 9949 const ConstantArrayType *ArrayType = 9950 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9951 9952 LValue Array; 9953 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9954 return false; 9955 9956 // Get a pointer to the first element of the array. 9957 Array.addArray(Info, E, ArrayType); 9958 9959 auto InvalidType = [&] { 9960 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9961 << E->getType(); 9962 return false; 9963 }; 9964 9965 // FIXME: Perform the checks on the field types in SemaInit. 9966 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9967 RecordDecl::field_iterator Field = Record->field_begin(); 9968 if (Field == Record->field_end()) 9969 return InvalidType(); 9970 9971 // Start pointer. 9972 if (!Field->getType()->isPointerType() || 9973 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9974 ArrayType->getElementType())) 9975 return InvalidType(); 9976 9977 // FIXME: What if the initializer_list type has base classes, etc? 9978 Result = APValue(APValue::UninitStruct(), 0, 2); 9979 Array.moveInto(Result.getStructField(0)); 9980 9981 if (++Field == Record->field_end()) 9982 return InvalidType(); 9983 9984 if (Field->getType()->isPointerType() && 9985 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9986 ArrayType->getElementType())) { 9987 // End pointer. 9988 if (!HandleLValueArrayAdjustment(Info, E, Array, 9989 ArrayType->getElementType(), 9990 ArrayType->getSize().getZExtValue())) 9991 return false; 9992 Array.moveInto(Result.getStructField(1)); 9993 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9994 // Length. 9995 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9996 else 9997 return InvalidType(); 9998 9999 if (++Field != Record->field_end()) 10000 return InvalidType(); 10001 10002 return true; 10003 } 10004 10005 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10006 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10007 if (ClosureClass->isInvalidDecl()) 10008 return false; 10009 10010 const size_t NumFields = 10011 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10012 10013 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10014 E->capture_init_end()) && 10015 "The number of lambda capture initializers should equal the number of " 10016 "fields within the closure type"); 10017 10018 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10019 // Iterate through all the lambda's closure object's fields and initialize 10020 // them. 10021 auto *CaptureInitIt = E->capture_init_begin(); 10022 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10023 bool Success = true; 10024 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10025 for (const auto *Field : ClosureClass->fields()) { 10026 assert(CaptureInitIt != E->capture_init_end()); 10027 // Get the initializer for this field 10028 Expr *const CurFieldInit = *CaptureInitIt++; 10029 10030 // If there is no initializer, either this is a VLA or an error has 10031 // occurred. 10032 if (!CurFieldInit) 10033 return Error(E); 10034 10035 LValue Subobject = This; 10036 10037 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10038 return false; 10039 10040 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10041 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10042 if (!Info.keepEvaluatingAfterFailure()) 10043 return false; 10044 Success = false; 10045 } 10046 ++CaptureIt; 10047 } 10048 return Success; 10049 } 10050 10051 static bool EvaluateRecord(const Expr *E, const LValue &This, 10052 APValue &Result, EvalInfo &Info) { 10053 assert(!E->isValueDependent()); 10054 assert(E->isRValue() && E->getType()->isRecordType() && 10055 "can't evaluate expression as a record rvalue"); 10056 return RecordExprEvaluator(Info, This, Result).Visit(E); 10057 } 10058 10059 //===----------------------------------------------------------------------===// 10060 // Temporary Evaluation 10061 // 10062 // Temporaries are represented in the AST as rvalues, but generally behave like 10063 // lvalues. The full-object of which the temporary is a subobject is implicitly 10064 // materialized so that a reference can bind to it. 10065 //===----------------------------------------------------------------------===// 10066 namespace { 10067 class TemporaryExprEvaluator 10068 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10069 public: 10070 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10071 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10072 10073 /// Visit an expression which constructs the value of this temporary. 10074 bool VisitConstructExpr(const Expr *E) { 10075 APValue &Value = Info.CurrentCall->createTemporary( 10076 E, E->getType(), ScopeKind::FullExpression, Result); 10077 return EvaluateInPlace(Value, Info, Result, E); 10078 } 10079 10080 bool VisitCastExpr(const CastExpr *E) { 10081 switch (E->getCastKind()) { 10082 default: 10083 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10084 10085 case CK_ConstructorConversion: 10086 return VisitConstructExpr(E->getSubExpr()); 10087 } 10088 } 10089 bool VisitInitListExpr(const InitListExpr *E) { 10090 return VisitConstructExpr(E); 10091 } 10092 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10093 return VisitConstructExpr(E); 10094 } 10095 bool VisitCallExpr(const CallExpr *E) { 10096 return VisitConstructExpr(E); 10097 } 10098 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10099 return VisitConstructExpr(E); 10100 } 10101 bool VisitLambdaExpr(const LambdaExpr *E) { 10102 return VisitConstructExpr(E); 10103 } 10104 }; 10105 } // end anonymous namespace 10106 10107 /// Evaluate an expression of record type as a temporary. 10108 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10109 assert(!E->isValueDependent()); 10110 assert(E->isRValue() && E->getType()->isRecordType()); 10111 return TemporaryExprEvaluator(Info, Result).Visit(E); 10112 } 10113 10114 //===----------------------------------------------------------------------===// 10115 // Vector Evaluation 10116 //===----------------------------------------------------------------------===// 10117 10118 namespace { 10119 class VectorExprEvaluator 10120 : public ExprEvaluatorBase<VectorExprEvaluator> { 10121 APValue &Result; 10122 public: 10123 10124 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10125 : ExprEvaluatorBaseTy(info), Result(Result) {} 10126 10127 bool Success(ArrayRef<APValue> V, const Expr *E) { 10128 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10129 // FIXME: remove this APValue copy. 10130 Result = APValue(V.data(), V.size()); 10131 return true; 10132 } 10133 bool Success(const APValue &V, const Expr *E) { 10134 assert(V.isVector()); 10135 Result = V; 10136 return true; 10137 } 10138 bool ZeroInitialization(const Expr *E); 10139 10140 bool VisitUnaryReal(const UnaryOperator *E) 10141 { return Visit(E->getSubExpr()); } 10142 bool VisitCastExpr(const CastExpr* E); 10143 bool VisitInitListExpr(const InitListExpr *E); 10144 bool VisitUnaryImag(const UnaryOperator *E); 10145 bool VisitBinaryOperator(const BinaryOperator *E); 10146 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10147 // conditional select), shufflevector, ExtVectorElementExpr 10148 }; 10149 } // end anonymous namespace 10150 10151 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10152 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 10153 return VectorExprEvaluator(Info, Result).Visit(E); 10154 } 10155 10156 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10157 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10158 unsigned NElts = VTy->getNumElements(); 10159 10160 const Expr *SE = E->getSubExpr(); 10161 QualType SETy = SE->getType(); 10162 10163 switch (E->getCastKind()) { 10164 case CK_VectorSplat: { 10165 APValue Val = APValue(); 10166 if (SETy->isIntegerType()) { 10167 APSInt IntResult; 10168 if (!EvaluateInteger(SE, IntResult, Info)) 10169 return false; 10170 Val = APValue(std::move(IntResult)); 10171 } else if (SETy->isRealFloatingType()) { 10172 APFloat FloatResult(0.0); 10173 if (!EvaluateFloat(SE, FloatResult, Info)) 10174 return false; 10175 Val = APValue(std::move(FloatResult)); 10176 } else { 10177 return Error(E); 10178 } 10179 10180 // Splat and create vector APValue. 10181 SmallVector<APValue, 4> Elts(NElts, Val); 10182 return Success(Elts, E); 10183 } 10184 case CK_BitCast: { 10185 // Evaluate the operand into an APInt we can extract from. 10186 llvm::APInt SValInt; 10187 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10188 return false; 10189 // Extract the elements 10190 QualType EltTy = VTy->getElementType(); 10191 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10192 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10193 SmallVector<APValue, 4> Elts; 10194 if (EltTy->isRealFloatingType()) { 10195 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10196 unsigned FloatEltSize = EltSize; 10197 if (&Sem == &APFloat::x87DoubleExtended()) 10198 FloatEltSize = 80; 10199 for (unsigned i = 0; i < NElts; i++) { 10200 llvm::APInt Elt; 10201 if (BigEndian) 10202 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10203 else 10204 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10205 Elts.push_back(APValue(APFloat(Sem, Elt))); 10206 } 10207 } else if (EltTy->isIntegerType()) { 10208 for (unsigned i = 0; i < NElts; i++) { 10209 llvm::APInt Elt; 10210 if (BigEndian) 10211 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10212 else 10213 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10214 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10215 } 10216 } else { 10217 return Error(E); 10218 } 10219 return Success(Elts, E); 10220 } 10221 default: 10222 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10223 } 10224 } 10225 10226 bool 10227 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10228 const VectorType *VT = E->getType()->castAs<VectorType>(); 10229 unsigned NumInits = E->getNumInits(); 10230 unsigned NumElements = VT->getNumElements(); 10231 10232 QualType EltTy = VT->getElementType(); 10233 SmallVector<APValue, 4> Elements; 10234 10235 // The number of initializers can be less than the number of 10236 // vector elements. For OpenCL, this can be due to nested vector 10237 // initialization. For GCC compatibility, missing trailing elements 10238 // should be initialized with zeroes. 10239 unsigned CountInits = 0, CountElts = 0; 10240 while (CountElts < NumElements) { 10241 // Handle nested vector initialization. 10242 if (CountInits < NumInits 10243 && E->getInit(CountInits)->getType()->isVectorType()) { 10244 APValue v; 10245 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10246 return Error(E); 10247 unsigned vlen = v.getVectorLength(); 10248 for (unsigned j = 0; j < vlen; j++) 10249 Elements.push_back(v.getVectorElt(j)); 10250 CountElts += vlen; 10251 } else if (EltTy->isIntegerType()) { 10252 llvm::APSInt sInt(32); 10253 if (CountInits < NumInits) { 10254 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10255 return false; 10256 } else // trailing integer zero. 10257 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10258 Elements.push_back(APValue(sInt)); 10259 CountElts++; 10260 } else { 10261 llvm::APFloat f(0.0); 10262 if (CountInits < NumInits) { 10263 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10264 return false; 10265 } else // trailing float zero. 10266 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10267 Elements.push_back(APValue(f)); 10268 CountElts++; 10269 } 10270 CountInits++; 10271 } 10272 return Success(Elements, E); 10273 } 10274 10275 bool 10276 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10277 const auto *VT = E->getType()->castAs<VectorType>(); 10278 QualType EltTy = VT->getElementType(); 10279 APValue ZeroElement; 10280 if (EltTy->isIntegerType()) 10281 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10282 else 10283 ZeroElement = 10284 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10285 10286 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10287 return Success(Elements, E); 10288 } 10289 10290 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10291 VisitIgnoredValue(E->getSubExpr()); 10292 return ZeroInitialization(E); 10293 } 10294 10295 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10296 BinaryOperatorKind Op = E->getOpcode(); 10297 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10298 "Operation not supported on vector types"); 10299 10300 if (Op == BO_Comma) 10301 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10302 10303 Expr *LHS = E->getLHS(); 10304 Expr *RHS = E->getRHS(); 10305 10306 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10307 "Must both be vector types"); 10308 // Checking JUST the types are the same would be fine, except shifts don't 10309 // need to have their types be the same (since you always shift by an int). 10310 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10311 E->getType()->getAs<VectorType>()->getNumElements() && 10312 RHS->getType()->getAs<VectorType>()->getNumElements() == 10313 E->getType()->getAs<VectorType>()->getNumElements() && 10314 "All operands must be the same size."); 10315 10316 APValue LHSValue; 10317 APValue RHSValue; 10318 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10319 if (!LHSOK && !Info.noteFailure()) 10320 return false; 10321 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10322 return false; 10323 10324 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10325 return false; 10326 10327 return Success(LHSValue, E); 10328 } 10329 10330 //===----------------------------------------------------------------------===// 10331 // Array Evaluation 10332 //===----------------------------------------------------------------------===// 10333 10334 namespace { 10335 class ArrayExprEvaluator 10336 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10337 const LValue &This; 10338 APValue &Result; 10339 public: 10340 10341 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10342 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10343 10344 bool Success(const APValue &V, const Expr *E) { 10345 assert(V.isArray() && "expected array"); 10346 Result = V; 10347 return true; 10348 } 10349 10350 bool ZeroInitialization(const Expr *E) { 10351 const ConstantArrayType *CAT = 10352 Info.Ctx.getAsConstantArrayType(E->getType()); 10353 if (!CAT) { 10354 if (E->getType()->isIncompleteArrayType()) { 10355 // We can be asked to zero-initialize a flexible array member; this 10356 // is represented as an ImplicitValueInitExpr of incomplete array 10357 // type. In this case, the array has zero elements. 10358 Result = APValue(APValue::UninitArray(), 0, 0); 10359 return true; 10360 } 10361 // FIXME: We could handle VLAs here. 10362 return Error(E); 10363 } 10364 10365 Result = APValue(APValue::UninitArray(), 0, 10366 CAT->getSize().getZExtValue()); 10367 if (!Result.hasArrayFiller()) return true; 10368 10369 // Zero-initialize all elements. 10370 LValue Subobject = This; 10371 Subobject.addArray(Info, E, CAT); 10372 ImplicitValueInitExpr VIE(CAT->getElementType()); 10373 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10374 } 10375 10376 bool VisitCallExpr(const CallExpr *E) { 10377 return handleCallExpr(E, Result, &This); 10378 } 10379 bool VisitInitListExpr(const InitListExpr *E, 10380 QualType AllocType = QualType()); 10381 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10382 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10383 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10384 const LValue &Subobject, 10385 APValue *Value, QualType Type); 10386 bool VisitStringLiteral(const StringLiteral *E, 10387 QualType AllocType = QualType()) { 10388 expandStringLiteral(Info, E, Result, AllocType); 10389 return true; 10390 } 10391 }; 10392 } // end anonymous namespace 10393 10394 static bool EvaluateArray(const Expr *E, const LValue &This, 10395 APValue &Result, EvalInfo &Info) { 10396 assert(!E->isValueDependent()); 10397 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10398 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10399 } 10400 10401 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10402 APValue &Result, const InitListExpr *ILE, 10403 QualType AllocType) { 10404 assert(!ILE->isValueDependent()); 10405 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10406 "not an array rvalue"); 10407 return ArrayExprEvaluator(Info, This, Result) 10408 .VisitInitListExpr(ILE, AllocType); 10409 } 10410 10411 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10412 APValue &Result, 10413 const CXXConstructExpr *CCE, 10414 QualType AllocType) { 10415 assert(!CCE->isValueDependent()); 10416 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10417 "not an array rvalue"); 10418 return ArrayExprEvaluator(Info, This, Result) 10419 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10420 } 10421 10422 // Return true iff the given array filler may depend on the element index. 10423 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10424 // For now, just allow non-class value-initialization and initialization 10425 // lists comprised of them. 10426 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10427 return false; 10428 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10429 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10430 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10431 return true; 10432 } 10433 return false; 10434 } 10435 return true; 10436 } 10437 10438 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10439 QualType AllocType) { 10440 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10441 AllocType.isNull() ? E->getType() : AllocType); 10442 if (!CAT) 10443 return Error(E); 10444 10445 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10446 // an appropriately-typed string literal enclosed in braces. 10447 if (E->isStringLiteralInit()) { 10448 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10449 // FIXME: Support ObjCEncodeExpr here once we support it in 10450 // ArrayExprEvaluator generally. 10451 if (!SL) 10452 return Error(E); 10453 return VisitStringLiteral(SL, AllocType); 10454 } 10455 10456 bool Success = true; 10457 10458 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10459 "zero-initialized array shouldn't have any initialized elts"); 10460 APValue Filler; 10461 if (Result.isArray() && Result.hasArrayFiller()) 10462 Filler = Result.getArrayFiller(); 10463 10464 unsigned NumEltsToInit = E->getNumInits(); 10465 unsigned NumElts = CAT->getSize().getZExtValue(); 10466 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10467 10468 // If the initializer might depend on the array index, run it for each 10469 // array element. 10470 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10471 NumEltsToInit = NumElts; 10472 10473 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10474 << NumEltsToInit << ".\n"); 10475 10476 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10477 10478 // If the array was previously zero-initialized, preserve the 10479 // zero-initialized values. 10480 if (Filler.hasValue()) { 10481 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10482 Result.getArrayInitializedElt(I) = Filler; 10483 if (Result.hasArrayFiller()) 10484 Result.getArrayFiller() = Filler; 10485 } 10486 10487 LValue Subobject = This; 10488 Subobject.addArray(Info, E, CAT); 10489 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10490 const Expr *Init = 10491 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10492 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10493 Info, Subobject, Init) || 10494 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10495 CAT->getElementType(), 1)) { 10496 if (!Info.noteFailure()) 10497 return false; 10498 Success = false; 10499 } 10500 } 10501 10502 if (!Result.hasArrayFiller()) 10503 return Success; 10504 10505 // If we get here, we have a trivial filler, which we can just evaluate 10506 // once and splat over the rest of the array elements. 10507 assert(FillerExpr && "no array filler for incomplete init list"); 10508 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10509 FillerExpr) && Success; 10510 } 10511 10512 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10513 LValue CommonLV; 10514 if (E->getCommonExpr() && 10515 !Evaluate(Info.CurrentCall->createTemporary( 10516 E->getCommonExpr(), 10517 getStorageType(Info.Ctx, E->getCommonExpr()), 10518 ScopeKind::FullExpression, CommonLV), 10519 Info, E->getCommonExpr()->getSourceExpr())) 10520 return false; 10521 10522 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10523 10524 uint64_t Elements = CAT->getSize().getZExtValue(); 10525 Result = APValue(APValue::UninitArray(), Elements, Elements); 10526 10527 LValue Subobject = This; 10528 Subobject.addArray(Info, E, CAT); 10529 10530 bool Success = true; 10531 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10532 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10533 Info, Subobject, E->getSubExpr()) || 10534 !HandleLValueArrayAdjustment(Info, E, Subobject, 10535 CAT->getElementType(), 1)) { 10536 if (!Info.noteFailure()) 10537 return false; 10538 Success = false; 10539 } 10540 } 10541 10542 return Success; 10543 } 10544 10545 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10546 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10547 } 10548 10549 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10550 const LValue &Subobject, 10551 APValue *Value, 10552 QualType Type) { 10553 bool HadZeroInit = Value->hasValue(); 10554 10555 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10556 unsigned N = CAT->getSize().getZExtValue(); 10557 10558 // Preserve the array filler if we had prior zero-initialization. 10559 APValue Filler = 10560 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10561 : APValue(); 10562 10563 *Value = APValue(APValue::UninitArray(), N, N); 10564 10565 if (HadZeroInit) 10566 for (unsigned I = 0; I != N; ++I) 10567 Value->getArrayInitializedElt(I) = Filler; 10568 10569 // Initialize the elements. 10570 LValue ArrayElt = Subobject; 10571 ArrayElt.addArray(Info, E, CAT); 10572 for (unsigned I = 0; I != N; ++I) 10573 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10574 CAT->getElementType()) || 10575 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10576 CAT->getElementType(), 1)) 10577 return false; 10578 10579 return true; 10580 } 10581 10582 if (!Type->isRecordType()) 10583 return Error(E); 10584 10585 return RecordExprEvaluator(Info, Subobject, *Value) 10586 .VisitCXXConstructExpr(E, Type); 10587 } 10588 10589 //===----------------------------------------------------------------------===// 10590 // Integer Evaluation 10591 // 10592 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10593 // types and back in constant folding. Integer values are thus represented 10594 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10595 //===----------------------------------------------------------------------===// 10596 10597 namespace { 10598 class IntExprEvaluator 10599 : public ExprEvaluatorBase<IntExprEvaluator> { 10600 APValue &Result; 10601 public: 10602 IntExprEvaluator(EvalInfo &info, APValue &result) 10603 : ExprEvaluatorBaseTy(info), Result(result) {} 10604 10605 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10606 assert(E->getType()->isIntegralOrEnumerationType() && 10607 "Invalid evaluation result."); 10608 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10609 "Invalid evaluation result."); 10610 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10611 "Invalid evaluation result."); 10612 Result = APValue(SI); 10613 return true; 10614 } 10615 bool Success(const llvm::APSInt &SI, const Expr *E) { 10616 return Success(SI, E, Result); 10617 } 10618 10619 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10620 assert(E->getType()->isIntegralOrEnumerationType() && 10621 "Invalid evaluation result."); 10622 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10623 "Invalid evaluation result."); 10624 Result = APValue(APSInt(I)); 10625 Result.getInt().setIsUnsigned( 10626 E->getType()->isUnsignedIntegerOrEnumerationType()); 10627 return true; 10628 } 10629 bool Success(const llvm::APInt &I, const Expr *E) { 10630 return Success(I, E, Result); 10631 } 10632 10633 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10634 assert(E->getType()->isIntegralOrEnumerationType() && 10635 "Invalid evaluation result."); 10636 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10637 return true; 10638 } 10639 bool Success(uint64_t Value, const Expr *E) { 10640 return Success(Value, E, Result); 10641 } 10642 10643 bool Success(CharUnits Size, const Expr *E) { 10644 return Success(Size.getQuantity(), E); 10645 } 10646 10647 bool Success(const APValue &V, const Expr *E) { 10648 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10649 Result = V; 10650 return true; 10651 } 10652 return Success(V.getInt(), E); 10653 } 10654 10655 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10656 10657 //===--------------------------------------------------------------------===// 10658 // Visitor Methods 10659 //===--------------------------------------------------------------------===// 10660 10661 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10662 return Success(E->getValue(), E); 10663 } 10664 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10665 return Success(E->getValue(), E); 10666 } 10667 10668 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10669 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10670 if (CheckReferencedDecl(E, E->getDecl())) 10671 return true; 10672 10673 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10674 } 10675 bool VisitMemberExpr(const MemberExpr *E) { 10676 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10677 VisitIgnoredBaseExpression(E->getBase()); 10678 return true; 10679 } 10680 10681 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10682 } 10683 10684 bool VisitCallExpr(const CallExpr *E); 10685 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10686 bool VisitBinaryOperator(const BinaryOperator *E); 10687 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10688 bool VisitUnaryOperator(const UnaryOperator *E); 10689 10690 bool VisitCastExpr(const CastExpr* E); 10691 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10692 10693 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10694 return Success(E->getValue(), E); 10695 } 10696 10697 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10698 return Success(E->getValue(), E); 10699 } 10700 10701 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10702 if (Info.ArrayInitIndex == uint64_t(-1)) { 10703 // We were asked to evaluate this subexpression independent of the 10704 // enclosing ArrayInitLoopExpr. We can't do that. 10705 Info.FFDiag(E); 10706 return false; 10707 } 10708 return Success(Info.ArrayInitIndex, E); 10709 } 10710 10711 // Note, GNU defines __null as an integer, not a pointer. 10712 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10713 return ZeroInitialization(E); 10714 } 10715 10716 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10717 return Success(E->getValue(), E); 10718 } 10719 10720 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10721 return Success(E->getValue(), E); 10722 } 10723 10724 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10725 return Success(E->getValue(), E); 10726 } 10727 10728 bool VisitUnaryReal(const UnaryOperator *E); 10729 bool VisitUnaryImag(const UnaryOperator *E); 10730 10731 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10732 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10733 bool VisitSourceLocExpr(const SourceLocExpr *E); 10734 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10735 bool VisitRequiresExpr(const RequiresExpr *E); 10736 // FIXME: Missing: array subscript of vector, member of vector 10737 }; 10738 10739 class FixedPointExprEvaluator 10740 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10741 APValue &Result; 10742 10743 public: 10744 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10745 : ExprEvaluatorBaseTy(info), Result(result) {} 10746 10747 bool Success(const llvm::APInt &I, const Expr *E) { 10748 return Success( 10749 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10750 } 10751 10752 bool Success(uint64_t Value, const Expr *E) { 10753 return Success( 10754 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10755 } 10756 10757 bool Success(const APValue &V, const Expr *E) { 10758 return Success(V.getFixedPoint(), E); 10759 } 10760 10761 bool Success(const APFixedPoint &V, const Expr *E) { 10762 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10763 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10764 "Invalid evaluation result."); 10765 Result = APValue(V); 10766 return true; 10767 } 10768 10769 //===--------------------------------------------------------------------===// 10770 // Visitor Methods 10771 //===--------------------------------------------------------------------===// 10772 10773 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10774 return Success(E->getValue(), E); 10775 } 10776 10777 bool VisitCastExpr(const CastExpr *E); 10778 bool VisitUnaryOperator(const UnaryOperator *E); 10779 bool VisitBinaryOperator(const BinaryOperator *E); 10780 }; 10781 } // end anonymous namespace 10782 10783 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10784 /// produce either the integer value or a pointer. 10785 /// 10786 /// GCC has a heinous extension which folds casts between pointer types and 10787 /// pointer-sized integral types. We support this by allowing the evaluation of 10788 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10789 /// Some simple arithmetic on such values is supported (they are treated much 10790 /// like char*). 10791 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10792 EvalInfo &Info) { 10793 assert(!E->isValueDependent()); 10794 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10795 return IntExprEvaluator(Info, Result).Visit(E); 10796 } 10797 10798 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10799 assert(!E->isValueDependent()); 10800 APValue Val; 10801 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10802 return false; 10803 if (!Val.isInt()) { 10804 // FIXME: It would be better to produce the diagnostic for casting 10805 // a pointer to an integer. 10806 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10807 return false; 10808 } 10809 Result = Val.getInt(); 10810 return true; 10811 } 10812 10813 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10814 APValue Evaluated = E->EvaluateInContext( 10815 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10816 return Success(Evaluated, E); 10817 } 10818 10819 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10820 EvalInfo &Info) { 10821 assert(!E->isValueDependent()); 10822 if (E->getType()->isFixedPointType()) { 10823 APValue Val; 10824 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10825 return false; 10826 if (!Val.isFixedPoint()) 10827 return false; 10828 10829 Result = Val.getFixedPoint(); 10830 return true; 10831 } 10832 return false; 10833 } 10834 10835 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10836 EvalInfo &Info) { 10837 assert(!E->isValueDependent()); 10838 if (E->getType()->isIntegerType()) { 10839 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10840 APSInt Val; 10841 if (!EvaluateInteger(E, Val, Info)) 10842 return false; 10843 Result = APFixedPoint(Val, FXSema); 10844 return true; 10845 } else if (E->getType()->isFixedPointType()) { 10846 return EvaluateFixedPoint(E, Result, Info); 10847 } 10848 return false; 10849 } 10850 10851 /// Check whether the given declaration can be directly converted to an integral 10852 /// rvalue. If not, no diagnostic is produced; there are other things we can 10853 /// try. 10854 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10855 // Enums are integer constant exprs. 10856 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10857 // Check for signedness/width mismatches between E type and ECD value. 10858 bool SameSign = (ECD->getInitVal().isSigned() 10859 == E->getType()->isSignedIntegerOrEnumerationType()); 10860 bool SameWidth = (ECD->getInitVal().getBitWidth() 10861 == Info.Ctx.getIntWidth(E->getType())); 10862 if (SameSign && SameWidth) 10863 return Success(ECD->getInitVal(), E); 10864 else { 10865 // Get rid of mismatch (otherwise Success assertions will fail) 10866 // by computing a new value matching the type of E. 10867 llvm::APSInt Val = ECD->getInitVal(); 10868 if (!SameSign) 10869 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10870 if (!SameWidth) 10871 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10872 return Success(Val, E); 10873 } 10874 } 10875 return false; 10876 } 10877 10878 /// Values returned by __builtin_classify_type, chosen to match the values 10879 /// produced by GCC's builtin. 10880 enum class GCCTypeClass { 10881 None = -1, 10882 Void = 0, 10883 Integer = 1, 10884 // GCC reserves 2 for character types, but instead classifies them as 10885 // integers. 10886 Enum = 3, 10887 Bool = 4, 10888 Pointer = 5, 10889 // GCC reserves 6 for references, but appears to never use it (because 10890 // expressions never have reference type, presumably). 10891 PointerToDataMember = 7, 10892 RealFloat = 8, 10893 Complex = 9, 10894 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10895 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10896 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10897 // uses 12 for that purpose, same as for a class or struct. Maybe it 10898 // internally implements a pointer to member as a struct? Who knows. 10899 PointerToMemberFunction = 12, // Not a bug, see above. 10900 ClassOrStruct = 12, 10901 Union = 13, 10902 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10903 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10904 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10905 // literals. 10906 }; 10907 10908 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10909 /// as GCC. 10910 static GCCTypeClass 10911 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10912 assert(!T->isDependentType() && "unexpected dependent type"); 10913 10914 QualType CanTy = T.getCanonicalType(); 10915 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10916 10917 switch (CanTy->getTypeClass()) { 10918 #define TYPE(ID, BASE) 10919 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10920 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10921 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10922 #include "clang/AST/TypeNodes.inc" 10923 case Type::Auto: 10924 case Type::DeducedTemplateSpecialization: 10925 llvm_unreachable("unexpected non-canonical or dependent type"); 10926 10927 case Type::Builtin: 10928 switch (BT->getKind()) { 10929 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10930 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10931 case BuiltinType::ID: return GCCTypeClass::Integer; 10932 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10933 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10934 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10935 case BuiltinType::ID: break; 10936 #include "clang/AST/BuiltinTypes.def" 10937 case BuiltinType::Void: 10938 return GCCTypeClass::Void; 10939 10940 case BuiltinType::Bool: 10941 return GCCTypeClass::Bool; 10942 10943 case BuiltinType::Char_U: 10944 case BuiltinType::UChar: 10945 case BuiltinType::WChar_U: 10946 case BuiltinType::Char8: 10947 case BuiltinType::Char16: 10948 case BuiltinType::Char32: 10949 case BuiltinType::UShort: 10950 case BuiltinType::UInt: 10951 case BuiltinType::ULong: 10952 case BuiltinType::ULongLong: 10953 case BuiltinType::UInt128: 10954 return GCCTypeClass::Integer; 10955 10956 case BuiltinType::UShortAccum: 10957 case BuiltinType::UAccum: 10958 case BuiltinType::ULongAccum: 10959 case BuiltinType::UShortFract: 10960 case BuiltinType::UFract: 10961 case BuiltinType::ULongFract: 10962 case BuiltinType::SatUShortAccum: 10963 case BuiltinType::SatUAccum: 10964 case BuiltinType::SatULongAccum: 10965 case BuiltinType::SatUShortFract: 10966 case BuiltinType::SatUFract: 10967 case BuiltinType::SatULongFract: 10968 return GCCTypeClass::None; 10969 10970 case BuiltinType::NullPtr: 10971 10972 case BuiltinType::ObjCId: 10973 case BuiltinType::ObjCClass: 10974 case BuiltinType::ObjCSel: 10975 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10976 case BuiltinType::Id: 10977 #include "clang/Basic/OpenCLImageTypes.def" 10978 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10979 case BuiltinType::Id: 10980 #include "clang/Basic/OpenCLExtensionTypes.def" 10981 case BuiltinType::OCLSampler: 10982 case BuiltinType::OCLEvent: 10983 case BuiltinType::OCLClkEvent: 10984 case BuiltinType::OCLQueue: 10985 case BuiltinType::OCLReserveID: 10986 #define SVE_TYPE(Name, Id, SingletonId) \ 10987 case BuiltinType::Id: 10988 #include "clang/Basic/AArch64SVEACLETypes.def" 10989 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 10990 case BuiltinType::Id: 10991 #include "clang/Basic/PPCTypes.def" 10992 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 10993 #include "clang/Basic/RISCVVTypes.def" 10994 return GCCTypeClass::None; 10995 10996 case BuiltinType::Dependent: 10997 llvm_unreachable("unexpected dependent type"); 10998 }; 10999 llvm_unreachable("unexpected placeholder type"); 11000 11001 case Type::Enum: 11002 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11003 11004 case Type::Pointer: 11005 case Type::ConstantArray: 11006 case Type::VariableArray: 11007 case Type::IncompleteArray: 11008 case Type::FunctionNoProto: 11009 case Type::FunctionProto: 11010 return GCCTypeClass::Pointer; 11011 11012 case Type::MemberPointer: 11013 return CanTy->isMemberDataPointerType() 11014 ? GCCTypeClass::PointerToDataMember 11015 : GCCTypeClass::PointerToMemberFunction; 11016 11017 case Type::Complex: 11018 return GCCTypeClass::Complex; 11019 11020 case Type::Record: 11021 return CanTy->isUnionType() ? GCCTypeClass::Union 11022 : GCCTypeClass::ClassOrStruct; 11023 11024 case Type::Atomic: 11025 // GCC classifies _Atomic T the same as T. 11026 return EvaluateBuiltinClassifyType( 11027 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11028 11029 case Type::BlockPointer: 11030 case Type::Vector: 11031 case Type::ExtVector: 11032 case Type::ConstantMatrix: 11033 case Type::ObjCObject: 11034 case Type::ObjCInterface: 11035 case Type::ObjCObjectPointer: 11036 case Type::Pipe: 11037 case Type::ExtInt: 11038 // GCC classifies vectors as None. We follow its lead and classify all 11039 // other types that don't fit into the regular classification the same way. 11040 return GCCTypeClass::None; 11041 11042 case Type::LValueReference: 11043 case Type::RValueReference: 11044 llvm_unreachable("invalid type for expression"); 11045 } 11046 11047 llvm_unreachable("unexpected type class"); 11048 } 11049 11050 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11051 /// as GCC. 11052 static GCCTypeClass 11053 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11054 // If no argument was supplied, default to None. This isn't 11055 // ideal, however it is what gcc does. 11056 if (E->getNumArgs() == 0) 11057 return GCCTypeClass::None; 11058 11059 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11060 // being an ICE, but still folds it to a constant using the type of the first 11061 // argument. 11062 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11063 } 11064 11065 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11066 /// __builtin_constant_p when applied to the given pointer. 11067 /// 11068 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11069 /// or it points to the first character of a string literal. 11070 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11071 APValue::LValueBase Base = LV.getLValueBase(); 11072 if (Base.isNull()) { 11073 // A null base is acceptable. 11074 return true; 11075 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11076 if (!isa<StringLiteral>(E)) 11077 return false; 11078 return LV.getLValueOffset().isZero(); 11079 } else if (Base.is<TypeInfoLValue>()) { 11080 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11081 // evaluate to true. 11082 return true; 11083 } else { 11084 // Any other base is not constant enough for GCC. 11085 return false; 11086 } 11087 } 11088 11089 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11090 /// GCC as we can manage. 11091 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11092 // This evaluation is not permitted to have side-effects, so evaluate it in 11093 // a speculative evaluation context. 11094 SpeculativeEvaluationRAII SpeculativeEval(Info); 11095 11096 // Constant-folding is always enabled for the operand of __builtin_constant_p 11097 // (even when the enclosing evaluation context otherwise requires a strict 11098 // language-specific constant expression). 11099 FoldConstant Fold(Info, true); 11100 11101 QualType ArgType = Arg->getType(); 11102 11103 // __builtin_constant_p always has one operand. The rules which gcc follows 11104 // are not precisely documented, but are as follows: 11105 // 11106 // - If the operand is of integral, floating, complex or enumeration type, 11107 // and can be folded to a known value of that type, it returns 1. 11108 // - If the operand can be folded to a pointer to the first character 11109 // of a string literal (or such a pointer cast to an integral type) 11110 // or to a null pointer or an integer cast to a pointer, it returns 1. 11111 // 11112 // Otherwise, it returns 0. 11113 // 11114 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11115 // its support for this did not work prior to GCC 9 and is not yet well 11116 // understood. 11117 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11118 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11119 ArgType->isNullPtrType()) { 11120 APValue V; 11121 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11122 Fold.keepDiagnostics(); 11123 return false; 11124 } 11125 11126 // For a pointer (possibly cast to integer), there are special rules. 11127 if (V.getKind() == APValue::LValue) 11128 return EvaluateBuiltinConstantPForLValue(V); 11129 11130 // Otherwise, any constant value is good enough. 11131 return V.hasValue(); 11132 } 11133 11134 // Anything else isn't considered to be sufficiently constant. 11135 return false; 11136 } 11137 11138 /// Retrieves the "underlying object type" of the given expression, 11139 /// as used by __builtin_object_size. 11140 static QualType getObjectType(APValue::LValueBase B) { 11141 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11142 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11143 return VD->getType(); 11144 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11145 if (isa<CompoundLiteralExpr>(E)) 11146 return E->getType(); 11147 } else if (B.is<TypeInfoLValue>()) { 11148 return B.getTypeInfoType(); 11149 } else if (B.is<DynamicAllocLValue>()) { 11150 return B.getDynamicAllocType(); 11151 } 11152 11153 return QualType(); 11154 } 11155 11156 /// A more selective version of E->IgnoreParenCasts for 11157 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11158 /// to change the type of E. 11159 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11160 /// 11161 /// Always returns an RValue with a pointer representation. 11162 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11163 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 11164 11165 auto *NoParens = E->IgnoreParens(); 11166 auto *Cast = dyn_cast<CastExpr>(NoParens); 11167 if (Cast == nullptr) 11168 return NoParens; 11169 11170 // We only conservatively allow a few kinds of casts, because this code is 11171 // inherently a simple solution that seeks to support the common case. 11172 auto CastKind = Cast->getCastKind(); 11173 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11174 CastKind != CK_AddressSpaceConversion) 11175 return NoParens; 11176 11177 auto *SubExpr = Cast->getSubExpr(); 11178 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 11179 return NoParens; 11180 return ignorePointerCastsAndParens(SubExpr); 11181 } 11182 11183 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11184 /// record layout. e.g. 11185 /// struct { struct { int a, b; } fst, snd; } obj; 11186 /// obj.fst // no 11187 /// obj.snd // yes 11188 /// obj.fst.a // no 11189 /// obj.fst.b // no 11190 /// obj.snd.a // no 11191 /// obj.snd.b // yes 11192 /// 11193 /// Please note: this function is specialized for how __builtin_object_size 11194 /// views "objects". 11195 /// 11196 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11197 /// correct result, it will always return true. 11198 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11199 assert(!LVal.Designator.Invalid); 11200 11201 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11202 const RecordDecl *Parent = FD->getParent(); 11203 Invalid = Parent->isInvalidDecl(); 11204 if (Invalid || Parent->isUnion()) 11205 return true; 11206 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11207 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11208 }; 11209 11210 auto &Base = LVal.getLValueBase(); 11211 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11212 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11213 bool Invalid; 11214 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11215 return Invalid; 11216 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11217 for (auto *FD : IFD->chain()) { 11218 bool Invalid; 11219 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11220 return Invalid; 11221 } 11222 } 11223 } 11224 11225 unsigned I = 0; 11226 QualType BaseType = getType(Base); 11227 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11228 // If we don't know the array bound, conservatively assume we're looking at 11229 // the final array element. 11230 ++I; 11231 if (BaseType->isIncompleteArrayType()) 11232 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11233 else 11234 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11235 } 11236 11237 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11238 const auto &Entry = LVal.Designator.Entries[I]; 11239 if (BaseType->isArrayType()) { 11240 // Because __builtin_object_size treats arrays as objects, we can ignore 11241 // the index iff this is the last array in the Designator. 11242 if (I + 1 == E) 11243 return true; 11244 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11245 uint64_t Index = Entry.getAsArrayIndex(); 11246 if (Index + 1 != CAT->getSize()) 11247 return false; 11248 BaseType = CAT->getElementType(); 11249 } else if (BaseType->isAnyComplexType()) { 11250 const auto *CT = BaseType->castAs<ComplexType>(); 11251 uint64_t Index = Entry.getAsArrayIndex(); 11252 if (Index != 1) 11253 return false; 11254 BaseType = CT->getElementType(); 11255 } else if (auto *FD = getAsField(Entry)) { 11256 bool Invalid; 11257 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11258 return Invalid; 11259 BaseType = FD->getType(); 11260 } else { 11261 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11262 return false; 11263 } 11264 } 11265 return true; 11266 } 11267 11268 /// Tests to see if the LValue has a user-specified designator (that isn't 11269 /// necessarily valid). Note that this always returns 'true' if the LValue has 11270 /// an unsized array as its first designator entry, because there's currently no 11271 /// way to tell if the user typed *foo or foo[0]. 11272 static bool refersToCompleteObject(const LValue &LVal) { 11273 if (LVal.Designator.Invalid) 11274 return false; 11275 11276 if (!LVal.Designator.Entries.empty()) 11277 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11278 11279 if (!LVal.InvalidBase) 11280 return true; 11281 11282 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11283 // the LValueBase. 11284 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11285 return !E || !isa<MemberExpr>(E); 11286 } 11287 11288 /// Attempts to detect a user writing into a piece of memory that's impossible 11289 /// to figure out the size of by just using types. 11290 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11291 const SubobjectDesignator &Designator = LVal.Designator; 11292 // Notes: 11293 // - Users can only write off of the end when we have an invalid base. Invalid 11294 // bases imply we don't know where the memory came from. 11295 // - We used to be a bit more aggressive here; we'd only be conservative if 11296 // the array at the end was flexible, or if it had 0 or 1 elements. This 11297 // broke some common standard library extensions (PR30346), but was 11298 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11299 // with some sort of list. OTOH, it seems that GCC is always 11300 // conservative with the last element in structs (if it's an array), so our 11301 // current behavior is more compatible than an explicit list approach would 11302 // be. 11303 return LVal.InvalidBase && 11304 Designator.Entries.size() == Designator.MostDerivedPathLength && 11305 Designator.MostDerivedIsArrayElement && 11306 isDesignatorAtObjectEnd(Ctx, LVal); 11307 } 11308 11309 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11310 /// Fails if the conversion would cause loss of precision. 11311 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11312 CharUnits &Result) { 11313 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11314 if (Int.ugt(CharUnitsMax)) 11315 return false; 11316 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11317 return true; 11318 } 11319 11320 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11321 /// determine how many bytes exist from the beginning of the object to either 11322 /// the end of the current subobject, or the end of the object itself, depending 11323 /// on what the LValue looks like + the value of Type. 11324 /// 11325 /// If this returns false, the value of Result is undefined. 11326 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11327 unsigned Type, const LValue &LVal, 11328 CharUnits &EndOffset) { 11329 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11330 11331 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11332 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11333 return false; 11334 return HandleSizeof(Info, ExprLoc, Ty, Result); 11335 }; 11336 11337 // We want to evaluate the size of the entire object. This is a valid fallback 11338 // for when Type=1 and the designator is invalid, because we're asked for an 11339 // upper-bound. 11340 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11341 // Type=3 wants a lower bound, so we can't fall back to this. 11342 if (Type == 3 && !DetermineForCompleteObject) 11343 return false; 11344 11345 llvm::APInt APEndOffset; 11346 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11347 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11348 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11349 11350 if (LVal.InvalidBase) 11351 return false; 11352 11353 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11354 return CheckedHandleSizeof(BaseTy, EndOffset); 11355 } 11356 11357 // We want to evaluate the size of a subobject. 11358 const SubobjectDesignator &Designator = LVal.Designator; 11359 11360 // The following is a moderately common idiom in C: 11361 // 11362 // struct Foo { int a; char c[1]; }; 11363 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11364 // strcpy(&F->c[0], Bar); 11365 // 11366 // In order to not break too much legacy code, we need to support it. 11367 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11368 // If we can resolve this to an alloc_size call, we can hand that back, 11369 // because we know for certain how many bytes there are to write to. 11370 llvm::APInt APEndOffset; 11371 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11372 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11373 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11374 11375 // If we cannot determine the size of the initial allocation, then we can't 11376 // given an accurate upper-bound. However, we are still able to give 11377 // conservative lower-bounds for Type=3. 11378 if (Type == 1) 11379 return false; 11380 } 11381 11382 CharUnits BytesPerElem; 11383 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11384 return false; 11385 11386 // According to the GCC documentation, we want the size of the subobject 11387 // denoted by the pointer. But that's not quite right -- what we actually 11388 // want is the size of the immediately-enclosing array, if there is one. 11389 int64_t ElemsRemaining; 11390 if (Designator.MostDerivedIsArrayElement && 11391 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11392 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11393 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11394 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11395 } else { 11396 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11397 } 11398 11399 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11400 return true; 11401 } 11402 11403 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11404 /// returns true and stores the result in @p Size. 11405 /// 11406 /// If @p WasError is non-null, this will report whether the failure to evaluate 11407 /// is to be treated as an Error in IntExprEvaluator. 11408 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11409 EvalInfo &Info, uint64_t &Size) { 11410 // Determine the denoted object. 11411 LValue LVal; 11412 { 11413 // The operand of __builtin_object_size is never evaluated for side-effects. 11414 // If there are any, but we can determine the pointed-to object anyway, then 11415 // ignore the side-effects. 11416 SpeculativeEvaluationRAII SpeculativeEval(Info); 11417 IgnoreSideEffectsRAII Fold(Info); 11418 11419 if (E->isGLValue()) { 11420 // It's possible for us to be given GLValues if we're called via 11421 // Expr::tryEvaluateObjectSize. 11422 APValue RVal; 11423 if (!EvaluateAsRValue(Info, E, RVal)) 11424 return false; 11425 LVal.setFrom(Info.Ctx, RVal); 11426 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11427 /*InvalidBaseOK=*/true)) 11428 return false; 11429 } 11430 11431 // If we point to before the start of the object, there are no accessible 11432 // bytes. 11433 if (LVal.getLValueOffset().isNegative()) { 11434 Size = 0; 11435 return true; 11436 } 11437 11438 CharUnits EndOffset; 11439 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11440 return false; 11441 11442 // If we've fallen outside of the end offset, just pretend there's nothing to 11443 // write to/read from. 11444 if (EndOffset <= LVal.getLValueOffset()) 11445 Size = 0; 11446 else 11447 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11448 return true; 11449 } 11450 11451 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11452 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11453 return VisitBuiltinCallExpr(E, BuiltinOp); 11454 11455 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11456 } 11457 11458 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11459 APValue &Val, APSInt &Alignment) { 11460 QualType SrcTy = E->getArg(0)->getType(); 11461 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11462 return false; 11463 // Even though we are evaluating integer expressions we could get a pointer 11464 // argument for the __builtin_is_aligned() case. 11465 if (SrcTy->isPointerType()) { 11466 LValue Ptr; 11467 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11468 return false; 11469 Ptr.moveInto(Val); 11470 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11471 Info.FFDiag(E->getArg(0)); 11472 return false; 11473 } else { 11474 APSInt SrcInt; 11475 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11476 return false; 11477 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11478 "Bit widths must be the same"); 11479 Val = APValue(SrcInt); 11480 } 11481 assert(Val.hasValue()); 11482 return true; 11483 } 11484 11485 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11486 unsigned BuiltinOp) { 11487 switch (BuiltinOp) { 11488 default: 11489 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11490 11491 case Builtin::BI__builtin_dynamic_object_size: 11492 case Builtin::BI__builtin_object_size: { 11493 // The type was checked when we built the expression. 11494 unsigned Type = 11495 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11496 assert(Type <= 3 && "unexpected type"); 11497 11498 uint64_t Size; 11499 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11500 return Success(Size, E); 11501 11502 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11503 return Success((Type & 2) ? 0 : -1, E); 11504 11505 // Expression had no side effects, but we couldn't statically determine the 11506 // size of the referenced object. 11507 switch (Info.EvalMode) { 11508 case EvalInfo::EM_ConstantExpression: 11509 case EvalInfo::EM_ConstantFold: 11510 case EvalInfo::EM_IgnoreSideEffects: 11511 // Leave it to IR generation. 11512 return Error(E); 11513 case EvalInfo::EM_ConstantExpressionUnevaluated: 11514 // Reduce it to a constant now. 11515 return Success((Type & 2) ? 0 : -1, E); 11516 } 11517 11518 llvm_unreachable("unexpected EvalMode"); 11519 } 11520 11521 case Builtin::BI__builtin_os_log_format_buffer_size: { 11522 analyze_os_log::OSLogBufferLayout Layout; 11523 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11524 return Success(Layout.size().getQuantity(), E); 11525 } 11526 11527 case Builtin::BI__builtin_is_aligned: { 11528 APValue Src; 11529 APSInt Alignment; 11530 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11531 return false; 11532 if (Src.isLValue()) { 11533 // If we evaluated a pointer, check the minimum known alignment. 11534 LValue Ptr; 11535 Ptr.setFrom(Info.Ctx, Src); 11536 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11537 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11538 // We can return true if the known alignment at the computed offset is 11539 // greater than the requested alignment. 11540 assert(PtrAlign.isPowerOfTwo()); 11541 assert(Alignment.isPowerOf2()); 11542 if (PtrAlign.getQuantity() >= Alignment) 11543 return Success(1, E); 11544 // If the alignment is not known to be sufficient, some cases could still 11545 // be aligned at run time. However, if the requested alignment is less or 11546 // equal to the base alignment and the offset is not aligned, we know that 11547 // the run-time value can never be aligned. 11548 if (BaseAlignment.getQuantity() >= Alignment && 11549 PtrAlign.getQuantity() < Alignment) 11550 return Success(0, E); 11551 // Otherwise we can't infer whether the value is sufficiently aligned. 11552 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11553 // in cases where we can't fully evaluate the pointer. 11554 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11555 << Alignment; 11556 return false; 11557 } 11558 assert(Src.isInt()); 11559 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11560 } 11561 case Builtin::BI__builtin_align_up: { 11562 APValue Src; 11563 APSInt Alignment; 11564 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11565 return false; 11566 if (!Src.isInt()) 11567 return Error(E); 11568 APSInt AlignedVal = 11569 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11570 Src.getInt().isUnsigned()); 11571 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11572 return Success(AlignedVal, E); 11573 } 11574 case Builtin::BI__builtin_align_down: { 11575 APValue Src; 11576 APSInt Alignment; 11577 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11578 return false; 11579 if (!Src.isInt()) 11580 return Error(E); 11581 APSInt AlignedVal = 11582 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11583 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11584 return Success(AlignedVal, E); 11585 } 11586 11587 case Builtin::BI__builtin_bitreverse8: 11588 case Builtin::BI__builtin_bitreverse16: 11589 case Builtin::BI__builtin_bitreverse32: 11590 case Builtin::BI__builtin_bitreverse64: { 11591 APSInt Val; 11592 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11593 return false; 11594 11595 return Success(Val.reverseBits(), E); 11596 } 11597 11598 case Builtin::BI__builtin_bswap16: 11599 case Builtin::BI__builtin_bswap32: 11600 case Builtin::BI__builtin_bswap64: { 11601 APSInt Val; 11602 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11603 return false; 11604 11605 return Success(Val.byteSwap(), E); 11606 } 11607 11608 case Builtin::BI__builtin_classify_type: 11609 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11610 11611 case Builtin::BI__builtin_clrsb: 11612 case Builtin::BI__builtin_clrsbl: 11613 case Builtin::BI__builtin_clrsbll: { 11614 APSInt Val; 11615 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11616 return false; 11617 11618 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11619 } 11620 11621 case Builtin::BI__builtin_clz: 11622 case Builtin::BI__builtin_clzl: 11623 case Builtin::BI__builtin_clzll: 11624 case Builtin::BI__builtin_clzs: { 11625 APSInt Val; 11626 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11627 return false; 11628 if (!Val) 11629 return Error(E); 11630 11631 return Success(Val.countLeadingZeros(), E); 11632 } 11633 11634 case Builtin::BI__builtin_constant_p: { 11635 const Expr *Arg = E->getArg(0); 11636 if (EvaluateBuiltinConstantP(Info, Arg)) 11637 return Success(true, E); 11638 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11639 // Outside a constant context, eagerly evaluate to false in the presence 11640 // of side-effects in order to avoid -Wunsequenced false-positives in 11641 // a branch on __builtin_constant_p(expr). 11642 return Success(false, E); 11643 } 11644 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11645 return false; 11646 } 11647 11648 case Builtin::BI__builtin_is_constant_evaluated: { 11649 const auto *Callee = Info.CurrentCall->getCallee(); 11650 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11651 (Info.CallStackDepth == 1 || 11652 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11653 Callee->getIdentifier() && 11654 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11655 // FIXME: Find a better way to avoid duplicated diagnostics. 11656 if (Info.EvalStatus.Diag) 11657 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11658 : Info.CurrentCall->CallLoc, 11659 diag::warn_is_constant_evaluated_always_true_constexpr) 11660 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11661 : "std::is_constant_evaluated"); 11662 } 11663 11664 return Success(Info.InConstantContext, E); 11665 } 11666 11667 case Builtin::BI__builtin_ctz: 11668 case Builtin::BI__builtin_ctzl: 11669 case Builtin::BI__builtin_ctzll: 11670 case Builtin::BI__builtin_ctzs: { 11671 APSInt Val; 11672 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11673 return false; 11674 if (!Val) 11675 return Error(E); 11676 11677 return Success(Val.countTrailingZeros(), E); 11678 } 11679 11680 case Builtin::BI__builtin_eh_return_data_regno: { 11681 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11682 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11683 return Success(Operand, E); 11684 } 11685 11686 case Builtin::BI__builtin_expect: 11687 case Builtin::BI__builtin_expect_with_probability: 11688 return Visit(E->getArg(0)); 11689 11690 case Builtin::BI__builtin_ffs: 11691 case Builtin::BI__builtin_ffsl: 11692 case Builtin::BI__builtin_ffsll: { 11693 APSInt Val; 11694 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11695 return false; 11696 11697 unsigned N = Val.countTrailingZeros(); 11698 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11699 } 11700 11701 case Builtin::BI__builtin_fpclassify: { 11702 APFloat Val(0.0); 11703 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11704 return false; 11705 unsigned Arg; 11706 switch (Val.getCategory()) { 11707 case APFloat::fcNaN: Arg = 0; break; 11708 case APFloat::fcInfinity: Arg = 1; break; 11709 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11710 case APFloat::fcZero: Arg = 4; break; 11711 } 11712 return Visit(E->getArg(Arg)); 11713 } 11714 11715 case Builtin::BI__builtin_isinf_sign: { 11716 APFloat Val(0.0); 11717 return EvaluateFloat(E->getArg(0), Val, Info) && 11718 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11719 } 11720 11721 case Builtin::BI__builtin_isinf: { 11722 APFloat Val(0.0); 11723 return EvaluateFloat(E->getArg(0), Val, Info) && 11724 Success(Val.isInfinity() ? 1 : 0, E); 11725 } 11726 11727 case Builtin::BI__builtin_isfinite: { 11728 APFloat Val(0.0); 11729 return EvaluateFloat(E->getArg(0), Val, Info) && 11730 Success(Val.isFinite() ? 1 : 0, E); 11731 } 11732 11733 case Builtin::BI__builtin_isnan: { 11734 APFloat Val(0.0); 11735 return EvaluateFloat(E->getArg(0), Val, Info) && 11736 Success(Val.isNaN() ? 1 : 0, E); 11737 } 11738 11739 case Builtin::BI__builtin_isnormal: { 11740 APFloat Val(0.0); 11741 return EvaluateFloat(E->getArg(0), Val, Info) && 11742 Success(Val.isNormal() ? 1 : 0, E); 11743 } 11744 11745 case Builtin::BI__builtin_parity: 11746 case Builtin::BI__builtin_parityl: 11747 case Builtin::BI__builtin_parityll: { 11748 APSInt Val; 11749 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11750 return false; 11751 11752 return Success(Val.countPopulation() % 2, E); 11753 } 11754 11755 case Builtin::BI__builtin_popcount: 11756 case Builtin::BI__builtin_popcountl: 11757 case Builtin::BI__builtin_popcountll: { 11758 APSInt Val; 11759 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11760 return false; 11761 11762 return Success(Val.countPopulation(), E); 11763 } 11764 11765 case Builtin::BI__builtin_rotateleft8: 11766 case Builtin::BI__builtin_rotateleft16: 11767 case Builtin::BI__builtin_rotateleft32: 11768 case Builtin::BI__builtin_rotateleft64: 11769 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11770 case Builtin::BI_rotl16: 11771 case Builtin::BI_rotl: 11772 case Builtin::BI_lrotl: 11773 case Builtin::BI_rotl64: { 11774 APSInt Val, Amt; 11775 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11776 !EvaluateInteger(E->getArg(1), Amt, Info)) 11777 return false; 11778 11779 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11780 } 11781 11782 case Builtin::BI__builtin_rotateright8: 11783 case Builtin::BI__builtin_rotateright16: 11784 case Builtin::BI__builtin_rotateright32: 11785 case Builtin::BI__builtin_rotateright64: 11786 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11787 case Builtin::BI_rotr16: 11788 case Builtin::BI_rotr: 11789 case Builtin::BI_lrotr: 11790 case Builtin::BI_rotr64: { 11791 APSInt Val, Amt; 11792 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11793 !EvaluateInteger(E->getArg(1), Amt, Info)) 11794 return false; 11795 11796 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11797 } 11798 11799 case Builtin::BIstrlen: 11800 case Builtin::BIwcslen: 11801 // A call to strlen is not a constant expression. 11802 if (Info.getLangOpts().CPlusPlus11) 11803 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11804 << /*isConstexpr*/0 << /*isConstructor*/0 11805 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11806 else 11807 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11808 LLVM_FALLTHROUGH; 11809 case Builtin::BI__builtin_strlen: 11810 case Builtin::BI__builtin_wcslen: { 11811 // As an extension, we support __builtin_strlen() as a constant expression, 11812 // and support folding strlen() to a constant. 11813 LValue String; 11814 if (!EvaluatePointer(E->getArg(0), String, Info)) 11815 return false; 11816 11817 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11818 11819 // Fast path: if it's a string literal, search the string value. 11820 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11821 String.getLValueBase().dyn_cast<const Expr *>())) { 11822 // The string literal may have embedded null characters. Find the first 11823 // one and truncate there. 11824 StringRef Str = S->getBytes(); 11825 int64_t Off = String.Offset.getQuantity(); 11826 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11827 S->getCharByteWidth() == 1 && 11828 // FIXME: Add fast-path for wchar_t too. 11829 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11830 Str = Str.substr(Off); 11831 11832 StringRef::size_type Pos = Str.find(0); 11833 if (Pos != StringRef::npos) 11834 Str = Str.substr(0, Pos); 11835 11836 return Success(Str.size(), E); 11837 } 11838 11839 // Fall through to slow path to issue appropriate diagnostic. 11840 } 11841 11842 // Slow path: scan the bytes of the string looking for the terminating 0. 11843 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11844 APValue Char; 11845 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11846 !Char.isInt()) 11847 return false; 11848 if (!Char.getInt()) 11849 return Success(Strlen, E); 11850 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11851 return false; 11852 } 11853 } 11854 11855 case Builtin::BIstrcmp: 11856 case Builtin::BIwcscmp: 11857 case Builtin::BIstrncmp: 11858 case Builtin::BIwcsncmp: 11859 case Builtin::BImemcmp: 11860 case Builtin::BIbcmp: 11861 case Builtin::BIwmemcmp: 11862 // A call to strlen is not a constant expression. 11863 if (Info.getLangOpts().CPlusPlus11) 11864 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11865 << /*isConstexpr*/0 << /*isConstructor*/0 11866 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11867 else 11868 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11869 LLVM_FALLTHROUGH; 11870 case Builtin::BI__builtin_strcmp: 11871 case Builtin::BI__builtin_wcscmp: 11872 case Builtin::BI__builtin_strncmp: 11873 case Builtin::BI__builtin_wcsncmp: 11874 case Builtin::BI__builtin_memcmp: 11875 case Builtin::BI__builtin_bcmp: 11876 case Builtin::BI__builtin_wmemcmp: { 11877 LValue String1, String2; 11878 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11879 !EvaluatePointer(E->getArg(1), String2, Info)) 11880 return false; 11881 11882 uint64_t MaxLength = uint64_t(-1); 11883 if (BuiltinOp != Builtin::BIstrcmp && 11884 BuiltinOp != Builtin::BIwcscmp && 11885 BuiltinOp != Builtin::BI__builtin_strcmp && 11886 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11887 APSInt N; 11888 if (!EvaluateInteger(E->getArg(2), N, Info)) 11889 return false; 11890 MaxLength = N.getExtValue(); 11891 } 11892 11893 // Empty substrings compare equal by definition. 11894 if (MaxLength == 0u) 11895 return Success(0, E); 11896 11897 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11898 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11899 String1.Designator.Invalid || String2.Designator.Invalid) 11900 return false; 11901 11902 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11903 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11904 11905 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11906 BuiltinOp == Builtin::BIbcmp || 11907 BuiltinOp == Builtin::BI__builtin_memcmp || 11908 BuiltinOp == Builtin::BI__builtin_bcmp; 11909 11910 assert(IsRawByte || 11911 (Info.Ctx.hasSameUnqualifiedType( 11912 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11913 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11914 11915 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11916 // 'char8_t', but no other types. 11917 if (IsRawByte && 11918 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11919 // FIXME: Consider using our bit_cast implementation to support this. 11920 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11921 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11922 << CharTy1 << CharTy2; 11923 return false; 11924 } 11925 11926 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11927 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11928 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11929 Char1.isInt() && Char2.isInt(); 11930 }; 11931 const auto &AdvanceElems = [&] { 11932 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11933 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11934 }; 11935 11936 bool StopAtNull = 11937 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11938 BuiltinOp != Builtin::BIwmemcmp && 11939 BuiltinOp != Builtin::BI__builtin_memcmp && 11940 BuiltinOp != Builtin::BI__builtin_bcmp && 11941 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11942 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11943 BuiltinOp == Builtin::BIwcsncmp || 11944 BuiltinOp == Builtin::BIwmemcmp || 11945 BuiltinOp == Builtin::BI__builtin_wcscmp || 11946 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11947 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11948 11949 for (; MaxLength; --MaxLength) { 11950 APValue Char1, Char2; 11951 if (!ReadCurElems(Char1, Char2)) 11952 return false; 11953 if (Char1.getInt().ne(Char2.getInt())) { 11954 if (IsWide) // wmemcmp compares with wchar_t signedness. 11955 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11956 // memcmp always compares unsigned chars. 11957 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11958 } 11959 if (StopAtNull && !Char1.getInt()) 11960 return Success(0, E); 11961 assert(!(StopAtNull && !Char2.getInt())); 11962 if (!AdvanceElems()) 11963 return false; 11964 } 11965 // We hit the strncmp / memcmp limit. 11966 return Success(0, E); 11967 } 11968 11969 case Builtin::BI__atomic_always_lock_free: 11970 case Builtin::BI__atomic_is_lock_free: 11971 case Builtin::BI__c11_atomic_is_lock_free: { 11972 APSInt SizeVal; 11973 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11974 return false; 11975 11976 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11977 // of two less than or equal to the maximum inline atomic width, we know it 11978 // is lock-free. If the size isn't a power of two, or greater than the 11979 // maximum alignment where we promote atomics, we know it is not lock-free 11980 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11981 // the answer can only be determined at runtime; for example, 16-byte 11982 // atomics have lock-free implementations on some, but not all, 11983 // x86-64 processors. 11984 11985 // Check power-of-two. 11986 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11987 if (Size.isPowerOfTwo()) { 11988 // Check against inlining width. 11989 unsigned InlineWidthBits = 11990 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11991 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11992 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11993 Size == CharUnits::One() || 11994 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11995 Expr::NPC_NeverValueDependent)) 11996 // OK, we will inline appropriately-aligned operations of this size, 11997 // and _Atomic(T) is appropriately-aligned. 11998 return Success(1, E); 11999 12000 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12001 castAs<PointerType>()->getPointeeType(); 12002 if (!PointeeType->isIncompleteType() && 12003 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12004 // OK, we will inline operations on this object. 12005 return Success(1, E); 12006 } 12007 } 12008 } 12009 12010 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12011 Success(0, E) : Error(E); 12012 } 12013 case Builtin::BIomp_is_initial_device: 12014 // We can decide statically which value the runtime would return if called. 12015 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 12016 case Builtin::BI__builtin_add_overflow: 12017 case Builtin::BI__builtin_sub_overflow: 12018 case Builtin::BI__builtin_mul_overflow: 12019 case Builtin::BI__builtin_sadd_overflow: 12020 case Builtin::BI__builtin_uadd_overflow: 12021 case Builtin::BI__builtin_uaddl_overflow: 12022 case Builtin::BI__builtin_uaddll_overflow: 12023 case Builtin::BI__builtin_usub_overflow: 12024 case Builtin::BI__builtin_usubl_overflow: 12025 case Builtin::BI__builtin_usubll_overflow: 12026 case Builtin::BI__builtin_umul_overflow: 12027 case Builtin::BI__builtin_umull_overflow: 12028 case Builtin::BI__builtin_umulll_overflow: 12029 case Builtin::BI__builtin_saddl_overflow: 12030 case Builtin::BI__builtin_saddll_overflow: 12031 case Builtin::BI__builtin_ssub_overflow: 12032 case Builtin::BI__builtin_ssubl_overflow: 12033 case Builtin::BI__builtin_ssubll_overflow: 12034 case Builtin::BI__builtin_smul_overflow: 12035 case Builtin::BI__builtin_smull_overflow: 12036 case Builtin::BI__builtin_smulll_overflow: { 12037 LValue ResultLValue; 12038 APSInt LHS, RHS; 12039 12040 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12041 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12042 !EvaluateInteger(E->getArg(1), RHS, Info) || 12043 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12044 return false; 12045 12046 APSInt Result; 12047 bool DidOverflow = false; 12048 12049 // If the types don't have to match, enlarge all 3 to the largest of them. 12050 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12051 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12052 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12053 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12054 ResultType->isSignedIntegerOrEnumerationType(); 12055 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12056 ResultType->isSignedIntegerOrEnumerationType(); 12057 uint64_t LHSSize = LHS.getBitWidth(); 12058 uint64_t RHSSize = RHS.getBitWidth(); 12059 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12060 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12061 12062 // Add an additional bit if the signedness isn't uniformly agreed to. We 12063 // could do this ONLY if there is a signed and an unsigned that both have 12064 // MaxBits, but the code to check that is pretty nasty. The issue will be 12065 // caught in the shrink-to-result later anyway. 12066 if (IsSigned && !AllSigned) 12067 ++MaxBits; 12068 12069 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12070 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12071 Result = APSInt(MaxBits, !IsSigned); 12072 } 12073 12074 // Find largest int. 12075 switch (BuiltinOp) { 12076 default: 12077 llvm_unreachable("Invalid value for BuiltinOp"); 12078 case Builtin::BI__builtin_add_overflow: 12079 case Builtin::BI__builtin_sadd_overflow: 12080 case Builtin::BI__builtin_saddl_overflow: 12081 case Builtin::BI__builtin_saddll_overflow: 12082 case Builtin::BI__builtin_uadd_overflow: 12083 case Builtin::BI__builtin_uaddl_overflow: 12084 case Builtin::BI__builtin_uaddll_overflow: 12085 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12086 : LHS.uadd_ov(RHS, DidOverflow); 12087 break; 12088 case Builtin::BI__builtin_sub_overflow: 12089 case Builtin::BI__builtin_ssub_overflow: 12090 case Builtin::BI__builtin_ssubl_overflow: 12091 case Builtin::BI__builtin_ssubll_overflow: 12092 case Builtin::BI__builtin_usub_overflow: 12093 case Builtin::BI__builtin_usubl_overflow: 12094 case Builtin::BI__builtin_usubll_overflow: 12095 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12096 : LHS.usub_ov(RHS, DidOverflow); 12097 break; 12098 case Builtin::BI__builtin_mul_overflow: 12099 case Builtin::BI__builtin_smul_overflow: 12100 case Builtin::BI__builtin_smull_overflow: 12101 case Builtin::BI__builtin_smulll_overflow: 12102 case Builtin::BI__builtin_umul_overflow: 12103 case Builtin::BI__builtin_umull_overflow: 12104 case Builtin::BI__builtin_umulll_overflow: 12105 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12106 : LHS.umul_ov(RHS, DidOverflow); 12107 break; 12108 } 12109 12110 // In the case where multiple sizes are allowed, truncate and see if 12111 // the values are the same. 12112 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12113 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12114 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12115 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12116 // since it will give us the behavior of a TruncOrSelf in the case where 12117 // its parameter <= its size. We previously set Result to be at least the 12118 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12119 // will work exactly like TruncOrSelf. 12120 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12121 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12122 12123 if (!APSInt::isSameValue(Temp, Result)) 12124 DidOverflow = true; 12125 Result = Temp; 12126 } 12127 12128 APValue APV{Result}; 12129 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12130 return false; 12131 return Success(DidOverflow, E); 12132 } 12133 } 12134 } 12135 12136 /// Determine whether this is a pointer past the end of the complete 12137 /// object referred to by the lvalue. 12138 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12139 const LValue &LV) { 12140 // A null pointer can be viewed as being "past the end" but we don't 12141 // choose to look at it that way here. 12142 if (!LV.getLValueBase()) 12143 return false; 12144 12145 // If the designator is valid and refers to a subobject, we're not pointing 12146 // past the end. 12147 if (!LV.getLValueDesignator().Invalid && 12148 !LV.getLValueDesignator().isOnePastTheEnd()) 12149 return false; 12150 12151 // A pointer to an incomplete type might be past-the-end if the type's size is 12152 // zero. We cannot tell because the type is incomplete. 12153 QualType Ty = getType(LV.getLValueBase()); 12154 if (Ty->isIncompleteType()) 12155 return true; 12156 12157 // We're a past-the-end pointer if we point to the byte after the object, 12158 // no matter what our type or path is. 12159 auto Size = Ctx.getTypeSizeInChars(Ty); 12160 return LV.getLValueOffset() == Size; 12161 } 12162 12163 namespace { 12164 12165 /// Data recursive integer evaluator of certain binary operators. 12166 /// 12167 /// We use a data recursive algorithm for binary operators so that we are able 12168 /// to handle extreme cases of chained binary operators without causing stack 12169 /// overflow. 12170 class DataRecursiveIntBinOpEvaluator { 12171 struct EvalResult { 12172 APValue Val; 12173 bool Failed; 12174 12175 EvalResult() : Failed(false) { } 12176 12177 void swap(EvalResult &RHS) { 12178 Val.swap(RHS.Val); 12179 Failed = RHS.Failed; 12180 RHS.Failed = false; 12181 } 12182 }; 12183 12184 struct Job { 12185 const Expr *E; 12186 EvalResult LHSResult; // meaningful only for binary operator expression. 12187 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12188 12189 Job() = default; 12190 Job(Job &&) = default; 12191 12192 void startSpeculativeEval(EvalInfo &Info) { 12193 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12194 } 12195 12196 private: 12197 SpeculativeEvaluationRAII SpecEvalRAII; 12198 }; 12199 12200 SmallVector<Job, 16> Queue; 12201 12202 IntExprEvaluator &IntEval; 12203 EvalInfo &Info; 12204 APValue &FinalResult; 12205 12206 public: 12207 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12208 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12209 12210 /// True if \param E is a binary operator that we are going to handle 12211 /// data recursively. 12212 /// We handle binary operators that are comma, logical, or that have operands 12213 /// with integral or enumeration type. 12214 static bool shouldEnqueue(const BinaryOperator *E) { 12215 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12216 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 12217 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12218 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12219 } 12220 12221 bool Traverse(const BinaryOperator *E) { 12222 enqueue(E); 12223 EvalResult PrevResult; 12224 while (!Queue.empty()) 12225 process(PrevResult); 12226 12227 if (PrevResult.Failed) return false; 12228 12229 FinalResult.swap(PrevResult.Val); 12230 return true; 12231 } 12232 12233 private: 12234 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12235 return IntEval.Success(Value, E, Result); 12236 } 12237 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12238 return IntEval.Success(Value, E, Result); 12239 } 12240 bool Error(const Expr *E) { 12241 return IntEval.Error(E); 12242 } 12243 bool Error(const Expr *E, diag::kind D) { 12244 return IntEval.Error(E, D); 12245 } 12246 12247 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12248 return Info.CCEDiag(E, D); 12249 } 12250 12251 // Returns true if visiting the RHS is necessary, false otherwise. 12252 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12253 bool &SuppressRHSDiags); 12254 12255 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12256 const BinaryOperator *E, APValue &Result); 12257 12258 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12259 Result.Failed = !Evaluate(Result.Val, Info, E); 12260 if (Result.Failed) 12261 Result.Val = APValue(); 12262 } 12263 12264 void process(EvalResult &Result); 12265 12266 void enqueue(const Expr *E) { 12267 E = E->IgnoreParens(); 12268 Queue.resize(Queue.size()+1); 12269 Queue.back().E = E; 12270 Queue.back().Kind = Job::AnyExprKind; 12271 } 12272 }; 12273 12274 } 12275 12276 bool DataRecursiveIntBinOpEvaluator:: 12277 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12278 bool &SuppressRHSDiags) { 12279 if (E->getOpcode() == BO_Comma) { 12280 // Ignore LHS but note if we could not evaluate it. 12281 if (LHSResult.Failed) 12282 return Info.noteSideEffect(); 12283 return true; 12284 } 12285 12286 if (E->isLogicalOp()) { 12287 bool LHSAsBool; 12288 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12289 // We were able to evaluate the LHS, see if we can get away with not 12290 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12291 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12292 Success(LHSAsBool, E, LHSResult.Val); 12293 return false; // Ignore RHS 12294 } 12295 } else { 12296 LHSResult.Failed = true; 12297 12298 // Since we weren't able to evaluate the left hand side, it 12299 // might have had side effects. 12300 if (!Info.noteSideEffect()) 12301 return false; 12302 12303 // We can't evaluate the LHS; however, sometimes the result 12304 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12305 // Don't ignore RHS and suppress diagnostics from this arm. 12306 SuppressRHSDiags = true; 12307 } 12308 12309 return true; 12310 } 12311 12312 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12313 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12314 12315 if (LHSResult.Failed && !Info.noteFailure()) 12316 return false; // Ignore RHS; 12317 12318 return true; 12319 } 12320 12321 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12322 bool IsSub) { 12323 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12324 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12325 // offsets. 12326 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12327 CharUnits &Offset = LVal.getLValueOffset(); 12328 uint64_t Offset64 = Offset.getQuantity(); 12329 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12330 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12331 : Offset64 + Index64); 12332 } 12333 12334 bool DataRecursiveIntBinOpEvaluator:: 12335 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12336 const BinaryOperator *E, APValue &Result) { 12337 if (E->getOpcode() == BO_Comma) { 12338 if (RHSResult.Failed) 12339 return false; 12340 Result = RHSResult.Val; 12341 return true; 12342 } 12343 12344 if (E->isLogicalOp()) { 12345 bool lhsResult, rhsResult; 12346 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12347 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12348 12349 if (LHSIsOK) { 12350 if (RHSIsOK) { 12351 if (E->getOpcode() == BO_LOr) 12352 return Success(lhsResult || rhsResult, E, Result); 12353 else 12354 return Success(lhsResult && rhsResult, E, Result); 12355 } 12356 } else { 12357 if (RHSIsOK) { 12358 // We can't evaluate the LHS; however, sometimes the result 12359 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12360 if (rhsResult == (E->getOpcode() == BO_LOr)) 12361 return Success(rhsResult, E, Result); 12362 } 12363 } 12364 12365 return false; 12366 } 12367 12368 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12369 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12370 12371 if (LHSResult.Failed || RHSResult.Failed) 12372 return false; 12373 12374 const APValue &LHSVal = LHSResult.Val; 12375 const APValue &RHSVal = RHSResult.Val; 12376 12377 // Handle cases like (unsigned long)&a + 4. 12378 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12379 Result = LHSVal; 12380 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12381 return true; 12382 } 12383 12384 // Handle cases like 4 + (unsigned long)&a 12385 if (E->getOpcode() == BO_Add && 12386 RHSVal.isLValue() && LHSVal.isInt()) { 12387 Result = RHSVal; 12388 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12389 return true; 12390 } 12391 12392 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12393 // Handle (intptr_t)&&A - (intptr_t)&&B. 12394 if (!LHSVal.getLValueOffset().isZero() || 12395 !RHSVal.getLValueOffset().isZero()) 12396 return false; 12397 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12398 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12399 if (!LHSExpr || !RHSExpr) 12400 return false; 12401 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12402 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12403 if (!LHSAddrExpr || !RHSAddrExpr) 12404 return false; 12405 // Make sure both labels come from the same function. 12406 if (LHSAddrExpr->getLabel()->getDeclContext() != 12407 RHSAddrExpr->getLabel()->getDeclContext()) 12408 return false; 12409 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12410 return true; 12411 } 12412 12413 // All the remaining cases expect both operands to be an integer 12414 if (!LHSVal.isInt() || !RHSVal.isInt()) 12415 return Error(E); 12416 12417 // Set up the width and signedness manually, in case it can't be deduced 12418 // from the operation we're performing. 12419 // FIXME: Don't do this in the cases where we can deduce it. 12420 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12421 E->getType()->isUnsignedIntegerOrEnumerationType()); 12422 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12423 RHSVal.getInt(), Value)) 12424 return false; 12425 return Success(Value, E, Result); 12426 } 12427 12428 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12429 Job &job = Queue.back(); 12430 12431 switch (job.Kind) { 12432 case Job::AnyExprKind: { 12433 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12434 if (shouldEnqueue(Bop)) { 12435 job.Kind = Job::BinOpKind; 12436 enqueue(Bop->getLHS()); 12437 return; 12438 } 12439 } 12440 12441 EvaluateExpr(job.E, Result); 12442 Queue.pop_back(); 12443 return; 12444 } 12445 12446 case Job::BinOpKind: { 12447 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12448 bool SuppressRHSDiags = false; 12449 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12450 Queue.pop_back(); 12451 return; 12452 } 12453 if (SuppressRHSDiags) 12454 job.startSpeculativeEval(Info); 12455 job.LHSResult.swap(Result); 12456 job.Kind = Job::BinOpVisitedLHSKind; 12457 enqueue(Bop->getRHS()); 12458 return; 12459 } 12460 12461 case Job::BinOpVisitedLHSKind: { 12462 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12463 EvalResult RHS; 12464 RHS.swap(Result); 12465 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12466 Queue.pop_back(); 12467 return; 12468 } 12469 } 12470 12471 llvm_unreachable("Invalid Job::Kind!"); 12472 } 12473 12474 namespace { 12475 enum class CmpResult { 12476 Unequal, 12477 Less, 12478 Equal, 12479 Greater, 12480 Unordered, 12481 }; 12482 } 12483 12484 template <class SuccessCB, class AfterCB> 12485 static bool 12486 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12487 SuccessCB &&Success, AfterCB &&DoAfter) { 12488 assert(!E->isValueDependent()); 12489 assert(E->isComparisonOp() && "expected comparison operator"); 12490 assert((E->getOpcode() == BO_Cmp || 12491 E->getType()->isIntegralOrEnumerationType()) && 12492 "unsupported binary expression evaluation"); 12493 auto Error = [&](const Expr *E) { 12494 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12495 return false; 12496 }; 12497 12498 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12499 bool IsEquality = E->isEqualityOp(); 12500 12501 QualType LHSTy = E->getLHS()->getType(); 12502 QualType RHSTy = E->getRHS()->getType(); 12503 12504 if (LHSTy->isIntegralOrEnumerationType() && 12505 RHSTy->isIntegralOrEnumerationType()) { 12506 APSInt LHS, RHS; 12507 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12508 if (!LHSOK && !Info.noteFailure()) 12509 return false; 12510 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12511 return false; 12512 if (LHS < RHS) 12513 return Success(CmpResult::Less, E); 12514 if (LHS > RHS) 12515 return Success(CmpResult::Greater, E); 12516 return Success(CmpResult::Equal, E); 12517 } 12518 12519 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12520 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12521 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12522 12523 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12524 if (!LHSOK && !Info.noteFailure()) 12525 return false; 12526 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12527 return false; 12528 if (LHSFX < RHSFX) 12529 return Success(CmpResult::Less, E); 12530 if (LHSFX > RHSFX) 12531 return Success(CmpResult::Greater, E); 12532 return Success(CmpResult::Equal, E); 12533 } 12534 12535 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12536 ComplexValue LHS, RHS; 12537 bool LHSOK; 12538 if (E->isAssignmentOp()) { 12539 LValue LV; 12540 EvaluateLValue(E->getLHS(), LV, Info); 12541 LHSOK = false; 12542 } else if (LHSTy->isRealFloatingType()) { 12543 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12544 if (LHSOK) { 12545 LHS.makeComplexFloat(); 12546 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12547 } 12548 } else { 12549 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12550 } 12551 if (!LHSOK && !Info.noteFailure()) 12552 return false; 12553 12554 if (E->getRHS()->getType()->isRealFloatingType()) { 12555 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12556 return false; 12557 RHS.makeComplexFloat(); 12558 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12559 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12560 return false; 12561 12562 if (LHS.isComplexFloat()) { 12563 APFloat::cmpResult CR_r = 12564 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12565 APFloat::cmpResult CR_i = 12566 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12567 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12568 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12569 } else { 12570 assert(IsEquality && "invalid complex comparison"); 12571 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12572 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12573 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12574 } 12575 } 12576 12577 if (LHSTy->isRealFloatingType() && 12578 RHSTy->isRealFloatingType()) { 12579 APFloat RHS(0.0), LHS(0.0); 12580 12581 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12582 if (!LHSOK && !Info.noteFailure()) 12583 return false; 12584 12585 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12586 return false; 12587 12588 assert(E->isComparisonOp() && "Invalid binary operator!"); 12589 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12590 if (!Info.InConstantContext && 12591 APFloatCmpResult == APFloat::cmpUnordered && 12592 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12593 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12594 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12595 return false; 12596 } 12597 auto GetCmpRes = [&]() { 12598 switch (APFloatCmpResult) { 12599 case APFloat::cmpEqual: 12600 return CmpResult::Equal; 12601 case APFloat::cmpLessThan: 12602 return CmpResult::Less; 12603 case APFloat::cmpGreaterThan: 12604 return CmpResult::Greater; 12605 case APFloat::cmpUnordered: 12606 return CmpResult::Unordered; 12607 } 12608 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12609 }; 12610 return Success(GetCmpRes(), E); 12611 } 12612 12613 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12614 LValue LHSValue, RHSValue; 12615 12616 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12617 if (!LHSOK && !Info.noteFailure()) 12618 return false; 12619 12620 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12621 return false; 12622 12623 // Reject differing bases from the normal codepath; we special-case 12624 // comparisons to null. 12625 if (!HasSameBase(LHSValue, RHSValue)) { 12626 // Inequalities and subtractions between unrelated pointers have 12627 // unspecified or undefined behavior. 12628 if (!IsEquality) { 12629 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12630 return false; 12631 } 12632 // A constant address may compare equal to the address of a symbol. 12633 // The one exception is that address of an object cannot compare equal 12634 // to a null pointer constant. 12635 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12636 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12637 return Error(E); 12638 // It's implementation-defined whether distinct literals will have 12639 // distinct addresses. In clang, the result of such a comparison is 12640 // unspecified, so it is not a constant expression. However, we do know 12641 // that the address of a literal will be non-null. 12642 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12643 LHSValue.Base && RHSValue.Base) 12644 return Error(E); 12645 // We can't tell whether weak symbols will end up pointing to the same 12646 // object. 12647 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12648 return Error(E); 12649 // We can't compare the address of the start of one object with the 12650 // past-the-end address of another object, per C++ DR1652. 12651 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12652 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12653 (RHSValue.Base && RHSValue.Offset.isZero() && 12654 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12655 return Error(E); 12656 // We can't tell whether an object is at the same address as another 12657 // zero sized object. 12658 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12659 (LHSValue.Base && isZeroSized(RHSValue))) 12660 return Error(E); 12661 return Success(CmpResult::Unequal, E); 12662 } 12663 12664 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12665 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12666 12667 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12668 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12669 12670 // C++11 [expr.rel]p3: 12671 // Pointers to void (after pointer conversions) can be compared, with a 12672 // result defined as follows: If both pointers represent the same 12673 // address or are both the null pointer value, the result is true if the 12674 // operator is <= or >= and false otherwise; otherwise the result is 12675 // unspecified. 12676 // We interpret this as applying to pointers to *cv* void. 12677 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12678 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12679 12680 // C++11 [expr.rel]p2: 12681 // - If two pointers point to non-static data members of the same object, 12682 // or to subobjects or array elements fo such members, recursively, the 12683 // pointer to the later declared member compares greater provided the 12684 // two members have the same access control and provided their class is 12685 // not a union. 12686 // [...] 12687 // - Otherwise pointer comparisons are unspecified. 12688 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12689 bool WasArrayIndex; 12690 unsigned Mismatch = FindDesignatorMismatch( 12691 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12692 // At the point where the designators diverge, the comparison has a 12693 // specified value if: 12694 // - we are comparing array indices 12695 // - we are comparing fields of a union, or fields with the same access 12696 // Otherwise, the result is unspecified and thus the comparison is not a 12697 // constant expression. 12698 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12699 Mismatch < RHSDesignator.Entries.size()) { 12700 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12701 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12702 if (!LF && !RF) 12703 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12704 else if (!LF) 12705 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12706 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12707 << RF->getParent() << RF; 12708 else if (!RF) 12709 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12710 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12711 << LF->getParent() << LF; 12712 else if (!LF->getParent()->isUnion() && 12713 LF->getAccess() != RF->getAccess()) 12714 Info.CCEDiag(E, 12715 diag::note_constexpr_pointer_comparison_differing_access) 12716 << LF << LF->getAccess() << RF << RF->getAccess() 12717 << LF->getParent(); 12718 } 12719 } 12720 12721 // The comparison here must be unsigned, and performed with the same 12722 // width as the pointer. 12723 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12724 uint64_t CompareLHS = LHSOffset.getQuantity(); 12725 uint64_t CompareRHS = RHSOffset.getQuantity(); 12726 assert(PtrSize <= 64 && "Unexpected pointer width"); 12727 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12728 CompareLHS &= Mask; 12729 CompareRHS &= Mask; 12730 12731 // If there is a base and this is a relational operator, we can only 12732 // compare pointers within the object in question; otherwise, the result 12733 // depends on where the object is located in memory. 12734 if (!LHSValue.Base.isNull() && IsRelational) { 12735 QualType BaseTy = getType(LHSValue.Base); 12736 if (BaseTy->isIncompleteType()) 12737 return Error(E); 12738 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12739 uint64_t OffsetLimit = Size.getQuantity(); 12740 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12741 return Error(E); 12742 } 12743 12744 if (CompareLHS < CompareRHS) 12745 return Success(CmpResult::Less, E); 12746 if (CompareLHS > CompareRHS) 12747 return Success(CmpResult::Greater, E); 12748 return Success(CmpResult::Equal, E); 12749 } 12750 12751 if (LHSTy->isMemberPointerType()) { 12752 assert(IsEquality && "unexpected member pointer operation"); 12753 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12754 12755 MemberPtr LHSValue, RHSValue; 12756 12757 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12758 if (!LHSOK && !Info.noteFailure()) 12759 return false; 12760 12761 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12762 return false; 12763 12764 // C++11 [expr.eq]p2: 12765 // If both operands are null, they compare equal. Otherwise if only one is 12766 // null, they compare unequal. 12767 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12768 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12769 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12770 } 12771 12772 // Otherwise if either is a pointer to a virtual member function, the 12773 // result is unspecified. 12774 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12775 if (MD->isVirtual()) 12776 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12777 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12778 if (MD->isVirtual()) 12779 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12780 12781 // Otherwise they compare equal if and only if they would refer to the 12782 // same member of the same most derived object or the same subobject if 12783 // they were dereferenced with a hypothetical object of the associated 12784 // class type. 12785 bool Equal = LHSValue == RHSValue; 12786 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12787 } 12788 12789 if (LHSTy->isNullPtrType()) { 12790 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12791 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12792 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12793 // are compared, the result is true of the operator is <=, >= or ==, and 12794 // false otherwise. 12795 return Success(CmpResult::Equal, E); 12796 } 12797 12798 return DoAfter(); 12799 } 12800 12801 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12802 if (!CheckLiteralType(Info, E)) 12803 return false; 12804 12805 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12806 ComparisonCategoryResult CCR; 12807 switch (CR) { 12808 case CmpResult::Unequal: 12809 llvm_unreachable("should never produce Unequal for three-way comparison"); 12810 case CmpResult::Less: 12811 CCR = ComparisonCategoryResult::Less; 12812 break; 12813 case CmpResult::Equal: 12814 CCR = ComparisonCategoryResult::Equal; 12815 break; 12816 case CmpResult::Greater: 12817 CCR = ComparisonCategoryResult::Greater; 12818 break; 12819 case CmpResult::Unordered: 12820 CCR = ComparisonCategoryResult::Unordered; 12821 break; 12822 } 12823 // Evaluation succeeded. Lookup the information for the comparison category 12824 // type and fetch the VarDecl for the result. 12825 const ComparisonCategoryInfo &CmpInfo = 12826 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12827 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12828 // Check and evaluate the result as a constant expression. 12829 LValue LV; 12830 LV.set(VD); 12831 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12832 return false; 12833 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12834 ConstantExprKind::Normal); 12835 }; 12836 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12837 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12838 }); 12839 } 12840 12841 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12842 // We don't support assignment in C. C++ assignments don't get here because 12843 // assignment is an lvalue in C++. 12844 if (E->isAssignmentOp()) { 12845 Error(E); 12846 if (!Info.noteFailure()) 12847 return false; 12848 } 12849 12850 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12851 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12852 12853 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12854 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12855 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12856 12857 if (E->isComparisonOp()) { 12858 // Evaluate builtin binary comparisons by evaluating them as three-way 12859 // comparisons and then translating the result. 12860 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12861 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12862 "should only produce Unequal for equality comparisons"); 12863 bool IsEqual = CR == CmpResult::Equal, 12864 IsLess = CR == CmpResult::Less, 12865 IsGreater = CR == CmpResult::Greater; 12866 auto Op = E->getOpcode(); 12867 switch (Op) { 12868 default: 12869 llvm_unreachable("unsupported binary operator"); 12870 case BO_EQ: 12871 case BO_NE: 12872 return Success(IsEqual == (Op == BO_EQ), E); 12873 case BO_LT: 12874 return Success(IsLess, E); 12875 case BO_GT: 12876 return Success(IsGreater, E); 12877 case BO_LE: 12878 return Success(IsEqual || IsLess, E); 12879 case BO_GE: 12880 return Success(IsEqual || IsGreater, E); 12881 } 12882 }; 12883 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12884 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12885 }); 12886 } 12887 12888 QualType LHSTy = E->getLHS()->getType(); 12889 QualType RHSTy = E->getRHS()->getType(); 12890 12891 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12892 E->getOpcode() == BO_Sub) { 12893 LValue LHSValue, RHSValue; 12894 12895 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12896 if (!LHSOK && !Info.noteFailure()) 12897 return false; 12898 12899 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12900 return false; 12901 12902 // Reject differing bases from the normal codepath; we special-case 12903 // comparisons to null. 12904 if (!HasSameBase(LHSValue, RHSValue)) { 12905 // Handle &&A - &&B. 12906 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12907 return Error(E); 12908 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12909 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12910 if (!LHSExpr || !RHSExpr) 12911 return Error(E); 12912 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12913 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12914 if (!LHSAddrExpr || !RHSAddrExpr) 12915 return Error(E); 12916 // Make sure both labels come from the same function. 12917 if (LHSAddrExpr->getLabel()->getDeclContext() != 12918 RHSAddrExpr->getLabel()->getDeclContext()) 12919 return Error(E); 12920 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12921 } 12922 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12923 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12924 12925 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12926 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12927 12928 // C++11 [expr.add]p6: 12929 // Unless both pointers point to elements of the same array object, or 12930 // one past the last element of the array object, the behavior is 12931 // undefined. 12932 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12933 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12934 RHSDesignator)) 12935 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12936 12937 QualType Type = E->getLHS()->getType(); 12938 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12939 12940 CharUnits ElementSize; 12941 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12942 return false; 12943 12944 // As an extension, a type may have zero size (empty struct or union in 12945 // C, array of zero length). Pointer subtraction in such cases has 12946 // undefined behavior, so is not constant. 12947 if (ElementSize.isZero()) { 12948 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12949 << ElementType; 12950 return false; 12951 } 12952 12953 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12954 // and produce incorrect results when it overflows. Such behavior 12955 // appears to be non-conforming, but is common, so perhaps we should 12956 // assume the standard intended for such cases to be undefined behavior 12957 // and check for them. 12958 12959 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12960 // overflow in the final conversion to ptrdiff_t. 12961 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12962 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12963 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12964 false); 12965 APSInt TrueResult = (LHS - RHS) / ElemSize; 12966 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12967 12968 if (Result.extend(65) != TrueResult && 12969 !HandleOverflow(Info, E, TrueResult, E->getType())) 12970 return false; 12971 return Success(Result, E); 12972 } 12973 12974 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12975 } 12976 12977 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12978 /// a result as the expression's type. 12979 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12980 const UnaryExprOrTypeTraitExpr *E) { 12981 switch(E->getKind()) { 12982 case UETT_PreferredAlignOf: 12983 case UETT_AlignOf: { 12984 if (E->isArgumentType()) 12985 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12986 E); 12987 else 12988 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12989 E); 12990 } 12991 12992 case UETT_VecStep: { 12993 QualType Ty = E->getTypeOfArgument(); 12994 12995 if (Ty->isVectorType()) { 12996 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12997 12998 // The vec_step built-in functions that take a 3-component 12999 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13000 if (n == 3) 13001 n = 4; 13002 13003 return Success(n, E); 13004 } else 13005 return Success(1, E); 13006 } 13007 13008 case UETT_SizeOf: { 13009 QualType SrcTy = E->getTypeOfArgument(); 13010 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13011 // the result is the size of the referenced type." 13012 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13013 SrcTy = Ref->getPointeeType(); 13014 13015 CharUnits Sizeof; 13016 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13017 return false; 13018 return Success(Sizeof, E); 13019 } 13020 case UETT_OpenMPRequiredSimdAlign: 13021 assert(E->isArgumentType()); 13022 return Success( 13023 Info.Ctx.toCharUnitsFromBits( 13024 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13025 .getQuantity(), 13026 E); 13027 } 13028 13029 llvm_unreachable("unknown expr/type trait"); 13030 } 13031 13032 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13033 CharUnits Result; 13034 unsigned n = OOE->getNumComponents(); 13035 if (n == 0) 13036 return Error(OOE); 13037 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13038 for (unsigned i = 0; i != n; ++i) { 13039 OffsetOfNode ON = OOE->getComponent(i); 13040 switch (ON.getKind()) { 13041 case OffsetOfNode::Array: { 13042 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13043 APSInt IdxResult; 13044 if (!EvaluateInteger(Idx, IdxResult, Info)) 13045 return false; 13046 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13047 if (!AT) 13048 return Error(OOE); 13049 CurrentType = AT->getElementType(); 13050 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13051 Result += IdxResult.getSExtValue() * ElementSize; 13052 break; 13053 } 13054 13055 case OffsetOfNode::Field: { 13056 FieldDecl *MemberDecl = ON.getField(); 13057 const RecordType *RT = CurrentType->getAs<RecordType>(); 13058 if (!RT) 13059 return Error(OOE); 13060 RecordDecl *RD = RT->getDecl(); 13061 if (RD->isInvalidDecl()) return false; 13062 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13063 unsigned i = MemberDecl->getFieldIndex(); 13064 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13065 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13066 CurrentType = MemberDecl->getType().getNonReferenceType(); 13067 break; 13068 } 13069 13070 case OffsetOfNode::Identifier: 13071 llvm_unreachable("dependent __builtin_offsetof"); 13072 13073 case OffsetOfNode::Base: { 13074 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13075 if (BaseSpec->isVirtual()) 13076 return Error(OOE); 13077 13078 // Find the layout of the class whose base we are looking into. 13079 const RecordType *RT = CurrentType->getAs<RecordType>(); 13080 if (!RT) 13081 return Error(OOE); 13082 RecordDecl *RD = RT->getDecl(); 13083 if (RD->isInvalidDecl()) return false; 13084 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13085 13086 // Find the base class itself. 13087 CurrentType = BaseSpec->getType(); 13088 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13089 if (!BaseRT) 13090 return Error(OOE); 13091 13092 // Add the offset to the base. 13093 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13094 break; 13095 } 13096 } 13097 } 13098 return Success(Result, OOE); 13099 } 13100 13101 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13102 switch (E->getOpcode()) { 13103 default: 13104 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13105 // See C99 6.6p3. 13106 return Error(E); 13107 case UO_Extension: 13108 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13109 // If so, we could clear the diagnostic ID. 13110 return Visit(E->getSubExpr()); 13111 case UO_Plus: 13112 // The result is just the value. 13113 return Visit(E->getSubExpr()); 13114 case UO_Minus: { 13115 if (!Visit(E->getSubExpr())) 13116 return false; 13117 if (!Result.isInt()) return Error(E); 13118 const APSInt &Value = Result.getInt(); 13119 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13120 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13121 E->getType())) 13122 return false; 13123 return Success(-Value, E); 13124 } 13125 case UO_Not: { 13126 if (!Visit(E->getSubExpr())) 13127 return false; 13128 if (!Result.isInt()) return Error(E); 13129 return Success(~Result.getInt(), E); 13130 } 13131 case UO_LNot: { 13132 bool bres; 13133 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13134 return false; 13135 return Success(!bres, E); 13136 } 13137 } 13138 } 13139 13140 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13141 /// result type is integer. 13142 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13143 const Expr *SubExpr = E->getSubExpr(); 13144 QualType DestType = E->getType(); 13145 QualType SrcType = SubExpr->getType(); 13146 13147 switch (E->getCastKind()) { 13148 case CK_BaseToDerived: 13149 case CK_DerivedToBase: 13150 case CK_UncheckedDerivedToBase: 13151 case CK_Dynamic: 13152 case CK_ToUnion: 13153 case CK_ArrayToPointerDecay: 13154 case CK_FunctionToPointerDecay: 13155 case CK_NullToPointer: 13156 case CK_NullToMemberPointer: 13157 case CK_BaseToDerivedMemberPointer: 13158 case CK_DerivedToBaseMemberPointer: 13159 case CK_ReinterpretMemberPointer: 13160 case CK_ConstructorConversion: 13161 case CK_IntegralToPointer: 13162 case CK_ToVoid: 13163 case CK_VectorSplat: 13164 case CK_IntegralToFloating: 13165 case CK_FloatingCast: 13166 case CK_CPointerToObjCPointerCast: 13167 case CK_BlockPointerToObjCPointerCast: 13168 case CK_AnyPointerToBlockPointerCast: 13169 case CK_ObjCObjectLValueCast: 13170 case CK_FloatingRealToComplex: 13171 case CK_FloatingComplexToReal: 13172 case CK_FloatingComplexCast: 13173 case CK_FloatingComplexToIntegralComplex: 13174 case CK_IntegralRealToComplex: 13175 case CK_IntegralComplexCast: 13176 case CK_IntegralComplexToFloatingComplex: 13177 case CK_BuiltinFnToFnPtr: 13178 case CK_ZeroToOCLOpaqueType: 13179 case CK_NonAtomicToAtomic: 13180 case CK_AddressSpaceConversion: 13181 case CK_IntToOCLSampler: 13182 case CK_FloatingToFixedPoint: 13183 case CK_FixedPointToFloating: 13184 case CK_FixedPointCast: 13185 case CK_IntegralToFixedPoint: 13186 llvm_unreachable("invalid cast kind for integral value"); 13187 13188 case CK_BitCast: 13189 case CK_Dependent: 13190 case CK_LValueBitCast: 13191 case CK_ARCProduceObject: 13192 case CK_ARCConsumeObject: 13193 case CK_ARCReclaimReturnedObject: 13194 case CK_ARCExtendBlockObject: 13195 case CK_CopyAndAutoreleaseBlockObject: 13196 return Error(E); 13197 13198 case CK_UserDefinedConversion: 13199 case CK_LValueToRValue: 13200 case CK_AtomicToNonAtomic: 13201 case CK_NoOp: 13202 case CK_LValueToRValueBitCast: 13203 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13204 13205 case CK_MemberPointerToBoolean: 13206 case CK_PointerToBoolean: 13207 case CK_IntegralToBoolean: 13208 case CK_FloatingToBoolean: 13209 case CK_BooleanToSignedIntegral: 13210 case CK_FloatingComplexToBoolean: 13211 case CK_IntegralComplexToBoolean: { 13212 bool BoolResult; 13213 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13214 return false; 13215 uint64_t IntResult = BoolResult; 13216 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13217 IntResult = (uint64_t)-1; 13218 return Success(IntResult, E); 13219 } 13220 13221 case CK_FixedPointToIntegral: { 13222 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13223 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13224 return false; 13225 bool Overflowed; 13226 llvm::APSInt Result = Src.convertToInt( 13227 Info.Ctx.getIntWidth(DestType), 13228 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13229 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13230 return false; 13231 return Success(Result, E); 13232 } 13233 13234 case CK_FixedPointToBoolean: { 13235 // Unsigned padding does not affect this. 13236 APValue Val; 13237 if (!Evaluate(Val, Info, SubExpr)) 13238 return false; 13239 return Success(Val.getFixedPoint().getBoolValue(), E); 13240 } 13241 13242 case CK_IntegralCast: { 13243 if (!Visit(SubExpr)) 13244 return false; 13245 13246 if (!Result.isInt()) { 13247 // Allow casts of address-of-label differences if they are no-ops 13248 // or narrowing. (The narrowing case isn't actually guaranteed to 13249 // be constant-evaluatable except in some narrow cases which are hard 13250 // to detect here. We let it through on the assumption the user knows 13251 // what they are doing.) 13252 if (Result.isAddrLabelDiff()) 13253 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13254 // Only allow casts of lvalues if they are lossless. 13255 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13256 } 13257 13258 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13259 Result.getInt()), E); 13260 } 13261 13262 case CK_PointerToIntegral: { 13263 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13264 13265 LValue LV; 13266 if (!EvaluatePointer(SubExpr, LV, Info)) 13267 return false; 13268 13269 if (LV.getLValueBase()) { 13270 // Only allow based lvalue casts if they are lossless. 13271 // FIXME: Allow a larger integer size than the pointer size, and allow 13272 // narrowing back down to pointer width in subsequent integral casts. 13273 // FIXME: Check integer type's active bits, not its type size. 13274 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13275 return Error(E); 13276 13277 LV.Designator.setInvalid(); 13278 LV.moveInto(Result); 13279 return true; 13280 } 13281 13282 APSInt AsInt; 13283 APValue V; 13284 LV.moveInto(V); 13285 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13286 llvm_unreachable("Can't cast this!"); 13287 13288 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13289 } 13290 13291 case CK_IntegralComplexToReal: { 13292 ComplexValue C; 13293 if (!EvaluateComplex(SubExpr, C, Info)) 13294 return false; 13295 return Success(C.getComplexIntReal(), E); 13296 } 13297 13298 case CK_FloatingToIntegral: { 13299 APFloat F(0.0); 13300 if (!EvaluateFloat(SubExpr, F, Info)) 13301 return false; 13302 13303 APSInt Value; 13304 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13305 return false; 13306 return Success(Value, E); 13307 } 13308 } 13309 13310 llvm_unreachable("unknown cast resulting in integral value"); 13311 } 13312 13313 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13314 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13315 ComplexValue LV; 13316 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13317 return false; 13318 if (!LV.isComplexInt()) 13319 return Error(E); 13320 return Success(LV.getComplexIntReal(), E); 13321 } 13322 13323 return Visit(E->getSubExpr()); 13324 } 13325 13326 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13327 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13328 ComplexValue LV; 13329 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13330 return false; 13331 if (!LV.isComplexInt()) 13332 return Error(E); 13333 return Success(LV.getComplexIntImag(), E); 13334 } 13335 13336 VisitIgnoredValue(E->getSubExpr()); 13337 return Success(0, E); 13338 } 13339 13340 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13341 return Success(E->getPackLength(), E); 13342 } 13343 13344 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13345 return Success(E->getValue(), E); 13346 } 13347 13348 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13349 const ConceptSpecializationExpr *E) { 13350 return Success(E->isSatisfied(), E); 13351 } 13352 13353 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13354 return Success(E->isSatisfied(), E); 13355 } 13356 13357 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13358 switch (E->getOpcode()) { 13359 default: 13360 // Invalid unary operators 13361 return Error(E); 13362 case UO_Plus: 13363 // The result is just the value. 13364 return Visit(E->getSubExpr()); 13365 case UO_Minus: { 13366 if (!Visit(E->getSubExpr())) return false; 13367 if (!Result.isFixedPoint()) 13368 return Error(E); 13369 bool Overflowed; 13370 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13371 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13372 return false; 13373 return Success(Negated, E); 13374 } 13375 case UO_LNot: { 13376 bool bres; 13377 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13378 return false; 13379 return Success(!bres, E); 13380 } 13381 } 13382 } 13383 13384 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13385 const Expr *SubExpr = E->getSubExpr(); 13386 QualType DestType = E->getType(); 13387 assert(DestType->isFixedPointType() && 13388 "Expected destination type to be a fixed point type"); 13389 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13390 13391 switch (E->getCastKind()) { 13392 case CK_FixedPointCast: { 13393 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13394 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13395 return false; 13396 bool Overflowed; 13397 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13398 if (Overflowed) { 13399 if (Info.checkingForUndefinedBehavior()) 13400 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13401 diag::warn_fixedpoint_constant_overflow) 13402 << Result.toString() << E->getType(); 13403 if (!HandleOverflow(Info, E, Result, E->getType())) 13404 return false; 13405 } 13406 return Success(Result, E); 13407 } 13408 case CK_IntegralToFixedPoint: { 13409 APSInt Src; 13410 if (!EvaluateInteger(SubExpr, Src, Info)) 13411 return false; 13412 13413 bool Overflowed; 13414 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13415 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13416 13417 if (Overflowed) { 13418 if (Info.checkingForUndefinedBehavior()) 13419 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13420 diag::warn_fixedpoint_constant_overflow) 13421 << IntResult.toString() << E->getType(); 13422 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13423 return false; 13424 } 13425 13426 return Success(IntResult, E); 13427 } 13428 case CK_FloatingToFixedPoint: { 13429 APFloat Src(0.0); 13430 if (!EvaluateFloat(SubExpr, Src, Info)) 13431 return false; 13432 13433 bool Overflowed; 13434 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13435 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13436 13437 if (Overflowed) { 13438 if (Info.checkingForUndefinedBehavior()) 13439 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13440 diag::warn_fixedpoint_constant_overflow) 13441 << Result.toString() << E->getType(); 13442 if (!HandleOverflow(Info, E, Result, E->getType())) 13443 return false; 13444 } 13445 13446 return Success(Result, E); 13447 } 13448 case CK_NoOp: 13449 case CK_LValueToRValue: 13450 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13451 default: 13452 return Error(E); 13453 } 13454 } 13455 13456 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13457 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13458 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13459 13460 const Expr *LHS = E->getLHS(); 13461 const Expr *RHS = E->getRHS(); 13462 FixedPointSemantics ResultFXSema = 13463 Info.Ctx.getFixedPointSemantics(E->getType()); 13464 13465 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13466 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13467 return false; 13468 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13469 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13470 return false; 13471 13472 bool OpOverflow = false, ConversionOverflow = false; 13473 APFixedPoint Result(LHSFX.getSemantics()); 13474 switch (E->getOpcode()) { 13475 case BO_Add: { 13476 Result = LHSFX.add(RHSFX, &OpOverflow) 13477 .convert(ResultFXSema, &ConversionOverflow); 13478 break; 13479 } 13480 case BO_Sub: { 13481 Result = LHSFX.sub(RHSFX, &OpOverflow) 13482 .convert(ResultFXSema, &ConversionOverflow); 13483 break; 13484 } 13485 case BO_Mul: { 13486 Result = LHSFX.mul(RHSFX, &OpOverflow) 13487 .convert(ResultFXSema, &ConversionOverflow); 13488 break; 13489 } 13490 case BO_Div: { 13491 if (RHSFX.getValue() == 0) { 13492 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13493 return false; 13494 } 13495 Result = LHSFX.div(RHSFX, &OpOverflow) 13496 .convert(ResultFXSema, &ConversionOverflow); 13497 break; 13498 } 13499 case BO_Shl: 13500 case BO_Shr: { 13501 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13502 llvm::APSInt RHSVal = RHSFX.getValue(); 13503 13504 unsigned ShiftBW = 13505 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13506 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13507 // Embedded-C 4.1.6.2.2: 13508 // The right operand must be nonnegative and less than the total number 13509 // of (nonpadding) bits of the fixed-point operand ... 13510 if (RHSVal.isNegative()) 13511 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13512 else if (Amt != RHSVal) 13513 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13514 << RHSVal << E->getType() << ShiftBW; 13515 13516 if (E->getOpcode() == BO_Shl) 13517 Result = LHSFX.shl(Amt, &OpOverflow); 13518 else 13519 Result = LHSFX.shr(Amt, &OpOverflow); 13520 break; 13521 } 13522 default: 13523 return false; 13524 } 13525 if (OpOverflow || ConversionOverflow) { 13526 if (Info.checkingForUndefinedBehavior()) 13527 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13528 diag::warn_fixedpoint_constant_overflow) 13529 << Result.toString() << E->getType(); 13530 if (!HandleOverflow(Info, E, Result, E->getType())) 13531 return false; 13532 } 13533 return Success(Result, E); 13534 } 13535 13536 //===----------------------------------------------------------------------===// 13537 // Float Evaluation 13538 //===----------------------------------------------------------------------===// 13539 13540 namespace { 13541 class FloatExprEvaluator 13542 : public ExprEvaluatorBase<FloatExprEvaluator> { 13543 APFloat &Result; 13544 public: 13545 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13546 : ExprEvaluatorBaseTy(info), Result(result) {} 13547 13548 bool Success(const APValue &V, const Expr *e) { 13549 Result = V.getFloat(); 13550 return true; 13551 } 13552 13553 bool ZeroInitialization(const Expr *E) { 13554 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13555 return true; 13556 } 13557 13558 bool VisitCallExpr(const CallExpr *E); 13559 13560 bool VisitUnaryOperator(const UnaryOperator *E); 13561 bool VisitBinaryOperator(const BinaryOperator *E); 13562 bool VisitFloatingLiteral(const FloatingLiteral *E); 13563 bool VisitCastExpr(const CastExpr *E); 13564 13565 bool VisitUnaryReal(const UnaryOperator *E); 13566 bool VisitUnaryImag(const UnaryOperator *E); 13567 13568 // FIXME: Missing: array subscript of vector, member of vector 13569 }; 13570 } // end anonymous namespace 13571 13572 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13573 assert(!E->isValueDependent()); 13574 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13575 return FloatExprEvaluator(Info, Result).Visit(E); 13576 } 13577 13578 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13579 QualType ResultTy, 13580 const Expr *Arg, 13581 bool SNaN, 13582 llvm::APFloat &Result) { 13583 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13584 if (!S) return false; 13585 13586 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13587 13588 llvm::APInt fill; 13589 13590 // Treat empty strings as if they were zero. 13591 if (S->getString().empty()) 13592 fill = llvm::APInt(32, 0); 13593 else if (S->getString().getAsInteger(0, fill)) 13594 return false; 13595 13596 if (Context.getTargetInfo().isNan2008()) { 13597 if (SNaN) 13598 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13599 else 13600 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13601 } else { 13602 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13603 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13604 // a different encoding to what became a standard in 2008, and for pre- 13605 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13606 // sNaN. This is now known as "legacy NaN" encoding. 13607 if (SNaN) 13608 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13609 else 13610 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13611 } 13612 13613 return true; 13614 } 13615 13616 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13617 switch (E->getBuiltinCallee()) { 13618 default: 13619 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13620 13621 case Builtin::BI__builtin_huge_val: 13622 case Builtin::BI__builtin_huge_valf: 13623 case Builtin::BI__builtin_huge_vall: 13624 case Builtin::BI__builtin_huge_valf128: 13625 case Builtin::BI__builtin_inf: 13626 case Builtin::BI__builtin_inff: 13627 case Builtin::BI__builtin_infl: 13628 case Builtin::BI__builtin_inff128: { 13629 const llvm::fltSemantics &Sem = 13630 Info.Ctx.getFloatTypeSemantics(E->getType()); 13631 Result = llvm::APFloat::getInf(Sem); 13632 return true; 13633 } 13634 13635 case Builtin::BI__builtin_nans: 13636 case Builtin::BI__builtin_nansf: 13637 case Builtin::BI__builtin_nansl: 13638 case Builtin::BI__builtin_nansf128: 13639 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13640 true, Result)) 13641 return Error(E); 13642 return true; 13643 13644 case Builtin::BI__builtin_nan: 13645 case Builtin::BI__builtin_nanf: 13646 case Builtin::BI__builtin_nanl: 13647 case Builtin::BI__builtin_nanf128: 13648 // If this is __builtin_nan() turn this into a nan, otherwise we 13649 // can't constant fold it. 13650 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13651 false, Result)) 13652 return Error(E); 13653 return true; 13654 13655 case Builtin::BI__builtin_fabs: 13656 case Builtin::BI__builtin_fabsf: 13657 case Builtin::BI__builtin_fabsl: 13658 case Builtin::BI__builtin_fabsf128: 13659 // The C standard says "fabs raises no floating-point exceptions, 13660 // even if x is a signaling NaN. The returned value is independent of 13661 // the current rounding direction mode." Therefore constant folding can 13662 // proceed without regard to the floating point settings. 13663 // Reference, WG14 N2478 F.10.4.3 13664 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13665 return false; 13666 13667 if (Result.isNegative()) 13668 Result.changeSign(); 13669 return true; 13670 13671 // FIXME: Builtin::BI__builtin_powi 13672 // FIXME: Builtin::BI__builtin_powif 13673 // FIXME: Builtin::BI__builtin_powil 13674 13675 case Builtin::BI__builtin_copysign: 13676 case Builtin::BI__builtin_copysignf: 13677 case Builtin::BI__builtin_copysignl: 13678 case Builtin::BI__builtin_copysignf128: { 13679 APFloat RHS(0.); 13680 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13681 !EvaluateFloat(E->getArg(1), RHS, Info)) 13682 return false; 13683 Result.copySign(RHS); 13684 return true; 13685 } 13686 } 13687 } 13688 13689 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13690 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13691 ComplexValue CV; 13692 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13693 return false; 13694 Result = CV.FloatReal; 13695 return true; 13696 } 13697 13698 return Visit(E->getSubExpr()); 13699 } 13700 13701 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13702 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13703 ComplexValue CV; 13704 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13705 return false; 13706 Result = CV.FloatImag; 13707 return true; 13708 } 13709 13710 VisitIgnoredValue(E->getSubExpr()); 13711 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13712 Result = llvm::APFloat::getZero(Sem); 13713 return true; 13714 } 13715 13716 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13717 switch (E->getOpcode()) { 13718 default: return Error(E); 13719 case UO_Plus: 13720 return EvaluateFloat(E->getSubExpr(), Result, Info); 13721 case UO_Minus: 13722 // In C standard, WG14 N2478 F.3 p4 13723 // "the unary - raises no floating point exceptions, 13724 // even if the operand is signalling." 13725 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13726 return false; 13727 Result.changeSign(); 13728 return true; 13729 } 13730 } 13731 13732 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13733 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13734 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13735 13736 APFloat RHS(0.0); 13737 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13738 if (!LHSOK && !Info.noteFailure()) 13739 return false; 13740 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13741 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13742 } 13743 13744 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13745 Result = E->getValue(); 13746 return true; 13747 } 13748 13749 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13750 const Expr* SubExpr = E->getSubExpr(); 13751 13752 switch (E->getCastKind()) { 13753 default: 13754 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13755 13756 case CK_IntegralToFloating: { 13757 APSInt IntResult; 13758 const FPOptions FPO = E->getFPFeaturesInEffect( 13759 Info.Ctx.getLangOpts()); 13760 return EvaluateInteger(SubExpr, IntResult, Info) && 13761 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13762 IntResult, E->getType(), Result); 13763 } 13764 13765 case CK_FixedPointToFloating: { 13766 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13767 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13768 return false; 13769 Result = 13770 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13771 return true; 13772 } 13773 13774 case CK_FloatingCast: { 13775 if (!Visit(SubExpr)) 13776 return false; 13777 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13778 Result); 13779 } 13780 13781 case CK_FloatingComplexToReal: { 13782 ComplexValue V; 13783 if (!EvaluateComplex(SubExpr, V, Info)) 13784 return false; 13785 Result = V.getComplexFloatReal(); 13786 return true; 13787 } 13788 } 13789 } 13790 13791 //===----------------------------------------------------------------------===// 13792 // Complex Evaluation (for float and integer) 13793 //===----------------------------------------------------------------------===// 13794 13795 namespace { 13796 class ComplexExprEvaluator 13797 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13798 ComplexValue &Result; 13799 13800 public: 13801 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13802 : ExprEvaluatorBaseTy(info), Result(Result) {} 13803 13804 bool Success(const APValue &V, const Expr *e) { 13805 Result.setFrom(V); 13806 return true; 13807 } 13808 13809 bool ZeroInitialization(const Expr *E); 13810 13811 //===--------------------------------------------------------------------===// 13812 // Visitor Methods 13813 //===--------------------------------------------------------------------===// 13814 13815 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13816 bool VisitCastExpr(const CastExpr *E); 13817 bool VisitBinaryOperator(const BinaryOperator *E); 13818 bool VisitUnaryOperator(const UnaryOperator *E); 13819 bool VisitInitListExpr(const InitListExpr *E); 13820 bool VisitCallExpr(const CallExpr *E); 13821 }; 13822 } // end anonymous namespace 13823 13824 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13825 EvalInfo &Info) { 13826 assert(!E->isValueDependent()); 13827 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13828 return ComplexExprEvaluator(Info, Result).Visit(E); 13829 } 13830 13831 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13832 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13833 if (ElemTy->isRealFloatingType()) { 13834 Result.makeComplexFloat(); 13835 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13836 Result.FloatReal = Zero; 13837 Result.FloatImag = Zero; 13838 } else { 13839 Result.makeComplexInt(); 13840 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13841 Result.IntReal = Zero; 13842 Result.IntImag = Zero; 13843 } 13844 return true; 13845 } 13846 13847 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13848 const Expr* SubExpr = E->getSubExpr(); 13849 13850 if (SubExpr->getType()->isRealFloatingType()) { 13851 Result.makeComplexFloat(); 13852 APFloat &Imag = Result.FloatImag; 13853 if (!EvaluateFloat(SubExpr, Imag, Info)) 13854 return false; 13855 13856 Result.FloatReal = APFloat(Imag.getSemantics()); 13857 return true; 13858 } else { 13859 assert(SubExpr->getType()->isIntegerType() && 13860 "Unexpected imaginary literal."); 13861 13862 Result.makeComplexInt(); 13863 APSInt &Imag = Result.IntImag; 13864 if (!EvaluateInteger(SubExpr, Imag, Info)) 13865 return false; 13866 13867 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13868 return true; 13869 } 13870 } 13871 13872 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13873 13874 switch (E->getCastKind()) { 13875 case CK_BitCast: 13876 case CK_BaseToDerived: 13877 case CK_DerivedToBase: 13878 case CK_UncheckedDerivedToBase: 13879 case CK_Dynamic: 13880 case CK_ToUnion: 13881 case CK_ArrayToPointerDecay: 13882 case CK_FunctionToPointerDecay: 13883 case CK_NullToPointer: 13884 case CK_NullToMemberPointer: 13885 case CK_BaseToDerivedMemberPointer: 13886 case CK_DerivedToBaseMemberPointer: 13887 case CK_MemberPointerToBoolean: 13888 case CK_ReinterpretMemberPointer: 13889 case CK_ConstructorConversion: 13890 case CK_IntegralToPointer: 13891 case CK_PointerToIntegral: 13892 case CK_PointerToBoolean: 13893 case CK_ToVoid: 13894 case CK_VectorSplat: 13895 case CK_IntegralCast: 13896 case CK_BooleanToSignedIntegral: 13897 case CK_IntegralToBoolean: 13898 case CK_IntegralToFloating: 13899 case CK_FloatingToIntegral: 13900 case CK_FloatingToBoolean: 13901 case CK_FloatingCast: 13902 case CK_CPointerToObjCPointerCast: 13903 case CK_BlockPointerToObjCPointerCast: 13904 case CK_AnyPointerToBlockPointerCast: 13905 case CK_ObjCObjectLValueCast: 13906 case CK_FloatingComplexToReal: 13907 case CK_FloatingComplexToBoolean: 13908 case CK_IntegralComplexToReal: 13909 case CK_IntegralComplexToBoolean: 13910 case CK_ARCProduceObject: 13911 case CK_ARCConsumeObject: 13912 case CK_ARCReclaimReturnedObject: 13913 case CK_ARCExtendBlockObject: 13914 case CK_CopyAndAutoreleaseBlockObject: 13915 case CK_BuiltinFnToFnPtr: 13916 case CK_ZeroToOCLOpaqueType: 13917 case CK_NonAtomicToAtomic: 13918 case CK_AddressSpaceConversion: 13919 case CK_IntToOCLSampler: 13920 case CK_FloatingToFixedPoint: 13921 case CK_FixedPointToFloating: 13922 case CK_FixedPointCast: 13923 case CK_FixedPointToBoolean: 13924 case CK_FixedPointToIntegral: 13925 case CK_IntegralToFixedPoint: 13926 llvm_unreachable("invalid cast kind for complex value"); 13927 13928 case CK_LValueToRValue: 13929 case CK_AtomicToNonAtomic: 13930 case CK_NoOp: 13931 case CK_LValueToRValueBitCast: 13932 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13933 13934 case CK_Dependent: 13935 case CK_LValueBitCast: 13936 case CK_UserDefinedConversion: 13937 return Error(E); 13938 13939 case CK_FloatingRealToComplex: { 13940 APFloat &Real = Result.FloatReal; 13941 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13942 return false; 13943 13944 Result.makeComplexFloat(); 13945 Result.FloatImag = APFloat(Real.getSemantics()); 13946 return true; 13947 } 13948 13949 case CK_FloatingComplexCast: { 13950 if (!Visit(E->getSubExpr())) 13951 return false; 13952 13953 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13954 QualType From 13955 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13956 13957 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13958 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13959 } 13960 13961 case CK_FloatingComplexToIntegralComplex: { 13962 if (!Visit(E->getSubExpr())) 13963 return false; 13964 13965 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13966 QualType From 13967 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13968 Result.makeComplexInt(); 13969 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13970 To, Result.IntReal) && 13971 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13972 To, Result.IntImag); 13973 } 13974 13975 case CK_IntegralRealToComplex: { 13976 APSInt &Real = Result.IntReal; 13977 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13978 return false; 13979 13980 Result.makeComplexInt(); 13981 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13982 return true; 13983 } 13984 13985 case CK_IntegralComplexCast: { 13986 if (!Visit(E->getSubExpr())) 13987 return false; 13988 13989 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13990 QualType From 13991 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13992 13993 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13994 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13995 return true; 13996 } 13997 13998 case CK_IntegralComplexToFloatingComplex: { 13999 if (!Visit(E->getSubExpr())) 14000 return false; 14001 14002 const FPOptions FPO = E->getFPFeaturesInEffect( 14003 Info.Ctx.getLangOpts()); 14004 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14005 QualType From 14006 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14007 Result.makeComplexFloat(); 14008 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14009 To, Result.FloatReal) && 14010 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14011 To, Result.FloatImag); 14012 } 14013 } 14014 14015 llvm_unreachable("unknown cast resulting in complex value"); 14016 } 14017 14018 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14019 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14020 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14021 14022 // Track whether the LHS or RHS is real at the type system level. When this is 14023 // the case we can simplify our evaluation strategy. 14024 bool LHSReal = false, RHSReal = false; 14025 14026 bool LHSOK; 14027 if (E->getLHS()->getType()->isRealFloatingType()) { 14028 LHSReal = true; 14029 APFloat &Real = Result.FloatReal; 14030 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14031 if (LHSOK) { 14032 Result.makeComplexFloat(); 14033 Result.FloatImag = APFloat(Real.getSemantics()); 14034 } 14035 } else { 14036 LHSOK = Visit(E->getLHS()); 14037 } 14038 if (!LHSOK && !Info.noteFailure()) 14039 return false; 14040 14041 ComplexValue RHS; 14042 if (E->getRHS()->getType()->isRealFloatingType()) { 14043 RHSReal = true; 14044 APFloat &Real = RHS.FloatReal; 14045 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14046 return false; 14047 RHS.makeComplexFloat(); 14048 RHS.FloatImag = APFloat(Real.getSemantics()); 14049 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14050 return false; 14051 14052 assert(!(LHSReal && RHSReal) && 14053 "Cannot have both operands of a complex operation be real."); 14054 switch (E->getOpcode()) { 14055 default: return Error(E); 14056 case BO_Add: 14057 if (Result.isComplexFloat()) { 14058 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14059 APFloat::rmNearestTiesToEven); 14060 if (LHSReal) 14061 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14062 else if (!RHSReal) 14063 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14064 APFloat::rmNearestTiesToEven); 14065 } else { 14066 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14067 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14068 } 14069 break; 14070 case BO_Sub: 14071 if (Result.isComplexFloat()) { 14072 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14073 APFloat::rmNearestTiesToEven); 14074 if (LHSReal) { 14075 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14076 Result.getComplexFloatImag().changeSign(); 14077 } else if (!RHSReal) { 14078 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14079 APFloat::rmNearestTiesToEven); 14080 } 14081 } else { 14082 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14083 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14084 } 14085 break; 14086 case BO_Mul: 14087 if (Result.isComplexFloat()) { 14088 // This is an implementation of complex multiplication according to the 14089 // constraints laid out in C11 Annex G. The implementation uses the 14090 // following naming scheme: 14091 // (a + ib) * (c + id) 14092 ComplexValue LHS = Result; 14093 APFloat &A = LHS.getComplexFloatReal(); 14094 APFloat &B = LHS.getComplexFloatImag(); 14095 APFloat &C = RHS.getComplexFloatReal(); 14096 APFloat &D = RHS.getComplexFloatImag(); 14097 APFloat &ResR = Result.getComplexFloatReal(); 14098 APFloat &ResI = Result.getComplexFloatImag(); 14099 if (LHSReal) { 14100 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14101 ResR = A * C; 14102 ResI = A * D; 14103 } else if (RHSReal) { 14104 ResR = C * A; 14105 ResI = C * B; 14106 } else { 14107 // In the fully general case, we need to handle NaNs and infinities 14108 // robustly. 14109 APFloat AC = A * C; 14110 APFloat BD = B * D; 14111 APFloat AD = A * D; 14112 APFloat BC = B * C; 14113 ResR = AC - BD; 14114 ResI = AD + BC; 14115 if (ResR.isNaN() && ResI.isNaN()) { 14116 bool Recalc = false; 14117 if (A.isInfinity() || B.isInfinity()) { 14118 A = APFloat::copySign( 14119 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14120 B = APFloat::copySign( 14121 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14122 if (C.isNaN()) 14123 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14124 if (D.isNaN()) 14125 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14126 Recalc = true; 14127 } 14128 if (C.isInfinity() || D.isInfinity()) { 14129 C = APFloat::copySign( 14130 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14131 D = APFloat::copySign( 14132 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14133 if (A.isNaN()) 14134 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14135 if (B.isNaN()) 14136 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14137 Recalc = true; 14138 } 14139 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14140 AD.isInfinity() || BC.isInfinity())) { 14141 if (A.isNaN()) 14142 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14143 if (B.isNaN()) 14144 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14145 if (C.isNaN()) 14146 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14147 if (D.isNaN()) 14148 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14149 Recalc = true; 14150 } 14151 if (Recalc) { 14152 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14153 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14154 } 14155 } 14156 } 14157 } else { 14158 ComplexValue LHS = Result; 14159 Result.getComplexIntReal() = 14160 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14161 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14162 Result.getComplexIntImag() = 14163 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14164 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14165 } 14166 break; 14167 case BO_Div: 14168 if (Result.isComplexFloat()) { 14169 // This is an implementation of complex division according to the 14170 // constraints laid out in C11 Annex G. The implementation uses the 14171 // following naming scheme: 14172 // (a + ib) / (c + id) 14173 ComplexValue LHS = Result; 14174 APFloat &A = LHS.getComplexFloatReal(); 14175 APFloat &B = LHS.getComplexFloatImag(); 14176 APFloat &C = RHS.getComplexFloatReal(); 14177 APFloat &D = RHS.getComplexFloatImag(); 14178 APFloat &ResR = Result.getComplexFloatReal(); 14179 APFloat &ResI = Result.getComplexFloatImag(); 14180 if (RHSReal) { 14181 ResR = A / C; 14182 ResI = B / C; 14183 } else { 14184 if (LHSReal) { 14185 // No real optimizations we can do here, stub out with zero. 14186 B = APFloat::getZero(A.getSemantics()); 14187 } 14188 int DenomLogB = 0; 14189 APFloat MaxCD = maxnum(abs(C), abs(D)); 14190 if (MaxCD.isFinite()) { 14191 DenomLogB = ilogb(MaxCD); 14192 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14193 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14194 } 14195 APFloat Denom = C * C + D * D; 14196 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14197 APFloat::rmNearestTiesToEven); 14198 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14199 APFloat::rmNearestTiesToEven); 14200 if (ResR.isNaN() && ResI.isNaN()) { 14201 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14202 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14203 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14204 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14205 D.isFinite()) { 14206 A = APFloat::copySign( 14207 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14208 B = APFloat::copySign( 14209 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14210 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14211 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14212 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14213 C = APFloat::copySign( 14214 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14215 D = APFloat::copySign( 14216 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14217 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14218 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14219 } 14220 } 14221 } 14222 } else { 14223 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14224 return Error(E, diag::note_expr_divide_by_zero); 14225 14226 ComplexValue LHS = Result; 14227 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14228 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14229 Result.getComplexIntReal() = 14230 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14231 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14232 Result.getComplexIntImag() = 14233 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14234 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14235 } 14236 break; 14237 } 14238 14239 return true; 14240 } 14241 14242 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14243 // Get the operand value into 'Result'. 14244 if (!Visit(E->getSubExpr())) 14245 return false; 14246 14247 switch (E->getOpcode()) { 14248 default: 14249 return Error(E); 14250 case UO_Extension: 14251 return true; 14252 case UO_Plus: 14253 // The result is always just the subexpr. 14254 return true; 14255 case UO_Minus: 14256 if (Result.isComplexFloat()) { 14257 Result.getComplexFloatReal().changeSign(); 14258 Result.getComplexFloatImag().changeSign(); 14259 } 14260 else { 14261 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14262 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14263 } 14264 return true; 14265 case UO_Not: 14266 if (Result.isComplexFloat()) 14267 Result.getComplexFloatImag().changeSign(); 14268 else 14269 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14270 return true; 14271 } 14272 } 14273 14274 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14275 if (E->getNumInits() == 2) { 14276 if (E->getType()->isComplexType()) { 14277 Result.makeComplexFloat(); 14278 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14279 return false; 14280 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14281 return false; 14282 } else { 14283 Result.makeComplexInt(); 14284 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14285 return false; 14286 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14287 return false; 14288 } 14289 return true; 14290 } 14291 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14292 } 14293 14294 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14295 switch (E->getBuiltinCallee()) { 14296 case Builtin::BI__builtin_complex: 14297 Result.makeComplexFloat(); 14298 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14299 return false; 14300 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14301 return false; 14302 return true; 14303 14304 default: 14305 break; 14306 } 14307 14308 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14309 } 14310 14311 //===----------------------------------------------------------------------===// 14312 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14313 // implicit conversion. 14314 //===----------------------------------------------------------------------===// 14315 14316 namespace { 14317 class AtomicExprEvaluator : 14318 public ExprEvaluatorBase<AtomicExprEvaluator> { 14319 const LValue *This; 14320 APValue &Result; 14321 public: 14322 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14323 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14324 14325 bool Success(const APValue &V, const Expr *E) { 14326 Result = V; 14327 return true; 14328 } 14329 14330 bool ZeroInitialization(const Expr *E) { 14331 ImplicitValueInitExpr VIE( 14332 E->getType()->castAs<AtomicType>()->getValueType()); 14333 // For atomic-qualified class (and array) types in C++, initialize the 14334 // _Atomic-wrapped subobject directly, in-place. 14335 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14336 : Evaluate(Result, Info, &VIE); 14337 } 14338 14339 bool VisitCastExpr(const CastExpr *E) { 14340 switch (E->getCastKind()) { 14341 default: 14342 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14343 case CK_NonAtomicToAtomic: 14344 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14345 : Evaluate(Result, Info, E->getSubExpr()); 14346 } 14347 } 14348 }; 14349 } // end anonymous namespace 14350 14351 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14352 EvalInfo &Info) { 14353 assert(!E->isValueDependent()); 14354 assert(E->isRValue() && E->getType()->isAtomicType()); 14355 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14356 } 14357 14358 //===----------------------------------------------------------------------===// 14359 // Void expression evaluation, primarily for a cast to void on the LHS of a 14360 // comma operator 14361 //===----------------------------------------------------------------------===// 14362 14363 namespace { 14364 class VoidExprEvaluator 14365 : public ExprEvaluatorBase<VoidExprEvaluator> { 14366 public: 14367 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14368 14369 bool Success(const APValue &V, const Expr *e) { return true; } 14370 14371 bool ZeroInitialization(const Expr *E) { return true; } 14372 14373 bool VisitCastExpr(const CastExpr *E) { 14374 switch (E->getCastKind()) { 14375 default: 14376 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14377 case CK_ToVoid: 14378 VisitIgnoredValue(E->getSubExpr()); 14379 return true; 14380 } 14381 } 14382 14383 bool VisitCallExpr(const CallExpr *E) { 14384 switch (E->getBuiltinCallee()) { 14385 case Builtin::BI__assume: 14386 case Builtin::BI__builtin_assume: 14387 // The argument is not evaluated! 14388 return true; 14389 14390 case Builtin::BI__builtin_operator_delete: 14391 return HandleOperatorDeleteCall(Info, E); 14392 14393 default: 14394 break; 14395 } 14396 14397 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14398 } 14399 14400 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14401 }; 14402 } // end anonymous namespace 14403 14404 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14405 // We cannot speculatively evaluate a delete expression. 14406 if (Info.SpeculativeEvaluationDepth) 14407 return false; 14408 14409 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14410 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14411 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14412 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14413 return false; 14414 } 14415 14416 const Expr *Arg = E->getArgument(); 14417 14418 LValue Pointer; 14419 if (!EvaluatePointer(Arg, Pointer, Info)) 14420 return false; 14421 if (Pointer.Designator.Invalid) 14422 return false; 14423 14424 // Deleting a null pointer has no effect. 14425 if (Pointer.isNullPointer()) { 14426 // This is the only case where we need to produce an extension warning: 14427 // the only other way we can succeed is if we find a dynamic allocation, 14428 // and we will have warned when we allocated it in that case. 14429 if (!Info.getLangOpts().CPlusPlus20) 14430 Info.CCEDiag(E, diag::note_constexpr_new); 14431 return true; 14432 } 14433 14434 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14435 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14436 if (!Alloc) 14437 return false; 14438 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14439 14440 // For the non-array case, the designator must be empty if the static type 14441 // does not have a virtual destructor. 14442 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14443 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14444 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14445 << Arg->getType()->getPointeeType() << AllocType; 14446 return false; 14447 } 14448 14449 // For a class type with a virtual destructor, the selected operator delete 14450 // is the one looked up when building the destructor. 14451 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14452 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14453 if (VirtualDelete && 14454 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14455 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14456 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14457 return false; 14458 } 14459 } 14460 14461 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14462 (*Alloc)->Value, AllocType)) 14463 return false; 14464 14465 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14466 // The element was already erased. This means the destructor call also 14467 // deleted the object. 14468 // FIXME: This probably results in undefined behavior before we get this 14469 // far, and should be diagnosed elsewhere first. 14470 Info.FFDiag(E, diag::note_constexpr_double_delete); 14471 return false; 14472 } 14473 14474 return true; 14475 } 14476 14477 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14478 assert(!E->isValueDependent()); 14479 assert(E->isRValue() && E->getType()->isVoidType()); 14480 return VoidExprEvaluator(Info).Visit(E); 14481 } 14482 14483 //===----------------------------------------------------------------------===// 14484 // Top level Expr::EvaluateAsRValue method. 14485 //===----------------------------------------------------------------------===// 14486 14487 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14488 assert(!E->isValueDependent()); 14489 // In C, function designators are not lvalues, but we evaluate them as if they 14490 // are. 14491 QualType T = E->getType(); 14492 if (E->isGLValue() || T->isFunctionType()) { 14493 LValue LV; 14494 if (!EvaluateLValue(E, LV, Info)) 14495 return false; 14496 LV.moveInto(Result); 14497 } else if (T->isVectorType()) { 14498 if (!EvaluateVector(E, Result, Info)) 14499 return false; 14500 } else if (T->isIntegralOrEnumerationType()) { 14501 if (!IntExprEvaluator(Info, Result).Visit(E)) 14502 return false; 14503 } else if (T->hasPointerRepresentation()) { 14504 LValue LV; 14505 if (!EvaluatePointer(E, LV, Info)) 14506 return false; 14507 LV.moveInto(Result); 14508 } else if (T->isRealFloatingType()) { 14509 llvm::APFloat F(0.0); 14510 if (!EvaluateFloat(E, F, Info)) 14511 return false; 14512 Result = APValue(F); 14513 } else if (T->isAnyComplexType()) { 14514 ComplexValue C; 14515 if (!EvaluateComplex(E, C, Info)) 14516 return false; 14517 C.moveInto(Result); 14518 } else if (T->isFixedPointType()) { 14519 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14520 } else if (T->isMemberPointerType()) { 14521 MemberPtr P; 14522 if (!EvaluateMemberPointer(E, P, Info)) 14523 return false; 14524 P.moveInto(Result); 14525 return true; 14526 } else if (T->isArrayType()) { 14527 LValue LV; 14528 APValue &Value = 14529 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14530 if (!EvaluateArray(E, LV, Value, Info)) 14531 return false; 14532 Result = Value; 14533 } else if (T->isRecordType()) { 14534 LValue LV; 14535 APValue &Value = 14536 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14537 if (!EvaluateRecord(E, LV, Value, Info)) 14538 return false; 14539 Result = Value; 14540 } else if (T->isVoidType()) { 14541 if (!Info.getLangOpts().CPlusPlus11) 14542 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14543 << E->getType(); 14544 if (!EvaluateVoid(E, Info)) 14545 return false; 14546 } else if (T->isAtomicType()) { 14547 QualType Unqual = T.getAtomicUnqualifiedType(); 14548 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14549 LValue LV; 14550 APValue &Value = Info.CurrentCall->createTemporary( 14551 E, Unqual, ScopeKind::FullExpression, LV); 14552 if (!EvaluateAtomic(E, &LV, Value, Info)) 14553 return false; 14554 } else { 14555 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14556 return false; 14557 } 14558 } else if (Info.getLangOpts().CPlusPlus11) { 14559 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14560 return false; 14561 } else { 14562 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14563 return false; 14564 } 14565 14566 return true; 14567 } 14568 14569 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14570 /// cases, the in-place evaluation is essential, since later initializers for 14571 /// an object can indirectly refer to subobjects which were initialized earlier. 14572 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14573 const Expr *E, bool AllowNonLiteralTypes) { 14574 assert(!E->isValueDependent()); 14575 14576 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14577 return false; 14578 14579 if (E->isRValue()) { 14580 // Evaluate arrays and record types in-place, so that later initializers can 14581 // refer to earlier-initialized members of the object. 14582 QualType T = E->getType(); 14583 if (T->isArrayType()) 14584 return EvaluateArray(E, This, Result, Info); 14585 else if (T->isRecordType()) 14586 return EvaluateRecord(E, This, Result, Info); 14587 else if (T->isAtomicType()) { 14588 QualType Unqual = T.getAtomicUnqualifiedType(); 14589 if (Unqual->isArrayType() || Unqual->isRecordType()) 14590 return EvaluateAtomic(E, &This, Result, Info); 14591 } 14592 } 14593 14594 // For any other type, in-place evaluation is unimportant. 14595 return Evaluate(Result, Info, E); 14596 } 14597 14598 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14599 /// lvalue-to-rvalue cast if it is an lvalue. 14600 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14601 assert(!E->isValueDependent()); 14602 if (Info.EnableNewConstInterp) { 14603 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14604 return false; 14605 } else { 14606 if (E->getType().isNull()) 14607 return false; 14608 14609 if (!CheckLiteralType(Info, E)) 14610 return false; 14611 14612 if (!::Evaluate(Result, Info, E)) 14613 return false; 14614 14615 if (E->isGLValue()) { 14616 LValue LV; 14617 LV.setFrom(Info.Ctx, Result); 14618 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14619 return false; 14620 } 14621 } 14622 14623 // Check this core constant expression is a constant expression. 14624 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14625 ConstantExprKind::Normal) && 14626 CheckMemoryLeaks(Info); 14627 } 14628 14629 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14630 const ASTContext &Ctx, bool &IsConst) { 14631 // Fast-path evaluations of integer literals, since we sometimes see files 14632 // containing vast quantities of these. 14633 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14634 Result.Val = APValue(APSInt(L->getValue(), 14635 L->getType()->isUnsignedIntegerType())); 14636 IsConst = true; 14637 return true; 14638 } 14639 14640 // This case should be rare, but we need to check it before we check on 14641 // the type below. 14642 if (Exp->getType().isNull()) { 14643 IsConst = false; 14644 return true; 14645 } 14646 14647 // FIXME: Evaluating values of large array and record types can cause 14648 // performance problems. Only do so in C++11 for now. 14649 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14650 Exp->getType()->isRecordType()) && 14651 !Ctx.getLangOpts().CPlusPlus11) { 14652 IsConst = false; 14653 return true; 14654 } 14655 return false; 14656 } 14657 14658 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14659 Expr::SideEffectsKind SEK) { 14660 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14661 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14662 } 14663 14664 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14665 const ASTContext &Ctx, EvalInfo &Info) { 14666 assert(!E->isValueDependent()); 14667 bool IsConst; 14668 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14669 return IsConst; 14670 14671 return EvaluateAsRValue(Info, E, Result.Val); 14672 } 14673 14674 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14675 const ASTContext &Ctx, 14676 Expr::SideEffectsKind AllowSideEffects, 14677 EvalInfo &Info) { 14678 assert(!E->isValueDependent()); 14679 if (!E->getType()->isIntegralOrEnumerationType()) 14680 return false; 14681 14682 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14683 !ExprResult.Val.isInt() || 14684 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14685 return false; 14686 14687 return true; 14688 } 14689 14690 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14691 const ASTContext &Ctx, 14692 Expr::SideEffectsKind AllowSideEffects, 14693 EvalInfo &Info) { 14694 assert(!E->isValueDependent()); 14695 if (!E->getType()->isFixedPointType()) 14696 return false; 14697 14698 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14699 return false; 14700 14701 if (!ExprResult.Val.isFixedPoint() || 14702 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14703 return false; 14704 14705 return true; 14706 } 14707 14708 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14709 /// any crazy technique (that has nothing to do with language standards) that 14710 /// we want to. If this function returns true, it returns the folded constant 14711 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14712 /// will be applied to the result. 14713 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14714 bool InConstantContext) const { 14715 assert(!isValueDependent() && 14716 "Expression evaluator can't be called on a dependent expression."); 14717 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14718 Info.InConstantContext = InConstantContext; 14719 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14720 } 14721 14722 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14723 bool InConstantContext) const { 14724 assert(!isValueDependent() && 14725 "Expression evaluator can't be called on a dependent expression."); 14726 EvalResult Scratch; 14727 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14728 HandleConversionToBool(Scratch.Val, Result); 14729 } 14730 14731 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14732 SideEffectsKind AllowSideEffects, 14733 bool InConstantContext) const { 14734 assert(!isValueDependent() && 14735 "Expression evaluator can't be called on a dependent expression."); 14736 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14737 Info.InConstantContext = InConstantContext; 14738 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14739 } 14740 14741 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14742 SideEffectsKind AllowSideEffects, 14743 bool InConstantContext) const { 14744 assert(!isValueDependent() && 14745 "Expression evaluator can't be called on a dependent expression."); 14746 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14747 Info.InConstantContext = InConstantContext; 14748 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14749 } 14750 14751 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14752 SideEffectsKind AllowSideEffects, 14753 bool InConstantContext) const { 14754 assert(!isValueDependent() && 14755 "Expression evaluator can't be called on a dependent expression."); 14756 14757 if (!getType()->isRealFloatingType()) 14758 return false; 14759 14760 EvalResult ExprResult; 14761 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14762 !ExprResult.Val.isFloat() || 14763 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14764 return false; 14765 14766 Result = ExprResult.Val.getFloat(); 14767 return true; 14768 } 14769 14770 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14771 bool InConstantContext) const { 14772 assert(!isValueDependent() && 14773 "Expression evaluator can't be called on a dependent expression."); 14774 14775 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14776 Info.InConstantContext = InConstantContext; 14777 LValue LV; 14778 CheckedTemporaries CheckedTemps; 14779 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14780 Result.HasSideEffects || 14781 !CheckLValueConstantExpression(Info, getExprLoc(), 14782 Ctx.getLValueReferenceType(getType()), LV, 14783 ConstantExprKind::Normal, CheckedTemps)) 14784 return false; 14785 14786 LV.moveInto(Result.Val); 14787 return true; 14788 } 14789 14790 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14791 APValue DestroyedValue, QualType Type, 14792 SourceLocation Loc, Expr::EvalStatus &EStatus, 14793 bool IsConstantDestruction) { 14794 EvalInfo Info(Ctx, EStatus, 14795 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14796 : EvalInfo::EM_ConstantFold); 14797 Info.setEvaluatingDecl(Base, DestroyedValue, 14798 EvalInfo::EvaluatingDeclKind::Dtor); 14799 Info.InConstantContext = IsConstantDestruction; 14800 14801 LValue LVal; 14802 LVal.set(Base); 14803 14804 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14805 EStatus.HasSideEffects) 14806 return false; 14807 14808 if (!Info.discardCleanups()) 14809 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14810 14811 return true; 14812 } 14813 14814 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14815 ConstantExprKind Kind) const { 14816 assert(!isValueDependent() && 14817 "Expression evaluator can't be called on a dependent expression."); 14818 14819 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14820 EvalInfo Info(Ctx, Result, EM); 14821 Info.InConstantContext = true; 14822 14823 // The type of the object we're initializing is 'const T' for a class NTTP. 14824 QualType T = getType(); 14825 if (Kind == ConstantExprKind::ClassTemplateArgument) 14826 T.addConst(); 14827 14828 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14829 // represent the result of the evaluation. CheckConstantExpression ensures 14830 // this doesn't escape. 14831 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14832 APValue::LValueBase Base(&BaseMTE); 14833 14834 Info.setEvaluatingDecl(Base, Result.Val); 14835 LValue LVal; 14836 LVal.set(Base); 14837 14838 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14839 return false; 14840 14841 if (!Info.discardCleanups()) 14842 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14843 14844 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14845 Result.Val, Kind)) 14846 return false; 14847 if (!CheckMemoryLeaks(Info)) 14848 return false; 14849 14850 // If this is a class template argument, it's required to have constant 14851 // destruction too. 14852 if (Kind == ConstantExprKind::ClassTemplateArgument && 14853 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 14854 true) || 14855 Result.HasSideEffects)) { 14856 // FIXME: Prefix a note to indicate that the problem is lack of constant 14857 // destruction. 14858 return false; 14859 } 14860 14861 return true; 14862 } 14863 14864 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14865 const VarDecl *VD, 14866 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14867 bool IsConstantInitialization) const { 14868 assert(!isValueDependent() && 14869 "Expression evaluator can't be called on a dependent expression."); 14870 14871 // FIXME: Evaluating initializers for large array and record types can cause 14872 // performance problems. Only do so in C++11 for now. 14873 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14874 !Ctx.getLangOpts().CPlusPlus11) 14875 return false; 14876 14877 Expr::EvalStatus EStatus; 14878 EStatus.Diag = &Notes; 14879 14880 EvalInfo Info(Ctx, EStatus, 14881 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14882 ? EvalInfo::EM_ConstantExpression 14883 : EvalInfo::EM_ConstantFold); 14884 Info.setEvaluatingDecl(VD, Value); 14885 Info.InConstantContext = IsConstantInitialization; 14886 14887 SourceLocation DeclLoc = VD->getLocation(); 14888 QualType DeclTy = VD->getType(); 14889 14890 if (Info.EnableNewConstInterp) { 14891 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14892 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14893 return false; 14894 } else { 14895 LValue LVal; 14896 LVal.set(VD); 14897 14898 if (!EvaluateInPlace(Value, Info, LVal, this, 14899 /*AllowNonLiteralTypes=*/true) || 14900 EStatus.HasSideEffects) 14901 return false; 14902 14903 // At this point, any lifetime-extended temporaries are completely 14904 // initialized. 14905 Info.performLifetimeExtension(); 14906 14907 if (!Info.discardCleanups()) 14908 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14909 } 14910 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 14911 ConstantExprKind::Normal) && 14912 CheckMemoryLeaks(Info); 14913 } 14914 14915 bool VarDecl::evaluateDestruction( 14916 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14917 Expr::EvalStatus EStatus; 14918 EStatus.Diag = &Notes; 14919 14920 // Only treat the destruction as constant destruction if we formally have 14921 // constant initialization (or are usable in a constant expression). 14922 bool IsConstantDestruction = hasConstantInitialization(); 14923 14924 // Make a copy of the value for the destructor to mutate, if we know it. 14925 // Otherwise, treat the value as default-initialized; if the destructor works 14926 // anyway, then the destruction is constant (and must be essentially empty). 14927 APValue DestroyedValue; 14928 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14929 DestroyedValue = *getEvaluatedValue(); 14930 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14931 return false; 14932 14933 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 14934 getType(), getLocation(), EStatus, 14935 IsConstantDestruction) || 14936 EStatus.HasSideEffects) 14937 return false; 14938 14939 ensureEvaluatedStmt()->HasConstantDestruction = true; 14940 return true; 14941 } 14942 14943 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14944 /// constant folded, but discard the result. 14945 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14946 assert(!isValueDependent() && 14947 "Expression evaluator can't be called on a dependent expression."); 14948 14949 EvalResult Result; 14950 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14951 !hasUnacceptableSideEffect(Result, SEK); 14952 } 14953 14954 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14955 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14956 assert(!isValueDependent() && 14957 "Expression evaluator can't be called on a dependent expression."); 14958 14959 EvalResult EVResult; 14960 EVResult.Diag = Diag; 14961 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14962 Info.InConstantContext = true; 14963 14964 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14965 (void)Result; 14966 assert(Result && "Could not evaluate expression"); 14967 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14968 14969 return EVResult.Val.getInt(); 14970 } 14971 14972 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14973 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14974 assert(!isValueDependent() && 14975 "Expression evaluator can't be called on a dependent expression."); 14976 14977 EvalResult EVResult; 14978 EVResult.Diag = Diag; 14979 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14980 Info.InConstantContext = true; 14981 Info.CheckingForUndefinedBehavior = true; 14982 14983 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14984 (void)Result; 14985 assert(Result && "Could not evaluate expression"); 14986 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14987 14988 return EVResult.Val.getInt(); 14989 } 14990 14991 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14992 assert(!isValueDependent() && 14993 "Expression evaluator can't be called on a dependent expression."); 14994 14995 bool IsConst; 14996 EvalResult EVResult; 14997 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14998 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14999 Info.CheckingForUndefinedBehavior = true; 15000 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15001 } 15002 } 15003 15004 bool Expr::EvalResult::isGlobalLValue() const { 15005 assert(Val.isLValue()); 15006 return IsGlobalLValue(Val.getLValueBase()); 15007 } 15008 15009 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15010 /// an integer constant expression. 15011 15012 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15013 /// comma, etc 15014 15015 // CheckICE - This function does the fundamental ICE checking: the returned 15016 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15017 // and a (possibly null) SourceLocation indicating the location of the problem. 15018 // 15019 // Note that to reduce code duplication, this helper does no evaluation 15020 // itself; the caller checks whether the expression is evaluatable, and 15021 // in the rare cases where CheckICE actually cares about the evaluated 15022 // value, it calls into Evaluate. 15023 15024 namespace { 15025 15026 enum ICEKind { 15027 /// This expression is an ICE. 15028 IK_ICE, 15029 /// This expression is not an ICE, but if it isn't evaluated, it's 15030 /// a legal subexpression for an ICE. This return value is used to handle 15031 /// the comma operator in C99 mode, and non-constant subexpressions. 15032 IK_ICEIfUnevaluated, 15033 /// This expression is not an ICE, and is not a legal subexpression for one. 15034 IK_NotICE 15035 }; 15036 15037 struct ICEDiag { 15038 ICEKind Kind; 15039 SourceLocation Loc; 15040 15041 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15042 }; 15043 15044 } 15045 15046 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15047 15048 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15049 15050 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15051 Expr::EvalResult EVResult; 15052 Expr::EvalStatus Status; 15053 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15054 15055 Info.InConstantContext = true; 15056 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15057 !EVResult.Val.isInt()) 15058 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15059 15060 return NoDiag(); 15061 } 15062 15063 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15064 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15065 if (!E->getType()->isIntegralOrEnumerationType()) 15066 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15067 15068 switch (E->getStmtClass()) { 15069 #define ABSTRACT_STMT(Node) 15070 #define STMT(Node, Base) case Expr::Node##Class: 15071 #define EXPR(Node, Base) 15072 #include "clang/AST/StmtNodes.inc" 15073 case Expr::PredefinedExprClass: 15074 case Expr::FloatingLiteralClass: 15075 case Expr::ImaginaryLiteralClass: 15076 case Expr::StringLiteralClass: 15077 case Expr::ArraySubscriptExprClass: 15078 case Expr::MatrixSubscriptExprClass: 15079 case Expr::OMPArraySectionExprClass: 15080 case Expr::OMPArrayShapingExprClass: 15081 case Expr::OMPIteratorExprClass: 15082 case Expr::MemberExprClass: 15083 case Expr::CompoundAssignOperatorClass: 15084 case Expr::CompoundLiteralExprClass: 15085 case Expr::ExtVectorElementExprClass: 15086 case Expr::DesignatedInitExprClass: 15087 case Expr::ArrayInitLoopExprClass: 15088 case Expr::ArrayInitIndexExprClass: 15089 case Expr::NoInitExprClass: 15090 case Expr::DesignatedInitUpdateExprClass: 15091 case Expr::ImplicitValueInitExprClass: 15092 case Expr::ParenListExprClass: 15093 case Expr::VAArgExprClass: 15094 case Expr::AddrLabelExprClass: 15095 case Expr::StmtExprClass: 15096 case Expr::CXXMemberCallExprClass: 15097 case Expr::CUDAKernelCallExprClass: 15098 case Expr::CXXAddrspaceCastExprClass: 15099 case Expr::CXXDynamicCastExprClass: 15100 case Expr::CXXTypeidExprClass: 15101 case Expr::CXXUuidofExprClass: 15102 case Expr::MSPropertyRefExprClass: 15103 case Expr::MSPropertySubscriptExprClass: 15104 case Expr::CXXNullPtrLiteralExprClass: 15105 case Expr::UserDefinedLiteralClass: 15106 case Expr::CXXThisExprClass: 15107 case Expr::CXXThrowExprClass: 15108 case Expr::CXXNewExprClass: 15109 case Expr::CXXDeleteExprClass: 15110 case Expr::CXXPseudoDestructorExprClass: 15111 case Expr::UnresolvedLookupExprClass: 15112 case Expr::TypoExprClass: 15113 case Expr::RecoveryExprClass: 15114 case Expr::DependentScopeDeclRefExprClass: 15115 case Expr::CXXConstructExprClass: 15116 case Expr::CXXInheritedCtorInitExprClass: 15117 case Expr::CXXStdInitializerListExprClass: 15118 case Expr::CXXBindTemporaryExprClass: 15119 case Expr::ExprWithCleanupsClass: 15120 case Expr::CXXTemporaryObjectExprClass: 15121 case Expr::CXXUnresolvedConstructExprClass: 15122 case Expr::CXXDependentScopeMemberExprClass: 15123 case Expr::UnresolvedMemberExprClass: 15124 case Expr::ObjCStringLiteralClass: 15125 case Expr::ObjCBoxedExprClass: 15126 case Expr::ObjCArrayLiteralClass: 15127 case Expr::ObjCDictionaryLiteralClass: 15128 case Expr::ObjCEncodeExprClass: 15129 case Expr::ObjCMessageExprClass: 15130 case Expr::ObjCSelectorExprClass: 15131 case Expr::ObjCProtocolExprClass: 15132 case Expr::ObjCIvarRefExprClass: 15133 case Expr::ObjCPropertyRefExprClass: 15134 case Expr::ObjCSubscriptRefExprClass: 15135 case Expr::ObjCIsaExprClass: 15136 case Expr::ObjCAvailabilityCheckExprClass: 15137 case Expr::ShuffleVectorExprClass: 15138 case Expr::ConvertVectorExprClass: 15139 case Expr::BlockExprClass: 15140 case Expr::NoStmtClass: 15141 case Expr::OpaqueValueExprClass: 15142 case Expr::PackExpansionExprClass: 15143 case Expr::SubstNonTypeTemplateParmPackExprClass: 15144 case Expr::FunctionParmPackExprClass: 15145 case Expr::AsTypeExprClass: 15146 case Expr::ObjCIndirectCopyRestoreExprClass: 15147 case Expr::MaterializeTemporaryExprClass: 15148 case Expr::PseudoObjectExprClass: 15149 case Expr::AtomicExprClass: 15150 case Expr::LambdaExprClass: 15151 case Expr::CXXFoldExprClass: 15152 case Expr::CoawaitExprClass: 15153 case Expr::DependentCoawaitExprClass: 15154 case Expr::CoyieldExprClass: 15155 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15156 15157 case Expr::InitListExprClass: { 15158 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15159 // form "T x = { a };" is equivalent to "T x = a;". 15160 // Unless we're initializing a reference, T is a scalar as it is known to be 15161 // of integral or enumeration type. 15162 if (E->isRValue()) 15163 if (cast<InitListExpr>(E)->getNumInits() == 1) 15164 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15165 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15166 } 15167 15168 case Expr::SizeOfPackExprClass: 15169 case Expr::GNUNullExprClass: 15170 case Expr::SourceLocExprClass: 15171 return NoDiag(); 15172 15173 case Expr::SubstNonTypeTemplateParmExprClass: 15174 return 15175 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15176 15177 case Expr::ConstantExprClass: 15178 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15179 15180 case Expr::ParenExprClass: 15181 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15182 case Expr::GenericSelectionExprClass: 15183 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15184 case Expr::IntegerLiteralClass: 15185 case Expr::FixedPointLiteralClass: 15186 case Expr::CharacterLiteralClass: 15187 case Expr::ObjCBoolLiteralExprClass: 15188 case Expr::CXXBoolLiteralExprClass: 15189 case Expr::CXXScalarValueInitExprClass: 15190 case Expr::TypeTraitExprClass: 15191 case Expr::ConceptSpecializationExprClass: 15192 case Expr::RequiresExprClass: 15193 case Expr::ArrayTypeTraitExprClass: 15194 case Expr::ExpressionTraitExprClass: 15195 case Expr::CXXNoexceptExprClass: 15196 return NoDiag(); 15197 case Expr::CallExprClass: 15198 case Expr::CXXOperatorCallExprClass: { 15199 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15200 // constant expressions, but they can never be ICEs because an ICE cannot 15201 // contain an operand of (pointer to) function type. 15202 const CallExpr *CE = cast<CallExpr>(E); 15203 if (CE->getBuiltinCallee()) 15204 return CheckEvalInICE(E, Ctx); 15205 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15206 } 15207 case Expr::CXXRewrittenBinaryOperatorClass: 15208 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15209 Ctx); 15210 case Expr::DeclRefExprClass: { 15211 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15212 if (isa<EnumConstantDecl>(D)) 15213 return NoDiag(); 15214 15215 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15216 // integer variables in constant expressions: 15217 // 15218 // C++ 7.1.5.1p2 15219 // A variable of non-volatile const-qualified integral or enumeration 15220 // type initialized by an ICE can be used in ICEs. 15221 // 15222 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15223 // that mode, use of reference variables should not be allowed. 15224 const VarDecl *VD = dyn_cast<VarDecl>(D); 15225 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15226 !VD->getType()->isReferenceType()) 15227 return NoDiag(); 15228 15229 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15230 } 15231 case Expr::UnaryOperatorClass: { 15232 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15233 switch (Exp->getOpcode()) { 15234 case UO_PostInc: 15235 case UO_PostDec: 15236 case UO_PreInc: 15237 case UO_PreDec: 15238 case UO_AddrOf: 15239 case UO_Deref: 15240 case UO_Coawait: 15241 // C99 6.6/3 allows increment and decrement within unevaluated 15242 // subexpressions of constant expressions, but they can never be ICEs 15243 // because an ICE cannot contain an lvalue operand. 15244 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15245 case UO_Extension: 15246 case UO_LNot: 15247 case UO_Plus: 15248 case UO_Minus: 15249 case UO_Not: 15250 case UO_Real: 15251 case UO_Imag: 15252 return CheckICE(Exp->getSubExpr(), Ctx); 15253 } 15254 llvm_unreachable("invalid unary operator class"); 15255 } 15256 case Expr::OffsetOfExprClass: { 15257 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15258 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15259 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15260 // compliance: we should warn earlier for offsetof expressions with 15261 // array subscripts that aren't ICEs, and if the array subscripts 15262 // are ICEs, the value of the offsetof must be an integer constant. 15263 return CheckEvalInICE(E, Ctx); 15264 } 15265 case Expr::UnaryExprOrTypeTraitExprClass: { 15266 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15267 if ((Exp->getKind() == UETT_SizeOf) && 15268 Exp->getTypeOfArgument()->isVariableArrayType()) 15269 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15270 return NoDiag(); 15271 } 15272 case Expr::BinaryOperatorClass: { 15273 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15274 switch (Exp->getOpcode()) { 15275 case BO_PtrMemD: 15276 case BO_PtrMemI: 15277 case BO_Assign: 15278 case BO_MulAssign: 15279 case BO_DivAssign: 15280 case BO_RemAssign: 15281 case BO_AddAssign: 15282 case BO_SubAssign: 15283 case BO_ShlAssign: 15284 case BO_ShrAssign: 15285 case BO_AndAssign: 15286 case BO_XorAssign: 15287 case BO_OrAssign: 15288 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15289 // constant expressions, but they can never be ICEs because an ICE cannot 15290 // contain an lvalue operand. 15291 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15292 15293 case BO_Mul: 15294 case BO_Div: 15295 case BO_Rem: 15296 case BO_Add: 15297 case BO_Sub: 15298 case BO_Shl: 15299 case BO_Shr: 15300 case BO_LT: 15301 case BO_GT: 15302 case BO_LE: 15303 case BO_GE: 15304 case BO_EQ: 15305 case BO_NE: 15306 case BO_And: 15307 case BO_Xor: 15308 case BO_Or: 15309 case BO_Comma: 15310 case BO_Cmp: { 15311 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15312 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15313 if (Exp->getOpcode() == BO_Div || 15314 Exp->getOpcode() == BO_Rem) { 15315 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15316 // we don't evaluate one. 15317 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15318 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15319 if (REval == 0) 15320 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15321 if (REval.isSigned() && REval.isAllOnesValue()) { 15322 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15323 if (LEval.isMinSignedValue()) 15324 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15325 } 15326 } 15327 } 15328 if (Exp->getOpcode() == BO_Comma) { 15329 if (Ctx.getLangOpts().C99) { 15330 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15331 // if it isn't evaluated. 15332 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15333 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15334 } else { 15335 // In both C89 and C++, commas in ICEs are illegal. 15336 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15337 } 15338 } 15339 return Worst(LHSResult, RHSResult); 15340 } 15341 case BO_LAnd: 15342 case BO_LOr: { 15343 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15344 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15345 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15346 // Rare case where the RHS has a comma "side-effect"; we need 15347 // to actually check the condition to see whether the side 15348 // with the comma is evaluated. 15349 if ((Exp->getOpcode() == BO_LAnd) != 15350 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15351 return RHSResult; 15352 return NoDiag(); 15353 } 15354 15355 return Worst(LHSResult, RHSResult); 15356 } 15357 } 15358 llvm_unreachable("invalid binary operator kind"); 15359 } 15360 case Expr::ImplicitCastExprClass: 15361 case Expr::CStyleCastExprClass: 15362 case Expr::CXXFunctionalCastExprClass: 15363 case Expr::CXXStaticCastExprClass: 15364 case Expr::CXXReinterpretCastExprClass: 15365 case Expr::CXXConstCastExprClass: 15366 case Expr::ObjCBridgedCastExprClass: { 15367 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15368 if (isa<ExplicitCastExpr>(E)) { 15369 if (const FloatingLiteral *FL 15370 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15371 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15372 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15373 APSInt IgnoredVal(DestWidth, !DestSigned); 15374 bool Ignored; 15375 // If the value does not fit in the destination type, the behavior is 15376 // undefined, so we are not required to treat it as a constant 15377 // expression. 15378 if (FL->getValue().convertToInteger(IgnoredVal, 15379 llvm::APFloat::rmTowardZero, 15380 &Ignored) & APFloat::opInvalidOp) 15381 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15382 return NoDiag(); 15383 } 15384 } 15385 switch (cast<CastExpr>(E)->getCastKind()) { 15386 case CK_LValueToRValue: 15387 case CK_AtomicToNonAtomic: 15388 case CK_NonAtomicToAtomic: 15389 case CK_NoOp: 15390 case CK_IntegralToBoolean: 15391 case CK_IntegralCast: 15392 return CheckICE(SubExpr, Ctx); 15393 default: 15394 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15395 } 15396 } 15397 case Expr::BinaryConditionalOperatorClass: { 15398 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15399 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15400 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15401 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15402 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15403 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15404 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15405 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15406 return FalseResult; 15407 } 15408 case Expr::ConditionalOperatorClass: { 15409 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15410 // If the condition (ignoring parens) is a __builtin_constant_p call, 15411 // then only the true side is actually considered in an integer constant 15412 // expression, and it is fully evaluated. This is an important GNU 15413 // extension. See GCC PR38377 for discussion. 15414 if (const CallExpr *CallCE 15415 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15416 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15417 return CheckEvalInICE(E, Ctx); 15418 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15419 if (CondResult.Kind == IK_NotICE) 15420 return CondResult; 15421 15422 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15423 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15424 15425 if (TrueResult.Kind == IK_NotICE) 15426 return TrueResult; 15427 if (FalseResult.Kind == IK_NotICE) 15428 return FalseResult; 15429 if (CondResult.Kind == IK_ICEIfUnevaluated) 15430 return CondResult; 15431 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15432 return NoDiag(); 15433 // Rare case where the diagnostics depend on which side is evaluated 15434 // Note that if we get here, CondResult is 0, and at least one of 15435 // TrueResult and FalseResult is non-zero. 15436 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15437 return FalseResult; 15438 return TrueResult; 15439 } 15440 case Expr::CXXDefaultArgExprClass: 15441 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15442 case Expr::CXXDefaultInitExprClass: 15443 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15444 case Expr::ChooseExprClass: { 15445 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15446 } 15447 case Expr::BuiltinBitCastExprClass: { 15448 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15449 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15450 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15451 } 15452 } 15453 15454 llvm_unreachable("Invalid StmtClass!"); 15455 } 15456 15457 /// Evaluate an expression as a C++11 integral constant expression. 15458 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15459 const Expr *E, 15460 llvm::APSInt *Value, 15461 SourceLocation *Loc) { 15462 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15463 if (Loc) *Loc = E->getExprLoc(); 15464 return false; 15465 } 15466 15467 APValue Result; 15468 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15469 return false; 15470 15471 if (!Result.isInt()) { 15472 if (Loc) *Loc = E->getExprLoc(); 15473 return false; 15474 } 15475 15476 if (Value) *Value = Result.getInt(); 15477 return true; 15478 } 15479 15480 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15481 SourceLocation *Loc) const { 15482 assert(!isValueDependent() && 15483 "Expression evaluator can't be called on a dependent expression."); 15484 15485 if (Ctx.getLangOpts().CPlusPlus11) 15486 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15487 15488 ICEDiag D = CheckICE(this, Ctx); 15489 if (D.Kind != IK_ICE) { 15490 if (Loc) *Loc = D.Loc; 15491 return false; 15492 } 15493 return true; 15494 } 15495 15496 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15497 SourceLocation *Loc, 15498 bool isEvaluated) const { 15499 assert(!isValueDependent() && 15500 "Expression evaluator can't be called on a dependent expression."); 15501 15502 APSInt Value; 15503 15504 if (Ctx.getLangOpts().CPlusPlus11) { 15505 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15506 return Value; 15507 return None; 15508 } 15509 15510 if (!isIntegerConstantExpr(Ctx, Loc)) 15511 return None; 15512 15513 // The only possible side-effects here are due to UB discovered in the 15514 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15515 // required to treat the expression as an ICE, so we produce the folded 15516 // value. 15517 EvalResult ExprResult; 15518 Expr::EvalStatus Status; 15519 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15520 Info.InConstantContext = true; 15521 15522 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15523 llvm_unreachable("ICE cannot be evaluated!"); 15524 15525 return ExprResult.Val.getInt(); 15526 } 15527 15528 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15529 assert(!isValueDependent() && 15530 "Expression evaluator can't be called on a dependent expression."); 15531 15532 return CheckICE(this, Ctx).Kind == IK_ICE; 15533 } 15534 15535 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15536 SourceLocation *Loc) const { 15537 assert(!isValueDependent() && 15538 "Expression evaluator can't be called on a dependent expression."); 15539 15540 // We support this checking in C++98 mode in order to diagnose compatibility 15541 // issues. 15542 assert(Ctx.getLangOpts().CPlusPlus); 15543 15544 // Build evaluation settings. 15545 Expr::EvalStatus Status; 15546 SmallVector<PartialDiagnosticAt, 8> Diags; 15547 Status.Diag = &Diags; 15548 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15549 15550 APValue Scratch; 15551 bool IsConstExpr = 15552 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15553 // FIXME: We don't produce a diagnostic for this, but the callers that 15554 // call us on arbitrary full-expressions should generally not care. 15555 Info.discardCleanups() && !Status.HasSideEffects; 15556 15557 if (!Diags.empty()) { 15558 IsConstExpr = false; 15559 if (Loc) *Loc = Diags[0].first; 15560 } else if (!IsConstExpr) { 15561 // FIXME: This shouldn't happen. 15562 if (Loc) *Loc = getExprLoc(); 15563 } 15564 15565 return IsConstExpr; 15566 } 15567 15568 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15569 const FunctionDecl *Callee, 15570 ArrayRef<const Expr*> Args, 15571 const Expr *This) const { 15572 assert(!isValueDependent() && 15573 "Expression evaluator can't be called on a dependent expression."); 15574 15575 Expr::EvalStatus Status; 15576 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15577 Info.InConstantContext = true; 15578 15579 LValue ThisVal; 15580 const LValue *ThisPtr = nullptr; 15581 if (This) { 15582 #ifndef NDEBUG 15583 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15584 assert(MD && "Don't provide `this` for non-methods."); 15585 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15586 #endif 15587 if (!This->isValueDependent() && 15588 EvaluateObjectArgument(Info, This, ThisVal) && 15589 !Info.EvalStatus.HasSideEffects) 15590 ThisPtr = &ThisVal; 15591 15592 // Ignore any side-effects from a failed evaluation. This is safe because 15593 // they can't interfere with any other argument evaluation. 15594 Info.EvalStatus.HasSideEffects = false; 15595 } 15596 15597 CallRef Call = Info.CurrentCall->createCall(Callee); 15598 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15599 I != E; ++I) { 15600 unsigned Idx = I - Args.begin(); 15601 if (Idx >= Callee->getNumParams()) 15602 break; 15603 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15604 if ((*I)->isValueDependent() || 15605 !EvaluateCallArg(PVD, *I, Call, Info) || 15606 Info.EvalStatus.HasSideEffects) { 15607 // If evaluation fails, throw away the argument entirely. 15608 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15609 *Slot = APValue(); 15610 } 15611 15612 // Ignore any side-effects from a failed evaluation. This is safe because 15613 // they can't interfere with any other argument evaluation. 15614 Info.EvalStatus.HasSideEffects = false; 15615 } 15616 15617 // Parameter cleanups happen in the caller and are not part of this 15618 // evaluation. 15619 Info.discardCleanups(); 15620 Info.EvalStatus.HasSideEffects = false; 15621 15622 // Build fake call to Callee. 15623 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15624 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15625 FullExpressionRAII Scope(Info); 15626 return Evaluate(Value, Info, this) && Scope.destroy() && 15627 !Info.EvalStatus.HasSideEffects; 15628 } 15629 15630 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15631 SmallVectorImpl< 15632 PartialDiagnosticAt> &Diags) { 15633 // FIXME: It would be useful to check constexpr function templates, but at the 15634 // moment the constant expression evaluator cannot cope with the non-rigorous 15635 // ASTs which we build for dependent expressions. 15636 if (FD->isDependentContext()) 15637 return true; 15638 15639 Expr::EvalStatus Status; 15640 Status.Diag = &Diags; 15641 15642 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15643 Info.InConstantContext = true; 15644 Info.CheckingPotentialConstantExpression = true; 15645 15646 // The constexpr VM attempts to compile all methods to bytecode here. 15647 if (Info.EnableNewConstInterp) { 15648 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15649 return Diags.empty(); 15650 } 15651 15652 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15653 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15654 15655 // Fabricate an arbitrary expression on the stack and pretend that it 15656 // is a temporary being used as the 'this' pointer. 15657 LValue This; 15658 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15659 This.set({&VIE, Info.CurrentCall->Index}); 15660 15661 ArrayRef<const Expr*> Args; 15662 15663 APValue Scratch; 15664 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15665 // Evaluate the call as a constant initializer, to allow the construction 15666 // of objects of non-literal types. 15667 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15668 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15669 } else { 15670 SourceLocation Loc = FD->getLocation(); 15671 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15672 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15673 } 15674 15675 return Diags.empty(); 15676 } 15677 15678 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15679 const FunctionDecl *FD, 15680 SmallVectorImpl< 15681 PartialDiagnosticAt> &Diags) { 15682 assert(!E->isValueDependent() && 15683 "Expression evaluator can't be called on a dependent expression."); 15684 15685 Expr::EvalStatus Status; 15686 Status.Diag = &Diags; 15687 15688 EvalInfo Info(FD->getASTContext(), Status, 15689 EvalInfo::EM_ConstantExpressionUnevaluated); 15690 Info.InConstantContext = true; 15691 Info.CheckingPotentialConstantExpression = true; 15692 15693 // Fabricate a call stack frame to give the arguments a plausible cover story. 15694 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15695 15696 APValue ResultScratch; 15697 Evaluate(ResultScratch, Info, E); 15698 return Diags.empty(); 15699 } 15700 15701 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15702 unsigned Type) const { 15703 if (!getType()->isPointerType()) 15704 return false; 15705 15706 Expr::EvalStatus Status; 15707 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15708 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15709 } 15710