1 //===-- Constants.cpp - Implement Constant nodes --------------------------===// 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 Constant* classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/Constants.h" 14 #include "ConstantFold.h" 15 #include "LLVMContextImpl.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringMap.h" 19 #include "llvm/IR/BasicBlock.h" 20 #include "llvm/IR/DerivedTypes.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/GetElementPtrTypeIterator.h" 23 #include "llvm/IR/GlobalAlias.h" 24 #include "llvm/IR/GlobalIFunc.h" 25 #include "llvm/IR/GlobalValue.h" 26 #include "llvm/IR/GlobalVariable.h" 27 #include "llvm/IR/Instructions.h" 28 #include "llvm/IR/Operator.h" 29 #include "llvm/IR/PatternMatch.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/MathExtras.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <algorithm> 34 35 using namespace llvm; 36 using namespace PatternMatch; 37 38 //===----------------------------------------------------------------------===// 39 // Constant Class 40 //===----------------------------------------------------------------------===// 41 42 bool Constant::isNegativeZeroValue() const { 43 // Floating point values have an explicit -0.0 value. 44 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 45 return CFP->isZero() && CFP->isNegative(); 46 47 // Equivalent for a vector of -0.0's. 48 if (getType()->isVectorTy()) 49 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue())) 50 return SplatCFP->isNegativeZeroValue(); 51 52 // We've already handled true FP case; any other FP vectors can't represent -0.0. 53 if (getType()->isFPOrFPVectorTy()) 54 return false; 55 56 // Otherwise, just use +0.0. 57 return isNullValue(); 58 } 59 60 // Return true iff this constant is positive zero (floating point), negative 61 // zero (floating point), or a null value. 62 bool Constant::isZeroValue() const { 63 // Floating point values have an explicit -0.0 value. 64 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 65 return CFP->isZero(); 66 67 // Check for constant splat vectors of 1 values. 68 if (getType()->isVectorTy()) 69 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue())) 70 return SplatCFP->isZero(); 71 72 // Otherwise, just use +0.0. 73 return isNullValue(); 74 } 75 76 bool Constant::isNullValue() const { 77 // 0 is null. 78 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 79 return CI->isZero(); 80 81 // +0.0 is null. 82 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 83 // ppc_fp128 determine isZero using high order double only 84 // Should check the bitwise value to make sure all bits are zero. 85 return CFP->isExactlyValue(+0.0); 86 87 // constant zero is zero for aggregates, cpnull is null for pointers, none for 88 // tokens. 89 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) || 90 isa<ConstantTokenNone>(this); 91 } 92 93 bool Constant::isAllOnesValue() const { 94 // Check for -1 integers 95 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 96 return CI->isMinusOne(); 97 98 // Check for FP which are bitcasted from -1 integers 99 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 100 return CFP->getValueAPF().bitcastToAPInt().isAllOnes(); 101 102 // Check for constant splat vectors of 1 values. 103 if (getType()->isVectorTy()) 104 if (const auto *SplatVal = getSplatValue()) 105 return SplatVal->isAllOnesValue(); 106 107 return false; 108 } 109 110 bool Constant::isOneValue() const { 111 // Check for 1 integers 112 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 113 return CI->isOne(); 114 115 // Check for FP which are bitcasted from 1 integers 116 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 117 return CFP->getValueAPF().bitcastToAPInt().isOne(); 118 119 // Check for constant splat vectors of 1 values. 120 if (getType()->isVectorTy()) 121 if (const auto *SplatVal = getSplatValue()) 122 return SplatVal->isOneValue(); 123 124 return false; 125 } 126 127 bool Constant::isNotOneValue() const { 128 // Check for 1 integers 129 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 130 return !CI->isOneValue(); 131 132 // Check for FP which are bitcasted from 1 integers 133 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 134 return !CFP->getValueAPF().bitcastToAPInt().isOne(); 135 136 // Check that vectors don't contain 1 137 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) { 138 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 139 Constant *Elt = getAggregateElement(I); 140 if (!Elt || !Elt->isNotOneValue()) 141 return false; 142 } 143 return true; 144 } 145 146 // Check for splats that don't contain 1 147 if (getType()->isVectorTy()) 148 if (const auto *SplatVal = getSplatValue()) 149 return SplatVal->isNotOneValue(); 150 151 // It *may* contain 1, we can't tell. 152 return false; 153 } 154 155 bool Constant::isMinSignedValue() const { 156 // Check for INT_MIN integers 157 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 158 return CI->isMinValue(/*isSigned=*/true); 159 160 // Check for FP which are bitcasted from INT_MIN integers 161 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 162 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue(); 163 164 // Check for splats of INT_MIN values. 165 if (getType()->isVectorTy()) 166 if (const auto *SplatVal = getSplatValue()) 167 return SplatVal->isMinSignedValue(); 168 169 return false; 170 } 171 172 bool Constant::isNotMinSignedValue() const { 173 // Check for INT_MIN integers 174 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 175 return !CI->isMinValue(/*isSigned=*/true); 176 177 // Check for FP which are bitcasted from INT_MIN integers 178 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 179 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue(); 180 181 // Check that vectors don't contain INT_MIN 182 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) { 183 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 184 Constant *Elt = getAggregateElement(I); 185 if (!Elt || !Elt->isNotMinSignedValue()) 186 return false; 187 } 188 return true; 189 } 190 191 // Check for splats that aren't INT_MIN 192 if (getType()->isVectorTy()) 193 if (const auto *SplatVal = getSplatValue()) 194 return SplatVal->isNotMinSignedValue(); 195 196 // It *may* contain INT_MIN, we can't tell. 197 return false; 198 } 199 200 bool Constant::isFiniteNonZeroFP() const { 201 if (auto *CFP = dyn_cast<ConstantFP>(this)) 202 return CFP->getValueAPF().isFiniteNonZero(); 203 204 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) { 205 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 206 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I)); 207 if (!CFP || !CFP->getValueAPF().isFiniteNonZero()) 208 return false; 209 } 210 return true; 211 } 212 213 if (getType()->isVectorTy()) 214 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue())) 215 return SplatCFP->isFiniteNonZeroFP(); 216 217 // It *may* contain finite non-zero, we can't tell. 218 return false; 219 } 220 221 bool Constant::isNormalFP() const { 222 if (auto *CFP = dyn_cast<ConstantFP>(this)) 223 return CFP->getValueAPF().isNormal(); 224 225 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) { 226 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 227 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I)); 228 if (!CFP || !CFP->getValueAPF().isNormal()) 229 return false; 230 } 231 return true; 232 } 233 234 if (getType()->isVectorTy()) 235 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue())) 236 return SplatCFP->isNormalFP(); 237 238 // It *may* contain a normal fp value, we can't tell. 239 return false; 240 } 241 242 bool Constant::hasExactInverseFP() const { 243 if (auto *CFP = dyn_cast<ConstantFP>(this)) 244 return CFP->getValueAPF().getExactInverse(nullptr); 245 246 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) { 247 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 248 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I)); 249 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr)) 250 return false; 251 } 252 return true; 253 } 254 255 if (getType()->isVectorTy()) 256 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue())) 257 return SplatCFP->hasExactInverseFP(); 258 259 // It *may* have an exact inverse fp value, we can't tell. 260 return false; 261 } 262 263 bool Constant::isNaN() const { 264 if (auto *CFP = dyn_cast<ConstantFP>(this)) 265 return CFP->isNaN(); 266 267 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) { 268 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 269 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I)); 270 if (!CFP || !CFP->isNaN()) 271 return false; 272 } 273 return true; 274 } 275 276 if (getType()->isVectorTy()) 277 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue())) 278 return SplatCFP->isNaN(); 279 280 // It *may* be NaN, we can't tell. 281 return false; 282 } 283 284 bool Constant::isElementWiseEqual(Value *Y) const { 285 // Are they fully identical? 286 if (this == Y) 287 return true; 288 289 // The input value must be a vector constant with the same type. 290 auto *VTy = dyn_cast<VectorType>(getType()); 291 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType()) 292 return false; 293 294 // TODO: Compare pointer constants? 295 if (!(VTy->getElementType()->isIntegerTy() || 296 VTy->getElementType()->isFloatingPointTy())) 297 return false; 298 299 // They may still be identical element-wise (if they have `undef`s). 300 // Bitcast to integer to allow exact bitwise comparison for all types. 301 Type *IntTy = VectorType::getInteger(VTy); 302 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy); 303 Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy); 304 Constant *CmpEq = ConstantExpr::getICmp(ICmpInst::ICMP_EQ, C0, C1); 305 return isa<UndefValue>(CmpEq) || match(CmpEq, m_One()); 306 } 307 308 static bool 309 containsUndefinedElement(const Constant *C, 310 function_ref<bool(const Constant *)> HasFn) { 311 if (auto *VTy = dyn_cast<VectorType>(C->getType())) { 312 if (HasFn(C)) 313 return true; 314 if (isa<ConstantAggregateZero>(C)) 315 return false; 316 if (isa<ScalableVectorType>(C->getType())) 317 return false; 318 319 for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements(); 320 i != e; ++i) { 321 if (Constant *Elem = C->getAggregateElement(i)) 322 if (HasFn(Elem)) 323 return true; 324 } 325 } 326 327 return false; 328 } 329 330 bool Constant::containsUndefOrPoisonElement() const { 331 return containsUndefinedElement( 332 this, [&](const auto *C) { return isa<UndefValue>(C); }); 333 } 334 335 bool Constant::containsPoisonElement() const { 336 return containsUndefinedElement( 337 this, [&](const auto *C) { return isa<PoisonValue>(C); }); 338 } 339 340 bool Constant::containsConstantExpression() const { 341 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) { 342 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) 343 if (isa<ConstantExpr>(getAggregateElement(i))) 344 return true; 345 } 346 return false; 347 } 348 349 /// Constructor to create a '0' constant of arbitrary type. 350 Constant *Constant::getNullValue(Type *Ty) { 351 switch (Ty->getTypeID()) { 352 case Type::IntegerTyID: 353 return ConstantInt::get(Ty, 0); 354 case Type::HalfTyID: 355 case Type::BFloatTyID: 356 case Type::FloatTyID: 357 case Type::DoubleTyID: 358 case Type::X86_FP80TyID: 359 case Type::FP128TyID: 360 case Type::PPC_FP128TyID: 361 return ConstantFP::get(Ty->getContext(), 362 APFloat::getZero(Ty->getFltSemantics())); 363 case Type::PointerTyID: 364 return ConstantPointerNull::get(cast<PointerType>(Ty)); 365 case Type::StructTyID: 366 case Type::ArrayTyID: 367 case Type::FixedVectorTyID: 368 case Type::ScalableVectorTyID: 369 return ConstantAggregateZero::get(Ty); 370 case Type::TokenTyID: 371 return ConstantTokenNone::get(Ty->getContext()); 372 default: 373 // Function, Label, or Opaque type? 374 llvm_unreachable("Cannot create a null constant of that type!"); 375 } 376 } 377 378 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) { 379 Type *ScalarTy = Ty->getScalarType(); 380 381 // Create the base integer constant. 382 Constant *C = ConstantInt::get(Ty->getContext(), V); 383 384 // Convert an integer to a pointer, if necessary. 385 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy)) 386 C = ConstantExpr::getIntToPtr(C, PTy); 387 388 // Broadcast a scalar to a vector, if necessary. 389 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 390 C = ConstantVector::getSplat(VTy->getElementCount(), C); 391 392 return C; 393 } 394 395 Constant *Constant::getAllOnesValue(Type *Ty) { 396 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty)) 397 return ConstantInt::get(Ty->getContext(), 398 APInt::getAllOnes(ITy->getBitWidth())); 399 400 if (Ty->isFloatingPointTy()) { 401 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics()); 402 return ConstantFP::get(Ty->getContext(), FL); 403 } 404 405 VectorType *VTy = cast<VectorType>(Ty); 406 return ConstantVector::getSplat(VTy->getElementCount(), 407 getAllOnesValue(VTy->getElementType())); 408 } 409 410 Constant *Constant::getAggregateElement(unsigned Elt) const { 411 assert((getType()->isAggregateType() || getType()->isVectorTy()) && 412 "Must be an aggregate/vector constant"); 413 414 if (const auto *CC = dyn_cast<ConstantAggregate>(this)) 415 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr; 416 417 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this)) 418 return Elt < CAZ->getElementCount().getKnownMinValue() 419 ? CAZ->getElementValue(Elt) 420 : nullptr; 421 422 // FIXME: getNumElements() will fail for non-fixed vector types. 423 if (isa<ScalableVectorType>(getType())) 424 return nullptr; 425 426 if (const auto *PV = dyn_cast<PoisonValue>(this)) 427 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr; 428 429 if (const auto *UV = dyn_cast<UndefValue>(this)) 430 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr; 431 432 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this)) 433 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) 434 : nullptr; 435 436 return nullptr; 437 } 438 439 Constant *Constant::getAggregateElement(Constant *Elt) const { 440 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer"); 441 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) { 442 // Check if the constant fits into an uint64_t. 443 if (CI->getValue().getActiveBits() > 64) 444 return nullptr; 445 return getAggregateElement(CI->getZExtValue()); 446 } 447 return nullptr; 448 } 449 450 void Constant::destroyConstant() { 451 /// First call destroyConstantImpl on the subclass. This gives the subclass 452 /// a chance to remove the constant from any maps/pools it's contained in. 453 switch (getValueID()) { 454 default: 455 llvm_unreachable("Not a constant!"); 456 #define HANDLE_CONSTANT(Name) \ 457 case Value::Name##Val: \ 458 cast<Name>(this)->destroyConstantImpl(); \ 459 break; 460 #include "llvm/IR/Value.def" 461 } 462 463 // When a Constant is destroyed, there may be lingering 464 // references to the constant by other constants in the constant pool. These 465 // constants are implicitly dependent on the module that is being deleted, 466 // but they don't know that. Because we only find out when the CPV is 467 // deleted, we must now notify all of our users (that should only be 468 // Constants) that they are, in fact, invalid now and should be deleted. 469 // 470 while (!use_empty()) { 471 Value *V = user_back(); 472 #ifndef NDEBUG // Only in -g mode... 473 if (!isa<Constant>(V)) { 474 dbgs() << "While deleting: " << *this 475 << "\n\nUse still stuck around after Def is destroyed: " << *V 476 << "\n\n"; 477 } 478 #endif 479 assert(isa<Constant>(V) && "References remain to Constant being destroyed"); 480 cast<Constant>(V)->destroyConstant(); 481 482 // The constant should remove itself from our use list... 483 assert((use_empty() || user_back() != V) && "Constant not removed!"); 484 } 485 486 // Value has no outstanding references it is safe to delete it now... 487 deleteConstant(this); 488 } 489 490 void llvm::deleteConstant(Constant *C) { 491 switch (C->getValueID()) { 492 case Constant::ConstantIntVal: 493 delete static_cast<ConstantInt *>(C); 494 break; 495 case Constant::ConstantFPVal: 496 delete static_cast<ConstantFP *>(C); 497 break; 498 case Constant::ConstantAggregateZeroVal: 499 delete static_cast<ConstantAggregateZero *>(C); 500 break; 501 case Constant::ConstantArrayVal: 502 delete static_cast<ConstantArray *>(C); 503 break; 504 case Constant::ConstantStructVal: 505 delete static_cast<ConstantStruct *>(C); 506 break; 507 case Constant::ConstantVectorVal: 508 delete static_cast<ConstantVector *>(C); 509 break; 510 case Constant::ConstantPointerNullVal: 511 delete static_cast<ConstantPointerNull *>(C); 512 break; 513 case Constant::ConstantDataArrayVal: 514 delete static_cast<ConstantDataArray *>(C); 515 break; 516 case Constant::ConstantDataVectorVal: 517 delete static_cast<ConstantDataVector *>(C); 518 break; 519 case Constant::ConstantTokenNoneVal: 520 delete static_cast<ConstantTokenNone *>(C); 521 break; 522 case Constant::BlockAddressVal: 523 delete static_cast<BlockAddress *>(C); 524 break; 525 case Constant::DSOLocalEquivalentVal: 526 delete static_cast<DSOLocalEquivalent *>(C); 527 break; 528 case Constant::NoCFIValueVal: 529 delete static_cast<NoCFIValue *>(C); 530 break; 531 case Constant::UndefValueVal: 532 delete static_cast<UndefValue *>(C); 533 break; 534 case Constant::PoisonValueVal: 535 delete static_cast<PoisonValue *>(C); 536 break; 537 case Constant::ConstantExprVal: 538 if (isa<UnaryConstantExpr>(C)) 539 delete static_cast<UnaryConstantExpr *>(C); 540 else if (isa<BinaryConstantExpr>(C)) 541 delete static_cast<BinaryConstantExpr *>(C); 542 else if (isa<SelectConstantExpr>(C)) 543 delete static_cast<SelectConstantExpr *>(C); 544 else if (isa<ExtractElementConstantExpr>(C)) 545 delete static_cast<ExtractElementConstantExpr *>(C); 546 else if (isa<InsertElementConstantExpr>(C)) 547 delete static_cast<InsertElementConstantExpr *>(C); 548 else if (isa<ShuffleVectorConstantExpr>(C)) 549 delete static_cast<ShuffleVectorConstantExpr *>(C); 550 else if (isa<ExtractValueConstantExpr>(C)) 551 delete static_cast<ExtractValueConstantExpr *>(C); 552 else if (isa<InsertValueConstantExpr>(C)) 553 delete static_cast<InsertValueConstantExpr *>(C); 554 else if (isa<GetElementPtrConstantExpr>(C)) 555 delete static_cast<GetElementPtrConstantExpr *>(C); 556 else if (isa<CompareConstantExpr>(C)) 557 delete static_cast<CompareConstantExpr *>(C); 558 else 559 llvm_unreachable("Unexpected constant expr"); 560 break; 561 default: 562 llvm_unreachable("Unexpected constant"); 563 } 564 } 565 566 static bool canTrapImpl(const Constant *C, 567 SmallPtrSetImpl<const Constant *> &NonTrappingOps) { 568 assert(C->getType()->isFirstClassType() && 569 "Cannot evaluate non-first-class types!"); 570 // ConstantExpr or ConstantAggregate trap if any operands can trap. 571 if (isa<ConstantExpr>(C) || isa<ConstantAggregate>(C)) { 572 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) { 573 const Constant *Op = cast<Constant>(C->getOperand(i)); 574 if (isa<ConstantExpr>(Op) || isa<ConstantAggregate>(Op)) { 575 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps)) 576 return true; 577 } 578 } 579 } 580 581 // The only leafs that can trap are constant expressions. 582 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C); 583 if (!CE) 584 return false; 585 586 // Otherwise, only specific operations can trap. 587 switch (CE->getOpcode()) { 588 default: 589 return false; 590 case Instruction::UDiv: 591 case Instruction::SDiv: 592 case Instruction::URem: 593 case Instruction::SRem: 594 // Div and rem can trap if the RHS is not known to be non-zero. 595 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue()) 596 return true; 597 return false; 598 } 599 } 600 601 bool Constant::canTrap() const { 602 SmallPtrSet<const Constant *, 4> NonTrappingOps; 603 return canTrapImpl(this, NonTrappingOps); 604 } 605 606 /// Check if C contains a GlobalValue for which Predicate is true. 607 static bool 608 ConstHasGlobalValuePredicate(const Constant *C, 609 bool (*Predicate)(const GlobalValue *)) { 610 SmallPtrSet<const Constant *, 8> Visited; 611 SmallVector<const Constant *, 8> WorkList; 612 WorkList.push_back(C); 613 Visited.insert(C); 614 615 while (!WorkList.empty()) { 616 const Constant *WorkItem = WorkList.pop_back_val(); 617 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem)) 618 if (Predicate(GV)) 619 return true; 620 for (const Value *Op : WorkItem->operands()) { 621 const Constant *ConstOp = dyn_cast<Constant>(Op); 622 if (!ConstOp) 623 continue; 624 if (Visited.insert(ConstOp).second) 625 WorkList.push_back(ConstOp); 626 } 627 } 628 return false; 629 } 630 631 bool Constant::isThreadDependent() const { 632 auto DLLImportPredicate = [](const GlobalValue *GV) { 633 return GV->isThreadLocal(); 634 }; 635 return ConstHasGlobalValuePredicate(this, DLLImportPredicate); 636 } 637 638 bool Constant::isDLLImportDependent() const { 639 auto DLLImportPredicate = [](const GlobalValue *GV) { 640 return GV->hasDLLImportStorageClass(); 641 }; 642 return ConstHasGlobalValuePredicate(this, DLLImportPredicate); 643 } 644 645 bool Constant::isConstantUsed() const { 646 for (const User *U : users()) { 647 const Constant *UC = dyn_cast<Constant>(U); 648 if (!UC || isa<GlobalValue>(UC)) 649 return true; 650 651 if (UC->isConstantUsed()) 652 return true; 653 } 654 return false; 655 } 656 657 bool Constant::needsDynamicRelocation() const { 658 return getRelocationInfo() == GlobalRelocation; 659 } 660 661 bool Constant::needsRelocation() const { 662 return getRelocationInfo() != NoRelocation; 663 } 664 665 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const { 666 if (isa<GlobalValue>(this)) 667 return GlobalRelocation; // Global reference. 668 669 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this)) 670 return BA->getFunction()->getRelocationInfo(); 671 672 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) { 673 if (CE->getOpcode() == Instruction::Sub) { 674 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0)); 675 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1)); 676 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt && 677 RHS->getOpcode() == Instruction::PtrToInt) { 678 Constant *LHSOp0 = LHS->getOperand(0); 679 Constant *RHSOp0 = RHS->getOperand(0); 680 681 // While raw uses of blockaddress need to be relocated, differences 682 // between two of them don't when they are for labels in the same 683 // function. This is a common idiom when creating a table for the 684 // indirect goto extension, so we handle it efficiently here. 685 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) && 686 cast<BlockAddress>(LHSOp0)->getFunction() == 687 cast<BlockAddress>(RHSOp0)->getFunction()) 688 return NoRelocation; 689 690 // Relative pointers do not need to be dynamically relocated. 691 if (auto *RHSGV = 692 dyn_cast<GlobalValue>(RHSOp0->stripInBoundsConstantOffsets())) { 693 auto *LHS = LHSOp0->stripInBoundsConstantOffsets(); 694 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) { 695 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal()) 696 return LocalRelocation; 697 } else if (isa<DSOLocalEquivalent>(LHS)) { 698 if (RHSGV->isDSOLocal()) 699 return LocalRelocation; 700 } 701 } 702 } 703 } 704 } 705 706 PossibleRelocationsTy Result = NoRelocation; 707 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 708 Result = 709 std::max(cast<Constant>(getOperand(i))->getRelocationInfo(), Result); 710 711 return Result; 712 } 713 714 /// Return true if the specified constantexpr is dead. This involves 715 /// recursively traversing users of the constantexpr. 716 /// If RemoveDeadUsers is true, also remove dead users at the same time. 717 static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) { 718 if (isa<GlobalValue>(C)) return false; // Cannot remove this 719 720 Value::const_user_iterator I = C->user_begin(), E = C->user_end(); 721 while (I != E) { 722 const Constant *User = dyn_cast<Constant>(*I); 723 if (!User) return false; // Non-constant usage; 724 if (!constantIsDead(User, RemoveDeadUsers)) 725 return false; // Constant wasn't dead 726 727 // Just removed User, so the iterator was invalidated. 728 // Since we return immediately upon finding a live user, we can always 729 // restart from user_begin(). 730 if (RemoveDeadUsers) 731 I = C->user_begin(); 732 else 733 ++I; 734 } 735 736 if (RemoveDeadUsers) { 737 // If C is only used by metadata, it should not be preserved but should 738 // have its uses replaced. 739 ReplaceableMetadataImpl::SalvageDebugInfo(*C); 740 const_cast<Constant *>(C)->destroyConstant(); 741 } 742 743 return true; 744 } 745 746 void Constant::removeDeadConstantUsers() const { 747 Value::const_user_iterator I = user_begin(), E = user_end(); 748 Value::const_user_iterator LastNonDeadUser = E; 749 while (I != E) { 750 const Constant *User = dyn_cast<Constant>(*I); 751 if (!User) { 752 LastNonDeadUser = I; 753 ++I; 754 continue; 755 } 756 757 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) { 758 // If the constant wasn't dead, remember that this was the last live use 759 // and move on to the next constant. 760 LastNonDeadUser = I; 761 ++I; 762 continue; 763 } 764 765 // If the constant was dead, then the iterator is invalidated. 766 if (LastNonDeadUser == E) 767 I = user_begin(); 768 else 769 I = std::next(LastNonDeadUser); 770 } 771 } 772 773 bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); } 774 775 bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); } 776 777 bool Constant::hasNLiveUses(unsigned N) const { 778 unsigned NumUses = 0; 779 for (const Use &U : uses()) { 780 const Constant *User = dyn_cast<Constant>(U.getUser()); 781 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) { 782 ++NumUses; 783 784 if (NumUses > N) 785 return false; 786 } 787 } 788 return NumUses == N; 789 } 790 791 Constant *Constant::replaceUndefsWith(Constant *C, Constant *Replacement) { 792 assert(C && Replacement && "Expected non-nullptr constant arguments"); 793 Type *Ty = C->getType(); 794 if (match(C, m_Undef())) { 795 assert(Ty == Replacement->getType() && "Expected matching types"); 796 return Replacement; 797 } 798 799 // Don't know how to deal with this constant. 800 auto *VTy = dyn_cast<FixedVectorType>(Ty); 801 if (!VTy) 802 return C; 803 804 unsigned NumElts = VTy->getNumElements(); 805 SmallVector<Constant *, 32> NewC(NumElts); 806 for (unsigned i = 0; i != NumElts; ++i) { 807 Constant *EltC = C->getAggregateElement(i); 808 assert((!EltC || EltC->getType() == Replacement->getType()) && 809 "Expected matching types"); 810 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC; 811 } 812 return ConstantVector::get(NewC); 813 } 814 815 Constant *Constant::mergeUndefsWith(Constant *C, Constant *Other) { 816 assert(C && Other && "Expected non-nullptr constant arguments"); 817 if (match(C, m_Undef())) 818 return C; 819 820 Type *Ty = C->getType(); 821 if (match(Other, m_Undef())) 822 return UndefValue::get(Ty); 823 824 auto *VTy = dyn_cast<FixedVectorType>(Ty); 825 if (!VTy) 826 return C; 827 828 Type *EltTy = VTy->getElementType(); 829 unsigned NumElts = VTy->getNumElements(); 830 assert(isa<FixedVectorType>(Other->getType()) && 831 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts && 832 "Type mismatch"); 833 834 bool FoundExtraUndef = false; 835 SmallVector<Constant *, 32> NewC(NumElts); 836 for (unsigned I = 0; I != NumElts; ++I) { 837 NewC[I] = C->getAggregateElement(I); 838 Constant *OtherEltC = Other->getAggregateElement(I); 839 assert(NewC[I] && OtherEltC && "Unknown vector element"); 840 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) { 841 NewC[I] = UndefValue::get(EltTy); 842 FoundExtraUndef = true; 843 } 844 } 845 if (FoundExtraUndef) 846 return ConstantVector::get(NewC); 847 return C; 848 } 849 850 bool Constant::isManifestConstant() const { 851 if (isa<ConstantData>(this)) 852 return true; 853 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) { 854 for (const Value *Op : operand_values()) 855 if (!cast<Constant>(Op)->isManifestConstant()) 856 return false; 857 return true; 858 } 859 return false; 860 } 861 862 //===----------------------------------------------------------------------===// 863 // ConstantInt 864 //===----------------------------------------------------------------------===// 865 866 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V) 867 : ConstantData(Ty, ConstantIntVal), Val(V) { 868 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type"); 869 } 870 871 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) { 872 LLVMContextImpl *pImpl = Context.pImpl; 873 if (!pImpl->TheTrueVal) 874 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1); 875 return pImpl->TheTrueVal; 876 } 877 878 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) { 879 LLVMContextImpl *pImpl = Context.pImpl; 880 if (!pImpl->TheFalseVal) 881 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0); 882 return pImpl->TheFalseVal; 883 } 884 885 ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) { 886 return V ? getTrue(Context) : getFalse(Context); 887 } 888 889 Constant *ConstantInt::getTrue(Type *Ty) { 890 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1."); 891 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext()); 892 if (auto *VTy = dyn_cast<VectorType>(Ty)) 893 return ConstantVector::getSplat(VTy->getElementCount(), TrueC); 894 return TrueC; 895 } 896 897 Constant *ConstantInt::getFalse(Type *Ty) { 898 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1."); 899 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext()); 900 if (auto *VTy = dyn_cast<VectorType>(Ty)) 901 return ConstantVector::getSplat(VTy->getElementCount(), FalseC); 902 return FalseC; 903 } 904 905 Constant *ConstantInt::getBool(Type *Ty, bool V) { 906 return V ? getTrue(Ty) : getFalse(Ty); 907 } 908 909 // Get a ConstantInt from an APInt. 910 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) { 911 // get an existing value or the insertion position 912 LLVMContextImpl *pImpl = Context.pImpl; 913 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V]; 914 if (!Slot) { 915 // Get the corresponding integer type for the bit width of the value. 916 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth()); 917 Slot.reset(new ConstantInt(ITy, V)); 918 } 919 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth())); 920 return Slot.get(); 921 } 922 923 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) { 924 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned); 925 926 // For vectors, broadcast the value. 927 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 928 return ConstantVector::getSplat(VTy->getElementCount(), C); 929 930 return C; 931 } 932 933 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) { 934 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned)); 935 } 936 937 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) { 938 return get(Ty, V, true); 939 } 940 941 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) { 942 return get(Ty, V, true); 943 } 944 945 Constant *ConstantInt::get(Type *Ty, const APInt& V) { 946 ConstantInt *C = get(Ty->getContext(), V); 947 assert(C->getType() == Ty->getScalarType() && 948 "ConstantInt type doesn't match the type implied by its value!"); 949 950 // For vectors, broadcast the value. 951 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 952 return ConstantVector::getSplat(VTy->getElementCount(), C); 953 954 return C; 955 } 956 957 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) { 958 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix)); 959 } 960 961 /// Remove the constant from the constant table. 962 void ConstantInt::destroyConstantImpl() { 963 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!"); 964 } 965 966 //===----------------------------------------------------------------------===// 967 // ConstantFP 968 //===----------------------------------------------------------------------===// 969 970 Constant *ConstantFP::get(Type *Ty, double V) { 971 LLVMContext &Context = Ty->getContext(); 972 973 APFloat FV(V); 974 bool ignored; 975 FV.convert(Ty->getScalarType()->getFltSemantics(), 976 APFloat::rmNearestTiesToEven, &ignored); 977 Constant *C = get(Context, FV); 978 979 // For vectors, broadcast the value. 980 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 981 return ConstantVector::getSplat(VTy->getElementCount(), C); 982 983 return C; 984 } 985 986 Constant *ConstantFP::get(Type *Ty, const APFloat &V) { 987 ConstantFP *C = get(Ty->getContext(), V); 988 assert(C->getType() == Ty->getScalarType() && 989 "ConstantFP type doesn't match the type implied by its value!"); 990 991 // For vectors, broadcast the value. 992 if (auto *VTy = dyn_cast<VectorType>(Ty)) 993 return ConstantVector::getSplat(VTy->getElementCount(), C); 994 995 return C; 996 } 997 998 Constant *ConstantFP::get(Type *Ty, StringRef Str) { 999 LLVMContext &Context = Ty->getContext(); 1000 1001 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str); 1002 Constant *C = get(Context, FV); 1003 1004 // For vectors, broadcast the value. 1005 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1006 return ConstantVector::getSplat(VTy->getElementCount(), C); 1007 1008 return C; 1009 } 1010 1011 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) { 1012 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics(); 1013 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload); 1014 Constant *C = get(Ty->getContext(), NaN); 1015 1016 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1017 return ConstantVector::getSplat(VTy->getElementCount(), C); 1018 1019 return C; 1020 } 1021 1022 Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) { 1023 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics(); 1024 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload); 1025 Constant *C = get(Ty->getContext(), NaN); 1026 1027 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1028 return ConstantVector::getSplat(VTy->getElementCount(), C); 1029 1030 return C; 1031 } 1032 1033 Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) { 1034 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics(); 1035 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload); 1036 Constant *C = get(Ty->getContext(), NaN); 1037 1038 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1039 return ConstantVector::getSplat(VTy->getElementCount(), C); 1040 1041 return C; 1042 } 1043 1044 Constant *ConstantFP::getZero(Type *Ty, bool Negative) { 1045 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics(); 1046 APFloat NegZero = APFloat::getZero(Semantics, Negative); 1047 Constant *C = get(Ty->getContext(), NegZero); 1048 1049 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1050 return ConstantVector::getSplat(VTy->getElementCount(), C); 1051 1052 return C; 1053 } 1054 1055 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) { 1056 if (Ty->isFPOrFPVectorTy()) 1057 return getNegativeZero(Ty); 1058 1059 return Constant::getNullValue(Ty); 1060 } 1061 1062 1063 // ConstantFP accessors. 1064 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) { 1065 LLVMContextImpl* pImpl = Context.pImpl; 1066 1067 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V]; 1068 1069 if (!Slot) { 1070 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics()); 1071 Slot.reset(new ConstantFP(Ty, V)); 1072 } 1073 1074 return Slot.get(); 1075 } 1076 1077 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) { 1078 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics(); 1079 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative)); 1080 1081 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1082 return ConstantVector::getSplat(VTy->getElementCount(), C); 1083 1084 return C; 1085 } 1086 1087 ConstantFP::ConstantFP(Type *Ty, const APFloat &V) 1088 : ConstantData(Ty, ConstantFPVal), Val(V) { 1089 assert(&V.getSemantics() == &Ty->getFltSemantics() && 1090 "FP type Mismatch"); 1091 } 1092 1093 bool ConstantFP::isExactlyValue(const APFloat &V) const { 1094 return Val.bitwiseIsEqual(V); 1095 } 1096 1097 /// Remove the constant from the constant table. 1098 void ConstantFP::destroyConstantImpl() { 1099 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!"); 1100 } 1101 1102 //===----------------------------------------------------------------------===// 1103 // ConstantAggregateZero Implementation 1104 //===----------------------------------------------------------------------===// 1105 1106 Constant *ConstantAggregateZero::getSequentialElement() const { 1107 if (auto *AT = dyn_cast<ArrayType>(getType())) 1108 return Constant::getNullValue(AT->getElementType()); 1109 return Constant::getNullValue(cast<VectorType>(getType())->getElementType()); 1110 } 1111 1112 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const { 1113 return Constant::getNullValue(getType()->getStructElementType(Elt)); 1114 } 1115 1116 Constant *ConstantAggregateZero::getElementValue(Constant *C) const { 1117 if (isa<ArrayType>(getType()) || isa<VectorType>(getType())) 1118 return getSequentialElement(); 1119 return getStructElement(cast<ConstantInt>(C)->getZExtValue()); 1120 } 1121 1122 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const { 1123 if (isa<ArrayType>(getType()) || isa<VectorType>(getType())) 1124 return getSequentialElement(); 1125 return getStructElement(Idx); 1126 } 1127 1128 ElementCount ConstantAggregateZero::getElementCount() const { 1129 Type *Ty = getType(); 1130 if (auto *AT = dyn_cast<ArrayType>(Ty)) 1131 return ElementCount::getFixed(AT->getNumElements()); 1132 if (auto *VT = dyn_cast<VectorType>(Ty)) 1133 return VT->getElementCount(); 1134 return ElementCount::getFixed(Ty->getStructNumElements()); 1135 } 1136 1137 //===----------------------------------------------------------------------===// 1138 // UndefValue Implementation 1139 //===----------------------------------------------------------------------===// 1140 1141 UndefValue *UndefValue::getSequentialElement() const { 1142 if (ArrayType *ATy = dyn_cast<ArrayType>(getType())) 1143 return UndefValue::get(ATy->getElementType()); 1144 return UndefValue::get(cast<VectorType>(getType())->getElementType()); 1145 } 1146 1147 UndefValue *UndefValue::getStructElement(unsigned Elt) const { 1148 return UndefValue::get(getType()->getStructElementType(Elt)); 1149 } 1150 1151 UndefValue *UndefValue::getElementValue(Constant *C) const { 1152 if (isa<ArrayType>(getType()) || isa<VectorType>(getType())) 1153 return getSequentialElement(); 1154 return getStructElement(cast<ConstantInt>(C)->getZExtValue()); 1155 } 1156 1157 UndefValue *UndefValue::getElementValue(unsigned Idx) const { 1158 if (isa<ArrayType>(getType()) || isa<VectorType>(getType())) 1159 return getSequentialElement(); 1160 return getStructElement(Idx); 1161 } 1162 1163 unsigned UndefValue::getNumElements() const { 1164 Type *Ty = getType(); 1165 if (auto *AT = dyn_cast<ArrayType>(Ty)) 1166 return AT->getNumElements(); 1167 if (auto *VT = dyn_cast<VectorType>(Ty)) 1168 return cast<FixedVectorType>(VT)->getNumElements(); 1169 return Ty->getStructNumElements(); 1170 } 1171 1172 //===----------------------------------------------------------------------===// 1173 // PoisonValue Implementation 1174 //===----------------------------------------------------------------------===// 1175 1176 PoisonValue *PoisonValue::getSequentialElement() const { 1177 if (ArrayType *ATy = dyn_cast<ArrayType>(getType())) 1178 return PoisonValue::get(ATy->getElementType()); 1179 return PoisonValue::get(cast<VectorType>(getType())->getElementType()); 1180 } 1181 1182 PoisonValue *PoisonValue::getStructElement(unsigned Elt) const { 1183 return PoisonValue::get(getType()->getStructElementType(Elt)); 1184 } 1185 1186 PoisonValue *PoisonValue::getElementValue(Constant *C) const { 1187 if (isa<ArrayType>(getType()) || isa<VectorType>(getType())) 1188 return getSequentialElement(); 1189 return getStructElement(cast<ConstantInt>(C)->getZExtValue()); 1190 } 1191 1192 PoisonValue *PoisonValue::getElementValue(unsigned Idx) const { 1193 if (isa<ArrayType>(getType()) || isa<VectorType>(getType())) 1194 return getSequentialElement(); 1195 return getStructElement(Idx); 1196 } 1197 1198 //===----------------------------------------------------------------------===// 1199 // ConstantXXX Classes 1200 //===----------------------------------------------------------------------===// 1201 1202 template <typename ItTy, typename EltTy> 1203 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) { 1204 for (; Start != End; ++Start) 1205 if (*Start != Elt) 1206 return false; 1207 return true; 1208 } 1209 1210 template <typename SequentialTy, typename ElementTy> 1211 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) { 1212 assert(!V.empty() && "Cannot get empty int sequence."); 1213 1214 SmallVector<ElementTy, 16> Elts; 1215 for (Constant *C : V) 1216 if (auto *CI = dyn_cast<ConstantInt>(C)) 1217 Elts.push_back(CI->getZExtValue()); 1218 else 1219 return nullptr; 1220 return SequentialTy::get(V[0]->getContext(), Elts); 1221 } 1222 1223 template <typename SequentialTy, typename ElementTy> 1224 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) { 1225 assert(!V.empty() && "Cannot get empty FP sequence."); 1226 1227 SmallVector<ElementTy, 16> Elts; 1228 for (Constant *C : V) 1229 if (auto *CFP = dyn_cast<ConstantFP>(C)) 1230 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue()); 1231 else 1232 return nullptr; 1233 return SequentialTy::getFP(V[0]->getType(), Elts); 1234 } 1235 1236 template <typename SequenceTy> 1237 static Constant *getSequenceIfElementsMatch(Constant *C, 1238 ArrayRef<Constant *> V) { 1239 // We speculatively build the elements here even if it turns out that there is 1240 // a constantexpr or something else weird, since it is so uncommon for that to 1241 // happen. 1242 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) { 1243 if (CI->getType()->isIntegerTy(8)) 1244 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V); 1245 else if (CI->getType()->isIntegerTy(16)) 1246 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V); 1247 else if (CI->getType()->isIntegerTy(32)) 1248 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V); 1249 else if (CI->getType()->isIntegerTy(64)) 1250 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V); 1251 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 1252 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy()) 1253 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V); 1254 else if (CFP->getType()->isFloatTy()) 1255 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V); 1256 else if (CFP->getType()->isDoubleTy()) 1257 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V); 1258 } 1259 1260 return nullptr; 1261 } 1262 1263 ConstantAggregate::ConstantAggregate(Type *T, ValueTy VT, 1264 ArrayRef<Constant *> V) 1265 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(), 1266 V.size()) { 1267 llvm::copy(V, op_begin()); 1268 1269 // Check that types match, unless this is an opaque struct. 1270 if (auto *ST = dyn_cast<StructType>(T)) { 1271 if (ST->isOpaque()) 1272 return; 1273 for (unsigned I = 0, E = V.size(); I != E; ++I) 1274 assert(V[I]->getType() == ST->getTypeAtIndex(I) && 1275 "Initializer for struct element doesn't match!"); 1276 } 1277 } 1278 1279 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V) 1280 : ConstantAggregate(T, ConstantArrayVal, V) { 1281 assert(V.size() == T->getNumElements() && 1282 "Invalid initializer for constant array"); 1283 } 1284 1285 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) { 1286 if (Constant *C = getImpl(Ty, V)) 1287 return C; 1288 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V); 1289 } 1290 1291 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) { 1292 // Empty arrays are canonicalized to ConstantAggregateZero. 1293 if (V.empty()) 1294 return ConstantAggregateZero::get(Ty); 1295 1296 for (Constant *C : V) { 1297 assert(C->getType() == Ty->getElementType() && 1298 "Wrong type in array element initializer"); 1299 (void)C; 1300 } 1301 1302 // If this is an all-zero array, return a ConstantAggregateZero object. If 1303 // all undef, return an UndefValue, if "all simple", then return a 1304 // ConstantDataArray. 1305 Constant *C = V[0]; 1306 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C)) 1307 return PoisonValue::get(Ty); 1308 1309 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C)) 1310 return UndefValue::get(Ty); 1311 1312 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C)) 1313 return ConstantAggregateZero::get(Ty); 1314 1315 // Check to see if all of the elements are ConstantFP or ConstantInt and if 1316 // the element type is compatible with ConstantDataVector. If so, use it. 1317 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) 1318 return getSequenceIfElementsMatch<ConstantDataArray>(C, V); 1319 1320 // Otherwise, we really do want to create a ConstantArray. 1321 return nullptr; 1322 } 1323 1324 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context, 1325 ArrayRef<Constant*> V, 1326 bool Packed) { 1327 unsigned VecSize = V.size(); 1328 SmallVector<Type*, 16> EltTypes(VecSize); 1329 for (unsigned i = 0; i != VecSize; ++i) 1330 EltTypes[i] = V[i]->getType(); 1331 1332 return StructType::get(Context, EltTypes, Packed); 1333 } 1334 1335 1336 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V, 1337 bool Packed) { 1338 assert(!V.empty() && 1339 "ConstantStruct::getTypeForElements cannot be called on empty list"); 1340 return getTypeForElements(V[0]->getContext(), V, Packed); 1341 } 1342 1343 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V) 1344 : ConstantAggregate(T, ConstantStructVal, V) { 1345 assert((T->isOpaque() || V.size() == T->getNumElements()) && 1346 "Invalid initializer for constant struct"); 1347 } 1348 1349 // ConstantStruct accessors. 1350 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) { 1351 assert((ST->isOpaque() || ST->getNumElements() == V.size()) && 1352 "Incorrect # elements specified to ConstantStruct::get"); 1353 1354 // Create a ConstantAggregateZero value if all elements are zeros. 1355 bool isZero = true; 1356 bool isUndef = false; 1357 bool isPoison = false; 1358 1359 if (!V.empty()) { 1360 isUndef = isa<UndefValue>(V[0]); 1361 isPoison = isa<PoisonValue>(V[0]); 1362 isZero = V[0]->isNullValue(); 1363 // PoisonValue inherits UndefValue, so its check is not necessary. 1364 if (isUndef || isZero) { 1365 for (Constant *C : V) { 1366 if (!C->isNullValue()) 1367 isZero = false; 1368 if (!isa<PoisonValue>(C)) 1369 isPoison = false; 1370 if (isa<PoisonValue>(C) || !isa<UndefValue>(C)) 1371 isUndef = false; 1372 } 1373 } 1374 } 1375 if (isZero) 1376 return ConstantAggregateZero::get(ST); 1377 if (isPoison) 1378 return PoisonValue::get(ST); 1379 if (isUndef) 1380 return UndefValue::get(ST); 1381 1382 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V); 1383 } 1384 1385 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V) 1386 : ConstantAggregate(T, ConstantVectorVal, V) { 1387 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() && 1388 "Invalid initializer for constant vector"); 1389 } 1390 1391 // ConstantVector accessors. 1392 Constant *ConstantVector::get(ArrayRef<Constant*> V) { 1393 if (Constant *C = getImpl(V)) 1394 return C; 1395 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size()); 1396 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V); 1397 } 1398 1399 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) { 1400 assert(!V.empty() && "Vectors can't be empty"); 1401 auto *T = FixedVectorType::get(V.front()->getType(), V.size()); 1402 1403 // If this is an all-undef or all-zero vector, return a 1404 // ConstantAggregateZero or UndefValue. 1405 Constant *C = V[0]; 1406 bool isZero = C->isNullValue(); 1407 bool isUndef = isa<UndefValue>(C); 1408 bool isPoison = isa<PoisonValue>(C); 1409 1410 if (isZero || isUndef) { 1411 for (unsigned i = 1, e = V.size(); i != e; ++i) 1412 if (V[i] != C) { 1413 isZero = isUndef = isPoison = false; 1414 break; 1415 } 1416 } 1417 1418 if (isZero) 1419 return ConstantAggregateZero::get(T); 1420 if (isPoison) 1421 return PoisonValue::get(T); 1422 if (isUndef) 1423 return UndefValue::get(T); 1424 1425 // Check to see if all of the elements are ConstantFP or ConstantInt and if 1426 // the element type is compatible with ConstantDataVector. If so, use it. 1427 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) 1428 return getSequenceIfElementsMatch<ConstantDataVector>(C, V); 1429 1430 // Otherwise, the element type isn't compatible with ConstantDataVector, or 1431 // the operand list contains a ConstantExpr or something else strange. 1432 return nullptr; 1433 } 1434 1435 Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) { 1436 if (!EC.isScalable()) { 1437 // If this splat is compatible with ConstantDataVector, use it instead of 1438 // ConstantVector. 1439 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) && 1440 ConstantDataSequential::isElementTypeCompatible(V->getType())) 1441 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V); 1442 1443 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V); 1444 return get(Elts); 1445 } 1446 1447 Type *VTy = VectorType::get(V->getType(), EC); 1448 1449 if (V->isNullValue()) 1450 return ConstantAggregateZero::get(VTy); 1451 else if (isa<UndefValue>(V)) 1452 return UndefValue::get(VTy); 1453 1454 Type *I32Ty = Type::getInt32Ty(VTy->getContext()); 1455 1456 // Move scalar into vector. 1457 Constant *PoisonV = PoisonValue::get(VTy); 1458 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(I32Ty, 0)); 1459 // Build shuffle mask to perform the splat. 1460 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0); 1461 // Splat. 1462 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros); 1463 } 1464 1465 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) { 1466 LLVMContextImpl *pImpl = Context.pImpl; 1467 if (!pImpl->TheNoneToken) 1468 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context)); 1469 return pImpl->TheNoneToken.get(); 1470 } 1471 1472 /// Remove the constant from the constant table. 1473 void ConstantTokenNone::destroyConstantImpl() { 1474 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!"); 1475 } 1476 1477 // Utility function for determining if a ConstantExpr is a CastOp or not. This 1478 // can't be inline because we don't want to #include Instruction.h into 1479 // Constant.h 1480 bool ConstantExpr::isCast() const { 1481 return Instruction::isCast(getOpcode()); 1482 } 1483 1484 bool ConstantExpr::isCompare() const { 1485 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp; 1486 } 1487 1488 bool ConstantExpr::hasIndices() const { 1489 return getOpcode() == Instruction::ExtractValue || 1490 getOpcode() == Instruction::InsertValue; 1491 } 1492 1493 ArrayRef<unsigned> ConstantExpr::getIndices() const { 1494 if (const ExtractValueConstantExpr *EVCE = 1495 dyn_cast<ExtractValueConstantExpr>(this)) 1496 return EVCE->Indices; 1497 1498 return cast<InsertValueConstantExpr>(this)->Indices; 1499 } 1500 1501 unsigned ConstantExpr::getPredicate() const { 1502 return cast<CompareConstantExpr>(this)->predicate; 1503 } 1504 1505 ArrayRef<int> ConstantExpr::getShuffleMask() const { 1506 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask; 1507 } 1508 1509 Constant *ConstantExpr::getShuffleMaskForBitcode() const { 1510 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode; 1511 } 1512 1513 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty, 1514 bool OnlyIfReduced, Type *SrcTy) const { 1515 assert(Ops.size() == getNumOperands() && "Operand count mismatch!"); 1516 1517 // If no operands changed return self. 1518 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin())) 1519 return const_cast<ConstantExpr*>(this); 1520 1521 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr; 1522 switch (getOpcode()) { 1523 case Instruction::Trunc: 1524 case Instruction::ZExt: 1525 case Instruction::SExt: 1526 case Instruction::FPTrunc: 1527 case Instruction::FPExt: 1528 case Instruction::UIToFP: 1529 case Instruction::SIToFP: 1530 case Instruction::FPToUI: 1531 case Instruction::FPToSI: 1532 case Instruction::PtrToInt: 1533 case Instruction::IntToPtr: 1534 case Instruction::BitCast: 1535 case Instruction::AddrSpaceCast: 1536 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced); 1537 case Instruction::Select: 1538 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy); 1539 case Instruction::InsertElement: 1540 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2], 1541 OnlyIfReducedTy); 1542 case Instruction::ExtractElement: 1543 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy); 1544 case Instruction::InsertValue: 1545 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(), 1546 OnlyIfReducedTy); 1547 case Instruction::ExtractValue: 1548 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy); 1549 case Instruction::FNeg: 1550 return ConstantExpr::getFNeg(Ops[0]); 1551 case Instruction::ShuffleVector: 1552 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(), 1553 OnlyIfReducedTy); 1554 case Instruction::GetElementPtr: { 1555 auto *GEPO = cast<GEPOperator>(this); 1556 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType())); 1557 return ConstantExpr::getGetElementPtr( 1558 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1), 1559 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy); 1560 } 1561 case Instruction::ICmp: 1562 case Instruction::FCmp: 1563 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1], 1564 OnlyIfReducedTy); 1565 default: 1566 assert(getNumOperands() == 2 && "Must be binary operator?"); 1567 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData, 1568 OnlyIfReducedTy); 1569 } 1570 } 1571 1572 1573 //===----------------------------------------------------------------------===// 1574 // isValueValidForType implementations 1575 1576 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) { 1577 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay 1578 if (Ty->isIntegerTy(1)) 1579 return Val == 0 || Val == 1; 1580 return isUIntN(NumBits, Val); 1581 } 1582 1583 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) { 1584 unsigned NumBits = Ty->getIntegerBitWidth(); 1585 if (Ty->isIntegerTy(1)) 1586 return Val == 0 || Val == 1 || Val == -1; 1587 return isIntN(NumBits, Val); 1588 } 1589 1590 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) { 1591 // convert modifies in place, so make a copy. 1592 APFloat Val2 = APFloat(Val); 1593 bool losesInfo; 1594 switch (Ty->getTypeID()) { 1595 default: 1596 return false; // These can't be represented as floating point! 1597 1598 // FIXME rounding mode needs to be more flexible 1599 case Type::HalfTyID: { 1600 if (&Val2.getSemantics() == &APFloat::IEEEhalf()) 1601 return true; 1602 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo); 1603 return !losesInfo; 1604 } 1605 case Type::BFloatTyID: { 1606 if (&Val2.getSemantics() == &APFloat::BFloat()) 1607 return true; 1608 Val2.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, &losesInfo); 1609 return !losesInfo; 1610 } 1611 case Type::FloatTyID: { 1612 if (&Val2.getSemantics() == &APFloat::IEEEsingle()) 1613 return true; 1614 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo); 1615 return !losesInfo; 1616 } 1617 case Type::DoubleTyID: { 1618 if (&Val2.getSemantics() == &APFloat::IEEEhalf() || 1619 &Val2.getSemantics() == &APFloat::BFloat() || 1620 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1621 &Val2.getSemantics() == &APFloat::IEEEdouble()) 1622 return true; 1623 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo); 1624 return !losesInfo; 1625 } 1626 case Type::X86_FP80TyID: 1627 return &Val2.getSemantics() == &APFloat::IEEEhalf() || 1628 &Val2.getSemantics() == &APFloat::BFloat() || 1629 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1630 &Val2.getSemantics() == &APFloat::IEEEdouble() || 1631 &Val2.getSemantics() == &APFloat::x87DoubleExtended(); 1632 case Type::FP128TyID: 1633 return &Val2.getSemantics() == &APFloat::IEEEhalf() || 1634 &Val2.getSemantics() == &APFloat::BFloat() || 1635 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1636 &Val2.getSemantics() == &APFloat::IEEEdouble() || 1637 &Val2.getSemantics() == &APFloat::IEEEquad(); 1638 case Type::PPC_FP128TyID: 1639 return &Val2.getSemantics() == &APFloat::IEEEhalf() || 1640 &Val2.getSemantics() == &APFloat::BFloat() || 1641 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1642 &Val2.getSemantics() == &APFloat::IEEEdouble() || 1643 &Val2.getSemantics() == &APFloat::PPCDoubleDouble(); 1644 } 1645 } 1646 1647 1648 //===----------------------------------------------------------------------===// 1649 // Factory Function Implementation 1650 1651 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) { 1652 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) && 1653 "Cannot create an aggregate zero of non-aggregate type!"); 1654 1655 std::unique_ptr<ConstantAggregateZero> &Entry = 1656 Ty->getContext().pImpl->CAZConstants[Ty]; 1657 if (!Entry) 1658 Entry.reset(new ConstantAggregateZero(Ty)); 1659 1660 return Entry.get(); 1661 } 1662 1663 /// Remove the constant from the constant table. 1664 void ConstantAggregateZero::destroyConstantImpl() { 1665 getContext().pImpl->CAZConstants.erase(getType()); 1666 } 1667 1668 /// Remove the constant from the constant table. 1669 void ConstantArray::destroyConstantImpl() { 1670 getType()->getContext().pImpl->ArrayConstants.remove(this); 1671 } 1672 1673 1674 //---- ConstantStruct::get() implementation... 1675 // 1676 1677 /// Remove the constant from the constant table. 1678 void ConstantStruct::destroyConstantImpl() { 1679 getType()->getContext().pImpl->StructConstants.remove(this); 1680 } 1681 1682 /// Remove the constant from the constant table. 1683 void ConstantVector::destroyConstantImpl() { 1684 getType()->getContext().pImpl->VectorConstants.remove(this); 1685 } 1686 1687 Constant *Constant::getSplatValue(bool AllowUndefs) const { 1688 assert(this->getType()->isVectorTy() && "Only valid for vectors!"); 1689 if (isa<ConstantAggregateZero>(this)) 1690 return getNullValue(cast<VectorType>(getType())->getElementType()); 1691 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) 1692 return CV->getSplatValue(); 1693 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) 1694 return CV->getSplatValue(AllowUndefs); 1695 1696 // Check if this is a constant expression splat of the form returned by 1697 // ConstantVector::getSplat() 1698 const auto *Shuf = dyn_cast<ConstantExpr>(this); 1699 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector && 1700 isa<UndefValue>(Shuf->getOperand(1))) { 1701 1702 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0)); 1703 if (IElt && IElt->getOpcode() == Instruction::InsertElement && 1704 isa<UndefValue>(IElt->getOperand(0))) { 1705 1706 ArrayRef<int> Mask = Shuf->getShuffleMask(); 1707 Constant *SplatVal = IElt->getOperand(1); 1708 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2)); 1709 1710 if (Index && Index->getValue() == 0 && 1711 llvm::all_of(Mask, [](int I) { return I == 0; })) 1712 return SplatVal; 1713 } 1714 } 1715 1716 return nullptr; 1717 } 1718 1719 Constant *ConstantVector::getSplatValue(bool AllowUndefs) const { 1720 // Check out first element. 1721 Constant *Elt = getOperand(0); 1722 // Then make sure all remaining elements point to the same value. 1723 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) { 1724 Constant *OpC = getOperand(I); 1725 if (OpC == Elt) 1726 continue; 1727 1728 // Strict mode: any mismatch is not a splat. 1729 if (!AllowUndefs) 1730 return nullptr; 1731 1732 // Allow undefs mode: ignore undefined elements. 1733 if (isa<UndefValue>(OpC)) 1734 continue; 1735 1736 // If we do not have a defined element yet, use the current operand. 1737 if (isa<UndefValue>(Elt)) 1738 Elt = OpC; 1739 1740 if (OpC != Elt) 1741 return nullptr; 1742 } 1743 return Elt; 1744 } 1745 1746 const APInt &Constant::getUniqueInteger() const { 1747 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 1748 return CI->getValue(); 1749 assert(this->getSplatValue() && "Doesn't contain a unique integer!"); 1750 const Constant *C = this->getAggregateElement(0U); 1751 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!"); 1752 return cast<ConstantInt>(C)->getValue(); 1753 } 1754 1755 //---- ConstantPointerNull::get() implementation. 1756 // 1757 1758 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) { 1759 std::unique_ptr<ConstantPointerNull> &Entry = 1760 Ty->getContext().pImpl->CPNConstants[Ty]; 1761 if (!Entry) 1762 Entry.reset(new ConstantPointerNull(Ty)); 1763 1764 return Entry.get(); 1765 } 1766 1767 /// Remove the constant from the constant table. 1768 void ConstantPointerNull::destroyConstantImpl() { 1769 getContext().pImpl->CPNConstants.erase(getType()); 1770 } 1771 1772 UndefValue *UndefValue::get(Type *Ty) { 1773 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty]; 1774 if (!Entry) 1775 Entry.reset(new UndefValue(Ty)); 1776 1777 return Entry.get(); 1778 } 1779 1780 /// Remove the constant from the constant table. 1781 void UndefValue::destroyConstantImpl() { 1782 // Free the constant and any dangling references to it. 1783 if (getValueID() == UndefValueVal) { 1784 getContext().pImpl->UVConstants.erase(getType()); 1785 } else if (getValueID() == PoisonValueVal) { 1786 getContext().pImpl->PVConstants.erase(getType()); 1787 } 1788 llvm_unreachable("Not a undef or a poison!"); 1789 } 1790 1791 PoisonValue *PoisonValue::get(Type *Ty) { 1792 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty]; 1793 if (!Entry) 1794 Entry.reset(new PoisonValue(Ty)); 1795 1796 return Entry.get(); 1797 } 1798 1799 /// Remove the constant from the constant table. 1800 void PoisonValue::destroyConstantImpl() { 1801 // Free the constant and any dangling references to it. 1802 getContext().pImpl->PVConstants.erase(getType()); 1803 } 1804 1805 BlockAddress *BlockAddress::get(BasicBlock *BB) { 1806 assert(BB->getParent() && "Block must have a parent"); 1807 return get(BB->getParent(), BB); 1808 } 1809 1810 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) { 1811 BlockAddress *&BA = 1812 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)]; 1813 if (!BA) 1814 BA = new BlockAddress(F, BB); 1815 1816 assert(BA->getFunction() == F && "Basic block moved between functions"); 1817 return BA; 1818 } 1819 1820 BlockAddress::BlockAddress(Function *F, BasicBlock *BB) 1821 : Constant(Type::getInt8PtrTy(F->getContext(), F->getAddressSpace()), 1822 Value::BlockAddressVal, &Op<0>(), 2) { 1823 setOperand(0, F); 1824 setOperand(1, BB); 1825 BB->AdjustBlockAddressRefCount(1); 1826 } 1827 1828 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) { 1829 if (!BB->hasAddressTaken()) 1830 return nullptr; 1831 1832 const Function *F = BB->getParent(); 1833 assert(F && "Block must have a parent"); 1834 BlockAddress *BA = 1835 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB)); 1836 assert(BA && "Refcount and block address map disagree!"); 1837 return BA; 1838 } 1839 1840 /// Remove the constant from the constant table. 1841 void BlockAddress::destroyConstantImpl() { 1842 getFunction()->getType()->getContext().pImpl 1843 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock())); 1844 getBasicBlock()->AdjustBlockAddressRefCount(-1); 1845 } 1846 1847 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) { 1848 // This could be replacing either the Basic Block or the Function. In either 1849 // case, we have to remove the map entry. 1850 Function *NewF = getFunction(); 1851 BasicBlock *NewBB = getBasicBlock(); 1852 1853 if (From == NewF) 1854 NewF = cast<Function>(To->stripPointerCasts()); 1855 else { 1856 assert(From == NewBB && "From does not match any operand"); 1857 NewBB = cast<BasicBlock>(To); 1858 } 1859 1860 // See if the 'new' entry already exists, if not, just update this in place 1861 // and return early. 1862 BlockAddress *&NewBA = 1863 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)]; 1864 if (NewBA) 1865 return NewBA; 1866 1867 getBasicBlock()->AdjustBlockAddressRefCount(-1); 1868 1869 // Remove the old entry, this can't cause the map to rehash (just a 1870 // tombstone will get added). 1871 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(), 1872 getBasicBlock())); 1873 NewBA = this; 1874 setOperand(0, NewF); 1875 setOperand(1, NewBB); 1876 getBasicBlock()->AdjustBlockAddressRefCount(1); 1877 1878 // If we just want to keep the existing value, then return null. 1879 // Callers know that this means we shouldn't delete this value. 1880 return nullptr; 1881 } 1882 1883 DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) { 1884 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV]; 1885 if (!Equiv) 1886 Equiv = new DSOLocalEquivalent(GV); 1887 1888 assert(Equiv->getGlobalValue() == GV && 1889 "DSOLocalFunction does not match the expected global value"); 1890 return Equiv; 1891 } 1892 1893 DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV) 1894 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, &Op<0>(), 1) { 1895 setOperand(0, GV); 1896 } 1897 1898 /// Remove the constant from the constant table. 1899 void DSOLocalEquivalent::destroyConstantImpl() { 1900 const GlobalValue *GV = getGlobalValue(); 1901 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV); 1902 } 1903 1904 Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) { 1905 assert(From == getGlobalValue() && "Changing value does not match operand."); 1906 assert(isa<Constant>(To) && "Can only replace the operands with a constant"); 1907 1908 // The replacement is with another global value. 1909 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) { 1910 DSOLocalEquivalent *&NewEquiv = 1911 getContext().pImpl->DSOLocalEquivalents[ToObj]; 1912 if (NewEquiv) 1913 return llvm::ConstantExpr::getBitCast(NewEquiv, getType()); 1914 } 1915 1916 // If the argument is replaced with a null value, just replace this constant 1917 // with a null value. 1918 if (cast<Constant>(To)->isNullValue()) 1919 return To; 1920 1921 // The replacement could be a bitcast or an alias to another function. We can 1922 // replace it with a bitcast to the dso_local_equivalent of that function. 1923 auto *Func = cast<Function>(To->stripPointerCastsAndAliases()); 1924 DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func]; 1925 if (NewEquiv) 1926 return llvm::ConstantExpr::getBitCast(NewEquiv, getType()); 1927 1928 // Replace this with the new one. 1929 getContext().pImpl->DSOLocalEquivalents.erase(getGlobalValue()); 1930 NewEquiv = this; 1931 setOperand(0, Func); 1932 1933 if (Func->getType() != getType()) { 1934 // It is ok to mutate the type here because this constant should always 1935 // reflect the type of the function it's holding. 1936 mutateType(Func->getType()); 1937 } 1938 return nullptr; 1939 } 1940 1941 NoCFIValue *NoCFIValue::get(GlobalValue *GV) { 1942 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV]; 1943 if (!NC) 1944 NC = new NoCFIValue(GV); 1945 1946 assert(NC->getGlobalValue() == GV && 1947 "NoCFIValue does not match the expected global value"); 1948 return NC; 1949 } 1950 1951 NoCFIValue::NoCFIValue(GlobalValue *GV) 1952 : Constant(GV->getType(), Value::NoCFIValueVal, &Op<0>(), 1) { 1953 setOperand(0, GV); 1954 } 1955 1956 /// Remove the constant from the constant table. 1957 void NoCFIValue::destroyConstantImpl() { 1958 const GlobalValue *GV = getGlobalValue(); 1959 GV->getContext().pImpl->NoCFIValues.erase(GV); 1960 } 1961 1962 Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) { 1963 assert(From == getGlobalValue() && "Changing value does not match operand."); 1964 1965 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts()); 1966 assert(GV && "Can only replace the operands with a global value"); 1967 1968 NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV]; 1969 if (NewNC) 1970 return llvm::ConstantExpr::getBitCast(NewNC, getType()); 1971 1972 getContext().pImpl->NoCFIValues.erase(getGlobalValue()); 1973 NewNC = this; 1974 setOperand(0, GV); 1975 1976 if (GV->getType() != getType()) 1977 mutateType(GV->getType()); 1978 1979 return nullptr; 1980 } 1981 1982 //---- ConstantExpr::get() implementations. 1983 // 1984 1985 /// This is a utility function to handle folding of casts and lookup of the 1986 /// cast in the ExprConstants map. It is used by the various get* methods below. 1987 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty, 1988 bool OnlyIfReduced = false) { 1989 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!"); 1990 // Fold a few common cases 1991 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty)) 1992 return FC; 1993 1994 if (OnlyIfReduced) 1995 return nullptr; 1996 1997 LLVMContextImpl *pImpl = Ty->getContext().pImpl; 1998 1999 // Look up the constant in the table first to ensure uniqueness. 2000 ConstantExprKeyType Key(opc, C); 2001 2002 return pImpl->ExprConstants.getOrCreate(Ty, Key); 2003 } 2004 2005 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty, 2006 bool OnlyIfReduced) { 2007 Instruction::CastOps opc = Instruction::CastOps(oc); 2008 assert(Instruction::isCast(opc) && "opcode out of range"); 2009 assert(C && Ty && "Null arguments to getCast"); 2010 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!"); 2011 2012 switch (opc) { 2013 default: 2014 llvm_unreachable("Invalid cast opcode"); 2015 case Instruction::Trunc: 2016 return getTrunc(C, Ty, OnlyIfReduced); 2017 case Instruction::ZExt: 2018 return getZExt(C, Ty, OnlyIfReduced); 2019 case Instruction::SExt: 2020 return getSExt(C, Ty, OnlyIfReduced); 2021 case Instruction::FPTrunc: 2022 return getFPTrunc(C, Ty, OnlyIfReduced); 2023 case Instruction::FPExt: 2024 return getFPExtend(C, Ty, OnlyIfReduced); 2025 case Instruction::UIToFP: 2026 return getUIToFP(C, Ty, OnlyIfReduced); 2027 case Instruction::SIToFP: 2028 return getSIToFP(C, Ty, OnlyIfReduced); 2029 case Instruction::FPToUI: 2030 return getFPToUI(C, Ty, OnlyIfReduced); 2031 case Instruction::FPToSI: 2032 return getFPToSI(C, Ty, OnlyIfReduced); 2033 case Instruction::PtrToInt: 2034 return getPtrToInt(C, Ty, OnlyIfReduced); 2035 case Instruction::IntToPtr: 2036 return getIntToPtr(C, Ty, OnlyIfReduced); 2037 case Instruction::BitCast: 2038 return getBitCast(C, Ty, OnlyIfReduced); 2039 case Instruction::AddrSpaceCast: 2040 return getAddrSpaceCast(C, Ty, OnlyIfReduced); 2041 } 2042 } 2043 2044 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) { 2045 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2046 return getBitCast(C, Ty); 2047 return getZExt(C, Ty); 2048 } 2049 2050 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) { 2051 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2052 return getBitCast(C, Ty); 2053 return getSExt(C, Ty); 2054 } 2055 2056 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) { 2057 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2058 return getBitCast(C, Ty); 2059 return getTrunc(C, Ty); 2060 } 2061 2062 Constant *ConstantExpr::getSExtOrTrunc(Constant *C, Type *Ty) { 2063 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 2064 "Can only sign extend/truncate integers!"); 2065 Type *CTy = C->getType(); 2066 if (CTy->getScalarSizeInBits() < Ty->getScalarSizeInBits()) 2067 return getSExt(C, Ty); 2068 if (CTy->getScalarSizeInBits() > Ty->getScalarSizeInBits()) 2069 return getTrunc(C, Ty); 2070 return C; 2071 } 2072 2073 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) { 2074 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2075 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2076 "Invalid cast"); 2077 2078 if (Ty->isIntOrIntVectorTy()) 2079 return getPtrToInt(S, Ty); 2080 2081 unsigned SrcAS = S->getType()->getPointerAddressSpace(); 2082 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace()) 2083 return getAddrSpaceCast(S, Ty); 2084 2085 return getBitCast(S, Ty); 2086 } 2087 2088 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S, 2089 Type *Ty) { 2090 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2091 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2092 2093 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2094 return getAddrSpaceCast(S, Ty); 2095 2096 return getBitCast(S, Ty); 2097 } 2098 2099 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) { 2100 assert(C->getType()->isIntOrIntVectorTy() && 2101 Ty->isIntOrIntVectorTy() && "Invalid cast"); 2102 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2103 unsigned DstBits = Ty->getScalarSizeInBits(); 2104 Instruction::CastOps opcode = 2105 (SrcBits == DstBits ? Instruction::BitCast : 2106 (SrcBits > DstBits ? Instruction::Trunc : 2107 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2108 return getCast(opcode, C, Ty); 2109 } 2110 2111 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) { 2112 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 2113 "Invalid cast"); 2114 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2115 unsigned DstBits = Ty->getScalarSizeInBits(); 2116 if (SrcBits == DstBits) 2117 return C; // Avoid a useless cast 2118 Instruction::CastOps opcode = 2119 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt); 2120 return getCast(opcode, C, Ty); 2121 } 2122 2123 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) { 2124 #ifndef NDEBUG 2125 bool fromVec = isa<VectorType>(C->getType()); 2126 bool toVec = isa<VectorType>(Ty); 2127 #endif 2128 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 2129 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer"); 2130 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral"); 2131 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&& 2132 "SrcTy must be larger than DestTy for Trunc!"); 2133 2134 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced); 2135 } 2136 2137 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) { 2138 #ifndef NDEBUG 2139 bool fromVec = isa<VectorType>(C->getType()); 2140 bool toVec = isa<VectorType>(Ty); 2141 #endif 2142 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 2143 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral"); 2144 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer"); 2145 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 2146 "SrcTy must be smaller than DestTy for SExt!"); 2147 2148 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced); 2149 } 2150 2151 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) { 2152 #ifndef NDEBUG 2153 bool fromVec = isa<VectorType>(C->getType()); 2154 bool toVec = isa<VectorType>(Ty); 2155 #endif 2156 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 2157 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral"); 2158 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer"); 2159 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 2160 "SrcTy must be smaller than DestTy for ZExt!"); 2161 2162 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced); 2163 } 2164 2165 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) { 2166 #ifndef NDEBUG 2167 bool fromVec = isa<VectorType>(C->getType()); 2168 bool toVec = isa<VectorType>(Ty); 2169 #endif 2170 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 2171 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 2172 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&& 2173 "This is an illegal floating point truncation!"); 2174 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced); 2175 } 2176 2177 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) { 2178 #ifndef NDEBUG 2179 bool fromVec = isa<VectorType>(C->getType()); 2180 bool toVec = isa<VectorType>(Ty); 2181 #endif 2182 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 2183 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 2184 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 2185 "This is an illegal floating point extension!"); 2186 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced); 2187 } 2188 2189 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) { 2190 #ifndef NDEBUG 2191 bool fromVec = isa<VectorType>(C->getType()); 2192 bool toVec = isa<VectorType>(Ty); 2193 #endif 2194 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 2195 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() && 2196 "This is an illegal uint to floating point cast!"); 2197 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced); 2198 } 2199 2200 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) { 2201 #ifndef NDEBUG 2202 bool fromVec = isa<VectorType>(C->getType()); 2203 bool toVec = isa<VectorType>(Ty); 2204 #endif 2205 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 2206 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() && 2207 "This is an illegal sint to floating point cast!"); 2208 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced); 2209 } 2210 2211 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) { 2212 #ifndef NDEBUG 2213 bool fromVec = isa<VectorType>(C->getType()); 2214 bool toVec = isa<VectorType>(Ty); 2215 #endif 2216 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 2217 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() && 2218 "This is an illegal floating point to uint cast!"); 2219 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced); 2220 } 2221 2222 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) { 2223 #ifndef NDEBUG 2224 bool fromVec = isa<VectorType>(C->getType()); 2225 bool toVec = isa<VectorType>(Ty); 2226 #endif 2227 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 2228 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() && 2229 "This is an illegal floating point to sint cast!"); 2230 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced); 2231 } 2232 2233 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy, 2234 bool OnlyIfReduced) { 2235 assert(C->getType()->isPtrOrPtrVectorTy() && 2236 "PtrToInt source must be pointer or pointer vector"); 2237 assert(DstTy->isIntOrIntVectorTy() && 2238 "PtrToInt destination must be integer or integer vector"); 2239 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy)); 2240 if (isa<VectorType>(C->getType())) 2241 assert(cast<VectorType>(C->getType())->getElementCount() == 2242 cast<VectorType>(DstTy)->getElementCount() && 2243 "Invalid cast between a different number of vector elements"); 2244 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced); 2245 } 2246 2247 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy, 2248 bool OnlyIfReduced) { 2249 assert(C->getType()->isIntOrIntVectorTy() && 2250 "IntToPtr source must be integer or integer vector"); 2251 assert(DstTy->isPtrOrPtrVectorTy() && 2252 "IntToPtr destination must be a pointer or pointer vector"); 2253 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy)); 2254 if (isa<VectorType>(C->getType())) 2255 assert(cast<VectorType>(C->getType())->getElementCount() == 2256 cast<VectorType>(DstTy)->getElementCount() && 2257 "Invalid cast between a different number of vector elements"); 2258 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced); 2259 } 2260 2261 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy, 2262 bool OnlyIfReduced) { 2263 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) && 2264 "Invalid constantexpr bitcast!"); 2265 2266 // It is common to ask for a bitcast of a value to its own type, handle this 2267 // speedily. 2268 if (C->getType() == DstTy) return C; 2269 2270 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced); 2271 } 2272 2273 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy, 2274 bool OnlyIfReduced) { 2275 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) && 2276 "Invalid constantexpr addrspacecast!"); 2277 2278 // Canonicalize addrspacecasts between different pointer types by first 2279 // bitcasting the pointer type and then converting the address space. 2280 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType()); 2281 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType()); 2282 if (!SrcScalarTy->hasSameElementTypeAs(DstScalarTy)) { 2283 Type *MidTy = PointerType::getWithSamePointeeType( 2284 DstScalarTy, SrcScalarTy->getAddressSpace()); 2285 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) { 2286 // Handle vectors of pointers. 2287 MidTy = FixedVectorType::get(MidTy, 2288 cast<FixedVectorType>(VT)->getNumElements()); 2289 } 2290 C = getBitCast(C, MidTy); 2291 } 2292 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced); 2293 } 2294 2295 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags, 2296 Type *OnlyIfReducedTy) { 2297 // Check the operands for consistency first. 2298 assert(Instruction::isUnaryOp(Opcode) && 2299 "Invalid opcode in unary constant expression"); 2300 2301 #ifndef NDEBUG 2302 switch (Opcode) { 2303 case Instruction::FNeg: 2304 assert(C->getType()->isFPOrFPVectorTy() && 2305 "Tried to create a floating-point operation on a " 2306 "non-floating-point type!"); 2307 break; 2308 default: 2309 break; 2310 } 2311 #endif 2312 2313 if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C)) 2314 return FC; 2315 2316 if (OnlyIfReducedTy == C->getType()) 2317 return nullptr; 2318 2319 Constant *ArgVec[] = { C }; 2320 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags); 2321 2322 LLVMContextImpl *pImpl = C->getContext().pImpl; 2323 return pImpl->ExprConstants.getOrCreate(C->getType(), Key); 2324 } 2325 2326 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2, 2327 unsigned Flags, Type *OnlyIfReducedTy) { 2328 // Check the operands for consistency first. 2329 assert(Instruction::isBinaryOp(Opcode) && 2330 "Invalid opcode in binary constant expression"); 2331 assert(C1->getType() == C2->getType() && 2332 "Operand types in binary constant expression should match"); 2333 2334 #ifndef NDEBUG 2335 switch (Opcode) { 2336 case Instruction::Add: 2337 case Instruction::Sub: 2338 case Instruction::Mul: 2339 case Instruction::UDiv: 2340 case Instruction::SDiv: 2341 case Instruction::URem: 2342 case Instruction::SRem: 2343 assert(C1->getType()->isIntOrIntVectorTy() && 2344 "Tried to create an integer operation on a non-integer type!"); 2345 break; 2346 case Instruction::FAdd: 2347 case Instruction::FSub: 2348 case Instruction::FMul: 2349 case Instruction::FDiv: 2350 case Instruction::FRem: 2351 assert(C1->getType()->isFPOrFPVectorTy() && 2352 "Tried to create a floating-point operation on a " 2353 "non-floating-point type!"); 2354 break; 2355 case Instruction::And: 2356 case Instruction::Or: 2357 case Instruction::Xor: 2358 assert(C1->getType()->isIntOrIntVectorTy() && 2359 "Tried to create a logical operation on a non-integral type!"); 2360 break; 2361 case Instruction::Shl: 2362 case Instruction::LShr: 2363 case Instruction::AShr: 2364 assert(C1->getType()->isIntOrIntVectorTy() && 2365 "Tried to create a shift operation on a non-integer type!"); 2366 break; 2367 default: 2368 break; 2369 } 2370 #endif 2371 2372 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2)) 2373 return FC; 2374 2375 if (OnlyIfReducedTy == C1->getType()) 2376 return nullptr; 2377 2378 Constant *ArgVec[] = { C1, C2 }; 2379 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags); 2380 2381 LLVMContextImpl *pImpl = C1->getContext().pImpl; 2382 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key); 2383 } 2384 2385 Constant *ConstantExpr::getSizeOf(Type* Ty) { 2386 // sizeof is implemented as: (i64) gep (Ty*)null, 1 2387 // Note that a non-inbounds gep is used, as null isn't within any object. 2388 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); 2389 Constant *GEP = getGetElementPtr( 2390 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx); 2391 return getPtrToInt(GEP, 2392 Type::getInt64Ty(Ty->getContext())); 2393 } 2394 2395 Constant *ConstantExpr::getAlignOf(Type* Ty) { 2396 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1 2397 // Note that a non-inbounds gep is used, as null isn't within any object. 2398 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty); 2399 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0)); 2400 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0); 2401 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); 2402 Constant *Indices[2] = { Zero, One }; 2403 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices); 2404 return getPtrToInt(GEP, 2405 Type::getInt64Ty(Ty->getContext())); 2406 } 2407 2408 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) { 2409 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()), 2410 FieldNo)); 2411 } 2412 2413 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) { 2414 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo 2415 // Note that a non-inbounds gep is used, as null isn't within any object. 2416 Constant *GEPIdx[] = { 2417 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0), 2418 FieldNo 2419 }; 2420 Constant *GEP = getGetElementPtr( 2421 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx); 2422 return getPtrToInt(GEP, 2423 Type::getInt64Ty(Ty->getContext())); 2424 } 2425 2426 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1, 2427 Constant *C2, bool OnlyIfReduced) { 2428 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 2429 2430 switch (Predicate) { 2431 default: llvm_unreachable("Invalid CmpInst predicate"); 2432 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT: 2433 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE: 2434 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO: 2435 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE: 2436 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE: 2437 case CmpInst::FCMP_TRUE: 2438 return getFCmp(Predicate, C1, C2, OnlyIfReduced); 2439 2440 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT: 2441 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE: 2442 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT: 2443 case CmpInst::ICMP_SLE: 2444 return getICmp(Predicate, C1, C2, OnlyIfReduced); 2445 } 2446 } 2447 2448 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2, 2449 Type *OnlyIfReducedTy) { 2450 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands"); 2451 2452 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2)) 2453 return SC; // Fold common cases 2454 2455 if (OnlyIfReducedTy == V1->getType()) 2456 return nullptr; 2457 2458 Constant *ArgVec[] = { C, V1, V2 }; 2459 ConstantExprKeyType Key(Instruction::Select, ArgVec); 2460 2461 LLVMContextImpl *pImpl = C->getContext().pImpl; 2462 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key); 2463 } 2464 2465 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C, 2466 ArrayRef<Value *> Idxs, bool InBounds, 2467 Optional<unsigned> InRangeIndex, 2468 Type *OnlyIfReducedTy) { 2469 PointerType *OrigPtrTy = cast<PointerType>(C->getType()->getScalarType()); 2470 assert(Ty && "Must specify element type"); 2471 assert(OrigPtrTy->isOpaqueOrPointeeTypeMatches(Ty)); 2472 2473 if (Constant *FC = 2474 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs)) 2475 return FC; // Fold a few common cases. 2476 2477 // Get the result type of the getelementptr! 2478 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs); 2479 assert(DestTy && "GEP indices invalid!"); 2480 unsigned AS = OrigPtrTy->getAddressSpace(); 2481 Type *ReqTy = OrigPtrTy->isOpaque() 2482 ? PointerType::get(OrigPtrTy->getContext(), AS) 2483 : DestTy->getPointerTo(AS); 2484 2485 auto EltCount = ElementCount::getFixed(0); 2486 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType())) 2487 EltCount = VecTy->getElementCount(); 2488 else 2489 for (auto Idx : Idxs) 2490 if (VectorType *VecTy = dyn_cast<VectorType>(Idx->getType())) 2491 EltCount = VecTy->getElementCount(); 2492 2493 if (EltCount.isNonZero()) 2494 ReqTy = VectorType::get(ReqTy, EltCount); 2495 2496 if (OnlyIfReducedTy == ReqTy) 2497 return nullptr; 2498 2499 // Look up the constant in the table first to ensure uniqueness 2500 std::vector<Constant*> ArgVec; 2501 ArgVec.reserve(1 + Idxs.size()); 2502 ArgVec.push_back(C); 2503 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs); 2504 for (; GTI != GTE; ++GTI) { 2505 auto *Idx = cast<Constant>(GTI.getOperand()); 2506 assert( 2507 (!isa<VectorType>(Idx->getType()) || 2508 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) && 2509 "getelementptr index type missmatch"); 2510 2511 if (GTI.isStruct() && Idx->getType()->isVectorTy()) { 2512 Idx = Idx->getSplatValue(); 2513 } else if (GTI.isSequential() && EltCount.isNonZero() && 2514 !Idx->getType()->isVectorTy()) { 2515 Idx = ConstantVector::getSplat(EltCount, Idx); 2516 } 2517 ArgVec.push_back(Idx); 2518 } 2519 2520 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0; 2521 if (InRangeIndex && *InRangeIndex < 63) 2522 SubClassOptionalData |= (*InRangeIndex + 1) << 1; 2523 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0, 2524 SubClassOptionalData, None, None, Ty); 2525 2526 LLVMContextImpl *pImpl = C->getContext().pImpl; 2527 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 2528 } 2529 2530 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS, 2531 Constant *RHS, bool OnlyIfReduced) { 2532 auto Predicate = static_cast<CmpInst::Predicate>(pred); 2533 assert(LHS->getType() == RHS->getType()); 2534 assert(CmpInst::isIntPredicate(Predicate) && "Invalid ICmp Predicate"); 2535 2536 if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS)) 2537 return FC; // Fold a few common cases... 2538 2539 if (OnlyIfReduced) 2540 return nullptr; 2541 2542 // Look up the constant in the table first to ensure uniqueness 2543 Constant *ArgVec[] = { LHS, RHS }; 2544 // Get the key type with both the opcode and predicate 2545 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, Predicate); 2546 2547 Type *ResultTy = Type::getInt1Ty(LHS->getContext()); 2548 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType())) 2549 ResultTy = VectorType::get(ResultTy, VT->getElementCount()); 2550 2551 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; 2552 return pImpl->ExprConstants.getOrCreate(ResultTy, Key); 2553 } 2554 2555 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, 2556 Constant *RHS, bool OnlyIfReduced) { 2557 auto Predicate = static_cast<CmpInst::Predicate>(pred); 2558 assert(LHS->getType() == RHS->getType()); 2559 assert(CmpInst::isFPPredicate(Predicate) && "Invalid FCmp Predicate"); 2560 2561 if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS)) 2562 return FC; // Fold a few common cases... 2563 2564 if (OnlyIfReduced) 2565 return nullptr; 2566 2567 // Look up the constant in the table first to ensure uniqueness 2568 Constant *ArgVec[] = { LHS, RHS }; 2569 // Get the key type with both the opcode and predicate 2570 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, Predicate); 2571 2572 Type *ResultTy = Type::getInt1Ty(LHS->getContext()); 2573 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType())) 2574 ResultTy = VectorType::get(ResultTy, VT->getElementCount()); 2575 2576 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; 2577 return pImpl->ExprConstants.getOrCreate(ResultTy, Key); 2578 } 2579 2580 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx, 2581 Type *OnlyIfReducedTy) { 2582 assert(Val->getType()->isVectorTy() && 2583 "Tried to create extractelement operation on non-vector type!"); 2584 assert(Idx->getType()->isIntegerTy() && 2585 "Extractelement index must be an integer type!"); 2586 2587 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx)) 2588 return FC; // Fold a few common cases. 2589 2590 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType(); 2591 if (OnlyIfReducedTy == ReqTy) 2592 return nullptr; 2593 2594 // Look up the constant in the table first to ensure uniqueness 2595 Constant *ArgVec[] = { Val, Idx }; 2596 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec); 2597 2598 LLVMContextImpl *pImpl = Val->getContext().pImpl; 2599 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 2600 } 2601 2602 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 2603 Constant *Idx, Type *OnlyIfReducedTy) { 2604 assert(Val->getType()->isVectorTy() && 2605 "Tried to create insertelement operation on non-vector type!"); 2606 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() && 2607 "Insertelement types must match!"); 2608 assert(Idx->getType()->isIntegerTy() && 2609 "Insertelement index must be i32 type!"); 2610 2611 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx)) 2612 return FC; // Fold a few common cases. 2613 2614 if (OnlyIfReducedTy == Val->getType()) 2615 return nullptr; 2616 2617 // Look up the constant in the table first to ensure uniqueness 2618 Constant *ArgVec[] = { Val, Elt, Idx }; 2619 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec); 2620 2621 LLVMContextImpl *pImpl = Val->getContext().pImpl; 2622 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key); 2623 } 2624 2625 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 2626 ArrayRef<int> Mask, 2627 Type *OnlyIfReducedTy) { 2628 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) && 2629 "Invalid shuffle vector constant expr operands!"); 2630 2631 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask)) 2632 return FC; // Fold a few common cases. 2633 2634 unsigned NElts = Mask.size(); 2635 auto V1VTy = cast<VectorType>(V1->getType()); 2636 Type *EltTy = V1VTy->getElementType(); 2637 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy); 2638 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable); 2639 2640 if (OnlyIfReducedTy == ShufTy) 2641 return nullptr; 2642 2643 // Look up the constant in the table first to ensure uniqueness 2644 Constant *ArgVec[] = {V1, V2}; 2645 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, 0, None, Mask); 2646 2647 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl; 2648 return pImpl->ExprConstants.getOrCreate(ShufTy, Key); 2649 } 2650 2651 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val, 2652 ArrayRef<unsigned> Idxs, 2653 Type *OnlyIfReducedTy) { 2654 assert(Agg->getType()->isFirstClassType() && 2655 "Non-first-class type for constant insertvalue expression"); 2656 2657 assert(ExtractValueInst::getIndexedType(Agg->getType(), 2658 Idxs) == Val->getType() && 2659 "insertvalue indices invalid!"); 2660 Type *ReqTy = Val->getType(); 2661 2662 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs)) 2663 return FC; 2664 2665 if (OnlyIfReducedTy == ReqTy) 2666 return nullptr; 2667 2668 Constant *ArgVec[] = { Agg, Val }; 2669 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs); 2670 2671 LLVMContextImpl *pImpl = Agg->getContext().pImpl; 2672 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 2673 } 2674 2675 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs, 2676 Type *OnlyIfReducedTy) { 2677 assert(Agg->getType()->isFirstClassType() && 2678 "Tried to create extractelement operation on non-first-class type!"); 2679 2680 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs); 2681 (void)ReqTy; 2682 assert(ReqTy && "extractvalue indices invalid!"); 2683 2684 assert(Agg->getType()->isFirstClassType() && 2685 "Non-first-class type for constant extractvalue expression"); 2686 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs)) 2687 return FC; 2688 2689 if (OnlyIfReducedTy == ReqTy) 2690 return nullptr; 2691 2692 Constant *ArgVec[] = { Agg }; 2693 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs); 2694 2695 LLVMContextImpl *pImpl = Agg->getContext().pImpl; 2696 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 2697 } 2698 2699 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) { 2700 assert(C->getType()->isIntOrIntVectorTy() && 2701 "Cannot NEG a nonintegral value!"); 2702 return getSub(ConstantFP::getZeroValueForNegation(C->getType()), 2703 C, HasNUW, HasNSW); 2704 } 2705 2706 Constant *ConstantExpr::getFNeg(Constant *C) { 2707 assert(C->getType()->isFPOrFPVectorTy() && 2708 "Cannot FNEG a non-floating-point value!"); 2709 return get(Instruction::FNeg, C); 2710 } 2711 2712 Constant *ConstantExpr::getNot(Constant *C) { 2713 assert(C->getType()->isIntOrIntVectorTy() && 2714 "Cannot NOT a nonintegral value!"); 2715 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType())); 2716 } 2717 2718 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2, 2719 bool HasNUW, bool HasNSW) { 2720 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 2721 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 2722 return get(Instruction::Add, C1, C2, Flags); 2723 } 2724 2725 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) { 2726 return get(Instruction::FAdd, C1, C2); 2727 } 2728 2729 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2, 2730 bool HasNUW, bool HasNSW) { 2731 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 2732 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 2733 return get(Instruction::Sub, C1, C2, Flags); 2734 } 2735 2736 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) { 2737 return get(Instruction::FSub, C1, C2); 2738 } 2739 2740 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2, 2741 bool HasNUW, bool HasNSW) { 2742 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 2743 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 2744 return get(Instruction::Mul, C1, C2, Flags); 2745 } 2746 2747 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) { 2748 return get(Instruction::FMul, C1, C2); 2749 } 2750 2751 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) { 2752 return get(Instruction::UDiv, C1, C2, 2753 isExact ? PossiblyExactOperator::IsExact : 0); 2754 } 2755 2756 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) { 2757 return get(Instruction::SDiv, C1, C2, 2758 isExact ? PossiblyExactOperator::IsExact : 0); 2759 } 2760 2761 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) { 2762 return get(Instruction::FDiv, C1, C2); 2763 } 2764 2765 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) { 2766 return get(Instruction::URem, C1, C2); 2767 } 2768 2769 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) { 2770 return get(Instruction::SRem, C1, C2); 2771 } 2772 2773 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) { 2774 return get(Instruction::FRem, C1, C2); 2775 } 2776 2777 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) { 2778 return get(Instruction::And, C1, C2); 2779 } 2780 2781 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) { 2782 return get(Instruction::Or, C1, C2); 2783 } 2784 2785 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) { 2786 return get(Instruction::Xor, C1, C2); 2787 } 2788 2789 Constant *ConstantExpr::getUMin(Constant *C1, Constant *C2) { 2790 Constant *Cmp = ConstantExpr::getICmp(CmpInst::ICMP_ULT, C1, C2); 2791 return getSelect(Cmp, C1, C2); 2792 } 2793 2794 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2, 2795 bool HasNUW, bool HasNSW) { 2796 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 2797 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 2798 return get(Instruction::Shl, C1, C2, Flags); 2799 } 2800 2801 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) { 2802 return get(Instruction::LShr, C1, C2, 2803 isExact ? PossiblyExactOperator::IsExact : 0); 2804 } 2805 2806 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) { 2807 return get(Instruction::AShr, C1, C2, 2808 isExact ? PossiblyExactOperator::IsExact : 0); 2809 } 2810 2811 Constant *ConstantExpr::getExactLogBase2(Constant *C) { 2812 Type *Ty = C->getType(); 2813 const APInt *IVal; 2814 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2()) 2815 return ConstantInt::get(Ty, IVal->logBase2()); 2816 2817 // FIXME: We can extract pow of 2 of splat constant for scalable vectors. 2818 auto *VecTy = dyn_cast<FixedVectorType>(Ty); 2819 if (!VecTy) 2820 return nullptr; 2821 2822 SmallVector<Constant *, 4> Elts; 2823 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) { 2824 Constant *Elt = C->getAggregateElement(I); 2825 if (!Elt) 2826 return nullptr; 2827 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N. 2828 if (isa<UndefValue>(Elt)) { 2829 Elts.push_back(Constant::getNullValue(Ty->getScalarType())); 2830 continue; 2831 } 2832 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2()) 2833 return nullptr; 2834 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2())); 2835 } 2836 2837 return ConstantVector::get(Elts); 2838 } 2839 2840 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty, 2841 bool AllowRHSConstant, bool NSZ) { 2842 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed"); 2843 2844 // Commutative opcodes: it does not matter if AllowRHSConstant is set. 2845 if (Instruction::isCommutative(Opcode)) { 2846 switch (Opcode) { 2847 case Instruction::Add: // X + 0 = X 2848 case Instruction::Or: // X | 0 = X 2849 case Instruction::Xor: // X ^ 0 = X 2850 return Constant::getNullValue(Ty); 2851 case Instruction::Mul: // X * 1 = X 2852 return ConstantInt::get(Ty, 1); 2853 case Instruction::And: // X & -1 = X 2854 return Constant::getAllOnesValue(Ty); 2855 case Instruction::FAdd: // X + -0.0 = X 2856 return ConstantFP::getZero(Ty, !NSZ); 2857 case Instruction::FMul: // X * 1.0 = X 2858 return ConstantFP::get(Ty, 1.0); 2859 default: 2860 llvm_unreachable("Every commutative binop has an identity constant"); 2861 } 2862 } 2863 2864 // Non-commutative opcodes: AllowRHSConstant must be set. 2865 if (!AllowRHSConstant) 2866 return nullptr; 2867 2868 switch (Opcode) { 2869 case Instruction::Sub: // X - 0 = X 2870 case Instruction::Shl: // X << 0 = X 2871 case Instruction::LShr: // X >>u 0 = X 2872 case Instruction::AShr: // X >> 0 = X 2873 case Instruction::FSub: // X - 0.0 = X 2874 return Constant::getNullValue(Ty); 2875 case Instruction::SDiv: // X / 1 = X 2876 case Instruction::UDiv: // X /u 1 = X 2877 return ConstantInt::get(Ty, 1); 2878 case Instruction::FDiv: // X / 1.0 = X 2879 return ConstantFP::get(Ty, 1.0); 2880 default: 2881 return nullptr; 2882 } 2883 } 2884 2885 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) { 2886 switch (Opcode) { 2887 default: 2888 // Doesn't have an absorber. 2889 return nullptr; 2890 2891 case Instruction::Or: 2892 return Constant::getAllOnesValue(Ty); 2893 2894 case Instruction::And: 2895 case Instruction::Mul: 2896 return Constant::getNullValue(Ty); 2897 } 2898 } 2899 2900 /// Remove the constant from the constant table. 2901 void ConstantExpr::destroyConstantImpl() { 2902 getType()->getContext().pImpl->ExprConstants.remove(this); 2903 } 2904 2905 const char *ConstantExpr::getOpcodeName() const { 2906 return Instruction::getOpcodeName(getOpcode()); 2907 } 2908 2909 GetElementPtrConstantExpr::GetElementPtrConstantExpr( 2910 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy) 2911 : ConstantExpr(DestTy, Instruction::GetElementPtr, 2912 OperandTraits<GetElementPtrConstantExpr>::op_end(this) - 2913 (IdxList.size() + 1), 2914 IdxList.size() + 1), 2915 SrcElementTy(SrcElementTy), 2916 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) { 2917 Op<0>() = C; 2918 Use *OperandList = getOperandList(); 2919 for (unsigned i = 0, E = IdxList.size(); i != E; ++i) 2920 OperandList[i+1] = IdxList[i]; 2921 } 2922 2923 Type *GetElementPtrConstantExpr::getSourceElementType() const { 2924 return SrcElementTy; 2925 } 2926 2927 Type *GetElementPtrConstantExpr::getResultElementType() const { 2928 return ResElementTy; 2929 } 2930 2931 //===----------------------------------------------------------------------===// 2932 // ConstantData* implementations 2933 2934 Type *ConstantDataSequential::getElementType() const { 2935 if (ArrayType *ATy = dyn_cast<ArrayType>(getType())) 2936 return ATy->getElementType(); 2937 return cast<VectorType>(getType())->getElementType(); 2938 } 2939 2940 StringRef ConstantDataSequential::getRawDataValues() const { 2941 return StringRef(DataElements, getNumElements()*getElementByteSize()); 2942 } 2943 2944 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) { 2945 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy()) 2946 return true; 2947 if (auto *IT = dyn_cast<IntegerType>(Ty)) { 2948 switch (IT->getBitWidth()) { 2949 case 8: 2950 case 16: 2951 case 32: 2952 case 64: 2953 return true; 2954 default: break; 2955 } 2956 } 2957 return false; 2958 } 2959 2960 unsigned ConstantDataSequential::getNumElements() const { 2961 if (ArrayType *AT = dyn_cast<ArrayType>(getType())) 2962 return AT->getNumElements(); 2963 return cast<FixedVectorType>(getType())->getNumElements(); 2964 } 2965 2966 2967 uint64_t ConstantDataSequential::getElementByteSize() const { 2968 return getElementType()->getPrimitiveSizeInBits()/8; 2969 } 2970 2971 /// Return the start of the specified element. 2972 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const { 2973 assert(Elt < getNumElements() && "Invalid Elt"); 2974 return DataElements+Elt*getElementByteSize(); 2975 } 2976 2977 2978 /// Return true if the array is empty or all zeros. 2979 static bool isAllZeros(StringRef Arr) { 2980 for (char I : Arr) 2981 if (I != 0) 2982 return false; 2983 return true; 2984 } 2985 2986 /// This is the underlying implementation of all of the 2987 /// ConstantDataSequential::get methods. They all thunk down to here, providing 2988 /// the correct element type. We take the bytes in as a StringRef because 2989 /// we *want* an underlying "char*" to avoid TBAA type punning violations. 2990 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) { 2991 #ifndef NDEBUG 2992 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) 2993 assert(isElementTypeCompatible(ATy->getElementType())); 2994 else 2995 assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType())); 2996 #endif 2997 // If the elements are all zero or there are no elements, return a CAZ, which 2998 // is more dense and canonical. 2999 if (isAllZeros(Elements)) 3000 return ConstantAggregateZero::get(Ty); 3001 3002 // Do a lookup to see if we have already formed one of these. 3003 auto &Slot = 3004 *Ty->getContext() 3005 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr)) 3006 .first; 3007 3008 // The bucket can point to a linked list of different CDS's that have the same 3009 // body but different types. For example, 0,0,0,1 could be a 4 element array 3010 // of i8, or a 1-element array of i32. They'll both end up in the same 3011 /// StringMap bucket, linked up by their Next pointers. Walk the list. 3012 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second; 3013 for (; *Entry; Entry = &(*Entry)->Next) 3014 if ((*Entry)->getType() == Ty) 3015 return Entry->get(); 3016 3017 // Okay, we didn't get a hit. Create a node of the right class, link it in, 3018 // and return it. 3019 if (isa<ArrayType>(Ty)) { 3020 // Use reset because std::make_unique can't access the constructor. 3021 Entry->reset(new ConstantDataArray(Ty, Slot.first().data())); 3022 return Entry->get(); 3023 } 3024 3025 assert(isa<VectorType>(Ty)); 3026 // Use reset because std::make_unique can't access the constructor. 3027 Entry->reset(new ConstantDataVector(Ty, Slot.first().data())); 3028 return Entry->get(); 3029 } 3030 3031 void ConstantDataSequential::destroyConstantImpl() { 3032 // Remove the constant from the StringMap. 3033 StringMap<std::unique_ptr<ConstantDataSequential>> &CDSConstants = 3034 getType()->getContext().pImpl->CDSConstants; 3035 3036 auto Slot = CDSConstants.find(getRawDataValues()); 3037 3038 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table"); 3039 3040 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue(); 3041 3042 // Remove the entry from the hash table. 3043 if (!(*Entry)->Next) { 3044 // If there is only one value in the bucket (common case) it must be this 3045 // entry, and removing the entry should remove the bucket completely. 3046 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential"); 3047 getContext().pImpl->CDSConstants.erase(Slot); 3048 return; 3049 } 3050 3051 // Otherwise, there are multiple entries linked off the bucket, unlink the 3052 // node we care about but keep the bucket around. 3053 while (true) { 3054 std::unique_ptr<ConstantDataSequential> &Node = *Entry; 3055 assert(Node && "Didn't find entry in its uniquing hash table!"); 3056 // If we found our entry, unlink it from the list and we're done. 3057 if (Node.get() == this) { 3058 Node = std::move(Node->Next); 3059 return; 3060 } 3061 3062 Entry = &Node->Next; 3063 } 3064 } 3065 3066 /// getFP() constructors - Return a constant of array type with a float 3067 /// element type taken from argument `ElementType', and count taken from 3068 /// argument `Elts'. The amount of bits of the contained type must match the 3069 /// number of bits of the type contained in the passed in ArrayRef. 3070 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note 3071 /// that this can return a ConstantAggregateZero object. 3072 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint16_t> Elts) { 3073 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) && 3074 "Element type is not a 16-bit float type"); 3075 Type *Ty = ArrayType::get(ElementType, Elts.size()); 3076 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3077 return getImpl(StringRef(Data, Elts.size() * 2), Ty); 3078 } 3079 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint32_t> Elts) { 3080 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type"); 3081 Type *Ty = ArrayType::get(ElementType, Elts.size()); 3082 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3083 return getImpl(StringRef(Data, Elts.size() * 4), Ty); 3084 } 3085 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint64_t> Elts) { 3086 assert(ElementType->isDoubleTy() && 3087 "Element type is not a 64-bit float type"); 3088 Type *Ty = ArrayType::get(ElementType, Elts.size()); 3089 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3090 return getImpl(StringRef(Data, Elts.size() * 8), Ty); 3091 } 3092 3093 Constant *ConstantDataArray::getString(LLVMContext &Context, 3094 StringRef Str, bool AddNull) { 3095 if (!AddNull) { 3096 const uint8_t *Data = Str.bytes_begin(); 3097 return get(Context, makeArrayRef(Data, Str.size())); 3098 } 3099 3100 SmallVector<uint8_t, 64> ElementVals; 3101 ElementVals.append(Str.begin(), Str.end()); 3102 ElementVals.push_back(0); 3103 return get(Context, ElementVals); 3104 } 3105 3106 /// get() constructors - Return a constant with vector type with an element 3107 /// count and element type matching the ArrayRef passed in. Note that this 3108 /// can return a ConstantAggregateZero object. 3109 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){ 3110 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size()); 3111 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3112 return getImpl(StringRef(Data, Elts.size() * 1), Ty); 3113 } 3114 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){ 3115 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size()); 3116 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3117 return getImpl(StringRef(Data, Elts.size() * 2), Ty); 3118 } 3119 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){ 3120 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size()); 3121 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3122 return getImpl(StringRef(Data, Elts.size() * 4), Ty); 3123 } 3124 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){ 3125 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size()); 3126 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3127 return getImpl(StringRef(Data, Elts.size() * 8), Ty); 3128 } 3129 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) { 3130 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size()); 3131 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3132 return getImpl(StringRef(Data, Elts.size() * 4), Ty); 3133 } 3134 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) { 3135 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size()); 3136 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3137 return getImpl(StringRef(Data, Elts.size() * 8), Ty); 3138 } 3139 3140 /// getFP() constructors - Return a constant of vector type with a float 3141 /// element type taken from argument `ElementType', and count taken from 3142 /// argument `Elts'. The amount of bits of the contained type must match the 3143 /// number of bits of the type contained in the passed in ArrayRef. 3144 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note 3145 /// that this can return a ConstantAggregateZero object. 3146 Constant *ConstantDataVector::getFP(Type *ElementType, 3147 ArrayRef<uint16_t> Elts) { 3148 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) && 3149 "Element type is not a 16-bit float type"); 3150 auto *Ty = FixedVectorType::get(ElementType, Elts.size()); 3151 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3152 return getImpl(StringRef(Data, Elts.size() * 2), Ty); 3153 } 3154 Constant *ConstantDataVector::getFP(Type *ElementType, 3155 ArrayRef<uint32_t> Elts) { 3156 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type"); 3157 auto *Ty = FixedVectorType::get(ElementType, Elts.size()); 3158 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3159 return getImpl(StringRef(Data, Elts.size() * 4), Ty); 3160 } 3161 Constant *ConstantDataVector::getFP(Type *ElementType, 3162 ArrayRef<uint64_t> Elts) { 3163 assert(ElementType->isDoubleTy() && 3164 "Element type is not a 64-bit float type"); 3165 auto *Ty = FixedVectorType::get(ElementType, Elts.size()); 3166 const char *Data = reinterpret_cast<const char *>(Elts.data()); 3167 return getImpl(StringRef(Data, Elts.size() * 8), Ty); 3168 } 3169 3170 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) { 3171 assert(isElementTypeCompatible(V->getType()) && 3172 "Element type not compatible with ConstantData"); 3173 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 3174 if (CI->getType()->isIntegerTy(8)) { 3175 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue()); 3176 return get(V->getContext(), Elts); 3177 } 3178 if (CI->getType()->isIntegerTy(16)) { 3179 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue()); 3180 return get(V->getContext(), Elts); 3181 } 3182 if (CI->getType()->isIntegerTy(32)) { 3183 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue()); 3184 return get(V->getContext(), Elts); 3185 } 3186 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type"); 3187 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue()); 3188 return get(V->getContext(), Elts); 3189 } 3190 3191 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { 3192 if (CFP->getType()->isHalfTy()) { 3193 SmallVector<uint16_t, 16> Elts( 3194 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue()); 3195 return getFP(V->getType(), Elts); 3196 } 3197 if (CFP->getType()->isBFloatTy()) { 3198 SmallVector<uint16_t, 16> Elts( 3199 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue()); 3200 return getFP(V->getType(), Elts); 3201 } 3202 if (CFP->getType()->isFloatTy()) { 3203 SmallVector<uint32_t, 16> Elts( 3204 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue()); 3205 return getFP(V->getType(), Elts); 3206 } 3207 if (CFP->getType()->isDoubleTy()) { 3208 SmallVector<uint64_t, 16> Elts( 3209 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue()); 3210 return getFP(V->getType(), Elts); 3211 } 3212 } 3213 return ConstantVector::getSplat(ElementCount::getFixed(NumElts), V); 3214 } 3215 3216 3217 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const { 3218 assert(isa<IntegerType>(getElementType()) && 3219 "Accessor can only be used when element is an integer"); 3220 const char *EltPtr = getElementPointer(Elt); 3221 3222 // The data is stored in host byte order, make sure to cast back to the right 3223 // type to load with the right endianness. 3224 switch (getElementType()->getIntegerBitWidth()) { 3225 default: llvm_unreachable("Invalid bitwidth for CDS"); 3226 case 8: 3227 return *reinterpret_cast<const uint8_t *>(EltPtr); 3228 case 16: 3229 return *reinterpret_cast<const uint16_t *>(EltPtr); 3230 case 32: 3231 return *reinterpret_cast<const uint32_t *>(EltPtr); 3232 case 64: 3233 return *reinterpret_cast<const uint64_t *>(EltPtr); 3234 } 3235 } 3236 3237 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const { 3238 assert(isa<IntegerType>(getElementType()) && 3239 "Accessor can only be used when element is an integer"); 3240 const char *EltPtr = getElementPointer(Elt); 3241 3242 // The data is stored in host byte order, make sure to cast back to the right 3243 // type to load with the right endianness. 3244 switch (getElementType()->getIntegerBitWidth()) { 3245 default: llvm_unreachable("Invalid bitwidth for CDS"); 3246 case 8: { 3247 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr); 3248 return APInt(8, EltVal); 3249 } 3250 case 16: { 3251 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr); 3252 return APInt(16, EltVal); 3253 } 3254 case 32: { 3255 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr); 3256 return APInt(32, EltVal); 3257 } 3258 case 64: { 3259 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr); 3260 return APInt(64, EltVal); 3261 } 3262 } 3263 } 3264 3265 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const { 3266 const char *EltPtr = getElementPointer(Elt); 3267 3268 switch (getElementType()->getTypeID()) { 3269 default: 3270 llvm_unreachable("Accessor can only be used when element is float/double!"); 3271 case Type::HalfTyID: { 3272 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr); 3273 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal)); 3274 } 3275 case Type::BFloatTyID: { 3276 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr); 3277 return APFloat(APFloat::BFloat(), APInt(16, EltVal)); 3278 } 3279 case Type::FloatTyID: { 3280 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr); 3281 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal)); 3282 } 3283 case Type::DoubleTyID: { 3284 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr); 3285 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal)); 3286 } 3287 } 3288 } 3289 3290 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const { 3291 assert(getElementType()->isFloatTy() && 3292 "Accessor can only be used when element is a 'float'"); 3293 return *reinterpret_cast<const float *>(getElementPointer(Elt)); 3294 } 3295 3296 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const { 3297 assert(getElementType()->isDoubleTy() && 3298 "Accessor can only be used when element is a 'float'"); 3299 return *reinterpret_cast<const double *>(getElementPointer(Elt)); 3300 } 3301 3302 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const { 3303 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() || 3304 getElementType()->isFloatTy() || getElementType()->isDoubleTy()) 3305 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt)); 3306 3307 return ConstantInt::get(getElementType(), getElementAsInteger(Elt)); 3308 } 3309 3310 bool ConstantDataSequential::isString(unsigned CharSize) const { 3311 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize); 3312 } 3313 3314 bool ConstantDataSequential::isCString() const { 3315 if (!isString()) 3316 return false; 3317 3318 StringRef Str = getAsString(); 3319 3320 // The last value must be nul. 3321 if (Str.back() != 0) return false; 3322 3323 // Other elements must be non-nul. 3324 return !Str.drop_back().contains(0); 3325 } 3326 3327 bool ConstantDataVector::isSplatData() const { 3328 const char *Base = getRawDataValues().data(); 3329 3330 // Compare elements 1+ to the 0'th element. 3331 unsigned EltSize = getElementByteSize(); 3332 for (unsigned i = 1, e = getNumElements(); i != e; ++i) 3333 if (memcmp(Base, Base+i*EltSize, EltSize)) 3334 return false; 3335 3336 return true; 3337 } 3338 3339 bool ConstantDataVector::isSplat() const { 3340 if (!IsSplatSet) { 3341 IsSplatSet = true; 3342 IsSplat = isSplatData(); 3343 } 3344 return IsSplat; 3345 } 3346 3347 Constant *ConstantDataVector::getSplatValue() const { 3348 // If they're all the same, return the 0th one as a representative. 3349 return isSplat() ? getElementAsConstant(0) : nullptr; 3350 } 3351 3352 //===----------------------------------------------------------------------===// 3353 // handleOperandChange implementations 3354 3355 /// Update this constant array to change uses of 3356 /// 'From' to be uses of 'To'. This must update the uniquing data structures 3357 /// etc. 3358 /// 3359 /// Note that we intentionally replace all uses of From with To here. Consider 3360 /// a large array that uses 'From' 1000 times. By handling this case all here, 3361 /// ConstantArray::handleOperandChange is only invoked once, and that 3362 /// single invocation handles all 1000 uses. Handling them one at a time would 3363 /// work, but would be really slow because it would have to unique each updated 3364 /// array instance. 3365 /// 3366 void Constant::handleOperandChange(Value *From, Value *To) { 3367 Value *Replacement = nullptr; 3368 switch (getValueID()) { 3369 default: 3370 llvm_unreachable("Not a constant!"); 3371 #define HANDLE_CONSTANT(Name) \ 3372 case Value::Name##Val: \ 3373 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \ 3374 break; 3375 #include "llvm/IR/Value.def" 3376 } 3377 3378 // If handleOperandChangeImpl returned nullptr, then it handled 3379 // replacing itself and we don't want to delete or replace anything else here. 3380 if (!Replacement) 3381 return; 3382 3383 // I do need to replace this with an existing value. 3384 assert(Replacement != this && "I didn't contain From!"); 3385 3386 // Everyone using this now uses the replacement. 3387 replaceAllUsesWith(Replacement); 3388 3389 // Delete the old constant! 3390 destroyConstant(); 3391 } 3392 3393 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) { 3394 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 3395 Constant *ToC = cast<Constant>(To); 3396 3397 SmallVector<Constant*, 8> Values; 3398 Values.reserve(getNumOperands()); // Build replacement array. 3399 3400 // Fill values with the modified operands of the constant array. Also, 3401 // compute whether this turns into an all-zeros array. 3402 unsigned NumUpdated = 0; 3403 3404 // Keep track of whether all the values in the array are "ToC". 3405 bool AllSame = true; 3406 Use *OperandList = getOperandList(); 3407 unsigned OperandNo = 0; 3408 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) { 3409 Constant *Val = cast<Constant>(O->get()); 3410 if (Val == From) { 3411 OperandNo = (O - OperandList); 3412 Val = ToC; 3413 ++NumUpdated; 3414 } 3415 Values.push_back(Val); 3416 AllSame &= Val == ToC; 3417 } 3418 3419 if (AllSame && ToC->isNullValue()) 3420 return ConstantAggregateZero::get(getType()); 3421 3422 if (AllSame && isa<UndefValue>(ToC)) 3423 return UndefValue::get(getType()); 3424 3425 // Check for any other type of constant-folding. 3426 if (Constant *C = getImpl(getType(), Values)) 3427 return C; 3428 3429 // Update to the new value. 3430 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace( 3431 Values, this, From, ToC, NumUpdated, OperandNo); 3432 } 3433 3434 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) { 3435 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 3436 Constant *ToC = cast<Constant>(To); 3437 3438 Use *OperandList = getOperandList(); 3439 3440 SmallVector<Constant*, 8> Values; 3441 Values.reserve(getNumOperands()); // Build replacement struct. 3442 3443 // Fill values with the modified operands of the constant struct. Also, 3444 // compute whether this turns into an all-zeros struct. 3445 unsigned NumUpdated = 0; 3446 bool AllSame = true; 3447 unsigned OperandNo = 0; 3448 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) { 3449 Constant *Val = cast<Constant>(O->get()); 3450 if (Val == From) { 3451 OperandNo = (O - OperandList); 3452 Val = ToC; 3453 ++NumUpdated; 3454 } 3455 Values.push_back(Val); 3456 AllSame &= Val == ToC; 3457 } 3458 3459 if (AllSame && ToC->isNullValue()) 3460 return ConstantAggregateZero::get(getType()); 3461 3462 if (AllSame && isa<UndefValue>(ToC)) 3463 return UndefValue::get(getType()); 3464 3465 // Update to the new value. 3466 return getContext().pImpl->StructConstants.replaceOperandsInPlace( 3467 Values, this, From, ToC, NumUpdated, OperandNo); 3468 } 3469 3470 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) { 3471 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 3472 Constant *ToC = cast<Constant>(To); 3473 3474 SmallVector<Constant*, 8> Values; 3475 Values.reserve(getNumOperands()); // Build replacement array... 3476 unsigned NumUpdated = 0; 3477 unsigned OperandNo = 0; 3478 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 3479 Constant *Val = getOperand(i); 3480 if (Val == From) { 3481 OperandNo = i; 3482 ++NumUpdated; 3483 Val = ToC; 3484 } 3485 Values.push_back(Val); 3486 } 3487 3488 if (Constant *C = getImpl(Values)) 3489 return C; 3490 3491 // Update to the new value. 3492 return getContext().pImpl->VectorConstants.replaceOperandsInPlace( 3493 Values, this, From, ToC, NumUpdated, OperandNo); 3494 } 3495 3496 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) { 3497 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!"); 3498 Constant *To = cast<Constant>(ToV); 3499 3500 SmallVector<Constant*, 8> NewOps; 3501 unsigned NumUpdated = 0; 3502 unsigned OperandNo = 0; 3503 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 3504 Constant *Op = getOperand(i); 3505 if (Op == From) { 3506 OperandNo = i; 3507 ++NumUpdated; 3508 Op = To; 3509 } 3510 NewOps.push_back(Op); 3511 } 3512 assert(NumUpdated && "I didn't contain From!"); 3513 3514 if (Constant *C = getWithOperands(NewOps, getType(), true)) 3515 return C; 3516 3517 // Update to the new value. 3518 return getContext().pImpl->ExprConstants.replaceOperandsInPlace( 3519 NewOps, this, From, To, NumUpdated, OperandNo); 3520 } 3521 3522 Instruction *ConstantExpr::getAsInstruction(Instruction *InsertBefore) const { 3523 SmallVector<Value *, 4> ValueOperands(operands()); 3524 ArrayRef<Value*> Ops(ValueOperands); 3525 3526 switch (getOpcode()) { 3527 case Instruction::Trunc: 3528 case Instruction::ZExt: 3529 case Instruction::SExt: 3530 case Instruction::FPTrunc: 3531 case Instruction::FPExt: 3532 case Instruction::UIToFP: 3533 case Instruction::SIToFP: 3534 case Instruction::FPToUI: 3535 case Instruction::FPToSI: 3536 case Instruction::PtrToInt: 3537 case Instruction::IntToPtr: 3538 case Instruction::BitCast: 3539 case Instruction::AddrSpaceCast: 3540 return CastInst::Create((Instruction::CastOps)getOpcode(), Ops[0], 3541 getType(), "", InsertBefore); 3542 case Instruction::Select: 3543 return SelectInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore); 3544 case Instruction::InsertElement: 3545 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore); 3546 case Instruction::ExtractElement: 3547 return ExtractElementInst::Create(Ops[0], Ops[1], "", InsertBefore); 3548 case Instruction::InsertValue: 3549 return InsertValueInst::Create(Ops[0], Ops[1], getIndices(), "", 3550 InsertBefore); 3551 case Instruction::ExtractValue: 3552 return ExtractValueInst::Create(Ops[0], getIndices(), "", InsertBefore); 3553 case Instruction::ShuffleVector: 3554 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "", 3555 InsertBefore); 3556 3557 case Instruction::GetElementPtr: { 3558 const auto *GO = cast<GEPOperator>(this); 3559 if (GO->isInBounds()) 3560 return GetElementPtrInst::CreateInBounds( 3561 GO->getSourceElementType(), Ops[0], Ops.slice(1), "", InsertBefore); 3562 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0], 3563 Ops.slice(1), "", InsertBefore); 3564 } 3565 case Instruction::ICmp: 3566 case Instruction::FCmp: 3567 return CmpInst::Create((Instruction::OtherOps)getOpcode(), 3568 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1], 3569 "", InsertBefore); 3570 case Instruction::FNeg: 3571 return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0], "", 3572 InsertBefore); 3573 default: 3574 assert(getNumOperands() == 2 && "Must be binary operator?"); 3575 BinaryOperator *BO = BinaryOperator::Create( 3576 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "", InsertBefore); 3577 if (isa<OverflowingBinaryOperator>(BO)) { 3578 BO->setHasNoUnsignedWrap(SubclassOptionalData & 3579 OverflowingBinaryOperator::NoUnsignedWrap); 3580 BO->setHasNoSignedWrap(SubclassOptionalData & 3581 OverflowingBinaryOperator::NoSignedWrap); 3582 } 3583 if (isa<PossiblyExactOperator>(BO)) 3584 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact); 3585 return BO; 3586 } 3587 } 3588