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