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