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