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