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