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