1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 return B.getType(); 83 } 84 85 /// Get an LValue path entry, which is known to not be an array index, as a 86 /// field declaration. 87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 89 } 90 /// Get an LValue path entry, which is known to not be an array index, as a 91 /// base class declaration. 92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 94 } 95 /// Determine whether this LValue path entry for a base class names a virtual 96 /// base class. 97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 98 return E.getAsBaseOrMember().getInt(); 99 } 100 101 /// Given an expression, determine the type used to store the result of 102 /// evaluating that expression. 103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 104 if (E->isRValue()) 105 return E->getType(); 106 return Ctx.getLValueReferenceType(E->getType()); 107 } 108 109 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 111 const FunctionDecl *Callee = CE->getDirectCallee(); 112 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 113 } 114 115 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 116 /// This will look through a single cast. 117 /// 118 /// Returns null if we couldn't unwrap a function with alloc_size. 119 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 120 if (!E->getType()->isPointerType()) 121 return nullptr; 122 123 E = E->IgnoreParens(); 124 // If we're doing a variable assignment from e.g. malloc(N), there will 125 // probably be a cast of some kind. In exotic cases, we might also see a 126 // top-level ExprWithCleanups. Ignore them either way. 127 if (const auto *FE = dyn_cast<FullExpr>(E)) 128 E = FE->getSubExpr()->IgnoreParens(); 129 130 if (const auto *Cast = dyn_cast<CastExpr>(E)) 131 E = Cast->getSubExpr()->IgnoreParens(); 132 133 if (const auto *CE = dyn_cast<CallExpr>(E)) 134 return getAllocSizeAttr(CE) ? CE : nullptr; 135 return nullptr; 136 } 137 138 /// Determines whether or not the given Base contains a call to a function 139 /// with the alloc_size attribute. 140 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 141 const auto *E = Base.dyn_cast<const Expr *>(); 142 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 143 } 144 145 /// Determines whether the given kind of constant expression is only ever 146 /// used for name mangling. If so, it's permitted to reference things that we 147 /// can't generate code for (in particular, dllimported functions). 148 static bool isForManglingOnly(ConstantExprKind Kind) { 149 switch (Kind) { 150 case ConstantExprKind::Normal: 151 case ConstantExprKind::ClassTemplateArgument: 152 case ConstantExprKind::ImmediateInvocation: 153 // Note that non-type template arguments of class type are emitted as 154 // template parameter objects. 155 return false; 156 157 case ConstantExprKind::NonClassTemplateArgument: 158 return true; 159 } 160 llvm_unreachable("unknown ConstantExprKind"); 161 } 162 163 static bool isTemplateArgument(ConstantExprKind Kind) { 164 switch (Kind) { 165 case ConstantExprKind::Normal: 166 case ConstantExprKind::ImmediateInvocation: 167 return false; 168 169 case ConstantExprKind::ClassTemplateArgument: 170 case ConstantExprKind::NonClassTemplateArgument: 171 return true; 172 } 173 llvm_unreachable("unknown ConstantExprKind"); 174 } 175 176 /// The bound to claim that an array of unknown bound has. 177 /// The value in MostDerivedArraySize is undefined in this case. So, set it 178 /// to an arbitrary value that's likely to loudly break things if it's used. 179 static const uint64_t AssumedSizeForUnsizedArray = 180 std::numeric_limits<uint64_t>::max() / 2; 181 182 /// Determines if an LValue with the given LValueBase will have an unsized 183 /// array in its designator. 184 /// Find the path length and type of the most-derived subobject in the given 185 /// path, and find the size of the containing array, if any. 186 static unsigned 187 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 188 ArrayRef<APValue::LValuePathEntry> Path, 189 uint64_t &ArraySize, QualType &Type, bool &IsArray, 190 bool &FirstEntryIsUnsizedArray) { 191 // This only accepts LValueBases from APValues, and APValues don't support 192 // arrays that lack size info. 193 assert(!isBaseAnAllocSizeCall(Base) && 194 "Unsized arrays shouldn't appear here"); 195 unsigned MostDerivedLength = 0; 196 Type = getType(Base); 197 198 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 199 if (Type->isArrayType()) { 200 const ArrayType *AT = Ctx.getAsArrayType(Type); 201 Type = AT->getElementType(); 202 MostDerivedLength = I + 1; 203 IsArray = true; 204 205 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 206 ArraySize = CAT->getSize().getZExtValue(); 207 } else { 208 assert(I == 0 && "unexpected unsized array designator"); 209 FirstEntryIsUnsizedArray = true; 210 ArraySize = AssumedSizeForUnsizedArray; 211 } 212 } else if (Type->isAnyComplexType()) { 213 const ComplexType *CT = Type->castAs<ComplexType>(); 214 Type = CT->getElementType(); 215 ArraySize = 2; 216 MostDerivedLength = I + 1; 217 IsArray = true; 218 } else if (const FieldDecl *FD = getAsField(Path[I])) { 219 Type = FD->getType(); 220 ArraySize = 0; 221 MostDerivedLength = I + 1; 222 IsArray = false; 223 } else { 224 // Path[I] describes a base class. 225 ArraySize = 0; 226 IsArray = false; 227 } 228 } 229 return MostDerivedLength; 230 } 231 232 /// A path from a glvalue to a subobject of that glvalue. 233 struct SubobjectDesignator { 234 /// True if the subobject was named in a manner not supported by C++11. Such 235 /// lvalues can still be folded, but they are not core constant expressions 236 /// and we cannot perform lvalue-to-rvalue conversions on them. 237 unsigned Invalid : 1; 238 239 /// Is this a pointer one past the end of an object? 240 unsigned IsOnePastTheEnd : 1; 241 242 /// Indicator of whether the first entry is an unsized array. 243 unsigned FirstEntryIsAnUnsizedArray : 1; 244 245 /// Indicator of whether the most-derived object is an array element. 246 unsigned MostDerivedIsArrayElement : 1; 247 248 /// The length of the path to the most-derived object of which this is a 249 /// subobject. 250 unsigned MostDerivedPathLength : 28; 251 252 /// The size of the array of which the most-derived object is an element. 253 /// This will always be 0 if the most-derived object is not an array 254 /// element. 0 is not an indicator of whether or not the most-derived object 255 /// is an array, however, because 0-length arrays are allowed. 256 /// 257 /// If the current array is an unsized array, the value of this is 258 /// undefined. 259 uint64_t MostDerivedArraySize; 260 261 /// The type of the most derived object referred to by this address. 262 QualType MostDerivedType; 263 264 typedef APValue::LValuePathEntry PathEntry; 265 266 /// The entries on the path from the glvalue to the designated subobject. 267 SmallVector<PathEntry, 8> Entries; 268 269 SubobjectDesignator() : Invalid(true) {} 270 271 explicit SubobjectDesignator(QualType T) 272 : Invalid(false), IsOnePastTheEnd(false), 273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 274 MostDerivedPathLength(0), MostDerivedArraySize(0), 275 MostDerivedType(T) {} 276 277 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 278 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 280 MostDerivedPathLength(0), MostDerivedArraySize(0) { 281 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 282 if (!Invalid) { 283 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 284 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 285 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 286 if (V.getLValueBase()) { 287 bool IsArray = false; 288 bool FirstIsUnsizedArray = false; 289 MostDerivedPathLength = findMostDerivedSubobject( 290 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 291 MostDerivedType, IsArray, FirstIsUnsizedArray); 292 MostDerivedIsArrayElement = IsArray; 293 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 294 } 295 } 296 } 297 298 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 299 unsigned NewLength) { 300 if (Invalid) 301 return; 302 303 assert(Base && "cannot truncate path for null pointer"); 304 assert(NewLength <= Entries.size() && "not a truncation"); 305 306 if (NewLength == Entries.size()) 307 return; 308 Entries.resize(NewLength); 309 310 bool IsArray = false; 311 bool FirstIsUnsizedArray = false; 312 MostDerivedPathLength = findMostDerivedSubobject( 313 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 314 FirstIsUnsizedArray); 315 MostDerivedIsArrayElement = IsArray; 316 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 317 } 318 319 void setInvalid() { 320 Invalid = true; 321 Entries.clear(); 322 } 323 324 /// Determine whether the most derived subobject is an array without a 325 /// known bound. 326 bool isMostDerivedAnUnsizedArray() const { 327 assert(!Invalid && "Calling this makes no sense on invalid designators"); 328 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 329 } 330 331 /// Determine what the most derived array's size is. Results in an assertion 332 /// failure if the most derived array lacks a size. 333 uint64_t getMostDerivedArraySize() const { 334 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 335 return MostDerivedArraySize; 336 } 337 338 /// Determine whether this is a one-past-the-end pointer. 339 bool isOnePastTheEnd() const { 340 assert(!Invalid); 341 if (IsOnePastTheEnd) 342 return true; 343 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 344 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 345 MostDerivedArraySize) 346 return true; 347 return false; 348 } 349 350 /// Get the range of valid index adjustments in the form 351 /// {maximum value that can be subtracted from this pointer, 352 /// maximum value that can be added to this pointer} 353 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 354 if (Invalid || isMostDerivedAnUnsizedArray()) 355 return {0, 0}; 356 357 // [expr.add]p4: For the purposes of these operators, a pointer to a 358 // nonarray object behaves the same as a pointer to the first element of 359 // an array of length one with the type of the object as its element type. 360 bool IsArray = MostDerivedPathLength == Entries.size() && 361 MostDerivedIsArrayElement; 362 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 363 : (uint64_t)IsOnePastTheEnd; 364 uint64_t ArraySize = 365 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 366 return {ArrayIndex, ArraySize - ArrayIndex}; 367 } 368 369 /// Check that this refers to a valid subobject. 370 bool isValidSubobject() const { 371 if (Invalid) 372 return false; 373 return !isOnePastTheEnd(); 374 } 375 /// Check that this refers to a valid subobject, and if not, produce a 376 /// relevant diagnostic and set the designator as invalid. 377 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 378 379 /// Get the type of the designated object. 380 QualType getType(ASTContext &Ctx) const { 381 assert(!Invalid && "invalid designator has no subobject type"); 382 return MostDerivedPathLength == Entries.size() 383 ? MostDerivedType 384 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 385 } 386 387 /// Update this designator to refer to the first element within this array. 388 void addArrayUnchecked(const ConstantArrayType *CAT) { 389 Entries.push_back(PathEntry::ArrayIndex(0)); 390 391 // This is a most-derived object. 392 MostDerivedType = CAT->getElementType(); 393 MostDerivedIsArrayElement = true; 394 MostDerivedArraySize = CAT->getSize().getZExtValue(); 395 MostDerivedPathLength = Entries.size(); 396 } 397 /// Update this designator to refer to the first element within the array of 398 /// elements of type T. This is an array of unknown size. 399 void addUnsizedArrayUnchecked(QualType ElemTy) { 400 Entries.push_back(PathEntry::ArrayIndex(0)); 401 402 MostDerivedType = ElemTy; 403 MostDerivedIsArrayElement = true; 404 // The value in MostDerivedArraySize is undefined in this case. So, set it 405 // to an arbitrary value that's likely to loudly break things if it's 406 // used. 407 MostDerivedArraySize = AssumedSizeForUnsizedArray; 408 MostDerivedPathLength = Entries.size(); 409 } 410 /// Update this designator to refer to the given base or member of this 411 /// object. 412 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 413 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 414 415 // If this isn't a base class, it's a new most-derived object. 416 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 417 MostDerivedType = FD->getType(); 418 MostDerivedIsArrayElement = false; 419 MostDerivedArraySize = 0; 420 MostDerivedPathLength = Entries.size(); 421 } 422 } 423 /// Update this designator to refer to the given complex component. 424 void addComplexUnchecked(QualType EltTy, bool Imag) { 425 Entries.push_back(PathEntry::ArrayIndex(Imag)); 426 427 // This is technically a most-derived object, though in practice this 428 // is unlikely to matter. 429 MostDerivedType = EltTy; 430 MostDerivedIsArrayElement = true; 431 MostDerivedArraySize = 2; 432 MostDerivedPathLength = Entries.size(); 433 } 434 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 435 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 436 const APSInt &N); 437 /// Add N to the address of this subobject. 438 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 439 if (Invalid || !N) return; 440 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 441 if (isMostDerivedAnUnsizedArray()) { 442 diagnoseUnsizedArrayPointerArithmetic(Info, E); 443 // Can't verify -- trust that the user is doing the right thing (or if 444 // not, trust that the caller will catch the bad behavior). 445 // FIXME: Should we reject if this overflows, at least? 446 Entries.back() = PathEntry::ArrayIndex( 447 Entries.back().getAsArrayIndex() + TruncatedN); 448 return; 449 } 450 451 // [expr.add]p4: For the purposes of these operators, a pointer to a 452 // nonarray object behaves the same as a pointer to the first element of 453 // an array of length one with the type of the object as its element type. 454 bool IsArray = MostDerivedPathLength == Entries.size() && 455 MostDerivedIsArrayElement; 456 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 457 : (uint64_t)IsOnePastTheEnd; 458 uint64_t ArraySize = 459 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 460 461 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 462 // Calculate the actual index in a wide enough type, so we can include 463 // it in the note. 464 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 465 (llvm::APInt&)N += ArrayIndex; 466 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 467 diagnosePointerArithmetic(Info, E, N); 468 setInvalid(); 469 return; 470 } 471 472 ArrayIndex += TruncatedN; 473 assert(ArrayIndex <= ArraySize && 474 "bounds check succeeded for out-of-bounds index"); 475 476 if (IsArray) 477 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 478 else 479 IsOnePastTheEnd = (ArrayIndex != 0); 480 } 481 }; 482 483 /// A scope at the end of which an object can need to be destroyed. 484 enum class ScopeKind { 485 Block, 486 FullExpression, 487 Call 488 }; 489 490 /// A reference to a particular call and its arguments. 491 struct CallRef { 492 CallRef() : OrigCallee(), CallIndex(0), Version() {} 493 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 494 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 495 496 explicit operator bool() const { return OrigCallee; } 497 498 /// Get the parameter that the caller initialized, corresponding to the 499 /// given parameter in the callee. 500 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 501 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 502 : PVD; 503 } 504 505 /// The callee at the point where the arguments were evaluated. This might 506 /// be different from the actual callee (a different redeclaration, or a 507 /// virtual override), but this function's parameters are the ones that 508 /// appear in the parameter map. 509 const FunctionDecl *OrigCallee; 510 /// The call index of the frame that holds the argument values. 511 unsigned CallIndex; 512 /// The version of the parameters corresponding to this call. 513 unsigned Version; 514 }; 515 516 /// A stack frame in the constexpr call stack. 517 class CallStackFrame : public interp::Frame { 518 public: 519 EvalInfo &Info; 520 521 /// Parent - The caller of this stack frame. 522 CallStackFrame *Caller; 523 524 /// Callee - The function which was called. 525 const FunctionDecl *Callee; 526 527 /// This - The binding for the this pointer in this call, if any. 528 const LValue *This; 529 530 /// Information on how to find the arguments to this call. Our arguments 531 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 532 /// key and this value as the version. 533 CallRef Arguments; 534 535 /// Source location information about the default argument or default 536 /// initializer expression we're evaluating, if any. 537 CurrentSourceLocExprScope CurSourceLocExprScope; 538 539 // Note that we intentionally use std::map here so that references to 540 // values are stable. 541 typedef std::pair<const void *, unsigned> MapKeyTy; 542 typedef std::map<MapKeyTy, APValue> MapTy; 543 /// Temporaries - Temporary lvalues materialized within this stack frame. 544 MapTy Temporaries; 545 546 /// CallLoc - The location of the call expression for this call. 547 SourceLocation CallLoc; 548 549 /// Index - The call index of this call. 550 unsigned Index; 551 552 /// The stack of integers for tracking version numbers for temporaries. 553 SmallVector<unsigned, 2> TempVersionStack = {1}; 554 unsigned CurTempVersion = TempVersionStack.back(); 555 556 unsigned getTempVersion() const { return TempVersionStack.back(); } 557 558 void pushTempVersion() { 559 TempVersionStack.push_back(++CurTempVersion); 560 } 561 562 void popTempVersion() { 563 TempVersionStack.pop_back(); 564 } 565 566 CallRef createCall(const FunctionDecl *Callee) { 567 return {Callee, Index, ++CurTempVersion}; 568 } 569 570 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 571 // on the overall stack usage of deeply-recursing constexpr evaluations. 572 // (We should cache this map rather than recomputing it repeatedly.) 573 // But let's try this and see how it goes; we can look into caching the map 574 // as a later change. 575 576 /// LambdaCaptureFields - Mapping from captured variables/this to 577 /// corresponding data members in the closure class. 578 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 579 FieldDecl *LambdaThisCaptureField; 580 581 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 582 const FunctionDecl *Callee, const LValue *This, 583 CallRef Arguments); 584 ~CallStackFrame(); 585 586 // Return the temporary for Key whose version number is Version. 587 APValue *getTemporary(const void *Key, unsigned Version) { 588 MapKeyTy KV(Key, Version); 589 auto LB = Temporaries.lower_bound(KV); 590 if (LB != Temporaries.end() && LB->first == KV) 591 return &LB->second; 592 // Pair (Key,Version) wasn't found in the map. Check that no elements 593 // in the map have 'Key' as their key. 594 assert((LB == Temporaries.end() || LB->first.first != Key) && 595 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 596 "Element with key 'Key' found in map"); 597 return nullptr; 598 } 599 600 // Return the current temporary for Key in the map. 601 APValue *getCurrentTemporary(const void *Key) { 602 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 603 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 604 return &std::prev(UB)->second; 605 return nullptr; 606 } 607 608 // Return the version number of the current temporary for Key. 609 unsigned getCurrentTemporaryVersion(const void *Key) const { 610 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 611 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 612 return std::prev(UB)->first.second; 613 return 0; 614 } 615 616 /// Allocate storage for an object of type T in this stack frame. 617 /// Populates LV with a handle to the created object. Key identifies 618 /// the temporary within the stack frame, and must not be reused without 619 /// bumping the temporary version number. 620 template<typename KeyT> 621 APValue &createTemporary(const KeyT *Key, QualType T, 622 ScopeKind Scope, LValue &LV); 623 624 /// Allocate storage for a parameter of a function call made in this frame. 625 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 626 627 void describe(llvm::raw_ostream &OS) override; 628 629 Frame *getCaller() const override { return Caller; } 630 SourceLocation getCallLocation() const override { return CallLoc; } 631 const FunctionDecl *getCallee() const override { return Callee; } 632 633 bool isStdFunction() const { 634 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 635 if (DC->isStdNamespace()) 636 return true; 637 return false; 638 } 639 640 private: 641 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 642 ScopeKind Scope); 643 }; 644 645 /// Temporarily override 'this'. 646 class ThisOverrideRAII { 647 public: 648 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 649 : Frame(Frame), OldThis(Frame.This) { 650 if (Enable) 651 Frame.This = NewThis; 652 } 653 ~ThisOverrideRAII() { 654 Frame.This = OldThis; 655 } 656 private: 657 CallStackFrame &Frame; 658 const LValue *OldThis; 659 }; 660 } 661 662 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 663 const LValue &This, QualType ThisType); 664 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 665 APValue::LValueBase LVBase, APValue &Value, 666 QualType T); 667 668 namespace { 669 /// A cleanup, and a flag indicating whether it is lifetime-extended. 670 class Cleanup { 671 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 672 APValue::LValueBase Base; 673 QualType T; 674 675 public: 676 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 677 ScopeKind Scope) 678 : Value(Val, Scope), Base(Base), T(T) {} 679 680 /// Determine whether this cleanup should be performed at the end of the 681 /// given kind of scope. 682 bool isDestroyedAtEndOf(ScopeKind K) const { 683 return (int)Value.getInt() >= (int)K; 684 } 685 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 686 if (RunDestructors) { 687 SourceLocation Loc; 688 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 689 Loc = VD->getLocation(); 690 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 691 Loc = E->getExprLoc(); 692 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 693 } 694 *Value.getPointer() = APValue(); 695 return true; 696 } 697 698 bool hasSideEffect() { 699 return T.isDestructedType(); 700 } 701 }; 702 703 /// A reference to an object whose construction we are currently evaluating. 704 struct ObjectUnderConstruction { 705 APValue::LValueBase Base; 706 ArrayRef<APValue::LValuePathEntry> Path; 707 friend bool operator==(const ObjectUnderConstruction &LHS, 708 const ObjectUnderConstruction &RHS) { 709 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 710 } 711 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 712 return llvm::hash_combine(Obj.Base, Obj.Path); 713 } 714 }; 715 enum class ConstructionPhase { 716 None, 717 Bases, 718 AfterBases, 719 AfterFields, 720 Destroying, 721 DestroyingBases 722 }; 723 } 724 725 namespace llvm { 726 template<> struct DenseMapInfo<ObjectUnderConstruction> { 727 using Base = DenseMapInfo<APValue::LValueBase>; 728 static ObjectUnderConstruction getEmptyKey() { 729 return {Base::getEmptyKey(), {}}; } 730 static ObjectUnderConstruction getTombstoneKey() { 731 return {Base::getTombstoneKey(), {}}; 732 } 733 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 734 return hash_value(Object); 735 } 736 static bool isEqual(const ObjectUnderConstruction &LHS, 737 const ObjectUnderConstruction &RHS) { 738 return LHS == RHS; 739 } 740 }; 741 } 742 743 namespace { 744 /// A dynamically-allocated heap object. 745 struct DynAlloc { 746 /// The value of this heap-allocated object. 747 APValue Value; 748 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 749 /// or a CallExpr (the latter is for direct calls to operator new inside 750 /// std::allocator<T>::allocate). 751 const Expr *AllocExpr = nullptr; 752 753 enum Kind { 754 New, 755 ArrayNew, 756 StdAllocator 757 }; 758 759 /// Get the kind of the allocation. This must match between allocation 760 /// and deallocation. 761 Kind getKind() const { 762 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 763 return NE->isArray() ? ArrayNew : New; 764 assert(isa<CallExpr>(AllocExpr)); 765 return StdAllocator; 766 } 767 }; 768 769 struct DynAllocOrder { 770 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 771 return L.getIndex() < R.getIndex(); 772 } 773 }; 774 775 /// EvalInfo - This is a private struct used by the evaluator to capture 776 /// information about a subexpression as it is folded. It retains information 777 /// about the AST context, but also maintains information about the folded 778 /// expression. 779 /// 780 /// If an expression could be evaluated, it is still possible it is not a C 781 /// "integer constant expression" or constant expression. If not, this struct 782 /// captures information about how and why not. 783 /// 784 /// One bit of information passed *into* the request for constant folding 785 /// indicates whether the subexpression is "evaluated" or not according to C 786 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 787 /// evaluate the expression regardless of what the RHS is, but C only allows 788 /// certain things in certain situations. 789 class EvalInfo : public interp::State { 790 public: 791 ASTContext &Ctx; 792 793 /// EvalStatus - Contains information about the evaluation. 794 Expr::EvalStatus &EvalStatus; 795 796 /// CurrentCall - The top of the constexpr call stack. 797 CallStackFrame *CurrentCall; 798 799 /// CallStackDepth - The number of calls in the call stack right now. 800 unsigned CallStackDepth; 801 802 /// NextCallIndex - The next call index to assign. 803 unsigned NextCallIndex; 804 805 /// StepsLeft - The remaining number of evaluation steps we're permitted 806 /// to perform. This is essentially a limit for the number of statements 807 /// we will evaluate. 808 unsigned StepsLeft; 809 810 /// Enable the experimental new constant interpreter. If an expression is 811 /// not supported by the interpreter, an error is triggered. 812 bool EnableNewConstInterp; 813 814 /// BottomFrame - The frame in which evaluation started. This must be 815 /// initialized after CurrentCall and CallStackDepth. 816 CallStackFrame BottomFrame; 817 818 /// A stack of values whose lifetimes end at the end of some surrounding 819 /// evaluation frame. 820 llvm::SmallVector<Cleanup, 16> CleanupStack; 821 822 /// EvaluatingDecl - This is the declaration whose initializer is being 823 /// evaluated, if any. 824 APValue::LValueBase EvaluatingDecl; 825 826 enum class EvaluatingDeclKind { 827 None, 828 /// We're evaluating the construction of EvaluatingDecl. 829 Ctor, 830 /// We're evaluating the destruction of EvaluatingDecl. 831 Dtor, 832 }; 833 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 834 835 /// EvaluatingDeclValue - This is the value being constructed for the 836 /// declaration whose initializer is being evaluated, if any. 837 APValue *EvaluatingDeclValue; 838 839 /// Set of objects that are currently being constructed. 840 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 841 ObjectsUnderConstruction; 842 843 /// Current heap allocations, along with the location where each was 844 /// allocated. We use std::map here because we need stable addresses 845 /// for the stored APValues. 846 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 847 848 /// The number of heap allocations performed so far in this evaluation. 849 unsigned NumHeapAllocs = 0; 850 851 struct EvaluatingConstructorRAII { 852 EvalInfo &EI; 853 ObjectUnderConstruction Object; 854 bool DidInsert; 855 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 856 bool HasBases) 857 : EI(EI), Object(Object) { 858 DidInsert = 859 EI.ObjectsUnderConstruction 860 .insert({Object, HasBases ? ConstructionPhase::Bases 861 : ConstructionPhase::AfterBases}) 862 .second; 863 } 864 void finishedConstructingBases() { 865 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 866 } 867 void finishedConstructingFields() { 868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 869 } 870 ~EvaluatingConstructorRAII() { 871 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 872 } 873 }; 874 875 struct EvaluatingDestructorRAII { 876 EvalInfo &EI; 877 ObjectUnderConstruction Object; 878 bool DidInsert; 879 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 880 : EI(EI), Object(Object) { 881 DidInsert = EI.ObjectsUnderConstruction 882 .insert({Object, ConstructionPhase::Destroying}) 883 .second; 884 } 885 void startedDestroyingBases() { 886 EI.ObjectsUnderConstruction[Object] = 887 ConstructionPhase::DestroyingBases; 888 } 889 ~EvaluatingDestructorRAII() { 890 if (DidInsert) 891 EI.ObjectsUnderConstruction.erase(Object); 892 } 893 }; 894 895 ConstructionPhase 896 isEvaluatingCtorDtor(APValue::LValueBase Base, 897 ArrayRef<APValue::LValuePathEntry> Path) { 898 return ObjectsUnderConstruction.lookup({Base, Path}); 899 } 900 901 /// If we're currently speculatively evaluating, the outermost call stack 902 /// depth at which we can mutate state, otherwise 0. 903 unsigned SpeculativeEvaluationDepth = 0; 904 905 /// The current array initialization index, if we're performing array 906 /// initialization. 907 uint64_t ArrayInitIndex = -1; 908 909 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 910 /// notes attached to it will also be stored, otherwise they will not be. 911 bool HasActiveDiagnostic; 912 913 /// Have we emitted a diagnostic explaining why we couldn't constant 914 /// fold (not just why it's not strictly a constant expression)? 915 bool HasFoldFailureDiagnostic; 916 917 /// Whether or not we're in a context where the front end requires a 918 /// constant value. 919 bool InConstantContext; 920 921 /// Whether we're checking that an expression is a potential constant 922 /// expression. If so, do not fail on constructs that could become constant 923 /// later on (such as a use of an undefined global). 924 bool CheckingPotentialConstantExpression = false; 925 926 /// Whether we're checking for an expression that has undefined behavior. 927 /// If so, we will produce warnings if we encounter an operation that is 928 /// always undefined. 929 bool CheckingForUndefinedBehavior = false; 930 931 enum EvaluationMode { 932 /// Evaluate as a constant expression. Stop if we find that the expression 933 /// is not a constant expression. 934 EM_ConstantExpression, 935 936 /// Evaluate as a constant expression. Stop if we find that the expression 937 /// is not a constant expression. Some expressions can be retried in the 938 /// optimizer if we don't constant fold them here, but in an unevaluated 939 /// context we try to fold them immediately since the optimizer never 940 /// gets a chance to look at it. 941 EM_ConstantExpressionUnevaluated, 942 943 /// Fold the expression to a constant. Stop if we hit a side-effect that 944 /// we can't model. 945 EM_ConstantFold, 946 947 /// Evaluate in any way we know how. Don't worry about side-effects that 948 /// can't be modeled. 949 EM_IgnoreSideEffects, 950 } EvalMode; 951 952 /// Are we checking whether the expression is a potential constant 953 /// expression? 954 bool checkingPotentialConstantExpression() const override { 955 return CheckingPotentialConstantExpression; 956 } 957 958 /// Are we checking an expression for overflow? 959 // FIXME: We should check for any kind of undefined or suspicious behavior 960 // in such constructs, not just overflow. 961 bool checkingForUndefinedBehavior() const override { 962 return CheckingForUndefinedBehavior; 963 } 964 965 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 966 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 967 CallStackDepth(0), NextCallIndex(1), 968 StepsLeft(C.getLangOpts().ConstexprStepLimit), 969 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 970 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 971 EvaluatingDecl((const ValueDecl *)nullptr), 972 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 973 HasFoldFailureDiagnostic(false), InConstantContext(false), 974 EvalMode(Mode) {} 975 976 ~EvalInfo() { 977 discardCleanups(); 978 } 979 980 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 981 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 982 EvaluatingDecl = Base; 983 IsEvaluatingDecl = EDK; 984 EvaluatingDeclValue = &Value; 985 } 986 987 bool CheckCallLimit(SourceLocation Loc) { 988 // Don't perform any constexpr calls (other than the call we're checking) 989 // when checking a potential constant expression. 990 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 991 return false; 992 if (NextCallIndex == 0) { 993 // NextCallIndex has wrapped around. 994 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 995 return false; 996 } 997 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 998 return true; 999 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1000 << getLangOpts().ConstexprCallDepth; 1001 return false; 1002 } 1003 1004 std::pair<CallStackFrame *, unsigned> 1005 getCallFrameAndDepth(unsigned CallIndex) { 1006 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1007 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1008 // be null in this loop. 1009 unsigned Depth = CallStackDepth; 1010 CallStackFrame *Frame = CurrentCall; 1011 while (Frame->Index > CallIndex) { 1012 Frame = Frame->Caller; 1013 --Depth; 1014 } 1015 if (Frame->Index == CallIndex) 1016 return {Frame, Depth}; 1017 return {nullptr, 0}; 1018 } 1019 1020 bool nextStep(const Stmt *S) { 1021 if (!StepsLeft) { 1022 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1023 return false; 1024 } 1025 --StepsLeft; 1026 return true; 1027 } 1028 1029 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1030 1031 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1032 Optional<DynAlloc*> Result; 1033 auto It = HeapAllocs.find(DA); 1034 if (It != HeapAllocs.end()) 1035 Result = &It->second; 1036 return Result; 1037 } 1038 1039 /// Get the allocated storage for the given parameter of the given call. 1040 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1041 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1042 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1043 : nullptr; 1044 } 1045 1046 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1047 struct StdAllocatorCaller { 1048 unsigned FrameIndex; 1049 QualType ElemType; 1050 explicit operator bool() const { return FrameIndex != 0; }; 1051 }; 1052 1053 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1054 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1055 Call = Call->Caller) { 1056 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1057 if (!MD) 1058 continue; 1059 const IdentifierInfo *FnII = MD->getIdentifier(); 1060 if (!FnII || !FnII->isStr(FnName)) 1061 continue; 1062 1063 const auto *CTSD = 1064 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1065 if (!CTSD) 1066 continue; 1067 1068 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1069 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1070 if (CTSD->isInStdNamespace() && ClassII && 1071 ClassII->isStr("allocator") && TAL.size() >= 1 && 1072 TAL[0].getKind() == TemplateArgument::Type) 1073 return {Call->Index, TAL[0].getAsType()}; 1074 } 1075 1076 return {}; 1077 } 1078 1079 void performLifetimeExtension() { 1080 // Disable the cleanups for lifetime-extended temporaries. 1081 CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1082 CleanupStack.end(), 1083 [](Cleanup &C) { 1084 return !C.isDestroyedAtEndOf( 1085 ScopeKind::FullExpression); 1086 }), 1087 CleanupStack.end()); 1088 } 1089 1090 /// Throw away any remaining cleanups at the end of evaluation. If any 1091 /// cleanups would have had a side-effect, note that as an unmodeled 1092 /// side-effect and return false. Otherwise, return true. 1093 bool discardCleanups() { 1094 for (Cleanup &C : CleanupStack) { 1095 if (C.hasSideEffect() && !noteSideEffect()) { 1096 CleanupStack.clear(); 1097 return false; 1098 } 1099 } 1100 CleanupStack.clear(); 1101 return true; 1102 } 1103 1104 private: 1105 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1106 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1107 1108 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1109 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1110 1111 void setFoldFailureDiagnostic(bool Flag) override { 1112 HasFoldFailureDiagnostic = Flag; 1113 } 1114 1115 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1116 1117 ASTContext &getCtx() const override { return Ctx; } 1118 1119 // If we have a prior diagnostic, it will be noting that the expression 1120 // isn't a constant expression. This diagnostic is more important, 1121 // unless we require this evaluation to produce a constant expression. 1122 // 1123 // FIXME: We might want to show both diagnostics to the user in 1124 // EM_ConstantFold mode. 1125 bool hasPriorDiagnostic() override { 1126 if (!EvalStatus.Diag->empty()) { 1127 switch (EvalMode) { 1128 case EM_ConstantFold: 1129 case EM_IgnoreSideEffects: 1130 if (!HasFoldFailureDiagnostic) 1131 break; 1132 // We've already failed to fold something. Keep that diagnostic. 1133 LLVM_FALLTHROUGH; 1134 case EM_ConstantExpression: 1135 case EM_ConstantExpressionUnevaluated: 1136 setActiveDiagnostic(false); 1137 return true; 1138 } 1139 } 1140 return false; 1141 } 1142 1143 unsigned getCallStackDepth() override { return CallStackDepth; } 1144 1145 public: 1146 /// Should we continue evaluation after encountering a side-effect that we 1147 /// couldn't model? 1148 bool keepEvaluatingAfterSideEffect() { 1149 switch (EvalMode) { 1150 case EM_IgnoreSideEffects: 1151 return true; 1152 1153 case EM_ConstantExpression: 1154 case EM_ConstantExpressionUnevaluated: 1155 case EM_ConstantFold: 1156 // By default, assume any side effect might be valid in some other 1157 // evaluation of this expression from a different context. 1158 return checkingPotentialConstantExpression() || 1159 checkingForUndefinedBehavior(); 1160 } 1161 llvm_unreachable("Missed EvalMode case"); 1162 } 1163 1164 /// Note that we have had a side-effect, and determine whether we should 1165 /// keep evaluating. 1166 bool noteSideEffect() { 1167 EvalStatus.HasSideEffects = true; 1168 return keepEvaluatingAfterSideEffect(); 1169 } 1170 1171 /// Should we continue evaluation after encountering undefined behavior? 1172 bool keepEvaluatingAfterUndefinedBehavior() { 1173 switch (EvalMode) { 1174 case EM_IgnoreSideEffects: 1175 case EM_ConstantFold: 1176 return true; 1177 1178 case EM_ConstantExpression: 1179 case EM_ConstantExpressionUnevaluated: 1180 return checkingForUndefinedBehavior(); 1181 } 1182 llvm_unreachable("Missed EvalMode case"); 1183 } 1184 1185 /// Note that we hit something that was technically undefined behavior, but 1186 /// that we can evaluate past it (such as signed overflow or floating-point 1187 /// division by zero.) 1188 bool noteUndefinedBehavior() override { 1189 EvalStatus.HasUndefinedBehavior = true; 1190 return keepEvaluatingAfterUndefinedBehavior(); 1191 } 1192 1193 /// Should we continue evaluation as much as possible after encountering a 1194 /// construct which can't be reduced to a value? 1195 bool keepEvaluatingAfterFailure() const override { 1196 if (!StepsLeft) 1197 return false; 1198 1199 switch (EvalMode) { 1200 case EM_ConstantExpression: 1201 case EM_ConstantExpressionUnevaluated: 1202 case EM_ConstantFold: 1203 case EM_IgnoreSideEffects: 1204 return checkingPotentialConstantExpression() || 1205 checkingForUndefinedBehavior(); 1206 } 1207 llvm_unreachable("Missed EvalMode case"); 1208 } 1209 1210 /// Notes that we failed to evaluate an expression that other expressions 1211 /// directly depend on, and determine if we should keep evaluating. This 1212 /// should only be called if we actually intend to keep evaluating. 1213 /// 1214 /// Call noteSideEffect() instead if we may be able to ignore the value that 1215 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1216 /// 1217 /// (Foo(), 1) // use noteSideEffect 1218 /// (Foo() || true) // use noteSideEffect 1219 /// Foo() + 1 // use noteFailure 1220 LLVM_NODISCARD bool noteFailure() { 1221 // Failure when evaluating some expression often means there is some 1222 // subexpression whose evaluation was skipped. Therefore, (because we 1223 // don't track whether we skipped an expression when unwinding after an 1224 // evaluation failure) every evaluation failure that bubbles up from a 1225 // subexpression implies that a side-effect has potentially happened. We 1226 // skip setting the HasSideEffects flag to true until we decide to 1227 // continue evaluating after that point, which happens here. 1228 bool KeepGoing = keepEvaluatingAfterFailure(); 1229 EvalStatus.HasSideEffects |= KeepGoing; 1230 return KeepGoing; 1231 } 1232 1233 class ArrayInitLoopIndex { 1234 EvalInfo &Info; 1235 uint64_t OuterIndex; 1236 1237 public: 1238 ArrayInitLoopIndex(EvalInfo &Info) 1239 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1240 Info.ArrayInitIndex = 0; 1241 } 1242 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1243 1244 operator uint64_t&() { return Info.ArrayInitIndex; } 1245 }; 1246 }; 1247 1248 /// Object used to treat all foldable expressions as constant expressions. 1249 struct FoldConstant { 1250 EvalInfo &Info; 1251 bool Enabled; 1252 bool HadNoPriorDiags; 1253 EvalInfo::EvaluationMode OldMode; 1254 1255 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1256 : Info(Info), 1257 Enabled(Enabled), 1258 HadNoPriorDiags(Info.EvalStatus.Diag && 1259 Info.EvalStatus.Diag->empty() && 1260 !Info.EvalStatus.HasSideEffects), 1261 OldMode(Info.EvalMode) { 1262 if (Enabled) 1263 Info.EvalMode = EvalInfo::EM_ConstantFold; 1264 } 1265 void keepDiagnostics() { Enabled = false; } 1266 ~FoldConstant() { 1267 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1268 !Info.EvalStatus.HasSideEffects) 1269 Info.EvalStatus.Diag->clear(); 1270 Info.EvalMode = OldMode; 1271 } 1272 }; 1273 1274 /// RAII object used to set the current evaluation mode to ignore 1275 /// side-effects. 1276 struct IgnoreSideEffectsRAII { 1277 EvalInfo &Info; 1278 EvalInfo::EvaluationMode OldMode; 1279 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1280 : Info(Info), OldMode(Info.EvalMode) { 1281 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1282 } 1283 1284 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1285 }; 1286 1287 /// RAII object used to optionally suppress diagnostics and side-effects from 1288 /// a speculative evaluation. 1289 class SpeculativeEvaluationRAII { 1290 EvalInfo *Info = nullptr; 1291 Expr::EvalStatus OldStatus; 1292 unsigned OldSpeculativeEvaluationDepth; 1293 1294 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1295 Info = Other.Info; 1296 OldStatus = Other.OldStatus; 1297 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1298 Other.Info = nullptr; 1299 } 1300 1301 void maybeRestoreState() { 1302 if (!Info) 1303 return; 1304 1305 Info->EvalStatus = OldStatus; 1306 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1307 } 1308 1309 public: 1310 SpeculativeEvaluationRAII() = default; 1311 1312 SpeculativeEvaluationRAII( 1313 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1314 : Info(&Info), OldStatus(Info.EvalStatus), 1315 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1316 Info.EvalStatus.Diag = NewDiag; 1317 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1318 } 1319 1320 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1321 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1322 moveFromAndCancel(std::move(Other)); 1323 } 1324 1325 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1326 maybeRestoreState(); 1327 moveFromAndCancel(std::move(Other)); 1328 return *this; 1329 } 1330 1331 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1332 }; 1333 1334 /// RAII object wrapping a full-expression or block scope, and handling 1335 /// the ending of the lifetime of temporaries created within it. 1336 template<ScopeKind Kind> 1337 class ScopeRAII { 1338 EvalInfo &Info; 1339 unsigned OldStackSize; 1340 public: 1341 ScopeRAII(EvalInfo &Info) 1342 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1343 // Push a new temporary version. This is needed to distinguish between 1344 // temporaries created in different iterations of a loop. 1345 Info.CurrentCall->pushTempVersion(); 1346 } 1347 bool destroy(bool RunDestructors = true) { 1348 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1349 OldStackSize = -1U; 1350 return OK; 1351 } 1352 ~ScopeRAII() { 1353 if (OldStackSize != -1U) 1354 destroy(false); 1355 // Body moved to a static method to encourage the compiler to inline away 1356 // instances of this class. 1357 Info.CurrentCall->popTempVersion(); 1358 } 1359 private: 1360 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1361 unsigned OldStackSize) { 1362 assert(OldStackSize <= Info.CleanupStack.size() && 1363 "running cleanups out of order?"); 1364 1365 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1366 // for a full-expression scope. 1367 bool Success = true; 1368 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1369 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1370 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1371 Success = false; 1372 break; 1373 } 1374 } 1375 } 1376 1377 // Compact any retained cleanups. 1378 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1379 if (Kind != ScopeKind::Block) 1380 NewEnd = 1381 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1382 return C.isDestroyedAtEndOf(Kind); 1383 }); 1384 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1385 return Success; 1386 } 1387 }; 1388 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1389 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1390 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1391 } 1392 1393 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1394 CheckSubobjectKind CSK) { 1395 if (Invalid) 1396 return false; 1397 if (isOnePastTheEnd()) { 1398 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1399 << CSK; 1400 setInvalid(); 1401 return false; 1402 } 1403 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1404 // must actually be at least one array element; even a VLA cannot have a 1405 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1406 return true; 1407 } 1408 1409 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1410 const Expr *E) { 1411 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1412 // Do not set the designator as invalid: we can represent this situation, 1413 // and correct handling of __builtin_object_size requires us to do so. 1414 } 1415 1416 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1417 const Expr *E, 1418 const APSInt &N) { 1419 // If we're complaining, we must be able to statically determine the size of 1420 // the most derived array. 1421 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1422 Info.CCEDiag(E, diag::note_constexpr_array_index) 1423 << N << /*array*/ 0 1424 << static_cast<unsigned>(getMostDerivedArraySize()); 1425 else 1426 Info.CCEDiag(E, diag::note_constexpr_array_index) 1427 << N << /*non-array*/ 1; 1428 setInvalid(); 1429 } 1430 1431 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1432 const FunctionDecl *Callee, const LValue *This, 1433 CallRef Call) 1434 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1435 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1436 Info.CurrentCall = this; 1437 ++Info.CallStackDepth; 1438 } 1439 1440 CallStackFrame::~CallStackFrame() { 1441 assert(Info.CurrentCall == this && "calls retired out of order"); 1442 --Info.CallStackDepth; 1443 Info.CurrentCall = Caller; 1444 } 1445 1446 static bool isRead(AccessKinds AK) { 1447 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1448 } 1449 1450 static bool isModification(AccessKinds AK) { 1451 switch (AK) { 1452 case AK_Read: 1453 case AK_ReadObjectRepresentation: 1454 case AK_MemberCall: 1455 case AK_DynamicCast: 1456 case AK_TypeId: 1457 return false; 1458 case AK_Assign: 1459 case AK_Increment: 1460 case AK_Decrement: 1461 case AK_Construct: 1462 case AK_Destroy: 1463 return true; 1464 } 1465 llvm_unreachable("unknown access kind"); 1466 } 1467 1468 static bool isAnyAccess(AccessKinds AK) { 1469 return isRead(AK) || isModification(AK); 1470 } 1471 1472 /// Is this an access per the C++ definition? 1473 static bool isFormalAccess(AccessKinds AK) { 1474 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1475 } 1476 1477 /// Is this kind of axcess valid on an indeterminate object value? 1478 static bool isValidIndeterminateAccess(AccessKinds AK) { 1479 switch (AK) { 1480 case AK_Read: 1481 case AK_Increment: 1482 case AK_Decrement: 1483 // These need the object's value. 1484 return false; 1485 1486 case AK_ReadObjectRepresentation: 1487 case AK_Assign: 1488 case AK_Construct: 1489 case AK_Destroy: 1490 // Construction and destruction don't need the value. 1491 return true; 1492 1493 case AK_MemberCall: 1494 case AK_DynamicCast: 1495 case AK_TypeId: 1496 // These aren't really meaningful on scalars. 1497 return true; 1498 } 1499 llvm_unreachable("unknown access kind"); 1500 } 1501 1502 namespace { 1503 struct ComplexValue { 1504 private: 1505 bool IsInt; 1506 1507 public: 1508 APSInt IntReal, IntImag; 1509 APFloat FloatReal, FloatImag; 1510 1511 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1512 1513 void makeComplexFloat() { IsInt = false; } 1514 bool isComplexFloat() const { return !IsInt; } 1515 APFloat &getComplexFloatReal() { return FloatReal; } 1516 APFloat &getComplexFloatImag() { return FloatImag; } 1517 1518 void makeComplexInt() { IsInt = true; } 1519 bool isComplexInt() const { return IsInt; } 1520 APSInt &getComplexIntReal() { return IntReal; } 1521 APSInt &getComplexIntImag() { return IntImag; } 1522 1523 void moveInto(APValue &v) const { 1524 if (isComplexFloat()) 1525 v = APValue(FloatReal, FloatImag); 1526 else 1527 v = APValue(IntReal, IntImag); 1528 } 1529 void setFrom(const APValue &v) { 1530 assert(v.isComplexFloat() || v.isComplexInt()); 1531 if (v.isComplexFloat()) { 1532 makeComplexFloat(); 1533 FloatReal = v.getComplexFloatReal(); 1534 FloatImag = v.getComplexFloatImag(); 1535 } else { 1536 makeComplexInt(); 1537 IntReal = v.getComplexIntReal(); 1538 IntImag = v.getComplexIntImag(); 1539 } 1540 } 1541 }; 1542 1543 struct LValue { 1544 APValue::LValueBase Base; 1545 CharUnits Offset; 1546 SubobjectDesignator Designator; 1547 bool IsNullPtr : 1; 1548 bool InvalidBase : 1; 1549 1550 const APValue::LValueBase getLValueBase() const { return Base; } 1551 CharUnits &getLValueOffset() { return Offset; } 1552 const CharUnits &getLValueOffset() const { return Offset; } 1553 SubobjectDesignator &getLValueDesignator() { return Designator; } 1554 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1555 bool isNullPointer() const { return IsNullPtr;} 1556 1557 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1558 unsigned getLValueVersion() const { return Base.getVersion(); } 1559 1560 void moveInto(APValue &V) const { 1561 if (Designator.Invalid) 1562 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1563 else { 1564 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1565 V = APValue(Base, Offset, Designator.Entries, 1566 Designator.IsOnePastTheEnd, IsNullPtr); 1567 } 1568 } 1569 void setFrom(ASTContext &Ctx, const APValue &V) { 1570 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1571 Base = V.getLValueBase(); 1572 Offset = V.getLValueOffset(); 1573 InvalidBase = false; 1574 Designator = SubobjectDesignator(Ctx, V); 1575 IsNullPtr = V.isNullPointer(); 1576 } 1577 1578 void set(APValue::LValueBase B, bool BInvalid = false) { 1579 #ifndef NDEBUG 1580 // We only allow a few types of invalid bases. Enforce that here. 1581 if (BInvalid) { 1582 const auto *E = B.get<const Expr *>(); 1583 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1584 "Unexpected type of invalid base"); 1585 } 1586 #endif 1587 1588 Base = B; 1589 Offset = CharUnits::fromQuantity(0); 1590 InvalidBase = BInvalid; 1591 Designator = SubobjectDesignator(getType(B)); 1592 IsNullPtr = false; 1593 } 1594 1595 void setNull(ASTContext &Ctx, QualType PointerTy) { 1596 Base = (const ValueDecl *)nullptr; 1597 Offset = 1598 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1599 InvalidBase = false; 1600 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1601 IsNullPtr = true; 1602 } 1603 1604 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1605 set(B, true); 1606 } 1607 1608 std::string toString(ASTContext &Ctx, QualType T) const { 1609 APValue Printable; 1610 moveInto(Printable); 1611 return Printable.getAsString(Ctx, T); 1612 } 1613 1614 private: 1615 // Check that this LValue is not based on a null pointer. If it is, produce 1616 // a diagnostic and mark the designator as invalid. 1617 template <typename GenDiagType> 1618 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1619 if (Designator.Invalid) 1620 return false; 1621 if (IsNullPtr) { 1622 GenDiag(); 1623 Designator.setInvalid(); 1624 return false; 1625 } 1626 return true; 1627 } 1628 1629 public: 1630 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1631 CheckSubobjectKind CSK) { 1632 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1633 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1634 }); 1635 } 1636 1637 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1638 AccessKinds AK) { 1639 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1640 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1641 }); 1642 } 1643 1644 // Check this LValue refers to an object. If not, set the designator to be 1645 // invalid and emit a diagnostic. 1646 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1647 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1648 Designator.checkSubobject(Info, E, CSK); 1649 } 1650 1651 void addDecl(EvalInfo &Info, const Expr *E, 1652 const Decl *D, bool Virtual = false) { 1653 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1654 Designator.addDeclUnchecked(D, Virtual); 1655 } 1656 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1657 if (!Designator.Entries.empty()) { 1658 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1659 Designator.setInvalid(); 1660 return; 1661 } 1662 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1663 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1664 Designator.FirstEntryIsAnUnsizedArray = true; 1665 Designator.addUnsizedArrayUnchecked(ElemTy); 1666 } 1667 } 1668 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1669 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1670 Designator.addArrayUnchecked(CAT); 1671 } 1672 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1673 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1674 Designator.addComplexUnchecked(EltTy, Imag); 1675 } 1676 void clearIsNullPointer() { 1677 IsNullPtr = false; 1678 } 1679 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1680 const APSInt &Index, CharUnits ElementSize) { 1681 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1682 // but we're not required to diagnose it and it's valid in C++.) 1683 if (!Index) 1684 return; 1685 1686 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1687 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1688 // offsets. 1689 uint64_t Offset64 = Offset.getQuantity(); 1690 uint64_t ElemSize64 = ElementSize.getQuantity(); 1691 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1692 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1693 1694 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1695 Designator.adjustIndex(Info, E, Index); 1696 clearIsNullPointer(); 1697 } 1698 void adjustOffset(CharUnits N) { 1699 Offset += N; 1700 if (N.getQuantity()) 1701 clearIsNullPointer(); 1702 } 1703 }; 1704 1705 struct MemberPtr { 1706 MemberPtr() {} 1707 explicit MemberPtr(const ValueDecl *Decl) : 1708 DeclAndIsDerivedMember(Decl, false), Path() {} 1709 1710 /// The member or (direct or indirect) field referred to by this member 1711 /// pointer, or 0 if this is a null member pointer. 1712 const ValueDecl *getDecl() const { 1713 return DeclAndIsDerivedMember.getPointer(); 1714 } 1715 /// Is this actually a member of some type derived from the relevant class? 1716 bool isDerivedMember() const { 1717 return DeclAndIsDerivedMember.getInt(); 1718 } 1719 /// Get the class which the declaration actually lives in. 1720 const CXXRecordDecl *getContainingRecord() const { 1721 return cast<CXXRecordDecl>( 1722 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1723 } 1724 1725 void moveInto(APValue &V) const { 1726 V = APValue(getDecl(), isDerivedMember(), Path); 1727 } 1728 void setFrom(const APValue &V) { 1729 assert(V.isMemberPointer()); 1730 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1731 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1732 Path.clear(); 1733 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1734 Path.insert(Path.end(), P.begin(), P.end()); 1735 } 1736 1737 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1738 /// whether the member is a member of some class derived from the class type 1739 /// of the member pointer. 1740 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1741 /// Path - The path of base/derived classes from the member declaration's 1742 /// class (exclusive) to the class type of the member pointer (inclusive). 1743 SmallVector<const CXXRecordDecl*, 4> Path; 1744 1745 /// Perform a cast towards the class of the Decl (either up or down the 1746 /// hierarchy). 1747 bool castBack(const CXXRecordDecl *Class) { 1748 assert(!Path.empty()); 1749 const CXXRecordDecl *Expected; 1750 if (Path.size() >= 2) 1751 Expected = Path[Path.size() - 2]; 1752 else 1753 Expected = getContainingRecord(); 1754 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1755 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1756 // if B does not contain the original member and is not a base or 1757 // derived class of the class containing the original member, the result 1758 // of the cast is undefined. 1759 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1760 // (D::*). We consider that to be a language defect. 1761 return false; 1762 } 1763 Path.pop_back(); 1764 return true; 1765 } 1766 /// Perform a base-to-derived member pointer cast. 1767 bool castToDerived(const CXXRecordDecl *Derived) { 1768 if (!getDecl()) 1769 return true; 1770 if (!isDerivedMember()) { 1771 Path.push_back(Derived); 1772 return true; 1773 } 1774 if (!castBack(Derived)) 1775 return false; 1776 if (Path.empty()) 1777 DeclAndIsDerivedMember.setInt(false); 1778 return true; 1779 } 1780 /// Perform a derived-to-base member pointer cast. 1781 bool castToBase(const CXXRecordDecl *Base) { 1782 if (!getDecl()) 1783 return true; 1784 if (Path.empty()) 1785 DeclAndIsDerivedMember.setInt(true); 1786 if (isDerivedMember()) { 1787 Path.push_back(Base); 1788 return true; 1789 } 1790 return castBack(Base); 1791 } 1792 }; 1793 1794 /// Compare two member pointers, which are assumed to be of the same type. 1795 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1796 if (!LHS.getDecl() || !RHS.getDecl()) 1797 return !LHS.getDecl() && !RHS.getDecl(); 1798 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1799 return false; 1800 return LHS.Path == RHS.Path; 1801 } 1802 } 1803 1804 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1805 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1806 const LValue &This, const Expr *E, 1807 bool AllowNonLiteralTypes = false); 1808 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1809 bool InvalidBaseOK = false); 1810 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1811 bool InvalidBaseOK = false); 1812 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1813 EvalInfo &Info); 1814 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1815 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1816 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1817 EvalInfo &Info); 1818 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1819 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1820 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1821 EvalInfo &Info); 1822 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result, 1823 bool &Dependent); 1824 1825 /// Evaluate an integer or fixed point expression into an APResult. 1826 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1827 EvalInfo &Info); 1828 1829 /// Evaluate only a fixed point expression into an APResult. 1830 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1831 EvalInfo &Info); 1832 1833 //===----------------------------------------------------------------------===// 1834 // Misc utilities 1835 //===----------------------------------------------------------------------===// 1836 1837 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1838 /// preserving its value (by extending by up to one bit as needed). 1839 static void negateAsSigned(APSInt &Int) { 1840 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1841 Int = Int.extend(Int.getBitWidth() + 1); 1842 Int.setIsSigned(true); 1843 } 1844 Int = -Int; 1845 } 1846 1847 template<typename KeyT> 1848 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1849 ScopeKind Scope, LValue &LV) { 1850 unsigned Version = getTempVersion(); 1851 APValue::LValueBase Base(Key, Index, Version); 1852 LV.set(Base); 1853 return createLocal(Base, Key, T, Scope); 1854 } 1855 1856 /// Allocate storage for a parameter of a function call made in this frame. 1857 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1858 LValue &LV) { 1859 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1860 APValue::LValueBase Base(PVD, Index, Args.Version); 1861 LV.set(Base); 1862 // We always destroy parameters at the end of the call, even if we'd allow 1863 // them to live to the end of the full-expression at runtime, in order to 1864 // give portable results and match other compilers. 1865 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1866 } 1867 1868 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1869 QualType T, ScopeKind Scope) { 1870 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1871 unsigned Version = Base.getVersion(); 1872 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1873 assert(Result.isAbsent() && "local created multiple times"); 1874 1875 // If we're creating a local immediately in the operand of a speculative 1876 // evaluation, don't register a cleanup to be run outside the speculative 1877 // evaluation context, since we won't actually be able to initialize this 1878 // object. 1879 if (Index <= Info.SpeculativeEvaluationDepth) { 1880 if (T.isDestructedType()) 1881 Info.noteSideEffect(); 1882 } else { 1883 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1884 } 1885 return Result; 1886 } 1887 1888 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1889 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1890 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1891 return nullptr; 1892 } 1893 1894 DynamicAllocLValue DA(NumHeapAllocs++); 1895 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1896 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1897 std::forward_as_tuple(DA), std::tuple<>()); 1898 assert(Result.second && "reused a heap alloc index?"); 1899 Result.first->second.AllocExpr = E; 1900 return &Result.first->second.Value; 1901 } 1902 1903 /// Produce a string describing the given constexpr call. 1904 void CallStackFrame::describe(raw_ostream &Out) { 1905 unsigned ArgIndex = 0; 1906 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1907 !isa<CXXConstructorDecl>(Callee) && 1908 cast<CXXMethodDecl>(Callee)->isInstance(); 1909 1910 if (!IsMemberCall) 1911 Out << *Callee << '('; 1912 1913 if (This && IsMemberCall) { 1914 APValue Val; 1915 This->moveInto(Val); 1916 Val.printPretty(Out, Info.Ctx, 1917 This->Designator.MostDerivedType); 1918 // FIXME: Add parens around Val if needed. 1919 Out << "->" << *Callee << '('; 1920 IsMemberCall = false; 1921 } 1922 1923 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1924 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1925 if (ArgIndex > (unsigned)IsMemberCall) 1926 Out << ", "; 1927 1928 const ParmVarDecl *Param = *I; 1929 APValue *V = Info.getParamSlot(Arguments, Param); 1930 if (V) 1931 V->printPretty(Out, Info.Ctx, Param->getType()); 1932 else 1933 Out << "<...>"; 1934 1935 if (ArgIndex == 0 && IsMemberCall) 1936 Out << "->" << *Callee << '('; 1937 } 1938 1939 Out << ')'; 1940 } 1941 1942 /// Evaluate an expression to see if it had side-effects, and discard its 1943 /// result. 1944 /// \return \c true if the caller should keep evaluating. 1945 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1946 assert(!E->isValueDependent()); 1947 APValue Scratch; 1948 if (!Evaluate(Scratch, Info, E)) 1949 // We don't need the value, but we might have skipped a side effect here. 1950 return Info.noteSideEffect(); 1951 return true; 1952 } 1953 1954 /// Should this call expression be treated as a string literal? 1955 static bool IsStringLiteralCall(const CallExpr *E) { 1956 unsigned Builtin = E->getBuiltinCallee(); 1957 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1958 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1959 } 1960 1961 static bool IsGlobalLValue(APValue::LValueBase B) { 1962 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1963 // constant expression of pointer type that evaluates to... 1964 1965 // ... a null pointer value, or a prvalue core constant expression of type 1966 // std::nullptr_t. 1967 if (!B) return true; 1968 1969 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1970 // ... the address of an object with static storage duration, 1971 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1972 return VD->hasGlobalStorage(); 1973 if (isa<TemplateParamObjectDecl>(D)) 1974 return true; 1975 // ... the address of a function, 1976 // ... the address of a GUID [MS extension], 1977 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1978 } 1979 1980 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1981 return true; 1982 1983 const Expr *E = B.get<const Expr*>(); 1984 switch (E->getStmtClass()) { 1985 default: 1986 return false; 1987 case Expr::CompoundLiteralExprClass: { 1988 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1989 return CLE->isFileScope() && CLE->isLValue(); 1990 } 1991 case Expr::MaterializeTemporaryExprClass: 1992 // A materialized temporary might have been lifetime-extended to static 1993 // storage duration. 1994 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1995 // A string literal has static storage duration. 1996 case Expr::StringLiteralClass: 1997 case Expr::PredefinedExprClass: 1998 case Expr::ObjCStringLiteralClass: 1999 case Expr::ObjCEncodeExprClass: 2000 return true; 2001 case Expr::ObjCBoxedExprClass: 2002 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2003 case Expr::CallExprClass: 2004 return IsStringLiteralCall(cast<CallExpr>(E)); 2005 // For GCC compatibility, &&label has static storage duration. 2006 case Expr::AddrLabelExprClass: 2007 return true; 2008 // A Block literal expression may be used as the initialization value for 2009 // Block variables at global or local static scope. 2010 case Expr::BlockExprClass: 2011 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2012 case Expr::ImplicitValueInitExprClass: 2013 // FIXME: 2014 // We can never form an lvalue with an implicit value initialization as its 2015 // base through expression evaluation, so these only appear in one case: the 2016 // implicit variable declaration we invent when checking whether a constexpr 2017 // constructor can produce a constant expression. We must assume that such 2018 // an expression might be a global lvalue. 2019 return true; 2020 } 2021 } 2022 2023 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2024 return LVal.Base.dyn_cast<const ValueDecl*>(); 2025 } 2026 2027 static bool IsLiteralLValue(const LValue &Value) { 2028 if (Value.getLValueCallIndex()) 2029 return false; 2030 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2031 return E && !isa<MaterializeTemporaryExpr>(E); 2032 } 2033 2034 static bool IsWeakLValue(const LValue &Value) { 2035 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2036 return Decl && Decl->isWeak(); 2037 } 2038 2039 static bool isZeroSized(const LValue &Value) { 2040 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2041 if (Decl && isa<VarDecl>(Decl)) { 2042 QualType Ty = Decl->getType(); 2043 if (Ty->isArrayType()) 2044 return Ty->isIncompleteType() || 2045 Decl->getASTContext().getTypeSize(Ty) == 0; 2046 } 2047 return false; 2048 } 2049 2050 static bool HasSameBase(const LValue &A, const LValue &B) { 2051 if (!A.getLValueBase()) 2052 return !B.getLValueBase(); 2053 if (!B.getLValueBase()) 2054 return false; 2055 2056 if (A.getLValueBase().getOpaqueValue() != 2057 B.getLValueBase().getOpaqueValue()) 2058 return false; 2059 2060 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2061 A.getLValueVersion() == B.getLValueVersion(); 2062 } 2063 2064 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2065 assert(Base && "no location for a null lvalue"); 2066 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2067 2068 // For a parameter, find the corresponding call stack frame (if it still 2069 // exists), and point at the parameter of the function definition we actually 2070 // invoked. 2071 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2072 unsigned Idx = PVD->getFunctionScopeIndex(); 2073 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2074 if (F->Arguments.CallIndex == Base.getCallIndex() && 2075 F->Arguments.Version == Base.getVersion() && F->Callee && 2076 Idx < F->Callee->getNumParams()) { 2077 VD = F->Callee->getParamDecl(Idx); 2078 break; 2079 } 2080 } 2081 } 2082 2083 if (VD) 2084 Info.Note(VD->getLocation(), diag::note_declared_at); 2085 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2086 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2087 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2088 // FIXME: Produce a note for dangling pointers too. 2089 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2090 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2091 diag::note_constexpr_dynamic_alloc_here); 2092 } 2093 // We have no information to show for a typeid(T) object. 2094 } 2095 2096 enum class CheckEvaluationResultKind { 2097 ConstantExpression, 2098 FullyInitialized, 2099 }; 2100 2101 /// Materialized temporaries that we've already checked to determine if they're 2102 /// initializsed by a constant expression. 2103 using CheckedTemporaries = 2104 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2105 2106 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2107 EvalInfo &Info, SourceLocation DiagLoc, 2108 QualType Type, const APValue &Value, 2109 ConstantExprKind Kind, 2110 SourceLocation SubobjectLoc, 2111 CheckedTemporaries &CheckedTemps, 2112 bool &Dependent); 2113 2114 /// Check that this reference or pointer core constant expression is a valid 2115 /// value for an address or reference constant expression. Return true if we 2116 /// can fold this expression, whether or not it's a constant expression. 2117 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2118 QualType Type, const LValue &LVal, 2119 ConstantExprKind Kind, 2120 CheckedTemporaries &CheckedTemps, 2121 bool &Dependent) { 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 Dependent |= BaseVD->isTemplated(); 2207 2208 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2209 // Check if this is a thread-local variable. 2210 if (Var->getTLSKind()) 2211 // FIXME: Diagnostic! 2212 return false; 2213 2214 // A dllimport variable never acts like a constant, unless we're 2215 // evaluating a value for use only in name mangling. 2216 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2217 // FIXME: Diagnostic! 2218 return false; 2219 } 2220 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2221 // __declspec(dllimport) must be handled very carefully: 2222 // We must never initialize an expression with the thunk in C++. 2223 // Doing otherwise would allow the same id-expression to yield 2224 // different addresses for the same function in different translation 2225 // units. However, this means that we must dynamically initialize the 2226 // expression with the contents of the import address table at runtime. 2227 // 2228 // The C language has no notion of ODR; furthermore, it has no notion of 2229 // dynamic initialization. This means that we are permitted to 2230 // perform initialization with the address of the thunk. 2231 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2232 FD->hasAttr<DLLImportAttr>()) 2233 // FIXME: Diagnostic! 2234 return false; 2235 } 2236 } else if (const auto *MTE = 2237 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2238 if (auto *Extending = MTE->getExtendingDecl()) 2239 Dependent |= Extending->isTemplated(); 2240 2241 if (CheckedTemps.insert(MTE).second) { 2242 QualType TempType = getType(Base); 2243 if (TempType.isDestructedType()) { 2244 Info.FFDiag(MTE->getExprLoc(), 2245 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2246 << TempType; 2247 return false; 2248 } 2249 2250 APValue *V = MTE->getOrCreateValue(false); 2251 assert(V && "evasluation result refers to uninitialised temporary"); 2252 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2253 Info, MTE->getExprLoc(), TempType, *V, Kind, 2254 SourceLocation(), CheckedTemps, Dependent)) 2255 return false; 2256 } 2257 } 2258 2259 // Allow address constant expressions to be past-the-end pointers. This is 2260 // an extension: the standard requires them to point to an object. 2261 if (!IsReferenceType) 2262 return true; 2263 2264 // A reference constant expression must refer to an object. 2265 if (!Base) { 2266 // FIXME: diagnostic 2267 Info.CCEDiag(Loc); 2268 return true; 2269 } 2270 2271 // Does this refer one past the end of some object? 2272 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2273 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2274 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2275 NoteLValueLocation(Info, Base); 2276 } 2277 2278 return true; 2279 } 2280 2281 /// Member pointers are constant expressions unless they point to a 2282 /// non-virtual dllimport member function. 2283 static bool 2284 CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, 2285 QualType Type, const APValue &Value, 2286 ConstantExprKind Kind, bool &Dependent) { 2287 const ValueDecl *Member = Value.getMemberPointerDecl(); 2288 if (!Member) 2289 return true; 2290 Dependent |= Member->isTemplated(); 2291 const auto *FD = dyn_cast<CXXMethodDecl>(Member); 2292 if (!FD) 2293 return true; 2294 if (FD->isConsteval()) { 2295 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2296 Info.Note(FD->getLocation(), diag::note_declared_at); 2297 return false; 2298 } 2299 return isForManglingOnly(Kind) || FD->isVirtual() || 2300 !FD->hasAttr<DLLImportAttr>(); 2301 } 2302 2303 /// Check that this core constant expression is of literal type, and if not, 2304 /// produce an appropriate diagnostic. 2305 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2306 const LValue *This = nullptr) { 2307 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2308 return true; 2309 2310 // C++1y: A constant initializer for an object o [...] may also invoke 2311 // constexpr constructors for o and its subobjects even if those objects 2312 // are of non-literal class types. 2313 // 2314 // C++11 missed this detail for aggregates, so classes like this: 2315 // struct foo_t { union { int i; volatile int j; } u; }; 2316 // are not (obviously) initializable like so: 2317 // __attribute__((__require_constant_initialization__)) 2318 // static const foo_t x = {{0}}; 2319 // because "i" is a subobject with non-literal initialization (due to the 2320 // volatile member of the union). See: 2321 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2322 // Therefore, we use the C++1y behavior. 2323 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2324 return true; 2325 2326 // Prvalue constant expressions must be of literal types. 2327 if (Info.getLangOpts().CPlusPlus11) 2328 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2329 << E->getType(); 2330 else 2331 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2332 return false; 2333 } 2334 2335 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2336 EvalInfo &Info, SourceLocation DiagLoc, 2337 QualType Type, const APValue &Value, 2338 ConstantExprKind Kind, 2339 SourceLocation SubobjectLoc, 2340 CheckedTemporaries &CheckedTemps, 2341 bool &Dependent) { 2342 if (!Value.hasValue()) { 2343 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2344 << true << Type; 2345 if (SubobjectLoc.isValid()) 2346 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2347 return false; 2348 } 2349 2350 // We allow _Atomic(T) to be initialized from anything that T can be 2351 // initialized from. 2352 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2353 Type = AT->getValueType(); 2354 2355 // Core issue 1454: For a literal constant expression of array or class type, 2356 // each subobject of its value shall have been initialized by a constant 2357 // expression. 2358 if (Value.isArray()) { 2359 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2360 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2361 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2362 Value.getArrayInitializedElt(I), Kind, 2363 SubobjectLoc, CheckedTemps, Dependent)) 2364 return false; 2365 } 2366 if (!Value.hasArrayFiller()) 2367 return true; 2368 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2369 Value.getArrayFiller(), Kind, SubobjectLoc, 2370 CheckedTemps, Dependent); 2371 } 2372 if (Value.isUnion() && Value.getUnionField()) { 2373 return CheckEvaluationResult( 2374 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2375 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2376 CheckedTemps, Dependent); 2377 } 2378 if (Value.isStruct()) { 2379 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2380 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2381 unsigned BaseIndex = 0; 2382 for (const CXXBaseSpecifier &BS : CD->bases()) { 2383 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2384 Value.getStructBase(BaseIndex), Kind, 2385 BS.getBeginLoc(), CheckedTemps, Dependent)) 2386 return false; 2387 ++BaseIndex; 2388 } 2389 } 2390 for (const auto *I : RD->fields()) { 2391 if (I->isUnnamedBitfield()) 2392 continue; 2393 2394 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2395 Value.getStructField(I->getFieldIndex()), Kind, 2396 I->getLocation(), CheckedTemps, Dependent)) 2397 return false; 2398 } 2399 } 2400 2401 if (Value.isLValue() && 2402 CERK == CheckEvaluationResultKind::ConstantExpression) { 2403 LValue LVal; 2404 LVal.setFrom(Info.Ctx, Value); 2405 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2406 CheckedTemps, Dependent); 2407 } 2408 2409 if (Value.isMemberPointer() && 2410 CERK == CheckEvaluationResultKind::ConstantExpression) 2411 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, 2412 Kind, Dependent); 2413 2414 // Everything else is fine. 2415 return true; 2416 } 2417 2418 /// Check that this core constant expression value is a valid value for a 2419 /// constant expression. If not, report an appropriate diagnostic. Does not 2420 /// check that the expression is of literal type. 2421 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2422 QualType Type, const APValue &Value, 2423 ConstantExprKind Kind, bool &Dependent) { 2424 // Nothing to check for a constant expression of type 'cv void'. 2425 if (Type->isVoidType()) 2426 return true; 2427 2428 CheckedTemporaries CheckedTemps; 2429 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2430 Info, DiagLoc, Type, Value, Kind, 2431 SourceLocation(), CheckedTemps, Dependent); 2432 } 2433 2434 /// Check that this evaluated value is fully-initialized and can be loaded by 2435 /// an lvalue-to-rvalue conversion. 2436 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2437 QualType Type, const APValue &Value) { 2438 bool Dependent = false; 2439 CheckedTemporaries CheckedTemps; 2440 return CheckEvaluationResult( 2441 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2442 ConstantExprKind::Normal, SourceLocation(), CheckedTemps, Dependent); 2443 } 2444 2445 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2446 /// "the allocated storage is deallocated within the evaluation". 2447 static bool CheckMemoryLeaks(EvalInfo &Info) { 2448 if (!Info.HeapAllocs.empty()) { 2449 // We can still fold to a constant despite a compile-time memory leak, 2450 // so long as the heap allocation isn't referenced in the result (we check 2451 // that in CheckConstantExpression). 2452 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2453 diag::note_constexpr_memory_leak) 2454 << unsigned(Info.HeapAllocs.size() - 1); 2455 } 2456 return true; 2457 } 2458 2459 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2460 // A null base expression indicates a null pointer. These are always 2461 // evaluatable, and they are false unless the offset is zero. 2462 if (!Value.getLValueBase()) { 2463 Result = !Value.getLValueOffset().isZero(); 2464 return true; 2465 } 2466 2467 // We have a non-null base. These are generally known to be true, but if it's 2468 // a weak declaration it can be null at runtime. 2469 Result = true; 2470 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2471 return !Decl || !Decl->isWeak(); 2472 } 2473 2474 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2475 switch (Val.getKind()) { 2476 case APValue::None: 2477 case APValue::Indeterminate: 2478 return false; 2479 case APValue::Int: 2480 Result = Val.getInt().getBoolValue(); 2481 return true; 2482 case APValue::FixedPoint: 2483 Result = Val.getFixedPoint().getBoolValue(); 2484 return true; 2485 case APValue::Float: 2486 Result = !Val.getFloat().isZero(); 2487 return true; 2488 case APValue::ComplexInt: 2489 Result = Val.getComplexIntReal().getBoolValue() || 2490 Val.getComplexIntImag().getBoolValue(); 2491 return true; 2492 case APValue::ComplexFloat: 2493 Result = !Val.getComplexFloatReal().isZero() || 2494 !Val.getComplexFloatImag().isZero(); 2495 return true; 2496 case APValue::LValue: 2497 return EvalPointerValueAsBool(Val, Result); 2498 case APValue::MemberPointer: 2499 Result = Val.getMemberPointerDecl(); 2500 return true; 2501 case APValue::Vector: 2502 case APValue::Array: 2503 case APValue::Struct: 2504 case APValue::Union: 2505 case APValue::AddrLabelDiff: 2506 return false; 2507 } 2508 2509 llvm_unreachable("unknown APValue kind"); 2510 } 2511 2512 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2513 EvalInfo &Info) { 2514 assert(!E->isValueDependent()); 2515 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2516 APValue Val; 2517 if (!Evaluate(Val, Info, E)) 2518 return false; 2519 return HandleConversionToBool(Val, Result); 2520 } 2521 2522 template<typename T> 2523 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2524 const T &SrcValue, QualType DestType) { 2525 Info.CCEDiag(E, diag::note_constexpr_overflow) 2526 << SrcValue << DestType; 2527 return Info.noteUndefinedBehavior(); 2528 } 2529 2530 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2531 QualType SrcType, const APFloat &Value, 2532 QualType DestType, APSInt &Result) { 2533 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2534 // Determine whether we are converting to unsigned or signed. 2535 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2536 2537 Result = APSInt(DestWidth, !DestSigned); 2538 bool ignored; 2539 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2540 & APFloat::opInvalidOp) 2541 return HandleOverflow(Info, E, Value, DestType); 2542 return true; 2543 } 2544 2545 /// Get rounding mode used for evaluation of the specified expression. 2546 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2547 /// dynamic. 2548 /// If rounding mode is unknown at compile time, still try to evaluate the 2549 /// expression. If the result is exact, it does not depend on rounding mode. 2550 /// So return "tonearest" mode instead of "dynamic". 2551 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2552 bool &DynamicRM) { 2553 llvm::RoundingMode RM = 2554 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2555 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2556 if (DynamicRM) 2557 RM = llvm::RoundingMode::NearestTiesToEven; 2558 return RM; 2559 } 2560 2561 /// Check if the given evaluation result is allowed for constant evaluation. 2562 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2563 APFloat::opStatus St) { 2564 // In a constant context, assume that any dynamic rounding mode or FP 2565 // exception state matches the default floating-point environment. 2566 if (Info.InConstantContext) 2567 return true; 2568 2569 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2570 if ((St & APFloat::opInexact) && 2571 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2572 // Inexact result means that it depends on rounding mode. If the requested 2573 // mode is dynamic, the evaluation cannot be made in compile time. 2574 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2575 return false; 2576 } 2577 2578 if ((St != APFloat::opOK) && 2579 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2580 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2581 FPO.getAllowFEnvAccess())) { 2582 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2583 return false; 2584 } 2585 2586 if ((St & APFloat::opStatus::opInvalidOp) && 2587 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2588 // There is no usefully definable result. 2589 Info.FFDiag(E); 2590 return false; 2591 } 2592 2593 // FIXME: if: 2594 // - evaluation triggered other FP exception, and 2595 // - exception mode is not "ignore", and 2596 // - the expression being evaluated is not a part of global variable 2597 // initializer, 2598 // the evaluation probably need to be rejected. 2599 return true; 2600 } 2601 2602 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2603 QualType SrcType, QualType DestType, 2604 APFloat &Result) { 2605 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2606 bool DynamicRM; 2607 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2608 APFloat::opStatus St; 2609 APFloat Value = Result; 2610 bool ignored; 2611 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2612 return checkFloatingPointResult(Info, E, St); 2613 } 2614 2615 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2616 QualType DestType, QualType SrcType, 2617 const APSInt &Value) { 2618 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2619 // Figure out if this is a truncate, extend or noop cast. 2620 // If the input is signed, do a sign extend, noop, or truncate. 2621 APSInt Result = Value.extOrTrunc(DestWidth); 2622 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2623 if (DestType->isBooleanType()) 2624 Result = Value.getBoolValue(); 2625 return Result; 2626 } 2627 2628 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2629 const FPOptions FPO, 2630 QualType SrcType, const APSInt &Value, 2631 QualType DestType, APFloat &Result) { 2632 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2633 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2634 APFloat::rmNearestTiesToEven); 2635 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2636 FPO.isFPConstrained()) { 2637 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2638 return false; 2639 } 2640 return true; 2641 } 2642 2643 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2644 APValue &Value, const FieldDecl *FD) { 2645 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2646 2647 if (!Value.isInt()) { 2648 // Trying to store a pointer-cast-to-integer into a bitfield. 2649 // FIXME: In this case, we should provide the diagnostic for casting 2650 // a pointer to an integer. 2651 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2652 Info.FFDiag(E); 2653 return false; 2654 } 2655 2656 APSInt &Int = Value.getInt(); 2657 unsigned OldBitWidth = Int.getBitWidth(); 2658 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2659 if (NewBitWidth < OldBitWidth) 2660 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2661 return true; 2662 } 2663 2664 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2665 llvm::APInt &Res) { 2666 APValue SVal; 2667 if (!Evaluate(SVal, Info, E)) 2668 return false; 2669 if (SVal.isInt()) { 2670 Res = SVal.getInt(); 2671 return true; 2672 } 2673 if (SVal.isFloat()) { 2674 Res = SVal.getFloat().bitcastToAPInt(); 2675 return true; 2676 } 2677 if (SVal.isVector()) { 2678 QualType VecTy = E->getType(); 2679 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2680 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2681 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2682 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2683 Res = llvm::APInt::getNullValue(VecSize); 2684 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2685 APValue &Elt = SVal.getVectorElt(i); 2686 llvm::APInt EltAsInt; 2687 if (Elt.isInt()) { 2688 EltAsInt = Elt.getInt(); 2689 } else if (Elt.isFloat()) { 2690 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2691 } else { 2692 // Don't try to handle vectors of anything other than int or float 2693 // (not sure if it's possible to hit this case). 2694 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2695 return false; 2696 } 2697 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2698 if (BigEndian) 2699 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2700 else 2701 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2702 } 2703 return true; 2704 } 2705 // Give up if the input isn't an int, float, or vector. For example, we 2706 // reject "(v4i16)(intptr_t)&a". 2707 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2708 return false; 2709 } 2710 2711 /// Perform the given integer operation, which is known to need at most BitWidth 2712 /// bits, and check for overflow in the original type (if that type was not an 2713 /// unsigned type). 2714 template<typename Operation> 2715 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2716 const APSInt &LHS, const APSInt &RHS, 2717 unsigned BitWidth, Operation Op, 2718 APSInt &Result) { 2719 if (LHS.isUnsigned()) { 2720 Result = Op(LHS, RHS); 2721 return true; 2722 } 2723 2724 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2725 Result = Value.trunc(LHS.getBitWidth()); 2726 if (Result.extend(BitWidth) != Value) { 2727 if (Info.checkingForUndefinedBehavior()) 2728 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2729 diag::warn_integer_constant_overflow) 2730 << Result.toString(10) << E->getType(); 2731 else 2732 return HandleOverflow(Info, E, Value, E->getType()); 2733 } 2734 return true; 2735 } 2736 2737 /// Perform the given binary integer operation. 2738 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2739 BinaryOperatorKind Opcode, APSInt RHS, 2740 APSInt &Result) { 2741 switch (Opcode) { 2742 default: 2743 Info.FFDiag(E); 2744 return false; 2745 case BO_Mul: 2746 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2747 std::multiplies<APSInt>(), Result); 2748 case BO_Add: 2749 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2750 std::plus<APSInt>(), Result); 2751 case BO_Sub: 2752 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2753 std::minus<APSInt>(), Result); 2754 case BO_And: Result = LHS & RHS; return true; 2755 case BO_Xor: Result = LHS ^ RHS; return true; 2756 case BO_Or: Result = LHS | RHS; return true; 2757 case BO_Div: 2758 case BO_Rem: 2759 if (RHS == 0) { 2760 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2761 return false; 2762 } 2763 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2764 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2765 // this operation and gives the two's complement result. 2766 if (RHS.isNegative() && RHS.isAllOnesValue() && 2767 LHS.isSigned() && LHS.isMinSignedValue()) 2768 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2769 E->getType()); 2770 return true; 2771 case BO_Shl: { 2772 if (Info.getLangOpts().OpenCL) 2773 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2774 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2775 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2776 RHS.isUnsigned()); 2777 else if (RHS.isSigned() && RHS.isNegative()) { 2778 // During constant-folding, a negative shift is an opposite shift. Such 2779 // a shift is not a constant expression. 2780 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2781 RHS = -RHS; 2782 goto shift_right; 2783 } 2784 shift_left: 2785 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2786 // the shifted type. 2787 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2788 if (SA != RHS) { 2789 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2790 << RHS << E->getType() << LHS.getBitWidth(); 2791 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2792 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2793 // operand, and must not overflow the corresponding unsigned type. 2794 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2795 // E1 x 2^E2 module 2^N. 2796 if (LHS.isNegative()) 2797 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2798 else if (LHS.countLeadingZeros() < SA) 2799 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2800 } 2801 Result = LHS << SA; 2802 return true; 2803 } 2804 case BO_Shr: { 2805 if (Info.getLangOpts().OpenCL) 2806 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2807 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2808 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2809 RHS.isUnsigned()); 2810 else if (RHS.isSigned() && RHS.isNegative()) { 2811 // During constant-folding, a negative shift is an opposite shift. Such a 2812 // shift is not a constant expression. 2813 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2814 RHS = -RHS; 2815 goto shift_left; 2816 } 2817 shift_right: 2818 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2819 // shifted type. 2820 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2821 if (SA != RHS) 2822 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2823 << RHS << E->getType() << LHS.getBitWidth(); 2824 Result = LHS >> SA; 2825 return true; 2826 } 2827 2828 case BO_LT: Result = LHS < RHS; return true; 2829 case BO_GT: Result = LHS > RHS; return true; 2830 case BO_LE: Result = LHS <= RHS; return true; 2831 case BO_GE: Result = LHS >= RHS; return true; 2832 case BO_EQ: Result = LHS == RHS; return true; 2833 case BO_NE: Result = LHS != RHS; return true; 2834 case BO_Cmp: 2835 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2836 } 2837 } 2838 2839 /// Perform the given binary floating-point operation, in-place, on LHS. 2840 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2841 APFloat &LHS, BinaryOperatorKind Opcode, 2842 const APFloat &RHS) { 2843 bool DynamicRM; 2844 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2845 APFloat::opStatus St; 2846 switch (Opcode) { 2847 default: 2848 Info.FFDiag(E); 2849 return false; 2850 case BO_Mul: 2851 St = LHS.multiply(RHS, RM); 2852 break; 2853 case BO_Add: 2854 St = LHS.add(RHS, RM); 2855 break; 2856 case BO_Sub: 2857 St = LHS.subtract(RHS, RM); 2858 break; 2859 case BO_Div: 2860 // [expr.mul]p4: 2861 // If the second operand of / or % is zero the behavior is undefined. 2862 if (RHS.isZero()) 2863 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2864 St = LHS.divide(RHS, RM); 2865 break; 2866 } 2867 2868 // [expr.pre]p4: 2869 // If during the evaluation of an expression, the result is not 2870 // mathematically defined [...], the behavior is undefined. 2871 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2872 if (LHS.isNaN()) { 2873 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2874 return Info.noteUndefinedBehavior(); 2875 } 2876 2877 return checkFloatingPointResult(Info, E, St); 2878 } 2879 2880 static bool handleLogicalOpForVector(const APInt &LHSValue, 2881 BinaryOperatorKind Opcode, 2882 const APInt &RHSValue, APInt &Result) { 2883 bool LHS = (LHSValue != 0); 2884 bool RHS = (RHSValue != 0); 2885 2886 if (Opcode == BO_LAnd) 2887 Result = LHS && RHS; 2888 else 2889 Result = LHS || RHS; 2890 return true; 2891 } 2892 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2893 BinaryOperatorKind Opcode, 2894 const APFloat &RHSValue, APInt &Result) { 2895 bool LHS = !LHSValue.isZero(); 2896 bool RHS = !RHSValue.isZero(); 2897 2898 if (Opcode == BO_LAnd) 2899 Result = LHS && RHS; 2900 else 2901 Result = LHS || RHS; 2902 return true; 2903 } 2904 2905 static bool handleLogicalOpForVector(const APValue &LHSValue, 2906 BinaryOperatorKind Opcode, 2907 const APValue &RHSValue, APInt &Result) { 2908 // The result is always an int type, however operands match the first. 2909 if (LHSValue.getKind() == APValue::Int) 2910 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2911 RHSValue.getInt(), Result); 2912 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2913 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2914 RHSValue.getFloat(), Result); 2915 } 2916 2917 template <typename APTy> 2918 static bool 2919 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2920 const APTy &RHSValue, APInt &Result) { 2921 switch (Opcode) { 2922 default: 2923 llvm_unreachable("unsupported binary operator"); 2924 case BO_EQ: 2925 Result = (LHSValue == RHSValue); 2926 break; 2927 case BO_NE: 2928 Result = (LHSValue != RHSValue); 2929 break; 2930 case BO_LT: 2931 Result = (LHSValue < RHSValue); 2932 break; 2933 case BO_GT: 2934 Result = (LHSValue > RHSValue); 2935 break; 2936 case BO_LE: 2937 Result = (LHSValue <= RHSValue); 2938 break; 2939 case BO_GE: 2940 Result = (LHSValue >= RHSValue); 2941 break; 2942 } 2943 2944 return true; 2945 } 2946 2947 static bool handleCompareOpForVector(const APValue &LHSValue, 2948 BinaryOperatorKind Opcode, 2949 const APValue &RHSValue, APInt &Result) { 2950 // The result is always an int type, however operands match the first. 2951 if (LHSValue.getKind() == APValue::Int) 2952 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2953 RHSValue.getInt(), Result); 2954 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2955 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2956 RHSValue.getFloat(), Result); 2957 } 2958 2959 // Perform binary operations for vector types, in place on the LHS. 2960 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2961 BinaryOperatorKind Opcode, 2962 APValue &LHSValue, 2963 const APValue &RHSValue) { 2964 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2965 "Operation not supported on vector types"); 2966 2967 const auto *VT = E->getType()->castAs<VectorType>(); 2968 unsigned NumElements = VT->getNumElements(); 2969 QualType EltTy = VT->getElementType(); 2970 2971 // In the cases (typically C as I've observed) where we aren't evaluating 2972 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2973 // just give up. 2974 if (!LHSValue.isVector()) { 2975 assert(LHSValue.isLValue() && 2976 "A vector result that isn't a vector OR uncalculated LValue"); 2977 Info.FFDiag(E); 2978 return false; 2979 } 2980 2981 assert(LHSValue.getVectorLength() == NumElements && 2982 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2983 2984 SmallVector<APValue, 4> ResultElements; 2985 2986 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2987 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2988 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2989 2990 if (EltTy->isIntegerType()) { 2991 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2992 EltTy->isUnsignedIntegerType()}; 2993 bool Success = true; 2994 2995 if (BinaryOperator::isLogicalOp(Opcode)) 2996 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2997 else if (BinaryOperator::isComparisonOp(Opcode)) 2998 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2999 else 3000 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 3001 RHSElt.getInt(), EltResult); 3002 3003 if (!Success) { 3004 Info.FFDiag(E); 3005 return false; 3006 } 3007 ResultElements.emplace_back(EltResult); 3008 3009 } else if (EltTy->isFloatingType()) { 3010 assert(LHSElt.getKind() == APValue::Float && 3011 RHSElt.getKind() == APValue::Float && 3012 "Mismatched LHS/RHS/Result Type"); 3013 APFloat LHSFloat = LHSElt.getFloat(); 3014 3015 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3016 RHSElt.getFloat())) { 3017 Info.FFDiag(E); 3018 return false; 3019 } 3020 3021 ResultElements.emplace_back(LHSFloat); 3022 } 3023 } 3024 3025 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3026 return true; 3027 } 3028 3029 /// Cast an lvalue referring to a base subobject to a derived class, by 3030 /// truncating the lvalue's path to the given length. 3031 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3032 const RecordDecl *TruncatedType, 3033 unsigned TruncatedElements) { 3034 SubobjectDesignator &D = Result.Designator; 3035 3036 // Check we actually point to a derived class object. 3037 if (TruncatedElements == D.Entries.size()) 3038 return true; 3039 assert(TruncatedElements >= D.MostDerivedPathLength && 3040 "not casting to a derived class"); 3041 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3042 return false; 3043 3044 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3045 const RecordDecl *RD = TruncatedType; 3046 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3047 if (RD->isInvalidDecl()) return false; 3048 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3049 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3050 if (isVirtualBaseClass(D.Entries[I])) 3051 Result.Offset -= Layout.getVBaseClassOffset(Base); 3052 else 3053 Result.Offset -= Layout.getBaseClassOffset(Base); 3054 RD = Base; 3055 } 3056 D.Entries.resize(TruncatedElements); 3057 return true; 3058 } 3059 3060 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3061 const CXXRecordDecl *Derived, 3062 const CXXRecordDecl *Base, 3063 const ASTRecordLayout *RL = nullptr) { 3064 if (!RL) { 3065 if (Derived->isInvalidDecl()) return false; 3066 RL = &Info.Ctx.getASTRecordLayout(Derived); 3067 } 3068 3069 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3070 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3071 return true; 3072 } 3073 3074 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3075 const CXXRecordDecl *DerivedDecl, 3076 const CXXBaseSpecifier *Base) { 3077 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3078 3079 if (!Base->isVirtual()) 3080 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3081 3082 SubobjectDesignator &D = Obj.Designator; 3083 if (D.Invalid) 3084 return false; 3085 3086 // Extract most-derived object and corresponding type. 3087 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3088 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3089 return false; 3090 3091 // Find the virtual base class. 3092 if (DerivedDecl->isInvalidDecl()) return false; 3093 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3094 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3095 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3096 return true; 3097 } 3098 3099 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3100 QualType Type, LValue &Result) { 3101 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3102 PathE = E->path_end(); 3103 PathI != PathE; ++PathI) { 3104 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3105 *PathI)) 3106 return false; 3107 Type = (*PathI)->getType(); 3108 } 3109 return true; 3110 } 3111 3112 /// Cast an lvalue referring to a derived class to a known base subobject. 3113 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3114 const CXXRecordDecl *DerivedRD, 3115 const CXXRecordDecl *BaseRD) { 3116 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3117 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3118 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3119 llvm_unreachable("Class must be derived from the passed in base class!"); 3120 3121 for (CXXBasePathElement &Elem : Paths.front()) 3122 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3123 return false; 3124 return true; 3125 } 3126 3127 /// Update LVal to refer to the given field, which must be a member of the type 3128 /// currently described by LVal. 3129 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3130 const FieldDecl *FD, 3131 const ASTRecordLayout *RL = nullptr) { 3132 if (!RL) { 3133 if (FD->getParent()->isInvalidDecl()) return false; 3134 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3135 } 3136 3137 unsigned I = FD->getFieldIndex(); 3138 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3139 LVal.addDecl(Info, E, FD); 3140 return true; 3141 } 3142 3143 /// Update LVal to refer to the given indirect field. 3144 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3145 LValue &LVal, 3146 const IndirectFieldDecl *IFD) { 3147 for (const auto *C : IFD->chain()) 3148 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3149 return false; 3150 return true; 3151 } 3152 3153 /// Get the size of the given type in char units. 3154 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3155 QualType Type, CharUnits &Size) { 3156 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3157 // extension. 3158 if (Type->isVoidType() || Type->isFunctionType()) { 3159 Size = CharUnits::One(); 3160 return true; 3161 } 3162 3163 if (Type->isDependentType()) { 3164 Info.FFDiag(Loc); 3165 return false; 3166 } 3167 3168 if (!Type->isConstantSizeType()) { 3169 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3170 // FIXME: Better diagnostic. 3171 Info.FFDiag(Loc); 3172 return false; 3173 } 3174 3175 Size = Info.Ctx.getTypeSizeInChars(Type); 3176 return true; 3177 } 3178 3179 /// Update a pointer value to model pointer arithmetic. 3180 /// \param Info - Information about the ongoing evaluation. 3181 /// \param E - The expression being evaluated, for diagnostic purposes. 3182 /// \param LVal - The pointer value to be updated. 3183 /// \param EltTy - The pointee type represented by LVal. 3184 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3185 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3186 LValue &LVal, QualType EltTy, 3187 APSInt Adjustment) { 3188 CharUnits SizeOfPointee; 3189 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3190 return false; 3191 3192 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3193 return true; 3194 } 3195 3196 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3197 LValue &LVal, QualType EltTy, 3198 int64_t Adjustment) { 3199 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3200 APSInt::get(Adjustment)); 3201 } 3202 3203 /// Update an lvalue to refer to a component of a complex number. 3204 /// \param Info - Information about the ongoing evaluation. 3205 /// \param LVal - The lvalue to be updated. 3206 /// \param EltTy - The complex number's component type. 3207 /// \param Imag - False for the real component, true for the imaginary. 3208 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3209 LValue &LVal, QualType EltTy, 3210 bool Imag) { 3211 if (Imag) { 3212 CharUnits SizeOfComponent; 3213 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3214 return false; 3215 LVal.Offset += SizeOfComponent; 3216 } 3217 LVal.addComplex(Info, E, EltTy, Imag); 3218 return true; 3219 } 3220 3221 /// Try to evaluate the initializer for a variable declaration. 3222 /// 3223 /// \param Info Information about the ongoing evaluation. 3224 /// \param E An expression to be used when printing diagnostics. 3225 /// \param VD The variable whose initializer should be obtained. 3226 /// \param Version The version of the variable within the frame. 3227 /// \param Frame The frame in which the variable was created. Must be null 3228 /// if this variable is not local to the evaluation. 3229 /// \param Result Filled in with a pointer to the value of the variable. 3230 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3231 const VarDecl *VD, CallStackFrame *Frame, 3232 unsigned Version, APValue *&Result) { 3233 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3234 3235 // If this is a local variable, dig out its value. 3236 if (Frame) { 3237 Result = Frame->getTemporary(VD, Version); 3238 if (Result) 3239 return true; 3240 3241 if (!isa<ParmVarDecl>(VD)) { 3242 // Assume variables referenced within a lambda's call operator that were 3243 // not declared within the call operator are captures and during checking 3244 // of a potential constant expression, assume they are unknown constant 3245 // expressions. 3246 assert(isLambdaCallOperator(Frame->Callee) && 3247 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3248 "missing value for local variable"); 3249 if (Info.checkingPotentialConstantExpression()) 3250 return false; 3251 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3252 // still reachable at all? 3253 Info.FFDiag(E->getBeginLoc(), 3254 diag::note_unimplemented_constexpr_lambda_feature_ast) 3255 << "captures not currently allowed"; 3256 return false; 3257 } 3258 } 3259 3260 // If we're currently evaluating the initializer of this declaration, use that 3261 // in-flight value. 3262 if (Info.EvaluatingDecl == Base) { 3263 Result = Info.EvaluatingDeclValue; 3264 return true; 3265 } 3266 3267 if (isa<ParmVarDecl>(VD)) { 3268 // Assume parameters of a potential constant expression are usable in 3269 // constant expressions. 3270 if (!Info.checkingPotentialConstantExpression() || 3271 !Info.CurrentCall->Callee || 3272 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3273 if (Info.getLangOpts().CPlusPlus11) { 3274 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3275 << VD; 3276 NoteLValueLocation(Info, Base); 3277 } else { 3278 Info.FFDiag(E); 3279 } 3280 } 3281 return false; 3282 } 3283 3284 // Dig out the initializer, and use the declaration which it's attached to. 3285 // FIXME: We should eventually check whether the variable has a reachable 3286 // initializing declaration. 3287 const Expr *Init = VD->getAnyInitializer(VD); 3288 if (!Init) { 3289 // Don't diagnose during potential constant expression checking; an 3290 // initializer might be added later. 3291 if (!Info.checkingPotentialConstantExpression()) { 3292 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3293 << VD; 3294 NoteLValueLocation(Info, Base); 3295 } 3296 return false; 3297 } 3298 3299 if (Init->isValueDependent()) { 3300 // The DeclRefExpr is not value-dependent, but the variable it refers to 3301 // has a value-dependent initializer. This should only happen in 3302 // constant-folding cases, where the variable is not actually of a suitable 3303 // type for use in a constant expression (otherwise the DeclRefExpr would 3304 // have been value-dependent too), so diagnose that. 3305 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3306 if (!Info.checkingPotentialConstantExpression()) { 3307 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3308 ? diag::note_constexpr_ltor_non_constexpr 3309 : diag::note_constexpr_ltor_non_integral, 1) 3310 << VD << VD->getType(); 3311 NoteLValueLocation(Info, Base); 3312 } 3313 return false; 3314 } 3315 3316 // Check that we can fold the initializer. In C++, we will have already done 3317 // this in the cases where it matters for conformance. 3318 if (!VD->evaluateValue()) { 3319 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3320 NoteLValueLocation(Info, Base); 3321 return false; 3322 } 3323 3324 // Check that the variable is actually usable in constant expressions. For a 3325 // const integral variable or a reference, we might have a non-constant 3326 // initializer that we can nonetheless evaluate the initializer for. Such 3327 // variables are not usable in constant expressions. In C++98, the 3328 // initializer also syntactically needs to be an ICE. 3329 // 3330 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3331 // expressions here; doing so would regress diagnostics for things like 3332 // reading from a volatile constexpr variable. 3333 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3334 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3335 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3336 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3337 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3338 NoteLValueLocation(Info, Base); 3339 } 3340 3341 // Never use the initializer of a weak variable, not even for constant 3342 // folding. We can't be sure that this is the definition that will be used. 3343 if (VD->isWeak()) { 3344 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3345 NoteLValueLocation(Info, Base); 3346 return false; 3347 } 3348 3349 Result = VD->getEvaluatedValue(); 3350 return true; 3351 } 3352 3353 /// Get the base index of the given base class within an APValue representing 3354 /// the given derived class. 3355 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3356 const CXXRecordDecl *Base) { 3357 Base = Base->getCanonicalDecl(); 3358 unsigned Index = 0; 3359 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3360 E = Derived->bases_end(); I != E; ++I, ++Index) { 3361 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3362 return Index; 3363 } 3364 3365 llvm_unreachable("base class missing from derived class's bases list"); 3366 } 3367 3368 /// Extract the value of a character from a string literal. 3369 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3370 uint64_t Index) { 3371 assert(!isa<SourceLocExpr>(Lit) && 3372 "SourceLocExpr should have already been converted to a StringLiteral"); 3373 3374 // FIXME: Support MakeStringConstant 3375 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3376 std::string Str; 3377 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3378 assert(Index <= Str.size() && "Index too large"); 3379 return APSInt::getUnsigned(Str.c_str()[Index]); 3380 } 3381 3382 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3383 Lit = PE->getFunctionName(); 3384 const StringLiteral *S = cast<StringLiteral>(Lit); 3385 const ConstantArrayType *CAT = 3386 Info.Ctx.getAsConstantArrayType(S->getType()); 3387 assert(CAT && "string literal isn't an array"); 3388 QualType CharType = CAT->getElementType(); 3389 assert(CharType->isIntegerType() && "unexpected character type"); 3390 3391 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3392 CharType->isUnsignedIntegerType()); 3393 if (Index < S->getLength()) 3394 Value = S->getCodeUnit(Index); 3395 return Value; 3396 } 3397 3398 // Expand a string literal into an array of characters. 3399 // 3400 // FIXME: This is inefficient; we should probably introduce something similar 3401 // to the LLVM ConstantDataArray to make this cheaper. 3402 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3403 APValue &Result, 3404 QualType AllocType = QualType()) { 3405 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3406 AllocType.isNull() ? S->getType() : AllocType); 3407 assert(CAT && "string literal isn't an array"); 3408 QualType CharType = CAT->getElementType(); 3409 assert(CharType->isIntegerType() && "unexpected character type"); 3410 3411 unsigned Elts = CAT->getSize().getZExtValue(); 3412 Result = APValue(APValue::UninitArray(), 3413 std::min(S->getLength(), Elts), Elts); 3414 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3415 CharType->isUnsignedIntegerType()); 3416 if (Result.hasArrayFiller()) 3417 Result.getArrayFiller() = APValue(Value); 3418 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3419 Value = S->getCodeUnit(I); 3420 Result.getArrayInitializedElt(I) = APValue(Value); 3421 } 3422 } 3423 3424 // Expand an array so that it has more than Index filled elements. 3425 static void expandArray(APValue &Array, unsigned Index) { 3426 unsigned Size = Array.getArraySize(); 3427 assert(Index < Size); 3428 3429 // Always at least double the number of elements for which we store a value. 3430 unsigned OldElts = Array.getArrayInitializedElts(); 3431 unsigned NewElts = std::max(Index+1, OldElts * 2); 3432 NewElts = std::min(Size, std::max(NewElts, 8u)); 3433 3434 // Copy the data across. 3435 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3436 for (unsigned I = 0; I != OldElts; ++I) 3437 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3438 for (unsigned I = OldElts; I != NewElts; ++I) 3439 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3440 if (NewValue.hasArrayFiller()) 3441 NewValue.getArrayFiller() = Array.getArrayFiller(); 3442 Array.swap(NewValue); 3443 } 3444 3445 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3446 /// conversion. If it's of class type, we may assume that the copy operation 3447 /// is trivial. Note that this is never true for a union type with fields 3448 /// (because the copy always "reads" the active member) and always true for 3449 /// a non-class type. 3450 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3451 static bool isReadByLvalueToRvalueConversion(QualType T) { 3452 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3453 return !RD || isReadByLvalueToRvalueConversion(RD); 3454 } 3455 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3456 // FIXME: A trivial copy of a union copies the object representation, even if 3457 // the union is empty. 3458 if (RD->isUnion()) 3459 return !RD->field_empty(); 3460 if (RD->isEmpty()) 3461 return false; 3462 3463 for (auto *Field : RD->fields()) 3464 if (!Field->isUnnamedBitfield() && 3465 isReadByLvalueToRvalueConversion(Field->getType())) 3466 return true; 3467 3468 for (auto &BaseSpec : RD->bases()) 3469 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3470 return true; 3471 3472 return false; 3473 } 3474 3475 /// Diagnose an attempt to read from any unreadable field within the specified 3476 /// type, which might be a class type. 3477 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3478 QualType T) { 3479 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3480 if (!RD) 3481 return false; 3482 3483 if (!RD->hasMutableFields()) 3484 return false; 3485 3486 for (auto *Field : RD->fields()) { 3487 // If we're actually going to read this field in some way, then it can't 3488 // be mutable. If we're in a union, then assigning to a mutable field 3489 // (even an empty one) can change the active member, so that's not OK. 3490 // FIXME: Add core issue number for the union case. 3491 if (Field->isMutable() && 3492 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3493 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3494 Info.Note(Field->getLocation(), diag::note_declared_at); 3495 return true; 3496 } 3497 3498 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3499 return true; 3500 } 3501 3502 for (auto &BaseSpec : RD->bases()) 3503 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3504 return true; 3505 3506 // All mutable fields were empty, and thus not actually read. 3507 return false; 3508 } 3509 3510 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3511 APValue::LValueBase Base, 3512 bool MutableSubobject = false) { 3513 // A temporary we created. 3514 if (Base.getCallIndex()) 3515 return true; 3516 3517 switch (Info.IsEvaluatingDecl) { 3518 case EvalInfo::EvaluatingDeclKind::None: 3519 return false; 3520 3521 case EvalInfo::EvaluatingDeclKind::Ctor: 3522 // The variable whose initializer we're evaluating. 3523 if (Info.EvaluatingDecl == Base) 3524 return true; 3525 3526 // A temporary lifetime-extended by the variable whose initializer we're 3527 // evaluating. 3528 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3529 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3530 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3531 return false; 3532 3533 case EvalInfo::EvaluatingDeclKind::Dtor: 3534 // C++2a [expr.const]p6: 3535 // [during constant destruction] the lifetime of a and its non-mutable 3536 // subobjects (but not its mutable subobjects) [are] considered to start 3537 // within e. 3538 if (MutableSubobject || Base != Info.EvaluatingDecl) 3539 return false; 3540 // FIXME: We can meaningfully extend this to cover non-const objects, but 3541 // we will need special handling: we should be able to access only 3542 // subobjects of such objects that are themselves declared const. 3543 QualType T = getType(Base); 3544 return T.isConstQualified() || T->isReferenceType(); 3545 } 3546 3547 llvm_unreachable("unknown evaluating decl kind"); 3548 } 3549 3550 namespace { 3551 /// A handle to a complete object (an object that is not a subobject of 3552 /// another object). 3553 struct CompleteObject { 3554 /// The identity of the object. 3555 APValue::LValueBase Base; 3556 /// The value of the complete object. 3557 APValue *Value; 3558 /// The type of the complete object. 3559 QualType Type; 3560 3561 CompleteObject() : Value(nullptr) {} 3562 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3563 : Base(Base), Value(Value), Type(Type) {} 3564 3565 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3566 // If this isn't a "real" access (eg, if it's just accessing the type 3567 // info), allow it. We assume the type doesn't change dynamically for 3568 // subobjects of constexpr objects (even though we'd hit UB here if it 3569 // did). FIXME: Is this right? 3570 if (!isAnyAccess(AK)) 3571 return true; 3572 3573 // In C++14 onwards, it is permitted to read a mutable member whose 3574 // lifetime began within the evaluation. 3575 // FIXME: Should we also allow this in C++11? 3576 if (!Info.getLangOpts().CPlusPlus14) 3577 return false; 3578 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3579 } 3580 3581 explicit operator bool() const { return !Type.isNull(); } 3582 }; 3583 } // end anonymous namespace 3584 3585 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3586 bool IsMutable = false) { 3587 // C++ [basic.type.qualifier]p1: 3588 // - A const object is an object of type const T or a non-mutable subobject 3589 // of a const object. 3590 if (ObjType.isConstQualified() && !IsMutable) 3591 SubobjType.addConst(); 3592 // - A volatile object is an object of type const T or a subobject of a 3593 // volatile object. 3594 if (ObjType.isVolatileQualified()) 3595 SubobjType.addVolatile(); 3596 return SubobjType; 3597 } 3598 3599 /// Find the designated sub-object of an rvalue. 3600 template<typename SubobjectHandler> 3601 typename SubobjectHandler::result_type 3602 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3603 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3604 if (Sub.Invalid) 3605 // A diagnostic will have already been produced. 3606 return handler.failed(); 3607 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3608 if (Info.getLangOpts().CPlusPlus11) 3609 Info.FFDiag(E, Sub.isOnePastTheEnd() 3610 ? diag::note_constexpr_access_past_end 3611 : diag::note_constexpr_access_unsized_array) 3612 << handler.AccessKind; 3613 else 3614 Info.FFDiag(E); 3615 return handler.failed(); 3616 } 3617 3618 APValue *O = Obj.Value; 3619 QualType ObjType = Obj.Type; 3620 const FieldDecl *LastField = nullptr; 3621 const FieldDecl *VolatileField = nullptr; 3622 3623 // Walk the designator's path to find the subobject. 3624 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3625 // Reading an indeterminate value is undefined, but assigning over one is OK. 3626 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3627 (O->isIndeterminate() && 3628 !isValidIndeterminateAccess(handler.AccessKind))) { 3629 if (!Info.checkingPotentialConstantExpression()) 3630 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3631 << handler.AccessKind << O->isIndeterminate(); 3632 return handler.failed(); 3633 } 3634 3635 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3636 // const and volatile semantics are not applied on an object under 3637 // {con,de}struction. 3638 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3639 ObjType->isRecordType() && 3640 Info.isEvaluatingCtorDtor( 3641 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3642 Sub.Entries.begin() + I)) != 3643 ConstructionPhase::None) { 3644 ObjType = Info.Ctx.getCanonicalType(ObjType); 3645 ObjType.removeLocalConst(); 3646 ObjType.removeLocalVolatile(); 3647 } 3648 3649 // If this is our last pass, check that the final object type is OK. 3650 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3651 // Accesses to volatile objects are prohibited. 3652 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3653 if (Info.getLangOpts().CPlusPlus) { 3654 int DiagKind; 3655 SourceLocation Loc; 3656 const NamedDecl *Decl = nullptr; 3657 if (VolatileField) { 3658 DiagKind = 2; 3659 Loc = VolatileField->getLocation(); 3660 Decl = VolatileField; 3661 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3662 DiagKind = 1; 3663 Loc = VD->getLocation(); 3664 Decl = VD; 3665 } else { 3666 DiagKind = 0; 3667 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3668 Loc = E->getExprLoc(); 3669 } 3670 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3671 << handler.AccessKind << DiagKind << Decl; 3672 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3673 } else { 3674 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3675 } 3676 return handler.failed(); 3677 } 3678 3679 // If we are reading an object of class type, there may still be more 3680 // things we need to check: if there are any mutable subobjects, we 3681 // cannot perform this read. (This only happens when performing a trivial 3682 // copy or assignment.) 3683 if (ObjType->isRecordType() && 3684 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3685 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3686 return handler.failed(); 3687 } 3688 3689 if (I == N) { 3690 if (!handler.found(*O, ObjType)) 3691 return false; 3692 3693 // If we modified a bit-field, truncate it to the right width. 3694 if (isModification(handler.AccessKind) && 3695 LastField && LastField->isBitField() && 3696 !truncateBitfieldValue(Info, E, *O, LastField)) 3697 return false; 3698 3699 return true; 3700 } 3701 3702 LastField = nullptr; 3703 if (ObjType->isArrayType()) { 3704 // Next subobject is an array element. 3705 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3706 assert(CAT && "vla in literal type?"); 3707 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3708 if (CAT->getSize().ule(Index)) { 3709 // Note, it should not be possible to form a pointer with a valid 3710 // designator which points more than one past the end of the array. 3711 if (Info.getLangOpts().CPlusPlus11) 3712 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3713 << handler.AccessKind; 3714 else 3715 Info.FFDiag(E); 3716 return handler.failed(); 3717 } 3718 3719 ObjType = CAT->getElementType(); 3720 3721 if (O->getArrayInitializedElts() > Index) 3722 O = &O->getArrayInitializedElt(Index); 3723 else if (!isRead(handler.AccessKind)) { 3724 expandArray(*O, Index); 3725 O = &O->getArrayInitializedElt(Index); 3726 } else 3727 O = &O->getArrayFiller(); 3728 } else if (ObjType->isAnyComplexType()) { 3729 // Next subobject is a complex number. 3730 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3731 if (Index > 1) { 3732 if (Info.getLangOpts().CPlusPlus11) 3733 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3734 << handler.AccessKind; 3735 else 3736 Info.FFDiag(E); 3737 return handler.failed(); 3738 } 3739 3740 ObjType = getSubobjectType( 3741 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3742 3743 assert(I == N - 1 && "extracting subobject of scalar?"); 3744 if (O->isComplexInt()) { 3745 return handler.found(Index ? O->getComplexIntImag() 3746 : O->getComplexIntReal(), ObjType); 3747 } else { 3748 assert(O->isComplexFloat()); 3749 return handler.found(Index ? O->getComplexFloatImag() 3750 : O->getComplexFloatReal(), ObjType); 3751 } 3752 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3753 if (Field->isMutable() && 3754 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3755 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3756 << handler.AccessKind << Field; 3757 Info.Note(Field->getLocation(), diag::note_declared_at); 3758 return handler.failed(); 3759 } 3760 3761 // Next subobject is a class, struct or union field. 3762 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3763 if (RD->isUnion()) { 3764 const FieldDecl *UnionField = O->getUnionField(); 3765 if (!UnionField || 3766 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3767 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3768 // Placement new onto an inactive union member makes it active. 3769 O->setUnion(Field, APValue()); 3770 } else { 3771 // FIXME: If O->getUnionValue() is absent, report that there's no 3772 // active union member rather than reporting the prior active union 3773 // member. We'll need to fix nullptr_t to not use APValue() as its 3774 // representation first. 3775 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3776 << handler.AccessKind << Field << !UnionField << UnionField; 3777 return handler.failed(); 3778 } 3779 } 3780 O = &O->getUnionValue(); 3781 } else 3782 O = &O->getStructField(Field->getFieldIndex()); 3783 3784 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3785 LastField = Field; 3786 if (Field->getType().isVolatileQualified()) 3787 VolatileField = Field; 3788 } else { 3789 // Next subobject is a base class. 3790 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3791 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3792 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3793 3794 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3795 } 3796 } 3797 } 3798 3799 namespace { 3800 struct ExtractSubobjectHandler { 3801 EvalInfo &Info; 3802 const Expr *E; 3803 APValue &Result; 3804 const AccessKinds AccessKind; 3805 3806 typedef bool result_type; 3807 bool failed() { return false; } 3808 bool found(APValue &Subobj, QualType SubobjType) { 3809 Result = Subobj; 3810 if (AccessKind == AK_ReadObjectRepresentation) 3811 return true; 3812 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3813 } 3814 bool found(APSInt &Value, QualType SubobjType) { 3815 Result = APValue(Value); 3816 return true; 3817 } 3818 bool found(APFloat &Value, QualType SubobjType) { 3819 Result = APValue(Value); 3820 return true; 3821 } 3822 }; 3823 } // end anonymous namespace 3824 3825 /// Extract the designated sub-object of an rvalue. 3826 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3827 const CompleteObject &Obj, 3828 const SubobjectDesignator &Sub, APValue &Result, 3829 AccessKinds AK = AK_Read) { 3830 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3831 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3832 return findSubobject(Info, E, Obj, Sub, Handler); 3833 } 3834 3835 namespace { 3836 struct ModifySubobjectHandler { 3837 EvalInfo &Info; 3838 APValue &NewVal; 3839 const Expr *E; 3840 3841 typedef bool result_type; 3842 static const AccessKinds AccessKind = AK_Assign; 3843 3844 bool checkConst(QualType QT) { 3845 // Assigning to a const object has undefined behavior. 3846 if (QT.isConstQualified()) { 3847 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3848 return false; 3849 } 3850 return true; 3851 } 3852 3853 bool failed() { return false; } 3854 bool found(APValue &Subobj, QualType SubobjType) { 3855 if (!checkConst(SubobjType)) 3856 return false; 3857 // We've been given ownership of NewVal, so just swap it in. 3858 Subobj.swap(NewVal); 3859 return true; 3860 } 3861 bool found(APSInt &Value, QualType SubobjType) { 3862 if (!checkConst(SubobjType)) 3863 return false; 3864 if (!NewVal.isInt()) { 3865 // Maybe trying to write a cast pointer value into a complex? 3866 Info.FFDiag(E); 3867 return false; 3868 } 3869 Value = NewVal.getInt(); 3870 return true; 3871 } 3872 bool found(APFloat &Value, QualType SubobjType) { 3873 if (!checkConst(SubobjType)) 3874 return false; 3875 Value = NewVal.getFloat(); 3876 return true; 3877 } 3878 }; 3879 } // end anonymous namespace 3880 3881 const AccessKinds ModifySubobjectHandler::AccessKind; 3882 3883 /// Update the designated sub-object of an rvalue to the given value. 3884 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3885 const CompleteObject &Obj, 3886 const SubobjectDesignator &Sub, 3887 APValue &NewVal) { 3888 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3889 return findSubobject(Info, E, Obj, Sub, Handler); 3890 } 3891 3892 /// Find the position where two subobject designators diverge, or equivalently 3893 /// the length of the common initial subsequence. 3894 static unsigned FindDesignatorMismatch(QualType ObjType, 3895 const SubobjectDesignator &A, 3896 const SubobjectDesignator &B, 3897 bool &WasArrayIndex) { 3898 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3899 for (/**/; I != N; ++I) { 3900 if (!ObjType.isNull() && 3901 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3902 // Next subobject is an array element. 3903 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3904 WasArrayIndex = true; 3905 return I; 3906 } 3907 if (ObjType->isAnyComplexType()) 3908 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3909 else 3910 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3911 } else { 3912 if (A.Entries[I].getAsBaseOrMember() != 3913 B.Entries[I].getAsBaseOrMember()) { 3914 WasArrayIndex = false; 3915 return I; 3916 } 3917 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3918 // Next subobject is a field. 3919 ObjType = FD->getType(); 3920 else 3921 // Next subobject is a base class. 3922 ObjType = QualType(); 3923 } 3924 } 3925 WasArrayIndex = false; 3926 return I; 3927 } 3928 3929 /// Determine whether the given subobject designators refer to elements of the 3930 /// same array object. 3931 static bool AreElementsOfSameArray(QualType ObjType, 3932 const SubobjectDesignator &A, 3933 const SubobjectDesignator &B) { 3934 if (A.Entries.size() != B.Entries.size()) 3935 return false; 3936 3937 bool IsArray = A.MostDerivedIsArrayElement; 3938 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3939 // A is a subobject of the array element. 3940 return false; 3941 3942 // If A (and B) designates an array element, the last entry will be the array 3943 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3944 // of length 1' case, and the entire path must match. 3945 bool WasArrayIndex; 3946 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3947 return CommonLength >= A.Entries.size() - IsArray; 3948 } 3949 3950 /// Find the complete object to which an LValue refers. 3951 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3952 AccessKinds AK, const LValue &LVal, 3953 QualType LValType) { 3954 if (LVal.InvalidBase) { 3955 Info.FFDiag(E); 3956 return CompleteObject(); 3957 } 3958 3959 if (!LVal.Base) { 3960 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3961 return CompleteObject(); 3962 } 3963 3964 CallStackFrame *Frame = nullptr; 3965 unsigned Depth = 0; 3966 if (LVal.getLValueCallIndex()) { 3967 std::tie(Frame, Depth) = 3968 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3969 if (!Frame) { 3970 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3971 << AK << LVal.Base.is<const ValueDecl*>(); 3972 NoteLValueLocation(Info, LVal.Base); 3973 return CompleteObject(); 3974 } 3975 } 3976 3977 bool IsAccess = isAnyAccess(AK); 3978 3979 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3980 // is not a constant expression (even if the object is non-volatile). We also 3981 // apply this rule to C++98, in order to conform to the expected 'volatile' 3982 // semantics. 3983 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3984 if (Info.getLangOpts().CPlusPlus) 3985 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3986 << AK << LValType; 3987 else 3988 Info.FFDiag(E); 3989 return CompleteObject(); 3990 } 3991 3992 // Compute value storage location and type of base object. 3993 APValue *BaseVal = nullptr; 3994 QualType BaseType = getType(LVal.Base); 3995 3996 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3997 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3998 // This is the object whose initializer we're evaluating, so its lifetime 3999 // started in the current evaluation. 4000 BaseVal = Info.EvaluatingDeclValue; 4001 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4002 // Allow reading from a GUID declaration. 4003 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4004 if (isModification(AK)) { 4005 // All the remaining cases do not permit modification of the object. 4006 Info.FFDiag(E, diag::note_constexpr_modify_global); 4007 return CompleteObject(); 4008 } 4009 APValue &V = GD->getAsAPValue(); 4010 if (V.isAbsent()) { 4011 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4012 << GD->getType(); 4013 return CompleteObject(); 4014 } 4015 return CompleteObject(LVal.Base, &V, GD->getType()); 4016 } 4017 4018 // Allow reading from template parameter objects. 4019 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4020 if (isModification(AK)) { 4021 Info.FFDiag(E, diag::note_constexpr_modify_global); 4022 return CompleteObject(); 4023 } 4024 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4025 TPO->getType()); 4026 } 4027 4028 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4029 // In C++11, constexpr, non-volatile variables initialized with constant 4030 // expressions are constant expressions too. Inside constexpr functions, 4031 // parameters are constant expressions even if they're non-const. 4032 // In C++1y, objects local to a constant expression (those with a Frame) are 4033 // both readable and writable inside constant expressions. 4034 // In C, such things can also be folded, although they are not ICEs. 4035 const VarDecl *VD = dyn_cast<VarDecl>(D); 4036 if (VD) { 4037 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4038 VD = VDef; 4039 } 4040 if (!VD || VD->isInvalidDecl()) { 4041 Info.FFDiag(E); 4042 return CompleteObject(); 4043 } 4044 4045 bool IsConstant = BaseType.isConstant(Info.Ctx); 4046 4047 // Unless we're looking at a local variable or argument in a constexpr call, 4048 // the variable we're reading must be const. 4049 if (!Frame) { 4050 if (IsAccess && isa<ParmVarDecl>(VD)) { 4051 // Access of a parameter that's not associated with a frame isn't going 4052 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4053 // suitable diagnostic. 4054 } else if (Info.getLangOpts().CPlusPlus14 && 4055 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4056 // OK, we can read and modify an object if we're in the process of 4057 // evaluating its initializer, because its lifetime began in this 4058 // evaluation. 4059 } else if (isModification(AK)) { 4060 // All the remaining cases do not permit modification of the object. 4061 Info.FFDiag(E, diag::note_constexpr_modify_global); 4062 return CompleteObject(); 4063 } else if (VD->isConstexpr()) { 4064 // OK, we can read this variable. 4065 } else if (BaseType->isIntegralOrEnumerationType()) { 4066 if (!IsConstant) { 4067 if (!IsAccess) 4068 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4069 if (Info.getLangOpts().CPlusPlus) { 4070 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4071 Info.Note(VD->getLocation(), diag::note_declared_at); 4072 } else { 4073 Info.FFDiag(E); 4074 } 4075 return CompleteObject(); 4076 } 4077 } else if (!IsAccess) { 4078 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4079 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4080 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4081 // This variable might end up being constexpr. Don't diagnose it yet. 4082 } else if (IsConstant) { 4083 // Keep evaluating to see what we can do. In particular, we support 4084 // folding of const floating-point types, in order to make static const 4085 // data members of such types (supported as an extension) more useful. 4086 if (Info.getLangOpts().CPlusPlus) { 4087 Info.CCEDiag(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.CCEDiag(E); 4094 } 4095 } else { 4096 // Never allow reading a non-const value. 4097 if (Info.getLangOpts().CPlusPlus) { 4098 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4099 ? diag::note_constexpr_ltor_non_constexpr 4100 : diag::note_constexpr_ltor_non_integral, 1) 4101 << VD << BaseType; 4102 Info.Note(VD->getLocation(), diag::note_declared_at); 4103 } else { 4104 Info.FFDiag(E); 4105 } 4106 return CompleteObject(); 4107 } 4108 } 4109 4110 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4111 return CompleteObject(); 4112 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4113 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4114 if (!Alloc) { 4115 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4116 return CompleteObject(); 4117 } 4118 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4119 LVal.Base.getDynamicAllocType()); 4120 } else { 4121 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4122 4123 if (!Frame) { 4124 if (const MaterializeTemporaryExpr *MTE = 4125 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4126 assert(MTE->getStorageDuration() == SD_Static && 4127 "should have a frame for a non-global materialized temporary"); 4128 4129 // C++20 [expr.const]p4: [DR2126] 4130 // An object or reference is usable in constant expressions if it is 4131 // - a temporary object of non-volatile const-qualified literal type 4132 // whose lifetime is extended to that of a variable that is usable 4133 // in constant expressions 4134 // 4135 // C++20 [expr.const]p5: 4136 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4137 // - a non-volatile glvalue that refers to an object that is usable 4138 // in constant expressions, or 4139 // - a non-volatile glvalue of literal type that refers to a 4140 // non-volatile object whose lifetime began within the evaluation 4141 // of E; 4142 // 4143 // C++11 misses the 'began within the evaluation of e' check and 4144 // instead allows all temporaries, including things like: 4145 // int &&r = 1; 4146 // int x = ++r; 4147 // constexpr int k = r; 4148 // Therefore we use the C++14-onwards rules in C++11 too. 4149 // 4150 // Note that temporaries whose lifetimes began while evaluating a 4151 // variable's constructor are not usable while evaluating the 4152 // corresponding destructor, not even if they're of const-qualified 4153 // types. 4154 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4155 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4156 if (!IsAccess) 4157 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4158 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4159 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4160 return CompleteObject(); 4161 } 4162 4163 BaseVal = MTE->getOrCreateValue(false); 4164 assert(BaseVal && "got reference to unevaluated temporary"); 4165 } else { 4166 if (!IsAccess) 4167 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4168 APValue Val; 4169 LVal.moveInto(Val); 4170 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4171 << AK 4172 << Val.getAsString(Info.Ctx, 4173 Info.Ctx.getLValueReferenceType(LValType)); 4174 NoteLValueLocation(Info, LVal.Base); 4175 return CompleteObject(); 4176 } 4177 } else { 4178 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4179 assert(BaseVal && "missing value for temporary"); 4180 } 4181 } 4182 4183 // In C++14, we can't safely access any mutable state when we might be 4184 // evaluating after an unmodeled side effect. Parameters are modeled as state 4185 // in the caller, but aren't visible once the call returns, so they can be 4186 // modified in a speculatively-evaluated call. 4187 // 4188 // FIXME: Not all local state is mutable. Allow local constant subobjects 4189 // to be read here (but take care with 'mutable' fields). 4190 unsigned VisibleDepth = Depth; 4191 if (llvm::isa_and_nonnull<ParmVarDecl>( 4192 LVal.Base.dyn_cast<const ValueDecl *>())) 4193 ++VisibleDepth; 4194 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4195 Info.EvalStatus.HasSideEffects) || 4196 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4197 return CompleteObject(); 4198 4199 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4200 } 4201 4202 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4203 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4204 /// glvalue referred to by an entity of reference type. 4205 /// 4206 /// \param Info - Information about the ongoing evaluation. 4207 /// \param Conv - The expression for which we are performing the conversion. 4208 /// Used for diagnostics. 4209 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4210 /// case of a non-class type). 4211 /// \param LVal - The glvalue on which we are attempting to perform this action. 4212 /// \param RVal - The produced value will be placed here. 4213 /// \param WantObjectRepresentation - If true, we're looking for the object 4214 /// representation rather than the value, and in particular, 4215 /// there is no requirement that the result be fully initialized. 4216 static bool 4217 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4218 const LValue &LVal, APValue &RVal, 4219 bool WantObjectRepresentation = false) { 4220 if (LVal.Designator.Invalid) 4221 return false; 4222 4223 // Check for special cases where there is no existing APValue to look at. 4224 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4225 4226 AccessKinds AK = 4227 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4228 4229 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4230 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4231 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4232 // initializer until now for such expressions. Such an expression can't be 4233 // an ICE in C, so this only matters for fold. 4234 if (Type.isVolatileQualified()) { 4235 Info.FFDiag(Conv); 4236 return false; 4237 } 4238 APValue Lit; 4239 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4240 return false; 4241 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4242 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4243 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4244 // Special-case character extraction so we don't have to construct an 4245 // APValue for the whole string. 4246 assert(LVal.Designator.Entries.size() <= 1 && 4247 "Can only read characters from string literals"); 4248 if (LVal.Designator.Entries.empty()) { 4249 // Fail for now for LValue to RValue conversion of an array. 4250 // (This shouldn't show up in C/C++, but it could be triggered by a 4251 // weird EvaluateAsRValue call from a tool.) 4252 Info.FFDiag(Conv); 4253 return false; 4254 } 4255 if (LVal.Designator.isOnePastTheEnd()) { 4256 if (Info.getLangOpts().CPlusPlus11) 4257 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4258 else 4259 Info.FFDiag(Conv); 4260 return false; 4261 } 4262 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4263 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4264 return true; 4265 } 4266 } 4267 4268 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4269 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4270 } 4271 4272 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4273 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4274 QualType LValType, APValue &Val) { 4275 if (LVal.Designator.Invalid) 4276 return false; 4277 4278 if (!Info.getLangOpts().CPlusPlus14) { 4279 Info.FFDiag(E); 4280 return false; 4281 } 4282 4283 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4284 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4285 } 4286 4287 namespace { 4288 struct CompoundAssignSubobjectHandler { 4289 EvalInfo &Info; 4290 const CompoundAssignOperator *E; 4291 QualType PromotedLHSType; 4292 BinaryOperatorKind Opcode; 4293 const APValue &RHS; 4294 4295 static const AccessKinds AccessKind = AK_Assign; 4296 4297 typedef bool result_type; 4298 4299 bool checkConst(QualType QT) { 4300 // Assigning to a const object has undefined behavior. 4301 if (QT.isConstQualified()) { 4302 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4303 return false; 4304 } 4305 return true; 4306 } 4307 4308 bool failed() { return false; } 4309 bool found(APValue &Subobj, QualType SubobjType) { 4310 switch (Subobj.getKind()) { 4311 case APValue::Int: 4312 return found(Subobj.getInt(), SubobjType); 4313 case APValue::Float: 4314 return found(Subobj.getFloat(), SubobjType); 4315 case APValue::ComplexInt: 4316 case APValue::ComplexFloat: 4317 // FIXME: Implement complex compound assignment. 4318 Info.FFDiag(E); 4319 return false; 4320 case APValue::LValue: 4321 return foundPointer(Subobj, SubobjType); 4322 case APValue::Vector: 4323 return foundVector(Subobj, SubobjType); 4324 default: 4325 // FIXME: can this happen? 4326 Info.FFDiag(E); 4327 return false; 4328 } 4329 } 4330 4331 bool foundVector(APValue &Value, QualType SubobjType) { 4332 if (!checkConst(SubobjType)) 4333 return false; 4334 4335 if (!SubobjType->isVectorType()) { 4336 Info.FFDiag(E); 4337 return false; 4338 } 4339 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4340 } 4341 4342 bool found(APSInt &Value, QualType SubobjType) { 4343 if (!checkConst(SubobjType)) 4344 return false; 4345 4346 if (!SubobjType->isIntegerType()) { 4347 // We don't support compound assignment on integer-cast-to-pointer 4348 // values. 4349 Info.FFDiag(E); 4350 return false; 4351 } 4352 4353 if (RHS.isInt()) { 4354 APSInt LHS = 4355 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4356 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4357 return false; 4358 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4359 return true; 4360 } else if (RHS.isFloat()) { 4361 const FPOptions FPO = E->getFPFeaturesInEffect( 4362 Info.Ctx.getLangOpts()); 4363 APFloat FValue(0.0); 4364 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4365 PromotedLHSType, FValue) && 4366 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4367 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4368 Value); 4369 } 4370 4371 Info.FFDiag(E); 4372 return false; 4373 } 4374 bool found(APFloat &Value, QualType SubobjType) { 4375 return checkConst(SubobjType) && 4376 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4377 Value) && 4378 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4379 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4380 } 4381 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4382 if (!checkConst(SubobjType)) 4383 return false; 4384 4385 QualType PointeeType; 4386 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4387 PointeeType = PT->getPointeeType(); 4388 4389 if (PointeeType.isNull() || !RHS.isInt() || 4390 (Opcode != BO_Add && Opcode != BO_Sub)) { 4391 Info.FFDiag(E); 4392 return false; 4393 } 4394 4395 APSInt Offset = RHS.getInt(); 4396 if (Opcode == BO_Sub) 4397 negateAsSigned(Offset); 4398 4399 LValue LVal; 4400 LVal.setFrom(Info.Ctx, Subobj); 4401 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4402 return false; 4403 LVal.moveInto(Subobj); 4404 return true; 4405 } 4406 }; 4407 } // end anonymous namespace 4408 4409 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4410 4411 /// Perform a compound assignment of LVal <op>= RVal. 4412 static bool handleCompoundAssignment(EvalInfo &Info, 4413 const CompoundAssignOperator *E, 4414 const LValue &LVal, QualType LValType, 4415 QualType PromotedLValType, 4416 BinaryOperatorKind Opcode, 4417 const APValue &RVal) { 4418 if (LVal.Designator.Invalid) 4419 return false; 4420 4421 if (!Info.getLangOpts().CPlusPlus14) { 4422 Info.FFDiag(E); 4423 return false; 4424 } 4425 4426 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4427 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4428 RVal }; 4429 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4430 } 4431 4432 namespace { 4433 struct IncDecSubobjectHandler { 4434 EvalInfo &Info; 4435 const UnaryOperator *E; 4436 AccessKinds AccessKind; 4437 APValue *Old; 4438 4439 typedef bool result_type; 4440 4441 bool checkConst(QualType QT) { 4442 // Assigning to a const object has undefined behavior. 4443 if (QT.isConstQualified()) { 4444 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4445 return false; 4446 } 4447 return true; 4448 } 4449 4450 bool failed() { return false; } 4451 bool found(APValue &Subobj, QualType SubobjType) { 4452 // Stash the old value. Also clear Old, so we don't clobber it later 4453 // if we're post-incrementing a complex. 4454 if (Old) { 4455 *Old = Subobj; 4456 Old = nullptr; 4457 } 4458 4459 switch (Subobj.getKind()) { 4460 case APValue::Int: 4461 return found(Subobj.getInt(), SubobjType); 4462 case APValue::Float: 4463 return found(Subobj.getFloat(), SubobjType); 4464 case APValue::ComplexInt: 4465 return found(Subobj.getComplexIntReal(), 4466 SubobjType->castAs<ComplexType>()->getElementType() 4467 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4468 case APValue::ComplexFloat: 4469 return found(Subobj.getComplexFloatReal(), 4470 SubobjType->castAs<ComplexType>()->getElementType() 4471 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4472 case APValue::LValue: 4473 return foundPointer(Subobj, SubobjType); 4474 default: 4475 // FIXME: can this happen? 4476 Info.FFDiag(E); 4477 return false; 4478 } 4479 } 4480 bool found(APSInt &Value, QualType SubobjType) { 4481 if (!checkConst(SubobjType)) 4482 return false; 4483 4484 if (!SubobjType->isIntegerType()) { 4485 // We don't support increment / decrement on integer-cast-to-pointer 4486 // values. 4487 Info.FFDiag(E); 4488 return false; 4489 } 4490 4491 if (Old) *Old = APValue(Value); 4492 4493 // bool arithmetic promotes to int, and the conversion back to bool 4494 // doesn't reduce mod 2^n, so special-case it. 4495 if (SubobjType->isBooleanType()) { 4496 if (AccessKind == AK_Increment) 4497 Value = 1; 4498 else 4499 Value = !Value; 4500 return true; 4501 } 4502 4503 bool WasNegative = Value.isNegative(); 4504 if (AccessKind == AK_Increment) { 4505 ++Value; 4506 4507 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4508 APSInt ActualValue(Value, /*IsUnsigned*/true); 4509 return HandleOverflow(Info, E, ActualValue, SubobjType); 4510 } 4511 } else { 4512 --Value; 4513 4514 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4515 unsigned BitWidth = Value.getBitWidth(); 4516 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4517 ActualValue.setBit(BitWidth); 4518 return HandleOverflow(Info, E, ActualValue, SubobjType); 4519 } 4520 } 4521 return true; 4522 } 4523 bool found(APFloat &Value, QualType SubobjType) { 4524 if (!checkConst(SubobjType)) 4525 return false; 4526 4527 if (Old) *Old = APValue(Value); 4528 4529 APFloat One(Value.getSemantics(), 1); 4530 if (AccessKind == AK_Increment) 4531 Value.add(One, APFloat::rmNearestTiesToEven); 4532 else 4533 Value.subtract(One, APFloat::rmNearestTiesToEven); 4534 return true; 4535 } 4536 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4537 if (!checkConst(SubobjType)) 4538 return false; 4539 4540 QualType PointeeType; 4541 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4542 PointeeType = PT->getPointeeType(); 4543 else { 4544 Info.FFDiag(E); 4545 return false; 4546 } 4547 4548 LValue LVal; 4549 LVal.setFrom(Info.Ctx, Subobj); 4550 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4551 AccessKind == AK_Increment ? 1 : -1)) 4552 return false; 4553 LVal.moveInto(Subobj); 4554 return true; 4555 } 4556 }; 4557 } // end anonymous namespace 4558 4559 /// Perform an increment or decrement on LVal. 4560 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4561 QualType LValType, bool IsIncrement, APValue *Old) { 4562 if (LVal.Designator.Invalid) 4563 return false; 4564 4565 if (!Info.getLangOpts().CPlusPlus14) { 4566 Info.FFDiag(E); 4567 return false; 4568 } 4569 4570 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4571 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4572 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4573 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4574 } 4575 4576 /// Build an lvalue for the object argument of a member function call. 4577 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4578 LValue &This) { 4579 if (Object->getType()->isPointerType() && Object->isRValue()) 4580 return EvaluatePointer(Object, This, Info); 4581 4582 if (Object->isGLValue()) 4583 return EvaluateLValue(Object, This, Info); 4584 4585 if (Object->getType()->isLiteralType(Info.Ctx)) 4586 return EvaluateTemporary(Object, This, Info); 4587 4588 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4589 return false; 4590 } 4591 4592 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4593 /// lvalue referring to the result. 4594 /// 4595 /// \param Info - Information about the ongoing evaluation. 4596 /// \param LV - An lvalue referring to the base of the member pointer. 4597 /// \param RHS - The member pointer expression. 4598 /// \param IncludeMember - Specifies whether the member itself is included in 4599 /// the resulting LValue subobject designator. This is not possible when 4600 /// creating a bound member function. 4601 /// \return The field or method declaration to which the member pointer refers, 4602 /// or 0 if evaluation fails. 4603 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4604 QualType LVType, 4605 LValue &LV, 4606 const Expr *RHS, 4607 bool IncludeMember = true) { 4608 MemberPtr MemPtr; 4609 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4610 return nullptr; 4611 4612 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4613 // member value, the behavior is undefined. 4614 if (!MemPtr.getDecl()) { 4615 // FIXME: Specific diagnostic. 4616 Info.FFDiag(RHS); 4617 return nullptr; 4618 } 4619 4620 if (MemPtr.isDerivedMember()) { 4621 // This is a member of some derived class. Truncate LV appropriately. 4622 // The end of the derived-to-base path for the base object must match the 4623 // derived-to-base path for the member pointer. 4624 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4625 LV.Designator.Entries.size()) { 4626 Info.FFDiag(RHS); 4627 return nullptr; 4628 } 4629 unsigned PathLengthToMember = 4630 LV.Designator.Entries.size() - MemPtr.Path.size(); 4631 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4632 const CXXRecordDecl *LVDecl = getAsBaseClass( 4633 LV.Designator.Entries[PathLengthToMember + I]); 4634 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4635 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4636 Info.FFDiag(RHS); 4637 return nullptr; 4638 } 4639 } 4640 4641 // Truncate the lvalue to the appropriate derived class. 4642 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4643 PathLengthToMember)) 4644 return nullptr; 4645 } else if (!MemPtr.Path.empty()) { 4646 // Extend the LValue path with the member pointer's path. 4647 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4648 MemPtr.Path.size() + IncludeMember); 4649 4650 // Walk down to the appropriate base class. 4651 if (const PointerType *PT = LVType->getAs<PointerType>()) 4652 LVType = PT->getPointeeType(); 4653 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4654 assert(RD && "member pointer access on non-class-type expression"); 4655 // The first class in the path is that of the lvalue. 4656 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4657 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4658 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4659 return nullptr; 4660 RD = Base; 4661 } 4662 // Finally cast to the class containing the member. 4663 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4664 MemPtr.getContainingRecord())) 4665 return nullptr; 4666 } 4667 4668 // Add the member. Note that we cannot build bound member functions here. 4669 if (IncludeMember) { 4670 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4671 if (!HandleLValueMember(Info, RHS, LV, FD)) 4672 return nullptr; 4673 } else if (const IndirectFieldDecl *IFD = 4674 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4675 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4676 return nullptr; 4677 } else { 4678 llvm_unreachable("can't construct reference to bound member function"); 4679 } 4680 } 4681 4682 return MemPtr.getDecl(); 4683 } 4684 4685 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4686 const BinaryOperator *BO, 4687 LValue &LV, 4688 bool IncludeMember = true) { 4689 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4690 4691 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4692 if (Info.noteFailure()) { 4693 MemberPtr MemPtr; 4694 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4695 } 4696 return nullptr; 4697 } 4698 4699 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4700 BO->getRHS(), IncludeMember); 4701 } 4702 4703 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4704 /// the provided lvalue, which currently refers to the base object. 4705 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4706 LValue &Result) { 4707 SubobjectDesignator &D = Result.Designator; 4708 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4709 return false; 4710 4711 QualType TargetQT = E->getType(); 4712 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4713 TargetQT = PT->getPointeeType(); 4714 4715 // Check this cast lands within the final derived-to-base subobject path. 4716 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4717 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4718 << D.MostDerivedType << TargetQT; 4719 return false; 4720 } 4721 4722 // Check the type of the final cast. We don't need to check the path, 4723 // since a cast can only be formed if the path is unique. 4724 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4725 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4726 const CXXRecordDecl *FinalType; 4727 if (NewEntriesSize == D.MostDerivedPathLength) 4728 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4729 else 4730 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4731 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4732 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4733 << D.MostDerivedType << TargetQT; 4734 return false; 4735 } 4736 4737 // Truncate the lvalue to the appropriate derived class. 4738 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4739 } 4740 4741 /// Get the value to use for a default-initialized object of type T. 4742 /// Return false if it encounters something invalid. 4743 static bool getDefaultInitValue(QualType T, APValue &Result) { 4744 bool Success = true; 4745 if (auto *RD = T->getAsCXXRecordDecl()) { 4746 if (RD->isInvalidDecl()) { 4747 Result = APValue(); 4748 return false; 4749 } 4750 if (RD->isUnion()) { 4751 Result = APValue((const FieldDecl *)nullptr); 4752 return true; 4753 } 4754 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4755 std::distance(RD->field_begin(), RD->field_end())); 4756 4757 unsigned Index = 0; 4758 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4759 End = RD->bases_end(); 4760 I != End; ++I, ++Index) 4761 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4762 4763 for (const auto *I : RD->fields()) { 4764 if (I->isUnnamedBitfield()) 4765 continue; 4766 Success &= getDefaultInitValue(I->getType(), 4767 Result.getStructField(I->getFieldIndex())); 4768 } 4769 return Success; 4770 } 4771 4772 if (auto *AT = 4773 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4774 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4775 if (Result.hasArrayFiller()) 4776 Success &= 4777 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4778 4779 return Success; 4780 } 4781 4782 Result = APValue::IndeterminateValue(); 4783 return true; 4784 } 4785 4786 namespace { 4787 enum EvalStmtResult { 4788 /// Evaluation failed. 4789 ESR_Failed, 4790 /// Hit a 'return' statement. 4791 ESR_Returned, 4792 /// Evaluation succeeded. 4793 ESR_Succeeded, 4794 /// Hit a 'continue' statement. 4795 ESR_Continue, 4796 /// Hit a 'break' statement. 4797 ESR_Break, 4798 /// Still scanning for 'case' or 'default' statement. 4799 ESR_CaseNotFound 4800 }; 4801 } 4802 4803 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4804 // We don't need to evaluate the initializer for a static local. 4805 if (!VD->hasLocalStorage()) 4806 return true; 4807 4808 LValue Result; 4809 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4810 ScopeKind::Block, Result); 4811 4812 const Expr *InitE = VD->getInit(); 4813 if (!InitE) { 4814 if (VD->getType()->isDependentType()) 4815 return Info.noteSideEffect(); 4816 return getDefaultInitValue(VD->getType(), Val); 4817 } 4818 if (InitE->isValueDependent()) 4819 return false; 4820 4821 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4822 // Wipe out any partially-computed value, to allow tracking that this 4823 // evaluation failed. 4824 Val = APValue(); 4825 return false; 4826 } 4827 4828 return true; 4829 } 4830 4831 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4832 bool OK = true; 4833 4834 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4835 OK &= EvaluateVarDecl(Info, VD); 4836 4837 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4838 for (auto *BD : DD->bindings()) 4839 if (auto *VD = BD->getHoldingVar()) 4840 OK &= EvaluateDecl(Info, VD); 4841 4842 return OK; 4843 } 4844 4845 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4846 assert(E->isValueDependent()); 4847 if (Info.noteSideEffect()) 4848 return true; 4849 assert(E->containsErrors() && "valid value-dependent expression should never " 4850 "reach invalid code path."); 4851 return false; 4852 } 4853 4854 /// Evaluate a condition (either a variable declaration or an expression). 4855 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4856 const Expr *Cond, bool &Result) { 4857 if (Cond->isValueDependent()) 4858 return false; 4859 FullExpressionRAII Scope(Info); 4860 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4861 return false; 4862 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4863 return false; 4864 return Scope.destroy(); 4865 } 4866 4867 namespace { 4868 /// A location where the result (returned value) of evaluating a 4869 /// statement should be stored. 4870 struct StmtResult { 4871 /// The APValue that should be filled in with the returned value. 4872 APValue &Value; 4873 /// The location containing the result, if any (used to support RVO). 4874 const LValue *Slot; 4875 }; 4876 4877 struct TempVersionRAII { 4878 CallStackFrame &Frame; 4879 4880 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4881 Frame.pushTempVersion(); 4882 } 4883 4884 ~TempVersionRAII() { 4885 Frame.popTempVersion(); 4886 } 4887 }; 4888 4889 } 4890 4891 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4892 const Stmt *S, 4893 const SwitchCase *SC = nullptr); 4894 4895 /// Evaluate the body of a loop, and translate the result as appropriate. 4896 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4897 const Stmt *Body, 4898 const SwitchCase *Case = nullptr) { 4899 BlockScopeRAII Scope(Info); 4900 4901 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4902 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4903 ESR = ESR_Failed; 4904 4905 switch (ESR) { 4906 case ESR_Break: 4907 return ESR_Succeeded; 4908 case ESR_Succeeded: 4909 case ESR_Continue: 4910 return ESR_Continue; 4911 case ESR_Failed: 4912 case ESR_Returned: 4913 case ESR_CaseNotFound: 4914 return ESR; 4915 } 4916 llvm_unreachable("Invalid EvalStmtResult!"); 4917 } 4918 4919 /// Evaluate a switch statement. 4920 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4921 const SwitchStmt *SS) { 4922 BlockScopeRAII Scope(Info); 4923 4924 // Evaluate the switch condition. 4925 APSInt Value; 4926 { 4927 if (const Stmt *Init = SS->getInit()) { 4928 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4929 if (ESR != ESR_Succeeded) { 4930 if (ESR != ESR_Failed && !Scope.destroy()) 4931 ESR = ESR_Failed; 4932 return ESR; 4933 } 4934 } 4935 4936 FullExpressionRAII CondScope(Info); 4937 if (SS->getConditionVariable() && 4938 !EvaluateDecl(Info, SS->getConditionVariable())) 4939 return ESR_Failed; 4940 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4941 return ESR_Failed; 4942 if (!CondScope.destroy()) 4943 return ESR_Failed; 4944 } 4945 4946 // Find the switch case corresponding to the value of the condition. 4947 // FIXME: Cache this lookup. 4948 const SwitchCase *Found = nullptr; 4949 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4950 SC = SC->getNextSwitchCase()) { 4951 if (isa<DefaultStmt>(SC)) { 4952 Found = SC; 4953 continue; 4954 } 4955 4956 const CaseStmt *CS = cast<CaseStmt>(SC); 4957 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4958 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4959 : LHS; 4960 if (LHS <= Value && Value <= RHS) { 4961 Found = SC; 4962 break; 4963 } 4964 } 4965 4966 if (!Found) 4967 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4968 4969 // Search the switch body for the switch case and evaluate it from there. 4970 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4971 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4972 return ESR_Failed; 4973 4974 switch (ESR) { 4975 case ESR_Break: 4976 return ESR_Succeeded; 4977 case ESR_Succeeded: 4978 case ESR_Continue: 4979 case ESR_Failed: 4980 case ESR_Returned: 4981 return ESR; 4982 case ESR_CaseNotFound: 4983 // This can only happen if the switch case is nested within a statement 4984 // expression. We have no intention of supporting that. 4985 Info.FFDiag(Found->getBeginLoc(), 4986 diag::note_constexpr_stmt_expr_unsupported); 4987 return ESR_Failed; 4988 } 4989 llvm_unreachable("Invalid EvalStmtResult!"); 4990 } 4991 4992 // Evaluate a statement. 4993 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4994 const Stmt *S, const SwitchCase *Case) { 4995 if (!Info.nextStep(S)) 4996 return ESR_Failed; 4997 4998 // If we're hunting down a 'case' or 'default' label, recurse through 4999 // substatements until we hit the label. 5000 if (Case) { 5001 switch (S->getStmtClass()) { 5002 case Stmt::CompoundStmtClass: 5003 // FIXME: Precompute which substatement of a compound statement we 5004 // would jump to, and go straight there rather than performing a 5005 // linear scan each time. 5006 case Stmt::LabelStmtClass: 5007 case Stmt::AttributedStmtClass: 5008 case Stmt::DoStmtClass: 5009 break; 5010 5011 case Stmt::CaseStmtClass: 5012 case Stmt::DefaultStmtClass: 5013 if (Case == S) 5014 Case = nullptr; 5015 break; 5016 5017 case Stmt::IfStmtClass: { 5018 // FIXME: Precompute which side of an 'if' we would jump to, and go 5019 // straight there rather than scanning both sides. 5020 const IfStmt *IS = cast<IfStmt>(S); 5021 5022 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5023 // preceded by our switch label. 5024 BlockScopeRAII Scope(Info); 5025 5026 // Step into the init statement in case it brings an (uninitialized) 5027 // variable into scope. 5028 if (const Stmt *Init = IS->getInit()) { 5029 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5030 if (ESR != ESR_CaseNotFound) { 5031 assert(ESR != ESR_Succeeded); 5032 return ESR; 5033 } 5034 } 5035 5036 // Condition variable must be initialized if it exists. 5037 // FIXME: We can skip evaluating the body if there's a condition 5038 // variable, as there can't be any case labels within it. 5039 // (The same is true for 'for' statements.) 5040 5041 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5042 if (ESR == ESR_Failed) 5043 return ESR; 5044 if (ESR != ESR_CaseNotFound) 5045 return Scope.destroy() ? ESR : ESR_Failed; 5046 if (!IS->getElse()) 5047 return ESR_CaseNotFound; 5048 5049 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5050 if (ESR == ESR_Failed) 5051 return ESR; 5052 if (ESR != ESR_CaseNotFound) 5053 return Scope.destroy() ? ESR : ESR_Failed; 5054 return ESR_CaseNotFound; 5055 } 5056 5057 case Stmt::WhileStmtClass: { 5058 EvalStmtResult ESR = 5059 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5060 if (ESR != ESR_Continue) 5061 return ESR; 5062 break; 5063 } 5064 5065 case Stmt::ForStmtClass: { 5066 const ForStmt *FS = cast<ForStmt>(S); 5067 BlockScopeRAII Scope(Info); 5068 5069 // Step into the init statement in case it brings an (uninitialized) 5070 // variable into scope. 5071 if (const Stmt *Init = FS->getInit()) { 5072 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5073 if (ESR != ESR_CaseNotFound) { 5074 assert(ESR != ESR_Succeeded); 5075 return ESR; 5076 } 5077 } 5078 5079 EvalStmtResult ESR = 5080 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5081 if (ESR != ESR_Continue) 5082 return ESR; 5083 if (const auto *Inc = FS->getInc()) { 5084 if (Inc->isValueDependent()) { 5085 if (!EvaluateDependentExpr(Inc, Info)) 5086 return ESR_Failed; 5087 } else { 5088 FullExpressionRAII IncScope(Info); 5089 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5090 return ESR_Failed; 5091 } 5092 } 5093 break; 5094 } 5095 5096 case Stmt::DeclStmtClass: { 5097 // Start the lifetime of any uninitialized variables we encounter. They 5098 // might be used by the selected branch of the switch. 5099 const DeclStmt *DS = cast<DeclStmt>(S); 5100 for (const auto *D : DS->decls()) { 5101 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5102 if (VD->hasLocalStorage() && !VD->getInit()) 5103 if (!EvaluateVarDecl(Info, VD)) 5104 return ESR_Failed; 5105 // FIXME: If the variable has initialization that can't be jumped 5106 // over, bail out of any immediately-surrounding compound-statement 5107 // too. There can't be any case labels here. 5108 } 5109 } 5110 return ESR_CaseNotFound; 5111 } 5112 5113 default: 5114 return ESR_CaseNotFound; 5115 } 5116 } 5117 5118 switch (S->getStmtClass()) { 5119 default: 5120 if (const Expr *E = dyn_cast<Expr>(S)) { 5121 if (E->isValueDependent()) { 5122 if (!EvaluateDependentExpr(E, Info)) 5123 return ESR_Failed; 5124 } else { 5125 // Don't bother evaluating beyond an expression-statement which couldn't 5126 // be evaluated. 5127 // FIXME: Do we need the FullExpressionRAII object here? 5128 // VisitExprWithCleanups should create one when necessary. 5129 FullExpressionRAII Scope(Info); 5130 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5131 return ESR_Failed; 5132 } 5133 return ESR_Succeeded; 5134 } 5135 5136 Info.FFDiag(S->getBeginLoc()); 5137 return ESR_Failed; 5138 5139 case Stmt::NullStmtClass: 5140 return ESR_Succeeded; 5141 5142 case Stmt::DeclStmtClass: { 5143 const DeclStmt *DS = cast<DeclStmt>(S); 5144 for (const auto *D : DS->decls()) { 5145 // Each declaration initialization is its own full-expression. 5146 FullExpressionRAII Scope(Info); 5147 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5148 return ESR_Failed; 5149 if (!Scope.destroy()) 5150 return ESR_Failed; 5151 } 5152 return ESR_Succeeded; 5153 } 5154 5155 case Stmt::ReturnStmtClass: { 5156 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5157 FullExpressionRAII Scope(Info); 5158 if (RetExpr && RetExpr->isValueDependent()) { 5159 EvaluateDependentExpr(RetExpr, Info); 5160 // We know we returned, but we don't know what the value is. 5161 return ESR_Failed; 5162 } 5163 if (RetExpr && 5164 !(Result.Slot 5165 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5166 : Evaluate(Result.Value, Info, RetExpr))) 5167 return ESR_Failed; 5168 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5169 } 5170 5171 case Stmt::CompoundStmtClass: { 5172 BlockScopeRAII Scope(Info); 5173 5174 const CompoundStmt *CS = cast<CompoundStmt>(S); 5175 for (const auto *BI : CS->body()) { 5176 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5177 if (ESR == ESR_Succeeded) 5178 Case = nullptr; 5179 else if (ESR != ESR_CaseNotFound) { 5180 if (ESR != ESR_Failed && !Scope.destroy()) 5181 return ESR_Failed; 5182 return ESR; 5183 } 5184 } 5185 if (Case) 5186 return ESR_CaseNotFound; 5187 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5188 } 5189 5190 case Stmt::IfStmtClass: { 5191 const IfStmt *IS = cast<IfStmt>(S); 5192 5193 // Evaluate the condition, as either a var decl or as an expression. 5194 BlockScopeRAII Scope(Info); 5195 if (const Stmt *Init = IS->getInit()) { 5196 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5197 if (ESR != ESR_Succeeded) { 5198 if (ESR != ESR_Failed && !Scope.destroy()) 5199 return ESR_Failed; 5200 return ESR; 5201 } 5202 } 5203 bool Cond; 5204 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5205 return ESR_Failed; 5206 5207 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5208 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5209 if (ESR != ESR_Succeeded) { 5210 if (ESR != ESR_Failed && !Scope.destroy()) 5211 return ESR_Failed; 5212 return ESR; 5213 } 5214 } 5215 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5216 } 5217 5218 case Stmt::WhileStmtClass: { 5219 const WhileStmt *WS = cast<WhileStmt>(S); 5220 while (true) { 5221 BlockScopeRAII Scope(Info); 5222 bool Continue; 5223 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5224 Continue)) 5225 return ESR_Failed; 5226 if (!Continue) 5227 break; 5228 5229 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5230 if (ESR != ESR_Continue) { 5231 if (ESR != ESR_Failed && !Scope.destroy()) 5232 return ESR_Failed; 5233 return ESR; 5234 } 5235 if (!Scope.destroy()) 5236 return ESR_Failed; 5237 } 5238 return ESR_Succeeded; 5239 } 5240 5241 case Stmt::DoStmtClass: { 5242 const DoStmt *DS = cast<DoStmt>(S); 5243 bool Continue; 5244 do { 5245 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5246 if (ESR != ESR_Continue) 5247 return ESR; 5248 Case = nullptr; 5249 5250 if (DS->getCond()->isValueDependent()) { 5251 EvaluateDependentExpr(DS->getCond(), Info); 5252 // Bailout as we don't know whether to keep going or terminate the loop. 5253 return ESR_Failed; 5254 } 5255 FullExpressionRAII CondScope(Info); 5256 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5257 !CondScope.destroy()) 5258 return ESR_Failed; 5259 } while (Continue); 5260 return ESR_Succeeded; 5261 } 5262 5263 case Stmt::ForStmtClass: { 5264 const ForStmt *FS = cast<ForStmt>(S); 5265 BlockScopeRAII ForScope(Info); 5266 if (FS->getInit()) { 5267 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5268 if (ESR != ESR_Succeeded) { 5269 if (ESR != ESR_Failed && !ForScope.destroy()) 5270 return ESR_Failed; 5271 return ESR; 5272 } 5273 } 5274 while (true) { 5275 BlockScopeRAII IterScope(Info); 5276 bool Continue = true; 5277 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5278 FS->getCond(), Continue)) 5279 return ESR_Failed; 5280 if (!Continue) 5281 break; 5282 5283 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5284 if (ESR != ESR_Continue) { 5285 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5286 return ESR_Failed; 5287 return ESR; 5288 } 5289 5290 if (const auto *Inc = FS->getInc()) { 5291 if (Inc->isValueDependent()) { 5292 if (!EvaluateDependentExpr(Inc, Info)) 5293 return ESR_Failed; 5294 } else { 5295 FullExpressionRAII IncScope(Info); 5296 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5297 return ESR_Failed; 5298 } 5299 } 5300 5301 if (!IterScope.destroy()) 5302 return ESR_Failed; 5303 } 5304 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5305 } 5306 5307 case Stmt::CXXForRangeStmtClass: { 5308 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5309 BlockScopeRAII Scope(Info); 5310 5311 // Evaluate the init-statement if present. 5312 if (FS->getInit()) { 5313 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5314 if (ESR != ESR_Succeeded) { 5315 if (ESR != ESR_Failed && !Scope.destroy()) 5316 return ESR_Failed; 5317 return ESR; 5318 } 5319 } 5320 5321 // Initialize the __range variable. 5322 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5323 if (ESR != ESR_Succeeded) { 5324 if (ESR != ESR_Failed && !Scope.destroy()) 5325 return ESR_Failed; 5326 return ESR; 5327 } 5328 5329 // Create the __begin and __end iterators. 5330 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5331 if (ESR != ESR_Succeeded) { 5332 if (ESR != ESR_Failed && !Scope.destroy()) 5333 return ESR_Failed; 5334 return ESR; 5335 } 5336 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5337 if (ESR != ESR_Succeeded) { 5338 if (ESR != ESR_Failed && !Scope.destroy()) 5339 return ESR_Failed; 5340 return ESR; 5341 } 5342 5343 while (true) { 5344 // Condition: __begin != __end. 5345 { 5346 if (FS->getCond()->isValueDependent()) { 5347 EvaluateDependentExpr(FS->getCond(), Info); 5348 // We don't know whether to keep going or terminate the loop. 5349 return ESR_Failed; 5350 } 5351 bool Continue = true; 5352 FullExpressionRAII CondExpr(Info); 5353 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5354 return ESR_Failed; 5355 if (!Continue) 5356 break; 5357 } 5358 5359 // User's variable declaration, initialized by *__begin. 5360 BlockScopeRAII InnerScope(Info); 5361 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5362 if (ESR != ESR_Succeeded) { 5363 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5364 return ESR_Failed; 5365 return ESR; 5366 } 5367 5368 // Loop body. 5369 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5370 if (ESR != ESR_Continue) { 5371 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5372 return ESR_Failed; 5373 return ESR; 5374 } 5375 if (FS->getInc()->isValueDependent()) { 5376 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5377 return ESR_Failed; 5378 } else { 5379 // Increment: ++__begin 5380 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5381 return ESR_Failed; 5382 } 5383 5384 if (!InnerScope.destroy()) 5385 return ESR_Failed; 5386 } 5387 5388 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5389 } 5390 5391 case Stmt::SwitchStmtClass: 5392 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5393 5394 case Stmt::ContinueStmtClass: 5395 return ESR_Continue; 5396 5397 case Stmt::BreakStmtClass: 5398 return ESR_Break; 5399 5400 case Stmt::LabelStmtClass: 5401 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5402 5403 case Stmt::AttributedStmtClass: 5404 // As a general principle, C++11 attributes can be ignored without 5405 // any semantic impact. 5406 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5407 Case); 5408 5409 case Stmt::CaseStmtClass: 5410 case Stmt::DefaultStmtClass: 5411 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5412 case Stmt::CXXTryStmtClass: 5413 // Evaluate try blocks by evaluating all sub statements. 5414 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5415 } 5416 } 5417 5418 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5419 /// default constructor. If so, we'll fold it whether or not it's marked as 5420 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5421 /// so we need special handling. 5422 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5423 const CXXConstructorDecl *CD, 5424 bool IsValueInitialization) { 5425 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5426 return false; 5427 5428 // Value-initialization does not call a trivial default constructor, so such a 5429 // call is a core constant expression whether or not the constructor is 5430 // constexpr. 5431 if (!CD->isConstexpr() && !IsValueInitialization) { 5432 if (Info.getLangOpts().CPlusPlus11) { 5433 // FIXME: If DiagDecl is an implicitly-declared special member function, 5434 // we should be much more explicit about why it's not constexpr. 5435 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5436 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5437 Info.Note(CD->getLocation(), diag::note_declared_at); 5438 } else { 5439 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5440 } 5441 } 5442 return true; 5443 } 5444 5445 /// CheckConstexprFunction - Check that a function can be called in a constant 5446 /// expression. 5447 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5448 const FunctionDecl *Declaration, 5449 const FunctionDecl *Definition, 5450 const Stmt *Body) { 5451 // Potential constant expressions can contain calls to declared, but not yet 5452 // defined, constexpr functions. 5453 if (Info.checkingPotentialConstantExpression() && !Definition && 5454 Declaration->isConstexpr()) 5455 return false; 5456 5457 // Bail out if the function declaration itself is invalid. We will 5458 // have produced a relevant diagnostic while parsing it, so just 5459 // note the problematic sub-expression. 5460 if (Declaration->isInvalidDecl()) { 5461 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5462 return false; 5463 } 5464 5465 // DR1872: An instantiated virtual constexpr function can't be called in a 5466 // constant expression (prior to C++20). We can still constant-fold such a 5467 // call. 5468 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5469 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5470 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5471 5472 if (Definition && Definition->isInvalidDecl()) { 5473 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5474 return false; 5475 } 5476 5477 // Can we evaluate this function call? 5478 if (Definition && Definition->isConstexpr() && Body) 5479 return true; 5480 5481 if (Info.getLangOpts().CPlusPlus11) { 5482 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5483 5484 // If this function is not constexpr because it is an inherited 5485 // non-constexpr constructor, diagnose that directly. 5486 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5487 if (CD && CD->isInheritingConstructor()) { 5488 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5489 if (!Inherited->isConstexpr()) 5490 DiagDecl = CD = Inherited; 5491 } 5492 5493 // FIXME: If DiagDecl is an implicitly-declared special member function 5494 // or an inheriting constructor, we should be much more explicit about why 5495 // it's not constexpr. 5496 if (CD && CD->isInheritingConstructor()) 5497 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5498 << CD->getInheritedConstructor().getConstructor()->getParent(); 5499 else 5500 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5501 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5502 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5503 } else { 5504 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5505 } 5506 return false; 5507 } 5508 5509 namespace { 5510 struct CheckDynamicTypeHandler { 5511 AccessKinds AccessKind; 5512 typedef bool result_type; 5513 bool failed() { return false; } 5514 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5515 bool found(APSInt &Value, QualType SubobjType) { return true; } 5516 bool found(APFloat &Value, QualType SubobjType) { return true; } 5517 }; 5518 } // end anonymous namespace 5519 5520 /// Check that we can access the notional vptr of an object / determine its 5521 /// dynamic type. 5522 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5523 AccessKinds AK, bool Polymorphic) { 5524 if (This.Designator.Invalid) 5525 return false; 5526 5527 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5528 5529 if (!Obj) 5530 return false; 5531 5532 if (!Obj.Value) { 5533 // The object is not usable in constant expressions, so we can't inspect 5534 // its value to see if it's in-lifetime or what the active union members 5535 // are. We can still check for a one-past-the-end lvalue. 5536 if (This.Designator.isOnePastTheEnd() || 5537 This.Designator.isMostDerivedAnUnsizedArray()) { 5538 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5539 ? diag::note_constexpr_access_past_end 5540 : diag::note_constexpr_access_unsized_array) 5541 << AK; 5542 return false; 5543 } else if (Polymorphic) { 5544 // Conservatively refuse to perform a polymorphic operation if we would 5545 // not be able to read a notional 'vptr' value. 5546 APValue Val; 5547 This.moveInto(Val); 5548 QualType StarThisType = 5549 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5550 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5551 << AK << Val.getAsString(Info.Ctx, StarThisType); 5552 return false; 5553 } 5554 return true; 5555 } 5556 5557 CheckDynamicTypeHandler Handler{AK}; 5558 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5559 } 5560 5561 /// Check that the pointee of the 'this' pointer in a member function call is 5562 /// either within its lifetime or in its period of construction or destruction. 5563 static bool 5564 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5565 const LValue &This, 5566 const CXXMethodDecl *NamedMember) { 5567 return checkDynamicType( 5568 Info, E, This, 5569 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5570 } 5571 5572 struct DynamicType { 5573 /// The dynamic class type of the object. 5574 const CXXRecordDecl *Type; 5575 /// The corresponding path length in the lvalue. 5576 unsigned PathLength; 5577 }; 5578 5579 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5580 unsigned PathLength) { 5581 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5582 Designator.Entries.size() && "invalid path length"); 5583 return (PathLength == Designator.MostDerivedPathLength) 5584 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5585 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5586 } 5587 5588 /// Determine the dynamic type of an object. 5589 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5590 LValue &This, AccessKinds AK) { 5591 // If we don't have an lvalue denoting an object of class type, there is no 5592 // meaningful dynamic type. (We consider objects of non-class type to have no 5593 // dynamic type.) 5594 if (!checkDynamicType(Info, E, This, AK, true)) 5595 return None; 5596 5597 // Refuse to compute a dynamic type in the presence of virtual bases. This 5598 // shouldn't happen other than in constant-folding situations, since literal 5599 // types can't have virtual bases. 5600 // 5601 // Note that consumers of DynamicType assume that the type has no virtual 5602 // bases, and will need modifications if this restriction is relaxed. 5603 const CXXRecordDecl *Class = 5604 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5605 if (!Class || Class->getNumVBases()) { 5606 Info.FFDiag(E); 5607 return None; 5608 } 5609 5610 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5611 // binary search here instead. But the overwhelmingly common case is that 5612 // we're not in the middle of a constructor, so it probably doesn't matter 5613 // in practice. 5614 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5615 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5616 PathLength <= Path.size(); ++PathLength) { 5617 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5618 Path.slice(0, PathLength))) { 5619 case ConstructionPhase::Bases: 5620 case ConstructionPhase::DestroyingBases: 5621 // We're constructing or destroying a base class. This is not the dynamic 5622 // type. 5623 break; 5624 5625 case ConstructionPhase::None: 5626 case ConstructionPhase::AfterBases: 5627 case ConstructionPhase::AfterFields: 5628 case ConstructionPhase::Destroying: 5629 // We've finished constructing the base classes and not yet started 5630 // destroying them again, so this is the dynamic type. 5631 return DynamicType{getBaseClassType(This.Designator, PathLength), 5632 PathLength}; 5633 } 5634 } 5635 5636 // CWG issue 1517: we're constructing a base class of the object described by 5637 // 'This', so that object has not yet begun its period of construction and 5638 // any polymorphic operation on it results in undefined behavior. 5639 Info.FFDiag(E); 5640 return None; 5641 } 5642 5643 /// Perform virtual dispatch. 5644 static const CXXMethodDecl *HandleVirtualDispatch( 5645 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5646 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5647 Optional<DynamicType> DynType = ComputeDynamicType( 5648 Info, E, This, 5649 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5650 if (!DynType) 5651 return nullptr; 5652 5653 // Find the final overrider. It must be declared in one of the classes on the 5654 // path from the dynamic type to the static type. 5655 // FIXME: If we ever allow literal types to have virtual base classes, that 5656 // won't be true. 5657 const CXXMethodDecl *Callee = Found; 5658 unsigned PathLength = DynType->PathLength; 5659 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5660 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5661 const CXXMethodDecl *Overrider = 5662 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5663 if (Overrider) { 5664 Callee = Overrider; 5665 break; 5666 } 5667 } 5668 5669 // C++2a [class.abstract]p6: 5670 // the effect of making a virtual call to a pure virtual function [...] is 5671 // undefined 5672 if (Callee->isPure()) { 5673 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5674 Info.Note(Callee->getLocation(), diag::note_declared_at); 5675 return nullptr; 5676 } 5677 5678 // If necessary, walk the rest of the path to determine the sequence of 5679 // covariant adjustment steps to apply. 5680 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5681 Found->getReturnType())) { 5682 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5683 for (unsigned CovariantPathLength = PathLength + 1; 5684 CovariantPathLength != This.Designator.Entries.size(); 5685 ++CovariantPathLength) { 5686 const CXXRecordDecl *NextClass = 5687 getBaseClassType(This.Designator, CovariantPathLength); 5688 const CXXMethodDecl *Next = 5689 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5690 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5691 Next->getReturnType(), CovariantAdjustmentPath.back())) 5692 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5693 } 5694 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5695 CovariantAdjustmentPath.back())) 5696 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5697 } 5698 5699 // Perform 'this' adjustment. 5700 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5701 return nullptr; 5702 5703 return Callee; 5704 } 5705 5706 /// Perform the adjustment from a value returned by a virtual function to 5707 /// a value of the statically expected type, which may be a pointer or 5708 /// reference to a base class of the returned type. 5709 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5710 APValue &Result, 5711 ArrayRef<QualType> Path) { 5712 assert(Result.isLValue() && 5713 "unexpected kind of APValue for covariant return"); 5714 if (Result.isNullPointer()) 5715 return true; 5716 5717 LValue LVal; 5718 LVal.setFrom(Info.Ctx, Result); 5719 5720 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5721 for (unsigned I = 1; I != Path.size(); ++I) { 5722 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5723 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5724 if (OldClass != NewClass && 5725 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5726 return false; 5727 OldClass = NewClass; 5728 } 5729 5730 LVal.moveInto(Result); 5731 return true; 5732 } 5733 5734 /// Determine whether \p Base, which is known to be a direct base class of 5735 /// \p Derived, is a public base class. 5736 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5737 const CXXRecordDecl *Base) { 5738 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5739 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5740 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5741 return BaseSpec.getAccessSpecifier() == AS_public; 5742 } 5743 llvm_unreachable("Base is not a direct base of Derived"); 5744 } 5745 5746 /// Apply the given dynamic cast operation on the provided lvalue. 5747 /// 5748 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5749 /// to find a suitable target subobject. 5750 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5751 LValue &Ptr) { 5752 // We can't do anything with a non-symbolic pointer value. 5753 SubobjectDesignator &D = Ptr.Designator; 5754 if (D.Invalid) 5755 return false; 5756 5757 // C++ [expr.dynamic.cast]p6: 5758 // If v is a null pointer value, the result is a null pointer value. 5759 if (Ptr.isNullPointer() && !E->isGLValue()) 5760 return true; 5761 5762 // For all the other cases, we need the pointer to point to an object within 5763 // its lifetime / period of construction / destruction, and we need to know 5764 // its dynamic type. 5765 Optional<DynamicType> DynType = 5766 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5767 if (!DynType) 5768 return false; 5769 5770 // C++ [expr.dynamic.cast]p7: 5771 // If T is "pointer to cv void", then the result is a pointer to the most 5772 // derived object 5773 if (E->getType()->isVoidPointerType()) 5774 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5775 5776 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5777 assert(C && "dynamic_cast target is not void pointer nor class"); 5778 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5779 5780 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5781 // C++ [expr.dynamic.cast]p9: 5782 if (!E->isGLValue()) { 5783 // The value of a failed cast to pointer type is the null pointer value 5784 // of the required result type. 5785 Ptr.setNull(Info.Ctx, E->getType()); 5786 return true; 5787 } 5788 5789 // A failed cast to reference type throws [...] std::bad_cast. 5790 unsigned DiagKind; 5791 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5792 DynType->Type->isDerivedFrom(C))) 5793 DiagKind = 0; 5794 else if (!Paths || Paths->begin() == Paths->end()) 5795 DiagKind = 1; 5796 else if (Paths->isAmbiguous(CQT)) 5797 DiagKind = 2; 5798 else { 5799 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5800 DiagKind = 3; 5801 } 5802 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5803 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5804 << Info.Ctx.getRecordType(DynType->Type) 5805 << E->getType().getUnqualifiedType(); 5806 return false; 5807 }; 5808 5809 // Runtime check, phase 1: 5810 // Walk from the base subobject towards the derived object looking for the 5811 // target type. 5812 for (int PathLength = Ptr.Designator.Entries.size(); 5813 PathLength >= (int)DynType->PathLength; --PathLength) { 5814 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5815 if (declaresSameEntity(Class, C)) 5816 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5817 // We can only walk across public inheritance edges. 5818 if (PathLength > (int)DynType->PathLength && 5819 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5820 Class)) 5821 return RuntimeCheckFailed(nullptr); 5822 } 5823 5824 // Runtime check, phase 2: 5825 // Search the dynamic type for an unambiguous public base of type C. 5826 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5827 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5828 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5829 Paths.front().Access == AS_public) { 5830 // Downcast to the dynamic type... 5831 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5832 return false; 5833 // ... then upcast to the chosen base class subobject. 5834 for (CXXBasePathElement &Elem : Paths.front()) 5835 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5836 return false; 5837 return true; 5838 } 5839 5840 // Otherwise, the runtime check fails. 5841 return RuntimeCheckFailed(&Paths); 5842 } 5843 5844 namespace { 5845 struct StartLifetimeOfUnionMemberHandler { 5846 EvalInfo &Info; 5847 const Expr *LHSExpr; 5848 const FieldDecl *Field; 5849 bool DuringInit; 5850 bool Failed = false; 5851 static const AccessKinds AccessKind = AK_Assign; 5852 5853 typedef bool result_type; 5854 bool failed() { return Failed; } 5855 bool found(APValue &Subobj, QualType SubobjType) { 5856 // We are supposed to perform no initialization but begin the lifetime of 5857 // the object. We interpret that as meaning to do what default 5858 // initialization of the object would do if all constructors involved were 5859 // trivial: 5860 // * All base, non-variant member, and array element subobjects' lifetimes 5861 // begin 5862 // * No variant members' lifetimes begin 5863 // * All scalar subobjects whose lifetimes begin have indeterminate values 5864 assert(SubobjType->isUnionType()); 5865 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5866 // This union member is already active. If it's also in-lifetime, there's 5867 // nothing to do. 5868 if (Subobj.getUnionValue().hasValue()) 5869 return true; 5870 } else if (DuringInit) { 5871 // We're currently in the process of initializing a different union 5872 // member. If we carried on, that initialization would attempt to 5873 // store to an inactive union member, resulting in undefined behavior. 5874 Info.FFDiag(LHSExpr, 5875 diag::note_constexpr_union_member_change_during_init); 5876 return false; 5877 } 5878 APValue Result; 5879 Failed = !getDefaultInitValue(Field->getType(), Result); 5880 Subobj.setUnion(Field, Result); 5881 return true; 5882 } 5883 bool found(APSInt &Value, QualType SubobjType) { 5884 llvm_unreachable("wrong value kind for union object"); 5885 } 5886 bool found(APFloat &Value, QualType SubobjType) { 5887 llvm_unreachable("wrong value kind for union object"); 5888 } 5889 }; 5890 } // end anonymous namespace 5891 5892 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5893 5894 /// Handle a builtin simple-assignment or a call to a trivial assignment 5895 /// operator whose left-hand side might involve a union member access. If it 5896 /// does, implicitly start the lifetime of any accessed union elements per 5897 /// C++20 [class.union]5. 5898 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5899 const LValue &LHS) { 5900 if (LHS.InvalidBase || LHS.Designator.Invalid) 5901 return false; 5902 5903 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5904 // C++ [class.union]p5: 5905 // define the set S(E) of subexpressions of E as follows: 5906 unsigned PathLength = LHS.Designator.Entries.size(); 5907 for (const Expr *E = LHSExpr; E != nullptr;) { 5908 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5909 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5910 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5911 // Note that we can't implicitly start the lifetime of a reference, 5912 // so we don't need to proceed any further if we reach one. 5913 if (!FD || FD->getType()->isReferenceType()) 5914 break; 5915 5916 // ... and also contains A.B if B names a union member ... 5917 if (FD->getParent()->isUnion()) { 5918 // ... of a non-class, non-array type, or of a class type with a 5919 // trivial default constructor that is not deleted, or an array of 5920 // such types. 5921 auto *RD = 5922 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5923 if (!RD || RD->hasTrivialDefaultConstructor()) 5924 UnionPathLengths.push_back({PathLength - 1, FD}); 5925 } 5926 5927 E = ME->getBase(); 5928 --PathLength; 5929 assert(declaresSameEntity(FD, 5930 LHS.Designator.Entries[PathLength] 5931 .getAsBaseOrMember().getPointer())); 5932 5933 // -- If E is of the form A[B] and is interpreted as a built-in array 5934 // subscripting operator, S(E) is [S(the array operand, if any)]. 5935 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5936 // Step over an ArrayToPointerDecay implicit cast. 5937 auto *Base = ASE->getBase()->IgnoreImplicit(); 5938 if (!Base->getType()->isArrayType()) 5939 break; 5940 5941 E = Base; 5942 --PathLength; 5943 5944 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5945 // Step over a derived-to-base conversion. 5946 E = ICE->getSubExpr(); 5947 if (ICE->getCastKind() == CK_NoOp) 5948 continue; 5949 if (ICE->getCastKind() != CK_DerivedToBase && 5950 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5951 break; 5952 // Walk path backwards as we walk up from the base to the derived class. 5953 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5954 --PathLength; 5955 (void)Elt; 5956 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5957 LHS.Designator.Entries[PathLength] 5958 .getAsBaseOrMember().getPointer())); 5959 } 5960 5961 // -- Otherwise, S(E) is empty. 5962 } else { 5963 break; 5964 } 5965 } 5966 5967 // Common case: no unions' lifetimes are started. 5968 if (UnionPathLengths.empty()) 5969 return true; 5970 5971 // if modification of X [would access an inactive union member], an object 5972 // of the type of X is implicitly created 5973 CompleteObject Obj = 5974 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5975 if (!Obj) 5976 return false; 5977 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5978 llvm::reverse(UnionPathLengths)) { 5979 // Form a designator for the union object. 5980 SubobjectDesignator D = LHS.Designator; 5981 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5982 5983 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5984 ConstructionPhase::AfterBases; 5985 StartLifetimeOfUnionMemberHandler StartLifetime{ 5986 Info, LHSExpr, LengthAndField.second, DuringInit}; 5987 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5988 return false; 5989 } 5990 5991 return true; 5992 } 5993 5994 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5995 CallRef Call, EvalInfo &Info, 5996 bool NonNull = false) { 5997 LValue LV; 5998 // Create the parameter slot and register its destruction. For a vararg 5999 // argument, create a temporary. 6000 // FIXME: For calling conventions that destroy parameters in the callee, 6001 // should we consider performing destruction when the function returns 6002 // instead? 6003 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6004 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6005 ScopeKind::Call, LV); 6006 if (!EvaluateInPlace(V, Info, LV, Arg)) 6007 return false; 6008 6009 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6010 // undefined behavior, so is non-constant. 6011 if (NonNull && V.isLValue() && V.isNullPointer()) { 6012 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6013 return false; 6014 } 6015 6016 return true; 6017 } 6018 6019 /// Evaluate the arguments to a function call. 6020 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6021 EvalInfo &Info, const FunctionDecl *Callee, 6022 bool RightToLeft = false) { 6023 bool Success = true; 6024 llvm::SmallBitVector ForbiddenNullArgs; 6025 if (Callee->hasAttr<NonNullAttr>()) { 6026 ForbiddenNullArgs.resize(Args.size()); 6027 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6028 if (!Attr->args_size()) { 6029 ForbiddenNullArgs.set(); 6030 break; 6031 } else 6032 for (auto Idx : Attr->args()) { 6033 unsigned ASTIdx = Idx.getASTIndex(); 6034 if (ASTIdx >= Args.size()) 6035 continue; 6036 ForbiddenNullArgs[ASTIdx] = 1; 6037 } 6038 } 6039 } 6040 for (unsigned I = 0; I < Args.size(); I++) { 6041 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6042 const ParmVarDecl *PVD = 6043 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6044 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6045 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6046 // If we're checking for a potential constant expression, evaluate all 6047 // initializers even if some of them fail. 6048 if (!Info.noteFailure()) 6049 return false; 6050 Success = false; 6051 } 6052 } 6053 return Success; 6054 } 6055 6056 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6057 /// constructor or assignment operator. 6058 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6059 const Expr *E, APValue &Result, 6060 bool CopyObjectRepresentation) { 6061 // Find the reference argument. 6062 CallStackFrame *Frame = Info.CurrentCall; 6063 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6064 if (!RefValue) { 6065 Info.FFDiag(E); 6066 return false; 6067 } 6068 6069 // Copy out the contents of the RHS object. 6070 LValue RefLValue; 6071 RefLValue.setFrom(Info.Ctx, *RefValue); 6072 return handleLValueToRValueConversion( 6073 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6074 CopyObjectRepresentation); 6075 } 6076 6077 /// Evaluate a function call. 6078 static bool HandleFunctionCall(SourceLocation CallLoc, 6079 const FunctionDecl *Callee, const LValue *This, 6080 ArrayRef<const Expr *> Args, CallRef Call, 6081 const Stmt *Body, EvalInfo &Info, 6082 APValue &Result, const LValue *ResultSlot) { 6083 if (!Info.CheckCallLimit(CallLoc)) 6084 return false; 6085 6086 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6087 6088 // For a trivial copy or move assignment, perform an APValue copy. This is 6089 // essential for unions, where the operations performed by the assignment 6090 // operator cannot be represented as statements. 6091 // 6092 // Skip this for non-union classes with no fields; in that case, the defaulted 6093 // copy/move does not actually read the object. 6094 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6095 if (MD && MD->isDefaulted() && 6096 (MD->getParent()->isUnion() || 6097 (MD->isTrivial() && 6098 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6099 assert(This && 6100 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6101 APValue RHSValue; 6102 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6103 MD->getParent()->isUnion())) 6104 return false; 6105 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6106 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6107 return false; 6108 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6109 RHSValue)) 6110 return false; 6111 This->moveInto(Result); 6112 return true; 6113 } else if (MD && isLambdaCallOperator(MD)) { 6114 // We're in a lambda; determine the lambda capture field maps unless we're 6115 // just constexpr checking a lambda's call operator. constexpr checking is 6116 // done before the captures have been added to the closure object (unless 6117 // we're inferring constexpr-ness), so we don't have access to them in this 6118 // case. But since we don't need the captures to constexpr check, we can 6119 // just ignore them. 6120 if (!Info.checkingPotentialConstantExpression()) 6121 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6122 Frame.LambdaThisCaptureField); 6123 } 6124 6125 StmtResult Ret = {Result, ResultSlot}; 6126 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6127 if (ESR == ESR_Succeeded) { 6128 if (Callee->getReturnType()->isVoidType()) 6129 return true; 6130 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6131 } 6132 return ESR == ESR_Returned; 6133 } 6134 6135 /// Evaluate a constructor call. 6136 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6137 CallRef Call, 6138 const CXXConstructorDecl *Definition, 6139 EvalInfo &Info, APValue &Result) { 6140 SourceLocation CallLoc = E->getExprLoc(); 6141 if (!Info.CheckCallLimit(CallLoc)) 6142 return false; 6143 6144 const CXXRecordDecl *RD = Definition->getParent(); 6145 if (RD->getNumVBases()) { 6146 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6147 return false; 6148 } 6149 6150 EvalInfo::EvaluatingConstructorRAII EvalObj( 6151 Info, 6152 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6153 RD->getNumBases()); 6154 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6155 6156 // FIXME: Creating an APValue just to hold a nonexistent return value is 6157 // wasteful. 6158 APValue RetVal; 6159 StmtResult Ret = {RetVal, nullptr}; 6160 6161 // If it's a delegating constructor, delegate. 6162 if (Definition->isDelegatingConstructor()) { 6163 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6164 if ((*I)->getInit()->isValueDependent()) { 6165 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6166 return false; 6167 } else { 6168 FullExpressionRAII InitScope(Info); 6169 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6170 !InitScope.destroy()) 6171 return false; 6172 } 6173 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6174 } 6175 6176 // For a trivial copy or move constructor, perform an APValue copy. This is 6177 // essential for unions (or classes with anonymous union members), where the 6178 // operations performed by the constructor cannot be represented by 6179 // ctor-initializers. 6180 // 6181 // Skip this for empty non-union classes; we should not perform an 6182 // lvalue-to-rvalue conversion on them because their copy constructor does not 6183 // actually read them. 6184 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6185 (Definition->getParent()->isUnion() || 6186 (Definition->isTrivial() && 6187 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6188 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6189 Definition->getParent()->isUnion()); 6190 } 6191 6192 // Reserve space for the struct members. 6193 if (!Result.hasValue()) { 6194 if (!RD->isUnion()) 6195 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6196 std::distance(RD->field_begin(), RD->field_end())); 6197 else 6198 // A union starts with no active member. 6199 Result = APValue((const FieldDecl*)nullptr); 6200 } 6201 6202 if (RD->isInvalidDecl()) return false; 6203 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6204 6205 // A scope for temporaries lifetime-extended by reference members. 6206 BlockScopeRAII LifetimeExtendedScope(Info); 6207 6208 bool Success = true; 6209 unsigned BasesSeen = 0; 6210 #ifndef NDEBUG 6211 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6212 #endif 6213 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6214 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6215 // We might be initializing the same field again if this is an indirect 6216 // field initialization. 6217 if (FieldIt == RD->field_end() || 6218 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6219 assert(Indirect && "fields out of order?"); 6220 return; 6221 } 6222 6223 // Default-initialize any fields with no explicit initializer. 6224 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6225 assert(FieldIt != RD->field_end() && "missing field?"); 6226 if (!FieldIt->isUnnamedBitfield()) 6227 Success &= getDefaultInitValue( 6228 FieldIt->getType(), 6229 Result.getStructField(FieldIt->getFieldIndex())); 6230 } 6231 ++FieldIt; 6232 }; 6233 for (const auto *I : Definition->inits()) { 6234 LValue Subobject = This; 6235 LValue SubobjectParent = This; 6236 APValue *Value = &Result; 6237 6238 // Determine the subobject to initialize. 6239 FieldDecl *FD = nullptr; 6240 if (I->isBaseInitializer()) { 6241 QualType BaseType(I->getBaseClass(), 0); 6242 #ifndef NDEBUG 6243 // Non-virtual base classes are initialized in the order in the class 6244 // definition. We have already checked for virtual base classes. 6245 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6246 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6247 "base class initializers not in expected order"); 6248 ++BaseIt; 6249 #endif 6250 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6251 BaseType->getAsCXXRecordDecl(), &Layout)) 6252 return false; 6253 Value = &Result.getStructBase(BasesSeen++); 6254 } else if ((FD = I->getMember())) { 6255 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6256 return false; 6257 if (RD->isUnion()) { 6258 Result = APValue(FD); 6259 Value = &Result.getUnionValue(); 6260 } else { 6261 SkipToField(FD, false); 6262 Value = &Result.getStructField(FD->getFieldIndex()); 6263 } 6264 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6265 // Walk the indirect field decl's chain to find the object to initialize, 6266 // and make sure we've initialized every step along it. 6267 auto IndirectFieldChain = IFD->chain(); 6268 for (auto *C : IndirectFieldChain) { 6269 FD = cast<FieldDecl>(C); 6270 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6271 // Switch the union field if it differs. This happens if we had 6272 // preceding zero-initialization, and we're now initializing a union 6273 // subobject other than the first. 6274 // FIXME: In this case, the values of the other subobjects are 6275 // specified, since zero-initialization sets all padding bits to zero. 6276 if (!Value->hasValue() || 6277 (Value->isUnion() && Value->getUnionField() != FD)) { 6278 if (CD->isUnion()) 6279 *Value = APValue(FD); 6280 else 6281 // FIXME: This immediately starts the lifetime of all members of 6282 // an anonymous struct. It would be preferable to strictly start 6283 // member lifetime in initialization order. 6284 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6285 } 6286 // Store Subobject as its parent before updating it for the last element 6287 // in the chain. 6288 if (C == IndirectFieldChain.back()) 6289 SubobjectParent = Subobject; 6290 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6291 return false; 6292 if (CD->isUnion()) 6293 Value = &Value->getUnionValue(); 6294 else { 6295 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6296 SkipToField(FD, true); 6297 Value = &Value->getStructField(FD->getFieldIndex()); 6298 } 6299 } 6300 } else { 6301 llvm_unreachable("unknown base initializer kind"); 6302 } 6303 6304 // Need to override This for implicit field initializers as in this case 6305 // This refers to innermost anonymous struct/union containing initializer, 6306 // not to currently constructed class. 6307 const Expr *Init = I->getInit(); 6308 if (Init->isValueDependent()) { 6309 if (!EvaluateDependentExpr(Init, Info)) 6310 return false; 6311 } else { 6312 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6313 isa<CXXDefaultInitExpr>(Init)); 6314 FullExpressionRAII InitScope(Info); 6315 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6316 (FD && FD->isBitField() && 6317 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6318 // If we're checking for a potential constant expression, evaluate all 6319 // initializers even if some of them fail. 6320 if (!Info.noteFailure()) 6321 return false; 6322 Success = false; 6323 } 6324 } 6325 6326 // This is the point at which the dynamic type of the object becomes this 6327 // class type. 6328 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6329 EvalObj.finishedConstructingBases(); 6330 } 6331 6332 // Default-initialize any remaining fields. 6333 if (!RD->isUnion()) { 6334 for (; FieldIt != RD->field_end(); ++FieldIt) { 6335 if (!FieldIt->isUnnamedBitfield()) 6336 Success &= getDefaultInitValue( 6337 FieldIt->getType(), 6338 Result.getStructField(FieldIt->getFieldIndex())); 6339 } 6340 } 6341 6342 EvalObj.finishedConstructingFields(); 6343 6344 return Success && 6345 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6346 LifetimeExtendedScope.destroy(); 6347 } 6348 6349 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6350 ArrayRef<const Expr*> Args, 6351 const CXXConstructorDecl *Definition, 6352 EvalInfo &Info, APValue &Result) { 6353 CallScopeRAII CallScope(Info); 6354 CallRef Call = Info.CurrentCall->createCall(Definition); 6355 if (!EvaluateArgs(Args, Call, Info, Definition)) 6356 return false; 6357 6358 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6359 CallScope.destroy(); 6360 } 6361 6362 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6363 const LValue &This, APValue &Value, 6364 QualType T) { 6365 // Objects can only be destroyed while they're within their lifetimes. 6366 // FIXME: We have no representation for whether an object of type nullptr_t 6367 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6368 // as indeterminate instead? 6369 if (Value.isAbsent() && !T->isNullPtrType()) { 6370 APValue Printable; 6371 This.moveInto(Printable); 6372 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6373 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6374 return false; 6375 } 6376 6377 // Invent an expression for location purposes. 6378 // FIXME: We shouldn't need to do this. 6379 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6380 6381 // For arrays, destroy elements right-to-left. 6382 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6383 uint64_t Size = CAT->getSize().getZExtValue(); 6384 QualType ElemT = CAT->getElementType(); 6385 6386 LValue ElemLV = This; 6387 ElemLV.addArray(Info, &LocE, CAT); 6388 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6389 return false; 6390 6391 // Ensure that we have actual array elements available to destroy; the 6392 // destructors might mutate the value, so we can't run them on the array 6393 // filler. 6394 if (Size && Size > Value.getArrayInitializedElts()) 6395 expandArray(Value, Value.getArraySize() - 1); 6396 6397 for (; Size != 0; --Size) { 6398 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6399 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6400 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6401 return false; 6402 } 6403 6404 // End the lifetime of this array now. 6405 Value = APValue(); 6406 return true; 6407 } 6408 6409 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6410 if (!RD) { 6411 if (T.isDestructedType()) { 6412 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6413 return false; 6414 } 6415 6416 Value = APValue(); 6417 return true; 6418 } 6419 6420 if (RD->getNumVBases()) { 6421 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6422 return false; 6423 } 6424 6425 const CXXDestructorDecl *DD = RD->getDestructor(); 6426 if (!DD && !RD->hasTrivialDestructor()) { 6427 Info.FFDiag(CallLoc); 6428 return false; 6429 } 6430 6431 if (!DD || DD->isTrivial() || 6432 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6433 // A trivial destructor just ends the lifetime of the object. Check for 6434 // this case before checking for a body, because we might not bother 6435 // building a body for a trivial destructor. Note that it doesn't matter 6436 // whether the destructor is constexpr in this case; all trivial 6437 // destructors are constexpr. 6438 // 6439 // If an anonymous union would be destroyed, some enclosing destructor must 6440 // have been explicitly defined, and the anonymous union destruction should 6441 // have no effect. 6442 Value = APValue(); 6443 return true; 6444 } 6445 6446 if (!Info.CheckCallLimit(CallLoc)) 6447 return false; 6448 6449 const FunctionDecl *Definition = nullptr; 6450 const Stmt *Body = DD->getBody(Definition); 6451 6452 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6453 return false; 6454 6455 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6456 6457 // We're now in the period of destruction of this object. 6458 unsigned BasesLeft = RD->getNumBases(); 6459 EvalInfo::EvaluatingDestructorRAII EvalObj( 6460 Info, 6461 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6462 if (!EvalObj.DidInsert) { 6463 // C++2a [class.dtor]p19: 6464 // the behavior is undefined if the destructor is invoked for an object 6465 // whose lifetime has ended 6466 // (Note that formally the lifetime ends when the period of destruction 6467 // begins, even though certain uses of the object remain valid until the 6468 // period of destruction ends.) 6469 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6470 return false; 6471 } 6472 6473 // FIXME: Creating an APValue just to hold a nonexistent return value is 6474 // wasteful. 6475 APValue RetVal; 6476 StmtResult Ret = {RetVal, nullptr}; 6477 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6478 return false; 6479 6480 // A union destructor does not implicitly destroy its members. 6481 if (RD->isUnion()) 6482 return true; 6483 6484 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6485 6486 // We don't have a good way to iterate fields in reverse, so collect all the 6487 // fields first and then walk them backwards. 6488 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6489 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6490 if (FD->isUnnamedBitfield()) 6491 continue; 6492 6493 LValue Subobject = This; 6494 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6495 return false; 6496 6497 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6498 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6499 FD->getType())) 6500 return false; 6501 } 6502 6503 if (BasesLeft != 0) 6504 EvalObj.startedDestroyingBases(); 6505 6506 // Destroy base classes in reverse order. 6507 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6508 --BasesLeft; 6509 6510 QualType BaseType = Base.getType(); 6511 LValue Subobject = This; 6512 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6513 BaseType->getAsCXXRecordDecl(), &Layout)) 6514 return false; 6515 6516 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6517 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6518 BaseType)) 6519 return false; 6520 } 6521 assert(BasesLeft == 0 && "NumBases was wrong?"); 6522 6523 // The period of destruction ends now. The object is gone. 6524 Value = APValue(); 6525 return true; 6526 } 6527 6528 namespace { 6529 struct DestroyObjectHandler { 6530 EvalInfo &Info; 6531 const Expr *E; 6532 const LValue &This; 6533 const AccessKinds AccessKind; 6534 6535 typedef bool result_type; 6536 bool failed() { return false; } 6537 bool found(APValue &Subobj, QualType SubobjType) { 6538 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6539 SubobjType); 6540 } 6541 bool found(APSInt &Value, QualType SubobjType) { 6542 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6543 return false; 6544 } 6545 bool found(APFloat &Value, QualType SubobjType) { 6546 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6547 return false; 6548 } 6549 }; 6550 } 6551 6552 /// Perform a destructor or pseudo-destructor call on the given object, which 6553 /// might in general not be a complete object. 6554 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6555 const LValue &This, QualType ThisType) { 6556 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6557 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6558 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6559 } 6560 6561 /// Destroy and end the lifetime of the given complete object. 6562 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6563 APValue::LValueBase LVBase, APValue &Value, 6564 QualType T) { 6565 // If we've had an unmodeled side-effect, we can't rely on mutable state 6566 // (such as the object we're about to destroy) being correct. 6567 if (Info.EvalStatus.HasSideEffects) 6568 return false; 6569 6570 LValue LV; 6571 LV.set({LVBase}); 6572 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6573 } 6574 6575 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6576 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6577 LValue &Result) { 6578 if (Info.checkingPotentialConstantExpression() || 6579 Info.SpeculativeEvaluationDepth) 6580 return false; 6581 6582 // This is permitted only within a call to std::allocator<T>::allocate. 6583 auto Caller = Info.getStdAllocatorCaller("allocate"); 6584 if (!Caller) { 6585 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6586 ? diag::note_constexpr_new_untyped 6587 : diag::note_constexpr_new); 6588 return false; 6589 } 6590 6591 QualType ElemType = Caller.ElemType; 6592 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6593 Info.FFDiag(E->getExprLoc(), 6594 diag::note_constexpr_new_not_complete_object_type) 6595 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6596 return false; 6597 } 6598 6599 APSInt ByteSize; 6600 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6601 return false; 6602 bool IsNothrow = false; 6603 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6604 EvaluateIgnoredValue(Info, E->getArg(I)); 6605 IsNothrow |= E->getType()->isNothrowT(); 6606 } 6607 6608 CharUnits ElemSize; 6609 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6610 return false; 6611 APInt Size, Remainder; 6612 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6613 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6614 if (Remainder != 0) { 6615 // This likely indicates a bug in the implementation of 'std::allocator'. 6616 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6617 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6618 return false; 6619 } 6620 6621 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6622 if (IsNothrow) { 6623 Result.setNull(Info.Ctx, E->getType()); 6624 return true; 6625 } 6626 6627 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6628 return false; 6629 } 6630 6631 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6632 ArrayType::Normal, 0); 6633 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6634 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6635 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6636 return true; 6637 } 6638 6639 static bool hasVirtualDestructor(QualType T) { 6640 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6641 if (CXXDestructorDecl *DD = RD->getDestructor()) 6642 return DD->isVirtual(); 6643 return false; 6644 } 6645 6646 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6647 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6648 if (CXXDestructorDecl *DD = RD->getDestructor()) 6649 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6650 return nullptr; 6651 } 6652 6653 /// Check that the given object is a suitable pointer to a heap allocation that 6654 /// still exists and is of the right kind for the purpose of a deletion. 6655 /// 6656 /// On success, returns the heap allocation to deallocate. On failure, produces 6657 /// a diagnostic and returns None. 6658 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6659 const LValue &Pointer, 6660 DynAlloc::Kind DeallocKind) { 6661 auto PointerAsString = [&] { 6662 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6663 }; 6664 6665 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6666 if (!DA) { 6667 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6668 << PointerAsString(); 6669 if (Pointer.Base) 6670 NoteLValueLocation(Info, Pointer.Base); 6671 return None; 6672 } 6673 6674 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6675 if (!Alloc) { 6676 Info.FFDiag(E, diag::note_constexpr_double_delete); 6677 return None; 6678 } 6679 6680 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6681 if (DeallocKind != (*Alloc)->getKind()) { 6682 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6683 << DeallocKind << (*Alloc)->getKind() << AllocType; 6684 NoteLValueLocation(Info, Pointer.Base); 6685 return None; 6686 } 6687 6688 bool Subobject = false; 6689 if (DeallocKind == DynAlloc::New) { 6690 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6691 Pointer.Designator.isOnePastTheEnd(); 6692 } else { 6693 Subobject = Pointer.Designator.Entries.size() != 1 || 6694 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6695 } 6696 if (Subobject) { 6697 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6698 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6699 return None; 6700 } 6701 6702 return Alloc; 6703 } 6704 6705 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6706 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6707 if (Info.checkingPotentialConstantExpression() || 6708 Info.SpeculativeEvaluationDepth) 6709 return false; 6710 6711 // This is permitted only within a call to std::allocator<T>::deallocate. 6712 if (!Info.getStdAllocatorCaller("deallocate")) { 6713 Info.FFDiag(E->getExprLoc()); 6714 return true; 6715 } 6716 6717 LValue Pointer; 6718 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6719 return false; 6720 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6721 EvaluateIgnoredValue(Info, E->getArg(I)); 6722 6723 if (Pointer.Designator.Invalid) 6724 return false; 6725 6726 // Deleting a null pointer has no effect. 6727 if (Pointer.isNullPointer()) 6728 return true; 6729 6730 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6731 return false; 6732 6733 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6734 return true; 6735 } 6736 6737 //===----------------------------------------------------------------------===// 6738 // Generic Evaluation 6739 //===----------------------------------------------------------------------===// 6740 namespace { 6741 6742 class BitCastBuffer { 6743 // FIXME: We're going to need bit-level granularity when we support 6744 // bit-fields. 6745 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6746 // we don't support a host or target where that is the case. Still, we should 6747 // use a more generic type in case we ever do. 6748 SmallVector<Optional<unsigned char>, 32> Bytes; 6749 6750 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6751 "Need at least 8 bit unsigned char"); 6752 6753 bool TargetIsLittleEndian; 6754 6755 public: 6756 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6757 : Bytes(Width.getQuantity()), 6758 TargetIsLittleEndian(TargetIsLittleEndian) {} 6759 6760 LLVM_NODISCARD 6761 bool readObject(CharUnits Offset, CharUnits Width, 6762 SmallVectorImpl<unsigned char> &Output) const { 6763 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6764 // If a byte of an integer is uninitialized, then the whole integer is 6765 // uninitalized. 6766 if (!Bytes[I.getQuantity()]) 6767 return false; 6768 Output.push_back(*Bytes[I.getQuantity()]); 6769 } 6770 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6771 std::reverse(Output.begin(), Output.end()); 6772 return true; 6773 } 6774 6775 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6776 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6777 std::reverse(Input.begin(), Input.end()); 6778 6779 size_t Index = 0; 6780 for (unsigned char Byte : Input) { 6781 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6782 Bytes[Offset.getQuantity() + Index] = Byte; 6783 ++Index; 6784 } 6785 } 6786 6787 size_t size() { return Bytes.size(); } 6788 }; 6789 6790 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6791 /// target would represent the value at runtime. 6792 class APValueToBufferConverter { 6793 EvalInfo &Info; 6794 BitCastBuffer Buffer; 6795 const CastExpr *BCE; 6796 6797 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6798 const CastExpr *BCE) 6799 : Info(Info), 6800 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6801 BCE(BCE) {} 6802 6803 bool visit(const APValue &Val, QualType Ty) { 6804 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6805 } 6806 6807 // Write out Val with type Ty into Buffer starting at Offset. 6808 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6809 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6810 6811 // As a special case, nullptr_t has an indeterminate value. 6812 if (Ty->isNullPtrType()) 6813 return true; 6814 6815 // Dig through Src to find the byte at SrcOffset. 6816 switch (Val.getKind()) { 6817 case APValue::Indeterminate: 6818 case APValue::None: 6819 return true; 6820 6821 case APValue::Int: 6822 return visitInt(Val.getInt(), Ty, Offset); 6823 case APValue::Float: 6824 return visitFloat(Val.getFloat(), Ty, Offset); 6825 case APValue::Array: 6826 return visitArray(Val, Ty, Offset); 6827 case APValue::Struct: 6828 return visitRecord(Val, Ty, Offset); 6829 6830 case APValue::ComplexInt: 6831 case APValue::ComplexFloat: 6832 case APValue::Vector: 6833 case APValue::FixedPoint: 6834 // FIXME: We should support these. 6835 6836 case APValue::Union: 6837 case APValue::MemberPointer: 6838 case APValue::AddrLabelDiff: { 6839 Info.FFDiag(BCE->getBeginLoc(), 6840 diag::note_constexpr_bit_cast_unsupported_type) 6841 << Ty; 6842 return false; 6843 } 6844 6845 case APValue::LValue: 6846 llvm_unreachable("LValue subobject in bit_cast?"); 6847 } 6848 llvm_unreachable("Unhandled APValue::ValueKind"); 6849 } 6850 6851 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6852 const RecordDecl *RD = Ty->getAsRecordDecl(); 6853 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6854 6855 // Visit the base classes. 6856 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6857 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6858 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6859 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6860 6861 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6862 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6863 return false; 6864 } 6865 } 6866 6867 // Visit the fields. 6868 unsigned FieldIdx = 0; 6869 for (FieldDecl *FD : RD->fields()) { 6870 if (FD->isBitField()) { 6871 Info.FFDiag(BCE->getBeginLoc(), 6872 diag::note_constexpr_bit_cast_unsupported_bitfield); 6873 return false; 6874 } 6875 6876 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6877 6878 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6879 "only bit-fields can have sub-char alignment"); 6880 CharUnits FieldOffset = 6881 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6882 QualType FieldTy = FD->getType(); 6883 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6884 return false; 6885 ++FieldIdx; 6886 } 6887 6888 return true; 6889 } 6890 6891 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6892 const auto *CAT = 6893 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6894 if (!CAT) 6895 return false; 6896 6897 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6898 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6899 unsigned ArraySize = Val.getArraySize(); 6900 // First, initialize the initialized elements. 6901 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6902 const APValue &SubObj = Val.getArrayInitializedElt(I); 6903 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6904 return false; 6905 } 6906 6907 // Next, initialize the rest of the array using the filler. 6908 if (Val.hasArrayFiller()) { 6909 const APValue &Filler = Val.getArrayFiller(); 6910 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6911 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6912 return false; 6913 } 6914 } 6915 6916 return true; 6917 } 6918 6919 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6920 APSInt AdjustedVal = Val; 6921 unsigned Width = AdjustedVal.getBitWidth(); 6922 if (Ty->isBooleanType()) { 6923 Width = Info.Ctx.getTypeSize(Ty); 6924 AdjustedVal = AdjustedVal.extend(Width); 6925 } 6926 6927 SmallVector<unsigned char, 8> Bytes(Width / 8); 6928 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6929 Buffer.writeObject(Offset, Bytes); 6930 return true; 6931 } 6932 6933 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6934 APSInt AsInt(Val.bitcastToAPInt()); 6935 return visitInt(AsInt, Ty, Offset); 6936 } 6937 6938 public: 6939 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6940 const CastExpr *BCE) { 6941 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6942 APValueToBufferConverter Converter(Info, DstSize, BCE); 6943 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6944 return None; 6945 return Converter.Buffer; 6946 } 6947 }; 6948 6949 /// Write an BitCastBuffer into an APValue. 6950 class BufferToAPValueConverter { 6951 EvalInfo &Info; 6952 const BitCastBuffer &Buffer; 6953 const CastExpr *BCE; 6954 6955 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6956 const CastExpr *BCE) 6957 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6958 6959 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6960 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6961 // Ideally this will be unreachable. 6962 llvm::NoneType unsupportedType(QualType Ty) { 6963 Info.FFDiag(BCE->getBeginLoc(), 6964 diag::note_constexpr_bit_cast_unsupported_type) 6965 << Ty; 6966 return None; 6967 } 6968 6969 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6970 Info.FFDiag(BCE->getBeginLoc(), 6971 diag::note_constexpr_bit_cast_unrepresentable_value) 6972 << Ty << Val.toString(/*Radix=*/10); 6973 return None; 6974 } 6975 6976 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6977 const EnumType *EnumSugar = nullptr) { 6978 if (T->isNullPtrType()) { 6979 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6980 return APValue((Expr *)nullptr, 6981 /*Offset=*/CharUnits::fromQuantity(NullValue), 6982 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6983 } 6984 6985 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6986 6987 // Work around floating point types that contain unused padding bytes. This 6988 // is really just `long double` on x86, which is the only fundamental type 6989 // with padding bytes. 6990 if (T->isRealFloatingType()) { 6991 const llvm::fltSemantics &Semantics = 6992 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6993 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6994 assert(NumBits % 8 == 0); 6995 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6996 if (NumBytes != SizeOf) 6997 SizeOf = NumBytes; 6998 } 6999 7000 SmallVector<uint8_t, 8> Bytes; 7001 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7002 // If this is std::byte or unsigned char, then its okay to store an 7003 // indeterminate value. 7004 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7005 bool IsUChar = 7006 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7007 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7008 if (!IsStdByte && !IsUChar) { 7009 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7010 Info.FFDiag(BCE->getExprLoc(), 7011 diag::note_constexpr_bit_cast_indet_dest) 7012 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7013 return None; 7014 } 7015 7016 return APValue::IndeterminateValue(); 7017 } 7018 7019 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7020 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7021 7022 if (T->isIntegralOrEnumerationType()) { 7023 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7024 7025 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7026 if (IntWidth != Val.getBitWidth()) { 7027 APSInt Truncated = Val.trunc(IntWidth); 7028 if (Truncated.extend(Val.getBitWidth()) != Val) 7029 return unrepresentableValue(QualType(T, 0), Val); 7030 Val = Truncated; 7031 } 7032 7033 return APValue(Val); 7034 } 7035 7036 if (T->isRealFloatingType()) { 7037 const llvm::fltSemantics &Semantics = 7038 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7039 return APValue(APFloat(Semantics, Val)); 7040 } 7041 7042 return unsupportedType(QualType(T, 0)); 7043 } 7044 7045 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7046 const RecordDecl *RD = RTy->getAsRecordDecl(); 7047 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7048 7049 unsigned NumBases = 0; 7050 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7051 NumBases = CXXRD->getNumBases(); 7052 7053 APValue ResultVal(APValue::UninitStruct(), NumBases, 7054 std::distance(RD->field_begin(), RD->field_end())); 7055 7056 // Visit the base classes. 7057 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7058 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7059 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7060 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7061 if (BaseDecl->isEmpty() || 7062 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7063 continue; 7064 7065 Optional<APValue> SubObj = visitType( 7066 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7067 if (!SubObj) 7068 return None; 7069 ResultVal.getStructBase(I) = *SubObj; 7070 } 7071 } 7072 7073 // Visit the fields. 7074 unsigned FieldIdx = 0; 7075 for (FieldDecl *FD : RD->fields()) { 7076 // FIXME: We don't currently support bit-fields. A lot of the logic for 7077 // this is in CodeGen, so we need to factor it around. 7078 if (FD->isBitField()) { 7079 Info.FFDiag(BCE->getBeginLoc(), 7080 diag::note_constexpr_bit_cast_unsupported_bitfield); 7081 return None; 7082 } 7083 7084 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7085 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7086 7087 CharUnits FieldOffset = 7088 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7089 Offset; 7090 QualType FieldTy = FD->getType(); 7091 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7092 if (!SubObj) 7093 return None; 7094 ResultVal.getStructField(FieldIdx) = *SubObj; 7095 ++FieldIdx; 7096 } 7097 7098 return ResultVal; 7099 } 7100 7101 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7102 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7103 assert(!RepresentationType.isNull() && 7104 "enum forward decl should be caught by Sema"); 7105 const auto *AsBuiltin = 7106 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7107 // Recurse into the underlying type. Treat std::byte transparently as 7108 // unsigned char. 7109 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7110 } 7111 7112 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7113 size_t Size = Ty->getSize().getLimitedValue(); 7114 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7115 7116 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7117 for (size_t I = 0; I != Size; ++I) { 7118 Optional<APValue> ElementValue = 7119 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7120 if (!ElementValue) 7121 return None; 7122 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7123 } 7124 7125 return ArrayValue; 7126 } 7127 7128 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7129 return unsupportedType(QualType(Ty, 0)); 7130 } 7131 7132 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7133 QualType Can = Ty.getCanonicalType(); 7134 7135 switch (Can->getTypeClass()) { 7136 #define TYPE(Class, Base) \ 7137 case Type::Class: \ 7138 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7139 #define ABSTRACT_TYPE(Class, Base) 7140 #define NON_CANONICAL_TYPE(Class, Base) \ 7141 case Type::Class: \ 7142 llvm_unreachable("non-canonical type should be impossible!"); 7143 #define DEPENDENT_TYPE(Class, Base) \ 7144 case Type::Class: \ 7145 llvm_unreachable( \ 7146 "dependent types aren't supported in the constant evaluator!"); 7147 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7148 case Type::Class: \ 7149 llvm_unreachable("either dependent or not canonical!"); 7150 #include "clang/AST/TypeNodes.inc" 7151 } 7152 llvm_unreachable("Unhandled Type::TypeClass"); 7153 } 7154 7155 public: 7156 // Pull out a full value of type DstType. 7157 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7158 const CastExpr *BCE) { 7159 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7160 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7161 } 7162 }; 7163 7164 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7165 QualType Ty, EvalInfo *Info, 7166 const ASTContext &Ctx, 7167 bool CheckingDest) { 7168 Ty = Ty.getCanonicalType(); 7169 7170 auto diag = [&](int Reason) { 7171 if (Info) 7172 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7173 << CheckingDest << (Reason == 4) << Reason; 7174 return false; 7175 }; 7176 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7177 if (Info) 7178 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7179 << NoteTy << Construct << Ty; 7180 return false; 7181 }; 7182 7183 if (Ty->isUnionType()) 7184 return diag(0); 7185 if (Ty->isPointerType()) 7186 return diag(1); 7187 if (Ty->isMemberPointerType()) 7188 return diag(2); 7189 if (Ty.isVolatileQualified()) 7190 return diag(3); 7191 7192 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7193 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7194 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7195 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7196 CheckingDest)) 7197 return note(1, BS.getType(), BS.getBeginLoc()); 7198 } 7199 for (FieldDecl *FD : Record->fields()) { 7200 if (FD->getType()->isReferenceType()) 7201 return diag(4); 7202 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7203 CheckingDest)) 7204 return note(0, FD->getType(), FD->getBeginLoc()); 7205 } 7206 } 7207 7208 if (Ty->isArrayType() && 7209 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7210 Info, Ctx, CheckingDest)) 7211 return false; 7212 7213 return true; 7214 } 7215 7216 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7217 const ASTContext &Ctx, 7218 const CastExpr *BCE) { 7219 bool DestOK = checkBitCastConstexprEligibilityType( 7220 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7221 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7222 BCE->getBeginLoc(), 7223 BCE->getSubExpr()->getType(), Info, Ctx, false); 7224 return SourceOK; 7225 } 7226 7227 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7228 APValue &SourceValue, 7229 const CastExpr *BCE) { 7230 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7231 "no host or target supports non 8-bit chars"); 7232 assert(SourceValue.isLValue() && 7233 "LValueToRValueBitcast requires an lvalue operand!"); 7234 7235 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7236 return false; 7237 7238 LValue SourceLValue; 7239 APValue SourceRValue; 7240 SourceLValue.setFrom(Info.Ctx, SourceValue); 7241 if (!handleLValueToRValueConversion( 7242 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7243 SourceRValue, /*WantObjectRepresentation=*/true)) 7244 return false; 7245 7246 // Read out SourceValue into a char buffer. 7247 Optional<BitCastBuffer> Buffer = 7248 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7249 if (!Buffer) 7250 return false; 7251 7252 // Write out the buffer into a new APValue. 7253 Optional<APValue> MaybeDestValue = 7254 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7255 if (!MaybeDestValue) 7256 return false; 7257 7258 DestValue = std::move(*MaybeDestValue); 7259 return true; 7260 } 7261 7262 template <class Derived> 7263 class ExprEvaluatorBase 7264 : public ConstStmtVisitor<Derived, bool> { 7265 private: 7266 Derived &getDerived() { return static_cast<Derived&>(*this); } 7267 bool DerivedSuccess(const APValue &V, const Expr *E) { 7268 return getDerived().Success(V, E); 7269 } 7270 bool DerivedZeroInitialization(const Expr *E) { 7271 return getDerived().ZeroInitialization(E); 7272 } 7273 7274 // Check whether a conditional operator with a non-constant condition is a 7275 // potential constant expression. If neither arm is a potential constant 7276 // expression, then the conditional operator is not either. 7277 template<typename ConditionalOperator> 7278 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7279 assert(Info.checkingPotentialConstantExpression()); 7280 7281 // Speculatively evaluate both arms. 7282 SmallVector<PartialDiagnosticAt, 8> Diag; 7283 { 7284 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7285 StmtVisitorTy::Visit(E->getFalseExpr()); 7286 if (Diag.empty()) 7287 return; 7288 } 7289 7290 { 7291 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7292 Diag.clear(); 7293 StmtVisitorTy::Visit(E->getTrueExpr()); 7294 if (Diag.empty()) 7295 return; 7296 } 7297 7298 Error(E, diag::note_constexpr_conditional_never_const); 7299 } 7300 7301 7302 template<typename ConditionalOperator> 7303 bool HandleConditionalOperator(const ConditionalOperator *E) { 7304 bool BoolResult; 7305 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7306 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7307 CheckPotentialConstantConditional(E); 7308 return false; 7309 } 7310 if (Info.noteFailure()) { 7311 StmtVisitorTy::Visit(E->getTrueExpr()); 7312 StmtVisitorTy::Visit(E->getFalseExpr()); 7313 } 7314 return false; 7315 } 7316 7317 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7318 return StmtVisitorTy::Visit(EvalExpr); 7319 } 7320 7321 protected: 7322 EvalInfo &Info; 7323 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7324 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7325 7326 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7327 return Info.CCEDiag(E, D); 7328 } 7329 7330 bool ZeroInitialization(const Expr *E) { return Error(E); } 7331 7332 public: 7333 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7334 7335 EvalInfo &getEvalInfo() { return Info; } 7336 7337 /// Report an evaluation error. This should only be called when an error is 7338 /// first discovered. When propagating an error, just return false. 7339 bool Error(const Expr *E, diag::kind D) { 7340 Info.FFDiag(E, D); 7341 return false; 7342 } 7343 bool Error(const Expr *E) { 7344 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7345 } 7346 7347 bool VisitStmt(const Stmt *) { 7348 llvm_unreachable("Expression evaluator should not be called on stmts"); 7349 } 7350 bool VisitExpr(const Expr *E) { 7351 return Error(E); 7352 } 7353 7354 bool VisitConstantExpr(const ConstantExpr *E) { 7355 if (E->hasAPValueResult()) 7356 return DerivedSuccess(E->getAPValueResult(), E); 7357 7358 return StmtVisitorTy::Visit(E->getSubExpr()); 7359 } 7360 7361 bool VisitParenExpr(const ParenExpr *E) 7362 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7363 bool VisitUnaryExtension(const UnaryOperator *E) 7364 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7365 bool VisitUnaryPlus(const UnaryOperator *E) 7366 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7367 bool VisitChooseExpr(const ChooseExpr *E) 7368 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7369 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7370 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7371 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7372 { return StmtVisitorTy::Visit(E->getReplacement()); } 7373 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7374 TempVersionRAII RAII(*Info.CurrentCall); 7375 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7376 return StmtVisitorTy::Visit(E->getExpr()); 7377 } 7378 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7379 TempVersionRAII RAII(*Info.CurrentCall); 7380 // The initializer may not have been parsed yet, or might be erroneous. 7381 if (!E->getExpr()) 7382 return Error(E); 7383 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7384 return StmtVisitorTy::Visit(E->getExpr()); 7385 } 7386 7387 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7388 FullExpressionRAII Scope(Info); 7389 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7390 } 7391 7392 // Temporaries are registered when created, so we don't care about 7393 // CXXBindTemporaryExpr. 7394 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7395 return StmtVisitorTy::Visit(E->getSubExpr()); 7396 } 7397 7398 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7399 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7400 return static_cast<Derived*>(this)->VisitCastExpr(E); 7401 } 7402 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7403 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7404 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7405 return static_cast<Derived*>(this)->VisitCastExpr(E); 7406 } 7407 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7408 return static_cast<Derived*>(this)->VisitCastExpr(E); 7409 } 7410 7411 bool VisitBinaryOperator(const BinaryOperator *E) { 7412 switch (E->getOpcode()) { 7413 default: 7414 return Error(E); 7415 7416 case BO_Comma: 7417 VisitIgnoredValue(E->getLHS()); 7418 return StmtVisitorTy::Visit(E->getRHS()); 7419 7420 case BO_PtrMemD: 7421 case BO_PtrMemI: { 7422 LValue Obj; 7423 if (!HandleMemberPointerAccess(Info, E, Obj)) 7424 return false; 7425 APValue Result; 7426 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7427 return false; 7428 return DerivedSuccess(Result, E); 7429 } 7430 } 7431 } 7432 7433 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7434 return StmtVisitorTy::Visit(E->getSemanticForm()); 7435 } 7436 7437 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7438 // Evaluate and cache the common expression. We treat it as a temporary, 7439 // even though it's not quite the same thing. 7440 LValue CommonLV; 7441 if (!Evaluate(Info.CurrentCall->createTemporary( 7442 E->getOpaqueValue(), 7443 getStorageType(Info.Ctx, E->getOpaqueValue()), 7444 ScopeKind::FullExpression, CommonLV), 7445 Info, E->getCommon())) 7446 return false; 7447 7448 return HandleConditionalOperator(E); 7449 } 7450 7451 bool VisitConditionalOperator(const ConditionalOperator *E) { 7452 bool IsBcpCall = false; 7453 // If the condition (ignoring parens) is a __builtin_constant_p call, 7454 // the result is a constant expression if it can be folded without 7455 // side-effects. This is an important GNU extension. See GCC PR38377 7456 // for discussion. 7457 if (const CallExpr *CallCE = 7458 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7459 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7460 IsBcpCall = true; 7461 7462 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7463 // constant expression; we can't check whether it's potentially foldable. 7464 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7465 // it would return 'false' in this mode. 7466 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7467 return false; 7468 7469 FoldConstant Fold(Info, IsBcpCall); 7470 if (!HandleConditionalOperator(E)) { 7471 Fold.keepDiagnostics(); 7472 return false; 7473 } 7474 7475 return true; 7476 } 7477 7478 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7479 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7480 return DerivedSuccess(*Value, E); 7481 7482 const Expr *Source = E->getSourceExpr(); 7483 if (!Source) 7484 return Error(E); 7485 if (Source == E) { // sanity checking. 7486 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7487 return Error(E); 7488 } 7489 return StmtVisitorTy::Visit(Source); 7490 } 7491 7492 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7493 for (const Expr *SemE : E->semantics()) { 7494 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7495 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7496 // result expression: there could be two different LValues that would 7497 // refer to the same object in that case, and we can't model that. 7498 if (SemE == E->getResultExpr()) 7499 return Error(E); 7500 7501 // Unique OVEs get evaluated if and when we encounter them when 7502 // emitting the rest of the semantic form, rather than eagerly. 7503 if (OVE->isUnique()) 7504 continue; 7505 7506 LValue LV; 7507 if (!Evaluate(Info.CurrentCall->createTemporary( 7508 OVE, getStorageType(Info.Ctx, OVE), 7509 ScopeKind::FullExpression, LV), 7510 Info, OVE->getSourceExpr())) 7511 return false; 7512 } else if (SemE == E->getResultExpr()) { 7513 if (!StmtVisitorTy::Visit(SemE)) 7514 return false; 7515 } else { 7516 if (!EvaluateIgnoredValue(Info, SemE)) 7517 return false; 7518 } 7519 } 7520 return true; 7521 } 7522 7523 bool VisitCallExpr(const CallExpr *E) { 7524 APValue Result; 7525 if (!handleCallExpr(E, Result, nullptr)) 7526 return false; 7527 return DerivedSuccess(Result, E); 7528 } 7529 7530 bool handleCallExpr(const CallExpr *E, APValue &Result, 7531 const LValue *ResultSlot) { 7532 CallScopeRAII CallScope(Info); 7533 7534 const Expr *Callee = E->getCallee()->IgnoreParens(); 7535 QualType CalleeType = Callee->getType(); 7536 7537 const FunctionDecl *FD = nullptr; 7538 LValue *This = nullptr, ThisVal; 7539 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7540 bool HasQualifier = false; 7541 7542 CallRef Call; 7543 7544 // Extract function decl and 'this' pointer from the callee. 7545 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7546 const CXXMethodDecl *Member = nullptr; 7547 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7548 // Explicit bound member calls, such as x.f() or p->g(); 7549 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7550 return false; 7551 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7552 if (!Member) 7553 return Error(Callee); 7554 This = &ThisVal; 7555 HasQualifier = ME->hasQualifier(); 7556 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7557 // Indirect bound member calls ('.*' or '->*'). 7558 const ValueDecl *D = 7559 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7560 if (!D) 7561 return false; 7562 Member = dyn_cast<CXXMethodDecl>(D); 7563 if (!Member) 7564 return Error(Callee); 7565 This = &ThisVal; 7566 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7567 if (!Info.getLangOpts().CPlusPlus20) 7568 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7569 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7570 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7571 } else 7572 return Error(Callee); 7573 FD = Member; 7574 } else if (CalleeType->isFunctionPointerType()) { 7575 LValue CalleeLV; 7576 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7577 return false; 7578 7579 if (!CalleeLV.getLValueOffset().isZero()) 7580 return Error(Callee); 7581 FD = dyn_cast_or_null<FunctionDecl>( 7582 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7583 if (!FD) 7584 return Error(Callee); 7585 // Don't call function pointers which have been cast to some other type. 7586 // Per DR (no number yet), the caller and callee can differ in noexcept. 7587 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7588 CalleeType->getPointeeType(), FD->getType())) { 7589 return Error(E); 7590 } 7591 7592 // For an (overloaded) assignment expression, evaluate the RHS before the 7593 // LHS. 7594 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7595 if (OCE && OCE->isAssignmentOp()) { 7596 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7597 Call = Info.CurrentCall->createCall(FD); 7598 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7599 Info, FD, /*RightToLeft=*/true)) 7600 return false; 7601 } 7602 7603 // Overloaded operator calls to member functions are represented as normal 7604 // calls with '*this' as the first argument. 7605 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7606 if (MD && !MD->isStatic()) { 7607 // FIXME: When selecting an implicit conversion for an overloaded 7608 // operator delete, we sometimes try to evaluate calls to conversion 7609 // operators without a 'this' parameter! 7610 if (Args.empty()) 7611 return Error(E); 7612 7613 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7614 return false; 7615 This = &ThisVal; 7616 Args = Args.slice(1); 7617 } else if (MD && MD->isLambdaStaticInvoker()) { 7618 // Map the static invoker for the lambda back to the call operator. 7619 // Conveniently, we don't have to slice out the 'this' argument (as is 7620 // being done for the non-static case), since a static member function 7621 // doesn't have an implicit argument passed in. 7622 const CXXRecordDecl *ClosureClass = MD->getParent(); 7623 assert( 7624 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7625 "Number of captures must be zero for conversion to function-ptr"); 7626 7627 const CXXMethodDecl *LambdaCallOp = 7628 ClosureClass->getLambdaCallOperator(); 7629 7630 // Set 'FD', the function that will be called below, to the call 7631 // operator. If the closure object represents a generic lambda, find 7632 // the corresponding specialization of the call operator. 7633 7634 if (ClosureClass->isGenericLambda()) { 7635 assert(MD->isFunctionTemplateSpecialization() && 7636 "A generic lambda's static-invoker function must be a " 7637 "template specialization"); 7638 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7639 FunctionTemplateDecl *CallOpTemplate = 7640 LambdaCallOp->getDescribedFunctionTemplate(); 7641 void *InsertPos = nullptr; 7642 FunctionDecl *CorrespondingCallOpSpecialization = 7643 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7644 assert(CorrespondingCallOpSpecialization && 7645 "We must always have a function call operator specialization " 7646 "that corresponds to our static invoker specialization"); 7647 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7648 } else 7649 FD = LambdaCallOp; 7650 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7651 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7652 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7653 LValue Ptr; 7654 if (!HandleOperatorNewCall(Info, E, Ptr)) 7655 return false; 7656 Ptr.moveInto(Result); 7657 return CallScope.destroy(); 7658 } else { 7659 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7660 } 7661 } 7662 } else 7663 return Error(E); 7664 7665 // Evaluate the arguments now if we've not already done so. 7666 if (!Call) { 7667 Call = Info.CurrentCall->createCall(FD); 7668 if (!EvaluateArgs(Args, Call, Info, FD)) 7669 return false; 7670 } 7671 7672 SmallVector<QualType, 4> CovariantAdjustmentPath; 7673 if (This) { 7674 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7675 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7676 // Perform virtual dispatch, if necessary. 7677 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7678 CovariantAdjustmentPath); 7679 if (!FD) 7680 return false; 7681 } else { 7682 // Check that the 'this' pointer points to an object of the right type. 7683 // FIXME: If this is an assignment operator call, we may need to change 7684 // the active union member before we check this. 7685 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7686 return false; 7687 } 7688 } 7689 7690 // Destructor calls are different enough that they have their own codepath. 7691 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7692 assert(This && "no 'this' pointer for destructor call"); 7693 return HandleDestruction(Info, E, *This, 7694 Info.Ctx.getRecordType(DD->getParent())) && 7695 CallScope.destroy(); 7696 } 7697 7698 const FunctionDecl *Definition = nullptr; 7699 Stmt *Body = FD->getBody(Definition); 7700 7701 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7702 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7703 Body, Info, Result, ResultSlot)) 7704 return false; 7705 7706 if (!CovariantAdjustmentPath.empty() && 7707 !HandleCovariantReturnAdjustment(Info, E, Result, 7708 CovariantAdjustmentPath)) 7709 return false; 7710 7711 return CallScope.destroy(); 7712 } 7713 7714 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7715 return StmtVisitorTy::Visit(E->getInitializer()); 7716 } 7717 bool VisitInitListExpr(const InitListExpr *E) { 7718 if (E->getNumInits() == 0) 7719 return DerivedZeroInitialization(E); 7720 if (E->getNumInits() == 1) 7721 return StmtVisitorTy::Visit(E->getInit(0)); 7722 return Error(E); 7723 } 7724 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7725 return DerivedZeroInitialization(E); 7726 } 7727 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7728 return DerivedZeroInitialization(E); 7729 } 7730 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7731 return DerivedZeroInitialization(E); 7732 } 7733 7734 /// A member expression where the object is a prvalue is itself a prvalue. 7735 bool VisitMemberExpr(const MemberExpr *E) { 7736 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7737 "missing temporary materialization conversion"); 7738 assert(!E->isArrow() && "missing call to bound member function?"); 7739 7740 APValue Val; 7741 if (!Evaluate(Val, Info, E->getBase())) 7742 return false; 7743 7744 QualType BaseTy = E->getBase()->getType(); 7745 7746 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7747 if (!FD) return Error(E); 7748 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7749 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7750 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7751 7752 // Note: there is no lvalue base here. But this case should only ever 7753 // happen in C or in C++98, where we cannot be evaluating a constexpr 7754 // constructor, which is the only case the base matters. 7755 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7756 SubobjectDesignator Designator(BaseTy); 7757 Designator.addDeclUnchecked(FD); 7758 7759 APValue Result; 7760 return extractSubobject(Info, E, Obj, Designator, Result) && 7761 DerivedSuccess(Result, E); 7762 } 7763 7764 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7765 APValue Val; 7766 if (!Evaluate(Val, Info, E->getBase())) 7767 return false; 7768 7769 if (Val.isVector()) { 7770 SmallVector<uint32_t, 4> Indices; 7771 E->getEncodedElementAccess(Indices); 7772 if (Indices.size() == 1) { 7773 // Return scalar. 7774 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7775 } else { 7776 // Construct new APValue vector. 7777 SmallVector<APValue, 4> Elts; 7778 for (unsigned I = 0; I < Indices.size(); ++I) { 7779 Elts.push_back(Val.getVectorElt(Indices[I])); 7780 } 7781 APValue VecResult(Elts.data(), Indices.size()); 7782 return DerivedSuccess(VecResult, E); 7783 } 7784 } 7785 7786 return false; 7787 } 7788 7789 bool VisitCastExpr(const CastExpr *E) { 7790 switch (E->getCastKind()) { 7791 default: 7792 break; 7793 7794 case CK_AtomicToNonAtomic: { 7795 APValue AtomicVal; 7796 // This does not need to be done in place even for class/array types: 7797 // atomic-to-non-atomic conversion implies copying the object 7798 // representation. 7799 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7800 return false; 7801 return DerivedSuccess(AtomicVal, E); 7802 } 7803 7804 case CK_NoOp: 7805 case CK_UserDefinedConversion: 7806 return StmtVisitorTy::Visit(E->getSubExpr()); 7807 7808 case CK_LValueToRValue: { 7809 LValue LVal; 7810 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7811 return false; 7812 APValue RVal; 7813 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7814 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7815 LVal, RVal)) 7816 return false; 7817 return DerivedSuccess(RVal, E); 7818 } 7819 case CK_LValueToRValueBitCast: { 7820 APValue DestValue, SourceValue; 7821 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7822 return false; 7823 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7824 return false; 7825 return DerivedSuccess(DestValue, E); 7826 } 7827 7828 case CK_AddressSpaceConversion: { 7829 APValue Value; 7830 if (!Evaluate(Value, Info, E->getSubExpr())) 7831 return false; 7832 return DerivedSuccess(Value, E); 7833 } 7834 } 7835 7836 return Error(E); 7837 } 7838 7839 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7840 return VisitUnaryPostIncDec(UO); 7841 } 7842 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7843 return VisitUnaryPostIncDec(UO); 7844 } 7845 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7846 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7847 return Error(UO); 7848 7849 LValue LVal; 7850 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7851 return false; 7852 APValue RVal; 7853 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7854 UO->isIncrementOp(), &RVal)) 7855 return false; 7856 return DerivedSuccess(RVal, UO); 7857 } 7858 7859 bool VisitStmtExpr(const StmtExpr *E) { 7860 // We will have checked the full-expressions inside the statement expression 7861 // when they were completed, and don't need to check them again now. 7862 if (Info.checkingForUndefinedBehavior()) 7863 return Error(E); 7864 7865 const CompoundStmt *CS = E->getSubStmt(); 7866 if (CS->body_empty()) 7867 return true; 7868 7869 BlockScopeRAII Scope(Info); 7870 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7871 BE = CS->body_end(); 7872 /**/; ++BI) { 7873 if (BI + 1 == BE) { 7874 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7875 if (!FinalExpr) { 7876 Info.FFDiag((*BI)->getBeginLoc(), 7877 diag::note_constexpr_stmt_expr_unsupported); 7878 return false; 7879 } 7880 return this->Visit(FinalExpr) && Scope.destroy(); 7881 } 7882 7883 APValue ReturnValue; 7884 StmtResult Result = { ReturnValue, nullptr }; 7885 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7886 if (ESR != ESR_Succeeded) { 7887 // FIXME: If the statement-expression terminated due to 'return', 7888 // 'break', or 'continue', it would be nice to propagate that to 7889 // the outer statement evaluation rather than bailing out. 7890 if (ESR != ESR_Failed) 7891 Info.FFDiag((*BI)->getBeginLoc(), 7892 diag::note_constexpr_stmt_expr_unsupported); 7893 return false; 7894 } 7895 } 7896 7897 llvm_unreachable("Return from function from the loop above."); 7898 } 7899 7900 /// Visit a value which is evaluated, but whose value is ignored. 7901 void VisitIgnoredValue(const Expr *E) { 7902 EvaluateIgnoredValue(Info, E); 7903 } 7904 7905 /// Potentially visit a MemberExpr's base expression. 7906 void VisitIgnoredBaseExpression(const Expr *E) { 7907 // While MSVC doesn't evaluate the base expression, it does diagnose the 7908 // presence of side-effecting behavior. 7909 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7910 return; 7911 VisitIgnoredValue(E); 7912 } 7913 }; 7914 7915 } // namespace 7916 7917 //===----------------------------------------------------------------------===// 7918 // Common base class for lvalue and temporary evaluation. 7919 //===----------------------------------------------------------------------===// 7920 namespace { 7921 template<class Derived> 7922 class LValueExprEvaluatorBase 7923 : public ExprEvaluatorBase<Derived> { 7924 protected: 7925 LValue &Result; 7926 bool InvalidBaseOK; 7927 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7928 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7929 7930 bool Success(APValue::LValueBase B) { 7931 Result.set(B); 7932 return true; 7933 } 7934 7935 bool evaluatePointer(const Expr *E, LValue &Result) { 7936 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7937 } 7938 7939 public: 7940 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7941 : ExprEvaluatorBaseTy(Info), Result(Result), 7942 InvalidBaseOK(InvalidBaseOK) {} 7943 7944 bool Success(const APValue &V, const Expr *E) { 7945 Result.setFrom(this->Info.Ctx, V); 7946 return true; 7947 } 7948 7949 bool VisitMemberExpr(const MemberExpr *E) { 7950 // Handle non-static data members. 7951 QualType BaseTy; 7952 bool EvalOK; 7953 if (E->isArrow()) { 7954 EvalOK = evaluatePointer(E->getBase(), Result); 7955 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7956 } else if (E->getBase()->isRValue()) { 7957 assert(E->getBase()->getType()->isRecordType()); 7958 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7959 BaseTy = E->getBase()->getType(); 7960 } else { 7961 EvalOK = this->Visit(E->getBase()); 7962 BaseTy = E->getBase()->getType(); 7963 } 7964 if (!EvalOK) { 7965 if (!InvalidBaseOK) 7966 return false; 7967 Result.setInvalid(E); 7968 return true; 7969 } 7970 7971 const ValueDecl *MD = E->getMemberDecl(); 7972 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7973 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7974 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7975 (void)BaseTy; 7976 if (!HandleLValueMember(this->Info, E, Result, FD)) 7977 return false; 7978 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7979 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7980 return false; 7981 } else 7982 return this->Error(E); 7983 7984 if (MD->getType()->isReferenceType()) { 7985 APValue RefValue; 7986 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7987 RefValue)) 7988 return false; 7989 return Success(RefValue, E); 7990 } 7991 return true; 7992 } 7993 7994 bool VisitBinaryOperator(const BinaryOperator *E) { 7995 switch (E->getOpcode()) { 7996 default: 7997 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7998 7999 case BO_PtrMemD: 8000 case BO_PtrMemI: 8001 return HandleMemberPointerAccess(this->Info, E, Result); 8002 } 8003 } 8004 8005 bool VisitCastExpr(const CastExpr *E) { 8006 switch (E->getCastKind()) { 8007 default: 8008 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8009 8010 case CK_DerivedToBase: 8011 case CK_UncheckedDerivedToBase: 8012 if (!this->Visit(E->getSubExpr())) 8013 return false; 8014 8015 // Now figure out the necessary offset to add to the base LV to get from 8016 // the derived class to the base class. 8017 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8018 Result); 8019 } 8020 } 8021 }; 8022 } 8023 8024 //===----------------------------------------------------------------------===// 8025 // LValue Evaluation 8026 // 8027 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8028 // function designators (in C), decl references to void objects (in C), and 8029 // temporaries (if building with -Wno-address-of-temporary). 8030 // 8031 // LValue evaluation produces values comprising a base expression of one of the 8032 // following types: 8033 // - Declarations 8034 // * VarDecl 8035 // * FunctionDecl 8036 // - Literals 8037 // * CompoundLiteralExpr in C (and in global scope in C++) 8038 // * StringLiteral 8039 // * PredefinedExpr 8040 // * ObjCStringLiteralExpr 8041 // * ObjCEncodeExpr 8042 // * AddrLabelExpr 8043 // * BlockExpr 8044 // * CallExpr for a MakeStringConstant builtin 8045 // - typeid(T) expressions, as TypeInfoLValues 8046 // - Locals and temporaries 8047 // * MaterializeTemporaryExpr 8048 // * Any Expr, with a CallIndex indicating the function in which the temporary 8049 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8050 // from the AST (FIXME). 8051 // * A MaterializeTemporaryExpr that has static storage duration, with no 8052 // CallIndex, for a lifetime-extended temporary. 8053 // * The ConstantExpr that is currently being evaluated during evaluation of an 8054 // immediate invocation. 8055 // plus an offset in bytes. 8056 //===----------------------------------------------------------------------===// 8057 namespace { 8058 class LValueExprEvaluator 8059 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8060 public: 8061 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8062 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8063 8064 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8065 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8066 8067 bool VisitDeclRefExpr(const DeclRefExpr *E); 8068 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8069 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8070 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8071 bool VisitMemberExpr(const MemberExpr *E); 8072 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8073 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8074 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8075 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8076 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8077 bool VisitUnaryDeref(const UnaryOperator *E); 8078 bool VisitUnaryReal(const UnaryOperator *E); 8079 bool VisitUnaryImag(const UnaryOperator *E); 8080 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8081 return VisitUnaryPreIncDec(UO); 8082 } 8083 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8084 return VisitUnaryPreIncDec(UO); 8085 } 8086 bool VisitBinAssign(const BinaryOperator *BO); 8087 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8088 8089 bool VisitCastExpr(const CastExpr *E) { 8090 switch (E->getCastKind()) { 8091 default: 8092 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8093 8094 case CK_LValueBitCast: 8095 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8096 if (!Visit(E->getSubExpr())) 8097 return false; 8098 Result.Designator.setInvalid(); 8099 return true; 8100 8101 case CK_BaseToDerived: 8102 if (!Visit(E->getSubExpr())) 8103 return false; 8104 return HandleBaseToDerivedCast(Info, E, Result); 8105 8106 case CK_Dynamic: 8107 if (!Visit(E->getSubExpr())) 8108 return false; 8109 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8110 } 8111 } 8112 }; 8113 } // end anonymous namespace 8114 8115 /// Evaluate an expression as an lvalue. This can be legitimately called on 8116 /// expressions which are not glvalues, in three cases: 8117 /// * function designators in C, and 8118 /// * "extern void" objects 8119 /// * @selector() expressions in Objective-C 8120 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8121 bool InvalidBaseOK) { 8122 assert(!E->isValueDependent()); 8123 assert(E->isGLValue() || E->getType()->isFunctionType() || 8124 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8125 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8126 } 8127 8128 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8129 const NamedDecl *D = E->getDecl(); 8130 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8131 return Success(cast<ValueDecl>(D)); 8132 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8133 return VisitVarDecl(E, VD); 8134 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8135 return Visit(BD->getBinding()); 8136 return Error(E); 8137 } 8138 8139 8140 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8141 8142 // If we are within a lambda's call operator, check whether the 'VD' referred 8143 // to within 'E' actually represents a lambda-capture that maps to a 8144 // data-member/field within the closure object, and if so, evaluate to the 8145 // field or what the field refers to. 8146 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8147 isa<DeclRefExpr>(E) && 8148 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8149 // We don't always have a complete capture-map when checking or inferring if 8150 // the function call operator meets the requirements of a constexpr function 8151 // - but we don't need to evaluate the captures to determine constexprness 8152 // (dcl.constexpr C++17). 8153 if (Info.checkingPotentialConstantExpression()) 8154 return false; 8155 8156 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8157 // Start with 'Result' referring to the complete closure object... 8158 Result = *Info.CurrentCall->This; 8159 // ... then update it to refer to the field of the closure object 8160 // that represents the capture. 8161 if (!HandleLValueMember(Info, E, Result, FD)) 8162 return false; 8163 // And if the field is of reference type, update 'Result' to refer to what 8164 // the field refers to. 8165 if (FD->getType()->isReferenceType()) { 8166 APValue RVal; 8167 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8168 RVal)) 8169 return false; 8170 Result.setFrom(Info.Ctx, RVal); 8171 } 8172 return true; 8173 } 8174 } 8175 8176 CallStackFrame *Frame = nullptr; 8177 unsigned Version = 0; 8178 if (VD->hasLocalStorage()) { 8179 // Only if a local variable was declared in the function currently being 8180 // evaluated, do we expect to be able to find its value in the current 8181 // frame. (Otherwise it was likely declared in an enclosing context and 8182 // could either have a valid evaluatable value (for e.g. a constexpr 8183 // variable) or be ill-formed (and trigger an appropriate evaluation 8184 // diagnostic)). 8185 CallStackFrame *CurrFrame = Info.CurrentCall; 8186 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8187 // Function parameters are stored in some caller's frame. (Usually the 8188 // immediate caller, but for an inherited constructor they may be more 8189 // distant.) 8190 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8191 if (CurrFrame->Arguments) { 8192 VD = CurrFrame->Arguments.getOrigParam(PVD); 8193 Frame = 8194 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8195 Version = CurrFrame->Arguments.Version; 8196 } 8197 } else { 8198 Frame = CurrFrame; 8199 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8200 } 8201 } 8202 } 8203 8204 if (!VD->getType()->isReferenceType()) { 8205 if (Frame) { 8206 Result.set({VD, Frame->Index, Version}); 8207 return true; 8208 } 8209 return Success(VD); 8210 } 8211 8212 if (!Info.getLangOpts().CPlusPlus11) { 8213 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8214 << VD << VD->getType(); 8215 Info.Note(VD->getLocation(), diag::note_declared_at); 8216 } 8217 8218 APValue *V; 8219 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8220 return false; 8221 if (!V->hasValue()) { 8222 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8223 // adjust the diagnostic to say that. 8224 if (!Info.checkingPotentialConstantExpression()) 8225 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8226 return false; 8227 } 8228 return Success(*V, E); 8229 } 8230 8231 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8232 const MaterializeTemporaryExpr *E) { 8233 // Walk through the expression to find the materialized temporary itself. 8234 SmallVector<const Expr *, 2> CommaLHSs; 8235 SmallVector<SubobjectAdjustment, 2> Adjustments; 8236 const Expr *Inner = 8237 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8238 8239 // If we passed any comma operators, evaluate their LHSs. 8240 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8241 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8242 return false; 8243 8244 // A materialized temporary with static storage duration can appear within the 8245 // result of a constant expression evaluation, so we need to preserve its 8246 // value for use outside this evaluation. 8247 APValue *Value; 8248 if (E->getStorageDuration() == SD_Static) { 8249 // FIXME: What about SD_Thread? 8250 Value = E->getOrCreateValue(true); 8251 *Value = APValue(); 8252 Result.set(E); 8253 } else { 8254 Value = &Info.CurrentCall->createTemporary( 8255 E, E->getType(), 8256 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8257 : ScopeKind::Block, 8258 Result); 8259 } 8260 8261 QualType Type = Inner->getType(); 8262 8263 // Materialize the temporary itself. 8264 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8265 *Value = APValue(); 8266 return false; 8267 } 8268 8269 // Adjust our lvalue to refer to the desired subobject. 8270 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8271 --I; 8272 switch (Adjustments[I].Kind) { 8273 case SubobjectAdjustment::DerivedToBaseAdjustment: 8274 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8275 Type, Result)) 8276 return false; 8277 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8278 break; 8279 8280 case SubobjectAdjustment::FieldAdjustment: 8281 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8282 return false; 8283 Type = Adjustments[I].Field->getType(); 8284 break; 8285 8286 case SubobjectAdjustment::MemberPointerAdjustment: 8287 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8288 Adjustments[I].Ptr.RHS)) 8289 return false; 8290 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8291 break; 8292 } 8293 } 8294 8295 return true; 8296 } 8297 8298 bool 8299 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8300 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8301 "lvalue compound literal in c++?"); 8302 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8303 // only see this when folding in C, so there's no standard to follow here. 8304 return Success(E); 8305 } 8306 8307 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8308 TypeInfoLValue TypeInfo; 8309 8310 if (!E->isPotentiallyEvaluated()) { 8311 if (E->isTypeOperand()) 8312 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8313 else 8314 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8315 } else { 8316 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8317 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8318 << E->getExprOperand()->getType() 8319 << E->getExprOperand()->getSourceRange(); 8320 } 8321 8322 if (!Visit(E->getExprOperand())) 8323 return false; 8324 8325 Optional<DynamicType> DynType = 8326 ComputeDynamicType(Info, E, Result, AK_TypeId); 8327 if (!DynType) 8328 return false; 8329 8330 TypeInfo = 8331 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8332 } 8333 8334 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8335 } 8336 8337 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8338 return Success(E->getGuidDecl()); 8339 } 8340 8341 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8342 // Handle static data members. 8343 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8344 VisitIgnoredBaseExpression(E->getBase()); 8345 return VisitVarDecl(E, VD); 8346 } 8347 8348 // Handle static member functions. 8349 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8350 if (MD->isStatic()) { 8351 VisitIgnoredBaseExpression(E->getBase()); 8352 return Success(MD); 8353 } 8354 } 8355 8356 // Handle non-static data members. 8357 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8358 } 8359 8360 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8361 // FIXME: Deal with vectors as array subscript bases. 8362 if (E->getBase()->getType()->isVectorType()) 8363 return Error(E); 8364 8365 APSInt Index; 8366 bool Success = true; 8367 8368 // C++17's rules require us to evaluate the LHS first, regardless of which 8369 // side is the base. 8370 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8371 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8372 : !EvaluateInteger(SubExpr, Index, Info)) { 8373 if (!Info.noteFailure()) 8374 return false; 8375 Success = false; 8376 } 8377 } 8378 8379 return Success && 8380 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8381 } 8382 8383 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8384 return evaluatePointer(E->getSubExpr(), Result); 8385 } 8386 8387 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8388 if (!Visit(E->getSubExpr())) 8389 return false; 8390 // __real is a no-op on scalar lvalues. 8391 if (E->getSubExpr()->getType()->isAnyComplexType()) 8392 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8393 return true; 8394 } 8395 8396 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8397 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8398 "lvalue __imag__ on scalar?"); 8399 if (!Visit(E->getSubExpr())) 8400 return false; 8401 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8402 return true; 8403 } 8404 8405 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8406 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8407 return Error(UO); 8408 8409 if (!this->Visit(UO->getSubExpr())) 8410 return false; 8411 8412 return handleIncDec( 8413 this->Info, UO, Result, UO->getSubExpr()->getType(), 8414 UO->isIncrementOp(), nullptr); 8415 } 8416 8417 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8418 const CompoundAssignOperator *CAO) { 8419 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8420 return Error(CAO); 8421 8422 bool Success = true; 8423 8424 // C++17 onwards require that we evaluate the RHS first. 8425 APValue RHS; 8426 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8427 if (!Info.noteFailure()) 8428 return false; 8429 Success = false; 8430 } 8431 8432 // The overall lvalue result is the result of evaluating the LHS. 8433 if (!this->Visit(CAO->getLHS()) || !Success) 8434 return false; 8435 8436 return handleCompoundAssignment( 8437 this->Info, CAO, 8438 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8439 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8440 } 8441 8442 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8443 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8444 return Error(E); 8445 8446 bool Success = true; 8447 8448 // C++17 onwards require that we evaluate the RHS first. 8449 APValue NewVal; 8450 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8451 if (!Info.noteFailure()) 8452 return false; 8453 Success = false; 8454 } 8455 8456 if (!this->Visit(E->getLHS()) || !Success) 8457 return false; 8458 8459 if (Info.getLangOpts().CPlusPlus20 && 8460 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8461 return false; 8462 8463 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8464 NewVal); 8465 } 8466 8467 //===----------------------------------------------------------------------===// 8468 // Pointer Evaluation 8469 //===----------------------------------------------------------------------===// 8470 8471 /// Attempts to compute the number of bytes available at the pointer 8472 /// returned by a function with the alloc_size attribute. Returns true if we 8473 /// were successful. Places an unsigned number into `Result`. 8474 /// 8475 /// This expects the given CallExpr to be a call to a function with an 8476 /// alloc_size attribute. 8477 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8478 const CallExpr *Call, 8479 llvm::APInt &Result) { 8480 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8481 8482 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8483 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8484 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8485 if (Call->getNumArgs() <= SizeArgNo) 8486 return false; 8487 8488 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8489 Expr::EvalResult ExprResult; 8490 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8491 return false; 8492 Into = ExprResult.Val.getInt(); 8493 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8494 return false; 8495 Into = Into.zextOrSelf(BitsInSizeT); 8496 return true; 8497 }; 8498 8499 APSInt SizeOfElem; 8500 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8501 return false; 8502 8503 if (!AllocSize->getNumElemsParam().isValid()) { 8504 Result = std::move(SizeOfElem); 8505 return true; 8506 } 8507 8508 APSInt NumberOfElems; 8509 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8510 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8511 return false; 8512 8513 bool Overflow; 8514 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8515 if (Overflow) 8516 return false; 8517 8518 Result = std::move(BytesAvailable); 8519 return true; 8520 } 8521 8522 /// Convenience function. LVal's base must be a call to an alloc_size 8523 /// function. 8524 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8525 const LValue &LVal, 8526 llvm::APInt &Result) { 8527 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8528 "Can't get the size of a non alloc_size function"); 8529 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8530 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8531 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8532 } 8533 8534 /// Attempts to evaluate the given LValueBase as the result of a call to 8535 /// a function with the alloc_size attribute. If it was possible to do so, this 8536 /// function will return true, make Result's Base point to said function call, 8537 /// and mark Result's Base as invalid. 8538 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8539 LValue &Result) { 8540 if (Base.isNull()) 8541 return false; 8542 8543 // Because we do no form of static analysis, we only support const variables. 8544 // 8545 // Additionally, we can't support parameters, nor can we support static 8546 // variables (in the latter case, use-before-assign isn't UB; in the former, 8547 // we have no clue what they'll be assigned to). 8548 const auto *VD = 8549 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8550 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8551 return false; 8552 8553 const Expr *Init = VD->getAnyInitializer(); 8554 if (!Init) 8555 return false; 8556 8557 const Expr *E = Init->IgnoreParens(); 8558 if (!tryUnwrapAllocSizeCall(E)) 8559 return false; 8560 8561 // Store E instead of E unwrapped so that the type of the LValue's base is 8562 // what the user wanted. 8563 Result.setInvalid(E); 8564 8565 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8566 Result.addUnsizedArray(Info, E, Pointee); 8567 return true; 8568 } 8569 8570 namespace { 8571 class PointerExprEvaluator 8572 : public ExprEvaluatorBase<PointerExprEvaluator> { 8573 LValue &Result; 8574 bool InvalidBaseOK; 8575 8576 bool Success(const Expr *E) { 8577 Result.set(E); 8578 return true; 8579 } 8580 8581 bool evaluateLValue(const Expr *E, LValue &Result) { 8582 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8583 } 8584 8585 bool evaluatePointer(const Expr *E, LValue &Result) { 8586 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8587 } 8588 8589 bool visitNonBuiltinCallExpr(const CallExpr *E); 8590 public: 8591 8592 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8593 : ExprEvaluatorBaseTy(info), Result(Result), 8594 InvalidBaseOK(InvalidBaseOK) {} 8595 8596 bool Success(const APValue &V, const Expr *E) { 8597 Result.setFrom(Info.Ctx, V); 8598 return true; 8599 } 8600 bool ZeroInitialization(const Expr *E) { 8601 Result.setNull(Info.Ctx, E->getType()); 8602 return true; 8603 } 8604 8605 bool VisitBinaryOperator(const BinaryOperator *E); 8606 bool VisitCastExpr(const CastExpr* E); 8607 bool VisitUnaryAddrOf(const UnaryOperator *E); 8608 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8609 { return Success(E); } 8610 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8611 if (E->isExpressibleAsConstantInitializer()) 8612 return Success(E); 8613 if (Info.noteFailure()) 8614 EvaluateIgnoredValue(Info, E->getSubExpr()); 8615 return Error(E); 8616 } 8617 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8618 { return Success(E); } 8619 bool VisitCallExpr(const CallExpr *E); 8620 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8621 bool VisitBlockExpr(const BlockExpr *E) { 8622 if (!E->getBlockDecl()->hasCaptures()) 8623 return Success(E); 8624 return Error(E); 8625 } 8626 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8627 // Can't look at 'this' when checking a potential constant expression. 8628 if (Info.checkingPotentialConstantExpression()) 8629 return false; 8630 if (!Info.CurrentCall->This) { 8631 if (Info.getLangOpts().CPlusPlus11) 8632 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8633 else 8634 Info.FFDiag(E); 8635 return false; 8636 } 8637 Result = *Info.CurrentCall->This; 8638 // If we are inside a lambda's call operator, the 'this' expression refers 8639 // to the enclosing '*this' object (either by value or reference) which is 8640 // either copied into the closure object's field that represents the '*this' 8641 // or refers to '*this'. 8642 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8643 // Ensure we actually have captured 'this'. (an error will have 8644 // been previously reported if not). 8645 if (!Info.CurrentCall->LambdaThisCaptureField) 8646 return false; 8647 8648 // Update 'Result' to refer to the data member/field of the closure object 8649 // that represents the '*this' capture. 8650 if (!HandleLValueMember(Info, E, Result, 8651 Info.CurrentCall->LambdaThisCaptureField)) 8652 return false; 8653 // If we captured '*this' by reference, replace the field with its referent. 8654 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8655 ->isPointerType()) { 8656 APValue RVal; 8657 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8658 RVal)) 8659 return false; 8660 8661 Result.setFrom(Info.Ctx, RVal); 8662 } 8663 } 8664 return true; 8665 } 8666 8667 bool VisitCXXNewExpr(const CXXNewExpr *E); 8668 8669 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8670 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8671 APValue LValResult = E->EvaluateInContext( 8672 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8673 Result.setFrom(Info.Ctx, LValResult); 8674 return true; 8675 } 8676 8677 // FIXME: Missing: @protocol, @selector 8678 }; 8679 } // end anonymous namespace 8680 8681 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8682 bool InvalidBaseOK) { 8683 assert(!E->isValueDependent()); 8684 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8685 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8686 } 8687 8688 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8689 if (E->getOpcode() != BO_Add && 8690 E->getOpcode() != BO_Sub) 8691 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8692 8693 const Expr *PExp = E->getLHS(); 8694 const Expr *IExp = E->getRHS(); 8695 if (IExp->getType()->isPointerType()) 8696 std::swap(PExp, IExp); 8697 8698 bool EvalPtrOK = evaluatePointer(PExp, Result); 8699 if (!EvalPtrOK && !Info.noteFailure()) 8700 return false; 8701 8702 llvm::APSInt Offset; 8703 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8704 return false; 8705 8706 if (E->getOpcode() == BO_Sub) 8707 negateAsSigned(Offset); 8708 8709 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8710 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8711 } 8712 8713 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8714 return evaluateLValue(E->getSubExpr(), Result); 8715 } 8716 8717 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8718 const Expr *SubExpr = E->getSubExpr(); 8719 8720 switch (E->getCastKind()) { 8721 default: 8722 break; 8723 case CK_BitCast: 8724 case CK_CPointerToObjCPointerCast: 8725 case CK_BlockPointerToObjCPointerCast: 8726 case CK_AnyPointerToBlockPointerCast: 8727 case CK_AddressSpaceConversion: 8728 if (!Visit(SubExpr)) 8729 return false; 8730 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8731 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8732 // also static_casts, but we disallow them as a resolution to DR1312. 8733 if (!E->getType()->isVoidPointerType()) { 8734 if (!Result.InvalidBase && !Result.Designator.Invalid && 8735 !Result.IsNullPtr && 8736 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8737 E->getType()->getPointeeType()) && 8738 Info.getStdAllocatorCaller("allocate")) { 8739 // Inside a call to std::allocator::allocate and friends, we permit 8740 // casting from void* back to cv1 T* for a pointer that points to a 8741 // cv2 T. 8742 } else { 8743 Result.Designator.setInvalid(); 8744 if (SubExpr->getType()->isVoidPointerType()) 8745 CCEDiag(E, diag::note_constexpr_invalid_cast) 8746 << 3 << SubExpr->getType(); 8747 else 8748 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8749 } 8750 } 8751 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8752 ZeroInitialization(E); 8753 return true; 8754 8755 case CK_DerivedToBase: 8756 case CK_UncheckedDerivedToBase: 8757 if (!evaluatePointer(E->getSubExpr(), Result)) 8758 return false; 8759 if (!Result.Base && Result.Offset.isZero()) 8760 return true; 8761 8762 // Now figure out the necessary offset to add to the base LV to get from 8763 // the derived class to the base class. 8764 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8765 castAs<PointerType>()->getPointeeType(), 8766 Result); 8767 8768 case CK_BaseToDerived: 8769 if (!Visit(E->getSubExpr())) 8770 return false; 8771 if (!Result.Base && Result.Offset.isZero()) 8772 return true; 8773 return HandleBaseToDerivedCast(Info, E, Result); 8774 8775 case CK_Dynamic: 8776 if (!Visit(E->getSubExpr())) 8777 return false; 8778 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8779 8780 case CK_NullToPointer: 8781 VisitIgnoredValue(E->getSubExpr()); 8782 return ZeroInitialization(E); 8783 8784 case CK_IntegralToPointer: { 8785 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8786 8787 APValue Value; 8788 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8789 break; 8790 8791 if (Value.isInt()) { 8792 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8793 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8794 Result.Base = (Expr*)nullptr; 8795 Result.InvalidBase = false; 8796 Result.Offset = CharUnits::fromQuantity(N); 8797 Result.Designator.setInvalid(); 8798 Result.IsNullPtr = false; 8799 return true; 8800 } else { 8801 // Cast is of an lvalue, no need to change value. 8802 Result.setFrom(Info.Ctx, Value); 8803 return true; 8804 } 8805 } 8806 8807 case CK_ArrayToPointerDecay: { 8808 if (SubExpr->isGLValue()) { 8809 if (!evaluateLValue(SubExpr, Result)) 8810 return false; 8811 } else { 8812 APValue &Value = Info.CurrentCall->createTemporary( 8813 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8814 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8815 return false; 8816 } 8817 // The result is a pointer to the first element of the array. 8818 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8819 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8820 Result.addArray(Info, E, CAT); 8821 else 8822 Result.addUnsizedArray(Info, E, AT->getElementType()); 8823 return true; 8824 } 8825 8826 case CK_FunctionToPointerDecay: 8827 return evaluateLValue(SubExpr, Result); 8828 8829 case CK_LValueToRValue: { 8830 LValue LVal; 8831 if (!evaluateLValue(E->getSubExpr(), LVal)) 8832 return false; 8833 8834 APValue RVal; 8835 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8836 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8837 LVal, RVal)) 8838 return InvalidBaseOK && 8839 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8840 return Success(RVal, E); 8841 } 8842 } 8843 8844 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8845 } 8846 8847 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8848 UnaryExprOrTypeTrait ExprKind) { 8849 // C++ [expr.alignof]p3: 8850 // When alignof is applied to a reference type, the result is the 8851 // alignment of the referenced type. 8852 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8853 T = Ref->getPointeeType(); 8854 8855 if (T.getQualifiers().hasUnaligned()) 8856 return CharUnits::One(); 8857 8858 const bool AlignOfReturnsPreferred = 8859 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8860 8861 // __alignof is defined to return the preferred alignment. 8862 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8863 // as well. 8864 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8865 return Info.Ctx.toCharUnitsFromBits( 8866 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8867 // alignof and _Alignof are defined to return the ABI alignment. 8868 else if (ExprKind == UETT_AlignOf) 8869 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8870 else 8871 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8872 } 8873 8874 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8875 UnaryExprOrTypeTrait ExprKind) { 8876 E = E->IgnoreParens(); 8877 8878 // The kinds of expressions that we have special-case logic here for 8879 // should be kept up to date with the special checks for those 8880 // expressions in Sema. 8881 8882 // alignof decl is always accepted, even if it doesn't make sense: we default 8883 // to 1 in those cases. 8884 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8885 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8886 /*RefAsPointee*/true); 8887 8888 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8889 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8890 /*RefAsPointee*/true); 8891 8892 return GetAlignOfType(Info, E->getType(), ExprKind); 8893 } 8894 8895 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8896 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8897 return Info.Ctx.getDeclAlign(VD); 8898 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8899 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8900 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8901 } 8902 8903 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8904 /// __builtin_is_aligned and __builtin_assume_aligned. 8905 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8906 EvalInfo &Info, APSInt &Alignment) { 8907 if (!EvaluateInteger(E, Alignment, Info)) 8908 return false; 8909 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8910 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8911 return false; 8912 } 8913 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8914 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8915 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8916 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8917 << MaxValue << ForType << Alignment; 8918 return false; 8919 } 8920 // Ensure both alignment and source value have the same bit width so that we 8921 // don't assert when computing the resulting value. 8922 APSInt ExtAlignment = 8923 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8924 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8925 "Alignment should not be changed by ext/trunc"); 8926 Alignment = ExtAlignment; 8927 assert(Alignment.getBitWidth() == SrcWidth); 8928 return true; 8929 } 8930 8931 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8932 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8933 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8934 return true; 8935 8936 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8937 return false; 8938 8939 Result.setInvalid(E); 8940 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8941 Result.addUnsizedArray(Info, E, PointeeTy); 8942 return true; 8943 } 8944 8945 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8946 if (IsStringLiteralCall(E)) 8947 return Success(E); 8948 8949 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8950 return VisitBuiltinCallExpr(E, BuiltinOp); 8951 8952 return visitNonBuiltinCallExpr(E); 8953 } 8954 8955 // Determine if T is a character type for which we guarantee that 8956 // sizeof(T) == 1. 8957 static bool isOneByteCharacterType(QualType T) { 8958 return T->isCharType() || T->isChar8Type(); 8959 } 8960 8961 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8962 unsigned BuiltinOp) { 8963 switch (BuiltinOp) { 8964 case Builtin::BI__builtin_addressof: 8965 return evaluateLValue(E->getArg(0), Result); 8966 case Builtin::BI__builtin_assume_aligned: { 8967 // We need to be very careful here because: if the pointer does not have the 8968 // asserted alignment, then the behavior is undefined, and undefined 8969 // behavior is non-constant. 8970 if (!evaluatePointer(E->getArg(0), Result)) 8971 return false; 8972 8973 LValue OffsetResult(Result); 8974 APSInt Alignment; 8975 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8976 Alignment)) 8977 return false; 8978 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8979 8980 if (E->getNumArgs() > 2) { 8981 APSInt Offset; 8982 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8983 return false; 8984 8985 int64_t AdditionalOffset = -Offset.getZExtValue(); 8986 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8987 } 8988 8989 // If there is a base object, then it must have the correct alignment. 8990 if (OffsetResult.Base) { 8991 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8992 8993 if (BaseAlignment < Align) { 8994 Result.Designator.setInvalid(); 8995 // FIXME: Add support to Diagnostic for long / long long. 8996 CCEDiag(E->getArg(0), 8997 diag::note_constexpr_baa_insufficient_alignment) << 0 8998 << (unsigned)BaseAlignment.getQuantity() 8999 << (unsigned)Align.getQuantity(); 9000 return false; 9001 } 9002 } 9003 9004 // The offset must also have the correct alignment. 9005 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9006 Result.Designator.setInvalid(); 9007 9008 (OffsetResult.Base 9009 ? CCEDiag(E->getArg(0), 9010 diag::note_constexpr_baa_insufficient_alignment) << 1 9011 : CCEDiag(E->getArg(0), 9012 diag::note_constexpr_baa_value_insufficient_alignment)) 9013 << (int)OffsetResult.Offset.getQuantity() 9014 << (unsigned)Align.getQuantity(); 9015 return false; 9016 } 9017 9018 return true; 9019 } 9020 case Builtin::BI__builtin_align_up: 9021 case Builtin::BI__builtin_align_down: { 9022 if (!evaluatePointer(E->getArg(0), Result)) 9023 return false; 9024 APSInt Alignment; 9025 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9026 Alignment)) 9027 return false; 9028 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9029 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9030 // For align_up/align_down, we can return the same value if the alignment 9031 // is known to be greater or equal to the requested value. 9032 if (PtrAlign.getQuantity() >= Alignment) 9033 return true; 9034 9035 // The alignment could be greater than the minimum at run-time, so we cannot 9036 // infer much about the resulting pointer value. One case is possible: 9037 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9038 // can infer the correct index if the requested alignment is smaller than 9039 // the base alignment so we can perform the computation on the offset. 9040 if (BaseAlignment.getQuantity() >= Alignment) { 9041 assert(Alignment.getBitWidth() <= 64 && 9042 "Cannot handle > 64-bit address-space"); 9043 uint64_t Alignment64 = Alignment.getZExtValue(); 9044 CharUnits NewOffset = CharUnits::fromQuantity( 9045 BuiltinOp == Builtin::BI__builtin_align_down 9046 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9047 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9048 Result.adjustOffset(NewOffset - Result.Offset); 9049 // TODO: diagnose out-of-bounds values/only allow for arrays? 9050 return true; 9051 } 9052 // Otherwise, we cannot constant-evaluate the result. 9053 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9054 << Alignment; 9055 return false; 9056 } 9057 case Builtin::BI__builtin_operator_new: 9058 return HandleOperatorNewCall(Info, E, Result); 9059 case Builtin::BI__builtin_launder: 9060 return evaluatePointer(E->getArg(0), Result); 9061 case Builtin::BIstrchr: 9062 case Builtin::BIwcschr: 9063 case Builtin::BImemchr: 9064 case Builtin::BIwmemchr: 9065 if (Info.getLangOpts().CPlusPlus11) 9066 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9067 << /*isConstexpr*/0 << /*isConstructor*/0 9068 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9069 else 9070 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9071 LLVM_FALLTHROUGH; 9072 case Builtin::BI__builtin_strchr: 9073 case Builtin::BI__builtin_wcschr: 9074 case Builtin::BI__builtin_memchr: 9075 case Builtin::BI__builtin_char_memchr: 9076 case Builtin::BI__builtin_wmemchr: { 9077 if (!Visit(E->getArg(0))) 9078 return false; 9079 APSInt Desired; 9080 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9081 return false; 9082 uint64_t MaxLength = uint64_t(-1); 9083 if (BuiltinOp != Builtin::BIstrchr && 9084 BuiltinOp != Builtin::BIwcschr && 9085 BuiltinOp != Builtin::BI__builtin_strchr && 9086 BuiltinOp != Builtin::BI__builtin_wcschr) { 9087 APSInt N; 9088 if (!EvaluateInteger(E->getArg(2), N, Info)) 9089 return false; 9090 MaxLength = N.getExtValue(); 9091 } 9092 // We cannot find the value if there are no candidates to match against. 9093 if (MaxLength == 0u) 9094 return ZeroInitialization(E); 9095 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9096 Result.Designator.Invalid) 9097 return false; 9098 QualType CharTy = Result.Designator.getType(Info.Ctx); 9099 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9100 BuiltinOp == Builtin::BI__builtin_memchr; 9101 assert(IsRawByte || 9102 Info.Ctx.hasSameUnqualifiedType( 9103 CharTy, E->getArg(0)->getType()->getPointeeType())); 9104 // Pointers to const void may point to objects of incomplete type. 9105 if (IsRawByte && CharTy->isIncompleteType()) { 9106 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9107 return false; 9108 } 9109 // Give up on byte-oriented matching against multibyte elements. 9110 // FIXME: We can compare the bytes in the correct order. 9111 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9112 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9113 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9114 << CharTy; 9115 return false; 9116 } 9117 // Figure out what value we're actually looking for (after converting to 9118 // the corresponding unsigned type if necessary). 9119 uint64_t DesiredVal; 9120 bool StopAtNull = false; 9121 switch (BuiltinOp) { 9122 case Builtin::BIstrchr: 9123 case Builtin::BI__builtin_strchr: 9124 // strchr compares directly to the passed integer, and therefore 9125 // always fails if given an int that is not a char. 9126 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9127 E->getArg(1)->getType(), 9128 Desired), 9129 Desired)) 9130 return ZeroInitialization(E); 9131 StopAtNull = true; 9132 LLVM_FALLTHROUGH; 9133 case Builtin::BImemchr: 9134 case Builtin::BI__builtin_memchr: 9135 case Builtin::BI__builtin_char_memchr: 9136 // memchr compares by converting both sides to unsigned char. That's also 9137 // correct for strchr if we get this far (to cope with plain char being 9138 // unsigned in the strchr case). 9139 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9140 break; 9141 9142 case Builtin::BIwcschr: 9143 case Builtin::BI__builtin_wcschr: 9144 StopAtNull = true; 9145 LLVM_FALLTHROUGH; 9146 case Builtin::BIwmemchr: 9147 case Builtin::BI__builtin_wmemchr: 9148 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9149 DesiredVal = Desired.getZExtValue(); 9150 break; 9151 } 9152 9153 for (; MaxLength; --MaxLength) { 9154 APValue Char; 9155 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9156 !Char.isInt()) 9157 return false; 9158 if (Char.getInt().getZExtValue() == DesiredVal) 9159 return true; 9160 if (StopAtNull && !Char.getInt()) 9161 break; 9162 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9163 return false; 9164 } 9165 // Not found: return nullptr. 9166 return ZeroInitialization(E); 9167 } 9168 9169 case Builtin::BImemcpy: 9170 case Builtin::BImemmove: 9171 case Builtin::BIwmemcpy: 9172 case Builtin::BIwmemmove: 9173 if (Info.getLangOpts().CPlusPlus11) 9174 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9175 << /*isConstexpr*/0 << /*isConstructor*/0 9176 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9177 else 9178 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9179 LLVM_FALLTHROUGH; 9180 case Builtin::BI__builtin_memcpy: 9181 case Builtin::BI__builtin_memmove: 9182 case Builtin::BI__builtin_wmemcpy: 9183 case Builtin::BI__builtin_wmemmove: { 9184 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9185 BuiltinOp == Builtin::BIwmemmove || 9186 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9187 BuiltinOp == Builtin::BI__builtin_wmemmove; 9188 bool Move = BuiltinOp == Builtin::BImemmove || 9189 BuiltinOp == Builtin::BIwmemmove || 9190 BuiltinOp == Builtin::BI__builtin_memmove || 9191 BuiltinOp == Builtin::BI__builtin_wmemmove; 9192 9193 // The result of mem* is the first argument. 9194 if (!Visit(E->getArg(0))) 9195 return false; 9196 LValue Dest = Result; 9197 9198 LValue Src; 9199 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9200 return false; 9201 9202 APSInt N; 9203 if (!EvaluateInteger(E->getArg(2), N, Info)) 9204 return false; 9205 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9206 9207 // If the size is zero, we treat this as always being a valid no-op. 9208 // (Even if one of the src and dest pointers is null.) 9209 if (!N) 9210 return true; 9211 9212 // Otherwise, if either of the operands is null, we can't proceed. Don't 9213 // try to determine the type of the copied objects, because there aren't 9214 // any. 9215 if (!Src.Base || !Dest.Base) { 9216 APValue Val; 9217 (!Src.Base ? Src : Dest).moveInto(Val); 9218 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9219 << Move << WChar << !!Src.Base 9220 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9221 return false; 9222 } 9223 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9224 return false; 9225 9226 // We require that Src and Dest are both pointers to arrays of 9227 // trivially-copyable type. (For the wide version, the designator will be 9228 // invalid if the designated object is not a wchar_t.) 9229 QualType T = Dest.Designator.getType(Info.Ctx); 9230 QualType SrcT = Src.Designator.getType(Info.Ctx); 9231 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9232 // FIXME: Consider using our bit_cast implementation to support this. 9233 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9234 return false; 9235 } 9236 if (T->isIncompleteType()) { 9237 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9238 return false; 9239 } 9240 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9241 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9242 return false; 9243 } 9244 9245 // Figure out how many T's we're copying. 9246 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9247 if (!WChar) { 9248 uint64_t Remainder; 9249 llvm::APInt OrigN = N; 9250 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9251 if (Remainder) { 9252 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9253 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 9254 << (unsigned)TSize; 9255 return false; 9256 } 9257 } 9258 9259 // Check that the copying will remain within the arrays, just so that we 9260 // can give a more meaningful diagnostic. This implicitly also checks that 9261 // N fits into 64 bits. 9262 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9263 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9264 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9265 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9266 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9267 << N.toString(10, /*Signed*/false); 9268 return false; 9269 } 9270 uint64_t NElems = N.getZExtValue(); 9271 uint64_t NBytes = NElems * TSize; 9272 9273 // Check for overlap. 9274 int Direction = 1; 9275 if (HasSameBase(Src, Dest)) { 9276 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9277 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9278 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9279 // Dest is inside the source region. 9280 if (!Move) { 9281 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9282 return false; 9283 } 9284 // For memmove and friends, copy backwards. 9285 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9286 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9287 return false; 9288 Direction = -1; 9289 } else if (!Move && SrcOffset >= DestOffset && 9290 SrcOffset - DestOffset < NBytes) { 9291 // Src is inside the destination region for memcpy: invalid. 9292 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9293 return false; 9294 } 9295 } 9296 9297 while (true) { 9298 APValue Val; 9299 // FIXME: Set WantObjectRepresentation to true if we're copying a 9300 // char-like type? 9301 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9302 !handleAssignment(Info, E, Dest, T, Val)) 9303 return false; 9304 // Do not iterate past the last element; if we're copying backwards, that 9305 // might take us off the start of the array. 9306 if (--NElems == 0) 9307 return true; 9308 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9309 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9310 return false; 9311 } 9312 } 9313 9314 default: 9315 break; 9316 } 9317 9318 return visitNonBuiltinCallExpr(E); 9319 } 9320 9321 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9322 APValue &Result, const InitListExpr *ILE, 9323 QualType AllocType); 9324 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9325 APValue &Result, 9326 const CXXConstructExpr *CCE, 9327 QualType AllocType); 9328 9329 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9330 if (!Info.getLangOpts().CPlusPlus20) 9331 Info.CCEDiag(E, diag::note_constexpr_new); 9332 9333 // We cannot speculatively evaluate a delete expression. 9334 if (Info.SpeculativeEvaluationDepth) 9335 return false; 9336 9337 FunctionDecl *OperatorNew = E->getOperatorNew(); 9338 9339 bool IsNothrow = false; 9340 bool IsPlacement = false; 9341 if (OperatorNew->isReservedGlobalPlacementOperator() && 9342 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9343 // FIXME Support array placement new. 9344 assert(E->getNumPlacementArgs() == 1); 9345 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9346 return false; 9347 if (Result.Designator.Invalid) 9348 return false; 9349 IsPlacement = true; 9350 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9351 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9352 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9353 return false; 9354 } else if (E->getNumPlacementArgs()) { 9355 // The only new-placement list we support is of the form (std::nothrow). 9356 // 9357 // FIXME: There is no restriction on this, but it's not clear that any 9358 // other form makes any sense. We get here for cases such as: 9359 // 9360 // new (std::align_val_t{N}) X(int) 9361 // 9362 // (which should presumably be valid only if N is a multiple of 9363 // alignof(int), and in any case can't be deallocated unless N is 9364 // alignof(X) and X has new-extended alignment). 9365 if (E->getNumPlacementArgs() != 1 || 9366 !E->getPlacementArg(0)->getType()->isNothrowT()) 9367 return Error(E, diag::note_constexpr_new_placement); 9368 9369 LValue Nothrow; 9370 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9371 return false; 9372 IsNothrow = true; 9373 } 9374 9375 const Expr *Init = E->getInitializer(); 9376 const InitListExpr *ResizedArrayILE = nullptr; 9377 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9378 bool ValueInit = false; 9379 9380 QualType AllocType = E->getAllocatedType(); 9381 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9382 const Expr *Stripped = *ArraySize; 9383 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9384 Stripped = ICE->getSubExpr()) 9385 if (ICE->getCastKind() != CK_NoOp && 9386 ICE->getCastKind() != CK_IntegralCast) 9387 break; 9388 9389 llvm::APSInt ArrayBound; 9390 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9391 return false; 9392 9393 // C++ [expr.new]p9: 9394 // The expression is erroneous if: 9395 // -- [...] its value before converting to size_t [or] applying the 9396 // second standard conversion sequence is less than zero 9397 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9398 if (IsNothrow) 9399 return ZeroInitialization(E); 9400 9401 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9402 << ArrayBound << (*ArraySize)->getSourceRange(); 9403 return false; 9404 } 9405 9406 // -- its value is such that the size of the allocated object would 9407 // exceed the implementation-defined limit 9408 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9409 ArrayBound) > 9410 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9411 if (IsNothrow) 9412 return ZeroInitialization(E); 9413 9414 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9415 << ArrayBound << (*ArraySize)->getSourceRange(); 9416 return false; 9417 } 9418 9419 // -- the new-initializer is a braced-init-list and the number of 9420 // array elements for which initializers are provided [...] 9421 // exceeds the number of elements to initialize 9422 if (!Init) { 9423 // No initialization is performed. 9424 } else if (isa<CXXScalarValueInitExpr>(Init) || 9425 isa<ImplicitValueInitExpr>(Init)) { 9426 ValueInit = true; 9427 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9428 ResizedArrayCCE = CCE; 9429 } else { 9430 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9431 assert(CAT && "unexpected type for array initializer"); 9432 9433 unsigned Bits = 9434 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9435 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9436 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9437 if (InitBound.ugt(AllocBound)) { 9438 if (IsNothrow) 9439 return ZeroInitialization(E); 9440 9441 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9442 << AllocBound.toString(10, /*Signed=*/false) 9443 << InitBound.toString(10, /*Signed=*/false) 9444 << (*ArraySize)->getSourceRange(); 9445 return false; 9446 } 9447 9448 // If the sizes differ, we must have an initializer list, and we need 9449 // special handling for this case when we initialize. 9450 if (InitBound != AllocBound) 9451 ResizedArrayILE = cast<InitListExpr>(Init); 9452 } 9453 9454 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9455 ArrayType::Normal, 0); 9456 } else { 9457 assert(!AllocType->isArrayType() && 9458 "array allocation with non-array new"); 9459 } 9460 9461 APValue *Val; 9462 if (IsPlacement) { 9463 AccessKinds AK = AK_Construct; 9464 struct FindObjectHandler { 9465 EvalInfo &Info; 9466 const Expr *E; 9467 QualType AllocType; 9468 const AccessKinds AccessKind; 9469 APValue *Value; 9470 9471 typedef bool result_type; 9472 bool failed() { return false; } 9473 bool found(APValue &Subobj, QualType SubobjType) { 9474 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9475 // old name of the object to be used to name the new object. 9476 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9477 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9478 SubobjType << AllocType; 9479 return false; 9480 } 9481 Value = &Subobj; 9482 return true; 9483 } 9484 bool found(APSInt &Value, QualType SubobjType) { 9485 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9486 return false; 9487 } 9488 bool found(APFloat &Value, QualType SubobjType) { 9489 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9490 return false; 9491 } 9492 } Handler = {Info, E, AllocType, AK, nullptr}; 9493 9494 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9495 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9496 return false; 9497 9498 Val = Handler.Value; 9499 9500 // [basic.life]p1: 9501 // The lifetime of an object o of type T ends when [...] the storage 9502 // which the object occupies is [...] reused by an object that is not 9503 // nested within o (6.6.2). 9504 *Val = APValue(); 9505 } else { 9506 // Perform the allocation and obtain a pointer to the resulting object. 9507 Val = Info.createHeapAlloc(E, AllocType, Result); 9508 if (!Val) 9509 return false; 9510 } 9511 9512 if (ValueInit) { 9513 ImplicitValueInitExpr VIE(AllocType); 9514 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9515 return false; 9516 } else if (ResizedArrayILE) { 9517 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9518 AllocType)) 9519 return false; 9520 } else if (ResizedArrayCCE) { 9521 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9522 AllocType)) 9523 return false; 9524 } else if (Init) { 9525 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9526 return false; 9527 } else if (!getDefaultInitValue(AllocType, *Val)) { 9528 return false; 9529 } 9530 9531 // Array new returns a pointer to the first element, not a pointer to the 9532 // array. 9533 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9534 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9535 9536 return true; 9537 } 9538 //===----------------------------------------------------------------------===// 9539 // Member Pointer Evaluation 9540 //===----------------------------------------------------------------------===// 9541 9542 namespace { 9543 class MemberPointerExprEvaluator 9544 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9545 MemberPtr &Result; 9546 9547 bool Success(const ValueDecl *D) { 9548 Result = MemberPtr(D); 9549 return true; 9550 } 9551 public: 9552 9553 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9554 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9555 9556 bool Success(const APValue &V, const Expr *E) { 9557 Result.setFrom(V); 9558 return true; 9559 } 9560 bool ZeroInitialization(const Expr *E) { 9561 return Success((const ValueDecl*)nullptr); 9562 } 9563 9564 bool VisitCastExpr(const CastExpr *E); 9565 bool VisitUnaryAddrOf(const UnaryOperator *E); 9566 }; 9567 } // end anonymous namespace 9568 9569 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9570 EvalInfo &Info) { 9571 assert(!E->isValueDependent()); 9572 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9573 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9574 } 9575 9576 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9577 switch (E->getCastKind()) { 9578 default: 9579 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9580 9581 case CK_NullToMemberPointer: 9582 VisitIgnoredValue(E->getSubExpr()); 9583 return ZeroInitialization(E); 9584 9585 case CK_BaseToDerivedMemberPointer: { 9586 if (!Visit(E->getSubExpr())) 9587 return false; 9588 if (E->path_empty()) 9589 return true; 9590 // Base-to-derived member pointer casts store the path in derived-to-base 9591 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9592 // the wrong end of the derived->base arc, so stagger the path by one class. 9593 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9594 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9595 PathI != PathE; ++PathI) { 9596 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9597 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9598 if (!Result.castToDerived(Derived)) 9599 return Error(E); 9600 } 9601 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9602 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9603 return Error(E); 9604 return true; 9605 } 9606 9607 case CK_DerivedToBaseMemberPointer: 9608 if (!Visit(E->getSubExpr())) 9609 return false; 9610 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9611 PathE = E->path_end(); PathI != PathE; ++PathI) { 9612 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9613 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9614 if (!Result.castToBase(Base)) 9615 return Error(E); 9616 } 9617 return true; 9618 } 9619 } 9620 9621 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9622 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9623 // member can be formed. 9624 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9625 } 9626 9627 //===----------------------------------------------------------------------===// 9628 // Record Evaluation 9629 //===----------------------------------------------------------------------===// 9630 9631 namespace { 9632 class RecordExprEvaluator 9633 : public ExprEvaluatorBase<RecordExprEvaluator> { 9634 const LValue &This; 9635 APValue &Result; 9636 public: 9637 9638 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9639 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9640 9641 bool Success(const APValue &V, const Expr *E) { 9642 Result = V; 9643 return true; 9644 } 9645 bool ZeroInitialization(const Expr *E) { 9646 return ZeroInitialization(E, E->getType()); 9647 } 9648 bool ZeroInitialization(const Expr *E, QualType T); 9649 9650 bool VisitCallExpr(const CallExpr *E) { 9651 return handleCallExpr(E, Result, &This); 9652 } 9653 bool VisitCastExpr(const CastExpr *E); 9654 bool VisitInitListExpr(const InitListExpr *E); 9655 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9656 return VisitCXXConstructExpr(E, E->getType()); 9657 } 9658 bool VisitLambdaExpr(const LambdaExpr *E); 9659 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9660 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9661 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9662 bool VisitBinCmp(const BinaryOperator *E); 9663 }; 9664 } 9665 9666 /// Perform zero-initialization on an object of non-union class type. 9667 /// C++11 [dcl.init]p5: 9668 /// To zero-initialize an object or reference of type T means: 9669 /// [...] 9670 /// -- if T is a (possibly cv-qualified) non-union class type, 9671 /// each non-static data member and each base-class subobject is 9672 /// zero-initialized 9673 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9674 const RecordDecl *RD, 9675 const LValue &This, APValue &Result) { 9676 assert(!RD->isUnion() && "Expected non-union class type"); 9677 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9678 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9679 std::distance(RD->field_begin(), RD->field_end())); 9680 9681 if (RD->isInvalidDecl()) return false; 9682 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9683 9684 if (CD) { 9685 unsigned Index = 0; 9686 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9687 End = CD->bases_end(); I != End; ++I, ++Index) { 9688 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9689 LValue Subobject = This; 9690 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9691 return false; 9692 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9693 Result.getStructBase(Index))) 9694 return false; 9695 } 9696 } 9697 9698 for (const auto *I : RD->fields()) { 9699 // -- if T is a reference type, no initialization is performed. 9700 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9701 continue; 9702 9703 LValue Subobject = This; 9704 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9705 return false; 9706 9707 ImplicitValueInitExpr VIE(I->getType()); 9708 if (!EvaluateInPlace( 9709 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9710 return false; 9711 } 9712 9713 return true; 9714 } 9715 9716 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9717 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9718 if (RD->isInvalidDecl()) return false; 9719 if (RD->isUnion()) { 9720 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9721 // object's first non-static named data member is zero-initialized 9722 RecordDecl::field_iterator I = RD->field_begin(); 9723 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9724 ++I; 9725 if (I == RD->field_end()) { 9726 Result = APValue((const FieldDecl*)nullptr); 9727 return true; 9728 } 9729 9730 LValue Subobject = This; 9731 if (!HandleLValueMember(Info, E, Subobject, *I)) 9732 return false; 9733 Result = APValue(*I); 9734 ImplicitValueInitExpr VIE(I->getType()); 9735 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9736 } 9737 9738 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9739 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9740 return false; 9741 } 9742 9743 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9744 } 9745 9746 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9747 switch (E->getCastKind()) { 9748 default: 9749 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9750 9751 case CK_ConstructorConversion: 9752 return Visit(E->getSubExpr()); 9753 9754 case CK_DerivedToBase: 9755 case CK_UncheckedDerivedToBase: { 9756 APValue DerivedObject; 9757 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9758 return false; 9759 if (!DerivedObject.isStruct()) 9760 return Error(E->getSubExpr()); 9761 9762 // Derived-to-base rvalue conversion: just slice off the derived part. 9763 APValue *Value = &DerivedObject; 9764 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9765 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9766 PathE = E->path_end(); PathI != PathE; ++PathI) { 9767 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9768 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9769 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9770 RD = Base; 9771 } 9772 Result = *Value; 9773 return true; 9774 } 9775 } 9776 } 9777 9778 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9779 if (E->isTransparent()) 9780 return Visit(E->getInit(0)); 9781 9782 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9783 if (RD->isInvalidDecl()) return false; 9784 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9785 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9786 9787 EvalInfo::EvaluatingConstructorRAII EvalObj( 9788 Info, 9789 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9790 CXXRD && CXXRD->getNumBases()); 9791 9792 if (RD->isUnion()) { 9793 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9794 Result = APValue(Field); 9795 if (!Field) 9796 return true; 9797 9798 // If the initializer list for a union does not contain any elements, the 9799 // first element of the union is value-initialized. 9800 // FIXME: The element should be initialized from an initializer list. 9801 // Is this difference ever observable for initializer lists which 9802 // we don't build? 9803 ImplicitValueInitExpr VIE(Field->getType()); 9804 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9805 9806 LValue Subobject = This; 9807 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9808 return false; 9809 9810 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9811 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9812 isa<CXXDefaultInitExpr>(InitExpr)); 9813 9814 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9815 } 9816 9817 if (!Result.hasValue()) 9818 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9819 std::distance(RD->field_begin(), RD->field_end())); 9820 unsigned ElementNo = 0; 9821 bool Success = true; 9822 9823 // Initialize base classes. 9824 if (CXXRD && CXXRD->getNumBases()) { 9825 for (const auto &Base : CXXRD->bases()) { 9826 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9827 const Expr *Init = E->getInit(ElementNo); 9828 9829 LValue Subobject = This; 9830 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9831 return false; 9832 9833 APValue &FieldVal = Result.getStructBase(ElementNo); 9834 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9835 if (!Info.noteFailure()) 9836 return false; 9837 Success = false; 9838 } 9839 ++ElementNo; 9840 } 9841 9842 EvalObj.finishedConstructingBases(); 9843 } 9844 9845 // Initialize members. 9846 for (const auto *Field : RD->fields()) { 9847 // Anonymous bit-fields are not considered members of the class for 9848 // purposes of aggregate initialization. 9849 if (Field->isUnnamedBitfield()) 9850 continue; 9851 9852 LValue Subobject = This; 9853 9854 bool HaveInit = ElementNo < E->getNumInits(); 9855 9856 // FIXME: Diagnostics here should point to the end of the initializer 9857 // list, not the start. 9858 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9859 Subobject, Field, &Layout)) 9860 return false; 9861 9862 // Perform an implicit value-initialization for members beyond the end of 9863 // the initializer list. 9864 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9865 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9866 9867 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9868 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9869 isa<CXXDefaultInitExpr>(Init)); 9870 9871 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9872 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9873 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9874 FieldVal, Field))) { 9875 if (!Info.noteFailure()) 9876 return false; 9877 Success = false; 9878 } 9879 } 9880 9881 EvalObj.finishedConstructingFields(); 9882 9883 return Success; 9884 } 9885 9886 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9887 QualType T) { 9888 // Note that E's type is not necessarily the type of our class here; we might 9889 // be initializing an array element instead. 9890 const CXXConstructorDecl *FD = E->getConstructor(); 9891 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9892 9893 bool ZeroInit = E->requiresZeroInitialization(); 9894 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9895 // If we've already performed zero-initialization, we're already done. 9896 if (Result.hasValue()) 9897 return true; 9898 9899 if (ZeroInit) 9900 return ZeroInitialization(E, T); 9901 9902 return getDefaultInitValue(T, Result); 9903 } 9904 9905 const FunctionDecl *Definition = nullptr; 9906 auto Body = FD->getBody(Definition); 9907 9908 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9909 return false; 9910 9911 // Avoid materializing a temporary for an elidable copy/move constructor. 9912 if (E->isElidable() && !ZeroInit) 9913 if (const MaterializeTemporaryExpr *ME 9914 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9915 return Visit(ME->getSubExpr()); 9916 9917 if (ZeroInit && !ZeroInitialization(E, T)) 9918 return false; 9919 9920 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9921 return HandleConstructorCall(E, This, Args, 9922 cast<CXXConstructorDecl>(Definition), Info, 9923 Result); 9924 } 9925 9926 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9927 const CXXInheritedCtorInitExpr *E) { 9928 if (!Info.CurrentCall) { 9929 assert(Info.checkingPotentialConstantExpression()); 9930 return false; 9931 } 9932 9933 const CXXConstructorDecl *FD = E->getConstructor(); 9934 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9935 return false; 9936 9937 const FunctionDecl *Definition = nullptr; 9938 auto Body = FD->getBody(Definition); 9939 9940 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9941 return false; 9942 9943 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9944 cast<CXXConstructorDecl>(Definition), Info, 9945 Result); 9946 } 9947 9948 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9949 const CXXStdInitializerListExpr *E) { 9950 const ConstantArrayType *ArrayType = 9951 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9952 9953 LValue Array; 9954 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9955 return false; 9956 9957 // Get a pointer to the first element of the array. 9958 Array.addArray(Info, E, ArrayType); 9959 9960 auto InvalidType = [&] { 9961 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9962 << E->getType(); 9963 return false; 9964 }; 9965 9966 // FIXME: Perform the checks on the field types in SemaInit. 9967 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9968 RecordDecl::field_iterator Field = Record->field_begin(); 9969 if (Field == Record->field_end()) 9970 return InvalidType(); 9971 9972 // Start pointer. 9973 if (!Field->getType()->isPointerType() || 9974 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9975 ArrayType->getElementType())) 9976 return InvalidType(); 9977 9978 // FIXME: What if the initializer_list type has base classes, etc? 9979 Result = APValue(APValue::UninitStruct(), 0, 2); 9980 Array.moveInto(Result.getStructField(0)); 9981 9982 if (++Field == Record->field_end()) 9983 return InvalidType(); 9984 9985 if (Field->getType()->isPointerType() && 9986 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9987 ArrayType->getElementType())) { 9988 // End pointer. 9989 if (!HandleLValueArrayAdjustment(Info, E, Array, 9990 ArrayType->getElementType(), 9991 ArrayType->getSize().getZExtValue())) 9992 return false; 9993 Array.moveInto(Result.getStructField(1)); 9994 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9995 // Length. 9996 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9997 else 9998 return InvalidType(); 9999 10000 if (++Field != Record->field_end()) 10001 return InvalidType(); 10002 10003 return true; 10004 } 10005 10006 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10007 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10008 if (ClosureClass->isInvalidDecl()) 10009 return false; 10010 10011 const size_t NumFields = 10012 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10013 10014 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10015 E->capture_init_end()) && 10016 "The number of lambda capture initializers should equal the number of " 10017 "fields within the closure type"); 10018 10019 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10020 // Iterate through all the lambda's closure object's fields and initialize 10021 // them. 10022 auto *CaptureInitIt = E->capture_init_begin(); 10023 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10024 bool Success = true; 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 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10036 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 10037 if (!Info.keepEvaluatingAfterFailure()) 10038 return false; 10039 Success = false; 10040 } 10041 ++CaptureIt; 10042 } 10043 return Success; 10044 } 10045 10046 static bool EvaluateRecord(const Expr *E, const LValue &This, 10047 APValue &Result, EvalInfo &Info) { 10048 assert(!E->isValueDependent()); 10049 assert(E->isRValue() && E->getType()->isRecordType() && 10050 "can't evaluate expression as a record rvalue"); 10051 return RecordExprEvaluator(Info, This, Result).Visit(E); 10052 } 10053 10054 //===----------------------------------------------------------------------===// 10055 // Temporary Evaluation 10056 // 10057 // Temporaries are represented in the AST as rvalues, but generally behave like 10058 // lvalues. The full-object of which the temporary is a subobject is implicitly 10059 // materialized so that a reference can bind to it. 10060 //===----------------------------------------------------------------------===// 10061 namespace { 10062 class TemporaryExprEvaluator 10063 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10064 public: 10065 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10066 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10067 10068 /// Visit an expression which constructs the value of this temporary. 10069 bool VisitConstructExpr(const Expr *E) { 10070 APValue &Value = Info.CurrentCall->createTemporary( 10071 E, E->getType(), ScopeKind::FullExpression, Result); 10072 return EvaluateInPlace(Value, Info, Result, E); 10073 } 10074 10075 bool VisitCastExpr(const CastExpr *E) { 10076 switch (E->getCastKind()) { 10077 default: 10078 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10079 10080 case CK_ConstructorConversion: 10081 return VisitConstructExpr(E->getSubExpr()); 10082 } 10083 } 10084 bool VisitInitListExpr(const InitListExpr *E) { 10085 return VisitConstructExpr(E); 10086 } 10087 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10088 return VisitConstructExpr(E); 10089 } 10090 bool VisitCallExpr(const CallExpr *E) { 10091 return VisitConstructExpr(E); 10092 } 10093 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10094 return VisitConstructExpr(E); 10095 } 10096 bool VisitLambdaExpr(const LambdaExpr *E) { 10097 return VisitConstructExpr(E); 10098 } 10099 }; 10100 } // end anonymous namespace 10101 10102 /// Evaluate an expression of record type as a temporary. 10103 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10104 assert(!E->isValueDependent()); 10105 assert(E->isRValue() && E->getType()->isRecordType()); 10106 return TemporaryExprEvaluator(Info, Result).Visit(E); 10107 } 10108 10109 //===----------------------------------------------------------------------===// 10110 // Vector Evaluation 10111 //===----------------------------------------------------------------------===// 10112 10113 namespace { 10114 class VectorExprEvaluator 10115 : public ExprEvaluatorBase<VectorExprEvaluator> { 10116 APValue &Result; 10117 public: 10118 10119 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10120 : ExprEvaluatorBaseTy(info), Result(Result) {} 10121 10122 bool Success(ArrayRef<APValue> V, const Expr *E) { 10123 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10124 // FIXME: remove this APValue copy. 10125 Result = APValue(V.data(), V.size()); 10126 return true; 10127 } 10128 bool Success(const APValue &V, const Expr *E) { 10129 assert(V.isVector()); 10130 Result = V; 10131 return true; 10132 } 10133 bool ZeroInitialization(const Expr *E); 10134 10135 bool VisitUnaryReal(const UnaryOperator *E) 10136 { return Visit(E->getSubExpr()); } 10137 bool VisitCastExpr(const CastExpr* E); 10138 bool VisitInitListExpr(const InitListExpr *E); 10139 bool VisitUnaryImag(const UnaryOperator *E); 10140 bool VisitBinaryOperator(const BinaryOperator *E); 10141 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10142 // conditional select), shufflevector, ExtVectorElementExpr 10143 }; 10144 } // end anonymous namespace 10145 10146 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10147 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 10148 return VectorExprEvaluator(Info, Result).Visit(E); 10149 } 10150 10151 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10152 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10153 unsigned NElts = VTy->getNumElements(); 10154 10155 const Expr *SE = E->getSubExpr(); 10156 QualType SETy = SE->getType(); 10157 10158 switch (E->getCastKind()) { 10159 case CK_VectorSplat: { 10160 APValue Val = APValue(); 10161 if (SETy->isIntegerType()) { 10162 APSInt IntResult; 10163 if (!EvaluateInteger(SE, IntResult, Info)) 10164 return false; 10165 Val = APValue(std::move(IntResult)); 10166 } else if (SETy->isRealFloatingType()) { 10167 APFloat FloatResult(0.0); 10168 if (!EvaluateFloat(SE, FloatResult, Info)) 10169 return false; 10170 Val = APValue(std::move(FloatResult)); 10171 } else { 10172 return Error(E); 10173 } 10174 10175 // Splat and create vector APValue. 10176 SmallVector<APValue, 4> Elts(NElts, Val); 10177 return Success(Elts, E); 10178 } 10179 case CK_BitCast: { 10180 // Evaluate the operand into an APInt we can extract from. 10181 llvm::APInt SValInt; 10182 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10183 return false; 10184 // Extract the elements 10185 QualType EltTy = VTy->getElementType(); 10186 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10187 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10188 SmallVector<APValue, 4> Elts; 10189 if (EltTy->isRealFloatingType()) { 10190 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10191 unsigned FloatEltSize = EltSize; 10192 if (&Sem == &APFloat::x87DoubleExtended()) 10193 FloatEltSize = 80; 10194 for (unsigned i = 0; i < NElts; i++) { 10195 llvm::APInt Elt; 10196 if (BigEndian) 10197 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10198 else 10199 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10200 Elts.push_back(APValue(APFloat(Sem, Elt))); 10201 } 10202 } else if (EltTy->isIntegerType()) { 10203 for (unsigned i = 0; i < NElts; i++) { 10204 llvm::APInt Elt; 10205 if (BigEndian) 10206 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10207 else 10208 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10209 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 10210 } 10211 } else { 10212 return Error(E); 10213 } 10214 return Success(Elts, E); 10215 } 10216 default: 10217 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10218 } 10219 } 10220 10221 bool 10222 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10223 const VectorType *VT = E->getType()->castAs<VectorType>(); 10224 unsigned NumInits = E->getNumInits(); 10225 unsigned NumElements = VT->getNumElements(); 10226 10227 QualType EltTy = VT->getElementType(); 10228 SmallVector<APValue, 4> Elements; 10229 10230 // The number of initializers can be less than the number of 10231 // vector elements. For OpenCL, this can be due to nested vector 10232 // initialization. For GCC compatibility, missing trailing elements 10233 // should be initialized with zeroes. 10234 unsigned CountInits = 0, CountElts = 0; 10235 while (CountElts < NumElements) { 10236 // Handle nested vector initialization. 10237 if (CountInits < NumInits 10238 && E->getInit(CountInits)->getType()->isVectorType()) { 10239 APValue v; 10240 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10241 return Error(E); 10242 unsigned vlen = v.getVectorLength(); 10243 for (unsigned j = 0; j < vlen; j++) 10244 Elements.push_back(v.getVectorElt(j)); 10245 CountElts += vlen; 10246 } else if (EltTy->isIntegerType()) { 10247 llvm::APSInt sInt(32); 10248 if (CountInits < NumInits) { 10249 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10250 return false; 10251 } else // trailing integer zero. 10252 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10253 Elements.push_back(APValue(sInt)); 10254 CountElts++; 10255 } else { 10256 llvm::APFloat f(0.0); 10257 if (CountInits < NumInits) { 10258 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10259 return false; 10260 } else // trailing float zero. 10261 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10262 Elements.push_back(APValue(f)); 10263 CountElts++; 10264 } 10265 CountInits++; 10266 } 10267 return Success(Elements, E); 10268 } 10269 10270 bool 10271 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10272 const auto *VT = E->getType()->castAs<VectorType>(); 10273 QualType EltTy = VT->getElementType(); 10274 APValue ZeroElement; 10275 if (EltTy->isIntegerType()) 10276 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10277 else 10278 ZeroElement = 10279 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10280 10281 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10282 return Success(Elements, E); 10283 } 10284 10285 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10286 VisitIgnoredValue(E->getSubExpr()); 10287 return ZeroInitialization(E); 10288 } 10289 10290 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10291 BinaryOperatorKind Op = E->getOpcode(); 10292 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10293 "Operation not supported on vector types"); 10294 10295 if (Op == BO_Comma) 10296 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10297 10298 Expr *LHS = E->getLHS(); 10299 Expr *RHS = E->getRHS(); 10300 10301 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10302 "Must both be vector types"); 10303 // Checking JUST the types are the same would be fine, except shifts don't 10304 // need to have their types be the same (since you always shift by an int). 10305 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10306 E->getType()->getAs<VectorType>()->getNumElements() && 10307 RHS->getType()->getAs<VectorType>()->getNumElements() == 10308 E->getType()->getAs<VectorType>()->getNumElements() && 10309 "All operands must be the same size."); 10310 10311 APValue LHSValue; 10312 APValue RHSValue; 10313 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10314 if (!LHSOK && !Info.noteFailure()) 10315 return false; 10316 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10317 return false; 10318 10319 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10320 return false; 10321 10322 return Success(LHSValue, E); 10323 } 10324 10325 //===----------------------------------------------------------------------===// 10326 // Array Evaluation 10327 //===----------------------------------------------------------------------===// 10328 10329 namespace { 10330 class ArrayExprEvaluator 10331 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10332 const LValue &This; 10333 APValue &Result; 10334 public: 10335 10336 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10337 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10338 10339 bool Success(const APValue &V, const Expr *E) { 10340 assert(V.isArray() && "expected array"); 10341 Result = V; 10342 return true; 10343 } 10344 10345 bool ZeroInitialization(const Expr *E) { 10346 const ConstantArrayType *CAT = 10347 Info.Ctx.getAsConstantArrayType(E->getType()); 10348 if (!CAT) { 10349 if (E->getType()->isIncompleteArrayType()) { 10350 // We can be asked to zero-initialize a flexible array member; this 10351 // is represented as an ImplicitValueInitExpr of incomplete array 10352 // type. In this case, the array has zero elements. 10353 Result = APValue(APValue::UninitArray(), 0, 0); 10354 return true; 10355 } 10356 // FIXME: We could handle VLAs here. 10357 return Error(E); 10358 } 10359 10360 Result = APValue(APValue::UninitArray(), 0, 10361 CAT->getSize().getZExtValue()); 10362 if (!Result.hasArrayFiller()) return true; 10363 10364 // Zero-initialize all elements. 10365 LValue Subobject = This; 10366 Subobject.addArray(Info, E, CAT); 10367 ImplicitValueInitExpr VIE(CAT->getElementType()); 10368 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10369 } 10370 10371 bool VisitCallExpr(const CallExpr *E) { 10372 return handleCallExpr(E, Result, &This); 10373 } 10374 bool VisitInitListExpr(const InitListExpr *E, 10375 QualType AllocType = QualType()); 10376 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10377 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10378 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10379 const LValue &Subobject, 10380 APValue *Value, QualType Type); 10381 bool VisitStringLiteral(const StringLiteral *E, 10382 QualType AllocType = QualType()) { 10383 expandStringLiteral(Info, E, Result, AllocType); 10384 return true; 10385 } 10386 }; 10387 } // end anonymous namespace 10388 10389 static bool EvaluateArray(const Expr *E, const LValue &This, 10390 APValue &Result, EvalInfo &Info) { 10391 assert(!E->isValueDependent()); 10392 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10393 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10394 } 10395 10396 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10397 APValue &Result, const InitListExpr *ILE, 10398 QualType AllocType) { 10399 assert(!ILE->isValueDependent()); 10400 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10401 "not an array rvalue"); 10402 return ArrayExprEvaluator(Info, This, Result) 10403 .VisitInitListExpr(ILE, AllocType); 10404 } 10405 10406 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10407 APValue &Result, 10408 const CXXConstructExpr *CCE, 10409 QualType AllocType) { 10410 assert(!CCE->isValueDependent()); 10411 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10412 "not an array rvalue"); 10413 return ArrayExprEvaluator(Info, This, Result) 10414 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10415 } 10416 10417 // Return true iff the given array filler may depend on the element index. 10418 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10419 // For now, just allow non-class value-initialization and initialization 10420 // lists comprised of them. 10421 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10422 return false; 10423 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10424 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10425 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10426 return true; 10427 } 10428 return false; 10429 } 10430 return true; 10431 } 10432 10433 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10434 QualType AllocType) { 10435 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10436 AllocType.isNull() ? E->getType() : AllocType); 10437 if (!CAT) 10438 return Error(E); 10439 10440 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10441 // an appropriately-typed string literal enclosed in braces. 10442 if (E->isStringLiteralInit()) { 10443 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10444 // FIXME: Support ObjCEncodeExpr here once we support it in 10445 // ArrayExprEvaluator generally. 10446 if (!SL) 10447 return Error(E); 10448 return VisitStringLiteral(SL, AllocType); 10449 } 10450 10451 bool Success = true; 10452 10453 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10454 "zero-initialized array shouldn't have any initialized elts"); 10455 APValue Filler; 10456 if (Result.isArray() && Result.hasArrayFiller()) 10457 Filler = Result.getArrayFiller(); 10458 10459 unsigned NumEltsToInit = E->getNumInits(); 10460 unsigned NumElts = CAT->getSize().getZExtValue(); 10461 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10462 10463 // If the initializer might depend on the array index, run it for each 10464 // array element. 10465 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10466 NumEltsToInit = NumElts; 10467 10468 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10469 << NumEltsToInit << ".\n"); 10470 10471 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10472 10473 // If the array was previously zero-initialized, preserve the 10474 // zero-initialized values. 10475 if (Filler.hasValue()) { 10476 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10477 Result.getArrayInitializedElt(I) = Filler; 10478 if (Result.hasArrayFiller()) 10479 Result.getArrayFiller() = Filler; 10480 } 10481 10482 LValue Subobject = This; 10483 Subobject.addArray(Info, E, CAT); 10484 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10485 const Expr *Init = 10486 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10487 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10488 Info, Subobject, Init) || 10489 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10490 CAT->getElementType(), 1)) { 10491 if (!Info.noteFailure()) 10492 return false; 10493 Success = false; 10494 } 10495 } 10496 10497 if (!Result.hasArrayFiller()) 10498 return Success; 10499 10500 // If we get here, we have a trivial filler, which we can just evaluate 10501 // once and splat over the rest of the array elements. 10502 assert(FillerExpr && "no array filler for incomplete init list"); 10503 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10504 FillerExpr) && Success; 10505 } 10506 10507 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10508 LValue CommonLV; 10509 if (E->getCommonExpr() && 10510 !Evaluate(Info.CurrentCall->createTemporary( 10511 E->getCommonExpr(), 10512 getStorageType(Info.Ctx, E->getCommonExpr()), 10513 ScopeKind::FullExpression, CommonLV), 10514 Info, E->getCommonExpr()->getSourceExpr())) 10515 return false; 10516 10517 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10518 10519 uint64_t Elements = CAT->getSize().getZExtValue(); 10520 Result = APValue(APValue::UninitArray(), Elements, Elements); 10521 10522 LValue Subobject = This; 10523 Subobject.addArray(Info, E, CAT); 10524 10525 bool Success = true; 10526 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10527 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10528 Info, Subobject, E->getSubExpr()) || 10529 !HandleLValueArrayAdjustment(Info, E, Subobject, 10530 CAT->getElementType(), 1)) { 10531 if (!Info.noteFailure()) 10532 return false; 10533 Success = false; 10534 } 10535 } 10536 10537 return Success; 10538 } 10539 10540 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10541 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10542 } 10543 10544 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10545 const LValue &Subobject, 10546 APValue *Value, 10547 QualType Type) { 10548 bool HadZeroInit = Value->hasValue(); 10549 10550 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10551 unsigned N = CAT->getSize().getZExtValue(); 10552 10553 // Preserve the array filler if we had prior zero-initialization. 10554 APValue Filler = 10555 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10556 : APValue(); 10557 10558 *Value = APValue(APValue::UninitArray(), N, N); 10559 10560 if (HadZeroInit) 10561 for (unsigned I = 0; I != N; ++I) 10562 Value->getArrayInitializedElt(I) = Filler; 10563 10564 // Initialize the elements. 10565 LValue ArrayElt = Subobject; 10566 ArrayElt.addArray(Info, E, CAT); 10567 for (unsigned I = 0; I != N; ++I) 10568 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10569 CAT->getElementType()) || 10570 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10571 CAT->getElementType(), 1)) 10572 return false; 10573 10574 return true; 10575 } 10576 10577 if (!Type->isRecordType()) 10578 return Error(E); 10579 10580 return RecordExprEvaluator(Info, Subobject, *Value) 10581 .VisitCXXConstructExpr(E, Type); 10582 } 10583 10584 //===----------------------------------------------------------------------===// 10585 // Integer Evaluation 10586 // 10587 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10588 // types and back in constant folding. Integer values are thus represented 10589 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10590 //===----------------------------------------------------------------------===// 10591 10592 namespace { 10593 class IntExprEvaluator 10594 : public ExprEvaluatorBase<IntExprEvaluator> { 10595 APValue &Result; 10596 public: 10597 IntExprEvaluator(EvalInfo &info, APValue &result) 10598 : ExprEvaluatorBaseTy(info), Result(result) {} 10599 10600 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10601 assert(E->getType()->isIntegralOrEnumerationType() && 10602 "Invalid evaluation result."); 10603 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10604 "Invalid evaluation result."); 10605 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10606 "Invalid evaluation result."); 10607 Result = APValue(SI); 10608 return true; 10609 } 10610 bool Success(const llvm::APSInt &SI, const Expr *E) { 10611 return Success(SI, E, Result); 10612 } 10613 10614 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10615 assert(E->getType()->isIntegralOrEnumerationType() && 10616 "Invalid evaluation result."); 10617 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10618 "Invalid evaluation result."); 10619 Result = APValue(APSInt(I)); 10620 Result.getInt().setIsUnsigned( 10621 E->getType()->isUnsignedIntegerOrEnumerationType()); 10622 return true; 10623 } 10624 bool Success(const llvm::APInt &I, const Expr *E) { 10625 return Success(I, E, Result); 10626 } 10627 10628 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10629 assert(E->getType()->isIntegralOrEnumerationType() && 10630 "Invalid evaluation result."); 10631 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10632 return true; 10633 } 10634 bool Success(uint64_t Value, const Expr *E) { 10635 return Success(Value, E, Result); 10636 } 10637 10638 bool Success(CharUnits Size, const Expr *E) { 10639 return Success(Size.getQuantity(), E); 10640 } 10641 10642 bool Success(const APValue &V, const Expr *E) { 10643 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10644 Result = V; 10645 return true; 10646 } 10647 return Success(V.getInt(), E); 10648 } 10649 10650 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10651 10652 //===--------------------------------------------------------------------===// 10653 // Visitor Methods 10654 //===--------------------------------------------------------------------===// 10655 10656 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10657 return Success(E->getValue(), E); 10658 } 10659 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10660 return Success(E->getValue(), E); 10661 } 10662 10663 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10664 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10665 if (CheckReferencedDecl(E, E->getDecl())) 10666 return true; 10667 10668 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10669 } 10670 bool VisitMemberExpr(const MemberExpr *E) { 10671 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10672 VisitIgnoredBaseExpression(E->getBase()); 10673 return true; 10674 } 10675 10676 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10677 } 10678 10679 bool VisitCallExpr(const CallExpr *E); 10680 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10681 bool VisitBinaryOperator(const BinaryOperator *E); 10682 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10683 bool VisitUnaryOperator(const UnaryOperator *E); 10684 10685 bool VisitCastExpr(const CastExpr* E); 10686 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10687 10688 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10689 return Success(E->getValue(), E); 10690 } 10691 10692 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10693 return Success(E->getValue(), E); 10694 } 10695 10696 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10697 if (Info.ArrayInitIndex == uint64_t(-1)) { 10698 // We were asked to evaluate this subexpression independent of the 10699 // enclosing ArrayInitLoopExpr. We can't do that. 10700 Info.FFDiag(E); 10701 return false; 10702 } 10703 return Success(Info.ArrayInitIndex, E); 10704 } 10705 10706 // Note, GNU defines __null as an integer, not a pointer. 10707 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10708 return ZeroInitialization(E); 10709 } 10710 10711 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10712 return Success(E->getValue(), E); 10713 } 10714 10715 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10716 return Success(E->getValue(), E); 10717 } 10718 10719 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10720 return Success(E->getValue(), E); 10721 } 10722 10723 bool VisitUnaryReal(const UnaryOperator *E); 10724 bool VisitUnaryImag(const UnaryOperator *E); 10725 10726 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10727 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10728 bool VisitSourceLocExpr(const SourceLocExpr *E); 10729 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10730 bool VisitRequiresExpr(const RequiresExpr *E); 10731 // FIXME: Missing: array subscript of vector, member of vector 10732 }; 10733 10734 class FixedPointExprEvaluator 10735 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10736 APValue &Result; 10737 10738 public: 10739 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10740 : ExprEvaluatorBaseTy(info), Result(result) {} 10741 10742 bool Success(const llvm::APInt &I, const Expr *E) { 10743 return Success( 10744 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10745 } 10746 10747 bool Success(uint64_t Value, const Expr *E) { 10748 return Success( 10749 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10750 } 10751 10752 bool Success(const APValue &V, const Expr *E) { 10753 return Success(V.getFixedPoint(), E); 10754 } 10755 10756 bool Success(const APFixedPoint &V, const Expr *E) { 10757 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10758 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10759 "Invalid evaluation result."); 10760 Result = APValue(V); 10761 return true; 10762 } 10763 10764 //===--------------------------------------------------------------------===// 10765 // Visitor Methods 10766 //===--------------------------------------------------------------------===// 10767 10768 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10769 return Success(E->getValue(), E); 10770 } 10771 10772 bool VisitCastExpr(const CastExpr *E); 10773 bool VisitUnaryOperator(const UnaryOperator *E); 10774 bool VisitBinaryOperator(const BinaryOperator *E); 10775 }; 10776 } // end anonymous namespace 10777 10778 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10779 /// produce either the integer value or a pointer. 10780 /// 10781 /// GCC has a heinous extension which folds casts between pointer types and 10782 /// pointer-sized integral types. We support this by allowing the evaluation of 10783 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10784 /// Some simple arithmetic on such values is supported (they are treated much 10785 /// like char*). 10786 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10787 EvalInfo &Info) { 10788 assert(!E->isValueDependent()); 10789 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10790 return IntExprEvaluator(Info, Result).Visit(E); 10791 } 10792 10793 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10794 assert(!E->isValueDependent()); 10795 APValue Val; 10796 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10797 return false; 10798 if (!Val.isInt()) { 10799 // FIXME: It would be better to produce the diagnostic for casting 10800 // a pointer to an integer. 10801 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10802 return false; 10803 } 10804 Result = Val.getInt(); 10805 return true; 10806 } 10807 10808 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10809 APValue Evaluated = E->EvaluateInContext( 10810 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10811 return Success(Evaluated, E); 10812 } 10813 10814 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10815 EvalInfo &Info) { 10816 assert(!E->isValueDependent()); 10817 if (E->getType()->isFixedPointType()) { 10818 APValue Val; 10819 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10820 return false; 10821 if (!Val.isFixedPoint()) 10822 return false; 10823 10824 Result = Val.getFixedPoint(); 10825 return true; 10826 } 10827 return false; 10828 } 10829 10830 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10831 EvalInfo &Info) { 10832 assert(!E->isValueDependent()); 10833 if (E->getType()->isIntegerType()) { 10834 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10835 APSInt Val; 10836 if (!EvaluateInteger(E, Val, Info)) 10837 return false; 10838 Result = APFixedPoint(Val, FXSema); 10839 return true; 10840 } else if (E->getType()->isFixedPointType()) { 10841 return EvaluateFixedPoint(E, Result, Info); 10842 } 10843 return false; 10844 } 10845 10846 /// Check whether the given declaration can be directly converted to an integral 10847 /// rvalue. If not, no diagnostic is produced; there are other things we can 10848 /// try. 10849 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10850 // Enums are integer constant exprs. 10851 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10852 // Check for signedness/width mismatches between E type and ECD value. 10853 bool SameSign = (ECD->getInitVal().isSigned() 10854 == E->getType()->isSignedIntegerOrEnumerationType()); 10855 bool SameWidth = (ECD->getInitVal().getBitWidth() 10856 == Info.Ctx.getIntWidth(E->getType())); 10857 if (SameSign && SameWidth) 10858 return Success(ECD->getInitVal(), E); 10859 else { 10860 // Get rid of mismatch (otherwise Success assertions will fail) 10861 // by computing a new value matching the type of E. 10862 llvm::APSInt Val = ECD->getInitVal(); 10863 if (!SameSign) 10864 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10865 if (!SameWidth) 10866 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10867 return Success(Val, E); 10868 } 10869 } 10870 return false; 10871 } 10872 10873 /// Values returned by __builtin_classify_type, chosen to match the values 10874 /// produced by GCC's builtin. 10875 enum class GCCTypeClass { 10876 None = -1, 10877 Void = 0, 10878 Integer = 1, 10879 // GCC reserves 2 for character types, but instead classifies them as 10880 // integers. 10881 Enum = 3, 10882 Bool = 4, 10883 Pointer = 5, 10884 // GCC reserves 6 for references, but appears to never use it (because 10885 // expressions never have reference type, presumably). 10886 PointerToDataMember = 7, 10887 RealFloat = 8, 10888 Complex = 9, 10889 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10890 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10891 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10892 // uses 12 for that purpose, same as for a class or struct. Maybe it 10893 // internally implements a pointer to member as a struct? Who knows. 10894 PointerToMemberFunction = 12, // Not a bug, see above. 10895 ClassOrStruct = 12, 10896 Union = 13, 10897 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10898 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10899 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10900 // literals. 10901 }; 10902 10903 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10904 /// as GCC. 10905 static GCCTypeClass 10906 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10907 assert(!T->isDependentType() && "unexpected dependent type"); 10908 10909 QualType CanTy = T.getCanonicalType(); 10910 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10911 10912 switch (CanTy->getTypeClass()) { 10913 #define TYPE(ID, BASE) 10914 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10915 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10916 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10917 #include "clang/AST/TypeNodes.inc" 10918 case Type::Auto: 10919 case Type::DeducedTemplateSpecialization: 10920 llvm_unreachable("unexpected non-canonical or dependent type"); 10921 10922 case Type::Builtin: 10923 switch (BT->getKind()) { 10924 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10925 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10926 case BuiltinType::ID: return GCCTypeClass::Integer; 10927 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10928 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10929 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10930 case BuiltinType::ID: break; 10931 #include "clang/AST/BuiltinTypes.def" 10932 case BuiltinType::Void: 10933 return GCCTypeClass::Void; 10934 10935 case BuiltinType::Bool: 10936 return GCCTypeClass::Bool; 10937 10938 case BuiltinType::Char_U: 10939 case BuiltinType::UChar: 10940 case BuiltinType::WChar_U: 10941 case BuiltinType::Char8: 10942 case BuiltinType::Char16: 10943 case BuiltinType::Char32: 10944 case BuiltinType::UShort: 10945 case BuiltinType::UInt: 10946 case BuiltinType::ULong: 10947 case BuiltinType::ULongLong: 10948 case BuiltinType::UInt128: 10949 return GCCTypeClass::Integer; 10950 10951 case BuiltinType::UShortAccum: 10952 case BuiltinType::UAccum: 10953 case BuiltinType::ULongAccum: 10954 case BuiltinType::UShortFract: 10955 case BuiltinType::UFract: 10956 case BuiltinType::ULongFract: 10957 case BuiltinType::SatUShortAccum: 10958 case BuiltinType::SatUAccum: 10959 case BuiltinType::SatULongAccum: 10960 case BuiltinType::SatUShortFract: 10961 case BuiltinType::SatUFract: 10962 case BuiltinType::SatULongFract: 10963 return GCCTypeClass::None; 10964 10965 case BuiltinType::NullPtr: 10966 10967 case BuiltinType::ObjCId: 10968 case BuiltinType::ObjCClass: 10969 case BuiltinType::ObjCSel: 10970 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10971 case BuiltinType::Id: 10972 #include "clang/Basic/OpenCLImageTypes.def" 10973 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10974 case BuiltinType::Id: 10975 #include "clang/Basic/OpenCLExtensionTypes.def" 10976 case BuiltinType::OCLSampler: 10977 case BuiltinType::OCLEvent: 10978 case BuiltinType::OCLClkEvent: 10979 case BuiltinType::OCLQueue: 10980 case BuiltinType::OCLReserveID: 10981 #define SVE_TYPE(Name, Id, SingletonId) \ 10982 case BuiltinType::Id: 10983 #include "clang/Basic/AArch64SVEACLETypes.def" 10984 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 10985 case BuiltinType::Id: 10986 #include "clang/Basic/PPCTypes.def" 10987 return GCCTypeClass::None; 10988 10989 case BuiltinType::Dependent: 10990 llvm_unreachable("unexpected dependent type"); 10991 }; 10992 llvm_unreachable("unexpected placeholder type"); 10993 10994 case Type::Enum: 10995 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10996 10997 case Type::Pointer: 10998 case Type::ConstantArray: 10999 case Type::VariableArray: 11000 case Type::IncompleteArray: 11001 case Type::FunctionNoProto: 11002 case Type::FunctionProto: 11003 return GCCTypeClass::Pointer; 11004 11005 case Type::MemberPointer: 11006 return CanTy->isMemberDataPointerType() 11007 ? GCCTypeClass::PointerToDataMember 11008 : GCCTypeClass::PointerToMemberFunction; 11009 11010 case Type::Complex: 11011 return GCCTypeClass::Complex; 11012 11013 case Type::Record: 11014 return CanTy->isUnionType() ? GCCTypeClass::Union 11015 : GCCTypeClass::ClassOrStruct; 11016 11017 case Type::Atomic: 11018 // GCC classifies _Atomic T the same as T. 11019 return EvaluateBuiltinClassifyType( 11020 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11021 11022 case Type::BlockPointer: 11023 case Type::Vector: 11024 case Type::ExtVector: 11025 case Type::ConstantMatrix: 11026 case Type::ObjCObject: 11027 case Type::ObjCInterface: 11028 case Type::ObjCObjectPointer: 11029 case Type::Pipe: 11030 case Type::ExtInt: 11031 // GCC classifies vectors as None. We follow its lead and classify all 11032 // other types that don't fit into the regular classification the same way. 11033 return GCCTypeClass::None; 11034 11035 case Type::LValueReference: 11036 case Type::RValueReference: 11037 llvm_unreachable("invalid type for expression"); 11038 } 11039 11040 llvm_unreachable("unexpected type class"); 11041 } 11042 11043 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11044 /// as GCC. 11045 static GCCTypeClass 11046 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11047 // If no argument was supplied, default to None. This isn't 11048 // ideal, however it is what gcc does. 11049 if (E->getNumArgs() == 0) 11050 return GCCTypeClass::None; 11051 11052 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11053 // being an ICE, but still folds it to a constant using the type of the first 11054 // argument. 11055 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11056 } 11057 11058 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11059 /// __builtin_constant_p when applied to the given pointer. 11060 /// 11061 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11062 /// or it points to the first character of a string literal. 11063 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11064 APValue::LValueBase Base = LV.getLValueBase(); 11065 if (Base.isNull()) { 11066 // A null base is acceptable. 11067 return true; 11068 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11069 if (!isa<StringLiteral>(E)) 11070 return false; 11071 return LV.getLValueOffset().isZero(); 11072 } else if (Base.is<TypeInfoLValue>()) { 11073 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11074 // evaluate to true. 11075 return true; 11076 } else { 11077 // Any other base is not constant enough for GCC. 11078 return false; 11079 } 11080 } 11081 11082 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11083 /// GCC as we can manage. 11084 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11085 // This evaluation is not permitted to have side-effects, so evaluate it in 11086 // a speculative evaluation context. 11087 SpeculativeEvaluationRAII SpeculativeEval(Info); 11088 11089 // Constant-folding is always enabled for the operand of __builtin_constant_p 11090 // (even when the enclosing evaluation context otherwise requires a strict 11091 // language-specific constant expression). 11092 FoldConstant Fold(Info, true); 11093 11094 QualType ArgType = Arg->getType(); 11095 11096 // __builtin_constant_p always has one operand. The rules which gcc follows 11097 // are not precisely documented, but are as follows: 11098 // 11099 // - If the operand is of integral, floating, complex or enumeration type, 11100 // and can be folded to a known value of that type, it returns 1. 11101 // - If the operand can be folded to a pointer to the first character 11102 // of a string literal (or such a pointer cast to an integral type) 11103 // or to a null pointer or an integer cast to a pointer, it returns 1. 11104 // 11105 // Otherwise, it returns 0. 11106 // 11107 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11108 // its support for this did not work prior to GCC 9 and is not yet well 11109 // understood. 11110 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11111 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11112 ArgType->isNullPtrType()) { 11113 APValue V; 11114 bool Dependent = false; 11115 if (!::EvaluateAsRValue(Info, Arg, V, Dependent) || 11116 Info.EvalStatus.HasSideEffects) { 11117 Fold.keepDiagnostics(); 11118 return false; 11119 } 11120 11121 // For a pointer (possibly cast to integer), there are special rules. 11122 if (V.getKind() == APValue::LValue) 11123 return EvaluateBuiltinConstantPForLValue(V); 11124 11125 // Otherwise, any constant value is good enough. 11126 return V.hasValue(); 11127 } 11128 11129 // Anything else isn't considered to be sufficiently constant. 11130 return false; 11131 } 11132 11133 /// Retrieves the "underlying object type" of the given expression, 11134 /// as used by __builtin_object_size. 11135 static QualType getObjectType(APValue::LValueBase B) { 11136 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11137 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11138 return VD->getType(); 11139 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11140 if (isa<CompoundLiteralExpr>(E)) 11141 return E->getType(); 11142 } else if (B.is<TypeInfoLValue>()) { 11143 return B.getTypeInfoType(); 11144 } else if (B.is<DynamicAllocLValue>()) { 11145 return B.getDynamicAllocType(); 11146 } 11147 11148 return QualType(); 11149 } 11150 11151 /// A more selective version of E->IgnoreParenCasts for 11152 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11153 /// to change the type of E. 11154 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11155 /// 11156 /// Always returns an RValue with a pointer representation. 11157 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11158 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 11159 11160 auto *NoParens = E->IgnoreParens(); 11161 auto *Cast = dyn_cast<CastExpr>(NoParens); 11162 if (Cast == nullptr) 11163 return NoParens; 11164 11165 // We only conservatively allow a few kinds of casts, because this code is 11166 // inherently a simple solution that seeks to support the common case. 11167 auto CastKind = Cast->getCastKind(); 11168 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11169 CastKind != CK_AddressSpaceConversion) 11170 return NoParens; 11171 11172 auto *SubExpr = Cast->getSubExpr(); 11173 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 11174 return NoParens; 11175 return ignorePointerCastsAndParens(SubExpr); 11176 } 11177 11178 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11179 /// record layout. e.g. 11180 /// struct { struct { int a, b; } fst, snd; } obj; 11181 /// obj.fst // no 11182 /// obj.snd // yes 11183 /// obj.fst.a // no 11184 /// obj.fst.b // no 11185 /// obj.snd.a // no 11186 /// obj.snd.b // yes 11187 /// 11188 /// Please note: this function is specialized for how __builtin_object_size 11189 /// views "objects". 11190 /// 11191 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11192 /// correct result, it will always return true. 11193 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11194 assert(!LVal.Designator.Invalid); 11195 11196 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11197 const RecordDecl *Parent = FD->getParent(); 11198 Invalid = Parent->isInvalidDecl(); 11199 if (Invalid || Parent->isUnion()) 11200 return true; 11201 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11202 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11203 }; 11204 11205 auto &Base = LVal.getLValueBase(); 11206 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11207 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11208 bool Invalid; 11209 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11210 return Invalid; 11211 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11212 for (auto *FD : IFD->chain()) { 11213 bool Invalid; 11214 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11215 return Invalid; 11216 } 11217 } 11218 } 11219 11220 unsigned I = 0; 11221 QualType BaseType = getType(Base); 11222 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11223 // If we don't know the array bound, conservatively assume we're looking at 11224 // the final array element. 11225 ++I; 11226 if (BaseType->isIncompleteArrayType()) 11227 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11228 else 11229 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11230 } 11231 11232 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11233 const auto &Entry = LVal.Designator.Entries[I]; 11234 if (BaseType->isArrayType()) { 11235 // Because __builtin_object_size treats arrays as objects, we can ignore 11236 // the index iff this is the last array in the Designator. 11237 if (I + 1 == E) 11238 return true; 11239 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11240 uint64_t Index = Entry.getAsArrayIndex(); 11241 if (Index + 1 != CAT->getSize()) 11242 return false; 11243 BaseType = CAT->getElementType(); 11244 } else if (BaseType->isAnyComplexType()) { 11245 const auto *CT = BaseType->castAs<ComplexType>(); 11246 uint64_t Index = Entry.getAsArrayIndex(); 11247 if (Index != 1) 11248 return false; 11249 BaseType = CT->getElementType(); 11250 } else if (auto *FD = getAsField(Entry)) { 11251 bool Invalid; 11252 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11253 return Invalid; 11254 BaseType = FD->getType(); 11255 } else { 11256 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11257 return false; 11258 } 11259 } 11260 return true; 11261 } 11262 11263 /// Tests to see if the LValue has a user-specified designator (that isn't 11264 /// necessarily valid). Note that this always returns 'true' if the LValue has 11265 /// an unsized array as its first designator entry, because there's currently no 11266 /// way to tell if the user typed *foo or foo[0]. 11267 static bool refersToCompleteObject(const LValue &LVal) { 11268 if (LVal.Designator.Invalid) 11269 return false; 11270 11271 if (!LVal.Designator.Entries.empty()) 11272 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11273 11274 if (!LVal.InvalidBase) 11275 return true; 11276 11277 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11278 // the LValueBase. 11279 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11280 return !E || !isa<MemberExpr>(E); 11281 } 11282 11283 /// Attempts to detect a user writing into a piece of memory that's impossible 11284 /// to figure out the size of by just using types. 11285 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11286 const SubobjectDesignator &Designator = LVal.Designator; 11287 // Notes: 11288 // - Users can only write off of the end when we have an invalid base. Invalid 11289 // bases imply we don't know where the memory came from. 11290 // - We used to be a bit more aggressive here; we'd only be conservative if 11291 // the array at the end was flexible, or if it had 0 or 1 elements. This 11292 // broke some common standard library extensions (PR30346), but was 11293 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11294 // with some sort of list. OTOH, it seems that GCC is always 11295 // conservative with the last element in structs (if it's an array), so our 11296 // current behavior is more compatible than an explicit list approach would 11297 // be. 11298 return LVal.InvalidBase && 11299 Designator.Entries.size() == Designator.MostDerivedPathLength && 11300 Designator.MostDerivedIsArrayElement && 11301 isDesignatorAtObjectEnd(Ctx, LVal); 11302 } 11303 11304 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11305 /// Fails if the conversion would cause loss of precision. 11306 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11307 CharUnits &Result) { 11308 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11309 if (Int.ugt(CharUnitsMax)) 11310 return false; 11311 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11312 return true; 11313 } 11314 11315 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11316 /// determine how many bytes exist from the beginning of the object to either 11317 /// the end of the current subobject, or the end of the object itself, depending 11318 /// on what the LValue looks like + the value of Type. 11319 /// 11320 /// If this returns false, the value of Result is undefined. 11321 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11322 unsigned Type, const LValue &LVal, 11323 CharUnits &EndOffset) { 11324 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11325 11326 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11327 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11328 return false; 11329 return HandleSizeof(Info, ExprLoc, Ty, Result); 11330 }; 11331 11332 // We want to evaluate the size of the entire object. This is a valid fallback 11333 // for when Type=1 and the designator is invalid, because we're asked for an 11334 // upper-bound. 11335 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11336 // Type=3 wants a lower bound, so we can't fall back to this. 11337 if (Type == 3 && !DetermineForCompleteObject) 11338 return false; 11339 11340 llvm::APInt APEndOffset; 11341 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11342 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11343 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11344 11345 if (LVal.InvalidBase) 11346 return false; 11347 11348 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11349 return CheckedHandleSizeof(BaseTy, EndOffset); 11350 } 11351 11352 // We want to evaluate the size of a subobject. 11353 const SubobjectDesignator &Designator = LVal.Designator; 11354 11355 // The following is a moderately common idiom in C: 11356 // 11357 // struct Foo { int a; char c[1]; }; 11358 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11359 // strcpy(&F->c[0], Bar); 11360 // 11361 // In order to not break too much legacy code, we need to support it. 11362 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11363 // If we can resolve this to an alloc_size call, we can hand that back, 11364 // because we know for certain how many bytes there are to write to. 11365 llvm::APInt APEndOffset; 11366 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11367 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11368 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11369 11370 // If we cannot determine the size of the initial allocation, then we can't 11371 // given an accurate upper-bound. However, we are still able to give 11372 // conservative lower-bounds for Type=3. 11373 if (Type == 1) 11374 return false; 11375 } 11376 11377 CharUnits BytesPerElem; 11378 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11379 return false; 11380 11381 // According to the GCC documentation, we want the size of the subobject 11382 // denoted by the pointer. But that's not quite right -- what we actually 11383 // want is the size of the immediately-enclosing array, if there is one. 11384 int64_t ElemsRemaining; 11385 if (Designator.MostDerivedIsArrayElement && 11386 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11387 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11388 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11389 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11390 } else { 11391 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11392 } 11393 11394 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11395 return true; 11396 } 11397 11398 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11399 /// returns true and stores the result in @p Size. 11400 /// 11401 /// If @p WasError is non-null, this will report whether the failure to evaluate 11402 /// is to be treated as an Error in IntExprEvaluator. 11403 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11404 EvalInfo &Info, uint64_t &Size) { 11405 // Determine the denoted object. 11406 LValue LVal; 11407 { 11408 // The operand of __builtin_object_size is never evaluated for side-effects. 11409 // If there are any, but we can determine the pointed-to object anyway, then 11410 // ignore the side-effects. 11411 SpeculativeEvaluationRAII SpeculativeEval(Info); 11412 IgnoreSideEffectsRAII Fold(Info); 11413 11414 if (E->isGLValue()) { 11415 // It's possible for us to be given GLValues if we're called via 11416 // Expr::tryEvaluateObjectSize. 11417 APValue RVal; 11418 bool Dependent = false; 11419 if (!EvaluateAsRValue(Info, E, RVal, Dependent)) 11420 return false; 11421 LVal.setFrom(Info.Ctx, RVal); 11422 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11423 /*InvalidBaseOK=*/true)) 11424 return false; 11425 } 11426 11427 // If we point outside of the object, there are no accessible bytes. 11428 if (LVal.getLValueOffset().isNegative() || 11429 ((Type & 1) && !LVal.Designator.isValidSubobject())) { 11430 Size = 0; 11431 return true; 11432 } 11433 11434 CharUnits EndOffset; 11435 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11436 return false; 11437 11438 // If we've fallen outside of the end offset, just pretend there's nothing to 11439 // write to/read from. 11440 if (EndOffset <= LVal.getLValueOffset()) 11441 Size = 0; 11442 else 11443 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11444 return true; 11445 } 11446 11447 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11448 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11449 return VisitBuiltinCallExpr(E, BuiltinOp); 11450 11451 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11452 } 11453 11454 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11455 APValue &Val, APSInt &Alignment) { 11456 QualType SrcTy = E->getArg(0)->getType(); 11457 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11458 return false; 11459 // Even though we are evaluating integer expressions we could get a pointer 11460 // argument for the __builtin_is_aligned() case. 11461 if (SrcTy->isPointerType()) { 11462 LValue Ptr; 11463 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11464 return false; 11465 Ptr.moveInto(Val); 11466 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11467 Info.FFDiag(E->getArg(0)); 11468 return false; 11469 } else { 11470 APSInt SrcInt; 11471 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11472 return false; 11473 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11474 "Bit widths must be the same"); 11475 Val = APValue(SrcInt); 11476 } 11477 assert(Val.hasValue()); 11478 return true; 11479 } 11480 11481 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11482 unsigned BuiltinOp) { 11483 switch (BuiltinOp) { 11484 default: 11485 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11486 11487 case Builtin::BI__builtin_dynamic_object_size: 11488 case Builtin::BI__builtin_object_size: { 11489 // The type was checked when we built the expression. 11490 unsigned Type = 11491 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11492 assert(Type <= 3 && "unexpected type"); 11493 11494 uint64_t Size; 11495 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11496 return Success(Size, E); 11497 11498 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11499 return Success((Type & 2) ? 0 : -1, E); 11500 11501 // Expression had no side effects, but we couldn't statically determine the 11502 // size of the referenced object. 11503 switch (Info.EvalMode) { 11504 case EvalInfo::EM_ConstantExpression: 11505 case EvalInfo::EM_ConstantFold: 11506 case EvalInfo::EM_IgnoreSideEffects: 11507 // Leave it to IR generation. 11508 return Error(E); 11509 case EvalInfo::EM_ConstantExpressionUnevaluated: 11510 // Reduce it to a constant now. 11511 return Success((Type & 2) ? 0 : -1, E); 11512 } 11513 11514 llvm_unreachable("unexpected EvalMode"); 11515 } 11516 11517 case Builtin::BI__builtin_os_log_format_buffer_size: { 11518 analyze_os_log::OSLogBufferLayout Layout; 11519 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11520 return Success(Layout.size().getQuantity(), E); 11521 } 11522 11523 case Builtin::BI__builtin_is_aligned: { 11524 APValue Src; 11525 APSInt Alignment; 11526 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11527 return false; 11528 if (Src.isLValue()) { 11529 // If we evaluated a pointer, check the minimum known alignment. 11530 LValue Ptr; 11531 Ptr.setFrom(Info.Ctx, Src); 11532 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11533 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11534 // We can return true if the known alignment at the computed offset is 11535 // greater than the requested alignment. 11536 assert(PtrAlign.isPowerOfTwo()); 11537 assert(Alignment.isPowerOf2()); 11538 if (PtrAlign.getQuantity() >= Alignment) 11539 return Success(1, E); 11540 // If the alignment is not known to be sufficient, some cases could still 11541 // be aligned at run time. However, if the requested alignment is less or 11542 // equal to the base alignment and the offset is not aligned, we know that 11543 // the run-time value can never be aligned. 11544 if (BaseAlignment.getQuantity() >= Alignment && 11545 PtrAlign.getQuantity() < Alignment) 11546 return Success(0, E); 11547 // Otherwise we can't infer whether the value is sufficiently aligned. 11548 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11549 // in cases where we can't fully evaluate the pointer. 11550 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11551 << Alignment; 11552 return false; 11553 } 11554 assert(Src.isInt()); 11555 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11556 } 11557 case Builtin::BI__builtin_align_up: { 11558 APValue Src; 11559 APSInt Alignment; 11560 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11561 return false; 11562 if (!Src.isInt()) 11563 return Error(E); 11564 APSInt AlignedVal = 11565 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11566 Src.getInt().isUnsigned()); 11567 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11568 return Success(AlignedVal, E); 11569 } 11570 case Builtin::BI__builtin_align_down: { 11571 APValue Src; 11572 APSInt Alignment; 11573 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11574 return false; 11575 if (!Src.isInt()) 11576 return Error(E); 11577 APSInt AlignedVal = 11578 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11579 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11580 return Success(AlignedVal, E); 11581 } 11582 11583 case Builtin::BI__builtin_bitreverse8: 11584 case Builtin::BI__builtin_bitreverse16: 11585 case Builtin::BI__builtin_bitreverse32: 11586 case Builtin::BI__builtin_bitreverse64: { 11587 APSInt Val; 11588 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11589 return false; 11590 11591 return Success(Val.reverseBits(), E); 11592 } 11593 11594 case Builtin::BI__builtin_bswap16: 11595 case Builtin::BI__builtin_bswap32: 11596 case Builtin::BI__builtin_bswap64: { 11597 APSInt Val; 11598 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11599 return false; 11600 11601 return Success(Val.byteSwap(), E); 11602 } 11603 11604 case Builtin::BI__builtin_classify_type: 11605 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11606 11607 case Builtin::BI__builtin_clrsb: 11608 case Builtin::BI__builtin_clrsbl: 11609 case Builtin::BI__builtin_clrsbll: { 11610 APSInt Val; 11611 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11612 return false; 11613 11614 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11615 } 11616 11617 case Builtin::BI__builtin_clz: 11618 case Builtin::BI__builtin_clzl: 11619 case Builtin::BI__builtin_clzll: 11620 case Builtin::BI__builtin_clzs: { 11621 APSInt Val; 11622 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11623 return false; 11624 if (!Val) 11625 return Error(E); 11626 11627 return Success(Val.countLeadingZeros(), E); 11628 } 11629 11630 case Builtin::BI__builtin_constant_p: { 11631 const Expr *Arg = E->getArg(0); 11632 if (EvaluateBuiltinConstantP(Info, Arg)) 11633 return Success(true, E); 11634 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11635 // Outside a constant context, eagerly evaluate to false in the presence 11636 // of side-effects in order to avoid -Wunsequenced false-positives in 11637 // a branch on __builtin_constant_p(expr). 11638 return Success(false, E); 11639 } 11640 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11641 return false; 11642 } 11643 11644 case Builtin::BI__builtin_is_constant_evaluated: { 11645 const auto *Callee = Info.CurrentCall->getCallee(); 11646 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11647 (Info.CallStackDepth == 1 || 11648 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11649 Callee->getIdentifier() && 11650 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11651 // FIXME: Find a better way to avoid duplicated diagnostics. 11652 if (Info.EvalStatus.Diag) 11653 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11654 : Info.CurrentCall->CallLoc, 11655 diag::warn_is_constant_evaluated_always_true_constexpr) 11656 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11657 : "std::is_constant_evaluated"); 11658 } 11659 11660 return Success(Info.InConstantContext, E); 11661 } 11662 11663 case Builtin::BI__builtin_ctz: 11664 case Builtin::BI__builtin_ctzl: 11665 case Builtin::BI__builtin_ctzll: 11666 case Builtin::BI__builtin_ctzs: { 11667 APSInt Val; 11668 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11669 return false; 11670 if (!Val) 11671 return Error(E); 11672 11673 return Success(Val.countTrailingZeros(), E); 11674 } 11675 11676 case Builtin::BI__builtin_eh_return_data_regno: { 11677 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11678 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11679 return Success(Operand, E); 11680 } 11681 11682 case Builtin::BI__builtin_expect: 11683 case Builtin::BI__builtin_expect_with_probability: 11684 return Visit(E->getArg(0)); 11685 11686 case Builtin::BI__builtin_ffs: 11687 case Builtin::BI__builtin_ffsl: 11688 case Builtin::BI__builtin_ffsll: { 11689 APSInt Val; 11690 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11691 return false; 11692 11693 unsigned N = Val.countTrailingZeros(); 11694 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11695 } 11696 11697 case Builtin::BI__builtin_fpclassify: { 11698 APFloat Val(0.0); 11699 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11700 return false; 11701 unsigned Arg; 11702 switch (Val.getCategory()) { 11703 case APFloat::fcNaN: Arg = 0; break; 11704 case APFloat::fcInfinity: Arg = 1; break; 11705 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11706 case APFloat::fcZero: Arg = 4; break; 11707 } 11708 return Visit(E->getArg(Arg)); 11709 } 11710 11711 case Builtin::BI__builtin_isinf_sign: { 11712 APFloat Val(0.0); 11713 return EvaluateFloat(E->getArg(0), Val, Info) && 11714 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11715 } 11716 11717 case Builtin::BI__builtin_isinf: { 11718 APFloat Val(0.0); 11719 return EvaluateFloat(E->getArg(0), Val, Info) && 11720 Success(Val.isInfinity() ? 1 : 0, E); 11721 } 11722 11723 case Builtin::BI__builtin_isfinite: { 11724 APFloat Val(0.0); 11725 return EvaluateFloat(E->getArg(0), Val, Info) && 11726 Success(Val.isFinite() ? 1 : 0, E); 11727 } 11728 11729 case Builtin::BI__builtin_isnan: { 11730 APFloat Val(0.0); 11731 return EvaluateFloat(E->getArg(0), Val, Info) && 11732 Success(Val.isNaN() ? 1 : 0, E); 11733 } 11734 11735 case Builtin::BI__builtin_isnormal: { 11736 APFloat Val(0.0); 11737 return EvaluateFloat(E->getArg(0), Val, Info) && 11738 Success(Val.isNormal() ? 1 : 0, E); 11739 } 11740 11741 case Builtin::BI__builtin_parity: 11742 case Builtin::BI__builtin_parityl: 11743 case Builtin::BI__builtin_parityll: { 11744 APSInt Val; 11745 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11746 return false; 11747 11748 return Success(Val.countPopulation() % 2, E); 11749 } 11750 11751 case Builtin::BI__builtin_popcount: 11752 case Builtin::BI__builtin_popcountl: 11753 case Builtin::BI__builtin_popcountll: { 11754 APSInt Val; 11755 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11756 return false; 11757 11758 return Success(Val.countPopulation(), E); 11759 } 11760 11761 case Builtin::BI__builtin_rotateleft8: 11762 case Builtin::BI__builtin_rotateleft16: 11763 case Builtin::BI__builtin_rotateleft32: 11764 case Builtin::BI__builtin_rotateleft64: 11765 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11766 case Builtin::BI_rotl16: 11767 case Builtin::BI_rotl: 11768 case Builtin::BI_lrotl: 11769 case Builtin::BI_rotl64: { 11770 APSInt Val, Amt; 11771 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11772 !EvaluateInteger(E->getArg(1), Amt, Info)) 11773 return false; 11774 11775 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11776 } 11777 11778 case Builtin::BI__builtin_rotateright8: 11779 case Builtin::BI__builtin_rotateright16: 11780 case Builtin::BI__builtin_rotateright32: 11781 case Builtin::BI__builtin_rotateright64: 11782 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11783 case Builtin::BI_rotr16: 11784 case Builtin::BI_rotr: 11785 case Builtin::BI_lrotr: 11786 case Builtin::BI_rotr64: { 11787 APSInt Val, Amt; 11788 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11789 !EvaluateInteger(E->getArg(1), Amt, Info)) 11790 return false; 11791 11792 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11793 } 11794 11795 case Builtin::BIstrlen: 11796 case Builtin::BIwcslen: 11797 // A call to strlen is not a constant expression. 11798 if (Info.getLangOpts().CPlusPlus11) 11799 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11800 << /*isConstexpr*/0 << /*isConstructor*/0 11801 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11802 else 11803 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11804 LLVM_FALLTHROUGH; 11805 case Builtin::BI__builtin_strlen: 11806 case Builtin::BI__builtin_wcslen: { 11807 // As an extension, we support __builtin_strlen() as a constant expression, 11808 // and support folding strlen() to a constant. 11809 LValue String; 11810 if (!EvaluatePointer(E->getArg(0), String, Info)) 11811 return false; 11812 11813 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11814 11815 // Fast path: if it's a string literal, search the string value. 11816 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11817 String.getLValueBase().dyn_cast<const Expr *>())) { 11818 // The string literal may have embedded null characters. Find the first 11819 // one and truncate there. 11820 StringRef Str = S->getBytes(); 11821 int64_t Off = String.Offset.getQuantity(); 11822 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11823 S->getCharByteWidth() == 1 && 11824 // FIXME: Add fast-path for wchar_t too. 11825 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11826 Str = Str.substr(Off); 11827 11828 StringRef::size_type Pos = Str.find(0); 11829 if (Pos != StringRef::npos) 11830 Str = Str.substr(0, Pos); 11831 11832 return Success(Str.size(), E); 11833 } 11834 11835 // Fall through to slow path to issue appropriate diagnostic. 11836 } 11837 11838 // Slow path: scan the bytes of the string looking for the terminating 0. 11839 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11840 APValue Char; 11841 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11842 !Char.isInt()) 11843 return false; 11844 if (!Char.getInt()) 11845 return Success(Strlen, E); 11846 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11847 return false; 11848 } 11849 } 11850 11851 case Builtin::BIstrcmp: 11852 case Builtin::BIwcscmp: 11853 case Builtin::BIstrncmp: 11854 case Builtin::BIwcsncmp: 11855 case Builtin::BImemcmp: 11856 case Builtin::BIbcmp: 11857 case Builtin::BIwmemcmp: 11858 // A call to strlen is not a constant expression. 11859 if (Info.getLangOpts().CPlusPlus11) 11860 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11861 << /*isConstexpr*/0 << /*isConstructor*/0 11862 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11863 else 11864 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11865 LLVM_FALLTHROUGH; 11866 case Builtin::BI__builtin_strcmp: 11867 case Builtin::BI__builtin_wcscmp: 11868 case Builtin::BI__builtin_strncmp: 11869 case Builtin::BI__builtin_wcsncmp: 11870 case Builtin::BI__builtin_memcmp: 11871 case Builtin::BI__builtin_bcmp: 11872 case Builtin::BI__builtin_wmemcmp: { 11873 LValue String1, String2; 11874 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11875 !EvaluatePointer(E->getArg(1), String2, Info)) 11876 return false; 11877 11878 uint64_t MaxLength = uint64_t(-1); 11879 if (BuiltinOp != Builtin::BIstrcmp && 11880 BuiltinOp != Builtin::BIwcscmp && 11881 BuiltinOp != Builtin::BI__builtin_strcmp && 11882 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11883 APSInt N; 11884 if (!EvaluateInteger(E->getArg(2), N, Info)) 11885 return false; 11886 MaxLength = N.getExtValue(); 11887 } 11888 11889 // Empty substrings compare equal by definition. 11890 if (MaxLength == 0u) 11891 return Success(0, E); 11892 11893 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11894 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11895 String1.Designator.Invalid || String2.Designator.Invalid) 11896 return false; 11897 11898 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11899 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11900 11901 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11902 BuiltinOp == Builtin::BIbcmp || 11903 BuiltinOp == Builtin::BI__builtin_memcmp || 11904 BuiltinOp == Builtin::BI__builtin_bcmp; 11905 11906 assert(IsRawByte || 11907 (Info.Ctx.hasSameUnqualifiedType( 11908 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11909 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11910 11911 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11912 // 'char8_t', but no other types. 11913 if (IsRawByte && 11914 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11915 // FIXME: Consider using our bit_cast implementation to support this. 11916 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11917 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11918 << CharTy1 << CharTy2; 11919 return false; 11920 } 11921 11922 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11923 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11924 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11925 Char1.isInt() && Char2.isInt(); 11926 }; 11927 const auto &AdvanceElems = [&] { 11928 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11929 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11930 }; 11931 11932 bool StopAtNull = 11933 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11934 BuiltinOp != Builtin::BIwmemcmp && 11935 BuiltinOp != Builtin::BI__builtin_memcmp && 11936 BuiltinOp != Builtin::BI__builtin_bcmp && 11937 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11938 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11939 BuiltinOp == Builtin::BIwcsncmp || 11940 BuiltinOp == Builtin::BIwmemcmp || 11941 BuiltinOp == Builtin::BI__builtin_wcscmp || 11942 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11943 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11944 11945 for (; MaxLength; --MaxLength) { 11946 APValue Char1, Char2; 11947 if (!ReadCurElems(Char1, Char2)) 11948 return false; 11949 if (Char1.getInt().ne(Char2.getInt())) { 11950 if (IsWide) // wmemcmp compares with wchar_t signedness. 11951 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11952 // memcmp always compares unsigned chars. 11953 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11954 } 11955 if (StopAtNull && !Char1.getInt()) 11956 return Success(0, E); 11957 assert(!(StopAtNull && !Char2.getInt())); 11958 if (!AdvanceElems()) 11959 return false; 11960 } 11961 // We hit the strncmp / memcmp limit. 11962 return Success(0, E); 11963 } 11964 11965 case Builtin::BI__atomic_always_lock_free: 11966 case Builtin::BI__atomic_is_lock_free: 11967 case Builtin::BI__c11_atomic_is_lock_free: { 11968 APSInt SizeVal; 11969 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11970 return false; 11971 11972 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11973 // of two less than or equal to the maximum inline atomic width, we know it 11974 // is lock-free. If the size isn't a power of two, or greater than the 11975 // maximum alignment where we promote atomics, we know it is not lock-free 11976 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11977 // the answer can only be determined at runtime; for example, 16-byte 11978 // atomics have lock-free implementations on some, but not all, 11979 // x86-64 processors. 11980 11981 // Check power-of-two. 11982 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11983 if (Size.isPowerOfTwo()) { 11984 // Check against inlining width. 11985 unsigned InlineWidthBits = 11986 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11987 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11988 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11989 Size == CharUnits::One() || 11990 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11991 Expr::NPC_NeverValueDependent)) 11992 // OK, we will inline appropriately-aligned operations of this size, 11993 // and _Atomic(T) is appropriately-aligned. 11994 return Success(1, E); 11995 11996 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11997 castAs<PointerType>()->getPointeeType(); 11998 if (!PointeeType->isIncompleteType() && 11999 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12000 // OK, we will inline operations on this object. 12001 return Success(1, E); 12002 } 12003 } 12004 } 12005 12006 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12007 Success(0, E) : Error(E); 12008 } 12009 case Builtin::BIomp_is_initial_device: 12010 // We can decide statically which value the runtime would return if called. 12011 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 12012 case Builtin::BI__builtin_add_overflow: 12013 case Builtin::BI__builtin_sub_overflow: 12014 case Builtin::BI__builtin_mul_overflow: 12015 case Builtin::BI__builtin_sadd_overflow: 12016 case Builtin::BI__builtin_uadd_overflow: 12017 case Builtin::BI__builtin_uaddl_overflow: 12018 case Builtin::BI__builtin_uaddll_overflow: 12019 case Builtin::BI__builtin_usub_overflow: 12020 case Builtin::BI__builtin_usubl_overflow: 12021 case Builtin::BI__builtin_usubll_overflow: 12022 case Builtin::BI__builtin_umul_overflow: 12023 case Builtin::BI__builtin_umull_overflow: 12024 case Builtin::BI__builtin_umulll_overflow: 12025 case Builtin::BI__builtin_saddl_overflow: 12026 case Builtin::BI__builtin_saddll_overflow: 12027 case Builtin::BI__builtin_ssub_overflow: 12028 case Builtin::BI__builtin_ssubl_overflow: 12029 case Builtin::BI__builtin_ssubll_overflow: 12030 case Builtin::BI__builtin_smul_overflow: 12031 case Builtin::BI__builtin_smull_overflow: 12032 case Builtin::BI__builtin_smulll_overflow: { 12033 LValue ResultLValue; 12034 APSInt LHS, RHS; 12035 12036 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12037 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12038 !EvaluateInteger(E->getArg(1), RHS, Info) || 12039 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12040 return false; 12041 12042 APSInt Result; 12043 bool DidOverflow = false; 12044 12045 // If the types don't have to match, enlarge all 3 to the largest of them. 12046 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12047 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12048 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12049 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12050 ResultType->isSignedIntegerOrEnumerationType(); 12051 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12052 ResultType->isSignedIntegerOrEnumerationType(); 12053 uint64_t LHSSize = LHS.getBitWidth(); 12054 uint64_t RHSSize = RHS.getBitWidth(); 12055 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12056 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12057 12058 // Add an additional bit if the signedness isn't uniformly agreed to. We 12059 // could do this ONLY if there is a signed and an unsigned that both have 12060 // MaxBits, but the code to check that is pretty nasty. The issue will be 12061 // caught in the shrink-to-result later anyway. 12062 if (IsSigned && !AllSigned) 12063 ++MaxBits; 12064 12065 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12066 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12067 Result = APSInt(MaxBits, !IsSigned); 12068 } 12069 12070 // Find largest int. 12071 switch (BuiltinOp) { 12072 default: 12073 llvm_unreachable("Invalid value for BuiltinOp"); 12074 case Builtin::BI__builtin_add_overflow: 12075 case Builtin::BI__builtin_sadd_overflow: 12076 case Builtin::BI__builtin_saddl_overflow: 12077 case Builtin::BI__builtin_saddll_overflow: 12078 case Builtin::BI__builtin_uadd_overflow: 12079 case Builtin::BI__builtin_uaddl_overflow: 12080 case Builtin::BI__builtin_uaddll_overflow: 12081 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12082 : LHS.uadd_ov(RHS, DidOverflow); 12083 break; 12084 case Builtin::BI__builtin_sub_overflow: 12085 case Builtin::BI__builtin_ssub_overflow: 12086 case Builtin::BI__builtin_ssubl_overflow: 12087 case Builtin::BI__builtin_ssubll_overflow: 12088 case Builtin::BI__builtin_usub_overflow: 12089 case Builtin::BI__builtin_usubl_overflow: 12090 case Builtin::BI__builtin_usubll_overflow: 12091 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12092 : LHS.usub_ov(RHS, DidOverflow); 12093 break; 12094 case Builtin::BI__builtin_mul_overflow: 12095 case Builtin::BI__builtin_smul_overflow: 12096 case Builtin::BI__builtin_smull_overflow: 12097 case Builtin::BI__builtin_smulll_overflow: 12098 case Builtin::BI__builtin_umul_overflow: 12099 case Builtin::BI__builtin_umull_overflow: 12100 case Builtin::BI__builtin_umulll_overflow: 12101 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12102 : LHS.umul_ov(RHS, DidOverflow); 12103 break; 12104 } 12105 12106 // In the case where multiple sizes are allowed, truncate and see if 12107 // the values are the same. 12108 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12109 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12110 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12111 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12112 // since it will give us the behavior of a TruncOrSelf in the case where 12113 // its parameter <= its size. We previously set Result to be at least the 12114 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12115 // will work exactly like TruncOrSelf. 12116 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12117 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12118 12119 if (!APSInt::isSameValue(Temp, Result)) 12120 DidOverflow = true; 12121 Result = Temp; 12122 } 12123 12124 APValue APV{Result}; 12125 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12126 return false; 12127 return Success(DidOverflow, E); 12128 } 12129 } 12130 } 12131 12132 /// Determine whether this is a pointer past the end of the complete 12133 /// object referred to by the lvalue. 12134 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12135 const LValue &LV) { 12136 // A null pointer can be viewed as being "past the end" but we don't 12137 // choose to look at it that way here. 12138 if (!LV.getLValueBase()) 12139 return false; 12140 12141 // If the designator is valid and refers to a subobject, we're not pointing 12142 // past the end. 12143 if (!LV.getLValueDesignator().Invalid && 12144 !LV.getLValueDesignator().isOnePastTheEnd()) 12145 return false; 12146 12147 // A pointer to an incomplete type might be past-the-end if the type's size is 12148 // zero. We cannot tell because the type is incomplete. 12149 QualType Ty = getType(LV.getLValueBase()); 12150 if (Ty->isIncompleteType()) 12151 return true; 12152 12153 // We're a past-the-end pointer if we point to the byte after the object, 12154 // no matter what our type or path is. 12155 auto Size = Ctx.getTypeSizeInChars(Ty); 12156 return LV.getLValueOffset() == Size; 12157 } 12158 12159 namespace { 12160 12161 /// Data recursive integer evaluator of certain binary operators. 12162 /// 12163 /// We use a data recursive algorithm for binary operators so that we are able 12164 /// to handle extreme cases of chained binary operators without causing stack 12165 /// overflow. 12166 class DataRecursiveIntBinOpEvaluator { 12167 struct EvalResult { 12168 APValue Val; 12169 bool Failed; 12170 12171 EvalResult() : Failed(false) { } 12172 12173 void swap(EvalResult &RHS) { 12174 Val.swap(RHS.Val); 12175 Failed = RHS.Failed; 12176 RHS.Failed = false; 12177 } 12178 }; 12179 12180 struct Job { 12181 const Expr *E; 12182 EvalResult LHSResult; // meaningful only for binary operator expression. 12183 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12184 12185 Job() = default; 12186 Job(Job &&) = default; 12187 12188 void startSpeculativeEval(EvalInfo &Info) { 12189 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12190 } 12191 12192 private: 12193 SpeculativeEvaluationRAII SpecEvalRAII; 12194 }; 12195 12196 SmallVector<Job, 16> Queue; 12197 12198 IntExprEvaluator &IntEval; 12199 EvalInfo &Info; 12200 APValue &FinalResult; 12201 12202 public: 12203 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12204 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12205 12206 /// True if \param E is a binary operator that we are going to handle 12207 /// data recursively. 12208 /// We handle binary operators that are comma, logical, or that have operands 12209 /// with integral or enumeration type. 12210 static bool shouldEnqueue(const BinaryOperator *E) { 12211 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12212 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 12213 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12214 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12215 } 12216 12217 bool Traverse(const BinaryOperator *E) { 12218 enqueue(E); 12219 EvalResult PrevResult; 12220 while (!Queue.empty()) 12221 process(PrevResult); 12222 12223 if (PrevResult.Failed) return false; 12224 12225 FinalResult.swap(PrevResult.Val); 12226 return true; 12227 } 12228 12229 private: 12230 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12231 return IntEval.Success(Value, E, Result); 12232 } 12233 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12234 return IntEval.Success(Value, E, Result); 12235 } 12236 bool Error(const Expr *E) { 12237 return IntEval.Error(E); 12238 } 12239 bool Error(const Expr *E, diag::kind D) { 12240 return IntEval.Error(E, D); 12241 } 12242 12243 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12244 return Info.CCEDiag(E, D); 12245 } 12246 12247 // Returns true if visiting the RHS is necessary, false otherwise. 12248 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12249 bool &SuppressRHSDiags); 12250 12251 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12252 const BinaryOperator *E, APValue &Result); 12253 12254 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12255 Result.Failed = !Evaluate(Result.Val, Info, E); 12256 if (Result.Failed) 12257 Result.Val = APValue(); 12258 } 12259 12260 void process(EvalResult &Result); 12261 12262 void enqueue(const Expr *E) { 12263 E = E->IgnoreParens(); 12264 Queue.resize(Queue.size()+1); 12265 Queue.back().E = E; 12266 Queue.back().Kind = Job::AnyExprKind; 12267 } 12268 }; 12269 12270 } 12271 12272 bool DataRecursiveIntBinOpEvaluator:: 12273 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12274 bool &SuppressRHSDiags) { 12275 if (E->getOpcode() == BO_Comma) { 12276 // Ignore LHS but note if we could not evaluate it. 12277 if (LHSResult.Failed) 12278 return Info.noteSideEffect(); 12279 return true; 12280 } 12281 12282 if (E->isLogicalOp()) { 12283 bool LHSAsBool; 12284 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12285 // We were able to evaluate the LHS, see if we can get away with not 12286 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12287 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12288 Success(LHSAsBool, E, LHSResult.Val); 12289 return false; // Ignore RHS 12290 } 12291 } else { 12292 LHSResult.Failed = true; 12293 12294 // Since we weren't able to evaluate the left hand side, it 12295 // might have had side effects. 12296 if (!Info.noteSideEffect()) 12297 return false; 12298 12299 // We can't evaluate the LHS; however, sometimes the result 12300 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12301 // Don't ignore RHS and suppress diagnostics from this arm. 12302 SuppressRHSDiags = true; 12303 } 12304 12305 return true; 12306 } 12307 12308 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12309 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12310 12311 if (LHSResult.Failed && !Info.noteFailure()) 12312 return false; // Ignore RHS; 12313 12314 return true; 12315 } 12316 12317 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12318 bool IsSub) { 12319 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12320 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12321 // offsets. 12322 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12323 CharUnits &Offset = LVal.getLValueOffset(); 12324 uint64_t Offset64 = Offset.getQuantity(); 12325 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12326 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12327 : Offset64 + Index64); 12328 } 12329 12330 bool DataRecursiveIntBinOpEvaluator:: 12331 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12332 const BinaryOperator *E, APValue &Result) { 12333 if (E->getOpcode() == BO_Comma) { 12334 if (RHSResult.Failed) 12335 return false; 12336 Result = RHSResult.Val; 12337 return true; 12338 } 12339 12340 if (E->isLogicalOp()) { 12341 bool lhsResult, rhsResult; 12342 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12343 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12344 12345 if (LHSIsOK) { 12346 if (RHSIsOK) { 12347 if (E->getOpcode() == BO_LOr) 12348 return Success(lhsResult || rhsResult, E, Result); 12349 else 12350 return Success(lhsResult && rhsResult, E, Result); 12351 } 12352 } else { 12353 if (RHSIsOK) { 12354 // We can't evaluate the LHS; however, sometimes the result 12355 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12356 if (rhsResult == (E->getOpcode() == BO_LOr)) 12357 return Success(rhsResult, E, Result); 12358 } 12359 } 12360 12361 return false; 12362 } 12363 12364 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12365 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12366 12367 if (LHSResult.Failed || RHSResult.Failed) 12368 return false; 12369 12370 const APValue &LHSVal = LHSResult.Val; 12371 const APValue &RHSVal = RHSResult.Val; 12372 12373 // Handle cases like (unsigned long)&a + 4. 12374 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12375 Result = LHSVal; 12376 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12377 return true; 12378 } 12379 12380 // Handle cases like 4 + (unsigned long)&a 12381 if (E->getOpcode() == BO_Add && 12382 RHSVal.isLValue() && LHSVal.isInt()) { 12383 Result = RHSVal; 12384 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12385 return true; 12386 } 12387 12388 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12389 // Handle (intptr_t)&&A - (intptr_t)&&B. 12390 if (!LHSVal.getLValueOffset().isZero() || 12391 !RHSVal.getLValueOffset().isZero()) 12392 return false; 12393 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12394 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12395 if (!LHSExpr || !RHSExpr) 12396 return false; 12397 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12398 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12399 if (!LHSAddrExpr || !RHSAddrExpr) 12400 return false; 12401 // Make sure both labels come from the same function. 12402 if (LHSAddrExpr->getLabel()->getDeclContext() != 12403 RHSAddrExpr->getLabel()->getDeclContext()) 12404 return false; 12405 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12406 return true; 12407 } 12408 12409 // All the remaining cases expect both operands to be an integer 12410 if (!LHSVal.isInt() || !RHSVal.isInt()) 12411 return Error(E); 12412 12413 // Set up the width and signedness manually, in case it can't be deduced 12414 // from the operation we're performing. 12415 // FIXME: Don't do this in the cases where we can deduce it. 12416 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12417 E->getType()->isUnsignedIntegerOrEnumerationType()); 12418 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12419 RHSVal.getInt(), Value)) 12420 return false; 12421 return Success(Value, E, Result); 12422 } 12423 12424 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12425 Job &job = Queue.back(); 12426 12427 switch (job.Kind) { 12428 case Job::AnyExprKind: { 12429 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12430 if (shouldEnqueue(Bop)) { 12431 job.Kind = Job::BinOpKind; 12432 enqueue(Bop->getLHS()); 12433 return; 12434 } 12435 } 12436 12437 EvaluateExpr(job.E, Result); 12438 Queue.pop_back(); 12439 return; 12440 } 12441 12442 case Job::BinOpKind: { 12443 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12444 bool SuppressRHSDiags = false; 12445 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12446 Queue.pop_back(); 12447 return; 12448 } 12449 if (SuppressRHSDiags) 12450 job.startSpeculativeEval(Info); 12451 job.LHSResult.swap(Result); 12452 job.Kind = Job::BinOpVisitedLHSKind; 12453 enqueue(Bop->getRHS()); 12454 return; 12455 } 12456 12457 case Job::BinOpVisitedLHSKind: { 12458 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12459 EvalResult RHS; 12460 RHS.swap(Result); 12461 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12462 Queue.pop_back(); 12463 return; 12464 } 12465 } 12466 12467 llvm_unreachable("Invalid Job::Kind!"); 12468 } 12469 12470 namespace { 12471 /// Used when we determine that we should fail, but can keep evaluating prior to 12472 /// noting that we had a failure. 12473 class DelayedNoteFailureRAII { 12474 EvalInfo &Info; 12475 bool NoteFailure; 12476 12477 public: 12478 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12479 : Info(Info), NoteFailure(NoteFailure) {} 12480 ~DelayedNoteFailureRAII() { 12481 if (NoteFailure) { 12482 bool ContinueAfterFailure = Info.noteFailure(); 12483 (void)ContinueAfterFailure; 12484 assert(ContinueAfterFailure && 12485 "Shouldn't have kept evaluating on failure."); 12486 } 12487 } 12488 }; 12489 12490 enum class CmpResult { 12491 Unequal, 12492 Less, 12493 Equal, 12494 Greater, 12495 Unordered, 12496 }; 12497 } 12498 12499 template <class SuccessCB, class AfterCB> 12500 static bool 12501 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12502 SuccessCB &&Success, AfterCB &&DoAfter) { 12503 assert(!E->isValueDependent()); 12504 assert(E->isComparisonOp() && "expected comparison operator"); 12505 assert((E->getOpcode() == BO_Cmp || 12506 E->getType()->isIntegralOrEnumerationType()) && 12507 "unsupported binary expression evaluation"); 12508 auto Error = [&](const Expr *E) { 12509 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12510 return false; 12511 }; 12512 12513 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12514 bool IsEquality = E->isEqualityOp(); 12515 12516 QualType LHSTy = E->getLHS()->getType(); 12517 QualType RHSTy = E->getRHS()->getType(); 12518 12519 if (LHSTy->isIntegralOrEnumerationType() && 12520 RHSTy->isIntegralOrEnumerationType()) { 12521 APSInt LHS, RHS; 12522 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12523 if (!LHSOK && !Info.noteFailure()) 12524 return false; 12525 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12526 return false; 12527 if (LHS < RHS) 12528 return Success(CmpResult::Less, E); 12529 if (LHS > RHS) 12530 return Success(CmpResult::Greater, E); 12531 return Success(CmpResult::Equal, E); 12532 } 12533 12534 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12535 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12536 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12537 12538 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12539 if (!LHSOK && !Info.noteFailure()) 12540 return false; 12541 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12542 return false; 12543 if (LHSFX < RHSFX) 12544 return Success(CmpResult::Less, E); 12545 if (LHSFX > RHSFX) 12546 return Success(CmpResult::Greater, E); 12547 return Success(CmpResult::Equal, E); 12548 } 12549 12550 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12551 ComplexValue LHS, RHS; 12552 bool LHSOK; 12553 if (E->isAssignmentOp()) { 12554 LValue LV; 12555 EvaluateLValue(E->getLHS(), LV, Info); 12556 LHSOK = false; 12557 } else if (LHSTy->isRealFloatingType()) { 12558 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12559 if (LHSOK) { 12560 LHS.makeComplexFloat(); 12561 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12562 } 12563 } else { 12564 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12565 } 12566 if (!LHSOK && !Info.noteFailure()) 12567 return false; 12568 12569 if (E->getRHS()->getType()->isRealFloatingType()) { 12570 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12571 return false; 12572 RHS.makeComplexFloat(); 12573 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12574 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12575 return false; 12576 12577 if (LHS.isComplexFloat()) { 12578 APFloat::cmpResult CR_r = 12579 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12580 APFloat::cmpResult CR_i = 12581 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12582 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12583 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12584 } else { 12585 assert(IsEquality && "invalid complex comparison"); 12586 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12587 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12588 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12589 } 12590 } 12591 12592 if (LHSTy->isRealFloatingType() && 12593 RHSTy->isRealFloatingType()) { 12594 APFloat RHS(0.0), LHS(0.0); 12595 12596 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12597 if (!LHSOK && !Info.noteFailure()) 12598 return false; 12599 12600 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12601 return false; 12602 12603 assert(E->isComparisonOp() && "Invalid binary operator!"); 12604 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12605 if (!Info.InConstantContext && 12606 APFloatCmpResult == APFloat::cmpUnordered && 12607 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12608 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12609 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12610 return false; 12611 } 12612 auto GetCmpRes = [&]() { 12613 switch (APFloatCmpResult) { 12614 case APFloat::cmpEqual: 12615 return CmpResult::Equal; 12616 case APFloat::cmpLessThan: 12617 return CmpResult::Less; 12618 case APFloat::cmpGreaterThan: 12619 return CmpResult::Greater; 12620 case APFloat::cmpUnordered: 12621 return CmpResult::Unordered; 12622 } 12623 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12624 }; 12625 return Success(GetCmpRes(), E); 12626 } 12627 12628 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12629 LValue LHSValue, RHSValue; 12630 12631 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12632 if (!LHSOK && !Info.noteFailure()) 12633 return false; 12634 12635 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12636 return false; 12637 12638 // Reject differing bases from the normal codepath; we special-case 12639 // comparisons to null. 12640 if (!HasSameBase(LHSValue, RHSValue)) { 12641 // Inequalities and subtractions between unrelated pointers have 12642 // unspecified or undefined behavior. 12643 if (!IsEquality) { 12644 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12645 return false; 12646 } 12647 // A constant address may compare equal to the address of a symbol. 12648 // The one exception is that address of an object cannot compare equal 12649 // to a null pointer constant. 12650 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12651 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12652 return Error(E); 12653 // It's implementation-defined whether distinct literals will have 12654 // distinct addresses. In clang, the result of such a comparison is 12655 // unspecified, so it is not a constant expression. However, we do know 12656 // that the address of a literal will be non-null. 12657 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12658 LHSValue.Base && RHSValue.Base) 12659 return Error(E); 12660 // We can't tell whether weak symbols will end up pointing to the same 12661 // object. 12662 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12663 return Error(E); 12664 // We can't compare the address of the start of one object with the 12665 // past-the-end address of another object, per C++ DR1652. 12666 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12667 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12668 (RHSValue.Base && RHSValue.Offset.isZero() && 12669 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12670 return Error(E); 12671 // We can't tell whether an object is at the same address as another 12672 // zero sized object. 12673 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12674 (LHSValue.Base && isZeroSized(RHSValue))) 12675 return Error(E); 12676 return Success(CmpResult::Unequal, E); 12677 } 12678 12679 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12680 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12681 12682 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12683 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12684 12685 // C++11 [expr.rel]p3: 12686 // Pointers to void (after pointer conversions) can be compared, with a 12687 // result defined as follows: If both pointers represent the same 12688 // address or are both the null pointer value, the result is true if the 12689 // operator is <= or >= and false otherwise; otherwise the result is 12690 // unspecified. 12691 // We interpret this as applying to pointers to *cv* void. 12692 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12693 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12694 12695 // C++11 [expr.rel]p2: 12696 // - If two pointers point to non-static data members of the same object, 12697 // or to subobjects or array elements fo such members, recursively, the 12698 // pointer to the later declared member compares greater provided the 12699 // two members have the same access control and provided their class is 12700 // not a union. 12701 // [...] 12702 // - Otherwise pointer comparisons are unspecified. 12703 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12704 bool WasArrayIndex; 12705 unsigned Mismatch = FindDesignatorMismatch( 12706 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12707 // At the point where the designators diverge, the comparison has a 12708 // specified value if: 12709 // - we are comparing array indices 12710 // - we are comparing fields of a union, or fields with the same access 12711 // Otherwise, the result is unspecified and thus the comparison is not a 12712 // constant expression. 12713 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12714 Mismatch < RHSDesignator.Entries.size()) { 12715 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12716 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12717 if (!LF && !RF) 12718 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12719 else if (!LF) 12720 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12721 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12722 << RF->getParent() << RF; 12723 else if (!RF) 12724 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12725 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12726 << LF->getParent() << LF; 12727 else if (!LF->getParent()->isUnion() && 12728 LF->getAccess() != RF->getAccess()) 12729 Info.CCEDiag(E, 12730 diag::note_constexpr_pointer_comparison_differing_access) 12731 << LF << LF->getAccess() << RF << RF->getAccess() 12732 << LF->getParent(); 12733 } 12734 } 12735 12736 // The comparison here must be unsigned, and performed with the same 12737 // width as the pointer. 12738 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12739 uint64_t CompareLHS = LHSOffset.getQuantity(); 12740 uint64_t CompareRHS = RHSOffset.getQuantity(); 12741 assert(PtrSize <= 64 && "Unexpected pointer width"); 12742 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12743 CompareLHS &= Mask; 12744 CompareRHS &= Mask; 12745 12746 // If there is a base and this is a relational operator, we can only 12747 // compare pointers within the object in question; otherwise, the result 12748 // depends on where the object is located in memory. 12749 if (!LHSValue.Base.isNull() && IsRelational) { 12750 QualType BaseTy = getType(LHSValue.Base); 12751 if (BaseTy->isIncompleteType()) 12752 return Error(E); 12753 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12754 uint64_t OffsetLimit = Size.getQuantity(); 12755 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12756 return Error(E); 12757 } 12758 12759 if (CompareLHS < CompareRHS) 12760 return Success(CmpResult::Less, E); 12761 if (CompareLHS > CompareRHS) 12762 return Success(CmpResult::Greater, E); 12763 return Success(CmpResult::Equal, E); 12764 } 12765 12766 if (LHSTy->isMemberPointerType()) { 12767 assert(IsEquality && "unexpected member pointer operation"); 12768 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12769 12770 MemberPtr LHSValue, RHSValue; 12771 12772 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12773 if (!LHSOK && !Info.noteFailure()) 12774 return false; 12775 12776 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12777 return false; 12778 12779 // C++11 [expr.eq]p2: 12780 // If both operands are null, they compare equal. Otherwise if only one is 12781 // null, they compare unequal. 12782 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12783 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12784 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12785 } 12786 12787 // Otherwise if either is a pointer to a virtual member function, the 12788 // result is unspecified. 12789 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12790 if (MD->isVirtual()) 12791 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12792 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12793 if (MD->isVirtual()) 12794 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12795 12796 // Otherwise they compare equal if and only if they would refer to the 12797 // same member of the same most derived object or the same subobject if 12798 // they were dereferenced with a hypothetical object of the associated 12799 // class type. 12800 bool Equal = LHSValue == RHSValue; 12801 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12802 } 12803 12804 if (LHSTy->isNullPtrType()) { 12805 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12806 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12807 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12808 // are compared, the result is true of the operator is <=, >= or ==, and 12809 // false otherwise. 12810 return Success(CmpResult::Equal, E); 12811 } 12812 12813 return DoAfter(); 12814 } 12815 12816 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12817 if (!CheckLiteralType(Info, E)) 12818 return false; 12819 12820 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12821 ComparisonCategoryResult CCR; 12822 switch (CR) { 12823 case CmpResult::Unequal: 12824 llvm_unreachable("should never produce Unequal for three-way comparison"); 12825 case CmpResult::Less: 12826 CCR = ComparisonCategoryResult::Less; 12827 break; 12828 case CmpResult::Equal: 12829 CCR = ComparisonCategoryResult::Equal; 12830 break; 12831 case CmpResult::Greater: 12832 CCR = ComparisonCategoryResult::Greater; 12833 break; 12834 case CmpResult::Unordered: 12835 CCR = ComparisonCategoryResult::Unordered; 12836 break; 12837 } 12838 // Evaluation succeeded. Lookup the information for the comparison category 12839 // type and fetch the VarDecl for the result. 12840 const ComparisonCategoryInfo &CmpInfo = 12841 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12842 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12843 // Check and evaluate the result as a constant expression. 12844 LValue LV; 12845 LV.set(VD); 12846 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12847 return false; 12848 bool Dependent = false; 12849 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12850 ConstantExprKind::Normal, Dependent); 12851 }; 12852 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12853 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12854 }); 12855 } 12856 12857 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12858 // We don't call noteFailure immediately because the assignment happens after 12859 // we evaluate LHS and RHS. 12860 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12861 return Error(E); 12862 12863 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12864 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12865 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12866 12867 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12868 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12869 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12870 12871 if (E->isComparisonOp()) { 12872 // Evaluate builtin binary comparisons by evaluating them as three-way 12873 // comparisons and then translating the result. 12874 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12875 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12876 "should only produce Unequal for equality comparisons"); 12877 bool IsEqual = CR == CmpResult::Equal, 12878 IsLess = CR == CmpResult::Less, 12879 IsGreater = CR == CmpResult::Greater; 12880 auto Op = E->getOpcode(); 12881 switch (Op) { 12882 default: 12883 llvm_unreachable("unsupported binary operator"); 12884 case BO_EQ: 12885 case BO_NE: 12886 return Success(IsEqual == (Op == BO_EQ), E); 12887 case BO_LT: 12888 return Success(IsLess, E); 12889 case BO_GT: 12890 return Success(IsGreater, E); 12891 case BO_LE: 12892 return Success(IsEqual || IsLess, E); 12893 case BO_GE: 12894 return Success(IsEqual || IsGreater, E); 12895 } 12896 }; 12897 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12898 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12899 }); 12900 } 12901 12902 QualType LHSTy = E->getLHS()->getType(); 12903 QualType RHSTy = E->getRHS()->getType(); 12904 12905 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12906 E->getOpcode() == BO_Sub) { 12907 LValue LHSValue, RHSValue; 12908 12909 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12910 if (!LHSOK && !Info.noteFailure()) 12911 return false; 12912 12913 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12914 return false; 12915 12916 // Reject differing bases from the normal codepath; we special-case 12917 // comparisons to null. 12918 if (!HasSameBase(LHSValue, RHSValue)) { 12919 // Handle &&A - &&B. 12920 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12921 return Error(E); 12922 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12923 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12924 if (!LHSExpr || !RHSExpr) 12925 return Error(E); 12926 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12927 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12928 if (!LHSAddrExpr || !RHSAddrExpr) 12929 return Error(E); 12930 // Make sure both labels come from the same function. 12931 if (LHSAddrExpr->getLabel()->getDeclContext() != 12932 RHSAddrExpr->getLabel()->getDeclContext()) 12933 return Error(E); 12934 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12935 } 12936 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12937 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12938 12939 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12940 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12941 12942 // C++11 [expr.add]p6: 12943 // Unless both pointers point to elements of the same array object, or 12944 // one past the last element of the array object, the behavior is 12945 // undefined. 12946 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12947 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12948 RHSDesignator)) 12949 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12950 12951 QualType Type = E->getLHS()->getType(); 12952 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12953 12954 CharUnits ElementSize; 12955 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12956 return false; 12957 12958 // As an extension, a type may have zero size (empty struct or union in 12959 // C, array of zero length). Pointer subtraction in such cases has 12960 // undefined behavior, so is not constant. 12961 if (ElementSize.isZero()) { 12962 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12963 << ElementType; 12964 return false; 12965 } 12966 12967 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12968 // and produce incorrect results when it overflows. Such behavior 12969 // appears to be non-conforming, but is common, so perhaps we should 12970 // assume the standard intended for such cases to be undefined behavior 12971 // and check for them. 12972 12973 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12974 // overflow in the final conversion to ptrdiff_t. 12975 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12976 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12977 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12978 false); 12979 APSInt TrueResult = (LHS - RHS) / ElemSize; 12980 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12981 12982 if (Result.extend(65) != TrueResult && 12983 !HandleOverflow(Info, E, TrueResult, E->getType())) 12984 return false; 12985 return Success(Result, E); 12986 } 12987 12988 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12989 } 12990 12991 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12992 /// a result as the expression's type. 12993 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12994 const UnaryExprOrTypeTraitExpr *E) { 12995 switch(E->getKind()) { 12996 case UETT_PreferredAlignOf: 12997 case UETT_AlignOf: { 12998 if (E->isArgumentType()) 12999 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13000 E); 13001 else 13002 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13003 E); 13004 } 13005 13006 case UETT_VecStep: { 13007 QualType Ty = E->getTypeOfArgument(); 13008 13009 if (Ty->isVectorType()) { 13010 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13011 13012 // The vec_step built-in functions that take a 3-component 13013 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13014 if (n == 3) 13015 n = 4; 13016 13017 return Success(n, E); 13018 } else 13019 return Success(1, E); 13020 } 13021 13022 case UETT_SizeOf: { 13023 QualType SrcTy = E->getTypeOfArgument(); 13024 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13025 // the result is the size of the referenced type." 13026 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13027 SrcTy = Ref->getPointeeType(); 13028 13029 CharUnits Sizeof; 13030 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13031 return false; 13032 return Success(Sizeof, E); 13033 } 13034 case UETT_OpenMPRequiredSimdAlign: 13035 assert(E->isArgumentType()); 13036 return Success( 13037 Info.Ctx.toCharUnitsFromBits( 13038 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13039 .getQuantity(), 13040 E); 13041 } 13042 13043 llvm_unreachable("unknown expr/type trait"); 13044 } 13045 13046 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13047 CharUnits Result; 13048 unsigned n = OOE->getNumComponents(); 13049 if (n == 0) 13050 return Error(OOE); 13051 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13052 for (unsigned i = 0; i != n; ++i) { 13053 OffsetOfNode ON = OOE->getComponent(i); 13054 switch (ON.getKind()) { 13055 case OffsetOfNode::Array: { 13056 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13057 APSInt IdxResult; 13058 if (!EvaluateInteger(Idx, IdxResult, Info)) 13059 return false; 13060 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13061 if (!AT) 13062 return Error(OOE); 13063 CurrentType = AT->getElementType(); 13064 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13065 Result += IdxResult.getSExtValue() * ElementSize; 13066 break; 13067 } 13068 13069 case OffsetOfNode::Field: { 13070 FieldDecl *MemberDecl = ON.getField(); 13071 const RecordType *RT = CurrentType->getAs<RecordType>(); 13072 if (!RT) 13073 return Error(OOE); 13074 RecordDecl *RD = RT->getDecl(); 13075 if (RD->isInvalidDecl()) return false; 13076 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13077 unsigned i = MemberDecl->getFieldIndex(); 13078 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13079 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13080 CurrentType = MemberDecl->getType().getNonReferenceType(); 13081 break; 13082 } 13083 13084 case OffsetOfNode::Identifier: 13085 llvm_unreachable("dependent __builtin_offsetof"); 13086 13087 case OffsetOfNode::Base: { 13088 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13089 if (BaseSpec->isVirtual()) 13090 return Error(OOE); 13091 13092 // Find the layout of the class whose base we are looking into. 13093 const RecordType *RT = CurrentType->getAs<RecordType>(); 13094 if (!RT) 13095 return Error(OOE); 13096 RecordDecl *RD = RT->getDecl(); 13097 if (RD->isInvalidDecl()) return false; 13098 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13099 13100 // Find the base class itself. 13101 CurrentType = BaseSpec->getType(); 13102 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13103 if (!BaseRT) 13104 return Error(OOE); 13105 13106 // Add the offset to the base. 13107 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13108 break; 13109 } 13110 } 13111 } 13112 return Success(Result, OOE); 13113 } 13114 13115 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13116 switch (E->getOpcode()) { 13117 default: 13118 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13119 // See C99 6.6p3. 13120 return Error(E); 13121 case UO_Extension: 13122 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13123 // If so, we could clear the diagnostic ID. 13124 return Visit(E->getSubExpr()); 13125 case UO_Plus: 13126 // The result is just the value. 13127 return Visit(E->getSubExpr()); 13128 case UO_Minus: { 13129 if (!Visit(E->getSubExpr())) 13130 return false; 13131 if (!Result.isInt()) return Error(E); 13132 const APSInt &Value = Result.getInt(); 13133 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13134 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13135 E->getType())) 13136 return false; 13137 return Success(-Value, E); 13138 } 13139 case UO_Not: { 13140 if (!Visit(E->getSubExpr())) 13141 return false; 13142 if (!Result.isInt()) return Error(E); 13143 return Success(~Result.getInt(), E); 13144 } 13145 case UO_LNot: { 13146 bool bres; 13147 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13148 return false; 13149 return Success(!bres, E); 13150 } 13151 } 13152 } 13153 13154 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13155 /// result type is integer. 13156 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13157 const Expr *SubExpr = E->getSubExpr(); 13158 QualType DestType = E->getType(); 13159 QualType SrcType = SubExpr->getType(); 13160 13161 switch (E->getCastKind()) { 13162 case CK_BaseToDerived: 13163 case CK_DerivedToBase: 13164 case CK_UncheckedDerivedToBase: 13165 case CK_Dynamic: 13166 case CK_ToUnion: 13167 case CK_ArrayToPointerDecay: 13168 case CK_FunctionToPointerDecay: 13169 case CK_NullToPointer: 13170 case CK_NullToMemberPointer: 13171 case CK_BaseToDerivedMemberPointer: 13172 case CK_DerivedToBaseMemberPointer: 13173 case CK_ReinterpretMemberPointer: 13174 case CK_ConstructorConversion: 13175 case CK_IntegralToPointer: 13176 case CK_ToVoid: 13177 case CK_VectorSplat: 13178 case CK_IntegralToFloating: 13179 case CK_FloatingCast: 13180 case CK_CPointerToObjCPointerCast: 13181 case CK_BlockPointerToObjCPointerCast: 13182 case CK_AnyPointerToBlockPointerCast: 13183 case CK_ObjCObjectLValueCast: 13184 case CK_FloatingRealToComplex: 13185 case CK_FloatingComplexToReal: 13186 case CK_FloatingComplexCast: 13187 case CK_FloatingComplexToIntegralComplex: 13188 case CK_IntegralRealToComplex: 13189 case CK_IntegralComplexCast: 13190 case CK_IntegralComplexToFloatingComplex: 13191 case CK_BuiltinFnToFnPtr: 13192 case CK_ZeroToOCLOpaqueType: 13193 case CK_NonAtomicToAtomic: 13194 case CK_AddressSpaceConversion: 13195 case CK_IntToOCLSampler: 13196 case CK_FloatingToFixedPoint: 13197 case CK_FixedPointToFloating: 13198 case CK_FixedPointCast: 13199 case CK_IntegralToFixedPoint: 13200 llvm_unreachable("invalid cast kind for integral value"); 13201 13202 case CK_BitCast: 13203 case CK_Dependent: 13204 case CK_LValueBitCast: 13205 case CK_ARCProduceObject: 13206 case CK_ARCConsumeObject: 13207 case CK_ARCReclaimReturnedObject: 13208 case CK_ARCExtendBlockObject: 13209 case CK_CopyAndAutoreleaseBlockObject: 13210 return Error(E); 13211 13212 case CK_UserDefinedConversion: 13213 case CK_LValueToRValue: 13214 case CK_AtomicToNonAtomic: 13215 case CK_NoOp: 13216 case CK_LValueToRValueBitCast: 13217 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13218 13219 case CK_MemberPointerToBoolean: 13220 case CK_PointerToBoolean: 13221 case CK_IntegralToBoolean: 13222 case CK_FloatingToBoolean: 13223 case CK_BooleanToSignedIntegral: 13224 case CK_FloatingComplexToBoolean: 13225 case CK_IntegralComplexToBoolean: { 13226 bool BoolResult; 13227 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13228 return false; 13229 uint64_t IntResult = BoolResult; 13230 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13231 IntResult = (uint64_t)-1; 13232 return Success(IntResult, E); 13233 } 13234 13235 case CK_FixedPointToIntegral: { 13236 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13237 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13238 return false; 13239 bool Overflowed; 13240 llvm::APSInt Result = Src.convertToInt( 13241 Info.Ctx.getIntWidth(DestType), 13242 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13243 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13244 return false; 13245 return Success(Result, E); 13246 } 13247 13248 case CK_FixedPointToBoolean: { 13249 // Unsigned padding does not affect this. 13250 APValue Val; 13251 if (!Evaluate(Val, Info, SubExpr)) 13252 return false; 13253 return Success(Val.getFixedPoint().getBoolValue(), E); 13254 } 13255 13256 case CK_IntegralCast: { 13257 if (!Visit(SubExpr)) 13258 return false; 13259 13260 if (!Result.isInt()) { 13261 // Allow casts of address-of-label differences if they are no-ops 13262 // or narrowing. (The narrowing case isn't actually guaranteed to 13263 // be constant-evaluatable except in some narrow cases which are hard 13264 // to detect here. We let it through on the assumption the user knows 13265 // what they are doing.) 13266 if (Result.isAddrLabelDiff()) 13267 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13268 // Only allow casts of lvalues if they are lossless. 13269 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13270 } 13271 13272 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13273 Result.getInt()), E); 13274 } 13275 13276 case CK_PointerToIntegral: { 13277 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13278 13279 LValue LV; 13280 if (!EvaluatePointer(SubExpr, LV, Info)) 13281 return false; 13282 13283 if (LV.getLValueBase()) { 13284 // Only allow based lvalue casts if they are lossless. 13285 // FIXME: Allow a larger integer size than the pointer size, and allow 13286 // narrowing back down to pointer width in subsequent integral casts. 13287 // FIXME: Check integer type's active bits, not its type size. 13288 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13289 return Error(E); 13290 13291 LV.Designator.setInvalid(); 13292 LV.moveInto(Result); 13293 return true; 13294 } 13295 13296 APSInt AsInt; 13297 APValue V; 13298 LV.moveInto(V); 13299 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13300 llvm_unreachable("Can't cast this!"); 13301 13302 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13303 } 13304 13305 case CK_IntegralComplexToReal: { 13306 ComplexValue C; 13307 if (!EvaluateComplex(SubExpr, C, Info)) 13308 return false; 13309 return Success(C.getComplexIntReal(), E); 13310 } 13311 13312 case CK_FloatingToIntegral: { 13313 APFloat F(0.0); 13314 if (!EvaluateFloat(SubExpr, F, Info)) 13315 return false; 13316 13317 APSInt Value; 13318 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13319 return false; 13320 return Success(Value, E); 13321 } 13322 } 13323 13324 llvm_unreachable("unknown cast resulting in integral value"); 13325 } 13326 13327 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13328 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13329 ComplexValue LV; 13330 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13331 return false; 13332 if (!LV.isComplexInt()) 13333 return Error(E); 13334 return Success(LV.getComplexIntReal(), E); 13335 } 13336 13337 return Visit(E->getSubExpr()); 13338 } 13339 13340 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13341 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13342 ComplexValue LV; 13343 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13344 return false; 13345 if (!LV.isComplexInt()) 13346 return Error(E); 13347 return Success(LV.getComplexIntImag(), E); 13348 } 13349 13350 VisitIgnoredValue(E->getSubExpr()); 13351 return Success(0, E); 13352 } 13353 13354 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13355 return Success(E->getPackLength(), E); 13356 } 13357 13358 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13359 return Success(E->getValue(), E); 13360 } 13361 13362 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13363 const ConceptSpecializationExpr *E) { 13364 return Success(E->isSatisfied(), E); 13365 } 13366 13367 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13368 return Success(E->isSatisfied(), E); 13369 } 13370 13371 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13372 switch (E->getOpcode()) { 13373 default: 13374 // Invalid unary operators 13375 return Error(E); 13376 case UO_Plus: 13377 // The result is just the value. 13378 return Visit(E->getSubExpr()); 13379 case UO_Minus: { 13380 if (!Visit(E->getSubExpr())) return false; 13381 if (!Result.isFixedPoint()) 13382 return Error(E); 13383 bool Overflowed; 13384 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13385 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13386 return false; 13387 return Success(Negated, E); 13388 } 13389 case UO_LNot: { 13390 bool bres; 13391 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13392 return false; 13393 return Success(!bres, E); 13394 } 13395 } 13396 } 13397 13398 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13399 const Expr *SubExpr = E->getSubExpr(); 13400 QualType DestType = E->getType(); 13401 assert(DestType->isFixedPointType() && 13402 "Expected destination type to be a fixed point type"); 13403 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13404 13405 switch (E->getCastKind()) { 13406 case CK_FixedPointCast: { 13407 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13408 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13409 return false; 13410 bool Overflowed; 13411 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13412 if (Overflowed) { 13413 if (Info.checkingForUndefinedBehavior()) 13414 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13415 diag::warn_fixedpoint_constant_overflow) 13416 << Result.toString() << E->getType(); 13417 else if (!HandleOverflow(Info, E, Result, E->getType())) 13418 return false; 13419 } 13420 return Success(Result, E); 13421 } 13422 case CK_IntegralToFixedPoint: { 13423 APSInt Src; 13424 if (!EvaluateInteger(SubExpr, Src, Info)) 13425 return false; 13426 13427 bool Overflowed; 13428 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13429 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13430 13431 if (Overflowed) { 13432 if (Info.checkingForUndefinedBehavior()) 13433 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13434 diag::warn_fixedpoint_constant_overflow) 13435 << IntResult.toString() << E->getType(); 13436 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 13437 return false; 13438 } 13439 13440 return Success(IntResult, E); 13441 } 13442 case CK_FloatingToFixedPoint: { 13443 APFloat Src(0.0); 13444 if (!EvaluateFloat(SubExpr, Src, Info)) 13445 return false; 13446 13447 bool Overflowed; 13448 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13449 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13450 13451 if (Overflowed) { 13452 if (Info.checkingForUndefinedBehavior()) 13453 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13454 diag::warn_fixedpoint_constant_overflow) 13455 << Result.toString() << E->getType(); 13456 else if (!HandleOverflow(Info, E, Result, E->getType())) 13457 return false; 13458 } 13459 13460 return Success(Result, E); 13461 } 13462 case CK_NoOp: 13463 case CK_LValueToRValue: 13464 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13465 default: 13466 return Error(E); 13467 } 13468 } 13469 13470 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13471 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13472 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13473 13474 const Expr *LHS = E->getLHS(); 13475 const Expr *RHS = E->getRHS(); 13476 FixedPointSemantics ResultFXSema = 13477 Info.Ctx.getFixedPointSemantics(E->getType()); 13478 13479 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13480 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13481 return false; 13482 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13483 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13484 return false; 13485 13486 bool OpOverflow = false, ConversionOverflow = false; 13487 APFixedPoint Result(LHSFX.getSemantics()); 13488 switch (E->getOpcode()) { 13489 case BO_Add: { 13490 Result = LHSFX.add(RHSFX, &OpOverflow) 13491 .convert(ResultFXSema, &ConversionOverflow); 13492 break; 13493 } 13494 case BO_Sub: { 13495 Result = LHSFX.sub(RHSFX, &OpOverflow) 13496 .convert(ResultFXSema, &ConversionOverflow); 13497 break; 13498 } 13499 case BO_Mul: { 13500 Result = LHSFX.mul(RHSFX, &OpOverflow) 13501 .convert(ResultFXSema, &ConversionOverflow); 13502 break; 13503 } 13504 case BO_Div: { 13505 if (RHSFX.getValue() == 0) { 13506 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13507 return false; 13508 } 13509 Result = LHSFX.div(RHSFX, &OpOverflow) 13510 .convert(ResultFXSema, &ConversionOverflow); 13511 break; 13512 } 13513 case BO_Shl: 13514 case BO_Shr: { 13515 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13516 llvm::APSInt RHSVal = RHSFX.getValue(); 13517 13518 unsigned ShiftBW = 13519 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13520 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13521 // Embedded-C 4.1.6.2.2: 13522 // The right operand must be nonnegative and less than the total number 13523 // of (nonpadding) bits of the fixed-point operand ... 13524 if (RHSVal.isNegative()) 13525 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13526 else if (Amt != RHSVal) 13527 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13528 << RHSVal << E->getType() << ShiftBW; 13529 13530 if (E->getOpcode() == BO_Shl) 13531 Result = LHSFX.shl(Amt, &OpOverflow); 13532 else 13533 Result = LHSFX.shr(Amt, &OpOverflow); 13534 break; 13535 } 13536 default: 13537 return false; 13538 } 13539 if (OpOverflow || ConversionOverflow) { 13540 if (Info.checkingForUndefinedBehavior()) 13541 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13542 diag::warn_fixedpoint_constant_overflow) 13543 << Result.toString() << E->getType(); 13544 else if (!HandleOverflow(Info, E, Result, E->getType())) 13545 return false; 13546 } 13547 return Success(Result, E); 13548 } 13549 13550 //===----------------------------------------------------------------------===// 13551 // Float Evaluation 13552 //===----------------------------------------------------------------------===// 13553 13554 namespace { 13555 class FloatExprEvaluator 13556 : public ExprEvaluatorBase<FloatExprEvaluator> { 13557 APFloat &Result; 13558 public: 13559 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13560 : ExprEvaluatorBaseTy(info), Result(result) {} 13561 13562 bool Success(const APValue &V, const Expr *e) { 13563 Result = V.getFloat(); 13564 return true; 13565 } 13566 13567 bool ZeroInitialization(const Expr *E) { 13568 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13569 return true; 13570 } 13571 13572 bool VisitCallExpr(const CallExpr *E); 13573 13574 bool VisitUnaryOperator(const UnaryOperator *E); 13575 bool VisitBinaryOperator(const BinaryOperator *E); 13576 bool VisitFloatingLiteral(const FloatingLiteral *E); 13577 bool VisitCastExpr(const CastExpr *E); 13578 13579 bool VisitUnaryReal(const UnaryOperator *E); 13580 bool VisitUnaryImag(const UnaryOperator *E); 13581 13582 // FIXME: Missing: array subscript of vector, member of vector 13583 }; 13584 } // end anonymous namespace 13585 13586 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13587 assert(!E->isValueDependent()); 13588 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13589 return FloatExprEvaluator(Info, Result).Visit(E); 13590 } 13591 13592 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13593 QualType ResultTy, 13594 const Expr *Arg, 13595 bool SNaN, 13596 llvm::APFloat &Result) { 13597 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13598 if (!S) return false; 13599 13600 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13601 13602 llvm::APInt fill; 13603 13604 // Treat empty strings as if they were zero. 13605 if (S->getString().empty()) 13606 fill = llvm::APInt(32, 0); 13607 else if (S->getString().getAsInteger(0, fill)) 13608 return false; 13609 13610 if (Context.getTargetInfo().isNan2008()) { 13611 if (SNaN) 13612 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13613 else 13614 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13615 } else { 13616 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13617 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13618 // a different encoding to what became a standard in 2008, and for pre- 13619 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13620 // sNaN. This is now known as "legacy NaN" encoding. 13621 if (SNaN) 13622 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13623 else 13624 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13625 } 13626 13627 return true; 13628 } 13629 13630 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13631 switch (E->getBuiltinCallee()) { 13632 default: 13633 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13634 13635 case Builtin::BI__builtin_huge_val: 13636 case Builtin::BI__builtin_huge_valf: 13637 case Builtin::BI__builtin_huge_vall: 13638 case Builtin::BI__builtin_huge_valf128: 13639 case Builtin::BI__builtin_inf: 13640 case Builtin::BI__builtin_inff: 13641 case Builtin::BI__builtin_infl: 13642 case Builtin::BI__builtin_inff128: { 13643 const llvm::fltSemantics &Sem = 13644 Info.Ctx.getFloatTypeSemantics(E->getType()); 13645 Result = llvm::APFloat::getInf(Sem); 13646 return true; 13647 } 13648 13649 case Builtin::BI__builtin_nans: 13650 case Builtin::BI__builtin_nansf: 13651 case Builtin::BI__builtin_nansl: 13652 case Builtin::BI__builtin_nansf128: 13653 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13654 true, Result)) 13655 return Error(E); 13656 return true; 13657 13658 case Builtin::BI__builtin_nan: 13659 case Builtin::BI__builtin_nanf: 13660 case Builtin::BI__builtin_nanl: 13661 case Builtin::BI__builtin_nanf128: 13662 // If this is __builtin_nan() turn this into a nan, otherwise we 13663 // can't constant fold it. 13664 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13665 false, Result)) 13666 return Error(E); 13667 return true; 13668 13669 case Builtin::BI__builtin_fabs: 13670 case Builtin::BI__builtin_fabsf: 13671 case Builtin::BI__builtin_fabsl: 13672 case Builtin::BI__builtin_fabsf128: 13673 // The C standard says "fabs raises no floating-point exceptions, 13674 // even if x is a signaling NaN. The returned value is independent of 13675 // the current rounding direction mode." Therefore constant folding can 13676 // proceed without regard to the floating point settings. 13677 // Reference, WG14 N2478 F.10.4.3 13678 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13679 return false; 13680 13681 if (Result.isNegative()) 13682 Result.changeSign(); 13683 return true; 13684 13685 // FIXME: Builtin::BI__builtin_powi 13686 // FIXME: Builtin::BI__builtin_powif 13687 // FIXME: Builtin::BI__builtin_powil 13688 13689 case Builtin::BI__builtin_copysign: 13690 case Builtin::BI__builtin_copysignf: 13691 case Builtin::BI__builtin_copysignl: 13692 case Builtin::BI__builtin_copysignf128: { 13693 APFloat RHS(0.); 13694 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13695 !EvaluateFloat(E->getArg(1), RHS, Info)) 13696 return false; 13697 Result.copySign(RHS); 13698 return true; 13699 } 13700 } 13701 } 13702 13703 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13704 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13705 ComplexValue CV; 13706 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13707 return false; 13708 Result = CV.FloatReal; 13709 return true; 13710 } 13711 13712 return Visit(E->getSubExpr()); 13713 } 13714 13715 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13716 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13717 ComplexValue CV; 13718 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13719 return false; 13720 Result = CV.FloatImag; 13721 return true; 13722 } 13723 13724 VisitIgnoredValue(E->getSubExpr()); 13725 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13726 Result = llvm::APFloat::getZero(Sem); 13727 return true; 13728 } 13729 13730 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13731 switch (E->getOpcode()) { 13732 default: return Error(E); 13733 case UO_Plus: 13734 return EvaluateFloat(E->getSubExpr(), Result, Info); 13735 case UO_Minus: 13736 // In C standard, WG14 N2478 F.3 p4 13737 // "the unary - raises no floating point exceptions, 13738 // even if the operand is signalling." 13739 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13740 return false; 13741 Result.changeSign(); 13742 return true; 13743 } 13744 } 13745 13746 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13747 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13748 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13749 13750 APFloat RHS(0.0); 13751 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13752 if (!LHSOK && !Info.noteFailure()) 13753 return false; 13754 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13755 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13756 } 13757 13758 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13759 Result = E->getValue(); 13760 return true; 13761 } 13762 13763 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13764 const Expr* SubExpr = E->getSubExpr(); 13765 13766 switch (E->getCastKind()) { 13767 default: 13768 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13769 13770 case CK_IntegralToFloating: { 13771 APSInt IntResult; 13772 const FPOptions FPO = E->getFPFeaturesInEffect( 13773 Info.Ctx.getLangOpts()); 13774 return EvaluateInteger(SubExpr, IntResult, Info) && 13775 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13776 IntResult, E->getType(), Result); 13777 } 13778 13779 case CK_FixedPointToFloating: { 13780 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13781 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13782 return false; 13783 Result = 13784 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13785 return true; 13786 } 13787 13788 case CK_FloatingCast: { 13789 if (!Visit(SubExpr)) 13790 return false; 13791 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13792 Result); 13793 } 13794 13795 case CK_FloatingComplexToReal: { 13796 ComplexValue V; 13797 if (!EvaluateComplex(SubExpr, V, Info)) 13798 return false; 13799 Result = V.getComplexFloatReal(); 13800 return true; 13801 } 13802 } 13803 } 13804 13805 //===----------------------------------------------------------------------===// 13806 // Complex Evaluation (for float and integer) 13807 //===----------------------------------------------------------------------===// 13808 13809 namespace { 13810 class ComplexExprEvaluator 13811 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13812 ComplexValue &Result; 13813 13814 public: 13815 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13816 : ExprEvaluatorBaseTy(info), Result(Result) {} 13817 13818 bool Success(const APValue &V, const Expr *e) { 13819 Result.setFrom(V); 13820 return true; 13821 } 13822 13823 bool ZeroInitialization(const Expr *E); 13824 13825 //===--------------------------------------------------------------------===// 13826 // Visitor Methods 13827 //===--------------------------------------------------------------------===// 13828 13829 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13830 bool VisitCastExpr(const CastExpr *E); 13831 bool VisitBinaryOperator(const BinaryOperator *E); 13832 bool VisitUnaryOperator(const UnaryOperator *E); 13833 bool VisitInitListExpr(const InitListExpr *E); 13834 bool VisitCallExpr(const CallExpr *E); 13835 }; 13836 } // end anonymous namespace 13837 13838 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13839 EvalInfo &Info) { 13840 assert(!E->isValueDependent()); 13841 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13842 return ComplexExprEvaluator(Info, Result).Visit(E); 13843 } 13844 13845 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13846 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13847 if (ElemTy->isRealFloatingType()) { 13848 Result.makeComplexFloat(); 13849 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13850 Result.FloatReal = Zero; 13851 Result.FloatImag = Zero; 13852 } else { 13853 Result.makeComplexInt(); 13854 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13855 Result.IntReal = Zero; 13856 Result.IntImag = Zero; 13857 } 13858 return true; 13859 } 13860 13861 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13862 const Expr* SubExpr = E->getSubExpr(); 13863 13864 if (SubExpr->getType()->isRealFloatingType()) { 13865 Result.makeComplexFloat(); 13866 APFloat &Imag = Result.FloatImag; 13867 if (!EvaluateFloat(SubExpr, Imag, Info)) 13868 return false; 13869 13870 Result.FloatReal = APFloat(Imag.getSemantics()); 13871 return true; 13872 } else { 13873 assert(SubExpr->getType()->isIntegerType() && 13874 "Unexpected imaginary literal."); 13875 13876 Result.makeComplexInt(); 13877 APSInt &Imag = Result.IntImag; 13878 if (!EvaluateInteger(SubExpr, Imag, Info)) 13879 return false; 13880 13881 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13882 return true; 13883 } 13884 } 13885 13886 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13887 13888 switch (E->getCastKind()) { 13889 case CK_BitCast: 13890 case CK_BaseToDerived: 13891 case CK_DerivedToBase: 13892 case CK_UncheckedDerivedToBase: 13893 case CK_Dynamic: 13894 case CK_ToUnion: 13895 case CK_ArrayToPointerDecay: 13896 case CK_FunctionToPointerDecay: 13897 case CK_NullToPointer: 13898 case CK_NullToMemberPointer: 13899 case CK_BaseToDerivedMemberPointer: 13900 case CK_DerivedToBaseMemberPointer: 13901 case CK_MemberPointerToBoolean: 13902 case CK_ReinterpretMemberPointer: 13903 case CK_ConstructorConversion: 13904 case CK_IntegralToPointer: 13905 case CK_PointerToIntegral: 13906 case CK_PointerToBoolean: 13907 case CK_ToVoid: 13908 case CK_VectorSplat: 13909 case CK_IntegralCast: 13910 case CK_BooleanToSignedIntegral: 13911 case CK_IntegralToBoolean: 13912 case CK_IntegralToFloating: 13913 case CK_FloatingToIntegral: 13914 case CK_FloatingToBoolean: 13915 case CK_FloatingCast: 13916 case CK_CPointerToObjCPointerCast: 13917 case CK_BlockPointerToObjCPointerCast: 13918 case CK_AnyPointerToBlockPointerCast: 13919 case CK_ObjCObjectLValueCast: 13920 case CK_FloatingComplexToReal: 13921 case CK_FloatingComplexToBoolean: 13922 case CK_IntegralComplexToReal: 13923 case CK_IntegralComplexToBoolean: 13924 case CK_ARCProduceObject: 13925 case CK_ARCConsumeObject: 13926 case CK_ARCReclaimReturnedObject: 13927 case CK_ARCExtendBlockObject: 13928 case CK_CopyAndAutoreleaseBlockObject: 13929 case CK_BuiltinFnToFnPtr: 13930 case CK_ZeroToOCLOpaqueType: 13931 case CK_NonAtomicToAtomic: 13932 case CK_AddressSpaceConversion: 13933 case CK_IntToOCLSampler: 13934 case CK_FloatingToFixedPoint: 13935 case CK_FixedPointToFloating: 13936 case CK_FixedPointCast: 13937 case CK_FixedPointToBoolean: 13938 case CK_FixedPointToIntegral: 13939 case CK_IntegralToFixedPoint: 13940 llvm_unreachable("invalid cast kind for complex value"); 13941 13942 case CK_LValueToRValue: 13943 case CK_AtomicToNonAtomic: 13944 case CK_NoOp: 13945 case CK_LValueToRValueBitCast: 13946 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13947 13948 case CK_Dependent: 13949 case CK_LValueBitCast: 13950 case CK_UserDefinedConversion: 13951 return Error(E); 13952 13953 case CK_FloatingRealToComplex: { 13954 APFloat &Real = Result.FloatReal; 13955 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13956 return false; 13957 13958 Result.makeComplexFloat(); 13959 Result.FloatImag = APFloat(Real.getSemantics()); 13960 return true; 13961 } 13962 13963 case CK_FloatingComplexCast: { 13964 if (!Visit(E->getSubExpr())) 13965 return false; 13966 13967 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13968 QualType From 13969 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13970 13971 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13972 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13973 } 13974 13975 case CK_FloatingComplexToIntegralComplex: { 13976 if (!Visit(E->getSubExpr())) 13977 return false; 13978 13979 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13980 QualType From 13981 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13982 Result.makeComplexInt(); 13983 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13984 To, Result.IntReal) && 13985 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13986 To, Result.IntImag); 13987 } 13988 13989 case CK_IntegralRealToComplex: { 13990 APSInt &Real = Result.IntReal; 13991 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13992 return false; 13993 13994 Result.makeComplexInt(); 13995 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13996 return true; 13997 } 13998 13999 case CK_IntegralComplexCast: { 14000 if (!Visit(E->getSubExpr())) 14001 return false; 14002 14003 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14004 QualType From 14005 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14006 14007 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14008 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14009 return true; 14010 } 14011 14012 case CK_IntegralComplexToFloatingComplex: { 14013 if (!Visit(E->getSubExpr())) 14014 return false; 14015 14016 const FPOptions FPO = E->getFPFeaturesInEffect( 14017 Info.Ctx.getLangOpts()); 14018 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14019 QualType From 14020 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14021 Result.makeComplexFloat(); 14022 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14023 To, Result.FloatReal) && 14024 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14025 To, Result.FloatImag); 14026 } 14027 } 14028 14029 llvm_unreachable("unknown cast resulting in complex value"); 14030 } 14031 14032 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14033 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14034 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14035 14036 // Track whether the LHS or RHS is real at the type system level. When this is 14037 // the case we can simplify our evaluation strategy. 14038 bool LHSReal = false, RHSReal = false; 14039 14040 bool LHSOK; 14041 if (E->getLHS()->getType()->isRealFloatingType()) { 14042 LHSReal = true; 14043 APFloat &Real = Result.FloatReal; 14044 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14045 if (LHSOK) { 14046 Result.makeComplexFloat(); 14047 Result.FloatImag = APFloat(Real.getSemantics()); 14048 } 14049 } else { 14050 LHSOK = Visit(E->getLHS()); 14051 } 14052 if (!LHSOK && !Info.noteFailure()) 14053 return false; 14054 14055 ComplexValue RHS; 14056 if (E->getRHS()->getType()->isRealFloatingType()) { 14057 RHSReal = true; 14058 APFloat &Real = RHS.FloatReal; 14059 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14060 return false; 14061 RHS.makeComplexFloat(); 14062 RHS.FloatImag = APFloat(Real.getSemantics()); 14063 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14064 return false; 14065 14066 assert(!(LHSReal && RHSReal) && 14067 "Cannot have both operands of a complex operation be real."); 14068 switch (E->getOpcode()) { 14069 default: return Error(E); 14070 case BO_Add: 14071 if (Result.isComplexFloat()) { 14072 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14073 APFloat::rmNearestTiesToEven); 14074 if (LHSReal) 14075 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14076 else if (!RHSReal) 14077 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14078 APFloat::rmNearestTiesToEven); 14079 } else { 14080 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14081 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14082 } 14083 break; 14084 case BO_Sub: 14085 if (Result.isComplexFloat()) { 14086 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14087 APFloat::rmNearestTiesToEven); 14088 if (LHSReal) { 14089 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14090 Result.getComplexFloatImag().changeSign(); 14091 } else if (!RHSReal) { 14092 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14093 APFloat::rmNearestTiesToEven); 14094 } 14095 } else { 14096 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14097 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14098 } 14099 break; 14100 case BO_Mul: 14101 if (Result.isComplexFloat()) { 14102 // This is an implementation of complex multiplication according to the 14103 // constraints laid out in C11 Annex G. The implementation uses the 14104 // following naming scheme: 14105 // (a + ib) * (c + id) 14106 ComplexValue LHS = Result; 14107 APFloat &A = LHS.getComplexFloatReal(); 14108 APFloat &B = LHS.getComplexFloatImag(); 14109 APFloat &C = RHS.getComplexFloatReal(); 14110 APFloat &D = RHS.getComplexFloatImag(); 14111 APFloat &ResR = Result.getComplexFloatReal(); 14112 APFloat &ResI = Result.getComplexFloatImag(); 14113 if (LHSReal) { 14114 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14115 ResR = A * C; 14116 ResI = A * D; 14117 } else if (RHSReal) { 14118 ResR = C * A; 14119 ResI = C * B; 14120 } else { 14121 // In the fully general case, we need to handle NaNs and infinities 14122 // robustly. 14123 APFloat AC = A * C; 14124 APFloat BD = B * D; 14125 APFloat AD = A * D; 14126 APFloat BC = B * C; 14127 ResR = AC - BD; 14128 ResI = AD + BC; 14129 if (ResR.isNaN() && ResI.isNaN()) { 14130 bool Recalc = false; 14131 if (A.isInfinity() || B.isInfinity()) { 14132 A = APFloat::copySign( 14133 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14134 B = APFloat::copySign( 14135 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14136 if (C.isNaN()) 14137 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14138 if (D.isNaN()) 14139 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14140 Recalc = true; 14141 } 14142 if (C.isInfinity() || D.isInfinity()) { 14143 C = APFloat::copySign( 14144 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14145 D = APFloat::copySign( 14146 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14147 if (A.isNaN()) 14148 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14149 if (B.isNaN()) 14150 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14151 Recalc = true; 14152 } 14153 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14154 AD.isInfinity() || BC.isInfinity())) { 14155 if (A.isNaN()) 14156 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14157 if (B.isNaN()) 14158 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14159 if (C.isNaN()) 14160 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14161 if (D.isNaN()) 14162 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14163 Recalc = true; 14164 } 14165 if (Recalc) { 14166 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14167 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14168 } 14169 } 14170 } 14171 } else { 14172 ComplexValue LHS = Result; 14173 Result.getComplexIntReal() = 14174 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14175 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14176 Result.getComplexIntImag() = 14177 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14178 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14179 } 14180 break; 14181 case BO_Div: 14182 if (Result.isComplexFloat()) { 14183 // This is an implementation of complex division according to the 14184 // constraints laid out in C11 Annex G. The implementation uses the 14185 // following naming scheme: 14186 // (a + ib) / (c + id) 14187 ComplexValue LHS = Result; 14188 APFloat &A = LHS.getComplexFloatReal(); 14189 APFloat &B = LHS.getComplexFloatImag(); 14190 APFloat &C = RHS.getComplexFloatReal(); 14191 APFloat &D = RHS.getComplexFloatImag(); 14192 APFloat &ResR = Result.getComplexFloatReal(); 14193 APFloat &ResI = Result.getComplexFloatImag(); 14194 if (RHSReal) { 14195 ResR = A / C; 14196 ResI = B / C; 14197 } else { 14198 if (LHSReal) { 14199 // No real optimizations we can do here, stub out with zero. 14200 B = APFloat::getZero(A.getSemantics()); 14201 } 14202 int DenomLogB = 0; 14203 APFloat MaxCD = maxnum(abs(C), abs(D)); 14204 if (MaxCD.isFinite()) { 14205 DenomLogB = ilogb(MaxCD); 14206 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14207 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14208 } 14209 APFloat Denom = C * C + D * D; 14210 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14211 APFloat::rmNearestTiesToEven); 14212 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14213 APFloat::rmNearestTiesToEven); 14214 if (ResR.isNaN() && ResI.isNaN()) { 14215 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14216 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14217 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14218 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14219 D.isFinite()) { 14220 A = APFloat::copySign( 14221 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14222 B = APFloat::copySign( 14223 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14224 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14225 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14226 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14227 C = APFloat::copySign( 14228 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14229 D = APFloat::copySign( 14230 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14231 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14232 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14233 } 14234 } 14235 } 14236 } else { 14237 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14238 return Error(E, diag::note_expr_divide_by_zero); 14239 14240 ComplexValue LHS = Result; 14241 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14242 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14243 Result.getComplexIntReal() = 14244 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14245 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14246 Result.getComplexIntImag() = 14247 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14248 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14249 } 14250 break; 14251 } 14252 14253 return true; 14254 } 14255 14256 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14257 // Get the operand value into 'Result'. 14258 if (!Visit(E->getSubExpr())) 14259 return false; 14260 14261 switch (E->getOpcode()) { 14262 default: 14263 return Error(E); 14264 case UO_Extension: 14265 return true; 14266 case UO_Plus: 14267 // The result is always just the subexpr. 14268 return true; 14269 case UO_Minus: 14270 if (Result.isComplexFloat()) { 14271 Result.getComplexFloatReal().changeSign(); 14272 Result.getComplexFloatImag().changeSign(); 14273 } 14274 else { 14275 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14276 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14277 } 14278 return true; 14279 case UO_Not: 14280 if (Result.isComplexFloat()) 14281 Result.getComplexFloatImag().changeSign(); 14282 else 14283 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14284 return true; 14285 } 14286 } 14287 14288 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14289 if (E->getNumInits() == 2) { 14290 if (E->getType()->isComplexType()) { 14291 Result.makeComplexFloat(); 14292 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14293 return false; 14294 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14295 return false; 14296 } else { 14297 Result.makeComplexInt(); 14298 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14299 return false; 14300 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14301 return false; 14302 } 14303 return true; 14304 } 14305 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14306 } 14307 14308 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14309 switch (E->getBuiltinCallee()) { 14310 case Builtin::BI__builtin_complex: 14311 Result.makeComplexFloat(); 14312 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14313 return false; 14314 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14315 return false; 14316 return true; 14317 14318 default: 14319 break; 14320 } 14321 14322 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14323 } 14324 14325 //===----------------------------------------------------------------------===// 14326 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14327 // implicit conversion. 14328 //===----------------------------------------------------------------------===// 14329 14330 namespace { 14331 class AtomicExprEvaluator : 14332 public ExprEvaluatorBase<AtomicExprEvaluator> { 14333 const LValue *This; 14334 APValue &Result; 14335 public: 14336 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14337 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14338 14339 bool Success(const APValue &V, const Expr *E) { 14340 Result = V; 14341 return true; 14342 } 14343 14344 bool ZeroInitialization(const Expr *E) { 14345 ImplicitValueInitExpr VIE( 14346 E->getType()->castAs<AtomicType>()->getValueType()); 14347 // For atomic-qualified class (and array) types in C++, initialize the 14348 // _Atomic-wrapped subobject directly, in-place. 14349 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14350 : Evaluate(Result, Info, &VIE); 14351 } 14352 14353 bool VisitCastExpr(const CastExpr *E) { 14354 switch (E->getCastKind()) { 14355 default: 14356 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14357 case CK_NonAtomicToAtomic: 14358 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14359 : Evaluate(Result, Info, E->getSubExpr()); 14360 } 14361 } 14362 }; 14363 } // end anonymous namespace 14364 14365 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14366 EvalInfo &Info) { 14367 assert(!E->isValueDependent()); 14368 assert(E->isRValue() && E->getType()->isAtomicType()); 14369 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14370 } 14371 14372 //===----------------------------------------------------------------------===// 14373 // Void expression evaluation, primarily for a cast to void on the LHS of a 14374 // comma operator 14375 //===----------------------------------------------------------------------===// 14376 14377 namespace { 14378 class VoidExprEvaluator 14379 : public ExprEvaluatorBase<VoidExprEvaluator> { 14380 public: 14381 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14382 14383 bool Success(const APValue &V, const Expr *e) { return true; } 14384 14385 bool ZeroInitialization(const Expr *E) { return true; } 14386 14387 bool VisitCastExpr(const CastExpr *E) { 14388 switch (E->getCastKind()) { 14389 default: 14390 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14391 case CK_ToVoid: 14392 VisitIgnoredValue(E->getSubExpr()); 14393 return true; 14394 } 14395 } 14396 14397 bool VisitCallExpr(const CallExpr *E) { 14398 switch (E->getBuiltinCallee()) { 14399 case Builtin::BI__assume: 14400 case Builtin::BI__builtin_assume: 14401 // The argument is not evaluated! 14402 return true; 14403 14404 case Builtin::BI__builtin_operator_delete: 14405 return HandleOperatorDeleteCall(Info, E); 14406 14407 default: 14408 break; 14409 } 14410 14411 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14412 } 14413 14414 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14415 }; 14416 } // end anonymous namespace 14417 14418 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14419 // We cannot speculatively evaluate a delete expression. 14420 if (Info.SpeculativeEvaluationDepth) 14421 return false; 14422 14423 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14424 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14425 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14426 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14427 return false; 14428 } 14429 14430 const Expr *Arg = E->getArgument(); 14431 14432 LValue Pointer; 14433 if (!EvaluatePointer(Arg, Pointer, Info)) 14434 return false; 14435 if (Pointer.Designator.Invalid) 14436 return false; 14437 14438 // Deleting a null pointer has no effect. 14439 if (Pointer.isNullPointer()) { 14440 // This is the only case where we need to produce an extension warning: 14441 // the only other way we can succeed is if we find a dynamic allocation, 14442 // and we will have warned when we allocated it in that case. 14443 if (!Info.getLangOpts().CPlusPlus20) 14444 Info.CCEDiag(E, diag::note_constexpr_new); 14445 return true; 14446 } 14447 14448 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14449 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14450 if (!Alloc) 14451 return false; 14452 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14453 14454 // For the non-array case, the designator must be empty if the static type 14455 // does not have a virtual destructor. 14456 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14457 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14458 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14459 << Arg->getType()->getPointeeType() << AllocType; 14460 return false; 14461 } 14462 14463 // For a class type with a virtual destructor, the selected operator delete 14464 // is the one looked up when building the destructor. 14465 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14466 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14467 if (VirtualDelete && 14468 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14469 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14470 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14471 return false; 14472 } 14473 } 14474 14475 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14476 (*Alloc)->Value, AllocType)) 14477 return false; 14478 14479 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14480 // The element was already erased. This means the destructor call also 14481 // deleted the object. 14482 // FIXME: This probably results in undefined behavior before we get this 14483 // far, and should be diagnosed elsewhere first. 14484 Info.FFDiag(E, diag::note_constexpr_double_delete); 14485 return false; 14486 } 14487 14488 return true; 14489 } 14490 14491 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14492 assert(!E->isValueDependent()); 14493 assert(E->isRValue() && E->getType()->isVoidType()); 14494 return VoidExprEvaluator(Info).Visit(E); 14495 } 14496 14497 //===----------------------------------------------------------------------===// 14498 // Top level Expr::EvaluateAsRValue method. 14499 //===----------------------------------------------------------------------===// 14500 14501 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14502 assert(!E->isValueDependent()); 14503 // In C, function designators are not lvalues, but we evaluate them as if they 14504 // are. 14505 QualType T = E->getType(); 14506 if (E->isGLValue() || T->isFunctionType()) { 14507 LValue LV; 14508 if (!EvaluateLValue(E, LV, Info)) 14509 return false; 14510 LV.moveInto(Result); 14511 } else if (T->isVectorType()) { 14512 if (!EvaluateVector(E, Result, Info)) 14513 return false; 14514 } else if (T->isIntegralOrEnumerationType()) { 14515 if (!IntExprEvaluator(Info, Result).Visit(E)) 14516 return false; 14517 } else if (T->hasPointerRepresentation()) { 14518 LValue LV; 14519 if (!EvaluatePointer(E, LV, Info)) 14520 return false; 14521 LV.moveInto(Result); 14522 } else if (T->isRealFloatingType()) { 14523 llvm::APFloat F(0.0); 14524 if (!EvaluateFloat(E, F, Info)) 14525 return false; 14526 Result = APValue(F); 14527 } else if (T->isAnyComplexType()) { 14528 ComplexValue C; 14529 if (!EvaluateComplex(E, C, Info)) 14530 return false; 14531 C.moveInto(Result); 14532 } else if (T->isFixedPointType()) { 14533 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14534 } else if (T->isMemberPointerType()) { 14535 MemberPtr P; 14536 if (!EvaluateMemberPointer(E, P, Info)) 14537 return false; 14538 P.moveInto(Result); 14539 return true; 14540 } else if (T->isArrayType()) { 14541 LValue LV; 14542 APValue &Value = 14543 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14544 if (!EvaluateArray(E, LV, Value, Info)) 14545 return false; 14546 Result = Value; 14547 } else if (T->isRecordType()) { 14548 LValue LV; 14549 APValue &Value = 14550 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14551 if (!EvaluateRecord(E, LV, Value, Info)) 14552 return false; 14553 Result = Value; 14554 } else if (T->isVoidType()) { 14555 if (!Info.getLangOpts().CPlusPlus11) 14556 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14557 << E->getType(); 14558 if (!EvaluateVoid(E, Info)) 14559 return false; 14560 } else if (T->isAtomicType()) { 14561 QualType Unqual = T.getAtomicUnqualifiedType(); 14562 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14563 LValue LV; 14564 APValue &Value = Info.CurrentCall->createTemporary( 14565 E, Unqual, ScopeKind::FullExpression, LV); 14566 if (!EvaluateAtomic(E, &LV, Value, Info)) 14567 return false; 14568 } else { 14569 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14570 return false; 14571 } 14572 } else if (Info.getLangOpts().CPlusPlus11) { 14573 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14574 return false; 14575 } else { 14576 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14577 return false; 14578 } 14579 14580 return true; 14581 } 14582 14583 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14584 /// cases, the in-place evaluation is essential, since later initializers for 14585 /// an object can indirectly refer to subobjects which were initialized earlier. 14586 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14587 const Expr *E, bool AllowNonLiteralTypes) { 14588 assert(!E->isValueDependent()); 14589 14590 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14591 return false; 14592 14593 if (E->isRValue()) { 14594 // Evaluate arrays and record types in-place, so that later initializers can 14595 // refer to earlier-initialized members of the object. 14596 QualType T = E->getType(); 14597 if (T->isArrayType()) 14598 return EvaluateArray(E, This, Result, Info); 14599 else if (T->isRecordType()) 14600 return EvaluateRecord(E, This, Result, Info); 14601 else if (T->isAtomicType()) { 14602 QualType Unqual = T.getAtomicUnqualifiedType(); 14603 if (Unqual->isArrayType() || Unqual->isRecordType()) 14604 return EvaluateAtomic(E, &This, Result, Info); 14605 } 14606 } 14607 14608 // For any other type, in-place evaluation is unimportant. 14609 return Evaluate(Result, Info, E); 14610 } 14611 14612 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14613 /// lvalue-to-rvalue cast if it is an lvalue. 14614 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result, 14615 bool &Dependent) { 14616 assert(!E->isValueDependent()); 14617 if (Info.EnableNewConstInterp) { 14618 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14619 return false; 14620 } else { 14621 if (E->getType().isNull()) 14622 return false; 14623 14624 if (!CheckLiteralType(Info, E)) 14625 return false; 14626 14627 if (!::Evaluate(Result, Info, E)) 14628 return false; 14629 14630 if (E->isGLValue()) { 14631 LValue LV; 14632 LV.setFrom(Info.Ctx, Result); 14633 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14634 return false; 14635 } 14636 } 14637 14638 // Check this core constant expression is a constant expression. 14639 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14640 ConstantExprKind::Normal, Dependent) && 14641 CheckMemoryLeaks(Info); 14642 } 14643 14644 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14645 const ASTContext &Ctx, bool &IsConst) { 14646 // Fast-path evaluations of integer literals, since we sometimes see files 14647 // containing vast quantities of these. 14648 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14649 Result.Val = APValue(APSInt(L->getValue(), 14650 L->getType()->isUnsignedIntegerType())); 14651 IsConst = true; 14652 return true; 14653 } 14654 14655 // This case should be rare, but we need to check it before we check on 14656 // the type below. 14657 if (Exp->getType().isNull()) { 14658 IsConst = false; 14659 return true; 14660 } 14661 14662 // FIXME: Evaluating values of large array and record types can cause 14663 // performance problems. Only do so in C++11 for now. 14664 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14665 Exp->getType()->isRecordType()) && 14666 !Ctx.getLangOpts().CPlusPlus11) { 14667 IsConst = false; 14668 return true; 14669 } 14670 return false; 14671 } 14672 14673 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14674 Expr::SideEffectsKind SEK) { 14675 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14676 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14677 } 14678 14679 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14680 const ASTContext &Ctx, EvalInfo &Info) { 14681 assert(!E->isValueDependent()); 14682 bool IsConst; 14683 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14684 return IsConst; 14685 14686 return EvaluateAsRValue(Info, E, Result.Val, Result.Dependent); 14687 } 14688 14689 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14690 const ASTContext &Ctx, 14691 Expr::SideEffectsKind AllowSideEffects, 14692 EvalInfo &Info) { 14693 assert(!E->isValueDependent()); 14694 if (!E->getType()->isIntegralOrEnumerationType()) 14695 return false; 14696 14697 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14698 !ExprResult.Val.isInt() || 14699 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14700 return false; 14701 14702 return true; 14703 } 14704 14705 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14706 const ASTContext &Ctx, 14707 Expr::SideEffectsKind AllowSideEffects, 14708 EvalInfo &Info) { 14709 assert(!E->isValueDependent()); 14710 if (!E->getType()->isFixedPointType()) 14711 return false; 14712 14713 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14714 return false; 14715 14716 if (!ExprResult.Val.isFixedPoint() || 14717 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14718 return false; 14719 14720 return true; 14721 } 14722 14723 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14724 /// any crazy technique (that has nothing to do with language standards) that 14725 /// we want to. If this function returns true, it returns the folded constant 14726 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14727 /// will be applied to the result. 14728 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14729 bool InConstantContext) const { 14730 assert(!isValueDependent() && 14731 "Expression evaluator can't be called on a dependent expression."); 14732 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14733 Info.InConstantContext = InConstantContext; 14734 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14735 } 14736 14737 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14738 bool InConstantContext) const { 14739 assert(!isValueDependent() && 14740 "Expression evaluator can't be called on a dependent expression."); 14741 EvalResult Scratch; 14742 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14743 HandleConversionToBool(Scratch.Val, Result); 14744 } 14745 14746 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14747 SideEffectsKind AllowSideEffects, 14748 bool InConstantContext) const { 14749 assert(!isValueDependent() && 14750 "Expression evaluator can't be called on a dependent expression."); 14751 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14752 Info.InConstantContext = InConstantContext; 14753 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14754 } 14755 14756 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14757 SideEffectsKind AllowSideEffects, 14758 bool InConstantContext) const { 14759 assert(!isValueDependent() && 14760 "Expression evaluator can't be called on a dependent expression."); 14761 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14762 Info.InConstantContext = InConstantContext; 14763 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14764 } 14765 14766 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14767 SideEffectsKind AllowSideEffects, 14768 bool InConstantContext) const { 14769 assert(!isValueDependent() && 14770 "Expression evaluator can't be called on a dependent expression."); 14771 14772 if (!getType()->isRealFloatingType()) 14773 return false; 14774 14775 EvalResult ExprResult; 14776 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14777 !ExprResult.Val.isFloat() || 14778 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14779 return false; 14780 14781 Result = ExprResult.Val.getFloat(); 14782 return true; 14783 } 14784 14785 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14786 bool InConstantContext) const { 14787 assert(!isValueDependent() && 14788 "Expression evaluator can't be called on a dependent expression."); 14789 14790 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14791 Info.InConstantContext = InConstantContext; 14792 LValue LV; 14793 CheckedTemporaries CheckedTemps; 14794 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14795 Result.HasSideEffects || 14796 !CheckLValueConstantExpression( 14797 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV, 14798 ConstantExprKind::Normal, CheckedTemps, Result.Dependent)) 14799 return false; 14800 14801 LV.moveInto(Result.Val); 14802 return true; 14803 } 14804 14805 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14806 APValue DestroyedValue, QualType Type, 14807 SourceLocation Loc, Expr::EvalStatus &EStatus) { 14808 EvalInfo Info(Ctx, EStatus, EvalInfo::EM_ConstantExpression); 14809 Info.setEvaluatingDecl(Base, DestroyedValue, 14810 EvalInfo::EvaluatingDeclKind::Dtor); 14811 Info.InConstantContext = true; 14812 14813 LValue LVal; 14814 LVal.set(Base); 14815 14816 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14817 EStatus.HasSideEffects) 14818 return false; 14819 14820 if (!Info.discardCleanups()) 14821 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14822 14823 return true; 14824 } 14825 14826 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14827 ConstantExprKind Kind) const { 14828 assert(!isValueDependent() && 14829 "Expression evaluator can't be called on a dependent expression."); 14830 14831 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14832 EvalInfo Info(Ctx, Result, EM); 14833 Info.InConstantContext = true; 14834 14835 // The type of the object we're initializing is 'const T' for a class NTTP. 14836 QualType T = getType(); 14837 if (Kind == ConstantExprKind::ClassTemplateArgument) 14838 T.addConst(); 14839 14840 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14841 // represent the result of the evaluation. CheckConstantExpression ensures 14842 // this doesn't escape. 14843 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14844 APValue::LValueBase Base(&BaseMTE); 14845 14846 Info.setEvaluatingDecl(Base, Result.Val); 14847 LValue LVal; 14848 LVal.set(Base); 14849 14850 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14851 return false; 14852 14853 if (!Info.discardCleanups()) 14854 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14855 14856 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14857 Result.Val, Kind, Result.Dependent)) 14858 return false; 14859 if (!CheckMemoryLeaks(Info)) 14860 return false; 14861 14862 // If this is a class template argument, it's required to have constant 14863 // destruction too. 14864 if (Kind == ConstantExprKind::ClassTemplateArgument && 14865 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result) || 14866 Result.HasSideEffects)) { 14867 // FIXME: Prefix a note to indicate that the problem is lack of constant 14868 // destruction. 14869 return false; 14870 } 14871 14872 return true; 14873 } 14874 14875 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14876 const VarDecl *VD, 14877 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14878 bool IsConstantInitialization) const { 14879 assert(!isValueDependent() && 14880 "Expression evaluator can't be called on a dependent expression."); 14881 14882 // FIXME: Evaluating initializers for large array and record types can cause 14883 // performance problems. Only do so in C++11 for now. 14884 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14885 !Ctx.getLangOpts().CPlusPlus11) 14886 return false; 14887 14888 Expr::EvalStatus EStatus; 14889 EStatus.Diag = &Notes; 14890 14891 EvalInfo Info(Ctx, EStatus, 14892 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14893 ? EvalInfo::EM_ConstantExpression 14894 : EvalInfo::EM_ConstantFold); 14895 Info.setEvaluatingDecl(VD, Value); 14896 Info.InConstantContext = IsConstantInitialization; 14897 14898 SourceLocation DeclLoc = VD->getLocation(); 14899 QualType DeclTy = VD->getType(); 14900 14901 if (Info.EnableNewConstInterp) { 14902 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14903 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14904 return false; 14905 } else { 14906 LValue LVal; 14907 LVal.set(VD); 14908 14909 if (!EvaluateInPlace(Value, Info, LVal, this, 14910 /*AllowNonLiteralTypes=*/true) || 14911 EStatus.HasSideEffects) 14912 return false; 14913 14914 // At this point, any lifetime-extended temporaries are completely 14915 // initialized. 14916 Info.performLifetimeExtension(); 14917 14918 if (!Info.discardCleanups()) 14919 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14920 } 14921 bool Dependent = false; 14922 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 14923 ConstantExprKind::Normal, Dependent) && 14924 CheckMemoryLeaks(Info); 14925 } 14926 14927 bool VarDecl::evaluateDestruction( 14928 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14929 Expr::EvalStatus EStatus; 14930 EStatus.Diag = &Notes; 14931 14932 // Make a copy of the value for the destructor to mutate, if we know it. 14933 // Otherwise, treat the value as default-initialized; if the destructor works 14934 // anyway, then the destruction is constant (and must be essentially empty). 14935 APValue DestroyedValue; 14936 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14937 DestroyedValue = *getEvaluatedValue(); 14938 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14939 return false; 14940 14941 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 14942 getType(), getLocation(), EStatus) || 14943 EStatus.HasSideEffects) 14944 return false; 14945 14946 ensureEvaluatedStmt()->HasConstantDestruction = true; 14947 return true; 14948 } 14949 14950 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14951 /// constant folded, but discard the result. 14952 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14953 assert(!isValueDependent() && 14954 "Expression evaluator can't be called on a dependent expression."); 14955 14956 EvalResult Result; 14957 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14958 !hasUnacceptableSideEffect(Result, SEK); 14959 } 14960 14961 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14962 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14963 assert(!isValueDependent() && 14964 "Expression evaluator can't be called on a dependent expression."); 14965 14966 EvalResult EVResult; 14967 EVResult.Diag = Diag; 14968 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14969 Info.InConstantContext = true; 14970 14971 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14972 (void)Result; 14973 assert(Result && "Could not evaluate expression"); 14974 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14975 14976 return EVResult.Val.getInt(); 14977 } 14978 14979 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14980 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14981 assert(!isValueDependent() && 14982 "Expression evaluator can't be called on a dependent expression."); 14983 14984 EvalResult EVResult; 14985 EVResult.Diag = Diag; 14986 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14987 Info.InConstantContext = true; 14988 Info.CheckingForUndefinedBehavior = true; 14989 14990 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14991 (void)Result; 14992 assert(Result && "Could not evaluate expression"); 14993 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14994 14995 return EVResult.Val.getInt(); 14996 } 14997 14998 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14999 assert(!isValueDependent() && 15000 "Expression evaluator can't be called on a dependent expression."); 15001 15002 EvalResult EVResult; 15003 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15004 Info.CheckingForUndefinedBehavior = true; 15005 (void)::EvaluateAsRValue(this, EVResult, Ctx, Info); 15006 } 15007 15008 bool Expr::EvalResult::isGlobalLValue() const { 15009 assert(Val.isLValue()); 15010 return IsGlobalLValue(Val.getLValueBase()); 15011 } 15012 15013 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15014 /// an integer constant expression. 15015 15016 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15017 /// comma, etc 15018 15019 // CheckICE - This function does the fundamental ICE checking: the returned 15020 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15021 // and a (possibly null) SourceLocation indicating the location of the problem. 15022 // 15023 // Note that to reduce code duplication, this helper does no evaluation 15024 // itself; the caller checks whether the expression is evaluatable, and 15025 // in the rare cases where CheckICE actually cares about the evaluated 15026 // value, it calls into Evaluate. 15027 15028 namespace { 15029 15030 enum ICEKind { 15031 /// This expression is an ICE. 15032 IK_ICE, 15033 /// This expression is not an ICE, but if it isn't evaluated, it's 15034 /// a legal subexpression for an ICE. This return value is used to handle 15035 /// the comma operator in C99 mode, and non-constant subexpressions. 15036 IK_ICEIfUnevaluated, 15037 /// This expression is not an ICE, and is not a legal subexpression for one. 15038 IK_NotICE 15039 }; 15040 15041 struct ICEDiag { 15042 ICEKind Kind; 15043 SourceLocation Loc; 15044 15045 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15046 }; 15047 15048 } 15049 15050 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15051 15052 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15053 15054 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15055 Expr::EvalResult EVResult; 15056 Expr::EvalStatus Status; 15057 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15058 15059 Info.InConstantContext = true; 15060 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15061 !EVResult.Val.isInt()) 15062 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15063 15064 return NoDiag(); 15065 } 15066 15067 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15068 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15069 if (!E->getType()->isIntegralOrEnumerationType()) 15070 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15071 15072 switch (E->getStmtClass()) { 15073 #define ABSTRACT_STMT(Node) 15074 #define STMT(Node, Base) case Expr::Node##Class: 15075 #define EXPR(Node, Base) 15076 #include "clang/AST/StmtNodes.inc" 15077 case Expr::PredefinedExprClass: 15078 case Expr::FloatingLiteralClass: 15079 case Expr::ImaginaryLiteralClass: 15080 case Expr::StringLiteralClass: 15081 case Expr::ArraySubscriptExprClass: 15082 case Expr::MatrixSubscriptExprClass: 15083 case Expr::OMPArraySectionExprClass: 15084 case Expr::OMPArrayShapingExprClass: 15085 case Expr::OMPIteratorExprClass: 15086 case Expr::MemberExprClass: 15087 case Expr::CompoundAssignOperatorClass: 15088 case Expr::CompoundLiteralExprClass: 15089 case Expr::ExtVectorElementExprClass: 15090 case Expr::DesignatedInitExprClass: 15091 case Expr::ArrayInitLoopExprClass: 15092 case Expr::ArrayInitIndexExprClass: 15093 case Expr::NoInitExprClass: 15094 case Expr::DesignatedInitUpdateExprClass: 15095 case Expr::ImplicitValueInitExprClass: 15096 case Expr::ParenListExprClass: 15097 case Expr::VAArgExprClass: 15098 case Expr::AddrLabelExprClass: 15099 case Expr::StmtExprClass: 15100 case Expr::CXXMemberCallExprClass: 15101 case Expr::CUDAKernelCallExprClass: 15102 case Expr::CXXAddrspaceCastExprClass: 15103 case Expr::CXXDynamicCastExprClass: 15104 case Expr::CXXTypeidExprClass: 15105 case Expr::CXXUuidofExprClass: 15106 case Expr::MSPropertyRefExprClass: 15107 case Expr::MSPropertySubscriptExprClass: 15108 case Expr::CXXNullPtrLiteralExprClass: 15109 case Expr::UserDefinedLiteralClass: 15110 case Expr::CXXThisExprClass: 15111 case Expr::CXXThrowExprClass: 15112 case Expr::CXXNewExprClass: 15113 case Expr::CXXDeleteExprClass: 15114 case Expr::CXXPseudoDestructorExprClass: 15115 case Expr::UnresolvedLookupExprClass: 15116 case Expr::TypoExprClass: 15117 case Expr::RecoveryExprClass: 15118 case Expr::DependentScopeDeclRefExprClass: 15119 case Expr::CXXConstructExprClass: 15120 case Expr::CXXInheritedCtorInitExprClass: 15121 case Expr::CXXStdInitializerListExprClass: 15122 case Expr::CXXBindTemporaryExprClass: 15123 case Expr::ExprWithCleanupsClass: 15124 case Expr::CXXTemporaryObjectExprClass: 15125 case Expr::CXXUnresolvedConstructExprClass: 15126 case Expr::CXXDependentScopeMemberExprClass: 15127 case Expr::UnresolvedMemberExprClass: 15128 case Expr::ObjCStringLiteralClass: 15129 case Expr::ObjCBoxedExprClass: 15130 case Expr::ObjCArrayLiteralClass: 15131 case Expr::ObjCDictionaryLiteralClass: 15132 case Expr::ObjCEncodeExprClass: 15133 case Expr::ObjCMessageExprClass: 15134 case Expr::ObjCSelectorExprClass: 15135 case Expr::ObjCProtocolExprClass: 15136 case Expr::ObjCIvarRefExprClass: 15137 case Expr::ObjCPropertyRefExprClass: 15138 case Expr::ObjCSubscriptRefExprClass: 15139 case Expr::ObjCIsaExprClass: 15140 case Expr::ObjCAvailabilityCheckExprClass: 15141 case Expr::ShuffleVectorExprClass: 15142 case Expr::ConvertVectorExprClass: 15143 case Expr::BlockExprClass: 15144 case Expr::NoStmtClass: 15145 case Expr::OpaqueValueExprClass: 15146 case Expr::PackExpansionExprClass: 15147 case Expr::SubstNonTypeTemplateParmPackExprClass: 15148 case Expr::FunctionParmPackExprClass: 15149 case Expr::AsTypeExprClass: 15150 case Expr::ObjCIndirectCopyRestoreExprClass: 15151 case Expr::MaterializeTemporaryExprClass: 15152 case Expr::PseudoObjectExprClass: 15153 case Expr::AtomicExprClass: 15154 case Expr::LambdaExprClass: 15155 case Expr::CXXFoldExprClass: 15156 case Expr::CoawaitExprClass: 15157 case Expr::DependentCoawaitExprClass: 15158 case Expr::CoyieldExprClass: 15159 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15160 15161 case Expr::InitListExprClass: { 15162 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15163 // form "T x = { a };" is equivalent to "T x = a;". 15164 // Unless we're initializing a reference, T is a scalar as it is known to be 15165 // of integral or enumeration type. 15166 if (E->isRValue()) 15167 if (cast<InitListExpr>(E)->getNumInits() == 1) 15168 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15169 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15170 } 15171 15172 case Expr::SizeOfPackExprClass: 15173 case Expr::GNUNullExprClass: 15174 case Expr::SourceLocExprClass: 15175 return NoDiag(); 15176 15177 case Expr::SubstNonTypeTemplateParmExprClass: 15178 return 15179 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15180 15181 case Expr::ConstantExprClass: 15182 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15183 15184 case Expr::ParenExprClass: 15185 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15186 case Expr::GenericSelectionExprClass: 15187 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15188 case Expr::IntegerLiteralClass: 15189 case Expr::FixedPointLiteralClass: 15190 case Expr::CharacterLiteralClass: 15191 case Expr::ObjCBoolLiteralExprClass: 15192 case Expr::CXXBoolLiteralExprClass: 15193 case Expr::CXXScalarValueInitExprClass: 15194 case Expr::TypeTraitExprClass: 15195 case Expr::ConceptSpecializationExprClass: 15196 case Expr::RequiresExprClass: 15197 case Expr::ArrayTypeTraitExprClass: 15198 case Expr::ExpressionTraitExprClass: 15199 case Expr::CXXNoexceptExprClass: 15200 return NoDiag(); 15201 case Expr::CallExprClass: 15202 case Expr::CXXOperatorCallExprClass: { 15203 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15204 // constant expressions, but they can never be ICEs because an ICE cannot 15205 // contain an operand of (pointer to) function type. 15206 const CallExpr *CE = cast<CallExpr>(E); 15207 if (CE->getBuiltinCallee()) 15208 return CheckEvalInICE(E, Ctx); 15209 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15210 } 15211 case Expr::CXXRewrittenBinaryOperatorClass: 15212 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15213 Ctx); 15214 case Expr::DeclRefExprClass: { 15215 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15216 if (isa<EnumConstantDecl>(D)) 15217 return NoDiag(); 15218 15219 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15220 // integer variables in constant expressions: 15221 // 15222 // C++ 7.1.5.1p2 15223 // A variable of non-volatile const-qualified integral or enumeration 15224 // type initialized by an ICE can be used in ICEs. 15225 // 15226 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15227 // that mode, use of reference variables should not be allowed. 15228 const VarDecl *VD = dyn_cast<VarDecl>(D); 15229 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15230 !VD->getType()->isReferenceType()) 15231 return NoDiag(); 15232 15233 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15234 } 15235 case Expr::UnaryOperatorClass: { 15236 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15237 switch (Exp->getOpcode()) { 15238 case UO_PostInc: 15239 case UO_PostDec: 15240 case UO_PreInc: 15241 case UO_PreDec: 15242 case UO_AddrOf: 15243 case UO_Deref: 15244 case UO_Coawait: 15245 // C99 6.6/3 allows increment and decrement within unevaluated 15246 // subexpressions of constant expressions, but they can never be ICEs 15247 // because an ICE cannot contain an lvalue operand. 15248 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15249 case UO_Extension: 15250 case UO_LNot: 15251 case UO_Plus: 15252 case UO_Minus: 15253 case UO_Not: 15254 case UO_Real: 15255 case UO_Imag: 15256 return CheckICE(Exp->getSubExpr(), Ctx); 15257 } 15258 llvm_unreachable("invalid unary operator class"); 15259 } 15260 case Expr::OffsetOfExprClass: { 15261 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15262 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15263 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15264 // compliance: we should warn earlier for offsetof expressions with 15265 // array subscripts that aren't ICEs, and if the array subscripts 15266 // are ICEs, the value of the offsetof must be an integer constant. 15267 return CheckEvalInICE(E, Ctx); 15268 } 15269 case Expr::UnaryExprOrTypeTraitExprClass: { 15270 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15271 if ((Exp->getKind() == UETT_SizeOf) && 15272 Exp->getTypeOfArgument()->isVariableArrayType()) 15273 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15274 return NoDiag(); 15275 } 15276 case Expr::BinaryOperatorClass: { 15277 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15278 switch (Exp->getOpcode()) { 15279 case BO_PtrMemD: 15280 case BO_PtrMemI: 15281 case BO_Assign: 15282 case BO_MulAssign: 15283 case BO_DivAssign: 15284 case BO_RemAssign: 15285 case BO_AddAssign: 15286 case BO_SubAssign: 15287 case BO_ShlAssign: 15288 case BO_ShrAssign: 15289 case BO_AndAssign: 15290 case BO_XorAssign: 15291 case BO_OrAssign: 15292 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15293 // constant expressions, but they can never be ICEs because an ICE cannot 15294 // contain an lvalue operand. 15295 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15296 15297 case BO_Mul: 15298 case BO_Div: 15299 case BO_Rem: 15300 case BO_Add: 15301 case BO_Sub: 15302 case BO_Shl: 15303 case BO_Shr: 15304 case BO_LT: 15305 case BO_GT: 15306 case BO_LE: 15307 case BO_GE: 15308 case BO_EQ: 15309 case BO_NE: 15310 case BO_And: 15311 case BO_Xor: 15312 case BO_Or: 15313 case BO_Comma: 15314 case BO_Cmp: { 15315 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15316 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15317 if (Exp->getOpcode() == BO_Div || 15318 Exp->getOpcode() == BO_Rem) { 15319 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15320 // we don't evaluate one. 15321 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15322 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15323 if (REval == 0) 15324 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15325 if (REval.isSigned() && REval.isAllOnesValue()) { 15326 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15327 if (LEval.isMinSignedValue()) 15328 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15329 } 15330 } 15331 } 15332 if (Exp->getOpcode() == BO_Comma) { 15333 if (Ctx.getLangOpts().C99) { 15334 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15335 // if it isn't evaluated. 15336 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15337 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15338 } else { 15339 // In both C89 and C++, commas in ICEs are illegal. 15340 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15341 } 15342 } 15343 return Worst(LHSResult, RHSResult); 15344 } 15345 case BO_LAnd: 15346 case BO_LOr: { 15347 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15348 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15349 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15350 // Rare case where the RHS has a comma "side-effect"; we need 15351 // to actually check the condition to see whether the side 15352 // with the comma is evaluated. 15353 if ((Exp->getOpcode() == BO_LAnd) != 15354 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15355 return RHSResult; 15356 return NoDiag(); 15357 } 15358 15359 return Worst(LHSResult, RHSResult); 15360 } 15361 } 15362 llvm_unreachable("invalid binary operator kind"); 15363 } 15364 case Expr::ImplicitCastExprClass: 15365 case Expr::CStyleCastExprClass: 15366 case Expr::CXXFunctionalCastExprClass: 15367 case Expr::CXXStaticCastExprClass: 15368 case Expr::CXXReinterpretCastExprClass: 15369 case Expr::CXXConstCastExprClass: 15370 case Expr::ObjCBridgedCastExprClass: { 15371 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15372 if (isa<ExplicitCastExpr>(E)) { 15373 if (const FloatingLiteral *FL 15374 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15375 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15376 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15377 APSInt IgnoredVal(DestWidth, !DestSigned); 15378 bool Ignored; 15379 // If the value does not fit in the destination type, the behavior is 15380 // undefined, so we are not required to treat it as a constant 15381 // expression. 15382 if (FL->getValue().convertToInteger(IgnoredVal, 15383 llvm::APFloat::rmTowardZero, 15384 &Ignored) & APFloat::opInvalidOp) 15385 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15386 return NoDiag(); 15387 } 15388 } 15389 switch (cast<CastExpr>(E)->getCastKind()) { 15390 case CK_LValueToRValue: 15391 case CK_AtomicToNonAtomic: 15392 case CK_NonAtomicToAtomic: 15393 case CK_NoOp: 15394 case CK_IntegralToBoolean: 15395 case CK_IntegralCast: 15396 return CheckICE(SubExpr, Ctx); 15397 default: 15398 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15399 } 15400 } 15401 case Expr::BinaryConditionalOperatorClass: { 15402 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15403 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15404 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15405 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15406 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15407 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15408 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15409 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15410 return FalseResult; 15411 } 15412 case Expr::ConditionalOperatorClass: { 15413 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15414 // If the condition (ignoring parens) is a __builtin_constant_p call, 15415 // then only the true side is actually considered in an integer constant 15416 // expression, and it is fully evaluated. This is an important GNU 15417 // extension. See GCC PR38377 for discussion. 15418 if (const CallExpr *CallCE 15419 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15420 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15421 return CheckEvalInICE(E, Ctx); 15422 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15423 if (CondResult.Kind == IK_NotICE) 15424 return CondResult; 15425 15426 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15427 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15428 15429 if (TrueResult.Kind == IK_NotICE) 15430 return TrueResult; 15431 if (FalseResult.Kind == IK_NotICE) 15432 return FalseResult; 15433 if (CondResult.Kind == IK_ICEIfUnevaluated) 15434 return CondResult; 15435 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15436 return NoDiag(); 15437 // Rare case where the diagnostics depend on which side is evaluated 15438 // Note that if we get here, CondResult is 0, and at least one of 15439 // TrueResult and FalseResult is non-zero. 15440 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15441 return FalseResult; 15442 return TrueResult; 15443 } 15444 case Expr::CXXDefaultArgExprClass: 15445 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15446 case Expr::CXXDefaultInitExprClass: 15447 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15448 case Expr::ChooseExprClass: { 15449 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15450 } 15451 case Expr::BuiltinBitCastExprClass: { 15452 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15453 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15454 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15455 } 15456 } 15457 15458 llvm_unreachable("Invalid StmtClass!"); 15459 } 15460 15461 /// Evaluate an expression as a C++11 integral constant expression. 15462 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15463 const Expr *E, 15464 llvm::APSInt *Value, 15465 SourceLocation *Loc) { 15466 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15467 if (Loc) *Loc = E->getExprLoc(); 15468 return false; 15469 } 15470 15471 APValue Result; 15472 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15473 return false; 15474 15475 if (!Result.isInt()) { 15476 if (Loc) *Loc = E->getExprLoc(); 15477 return false; 15478 } 15479 15480 if (Value) *Value = Result.getInt(); 15481 return true; 15482 } 15483 15484 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15485 SourceLocation *Loc) const { 15486 assert(!isValueDependent() && 15487 "Expression evaluator can't be called on a dependent expression."); 15488 15489 if (Ctx.getLangOpts().CPlusPlus11) 15490 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15491 15492 ICEDiag D = CheckICE(this, Ctx); 15493 if (D.Kind != IK_ICE) { 15494 if (Loc) *Loc = D.Loc; 15495 return false; 15496 } 15497 return true; 15498 } 15499 15500 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15501 SourceLocation *Loc, 15502 bool isEvaluated) const { 15503 assert(!isValueDependent() && 15504 "Expression evaluator can't be called on a dependent expression."); 15505 15506 APSInt Value; 15507 15508 if (Ctx.getLangOpts().CPlusPlus11) { 15509 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15510 return Value; 15511 return None; 15512 } 15513 15514 if (!isIntegerConstantExpr(Ctx, Loc)) 15515 return None; 15516 15517 // The only possible side-effects here are due to UB discovered in the 15518 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15519 // required to treat the expression as an ICE, so we produce the folded 15520 // value. 15521 EvalResult ExprResult; 15522 Expr::EvalStatus Status; 15523 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15524 Info.InConstantContext = true; 15525 15526 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15527 llvm_unreachable("ICE cannot be evaluated!"); 15528 15529 return ExprResult.Val.getInt(); 15530 } 15531 15532 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15533 assert(!isValueDependent() && 15534 "Expression evaluator can't be called on a dependent expression."); 15535 15536 return CheckICE(this, Ctx).Kind == IK_ICE; 15537 } 15538 15539 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15540 SourceLocation *Loc) const { 15541 assert(!isValueDependent() && 15542 "Expression evaluator can't be called on a dependent expression."); 15543 15544 // We support this checking in C++98 mode in order to diagnose compatibility 15545 // issues. 15546 assert(Ctx.getLangOpts().CPlusPlus); 15547 15548 // Build evaluation settings. 15549 Expr::EvalStatus Status; 15550 SmallVector<PartialDiagnosticAt, 8> Diags; 15551 Status.Diag = &Diags; 15552 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15553 15554 APValue Scratch; 15555 bool Dependent = false; 15556 bool IsConstExpr = 15557 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch, Dependent) && 15558 // FIXME: We don't produce a diagnostic for this, but the callers that 15559 // call us on arbitrary full-expressions should generally not care. 15560 Info.discardCleanups() && !Status.HasSideEffects; 15561 15562 if (!Diags.empty()) { 15563 IsConstExpr = false; 15564 if (Loc) *Loc = Diags[0].first; 15565 } else if (!IsConstExpr) { 15566 // FIXME: This shouldn't happen. 15567 if (Loc) *Loc = getExprLoc(); 15568 } 15569 15570 return IsConstExpr; 15571 } 15572 15573 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15574 const FunctionDecl *Callee, 15575 ArrayRef<const Expr*> Args, 15576 const Expr *This) const { 15577 assert(!isValueDependent() && 15578 "Expression evaluator can't be called on a dependent expression."); 15579 15580 Expr::EvalStatus Status; 15581 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15582 Info.InConstantContext = true; 15583 15584 LValue ThisVal; 15585 const LValue *ThisPtr = nullptr; 15586 if (This) { 15587 #ifndef NDEBUG 15588 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15589 assert(MD && "Don't provide `this` for non-methods."); 15590 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15591 #endif 15592 if (!This->isValueDependent() && 15593 EvaluateObjectArgument(Info, This, ThisVal) && 15594 !Info.EvalStatus.HasSideEffects) 15595 ThisPtr = &ThisVal; 15596 15597 // Ignore any side-effects from a failed evaluation. This is safe because 15598 // they can't interfere with any other argument evaluation. 15599 Info.EvalStatus.HasSideEffects = false; 15600 } 15601 15602 CallRef Call = Info.CurrentCall->createCall(Callee); 15603 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15604 I != E; ++I) { 15605 unsigned Idx = I - Args.begin(); 15606 if (Idx >= Callee->getNumParams()) 15607 break; 15608 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15609 if ((*I)->isValueDependent() || 15610 !EvaluateCallArg(PVD, *I, Call, Info) || 15611 Info.EvalStatus.HasSideEffects) { 15612 // If evaluation fails, throw away the argument entirely. 15613 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15614 *Slot = APValue(); 15615 } 15616 15617 // Ignore any side-effects from a failed evaluation. This is safe because 15618 // they can't interfere with any other argument evaluation. 15619 Info.EvalStatus.HasSideEffects = false; 15620 } 15621 15622 // Parameter cleanups happen in the caller and are not part of this 15623 // evaluation. 15624 Info.discardCleanups(); 15625 Info.EvalStatus.HasSideEffects = false; 15626 15627 // Build fake call to Callee. 15628 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15629 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15630 FullExpressionRAII Scope(Info); 15631 return Evaluate(Value, Info, this) && Scope.destroy() && 15632 !Info.EvalStatus.HasSideEffects; 15633 } 15634 15635 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15636 SmallVectorImpl< 15637 PartialDiagnosticAt> &Diags) { 15638 // FIXME: It would be useful to check constexpr function templates, but at the 15639 // moment the constant expression evaluator cannot cope with the non-rigorous 15640 // ASTs which we build for dependent expressions. 15641 if (FD->isDependentContext()) 15642 return true; 15643 15644 Expr::EvalStatus Status; 15645 Status.Diag = &Diags; 15646 15647 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15648 Info.InConstantContext = true; 15649 Info.CheckingPotentialConstantExpression = true; 15650 15651 // The constexpr VM attempts to compile all methods to bytecode here. 15652 if (Info.EnableNewConstInterp) { 15653 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15654 return Diags.empty(); 15655 } 15656 15657 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15658 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15659 15660 // Fabricate an arbitrary expression on the stack and pretend that it 15661 // is a temporary being used as the 'this' pointer. 15662 LValue This; 15663 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15664 This.set({&VIE, Info.CurrentCall->Index}); 15665 15666 ArrayRef<const Expr*> Args; 15667 15668 APValue Scratch; 15669 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15670 // Evaluate the call as a constant initializer, to allow the construction 15671 // of objects of non-literal types. 15672 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15673 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15674 } else { 15675 SourceLocation Loc = FD->getLocation(); 15676 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15677 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15678 } 15679 15680 return Diags.empty(); 15681 } 15682 15683 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15684 const FunctionDecl *FD, 15685 SmallVectorImpl< 15686 PartialDiagnosticAt> &Diags) { 15687 assert(!E->isValueDependent() && 15688 "Expression evaluator can't be called on a dependent expression."); 15689 15690 Expr::EvalStatus Status; 15691 Status.Diag = &Diags; 15692 15693 EvalInfo Info(FD->getASTContext(), Status, 15694 EvalInfo::EM_ConstantExpressionUnevaluated); 15695 Info.InConstantContext = true; 15696 Info.CheckingPotentialConstantExpression = true; 15697 15698 // Fabricate a call stack frame to give the arguments a plausible cover story. 15699 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15700 15701 APValue ResultScratch; 15702 Evaluate(ResultScratch, Info, E); 15703 return Diags.empty(); 15704 } 15705 15706 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15707 unsigned Type) const { 15708 if (!getType()->isPointerType()) 15709 return false; 15710 15711 Expr::EvalStatus Status; 15712 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15713 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15714 } 15715