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