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