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(CompositeType *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() == T->getTypeAtIndex(I) && 1062 "Initializer for composite element doesn't match!"); 1063 } 1064 1065 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V) 1066 : ConstantAggregate(T, ConstantArrayVal, V) { 1067 assert(V.size() == T->getNumElements() && 1068 "Invalid initializer for constant array"); 1069 } 1070 1071 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) { 1072 if (Constant *C = getImpl(Ty, V)) 1073 return C; 1074 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V); 1075 } 1076 1077 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) { 1078 // Empty arrays are canonicalized to ConstantAggregateZero. 1079 if (V.empty()) 1080 return ConstantAggregateZero::get(Ty); 1081 1082 for (unsigned i = 0, e = V.size(); i != e; ++i) { 1083 assert(V[i]->getType() == Ty->getElementType() && 1084 "Wrong type in array element initializer"); 1085 } 1086 1087 // If this is an all-zero array, return a ConstantAggregateZero object. If 1088 // all undef, return an UndefValue, if "all simple", then return a 1089 // ConstantDataArray. 1090 Constant *C = V[0]; 1091 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C)) 1092 return UndefValue::get(Ty); 1093 1094 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C)) 1095 return ConstantAggregateZero::get(Ty); 1096 1097 // Check to see if all of the elements are ConstantFP or ConstantInt and if 1098 // the element type is compatible with ConstantDataVector. If so, use it. 1099 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) 1100 return getSequenceIfElementsMatch<ConstantDataArray>(C, V); 1101 1102 // Otherwise, we really do want to create a ConstantArray. 1103 return nullptr; 1104 } 1105 1106 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context, 1107 ArrayRef<Constant*> V, 1108 bool Packed) { 1109 unsigned VecSize = V.size(); 1110 SmallVector<Type*, 16> EltTypes(VecSize); 1111 for (unsigned i = 0; i != VecSize; ++i) 1112 EltTypes[i] = V[i]->getType(); 1113 1114 return StructType::get(Context, EltTypes, Packed); 1115 } 1116 1117 1118 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V, 1119 bool Packed) { 1120 assert(!V.empty() && 1121 "ConstantStruct::getTypeForElements cannot be called on empty list"); 1122 return getTypeForElements(V[0]->getContext(), V, Packed); 1123 } 1124 1125 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V) 1126 : ConstantAggregate(T, ConstantStructVal, V) { 1127 assert((T->isOpaque() || V.size() == T->getNumElements()) && 1128 "Invalid initializer for constant struct"); 1129 } 1130 1131 // ConstantStruct accessors. 1132 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) { 1133 assert((ST->isOpaque() || ST->getNumElements() == V.size()) && 1134 "Incorrect # elements specified to ConstantStruct::get"); 1135 1136 // Create a ConstantAggregateZero value if all elements are zeros. 1137 bool isZero = true; 1138 bool isUndef = false; 1139 1140 if (!V.empty()) { 1141 isUndef = isa<UndefValue>(V[0]); 1142 isZero = V[0]->isNullValue(); 1143 if (isUndef || isZero) { 1144 for (unsigned i = 0, e = V.size(); i != e; ++i) { 1145 if (!V[i]->isNullValue()) 1146 isZero = false; 1147 if (!isa<UndefValue>(V[i])) 1148 isUndef = false; 1149 } 1150 } 1151 } 1152 if (isZero) 1153 return ConstantAggregateZero::get(ST); 1154 if (isUndef) 1155 return UndefValue::get(ST); 1156 1157 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V); 1158 } 1159 1160 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V) 1161 : ConstantAggregate(T, ConstantVectorVal, V) { 1162 assert(V.size() == T->getNumElements() && 1163 "Invalid initializer for constant vector"); 1164 } 1165 1166 // ConstantVector accessors. 1167 Constant *ConstantVector::get(ArrayRef<Constant*> V) { 1168 if (Constant *C = getImpl(V)) 1169 return C; 1170 VectorType *Ty = VectorType::get(V.front()->getType(), V.size()); 1171 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V); 1172 } 1173 1174 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) { 1175 assert(!V.empty() && "Vectors can't be empty"); 1176 VectorType *T = VectorType::get(V.front()->getType(), V.size()); 1177 1178 // If this is an all-undef or all-zero vector, return a 1179 // ConstantAggregateZero or UndefValue. 1180 Constant *C = V[0]; 1181 bool isZero = C->isNullValue(); 1182 bool isUndef = isa<UndefValue>(C); 1183 1184 if (isZero || isUndef) { 1185 for (unsigned i = 1, e = V.size(); i != e; ++i) 1186 if (V[i] != C) { 1187 isZero = isUndef = false; 1188 break; 1189 } 1190 } 1191 1192 if (isZero) 1193 return ConstantAggregateZero::get(T); 1194 if (isUndef) 1195 return UndefValue::get(T); 1196 1197 // Check to see if all of the elements are ConstantFP or ConstantInt and if 1198 // the element type is compatible with ConstantDataVector. If so, use it. 1199 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) 1200 return getSequenceIfElementsMatch<ConstantDataVector>(C, V); 1201 1202 // Otherwise, the element type isn't compatible with ConstantDataVector, or 1203 // the operand list contains a ConstantExpr or something else strange. 1204 return nullptr; 1205 } 1206 1207 Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) { 1208 if (!EC.Scalable) { 1209 // If this splat is compatible with ConstantDataVector, use it instead of 1210 // ConstantVector. 1211 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) && 1212 ConstantDataSequential::isElementTypeCompatible(V->getType())) 1213 return ConstantDataVector::getSplat(EC.Min, V); 1214 1215 SmallVector<Constant *, 32> Elts(EC.Min, V); 1216 return get(Elts); 1217 } 1218 1219 Type *VTy = VectorType::get(V->getType(), EC); 1220 1221 if (V->isNullValue()) 1222 return ConstantAggregateZero::get(VTy); 1223 else if (isa<UndefValue>(V)) 1224 return UndefValue::get(VTy); 1225 1226 Type *I32Ty = Type::getInt32Ty(VTy->getContext()); 1227 1228 // Move scalar into vector. 1229 Constant *UndefV = UndefValue::get(VTy); 1230 V = ConstantExpr::getInsertElement(UndefV, V, ConstantInt::get(I32Ty, 0)); 1231 // Build shuffle mask to perform the splat. 1232 Type *MaskTy = VectorType::get(I32Ty, EC); 1233 Constant *Zeros = ConstantAggregateZero::get(MaskTy); 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 Constant * 1301 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const { 1302 assert(Op->getType() == getOperand(OpNo)->getType() && 1303 "Replacing operand with value of different type!"); 1304 if (getOperand(OpNo) == Op) 1305 return const_cast<ConstantExpr*>(this); 1306 1307 SmallVector<Constant*, 8> NewOps; 1308 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 1309 NewOps.push_back(i == OpNo ? Op : getOperand(i)); 1310 1311 return getWithOperands(NewOps); 1312 } 1313 1314 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty, 1315 bool OnlyIfReduced, Type *SrcTy) const { 1316 assert(Ops.size() == getNumOperands() && "Operand count mismatch!"); 1317 1318 // If no operands changed return self. 1319 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin())) 1320 return const_cast<ConstantExpr*>(this); 1321 1322 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr; 1323 switch (getOpcode()) { 1324 case Instruction::Trunc: 1325 case Instruction::ZExt: 1326 case Instruction::SExt: 1327 case Instruction::FPTrunc: 1328 case Instruction::FPExt: 1329 case Instruction::UIToFP: 1330 case Instruction::SIToFP: 1331 case Instruction::FPToUI: 1332 case Instruction::FPToSI: 1333 case Instruction::PtrToInt: 1334 case Instruction::IntToPtr: 1335 case Instruction::BitCast: 1336 case Instruction::AddrSpaceCast: 1337 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced); 1338 case Instruction::Select: 1339 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy); 1340 case Instruction::InsertElement: 1341 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2], 1342 OnlyIfReducedTy); 1343 case Instruction::ExtractElement: 1344 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy); 1345 case Instruction::InsertValue: 1346 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(), 1347 OnlyIfReducedTy); 1348 case Instruction::ExtractValue: 1349 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy); 1350 case Instruction::ShuffleVector: 1351 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2], 1352 OnlyIfReducedTy); 1353 case Instruction::GetElementPtr: { 1354 auto *GEPO = cast<GEPOperator>(this); 1355 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType())); 1356 return ConstantExpr::getGetElementPtr( 1357 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1), 1358 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy); 1359 } 1360 case Instruction::ICmp: 1361 case Instruction::FCmp: 1362 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1], 1363 OnlyIfReducedTy); 1364 default: 1365 assert(getNumOperands() == 2 && "Must be binary operator?"); 1366 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData, 1367 OnlyIfReducedTy); 1368 } 1369 } 1370 1371 1372 //===----------------------------------------------------------------------===// 1373 // isValueValidForType implementations 1374 1375 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) { 1376 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay 1377 if (Ty->isIntegerTy(1)) 1378 return Val == 0 || Val == 1; 1379 return isUIntN(NumBits, Val); 1380 } 1381 1382 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) { 1383 unsigned NumBits = Ty->getIntegerBitWidth(); 1384 if (Ty->isIntegerTy(1)) 1385 return Val == 0 || Val == 1 || Val == -1; 1386 return isIntN(NumBits, Val); 1387 } 1388 1389 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) { 1390 // convert modifies in place, so make a copy. 1391 APFloat Val2 = APFloat(Val); 1392 bool losesInfo; 1393 switch (Ty->getTypeID()) { 1394 default: 1395 return false; // These can't be represented as floating point! 1396 1397 // FIXME rounding mode needs to be more flexible 1398 case Type::HalfTyID: { 1399 if (&Val2.getSemantics() == &APFloat::IEEEhalf()) 1400 return true; 1401 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo); 1402 return !losesInfo; 1403 } 1404 case Type::FloatTyID: { 1405 if (&Val2.getSemantics() == &APFloat::IEEEsingle()) 1406 return true; 1407 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo); 1408 return !losesInfo; 1409 } 1410 case Type::DoubleTyID: { 1411 if (&Val2.getSemantics() == &APFloat::IEEEhalf() || 1412 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1413 &Val2.getSemantics() == &APFloat::IEEEdouble()) 1414 return true; 1415 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo); 1416 return !losesInfo; 1417 } 1418 case Type::X86_FP80TyID: 1419 return &Val2.getSemantics() == &APFloat::IEEEhalf() || 1420 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1421 &Val2.getSemantics() == &APFloat::IEEEdouble() || 1422 &Val2.getSemantics() == &APFloat::x87DoubleExtended(); 1423 case Type::FP128TyID: 1424 return &Val2.getSemantics() == &APFloat::IEEEhalf() || 1425 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1426 &Val2.getSemantics() == &APFloat::IEEEdouble() || 1427 &Val2.getSemantics() == &APFloat::IEEEquad(); 1428 case Type::PPC_FP128TyID: 1429 return &Val2.getSemantics() == &APFloat::IEEEhalf() || 1430 &Val2.getSemantics() == &APFloat::IEEEsingle() || 1431 &Val2.getSemantics() == &APFloat::IEEEdouble() || 1432 &Val2.getSemantics() == &APFloat::PPCDoubleDouble(); 1433 } 1434 } 1435 1436 1437 //===----------------------------------------------------------------------===// 1438 // Factory Function Implementation 1439 1440 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) { 1441 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) && 1442 "Cannot create an aggregate zero of non-aggregate type!"); 1443 1444 std::unique_ptr<ConstantAggregateZero> &Entry = 1445 Ty->getContext().pImpl->CAZConstants[Ty]; 1446 if (!Entry) 1447 Entry.reset(new ConstantAggregateZero(Ty)); 1448 1449 return Entry.get(); 1450 } 1451 1452 /// Remove the constant from the constant table. 1453 void ConstantAggregateZero::destroyConstantImpl() { 1454 getContext().pImpl->CAZConstants.erase(getType()); 1455 } 1456 1457 /// Remove the constant from the constant table. 1458 void ConstantArray::destroyConstantImpl() { 1459 getType()->getContext().pImpl->ArrayConstants.remove(this); 1460 } 1461 1462 1463 //---- ConstantStruct::get() implementation... 1464 // 1465 1466 /// Remove the constant from the constant table. 1467 void ConstantStruct::destroyConstantImpl() { 1468 getType()->getContext().pImpl->StructConstants.remove(this); 1469 } 1470 1471 /// Remove the constant from the constant table. 1472 void ConstantVector::destroyConstantImpl() { 1473 getType()->getContext().pImpl->VectorConstants.remove(this); 1474 } 1475 1476 Constant *Constant::getSplatValue(bool AllowUndefs) const { 1477 assert(this->getType()->isVectorTy() && "Only valid for vectors!"); 1478 if (isa<ConstantAggregateZero>(this)) 1479 return getNullValue(this->getType()->getVectorElementType()); 1480 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) 1481 return CV->getSplatValue(); 1482 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) 1483 return CV->getSplatValue(AllowUndefs); 1484 return nullptr; 1485 } 1486 1487 Constant *ConstantVector::getSplatValue(bool AllowUndefs) const { 1488 // Check out first element. 1489 Constant *Elt = getOperand(0); 1490 // Then make sure all remaining elements point to the same value. 1491 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) { 1492 Constant *OpC = getOperand(I); 1493 if (OpC == Elt) 1494 continue; 1495 1496 // Strict mode: any mismatch is not a splat. 1497 if (!AllowUndefs) 1498 return nullptr; 1499 1500 // Allow undefs mode: ignore undefined elements. 1501 if (isa<UndefValue>(OpC)) 1502 continue; 1503 1504 // If we do not have a defined element yet, use the current operand. 1505 if (isa<UndefValue>(Elt)) 1506 Elt = OpC; 1507 1508 if (OpC != Elt) 1509 return nullptr; 1510 } 1511 return Elt; 1512 } 1513 1514 const APInt &Constant::getUniqueInteger() const { 1515 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 1516 return CI->getValue(); 1517 assert(this->getSplatValue() && "Doesn't contain a unique integer!"); 1518 const Constant *C = this->getAggregateElement(0U); 1519 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!"); 1520 return cast<ConstantInt>(C)->getValue(); 1521 } 1522 1523 //---- ConstantPointerNull::get() implementation. 1524 // 1525 1526 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) { 1527 std::unique_ptr<ConstantPointerNull> &Entry = 1528 Ty->getContext().pImpl->CPNConstants[Ty]; 1529 if (!Entry) 1530 Entry.reset(new ConstantPointerNull(Ty)); 1531 1532 return Entry.get(); 1533 } 1534 1535 /// Remove the constant from the constant table. 1536 void ConstantPointerNull::destroyConstantImpl() { 1537 getContext().pImpl->CPNConstants.erase(getType()); 1538 } 1539 1540 UndefValue *UndefValue::get(Type *Ty) { 1541 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty]; 1542 if (!Entry) 1543 Entry.reset(new UndefValue(Ty)); 1544 1545 return Entry.get(); 1546 } 1547 1548 /// Remove the constant from the constant table. 1549 void UndefValue::destroyConstantImpl() { 1550 // Free the constant and any dangling references to it. 1551 getContext().pImpl->UVConstants.erase(getType()); 1552 } 1553 1554 BlockAddress *BlockAddress::get(BasicBlock *BB) { 1555 assert(BB->getParent() && "Block must have a parent"); 1556 return get(BB->getParent(), BB); 1557 } 1558 1559 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) { 1560 BlockAddress *&BA = 1561 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)]; 1562 if (!BA) 1563 BA = new BlockAddress(F, BB); 1564 1565 assert(BA->getFunction() == F && "Basic block moved between functions"); 1566 return BA; 1567 } 1568 1569 BlockAddress::BlockAddress(Function *F, BasicBlock *BB) 1570 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal, 1571 &Op<0>(), 2) { 1572 setOperand(0, F); 1573 setOperand(1, BB); 1574 BB->AdjustBlockAddressRefCount(1); 1575 } 1576 1577 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) { 1578 if (!BB->hasAddressTaken()) 1579 return nullptr; 1580 1581 const Function *F = BB->getParent(); 1582 assert(F && "Block must have a parent"); 1583 BlockAddress *BA = 1584 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB)); 1585 assert(BA && "Refcount and block address map disagree!"); 1586 return BA; 1587 } 1588 1589 /// Remove the constant from the constant table. 1590 void BlockAddress::destroyConstantImpl() { 1591 getFunction()->getType()->getContext().pImpl 1592 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock())); 1593 getBasicBlock()->AdjustBlockAddressRefCount(-1); 1594 } 1595 1596 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) { 1597 // This could be replacing either the Basic Block or the Function. In either 1598 // case, we have to remove the map entry. 1599 Function *NewF = getFunction(); 1600 BasicBlock *NewBB = getBasicBlock(); 1601 1602 if (From == NewF) 1603 NewF = cast<Function>(To->stripPointerCasts()); 1604 else { 1605 assert(From == NewBB && "From does not match any operand"); 1606 NewBB = cast<BasicBlock>(To); 1607 } 1608 1609 // See if the 'new' entry already exists, if not, just update this in place 1610 // and return early. 1611 BlockAddress *&NewBA = 1612 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)]; 1613 if (NewBA) 1614 return NewBA; 1615 1616 getBasicBlock()->AdjustBlockAddressRefCount(-1); 1617 1618 // Remove the old entry, this can't cause the map to rehash (just a 1619 // tombstone will get added). 1620 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(), 1621 getBasicBlock())); 1622 NewBA = this; 1623 setOperand(0, NewF); 1624 setOperand(1, NewBB); 1625 getBasicBlock()->AdjustBlockAddressRefCount(1); 1626 1627 // If we just want to keep the existing value, then return null. 1628 // Callers know that this means we shouldn't delete this value. 1629 return nullptr; 1630 } 1631 1632 //---- ConstantExpr::get() implementations. 1633 // 1634 1635 /// This is a utility function to handle folding of casts and lookup of the 1636 /// cast in the ExprConstants map. It is used by the various get* methods below. 1637 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty, 1638 bool OnlyIfReduced = false) { 1639 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!"); 1640 // Fold a few common cases 1641 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty)) 1642 return FC; 1643 1644 if (OnlyIfReduced) 1645 return nullptr; 1646 1647 LLVMContextImpl *pImpl = Ty->getContext().pImpl; 1648 1649 // Look up the constant in the table first to ensure uniqueness. 1650 ConstantExprKeyType Key(opc, C); 1651 1652 return pImpl->ExprConstants.getOrCreate(Ty, Key); 1653 } 1654 1655 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty, 1656 bool OnlyIfReduced) { 1657 Instruction::CastOps opc = Instruction::CastOps(oc); 1658 assert(Instruction::isCast(opc) && "opcode out of range"); 1659 assert(C && Ty && "Null arguments to getCast"); 1660 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!"); 1661 1662 switch (opc) { 1663 default: 1664 llvm_unreachable("Invalid cast opcode"); 1665 case Instruction::Trunc: 1666 return getTrunc(C, Ty, OnlyIfReduced); 1667 case Instruction::ZExt: 1668 return getZExt(C, Ty, OnlyIfReduced); 1669 case Instruction::SExt: 1670 return getSExt(C, Ty, OnlyIfReduced); 1671 case Instruction::FPTrunc: 1672 return getFPTrunc(C, Ty, OnlyIfReduced); 1673 case Instruction::FPExt: 1674 return getFPExtend(C, Ty, OnlyIfReduced); 1675 case Instruction::UIToFP: 1676 return getUIToFP(C, Ty, OnlyIfReduced); 1677 case Instruction::SIToFP: 1678 return getSIToFP(C, Ty, OnlyIfReduced); 1679 case Instruction::FPToUI: 1680 return getFPToUI(C, Ty, OnlyIfReduced); 1681 case Instruction::FPToSI: 1682 return getFPToSI(C, Ty, OnlyIfReduced); 1683 case Instruction::PtrToInt: 1684 return getPtrToInt(C, Ty, OnlyIfReduced); 1685 case Instruction::IntToPtr: 1686 return getIntToPtr(C, Ty, OnlyIfReduced); 1687 case Instruction::BitCast: 1688 return getBitCast(C, Ty, OnlyIfReduced); 1689 case Instruction::AddrSpaceCast: 1690 return getAddrSpaceCast(C, Ty, OnlyIfReduced); 1691 } 1692 } 1693 1694 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) { 1695 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 1696 return getBitCast(C, Ty); 1697 return getZExt(C, Ty); 1698 } 1699 1700 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) { 1701 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 1702 return getBitCast(C, Ty); 1703 return getSExt(C, Ty); 1704 } 1705 1706 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) { 1707 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 1708 return getBitCast(C, Ty); 1709 return getTrunc(C, Ty); 1710 } 1711 1712 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) { 1713 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 1714 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 1715 "Invalid cast"); 1716 1717 if (Ty->isIntOrIntVectorTy()) 1718 return getPtrToInt(S, Ty); 1719 1720 unsigned SrcAS = S->getType()->getPointerAddressSpace(); 1721 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace()) 1722 return getAddrSpaceCast(S, Ty); 1723 1724 return getBitCast(S, Ty); 1725 } 1726 1727 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S, 1728 Type *Ty) { 1729 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 1730 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 1731 1732 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 1733 return getAddrSpaceCast(S, Ty); 1734 1735 return getBitCast(S, Ty); 1736 } 1737 1738 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) { 1739 assert(C->getType()->isIntOrIntVectorTy() && 1740 Ty->isIntOrIntVectorTy() && "Invalid cast"); 1741 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 1742 unsigned DstBits = Ty->getScalarSizeInBits(); 1743 Instruction::CastOps opcode = 1744 (SrcBits == DstBits ? Instruction::BitCast : 1745 (SrcBits > DstBits ? Instruction::Trunc : 1746 (isSigned ? Instruction::SExt : Instruction::ZExt))); 1747 return getCast(opcode, C, Ty); 1748 } 1749 1750 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) { 1751 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 1752 "Invalid cast"); 1753 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 1754 unsigned DstBits = Ty->getScalarSizeInBits(); 1755 if (SrcBits == DstBits) 1756 return C; // Avoid a useless cast 1757 Instruction::CastOps opcode = 1758 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt); 1759 return getCast(opcode, C, Ty); 1760 } 1761 1762 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) { 1763 #ifndef NDEBUG 1764 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1765 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1766 #endif 1767 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1768 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer"); 1769 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral"); 1770 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&& 1771 "SrcTy must be larger than DestTy for Trunc!"); 1772 1773 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced); 1774 } 1775 1776 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) { 1777 #ifndef NDEBUG 1778 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1779 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1780 #endif 1781 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1782 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral"); 1783 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer"); 1784 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 1785 "SrcTy must be smaller than DestTy for SExt!"); 1786 1787 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced); 1788 } 1789 1790 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) { 1791 #ifndef NDEBUG 1792 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1793 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1794 #endif 1795 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1796 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral"); 1797 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer"); 1798 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 1799 "SrcTy must be smaller than DestTy for ZExt!"); 1800 1801 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced); 1802 } 1803 1804 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) { 1805 #ifndef NDEBUG 1806 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1807 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1808 #endif 1809 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1810 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 1811 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&& 1812 "This is an illegal floating point truncation!"); 1813 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced); 1814 } 1815 1816 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) { 1817 #ifndef NDEBUG 1818 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1819 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1820 #endif 1821 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1822 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 1823 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 1824 "This is an illegal floating point extension!"); 1825 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced); 1826 } 1827 1828 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) { 1829 #ifndef NDEBUG 1830 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1831 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1832 #endif 1833 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1834 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() && 1835 "This is an illegal uint to floating point cast!"); 1836 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced); 1837 } 1838 1839 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) { 1840 #ifndef NDEBUG 1841 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1842 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1843 #endif 1844 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1845 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() && 1846 "This is an illegal sint to floating point cast!"); 1847 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced); 1848 } 1849 1850 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) { 1851 #ifndef NDEBUG 1852 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1853 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1854 #endif 1855 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1856 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() && 1857 "This is an illegal floating point to uint cast!"); 1858 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced); 1859 } 1860 1861 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) { 1862 #ifndef NDEBUG 1863 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 1864 bool toVec = Ty->getTypeID() == Type::VectorTyID; 1865 #endif 1866 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 1867 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() && 1868 "This is an illegal floating point to sint cast!"); 1869 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced); 1870 } 1871 1872 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy, 1873 bool OnlyIfReduced) { 1874 assert(C->getType()->isPtrOrPtrVectorTy() && 1875 "PtrToInt source must be pointer or pointer vector"); 1876 assert(DstTy->isIntOrIntVectorTy() && 1877 "PtrToInt destination must be integer or integer vector"); 1878 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy)); 1879 if (isa<VectorType>(C->getType())) 1880 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&& 1881 "Invalid cast between a different number of vector elements"); 1882 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced); 1883 } 1884 1885 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy, 1886 bool OnlyIfReduced) { 1887 assert(C->getType()->isIntOrIntVectorTy() && 1888 "IntToPtr source must be integer or integer vector"); 1889 assert(DstTy->isPtrOrPtrVectorTy() && 1890 "IntToPtr destination must be a pointer or pointer vector"); 1891 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy)); 1892 if (isa<VectorType>(C->getType())) 1893 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&& 1894 "Invalid cast between a different number of vector elements"); 1895 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced); 1896 } 1897 1898 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy, 1899 bool OnlyIfReduced) { 1900 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) && 1901 "Invalid constantexpr bitcast!"); 1902 1903 // It is common to ask for a bitcast of a value to its own type, handle this 1904 // speedily. 1905 if (C->getType() == DstTy) return C; 1906 1907 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced); 1908 } 1909 1910 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy, 1911 bool OnlyIfReduced) { 1912 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) && 1913 "Invalid constantexpr addrspacecast!"); 1914 1915 // Canonicalize addrspacecasts between different pointer types by first 1916 // bitcasting the pointer type and then converting the address space. 1917 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType()); 1918 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType()); 1919 Type *DstElemTy = DstScalarTy->getElementType(); 1920 if (SrcScalarTy->getElementType() != DstElemTy) { 1921 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace()); 1922 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) { 1923 // Handle vectors of pointers. 1924 MidTy = VectorType::get(MidTy, VT->getNumElements()); 1925 } 1926 C = getBitCast(C, MidTy); 1927 } 1928 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced); 1929 } 1930 1931 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags, 1932 Type *OnlyIfReducedTy) { 1933 // Check the operands for consistency first. 1934 assert(Instruction::isUnaryOp(Opcode) && 1935 "Invalid opcode in unary constant expression"); 1936 1937 #ifndef NDEBUG 1938 switch (Opcode) { 1939 case Instruction::FNeg: 1940 assert(C->getType()->isFPOrFPVectorTy() && 1941 "Tried to create a floating-point operation on a " 1942 "non-floating-point type!"); 1943 break; 1944 default: 1945 break; 1946 } 1947 #endif 1948 1949 if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C)) 1950 return FC; 1951 1952 if (OnlyIfReducedTy == C->getType()) 1953 return nullptr; 1954 1955 Constant *ArgVec[] = { C }; 1956 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags); 1957 1958 LLVMContextImpl *pImpl = C->getContext().pImpl; 1959 return pImpl->ExprConstants.getOrCreate(C->getType(), Key); 1960 } 1961 1962 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2, 1963 unsigned Flags, Type *OnlyIfReducedTy) { 1964 // Check the operands for consistency first. 1965 assert(Instruction::isBinaryOp(Opcode) && 1966 "Invalid opcode in binary constant expression"); 1967 assert(C1->getType() == C2->getType() && 1968 "Operand types in binary constant expression should match"); 1969 1970 #ifndef NDEBUG 1971 switch (Opcode) { 1972 case Instruction::Add: 1973 case Instruction::Sub: 1974 case Instruction::Mul: 1975 case Instruction::UDiv: 1976 case Instruction::SDiv: 1977 case Instruction::URem: 1978 case Instruction::SRem: 1979 assert(C1->getType()->isIntOrIntVectorTy() && 1980 "Tried to create an integer operation on a non-integer type!"); 1981 break; 1982 case Instruction::FAdd: 1983 case Instruction::FSub: 1984 case Instruction::FMul: 1985 case Instruction::FDiv: 1986 case Instruction::FRem: 1987 assert(C1->getType()->isFPOrFPVectorTy() && 1988 "Tried to create a floating-point operation on a " 1989 "non-floating-point type!"); 1990 break; 1991 case Instruction::And: 1992 case Instruction::Or: 1993 case Instruction::Xor: 1994 assert(C1->getType()->isIntOrIntVectorTy() && 1995 "Tried to create a logical operation on a non-integral type!"); 1996 break; 1997 case Instruction::Shl: 1998 case Instruction::LShr: 1999 case Instruction::AShr: 2000 assert(C1->getType()->isIntOrIntVectorTy() && 2001 "Tried to create a shift operation on a non-integer type!"); 2002 break; 2003 default: 2004 break; 2005 } 2006 #endif 2007 2008 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2)) 2009 return FC; 2010 2011 if (OnlyIfReducedTy == C1->getType()) 2012 return nullptr; 2013 2014 Constant *ArgVec[] = { C1, C2 }; 2015 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags); 2016 2017 LLVMContextImpl *pImpl = C1->getContext().pImpl; 2018 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key); 2019 } 2020 2021 Constant *ConstantExpr::getSizeOf(Type* Ty) { 2022 // sizeof is implemented as: (i64) gep (Ty*)null, 1 2023 // Note that a non-inbounds gep is used, as null isn't within any object. 2024 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); 2025 Constant *GEP = getGetElementPtr( 2026 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx); 2027 return getPtrToInt(GEP, 2028 Type::getInt64Ty(Ty->getContext())); 2029 } 2030 2031 Constant *ConstantExpr::getAlignOf(Type* Ty) { 2032 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1 2033 // Note that a non-inbounds gep is used, as null isn't within any object. 2034 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty); 2035 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0)); 2036 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0); 2037 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); 2038 Constant *Indices[2] = { Zero, One }; 2039 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices); 2040 return getPtrToInt(GEP, 2041 Type::getInt64Ty(Ty->getContext())); 2042 } 2043 2044 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) { 2045 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()), 2046 FieldNo)); 2047 } 2048 2049 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) { 2050 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo 2051 // Note that a non-inbounds gep is used, as null isn't within any object. 2052 Constant *GEPIdx[] = { 2053 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0), 2054 FieldNo 2055 }; 2056 Constant *GEP = getGetElementPtr( 2057 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx); 2058 return getPtrToInt(GEP, 2059 Type::getInt64Ty(Ty->getContext())); 2060 } 2061 2062 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1, 2063 Constant *C2, bool OnlyIfReduced) { 2064 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 2065 2066 switch (Predicate) { 2067 default: llvm_unreachable("Invalid CmpInst predicate"); 2068 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT: 2069 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE: 2070 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO: 2071 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE: 2072 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE: 2073 case CmpInst::FCMP_TRUE: 2074 return getFCmp(Predicate, C1, C2, OnlyIfReduced); 2075 2076 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT: 2077 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE: 2078 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT: 2079 case CmpInst::ICMP_SLE: 2080 return getICmp(Predicate, C1, C2, OnlyIfReduced); 2081 } 2082 } 2083 2084 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2, 2085 Type *OnlyIfReducedTy) { 2086 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands"); 2087 2088 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2)) 2089 return SC; // Fold common cases 2090 2091 if (OnlyIfReducedTy == V1->getType()) 2092 return nullptr; 2093 2094 Constant *ArgVec[] = { C, V1, V2 }; 2095 ConstantExprKeyType Key(Instruction::Select, ArgVec); 2096 2097 LLVMContextImpl *pImpl = C->getContext().pImpl; 2098 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key); 2099 } 2100 2101 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C, 2102 ArrayRef<Value *> Idxs, bool InBounds, 2103 Optional<unsigned> InRangeIndex, 2104 Type *OnlyIfReducedTy) { 2105 if (!Ty) 2106 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType(); 2107 else 2108 assert(Ty == 2109 cast<PointerType>(C->getType()->getScalarType())->getElementType()); 2110 2111 if (Constant *FC = 2112 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs)) 2113 return FC; // Fold a few common cases. 2114 2115 // Get the result type of the getelementptr! 2116 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs); 2117 assert(DestTy && "GEP indices invalid!"); 2118 unsigned AS = C->getType()->getPointerAddressSpace(); 2119 Type *ReqTy = DestTy->getPointerTo(AS); 2120 2121 ElementCount EltCount = {0, false}; 2122 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType())) 2123 EltCount = VecTy->getElementCount(); 2124 else 2125 for (auto Idx : Idxs) 2126 if (VectorType *VecTy = dyn_cast<VectorType>(Idx->getType())) 2127 EltCount = VecTy->getElementCount(); 2128 2129 if (EltCount.Min != 0) 2130 ReqTy = VectorType::get(ReqTy, EltCount); 2131 2132 if (OnlyIfReducedTy == ReqTy) 2133 return nullptr; 2134 2135 // Look up the constant in the table first to ensure uniqueness 2136 std::vector<Constant*> ArgVec; 2137 ArgVec.reserve(1 + Idxs.size()); 2138 ArgVec.push_back(C); 2139 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) { 2140 assert((!Idxs[i]->getType()->isVectorTy() || 2141 Idxs[i]->getType()->getVectorElementCount() == EltCount) && 2142 "getelementptr index type missmatch"); 2143 2144 Constant *Idx = cast<Constant>(Idxs[i]); 2145 if (EltCount.Min != 0 && !Idxs[i]->getType()->isVectorTy()) 2146 Idx = ConstantVector::getSplat(EltCount, Idx); 2147 ArgVec.push_back(Idx); 2148 } 2149 2150 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0; 2151 if (InRangeIndex && *InRangeIndex < 63) 2152 SubClassOptionalData |= (*InRangeIndex + 1) << 1; 2153 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0, 2154 SubClassOptionalData, None, Ty); 2155 2156 LLVMContextImpl *pImpl = C->getContext().pImpl; 2157 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 2158 } 2159 2160 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS, 2161 Constant *RHS, bool OnlyIfReduced) { 2162 assert(LHS->getType() == RHS->getType()); 2163 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) && 2164 "Invalid ICmp Predicate"); 2165 2166 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS)) 2167 return FC; // Fold a few common cases... 2168 2169 if (OnlyIfReduced) 2170 return nullptr; 2171 2172 // Look up the constant in the table first to ensure uniqueness 2173 Constant *ArgVec[] = { LHS, RHS }; 2174 // Get the key type with both the opcode and predicate 2175 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred); 2176 2177 Type *ResultTy = Type::getInt1Ty(LHS->getContext()); 2178 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType())) 2179 ResultTy = VectorType::get(ResultTy, VT->getElementCount()); 2180 2181 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; 2182 return pImpl->ExprConstants.getOrCreate(ResultTy, Key); 2183 } 2184 2185 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, 2186 Constant *RHS, bool OnlyIfReduced) { 2187 assert(LHS->getType() == RHS->getType()); 2188 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) && 2189 "Invalid FCmp Predicate"); 2190 2191 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS)) 2192 return FC; // Fold a few common cases... 2193 2194 if (OnlyIfReduced) 2195 return nullptr; 2196 2197 // Look up the constant in the table first to ensure uniqueness 2198 Constant *ArgVec[] = { LHS, RHS }; 2199 // Get the key type with both the opcode and predicate 2200 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred); 2201 2202 Type *ResultTy = Type::getInt1Ty(LHS->getContext()); 2203 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType())) 2204 ResultTy = VectorType::get(ResultTy, VT->getElementCount()); 2205 2206 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; 2207 return pImpl->ExprConstants.getOrCreate(ResultTy, Key); 2208 } 2209 2210 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx, 2211 Type *OnlyIfReducedTy) { 2212 assert(Val->getType()->isVectorTy() && 2213 "Tried to create extractelement operation on non-vector type!"); 2214 assert(Idx->getType()->isIntegerTy() && 2215 "Extractelement index must be an integer type!"); 2216 2217 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx)) 2218 return FC; // Fold a few common cases. 2219 2220 Type *ReqTy = Val->getType()->getVectorElementType(); 2221 if (OnlyIfReducedTy == ReqTy) 2222 return nullptr; 2223 2224 // Look up the constant in the table first to ensure uniqueness 2225 Constant *ArgVec[] = { Val, Idx }; 2226 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec); 2227 2228 LLVMContextImpl *pImpl = Val->getContext().pImpl; 2229 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 2230 } 2231 2232 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 2233 Constant *Idx, Type *OnlyIfReducedTy) { 2234 assert(Val->getType()->isVectorTy() && 2235 "Tried to create insertelement operation on non-vector type!"); 2236 assert(Elt->getType() == Val->getType()->getVectorElementType() && 2237 "Insertelement types must match!"); 2238 assert(Idx->getType()->isIntegerTy() && 2239 "Insertelement index must be i32 type!"); 2240 2241 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx)) 2242 return FC; // Fold a few common cases. 2243 2244 if (OnlyIfReducedTy == Val->getType()) 2245 return nullptr; 2246 2247 // Look up the constant in the table first to ensure uniqueness 2248 Constant *ArgVec[] = { Val, Elt, Idx }; 2249 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec); 2250 2251 LLVMContextImpl *pImpl = Val->getContext().pImpl; 2252 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key); 2253 } 2254 2255 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 2256 Constant *Mask, Type *OnlyIfReducedTy) { 2257 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) && 2258 "Invalid shuffle vector constant expr operands!"); 2259 2260 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask)) 2261 return FC; // Fold a few common cases. 2262 2263 ElementCount NElts = Mask->getType()->getVectorElementCount(); 2264 Type *EltTy = V1->getType()->getVectorElementType(); 2265 Type *ShufTy = VectorType::get(EltTy, NElts); 2266 2267 if (OnlyIfReducedTy == ShufTy) 2268 return nullptr; 2269 2270 // Look up the constant in the table first to ensure uniqueness 2271 Constant *ArgVec[] = { V1, V2, Mask }; 2272 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec); 2273 2274 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl; 2275 return pImpl->ExprConstants.getOrCreate(ShufTy, Key); 2276 } 2277 2278 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val, 2279 ArrayRef<unsigned> Idxs, 2280 Type *OnlyIfReducedTy) { 2281 assert(Agg->getType()->isFirstClassType() && 2282 "Non-first-class type for constant insertvalue expression"); 2283 2284 assert(ExtractValueInst::getIndexedType(Agg->getType(), 2285 Idxs) == Val->getType() && 2286 "insertvalue indices invalid!"); 2287 Type *ReqTy = Val->getType(); 2288 2289 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs)) 2290 return FC; 2291 2292 if (OnlyIfReducedTy == ReqTy) 2293 return nullptr; 2294 2295 Constant *ArgVec[] = { Agg, Val }; 2296 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs); 2297 2298 LLVMContextImpl *pImpl = Agg->getContext().pImpl; 2299 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 2300 } 2301 2302 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs, 2303 Type *OnlyIfReducedTy) { 2304 assert(Agg->getType()->isFirstClassType() && 2305 "Tried to create extractelement operation on non-first-class type!"); 2306 2307 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs); 2308 (void)ReqTy; 2309 assert(ReqTy && "extractvalue indices invalid!"); 2310 2311 assert(Agg->getType()->isFirstClassType() && 2312 "Non-first-class type for constant extractvalue expression"); 2313 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs)) 2314 return FC; 2315 2316 if (OnlyIfReducedTy == ReqTy) 2317 return nullptr; 2318 2319 Constant *ArgVec[] = { Agg }; 2320 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs); 2321 2322 LLVMContextImpl *pImpl = Agg->getContext().pImpl; 2323 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 2324 } 2325 2326 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) { 2327 assert(C->getType()->isIntOrIntVectorTy() && 2328 "Cannot NEG a nonintegral value!"); 2329 return getSub(ConstantFP::getZeroValueForNegation(C->getType()), 2330 C, HasNUW, HasNSW); 2331 } 2332 2333 Constant *ConstantExpr::getFNeg(Constant *C) { 2334 assert(C->getType()->isFPOrFPVectorTy() && 2335 "Cannot FNEG a non-floating-point value!"); 2336 return get(Instruction::FNeg, C); 2337 } 2338 2339 Constant *ConstantExpr::getNot(Constant *C) { 2340 assert(C->getType()->isIntOrIntVectorTy() && 2341 "Cannot NOT a nonintegral value!"); 2342 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType())); 2343 } 2344 2345 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2, 2346 bool HasNUW, bool HasNSW) { 2347 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 2348 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 2349 return get(Instruction::Add, C1, C2, Flags); 2350 } 2351 2352 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) { 2353 return get(Instruction::FAdd, C1, C2); 2354 } 2355 2356 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2, 2357 bool HasNUW, bool HasNSW) { 2358 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 2359 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 2360 return get(Instruction::Sub, C1, C2, Flags); 2361 } 2362 2363 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) { 2364 return get(Instruction::FSub, C1, C2); 2365 } 2366 2367 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2, 2368 bool HasNUW, bool HasNSW) { 2369 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 2370 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 2371 return get(Instruction::Mul, C1, C2, Flags); 2372 } 2373 2374 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) { 2375 return get(Instruction::FMul, C1, C2); 2376 } 2377 2378 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) { 2379 return get(Instruction::UDiv, C1, C2, 2380 isExact ? PossiblyExactOperator::IsExact : 0); 2381 } 2382 2383 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) { 2384 return get(Instruction::SDiv, C1, C2, 2385 isExact ? PossiblyExactOperator::IsExact : 0); 2386 } 2387 2388 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) { 2389 return get(Instruction::FDiv, C1, C2); 2390 } 2391 2392 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) { 2393 return get(Instruction::URem, C1, C2); 2394 } 2395 2396 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) { 2397 return get(Instruction::SRem, C1, C2); 2398 } 2399 2400 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) { 2401 return get(Instruction::FRem, C1, C2); 2402 } 2403 2404 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) { 2405 return get(Instruction::And, C1, C2); 2406 } 2407 2408 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) { 2409 return get(Instruction::Or, C1, C2); 2410 } 2411 2412 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) { 2413 return get(Instruction::Xor, C1, C2); 2414 } 2415 2416 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2, 2417 bool HasNUW, bool HasNSW) { 2418 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 2419 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 2420 return get(Instruction::Shl, C1, C2, Flags); 2421 } 2422 2423 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) { 2424 return get(Instruction::LShr, C1, C2, 2425 isExact ? PossiblyExactOperator::IsExact : 0); 2426 } 2427 2428 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) { 2429 return get(Instruction::AShr, C1, C2, 2430 isExact ? PossiblyExactOperator::IsExact : 0); 2431 } 2432 2433 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty, 2434 bool AllowRHSConstant) { 2435 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed"); 2436 2437 // Commutative opcodes: it does not matter if AllowRHSConstant is set. 2438 if (Instruction::isCommutative(Opcode)) { 2439 switch (Opcode) { 2440 case Instruction::Add: // X + 0 = X 2441 case Instruction::Or: // X | 0 = X 2442 case Instruction::Xor: // X ^ 0 = X 2443 return Constant::getNullValue(Ty); 2444 case Instruction::Mul: // X * 1 = X 2445 return ConstantInt::get(Ty, 1); 2446 case Instruction::And: // X & -1 = X 2447 return Constant::getAllOnesValue(Ty); 2448 case Instruction::FAdd: // X + -0.0 = X 2449 // TODO: If the fadd has 'nsz', should we return +0.0? 2450 return ConstantFP::getNegativeZero(Ty); 2451 case Instruction::FMul: // X * 1.0 = X 2452 return ConstantFP::get(Ty, 1.0); 2453 default: 2454 llvm_unreachable("Every commutative binop has an identity constant"); 2455 } 2456 } 2457 2458 // Non-commutative opcodes: AllowRHSConstant must be set. 2459 if (!AllowRHSConstant) 2460 return nullptr; 2461 2462 switch (Opcode) { 2463 case Instruction::Sub: // X - 0 = X 2464 case Instruction::Shl: // X << 0 = X 2465 case Instruction::LShr: // X >>u 0 = X 2466 case Instruction::AShr: // X >> 0 = X 2467 case Instruction::FSub: // X - 0.0 = X 2468 return Constant::getNullValue(Ty); 2469 case Instruction::SDiv: // X / 1 = X 2470 case Instruction::UDiv: // X /u 1 = X 2471 return ConstantInt::get(Ty, 1); 2472 case Instruction::FDiv: // X / 1.0 = X 2473 return ConstantFP::get(Ty, 1.0); 2474 default: 2475 return nullptr; 2476 } 2477 } 2478 2479 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) { 2480 switch (Opcode) { 2481 default: 2482 // Doesn't have an absorber. 2483 return nullptr; 2484 2485 case Instruction::Or: 2486 return Constant::getAllOnesValue(Ty); 2487 2488 case Instruction::And: 2489 case Instruction::Mul: 2490 return Constant::getNullValue(Ty); 2491 } 2492 } 2493 2494 /// Remove the constant from the constant table. 2495 void ConstantExpr::destroyConstantImpl() { 2496 getType()->getContext().pImpl->ExprConstants.remove(this); 2497 } 2498 2499 const char *ConstantExpr::getOpcodeName() const { 2500 return Instruction::getOpcodeName(getOpcode()); 2501 } 2502 2503 GetElementPtrConstantExpr::GetElementPtrConstantExpr( 2504 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy) 2505 : ConstantExpr(DestTy, Instruction::GetElementPtr, 2506 OperandTraits<GetElementPtrConstantExpr>::op_end(this) - 2507 (IdxList.size() + 1), 2508 IdxList.size() + 1), 2509 SrcElementTy(SrcElementTy), 2510 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) { 2511 Op<0>() = C; 2512 Use *OperandList = getOperandList(); 2513 for (unsigned i = 0, E = IdxList.size(); i != E; ++i) 2514 OperandList[i+1] = IdxList[i]; 2515 } 2516 2517 Type *GetElementPtrConstantExpr::getSourceElementType() const { 2518 return SrcElementTy; 2519 } 2520 2521 Type *GetElementPtrConstantExpr::getResultElementType() const { 2522 return ResElementTy; 2523 } 2524 2525 //===----------------------------------------------------------------------===// 2526 // ConstantData* implementations 2527 2528 Type *ConstantDataSequential::getElementType() const { 2529 return getType()->getElementType(); 2530 } 2531 2532 StringRef ConstantDataSequential::getRawDataValues() const { 2533 return StringRef(DataElements, getNumElements()*getElementByteSize()); 2534 } 2535 2536 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) { 2537 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true; 2538 if (auto *IT = dyn_cast<IntegerType>(Ty)) { 2539 switch (IT->getBitWidth()) { 2540 case 8: 2541 case 16: 2542 case 32: 2543 case 64: 2544 return true; 2545 default: break; 2546 } 2547 } 2548 return false; 2549 } 2550 2551 unsigned ConstantDataSequential::getNumElements() const { 2552 if (ArrayType *AT = dyn_cast<ArrayType>(getType())) 2553 return AT->getNumElements(); 2554 return getType()->getVectorNumElements(); 2555 } 2556 2557 2558 uint64_t ConstantDataSequential::getElementByteSize() const { 2559 return getElementType()->getPrimitiveSizeInBits()/8; 2560 } 2561 2562 /// Return the start of the specified element. 2563 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const { 2564 assert(Elt < getNumElements() && "Invalid Elt"); 2565 return DataElements+Elt*getElementByteSize(); 2566 } 2567 2568 2569 /// Return true if the array is empty or all zeros. 2570 static bool isAllZeros(StringRef Arr) { 2571 for (char I : Arr) 2572 if (I != 0) 2573 return false; 2574 return true; 2575 } 2576 2577 /// This is the underlying implementation of all of the 2578 /// ConstantDataSequential::get methods. They all thunk down to here, providing 2579 /// the correct element type. We take the bytes in as a StringRef because 2580 /// we *want* an underlying "char*" to avoid TBAA type punning violations. 2581 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) { 2582 assert(isElementTypeCompatible(Ty->getSequentialElementType())); 2583 // If the elements are all zero or there are no elements, return a CAZ, which 2584 // is more dense and canonical. 2585 if (isAllZeros(Elements)) 2586 return ConstantAggregateZero::get(Ty); 2587 2588 // Do a lookup to see if we have already formed one of these. 2589 auto &Slot = 2590 *Ty->getContext() 2591 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr)) 2592 .first; 2593 2594 // The bucket can point to a linked list of different CDS's that have the same 2595 // body but different types. For example, 0,0,0,1 could be a 4 element array 2596 // of i8, or a 1-element array of i32. They'll both end up in the same 2597 /// StringMap bucket, linked up by their Next pointers. Walk the list. 2598 ConstantDataSequential **Entry = &Slot.second; 2599 for (ConstantDataSequential *Node = *Entry; Node; 2600 Entry = &Node->Next, Node = *Entry) 2601 if (Node->getType() == Ty) 2602 return Node; 2603 2604 // Okay, we didn't get a hit. Create a node of the right class, link it in, 2605 // and return it. 2606 if (isa<ArrayType>(Ty)) 2607 return *Entry = new ConstantDataArray(Ty, Slot.first().data()); 2608 2609 assert(isa<VectorType>(Ty)); 2610 return *Entry = new ConstantDataVector(Ty, Slot.first().data()); 2611 } 2612 2613 void ConstantDataSequential::destroyConstantImpl() { 2614 // Remove the constant from the StringMap. 2615 StringMap<ConstantDataSequential*> &CDSConstants = 2616 getType()->getContext().pImpl->CDSConstants; 2617 2618 StringMap<ConstantDataSequential*>::iterator Slot = 2619 CDSConstants.find(getRawDataValues()); 2620 2621 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table"); 2622 2623 ConstantDataSequential **Entry = &Slot->getValue(); 2624 2625 // Remove the entry from the hash table. 2626 if (!(*Entry)->Next) { 2627 // If there is only one value in the bucket (common case) it must be this 2628 // entry, and removing the entry should remove the bucket completely. 2629 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential"); 2630 getContext().pImpl->CDSConstants.erase(Slot); 2631 } else { 2632 // Otherwise, there are multiple entries linked off the bucket, unlink the 2633 // node we care about but keep the bucket around. 2634 for (ConstantDataSequential *Node = *Entry; ; 2635 Entry = &Node->Next, Node = *Entry) { 2636 assert(Node && "Didn't find entry in its uniquing hash table!"); 2637 // If we found our entry, unlink it from the list and we're done. 2638 if (Node == this) { 2639 *Entry = Node->Next; 2640 break; 2641 } 2642 } 2643 } 2644 2645 // If we were part of a list, make sure that we don't delete the list that is 2646 // still owned by the uniquing map. 2647 Next = nullptr; 2648 } 2649 2650 /// getFP() constructors - Return a constant with array type with an element 2651 /// count and element type of float with precision matching the number of 2652 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits, 2653 /// double for 64bits) Note that this can return a ConstantAggregateZero 2654 /// object. 2655 Constant *ConstantDataArray::getFP(LLVMContext &Context, 2656 ArrayRef<uint16_t> Elts) { 2657 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size()); 2658 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2659 return getImpl(StringRef(Data, Elts.size() * 2), Ty); 2660 } 2661 Constant *ConstantDataArray::getFP(LLVMContext &Context, 2662 ArrayRef<uint32_t> Elts) { 2663 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size()); 2664 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2665 return getImpl(StringRef(Data, Elts.size() * 4), Ty); 2666 } 2667 Constant *ConstantDataArray::getFP(LLVMContext &Context, 2668 ArrayRef<uint64_t> Elts) { 2669 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size()); 2670 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2671 return getImpl(StringRef(Data, Elts.size() * 8), Ty); 2672 } 2673 2674 Constant *ConstantDataArray::getString(LLVMContext &Context, 2675 StringRef Str, bool AddNull) { 2676 if (!AddNull) { 2677 const uint8_t *Data = Str.bytes_begin(); 2678 return get(Context, makeArrayRef(Data, Str.size())); 2679 } 2680 2681 SmallVector<uint8_t, 64> ElementVals; 2682 ElementVals.append(Str.begin(), Str.end()); 2683 ElementVals.push_back(0); 2684 return get(Context, ElementVals); 2685 } 2686 2687 /// get() constructors - Return a constant with vector type with an element 2688 /// count and element type matching the ArrayRef passed in. Note that this 2689 /// can return a ConstantAggregateZero object. 2690 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){ 2691 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size()); 2692 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2693 return getImpl(StringRef(Data, Elts.size() * 1), Ty); 2694 } 2695 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){ 2696 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size()); 2697 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2698 return getImpl(StringRef(Data, Elts.size() * 2), Ty); 2699 } 2700 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){ 2701 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size()); 2702 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2703 return getImpl(StringRef(Data, Elts.size() * 4), Ty); 2704 } 2705 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){ 2706 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size()); 2707 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2708 return getImpl(StringRef(Data, Elts.size() * 8), Ty); 2709 } 2710 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) { 2711 Type *Ty = VectorType::get(Type::getFloatTy(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<double> Elts) { 2716 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size()); 2717 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2718 return getImpl(StringRef(Data, Elts.size() * 8), Ty); 2719 } 2720 2721 /// getFP() constructors - Return a constant with vector type with an element 2722 /// count and element type of float with the precision matching the number of 2723 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits, 2724 /// double for 64bits) Note that this can return a ConstantAggregateZero 2725 /// object. 2726 Constant *ConstantDataVector::getFP(LLVMContext &Context, 2727 ArrayRef<uint16_t> Elts) { 2728 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size()); 2729 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2730 return getImpl(StringRef(Data, Elts.size() * 2), Ty); 2731 } 2732 Constant *ConstantDataVector::getFP(LLVMContext &Context, 2733 ArrayRef<uint32_t> Elts) { 2734 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size()); 2735 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2736 return getImpl(StringRef(Data, Elts.size() * 4), Ty); 2737 } 2738 Constant *ConstantDataVector::getFP(LLVMContext &Context, 2739 ArrayRef<uint64_t> Elts) { 2740 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size()); 2741 const char *Data = reinterpret_cast<const char *>(Elts.data()); 2742 return getImpl(StringRef(Data, Elts.size() * 8), Ty); 2743 } 2744 2745 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) { 2746 assert(isElementTypeCompatible(V->getType()) && 2747 "Element type not compatible with ConstantData"); 2748 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 2749 if (CI->getType()->isIntegerTy(8)) { 2750 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue()); 2751 return get(V->getContext(), Elts); 2752 } 2753 if (CI->getType()->isIntegerTy(16)) { 2754 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue()); 2755 return get(V->getContext(), Elts); 2756 } 2757 if (CI->getType()->isIntegerTy(32)) { 2758 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue()); 2759 return get(V->getContext(), Elts); 2760 } 2761 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type"); 2762 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue()); 2763 return get(V->getContext(), Elts); 2764 } 2765 2766 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { 2767 if (CFP->getType()->isHalfTy()) { 2768 SmallVector<uint16_t, 16> Elts( 2769 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue()); 2770 return getFP(V->getContext(), Elts); 2771 } 2772 if (CFP->getType()->isFloatTy()) { 2773 SmallVector<uint32_t, 16> Elts( 2774 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue()); 2775 return getFP(V->getContext(), Elts); 2776 } 2777 if (CFP->getType()->isDoubleTy()) { 2778 SmallVector<uint64_t, 16> Elts( 2779 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue()); 2780 return getFP(V->getContext(), Elts); 2781 } 2782 } 2783 return ConstantVector::getSplat({NumElts, false}, V); 2784 } 2785 2786 2787 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const { 2788 assert(isa<IntegerType>(getElementType()) && 2789 "Accessor can only be used when element is an integer"); 2790 const char *EltPtr = getElementPointer(Elt); 2791 2792 // The data is stored in host byte order, make sure to cast back to the right 2793 // type to load with the right endianness. 2794 switch (getElementType()->getIntegerBitWidth()) { 2795 default: llvm_unreachable("Invalid bitwidth for CDS"); 2796 case 8: 2797 return *reinterpret_cast<const uint8_t *>(EltPtr); 2798 case 16: 2799 return *reinterpret_cast<const uint16_t *>(EltPtr); 2800 case 32: 2801 return *reinterpret_cast<const uint32_t *>(EltPtr); 2802 case 64: 2803 return *reinterpret_cast<const uint64_t *>(EltPtr); 2804 } 2805 } 2806 2807 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const { 2808 assert(isa<IntegerType>(getElementType()) && 2809 "Accessor can only be used when element is an integer"); 2810 const char *EltPtr = getElementPointer(Elt); 2811 2812 // The data is stored in host byte order, make sure to cast back to the right 2813 // type to load with the right endianness. 2814 switch (getElementType()->getIntegerBitWidth()) { 2815 default: llvm_unreachable("Invalid bitwidth for CDS"); 2816 case 8: { 2817 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr); 2818 return APInt(8, EltVal); 2819 } 2820 case 16: { 2821 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr); 2822 return APInt(16, EltVal); 2823 } 2824 case 32: { 2825 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr); 2826 return APInt(32, EltVal); 2827 } 2828 case 64: { 2829 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr); 2830 return APInt(64, EltVal); 2831 } 2832 } 2833 } 2834 2835 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const { 2836 const char *EltPtr = getElementPointer(Elt); 2837 2838 switch (getElementType()->getTypeID()) { 2839 default: 2840 llvm_unreachable("Accessor can only be used when element is float/double!"); 2841 case Type::HalfTyID: { 2842 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr); 2843 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal)); 2844 } 2845 case Type::FloatTyID: { 2846 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr); 2847 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal)); 2848 } 2849 case Type::DoubleTyID: { 2850 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr); 2851 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal)); 2852 } 2853 } 2854 } 2855 2856 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const { 2857 assert(getElementType()->isFloatTy() && 2858 "Accessor can only be used when element is a 'float'"); 2859 return *reinterpret_cast<const float *>(getElementPointer(Elt)); 2860 } 2861 2862 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const { 2863 assert(getElementType()->isDoubleTy() && 2864 "Accessor can only be used when element is a 'float'"); 2865 return *reinterpret_cast<const double *>(getElementPointer(Elt)); 2866 } 2867 2868 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const { 2869 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() || 2870 getElementType()->isDoubleTy()) 2871 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt)); 2872 2873 return ConstantInt::get(getElementType(), getElementAsInteger(Elt)); 2874 } 2875 2876 bool ConstantDataSequential::isString(unsigned CharSize) const { 2877 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize); 2878 } 2879 2880 bool ConstantDataSequential::isCString() const { 2881 if (!isString()) 2882 return false; 2883 2884 StringRef Str = getAsString(); 2885 2886 // The last value must be nul. 2887 if (Str.back() != 0) return false; 2888 2889 // Other elements must be non-nul. 2890 return Str.drop_back().find(0) == StringRef::npos; 2891 } 2892 2893 bool ConstantDataVector::isSplat() const { 2894 const char *Base = getRawDataValues().data(); 2895 2896 // Compare elements 1+ to the 0'th element. 2897 unsigned EltSize = getElementByteSize(); 2898 for (unsigned i = 1, e = getNumElements(); i != e; ++i) 2899 if (memcmp(Base, Base+i*EltSize, EltSize)) 2900 return false; 2901 2902 return true; 2903 } 2904 2905 Constant *ConstantDataVector::getSplatValue() const { 2906 // If they're all the same, return the 0th one as a representative. 2907 return isSplat() ? getElementAsConstant(0) : nullptr; 2908 } 2909 2910 //===----------------------------------------------------------------------===// 2911 // handleOperandChange implementations 2912 2913 /// Update this constant array to change uses of 2914 /// 'From' to be uses of 'To'. This must update the uniquing data structures 2915 /// etc. 2916 /// 2917 /// Note that we intentionally replace all uses of From with To here. Consider 2918 /// a large array that uses 'From' 1000 times. By handling this case all here, 2919 /// ConstantArray::handleOperandChange is only invoked once, and that 2920 /// single invocation handles all 1000 uses. Handling them one at a time would 2921 /// work, but would be really slow because it would have to unique each updated 2922 /// array instance. 2923 /// 2924 void Constant::handleOperandChange(Value *From, Value *To) { 2925 Value *Replacement = nullptr; 2926 switch (getValueID()) { 2927 default: 2928 llvm_unreachable("Not a constant!"); 2929 #define HANDLE_CONSTANT(Name) \ 2930 case Value::Name##Val: \ 2931 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \ 2932 break; 2933 #include "llvm/IR/Value.def" 2934 } 2935 2936 // If handleOperandChangeImpl returned nullptr, then it handled 2937 // replacing itself and we don't want to delete or replace anything else here. 2938 if (!Replacement) 2939 return; 2940 2941 // I do need to replace this with an existing value. 2942 assert(Replacement != this && "I didn't contain From!"); 2943 2944 // Everyone using this now uses the replacement. 2945 replaceAllUsesWith(Replacement); 2946 2947 // Delete the old constant! 2948 destroyConstant(); 2949 } 2950 2951 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) { 2952 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 2953 Constant *ToC = cast<Constant>(To); 2954 2955 SmallVector<Constant*, 8> Values; 2956 Values.reserve(getNumOperands()); // Build replacement array. 2957 2958 // Fill values with the modified operands of the constant array. Also, 2959 // compute whether this turns into an all-zeros array. 2960 unsigned NumUpdated = 0; 2961 2962 // Keep track of whether all the values in the array are "ToC". 2963 bool AllSame = true; 2964 Use *OperandList = getOperandList(); 2965 unsigned OperandNo = 0; 2966 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) { 2967 Constant *Val = cast<Constant>(O->get()); 2968 if (Val == From) { 2969 OperandNo = (O - OperandList); 2970 Val = ToC; 2971 ++NumUpdated; 2972 } 2973 Values.push_back(Val); 2974 AllSame &= Val == ToC; 2975 } 2976 2977 if (AllSame && ToC->isNullValue()) 2978 return ConstantAggregateZero::get(getType()); 2979 2980 if (AllSame && isa<UndefValue>(ToC)) 2981 return UndefValue::get(getType()); 2982 2983 // Check for any other type of constant-folding. 2984 if (Constant *C = getImpl(getType(), Values)) 2985 return C; 2986 2987 // Update to the new value. 2988 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace( 2989 Values, this, From, ToC, NumUpdated, OperandNo); 2990 } 2991 2992 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) { 2993 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 2994 Constant *ToC = cast<Constant>(To); 2995 2996 Use *OperandList = getOperandList(); 2997 2998 SmallVector<Constant*, 8> Values; 2999 Values.reserve(getNumOperands()); // Build replacement struct. 3000 3001 // Fill values with the modified operands of the constant struct. Also, 3002 // compute whether this turns into an all-zeros struct. 3003 unsigned NumUpdated = 0; 3004 bool AllSame = true; 3005 unsigned OperandNo = 0; 3006 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) { 3007 Constant *Val = cast<Constant>(O->get()); 3008 if (Val == From) { 3009 OperandNo = (O - OperandList); 3010 Val = ToC; 3011 ++NumUpdated; 3012 } 3013 Values.push_back(Val); 3014 AllSame &= Val == ToC; 3015 } 3016 3017 if (AllSame && ToC->isNullValue()) 3018 return ConstantAggregateZero::get(getType()); 3019 3020 if (AllSame && isa<UndefValue>(ToC)) 3021 return UndefValue::get(getType()); 3022 3023 // Update to the new value. 3024 return getContext().pImpl->StructConstants.replaceOperandsInPlace( 3025 Values, this, From, ToC, NumUpdated, OperandNo); 3026 } 3027 3028 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) { 3029 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 3030 Constant *ToC = cast<Constant>(To); 3031 3032 SmallVector<Constant*, 8> Values; 3033 Values.reserve(getNumOperands()); // Build replacement array... 3034 unsigned NumUpdated = 0; 3035 unsigned OperandNo = 0; 3036 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 3037 Constant *Val = getOperand(i); 3038 if (Val == From) { 3039 OperandNo = i; 3040 ++NumUpdated; 3041 Val = ToC; 3042 } 3043 Values.push_back(Val); 3044 } 3045 3046 if (Constant *C = getImpl(Values)) 3047 return C; 3048 3049 // Update to the new value. 3050 return getContext().pImpl->VectorConstants.replaceOperandsInPlace( 3051 Values, this, From, ToC, NumUpdated, OperandNo); 3052 } 3053 3054 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) { 3055 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!"); 3056 Constant *To = cast<Constant>(ToV); 3057 3058 SmallVector<Constant*, 8> NewOps; 3059 unsigned NumUpdated = 0; 3060 unsigned OperandNo = 0; 3061 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 3062 Constant *Op = getOperand(i); 3063 if (Op == From) { 3064 OperandNo = i; 3065 ++NumUpdated; 3066 Op = To; 3067 } 3068 NewOps.push_back(Op); 3069 } 3070 assert(NumUpdated && "I didn't contain From!"); 3071 3072 if (Constant *C = getWithOperands(NewOps, getType(), true)) 3073 return C; 3074 3075 // Update to the new value. 3076 return getContext().pImpl->ExprConstants.replaceOperandsInPlace( 3077 NewOps, this, From, To, NumUpdated, OperandNo); 3078 } 3079 3080 Instruction *ConstantExpr::getAsInstruction() const { 3081 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end()); 3082 ArrayRef<Value*> Ops(ValueOperands); 3083 3084 switch (getOpcode()) { 3085 case Instruction::Trunc: 3086 case Instruction::ZExt: 3087 case Instruction::SExt: 3088 case Instruction::FPTrunc: 3089 case Instruction::FPExt: 3090 case Instruction::UIToFP: 3091 case Instruction::SIToFP: 3092 case Instruction::FPToUI: 3093 case Instruction::FPToSI: 3094 case Instruction::PtrToInt: 3095 case Instruction::IntToPtr: 3096 case Instruction::BitCast: 3097 case Instruction::AddrSpaceCast: 3098 return CastInst::Create((Instruction::CastOps)getOpcode(), 3099 Ops[0], getType()); 3100 case Instruction::Select: 3101 return SelectInst::Create(Ops[0], Ops[1], Ops[2]); 3102 case Instruction::InsertElement: 3103 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]); 3104 case Instruction::ExtractElement: 3105 return ExtractElementInst::Create(Ops[0], Ops[1]); 3106 case Instruction::InsertValue: 3107 return InsertValueInst::Create(Ops[0], Ops[1], getIndices()); 3108 case Instruction::ExtractValue: 3109 return ExtractValueInst::Create(Ops[0], getIndices()); 3110 case Instruction::ShuffleVector: 3111 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]); 3112 3113 case Instruction::GetElementPtr: { 3114 const auto *GO = cast<GEPOperator>(this); 3115 if (GO->isInBounds()) 3116 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(), 3117 Ops[0], Ops.slice(1)); 3118 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0], 3119 Ops.slice(1)); 3120 } 3121 case Instruction::ICmp: 3122 case Instruction::FCmp: 3123 return CmpInst::Create((Instruction::OtherOps)getOpcode(), 3124 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]); 3125 case Instruction::FNeg: 3126 return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0]); 3127 default: 3128 assert(getNumOperands() == 2 && "Must be binary operator?"); 3129 BinaryOperator *BO = 3130 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(), 3131 Ops[0], Ops[1]); 3132 if (isa<OverflowingBinaryOperator>(BO)) { 3133 BO->setHasNoUnsignedWrap(SubclassOptionalData & 3134 OverflowingBinaryOperator::NoUnsignedWrap); 3135 BO->setHasNoSignedWrap(SubclassOptionalData & 3136 OverflowingBinaryOperator::NoSignedWrap); 3137 } 3138 if (isa<PossiblyExactOperator>(BO)) 3139 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact); 3140 return BO; 3141 } 3142 } 3143