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