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