1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements all of the non-inline methods for the LLVM instruction 10 // classes. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/Instructions.h" 15 #include "LLVMContextImpl.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/IR/Attributes.h" 20 #include "llvm/IR/BasicBlock.h" 21 #include "llvm/IR/Constant.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/IR/InstrTypes.h" 27 #include "llvm/IR/Instruction.h" 28 #include "llvm/IR/Intrinsics.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/MDBuilder.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/Operator.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/Support/AtomicOrdering.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/TypeSize.h" 41 #include <algorithm> 42 #include <cassert> 43 #include <cstdint> 44 #include <vector> 45 46 using namespace llvm; 47 48 //===----------------------------------------------------------------------===// 49 // AllocaInst Class 50 //===----------------------------------------------------------------------===// 51 52 Optional<uint64_t> 53 AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const { 54 uint64_t Size = DL.getTypeAllocSizeInBits(getAllocatedType()); 55 if (isArrayAllocation()) { 56 auto C = dyn_cast<ConstantInt>(getArraySize()); 57 if (!C) 58 return None; 59 Size *= C->getZExtValue(); 60 } 61 return Size; 62 } 63 64 //===----------------------------------------------------------------------===// 65 // SelectInst Class 66 //===----------------------------------------------------------------------===// 67 68 /// areInvalidOperands - Return a string if the specified operands are invalid 69 /// for a select operation, otherwise return null. 70 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { 71 if (Op1->getType() != Op2->getType()) 72 return "both values to select must have same type"; 73 74 if (Op1->getType()->isTokenTy()) 75 return "select values cannot have token type"; 76 77 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { 78 // Vector select. 79 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext())) 80 return "vector select condition element type must be i1"; 81 VectorType *ET = dyn_cast<VectorType>(Op1->getType()); 82 if (!ET) 83 return "selected values for vector select must be vectors"; 84 if (ET->getElementCount() != VT->getElementCount()) 85 return "vector select requires selected vectors to have " 86 "the same vector length as select condition"; 87 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) { 88 return "select condition must be i1 or <n x i1>"; 89 } 90 return nullptr; 91 } 92 93 //===----------------------------------------------------------------------===// 94 // PHINode Class 95 //===----------------------------------------------------------------------===// 96 97 PHINode::PHINode(const PHINode &PN) 98 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()), 99 ReservedSpace(PN.getNumOperands()) { 100 allocHungoffUses(PN.getNumOperands()); 101 std::copy(PN.op_begin(), PN.op_end(), op_begin()); 102 std::copy(PN.block_begin(), PN.block_end(), block_begin()); 103 SubclassOptionalData = PN.SubclassOptionalData; 104 } 105 106 // removeIncomingValue - Remove an incoming value. This is useful if a 107 // predecessor basic block is deleted. 108 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { 109 Value *Removed = getIncomingValue(Idx); 110 111 // Move everything after this operand down. 112 // 113 // FIXME: we could just swap with the end of the list, then erase. However, 114 // clients might not expect this to happen. The code as it is thrashes the 115 // use/def lists, which is kinda lame. 116 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx); 117 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx); 118 119 // Nuke the last value. 120 Op<-1>().set(nullptr); 121 setNumHungOffUseOperands(getNumOperands() - 1); 122 123 // If the PHI node is dead, because it has zero entries, nuke it now. 124 if (getNumOperands() == 0 && DeletePHIIfEmpty) { 125 // If anyone is using this PHI, make them use a dummy value instead... 126 replaceAllUsesWith(UndefValue::get(getType())); 127 eraseFromParent(); 128 } 129 return Removed; 130 } 131 132 /// growOperands - grow operands - This grows the operand list in response 133 /// to a push_back style of operation. This grows the number of ops by 1.5 134 /// times. 135 /// 136 void PHINode::growOperands() { 137 unsigned e = getNumOperands(); 138 unsigned NumOps = e + e / 2; 139 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common. 140 141 ReservedSpace = NumOps; 142 growHungoffUses(ReservedSpace, /* IsPhi */ true); 143 } 144 145 /// hasConstantValue - If the specified PHI node always merges together the same 146 /// value, return the value, otherwise return null. 147 Value *PHINode::hasConstantValue() const { 148 // Exploit the fact that phi nodes always have at least one entry. 149 Value *ConstantValue = getIncomingValue(0); 150 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i) 151 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) { 152 if (ConstantValue != this) 153 return nullptr; // Incoming values not all the same. 154 // The case where the first value is this PHI. 155 ConstantValue = getIncomingValue(i); 156 } 157 if (ConstantValue == this) 158 return UndefValue::get(getType()); 159 return ConstantValue; 160 } 161 162 /// hasConstantOrUndefValue - Whether the specified PHI node always merges 163 /// together the same value, assuming that undefs result in the same value as 164 /// non-undefs. 165 /// Unlike \ref hasConstantValue, this does not return a value because the 166 /// unique non-undef incoming value need not dominate the PHI node. 167 bool PHINode::hasConstantOrUndefValue() const { 168 Value *ConstantValue = nullptr; 169 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) { 170 Value *Incoming = getIncomingValue(i); 171 if (Incoming != this && !isa<UndefValue>(Incoming)) { 172 if (ConstantValue && ConstantValue != Incoming) 173 return false; 174 ConstantValue = Incoming; 175 } 176 } 177 return true; 178 } 179 180 //===----------------------------------------------------------------------===// 181 // LandingPadInst Implementation 182 //===----------------------------------------------------------------------===// 183 184 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 185 const Twine &NameStr, Instruction *InsertBefore) 186 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) { 187 init(NumReservedValues, NameStr); 188 } 189 190 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 191 const Twine &NameStr, BasicBlock *InsertAtEnd) 192 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) { 193 init(NumReservedValues, NameStr); 194 } 195 196 LandingPadInst::LandingPadInst(const LandingPadInst &LP) 197 : Instruction(LP.getType(), Instruction::LandingPad, nullptr, 198 LP.getNumOperands()), 199 ReservedSpace(LP.getNumOperands()) { 200 allocHungoffUses(LP.getNumOperands()); 201 Use *OL = getOperandList(); 202 const Use *InOL = LP.getOperandList(); 203 for (unsigned I = 0, E = ReservedSpace; I != E; ++I) 204 OL[I] = InOL[I]; 205 206 setCleanup(LP.isCleanup()); 207 } 208 209 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 210 const Twine &NameStr, 211 Instruction *InsertBefore) { 212 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore); 213 } 214 215 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 216 const Twine &NameStr, 217 BasicBlock *InsertAtEnd) { 218 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd); 219 } 220 221 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) { 222 ReservedSpace = NumReservedValues; 223 setNumHungOffUseOperands(0); 224 allocHungoffUses(ReservedSpace); 225 setName(NameStr); 226 setCleanup(false); 227 } 228 229 /// growOperands - grow operands - This grows the operand list in response to a 230 /// push_back style of operation. This grows the number of ops by 2 times. 231 void LandingPadInst::growOperands(unsigned Size) { 232 unsigned e = getNumOperands(); 233 if (ReservedSpace >= e + Size) return; 234 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2; 235 growHungoffUses(ReservedSpace); 236 } 237 238 void LandingPadInst::addClause(Constant *Val) { 239 unsigned OpNo = getNumOperands(); 240 growOperands(1); 241 assert(OpNo < ReservedSpace && "Growing didn't work!"); 242 setNumHungOffUseOperands(getNumOperands() + 1); 243 getOperandList()[OpNo] = Val; 244 } 245 246 //===----------------------------------------------------------------------===// 247 // CallBase Implementation 248 //===----------------------------------------------------------------------===// 249 250 Function *CallBase::getCaller() { return getParent()->getParent(); } 251 252 unsigned CallBase::getNumSubclassExtraOperandsDynamic() const { 253 assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!"); 254 return cast<CallBrInst>(this)->getNumIndirectDests() + 1; 255 } 256 257 bool CallBase::isIndirectCall() const { 258 const Value *V = getCalledOperand(); 259 if (isa<Function>(V) || isa<Constant>(V)) 260 return false; 261 return !isInlineAsm(); 262 } 263 264 /// Tests if this call site must be tail call optimized. Only a CallInst can 265 /// be tail call optimized. 266 bool CallBase::isMustTailCall() const { 267 if (auto *CI = dyn_cast<CallInst>(this)) 268 return CI->isMustTailCall(); 269 return false; 270 } 271 272 /// Tests if this call site is marked as a tail call. 273 bool CallBase::isTailCall() const { 274 if (auto *CI = dyn_cast<CallInst>(this)) 275 return CI->isTailCall(); 276 return false; 277 } 278 279 Intrinsic::ID CallBase::getIntrinsicID() const { 280 if (auto *F = getCalledFunction()) 281 return F->getIntrinsicID(); 282 return Intrinsic::not_intrinsic; 283 } 284 285 bool CallBase::isReturnNonNull() const { 286 if (hasRetAttr(Attribute::NonNull)) 287 return true; 288 289 if (getDereferenceableBytes(AttributeList::ReturnIndex) > 0 && 290 !NullPointerIsDefined(getCaller(), 291 getType()->getPointerAddressSpace())) 292 return true; 293 294 return false; 295 } 296 297 Value *CallBase::getReturnedArgOperand() const { 298 unsigned Index; 299 300 if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index) 301 return getArgOperand(Index - AttributeList::FirstArgIndex); 302 if (const Function *F = getCalledFunction()) 303 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) && 304 Index) 305 return getArgOperand(Index - AttributeList::FirstArgIndex); 306 307 return nullptr; 308 } 309 310 bool CallBase::hasRetAttr(Attribute::AttrKind Kind) const { 311 if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind)) 312 return true; 313 314 // Look at the callee, if available. 315 if (const Function *F = getCalledFunction()) 316 return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind); 317 return false; 318 } 319 320 /// Determine whether the argument or parameter has the given attribute. 321 bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const { 322 assert(ArgNo < getNumArgOperands() && "Param index out of bounds!"); 323 324 if (Attrs.hasParamAttribute(ArgNo, Kind)) 325 return true; 326 if (const Function *F = getCalledFunction()) 327 return F->getAttributes().hasParamAttribute(ArgNo, Kind); 328 return false; 329 } 330 331 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const { 332 if (const Function *F = getCalledFunction()) 333 return F->getAttributes().hasFnAttribute(Kind); 334 return false; 335 } 336 337 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const { 338 if (const Function *F = getCalledFunction()) 339 return F->getAttributes().hasFnAttribute(Kind); 340 return false; 341 } 342 343 void CallBase::getOperandBundlesAsDefs( 344 SmallVectorImpl<OperandBundleDef> &Defs) const { 345 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) 346 Defs.emplace_back(getOperandBundleAt(i)); 347 } 348 349 CallBase::op_iterator 350 CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles, 351 const unsigned BeginIndex) { 352 auto It = op_begin() + BeginIndex; 353 for (auto &B : Bundles) 354 It = std::copy(B.input_begin(), B.input_end(), It); 355 356 auto *ContextImpl = getContext().pImpl; 357 auto BI = Bundles.begin(); 358 unsigned CurrentIndex = BeginIndex; 359 360 for (auto &BOI : bundle_op_infos()) { 361 assert(BI != Bundles.end() && "Incorrect allocation?"); 362 363 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag()); 364 BOI.Begin = CurrentIndex; 365 BOI.End = CurrentIndex + BI->input_size(); 366 CurrentIndex = BOI.End; 367 BI++; 368 } 369 370 assert(BI == Bundles.end() && "Incorrect allocation?"); 371 372 return It; 373 } 374 375 CallBase::BundleOpInfo &CallBase::getBundleOpInfoForOperand(unsigned OpIdx) { 376 /// When there isn't many bundles, we do a simple linear search. 377 /// Else fallback to a binary-search that use the fact that bundles usually 378 /// have similar number of argument to get faster convergence. 379 if (bundle_op_info_end() - bundle_op_info_begin() < 8) { 380 for (auto &BOI : bundle_op_infos()) 381 if (BOI.Begin <= OpIdx && OpIdx < BOI.End) 382 return BOI; 383 384 llvm_unreachable("Did not find operand bundle for operand!"); 385 } 386 387 assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles"); 388 assert(bundle_op_info_end() - bundle_op_info_begin() > 0 && 389 OpIdx < std::prev(bundle_op_info_end())->End && 390 "The Idx isn't in the operand bundle"); 391 392 /// We need a decimal number below and to prevent using floating point numbers 393 /// we use an intergal value multiplied by this constant. 394 constexpr unsigned NumberScaling = 1024; 395 396 bundle_op_iterator Begin = bundle_op_info_begin(); 397 bundle_op_iterator End = bundle_op_info_end(); 398 bundle_op_iterator Current; 399 400 while (Begin != End) { 401 unsigned ScaledOperandPerBundle = 402 NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin); 403 Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) / 404 ScaledOperandPerBundle); 405 if (Current >= End) 406 Current = std::prev(End); 407 assert(Current < End && Current >= Begin && 408 "the operand bundle doesn't cover every value in the range"); 409 if (OpIdx >= Current->Begin && OpIdx < Current->End) 410 break; 411 if (OpIdx >= Current->End) 412 Begin = Current + 1; 413 else 414 End = Current; 415 } 416 417 assert(OpIdx >= Current->Begin && OpIdx < Current->End && 418 "the operand bundle doesn't cover every value in the range"); 419 return *Current; 420 } 421 422 //===----------------------------------------------------------------------===// 423 // CallInst Implementation 424 //===----------------------------------------------------------------------===// 425 426 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, 427 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) { 428 this->FTy = FTy; 429 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 && 430 "NumOperands not set up?"); 431 setCalledOperand(Func); 432 433 #ifndef NDEBUG 434 assert((Args.size() == FTy->getNumParams() || 435 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 436 "Calling a function with bad signature!"); 437 438 for (unsigned i = 0; i != Args.size(); ++i) 439 assert((i >= FTy->getNumParams() || 440 FTy->getParamType(i) == Args[i]->getType()) && 441 "Calling a function with a bad signature!"); 442 #endif 443 444 llvm::copy(Args, op_begin()); 445 446 auto It = populateBundleOperandInfos(Bundles, Args.size()); 447 (void)It; 448 assert(It + 1 == op_end() && "Should add up!"); 449 450 setName(NameStr); 451 } 452 453 void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) { 454 this->FTy = FTy; 455 assert(getNumOperands() == 1 && "NumOperands not set up?"); 456 setCalledOperand(Func); 457 458 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature"); 459 460 setName(NameStr); 461 } 462 463 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name, 464 Instruction *InsertBefore) 465 : CallBase(Ty->getReturnType(), Instruction::Call, 466 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) { 467 init(Ty, Func, Name); 468 } 469 470 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name, 471 BasicBlock *InsertAtEnd) 472 : CallBase(Ty->getReturnType(), Instruction::Call, 473 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) { 474 init(Ty, Func, Name); 475 } 476 477 CallInst::CallInst(const CallInst &CI) 478 : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call, 479 OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(), 480 CI.getNumOperands()) { 481 setTailCallKind(CI.getTailCallKind()); 482 setCallingConv(CI.getCallingConv()); 483 484 std::copy(CI.op_begin(), CI.op_end(), op_begin()); 485 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(), 486 bundle_op_info_begin()); 487 SubclassOptionalData = CI.SubclassOptionalData; 488 } 489 490 CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB, 491 Instruction *InsertPt) { 492 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end()); 493 494 auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(), 495 Args, OpB, CI->getName(), InsertPt); 496 NewCI->setTailCallKind(CI->getTailCallKind()); 497 NewCI->setCallingConv(CI->getCallingConv()); 498 NewCI->SubclassOptionalData = CI->SubclassOptionalData; 499 NewCI->setAttributes(CI->getAttributes()); 500 NewCI->setDebugLoc(CI->getDebugLoc()); 501 return NewCI; 502 } 503 504 // Update profile weight for call instruction by scaling it using the ratio 505 // of S/T. The meaning of "branch_weights" meta data for call instruction is 506 // transfered to represent call count. 507 void CallInst::updateProfWeight(uint64_t S, uint64_t T) { 508 auto *ProfileData = getMetadata(LLVMContext::MD_prof); 509 if (ProfileData == nullptr) 510 return; 511 512 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0)); 513 if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") && 514 !ProfDataName->getString().equals("VP"))) 515 return; 516 517 if (T == 0) { 518 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in " 519 "div by 0. Ignoring. Likely the function " 520 << getParent()->getParent()->getName() 521 << " has 0 entry count, and contains call instructions " 522 "with non-zero prof info."); 523 return; 524 } 525 526 MDBuilder MDB(getContext()); 527 SmallVector<Metadata *, 3> Vals; 528 Vals.push_back(ProfileData->getOperand(0)); 529 APInt APS(128, S), APT(128, T); 530 if (ProfDataName->getString().equals("branch_weights") && 531 ProfileData->getNumOperands() > 0) { 532 // Using APInt::div may be expensive, but most cases should fit 64 bits. 533 APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1)) 534 ->getValue() 535 .getZExtValue()); 536 Val *= APS; 537 Vals.push_back(MDB.createConstant(ConstantInt::get( 538 Type::getInt64Ty(getContext()), Val.udiv(APT).getLimitedValue()))); 539 } else if (ProfDataName->getString().equals("VP")) 540 for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) { 541 // The first value is the key of the value profile, which will not change. 542 Vals.push_back(ProfileData->getOperand(i)); 543 // Using APInt::div may be expensive, but most cases should fit 64 bits. 544 APInt Val(128, 545 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1)) 546 ->getValue() 547 .getZExtValue()); 548 Val *= APS; 549 Vals.push_back(MDB.createConstant( 550 ConstantInt::get(Type::getInt64Ty(getContext()), 551 Val.udiv(APT).getLimitedValue()))); 552 } 553 setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals)); 554 } 555 556 /// IsConstantOne - Return true only if val is constant int 1 557 static bool IsConstantOne(Value *val) { 558 assert(val && "IsConstantOne does not work with nullptr val"); 559 const ConstantInt *CVal = dyn_cast<ConstantInt>(val); 560 return CVal && CVal->isOne(); 561 } 562 563 static Instruction *createMalloc(Instruction *InsertBefore, 564 BasicBlock *InsertAtEnd, Type *IntPtrTy, 565 Type *AllocTy, Value *AllocSize, 566 Value *ArraySize, 567 ArrayRef<OperandBundleDef> OpB, 568 Function *MallocF, const Twine &Name) { 569 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 570 "createMalloc needs either InsertBefore or InsertAtEnd"); 571 572 // malloc(type) becomes: 573 // bitcast (i8* malloc(typeSize)) to type* 574 // malloc(type, arraySize) becomes: 575 // bitcast (i8* malloc(typeSize*arraySize)) to type* 576 if (!ArraySize) 577 ArraySize = ConstantInt::get(IntPtrTy, 1); 578 else if (ArraySize->getType() != IntPtrTy) { 579 if (InsertBefore) 580 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 581 "", InsertBefore); 582 else 583 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 584 "", InsertAtEnd); 585 } 586 587 if (!IsConstantOne(ArraySize)) { 588 if (IsConstantOne(AllocSize)) { 589 AllocSize = ArraySize; // Operand * 1 = Operand 590 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) { 591 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy, 592 false /*ZExt*/); 593 // Malloc arg is constant product of type size and array size 594 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize)); 595 } else { 596 // Multiply type size by the array size... 597 if (InsertBefore) 598 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 599 "mallocsize", InsertBefore); 600 else 601 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 602 "mallocsize", InsertAtEnd); 603 } 604 } 605 606 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size"); 607 // Create the call to Malloc. 608 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 609 Module *M = BB->getParent()->getParent(); 610 Type *BPTy = Type::getInt8PtrTy(BB->getContext()); 611 FunctionCallee MallocFunc = MallocF; 612 if (!MallocFunc) 613 // prototype malloc as "void *malloc(size_t)" 614 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy); 615 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy); 616 CallInst *MCall = nullptr; 617 Instruction *Result = nullptr; 618 if (InsertBefore) { 619 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall", 620 InsertBefore); 621 Result = MCall; 622 if (Result->getType() != AllocPtrType) 623 // Create a cast instruction to convert to the right type... 624 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore); 625 } else { 626 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall"); 627 Result = MCall; 628 if (Result->getType() != AllocPtrType) { 629 InsertAtEnd->getInstList().push_back(MCall); 630 // Create a cast instruction to convert to the right type... 631 Result = new BitCastInst(MCall, AllocPtrType, Name); 632 } 633 } 634 MCall->setTailCall(); 635 if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) { 636 MCall->setCallingConv(F->getCallingConv()); 637 if (!F->returnDoesNotAlias()) 638 F->setReturnDoesNotAlias(); 639 } 640 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type"); 641 642 return Result; 643 } 644 645 /// CreateMalloc - Generate the IR for a call to malloc: 646 /// 1. Compute the malloc call's argument as the specified type's size, 647 /// possibly multiplied by the array size if the array size is not 648 /// constant 1. 649 /// 2. Call malloc with that argument. 650 /// 3. Bitcast the result of the malloc call to the specified type. 651 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, 652 Type *IntPtrTy, Type *AllocTy, 653 Value *AllocSize, Value *ArraySize, 654 Function *MallocF, 655 const Twine &Name) { 656 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, 657 ArraySize, None, MallocF, Name); 658 } 659 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, 660 Type *IntPtrTy, Type *AllocTy, 661 Value *AllocSize, Value *ArraySize, 662 ArrayRef<OperandBundleDef> OpB, 663 Function *MallocF, 664 const Twine &Name) { 665 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, 666 ArraySize, OpB, MallocF, Name); 667 } 668 669 /// CreateMalloc - Generate the IR for a call to malloc: 670 /// 1. Compute the malloc call's argument as the specified type's size, 671 /// possibly multiplied by the array size if the array size is not 672 /// constant 1. 673 /// 2. Call malloc with that argument. 674 /// 3. Bitcast the result of the malloc call to the specified type. 675 /// Note: This function does not add the bitcast to the basic block, that is the 676 /// responsibility of the caller. 677 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, 678 Type *IntPtrTy, Type *AllocTy, 679 Value *AllocSize, Value *ArraySize, 680 Function *MallocF, const Twine &Name) { 681 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, 682 ArraySize, None, MallocF, Name); 683 } 684 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, 685 Type *IntPtrTy, Type *AllocTy, 686 Value *AllocSize, Value *ArraySize, 687 ArrayRef<OperandBundleDef> OpB, 688 Function *MallocF, const Twine &Name) { 689 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, 690 ArraySize, OpB, MallocF, Name); 691 } 692 693 static Instruction *createFree(Value *Source, 694 ArrayRef<OperandBundleDef> Bundles, 695 Instruction *InsertBefore, 696 BasicBlock *InsertAtEnd) { 697 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 698 "createFree needs either InsertBefore or InsertAtEnd"); 699 assert(Source->getType()->isPointerTy() && 700 "Can not free something of nonpointer type!"); 701 702 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 703 Module *M = BB->getParent()->getParent(); 704 705 Type *VoidTy = Type::getVoidTy(M->getContext()); 706 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext()); 707 // prototype free as "void free(void*)" 708 FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy); 709 CallInst *Result = nullptr; 710 Value *PtrCast = Source; 711 if (InsertBefore) { 712 if (Source->getType() != IntPtrTy) 713 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore); 714 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore); 715 } else { 716 if (Source->getType() != IntPtrTy) 717 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd); 718 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, ""); 719 } 720 Result->setTailCall(); 721 if (Function *F = dyn_cast<Function>(FreeFunc.getCallee())) 722 Result->setCallingConv(F->getCallingConv()); 723 724 return Result; 725 } 726 727 /// CreateFree - Generate the IR for a call to the builtin free function. 728 Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) { 729 return createFree(Source, None, InsertBefore, nullptr); 730 } 731 Instruction *CallInst::CreateFree(Value *Source, 732 ArrayRef<OperandBundleDef> Bundles, 733 Instruction *InsertBefore) { 734 return createFree(Source, Bundles, InsertBefore, nullptr); 735 } 736 737 /// CreateFree - Generate the IR for a call to the builtin free function. 738 /// Note: This function does not add the call to the basic block, that is the 739 /// responsibility of the caller. 740 Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) { 741 Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd); 742 assert(FreeCall && "CreateFree did not create a CallInst"); 743 return FreeCall; 744 } 745 Instruction *CallInst::CreateFree(Value *Source, 746 ArrayRef<OperandBundleDef> Bundles, 747 BasicBlock *InsertAtEnd) { 748 Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd); 749 assert(FreeCall && "CreateFree did not create a CallInst"); 750 return FreeCall; 751 } 752 753 //===----------------------------------------------------------------------===// 754 // InvokeInst Implementation 755 //===----------------------------------------------------------------------===// 756 757 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal, 758 BasicBlock *IfException, ArrayRef<Value *> Args, 759 ArrayRef<OperandBundleDef> Bundles, 760 const Twine &NameStr) { 761 this->FTy = FTy; 762 763 assert((int)getNumOperands() == 764 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) && 765 "NumOperands not set up?"); 766 setNormalDest(IfNormal); 767 setUnwindDest(IfException); 768 setCalledOperand(Fn); 769 770 #ifndef NDEBUG 771 assert(((Args.size() == FTy->getNumParams()) || 772 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 773 "Invoking a function with bad signature"); 774 775 for (unsigned i = 0, e = Args.size(); i != e; i++) 776 assert((i >= FTy->getNumParams() || 777 FTy->getParamType(i) == Args[i]->getType()) && 778 "Invoking a function with a bad signature!"); 779 #endif 780 781 llvm::copy(Args, op_begin()); 782 783 auto It = populateBundleOperandInfos(Bundles, Args.size()); 784 (void)It; 785 assert(It + 3 == op_end() && "Should add up!"); 786 787 setName(NameStr); 788 } 789 790 InvokeInst::InvokeInst(const InvokeInst &II) 791 : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke, 792 OperandTraits<CallBase>::op_end(this) - II.getNumOperands(), 793 II.getNumOperands()) { 794 setCallingConv(II.getCallingConv()); 795 std::copy(II.op_begin(), II.op_end(), op_begin()); 796 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(), 797 bundle_op_info_begin()); 798 SubclassOptionalData = II.SubclassOptionalData; 799 } 800 801 InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB, 802 Instruction *InsertPt) { 803 std::vector<Value *> Args(II->arg_begin(), II->arg_end()); 804 805 auto *NewII = InvokeInst::Create( 806 II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(), 807 II->getUnwindDest(), Args, OpB, II->getName(), InsertPt); 808 NewII->setCallingConv(II->getCallingConv()); 809 NewII->SubclassOptionalData = II->SubclassOptionalData; 810 NewII->setAttributes(II->getAttributes()); 811 NewII->setDebugLoc(II->getDebugLoc()); 812 return NewII; 813 } 814 815 816 LandingPadInst *InvokeInst::getLandingPadInst() const { 817 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI()); 818 } 819 820 //===----------------------------------------------------------------------===// 821 // CallBrInst Implementation 822 //===----------------------------------------------------------------------===// 823 824 void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough, 825 ArrayRef<BasicBlock *> IndirectDests, 826 ArrayRef<Value *> Args, 827 ArrayRef<OperandBundleDef> Bundles, 828 const Twine &NameStr) { 829 this->FTy = FTy; 830 831 assert((int)getNumOperands() == 832 ComputeNumOperands(Args.size(), IndirectDests.size(), 833 CountBundleInputs(Bundles)) && 834 "NumOperands not set up?"); 835 NumIndirectDests = IndirectDests.size(); 836 setDefaultDest(Fallthrough); 837 for (unsigned i = 0; i != NumIndirectDests; ++i) 838 setIndirectDest(i, IndirectDests[i]); 839 setCalledOperand(Fn); 840 841 #ifndef NDEBUG 842 assert(((Args.size() == FTy->getNumParams()) || 843 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 844 "Calling a function with bad signature"); 845 846 for (unsigned i = 0, e = Args.size(); i != e; i++) 847 assert((i >= FTy->getNumParams() || 848 FTy->getParamType(i) == Args[i]->getType()) && 849 "Calling a function with a bad signature!"); 850 #endif 851 852 std::copy(Args.begin(), Args.end(), op_begin()); 853 854 auto It = populateBundleOperandInfos(Bundles, Args.size()); 855 (void)It; 856 assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!"); 857 858 setName(NameStr); 859 } 860 861 void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) { 862 assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr"); 863 if (BasicBlock *OldBB = getIndirectDest(i)) { 864 BlockAddress *Old = BlockAddress::get(OldBB); 865 BlockAddress *New = BlockAddress::get(B); 866 for (unsigned ArgNo = 0, e = getNumArgOperands(); ArgNo != e; ++ArgNo) 867 if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old) 868 setArgOperand(ArgNo, New); 869 } 870 } 871 872 CallBrInst::CallBrInst(const CallBrInst &CBI) 873 : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr, 874 OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(), 875 CBI.getNumOperands()) { 876 setCallingConv(CBI.getCallingConv()); 877 std::copy(CBI.op_begin(), CBI.op_end(), op_begin()); 878 std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(), 879 bundle_op_info_begin()); 880 SubclassOptionalData = CBI.SubclassOptionalData; 881 NumIndirectDests = CBI.NumIndirectDests; 882 } 883 884 CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB, 885 Instruction *InsertPt) { 886 std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end()); 887 888 auto *NewCBI = CallBrInst::Create( 889 CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(), 890 CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt); 891 NewCBI->setCallingConv(CBI->getCallingConv()); 892 NewCBI->SubclassOptionalData = CBI->SubclassOptionalData; 893 NewCBI->setAttributes(CBI->getAttributes()); 894 NewCBI->setDebugLoc(CBI->getDebugLoc()); 895 NewCBI->NumIndirectDests = CBI->NumIndirectDests; 896 return NewCBI; 897 } 898 899 //===----------------------------------------------------------------------===// 900 // ReturnInst Implementation 901 //===----------------------------------------------------------------------===// 902 903 ReturnInst::ReturnInst(const ReturnInst &RI) 904 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret, 905 OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(), 906 RI.getNumOperands()) { 907 if (RI.getNumOperands()) 908 Op<0>() = RI.Op<0>(); 909 SubclassOptionalData = RI.SubclassOptionalData; 910 } 911 912 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore) 913 : Instruction(Type::getVoidTy(C), Instruction::Ret, 914 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 915 InsertBefore) { 916 if (retVal) 917 Op<0>() = retVal; 918 } 919 920 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) 921 : Instruction(Type::getVoidTy(C), Instruction::Ret, 922 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 923 InsertAtEnd) { 924 if (retVal) 925 Op<0>() = retVal; 926 } 927 928 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 929 : Instruction(Type::getVoidTy(Context), Instruction::Ret, 930 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {} 931 932 //===----------------------------------------------------------------------===// 933 // ResumeInst Implementation 934 //===----------------------------------------------------------------------===// 935 936 ResumeInst::ResumeInst(const ResumeInst &RI) 937 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume, 938 OperandTraits<ResumeInst>::op_begin(this), 1) { 939 Op<0>() = RI.Op<0>(); 940 } 941 942 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore) 943 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 944 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) { 945 Op<0>() = Exn; 946 } 947 948 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd) 949 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 950 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) { 951 Op<0>() = Exn; 952 } 953 954 //===----------------------------------------------------------------------===// 955 // CleanupReturnInst Implementation 956 //===----------------------------------------------------------------------===// 957 958 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI) 959 : Instruction(CRI.getType(), Instruction::CleanupRet, 960 OperandTraits<CleanupReturnInst>::op_end(this) - 961 CRI.getNumOperands(), 962 CRI.getNumOperands()) { 963 setInstructionSubclassData(CRI.getSubclassDataFromInstruction()); 964 Op<0>() = CRI.Op<0>(); 965 if (CRI.hasUnwindDest()) 966 Op<1>() = CRI.Op<1>(); 967 } 968 969 void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) { 970 if (UnwindBB) 971 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 972 973 Op<0>() = CleanupPad; 974 if (UnwindBB) 975 Op<1>() = UnwindBB; 976 } 977 978 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, 979 unsigned Values, Instruction *InsertBefore) 980 : Instruction(Type::getVoidTy(CleanupPad->getContext()), 981 Instruction::CleanupRet, 982 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 983 Values, InsertBefore) { 984 init(CleanupPad, UnwindBB); 985 } 986 987 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, 988 unsigned Values, BasicBlock *InsertAtEnd) 989 : Instruction(Type::getVoidTy(CleanupPad->getContext()), 990 Instruction::CleanupRet, 991 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 992 Values, InsertAtEnd) { 993 init(CleanupPad, UnwindBB); 994 } 995 996 //===----------------------------------------------------------------------===// 997 // CatchReturnInst Implementation 998 //===----------------------------------------------------------------------===// 999 void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) { 1000 Op<0>() = CatchPad; 1001 Op<1>() = BB; 1002 } 1003 1004 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI) 1005 : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet, 1006 OperandTraits<CatchReturnInst>::op_begin(this), 2) { 1007 Op<0>() = CRI.Op<0>(); 1008 Op<1>() = CRI.Op<1>(); 1009 } 1010 1011 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, 1012 Instruction *InsertBefore) 1013 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 1014 OperandTraits<CatchReturnInst>::op_begin(this), 2, 1015 InsertBefore) { 1016 init(CatchPad, BB); 1017 } 1018 1019 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, 1020 BasicBlock *InsertAtEnd) 1021 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 1022 OperandTraits<CatchReturnInst>::op_begin(this), 2, 1023 InsertAtEnd) { 1024 init(CatchPad, BB); 1025 } 1026 1027 //===----------------------------------------------------------------------===// 1028 // CatchSwitchInst Implementation 1029 //===----------------------------------------------------------------------===// 1030 1031 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, 1032 unsigned NumReservedValues, 1033 const Twine &NameStr, 1034 Instruction *InsertBefore) 1035 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, 1036 InsertBefore) { 1037 if (UnwindDest) 1038 ++NumReservedValues; 1039 init(ParentPad, UnwindDest, NumReservedValues + 1); 1040 setName(NameStr); 1041 } 1042 1043 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, 1044 unsigned NumReservedValues, 1045 const Twine &NameStr, BasicBlock *InsertAtEnd) 1046 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, 1047 InsertAtEnd) { 1048 if (UnwindDest) 1049 ++NumReservedValues; 1050 init(ParentPad, UnwindDest, NumReservedValues + 1); 1051 setName(NameStr); 1052 } 1053 1054 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI) 1055 : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr, 1056 CSI.getNumOperands()) { 1057 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands()); 1058 setNumHungOffUseOperands(ReservedSpace); 1059 Use *OL = getOperandList(); 1060 const Use *InOL = CSI.getOperandList(); 1061 for (unsigned I = 1, E = ReservedSpace; I != E; ++I) 1062 OL[I] = InOL[I]; 1063 } 1064 1065 void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest, 1066 unsigned NumReservedValues) { 1067 assert(ParentPad && NumReservedValues); 1068 1069 ReservedSpace = NumReservedValues; 1070 setNumHungOffUseOperands(UnwindDest ? 2 : 1); 1071 allocHungoffUses(ReservedSpace); 1072 1073 Op<0>() = ParentPad; 1074 if (UnwindDest) { 1075 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 1076 setUnwindDest(UnwindDest); 1077 } 1078 } 1079 1080 /// growOperands - grow operands - This grows the operand list in response to a 1081 /// push_back style of operation. This grows the number of ops by 2 times. 1082 void CatchSwitchInst::growOperands(unsigned Size) { 1083 unsigned NumOperands = getNumOperands(); 1084 assert(NumOperands >= 1); 1085 if (ReservedSpace >= NumOperands + Size) 1086 return; 1087 ReservedSpace = (NumOperands + Size / 2) * 2; 1088 growHungoffUses(ReservedSpace); 1089 } 1090 1091 void CatchSwitchInst::addHandler(BasicBlock *Handler) { 1092 unsigned OpNo = getNumOperands(); 1093 growOperands(1); 1094 assert(OpNo < ReservedSpace && "Growing didn't work!"); 1095 setNumHungOffUseOperands(getNumOperands() + 1); 1096 getOperandList()[OpNo] = Handler; 1097 } 1098 1099 void CatchSwitchInst::removeHandler(handler_iterator HI) { 1100 // Move all subsequent handlers up one. 1101 Use *EndDst = op_end() - 1; 1102 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst) 1103 *CurDst = *(CurDst + 1); 1104 // Null out the last handler use. 1105 *EndDst = nullptr; 1106 1107 setNumHungOffUseOperands(getNumOperands() - 1); 1108 } 1109 1110 //===----------------------------------------------------------------------===// 1111 // FuncletPadInst Implementation 1112 //===----------------------------------------------------------------------===// 1113 void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args, 1114 const Twine &NameStr) { 1115 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?"); 1116 llvm::copy(Args, op_begin()); 1117 setParentPad(ParentPad); 1118 setName(NameStr); 1119 } 1120 1121 FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI) 1122 : Instruction(FPI.getType(), FPI.getOpcode(), 1123 OperandTraits<FuncletPadInst>::op_end(this) - 1124 FPI.getNumOperands(), 1125 FPI.getNumOperands()) { 1126 std::copy(FPI.op_begin(), FPI.op_end(), op_begin()); 1127 setParentPad(FPI.getParentPad()); 1128 } 1129 1130 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1131 ArrayRef<Value *> Args, unsigned Values, 1132 const Twine &NameStr, Instruction *InsertBefore) 1133 : Instruction(ParentPad->getType(), Op, 1134 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, 1135 InsertBefore) { 1136 init(ParentPad, Args, NameStr); 1137 } 1138 1139 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1140 ArrayRef<Value *> Args, unsigned Values, 1141 const Twine &NameStr, BasicBlock *InsertAtEnd) 1142 : Instruction(ParentPad->getType(), Op, 1143 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, 1144 InsertAtEnd) { 1145 init(ParentPad, Args, NameStr); 1146 } 1147 1148 //===----------------------------------------------------------------------===// 1149 // UnreachableInst Implementation 1150 //===----------------------------------------------------------------------===// 1151 1152 UnreachableInst::UnreachableInst(LLVMContext &Context, 1153 Instruction *InsertBefore) 1154 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, 1155 0, InsertBefore) {} 1156 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 1157 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, 1158 0, InsertAtEnd) {} 1159 1160 //===----------------------------------------------------------------------===// 1161 // BranchInst Implementation 1162 //===----------------------------------------------------------------------===// 1163 1164 void BranchInst::AssertOK() { 1165 if (isConditional()) 1166 assert(getCondition()->getType()->isIntegerTy(1) && 1167 "May only branch on boolean predicates!"); 1168 } 1169 1170 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) 1171 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1172 OperandTraits<BranchInst>::op_end(this) - 1, 1, 1173 InsertBefore) { 1174 assert(IfTrue && "Branch destination may not be null!"); 1175 Op<-1>() = IfTrue; 1176 } 1177 1178 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1179 Instruction *InsertBefore) 1180 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1181 OperandTraits<BranchInst>::op_end(this) - 3, 3, 1182 InsertBefore) { 1183 Op<-1>() = IfTrue; 1184 Op<-2>() = IfFalse; 1185 Op<-3>() = Cond; 1186 #ifndef NDEBUG 1187 AssertOK(); 1188 #endif 1189 } 1190 1191 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) 1192 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1193 OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) { 1194 assert(IfTrue && "Branch destination may not be null!"); 1195 Op<-1>() = IfTrue; 1196 } 1197 1198 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1199 BasicBlock *InsertAtEnd) 1200 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1201 OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) { 1202 Op<-1>() = IfTrue; 1203 Op<-2>() = IfFalse; 1204 Op<-3>() = Cond; 1205 #ifndef NDEBUG 1206 AssertOK(); 1207 #endif 1208 } 1209 1210 BranchInst::BranchInst(const BranchInst &BI) 1211 : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br, 1212 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), 1213 BI.getNumOperands()) { 1214 Op<-1>() = BI.Op<-1>(); 1215 if (BI.getNumOperands() != 1) { 1216 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!"); 1217 Op<-3>() = BI.Op<-3>(); 1218 Op<-2>() = BI.Op<-2>(); 1219 } 1220 SubclassOptionalData = BI.SubclassOptionalData; 1221 } 1222 1223 void BranchInst::swapSuccessors() { 1224 assert(isConditional() && 1225 "Cannot swap successors of an unconditional branch"); 1226 Op<-1>().swap(Op<-2>()); 1227 1228 // Update profile metadata if present and it matches our structural 1229 // expectations. 1230 swapProfMetadata(); 1231 } 1232 1233 //===----------------------------------------------------------------------===// 1234 // AllocaInst Implementation 1235 //===----------------------------------------------------------------------===// 1236 1237 static Value *getAISize(LLVMContext &Context, Value *Amt) { 1238 if (!Amt) 1239 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1); 1240 else { 1241 assert(!isa<BasicBlock>(Amt) && 1242 "Passed basic block into allocation size parameter! Use other ctor"); 1243 assert(Amt->getType()->isIntegerTy() && 1244 "Allocation array size is not an integer!"); 1245 } 1246 return Amt; 1247 } 1248 1249 static Align computeAllocaDefaultAlign(Type *Ty, BasicBlock *BB) { 1250 const DataLayout &DL = BB->getModule()->getDataLayout(); 1251 return DL.getPrefTypeAlign(Ty); 1252 } 1253 1254 static Align computeAllocaDefaultAlign(Type *Ty, Instruction *I) { 1255 return computeAllocaDefaultAlign(Ty, I->getParent()); 1256 } 1257 1258 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1259 Instruction *InsertBefore) 1260 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {} 1261 1262 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1263 BasicBlock *InsertAtEnd) 1264 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {} 1265 1266 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1267 const Twine &Name, Instruction *InsertBefore) 1268 : AllocaInst(Ty, AddrSpace, ArraySize, 1269 computeAllocaDefaultAlign(Ty, InsertBefore), Name, 1270 InsertBefore) {} 1271 1272 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1273 const Twine &Name, BasicBlock *InsertAtEnd) 1274 : AllocaInst(Ty, AddrSpace, ArraySize, 1275 computeAllocaDefaultAlign(Ty, InsertAtEnd), Name, 1276 InsertAtEnd) {} 1277 1278 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1279 Align Align, const Twine &Name, 1280 Instruction *InsertBefore) 1281 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1282 getAISize(Ty->getContext(), ArraySize), InsertBefore), 1283 AllocatedType(Ty) { 1284 setAlignment(Align); 1285 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1286 setName(Name); 1287 } 1288 1289 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1290 Align Align, const Twine &Name, BasicBlock *InsertAtEnd) 1291 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1292 getAISize(Ty->getContext(), ArraySize), InsertAtEnd), 1293 AllocatedType(Ty) { 1294 setAlignment(Align); 1295 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1296 setName(Name); 1297 } 1298 1299 void AllocaInst::setAlignment(Align Align) { 1300 assert(Align <= MaximumAlignment && 1301 "Alignment is greater than MaximumAlignment!"); 1302 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) | 1303 encode(Align)); 1304 assert(getAlignment() == Align.value() && "Alignment representation error!"); 1305 } 1306 1307 bool AllocaInst::isArrayAllocation() const { 1308 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) 1309 return !CI->isOne(); 1310 return true; 1311 } 1312 1313 /// isStaticAlloca - Return true if this alloca is in the entry block of the 1314 /// function and is a constant size. If so, the code generator will fold it 1315 /// into the prolog/epilog code, so it is basically free. 1316 bool AllocaInst::isStaticAlloca() const { 1317 // Must be constant size. 1318 if (!isa<ConstantInt>(getArraySize())) return false; 1319 1320 // Must be in the entry block. 1321 const BasicBlock *Parent = getParent(); 1322 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca(); 1323 } 1324 1325 //===----------------------------------------------------------------------===// 1326 // LoadInst Implementation 1327 //===----------------------------------------------------------------------===// 1328 1329 void LoadInst::AssertOK() { 1330 assert(getOperand(0)->getType()->isPointerTy() && 1331 "Ptr must have pointer type."); 1332 assert(!(isAtomic() && getAlignment() == 0) && 1333 "Alignment required for atomic load"); 1334 } 1335 1336 static Align computeLoadStoreDefaultAlign(Type *Ty, BasicBlock *BB) { 1337 const DataLayout &DL = BB->getModule()->getDataLayout(); 1338 return DL.getABITypeAlign(Ty); 1339 } 1340 1341 static Align computeLoadStoreDefaultAlign(Type *Ty, Instruction *I) { 1342 return computeLoadStoreDefaultAlign(Ty, I->getParent()); 1343 } 1344 1345 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, 1346 Instruction *InsertBef) 1347 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {} 1348 1349 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, 1350 BasicBlock *InsertAE) 1351 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {} 1352 1353 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1354 Instruction *InsertBef) 1355 : LoadInst(Ty, Ptr, Name, isVolatile, 1356 computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {} 1357 1358 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1359 BasicBlock *InsertAE) 1360 : LoadInst(Ty, Ptr, Name, isVolatile, 1361 computeLoadStoreDefaultAlign(Ty, InsertAE), InsertAE) {} 1362 1363 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1364 Align Align, Instruction *InsertBef) 1365 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1366 SyncScope::System, InsertBef) {} 1367 1368 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1369 Align Align, BasicBlock *InsertAE) 1370 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1371 SyncScope::System, InsertAE) {} 1372 1373 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1374 Align Align, AtomicOrdering Order, SyncScope::ID SSID, 1375 Instruction *InsertBef) 1376 : UnaryInstruction(Ty, Load, Ptr, InsertBef) { 1377 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1378 setVolatile(isVolatile); 1379 setAlignment(Align); 1380 setAtomic(Order, SSID); 1381 AssertOK(); 1382 setName(Name); 1383 } 1384 1385 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1386 Align Align, AtomicOrdering Order, SyncScope::ID SSID, 1387 BasicBlock *InsertAE) 1388 : UnaryInstruction(Ty, Load, Ptr, InsertAE) { 1389 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1390 setVolatile(isVolatile); 1391 setAlignment(Align); 1392 setAtomic(Order, SSID); 1393 AssertOK(); 1394 setName(Name); 1395 } 1396 1397 void LoadInst::setAlignment(Align Align) { 1398 assert(Align <= MaximumAlignment && 1399 "Alignment is greater than MaximumAlignment!"); 1400 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1401 (encode(Align) << 1)); 1402 assert(getAlign() == Align && "Alignment representation error!"); 1403 } 1404 1405 //===----------------------------------------------------------------------===// 1406 // StoreInst Implementation 1407 //===----------------------------------------------------------------------===// 1408 1409 void StoreInst::AssertOK() { 1410 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); 1411 assert(getOperand(1)->getType()->isPointerTy() && 1412 "Ptr must have pointer type!"); 1413 assert(getOperand(0)->getType() == 1414 cast<PointerType>(getOperand(1)->getType())->getElementType() 1415 && "Ptr must be a pointer to Val type!"); 1416 assert(!(isAtomic() && getAlignment() == 0) && 1417 "Alignment required for atomic store"); 1418 } 1419 1420 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) 1421 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {} 1422 1423 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) 1424 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {} 1425 1426 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1427 Instruction *InsertBefore) 1428 : StoreInst(val, addr, isVolatile, 1429 computeLoadStoreDefaultAlign(val->getType(), InsertBefore), 1430 InsertBefore) {} 1431 1432 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1433 BasicBlock *InsertAtEnd) 1434 : StoreInst(val, addr, isVolatile, 1435 computeLoadStoreDefaultAlign(val->getType(), InsertAtEnd), 1436 InsertAtEnd) {} 1437 1438 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, 1439 Instruction *InsertBefore) 1440 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1441 SyncScope::System, InsertBefore) {} 1442 1443 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, 1444 BasicBlock *InsertAtEnd) 1445 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1446 SyncScope::System, InsertAtEnd) {} 1447 1448 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, 1449 AtomicOrdering Order, SyncScope::ID SSID, 1450 Instruction *InsertBefore) 1451 : Instruction(Type::getVoidTy(val->getContext()), Store, 1452 OperandTraits<StoreInst>::op_begin(this), 1453 OperandTraits<StoreInst>::operands(this), InsertBefore) { 1454 Op<0>() = val; 1455 Op<1>() = addr; 1456 setVolatile(isVolatile); 1457 setAlignment(Align); 1458 setAtomic(Order, SSID); 1459 AssertOK(); 1460 } 1461 1462 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, 1463 AtomicOrdering Order, SyncScope::ID SSID, 1464 BasicBlock *InsertAtEnd) 1465 : Instruction(Type::getVoidTy(val->getContext()), Store, 1466 OperandTraits<StoreInst>::op_begin(this), 1467 OperandTraits<StoreInst>::operands(this), InsertAtEnd) { 1468 Op<0>() = val; 1469 Op<1>() = addr; 1470 setVolatile(isVolatile); 1471 setAlignment(Align); 1472 setAtomic(Order, SSID); 1473 AssertOK(); 1474 } 1475 1476 void StoreInst::setAlignment(Align Alignment) { 1477 assert(Alignment <= MaximumAlignment && 1478 "Alignment is greater than MaximumAlignment!"); 1479 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1480 (encode(Alignment) << 1)); 1481 assert(getAlign() == Alignment && "Alignment representation error!"); 1482 } 1483 1484 //===----------------------------------------------------------------------===// 1485 // AtomicCmpXchgInst Implementation 1486 //===----------------------------------------------------------------------===// 1487 1488 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal, 1489 AtomicOrdering SuccessOrdering, 1490 AtomicOrdering FailureOrdering, 1491 SyncScope::ID SSID) { 1492 Op<0>() = Ptr; 1493 Op<1>() = Cmp; 1494 Op<2>() = NewVal; 1495 setSuccessOrdering(SuccessOrdering); 1496 setFailureOrdering(FailureOrdering); 1497 setSyncScopeID(SSID); 1498 1499 assert(getOperand(0) && getOperand(1) && getOperand(2) && 1500 "All operands must be non-null!"); 1501 assert(getOperand(0)->getType()->isPointerTy() && 1502 "Ptr must have pointer type!"); 1503 assert(getOperand(1)->getType() == 1504 cast<PointerType>(getOperand(0)->getType())->getElementType() 1505 && "Ptr must be a pointer to Cmp type!"); 1506 assert(getOperand(2)->getType() == 1507 cast<PointerType>(getOperand(0)->getType())->getElementType() 1508 && "Ptr must be a pointer to NewVal type!"); 1509 assert(SuccessOrdering != AtomicOrdering::NotAtomic && 1510 "AtomicCmpXchg instructions must be atomic!"); 1511 assert(FailureOrdering != AtomicOrdering::NotAtomic && 1512 "AtomicCmpXchg instructions must be atomic!"); 1513 assert(!isStrongerThan(FailureOrdering, SuccessOrdering) && 1514 "AtomicCmpXchg failure argument shall be no stronger than the success " 1515 "argument"); 1516 assert(FailureOrdering != AtomicOrdering::Release && 1517 FailureOrdering != AtomicOrdering::AcquireRelease && 1518 "AtomicCmpXchg failure ordering cannot include release semantics"); 1519 } 1520 1521 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1522 AtomicOrdering SuccessOrdering, 1523 AtomicOrdering FailureOrdering, 1524 SyncScope::ID SSID, 1525 Instruction *InsertBefore) 1526 : Instruction( 1527 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1528 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1529 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) { 1530 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID); 1531 } 1532 1533 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1534 AtomicOrdering SuccessOrdering, 1535 AtomicOrdering FailureOrdering, 1536 SyncScope::ID SSID, 1537 BasicBlock *InsertAtEnd) 1538 : Instruction( 1539 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1540 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1541 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) { 1542 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID); 1543 } 1544 1545 //===----------------------------------------------------------------------===// 1546 // AtomicRMWInst Implementation 1547 //===----------------------------------------------------------------------===// 1548 1549 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val, 1550 AtomicOrdering Ordering, 1551 SyncScope::ID SSID) { 1552 Op<0>() = Ptr; 1553 Op<1>() = Val; 1554 setOperation(Operation); 1555 setOrdering(Ordering); 1556 setSyncScopeID(SSID); 1557 1558 assert(getOperand(0) && getOperand(1) && 1559 "All operands must be non-null!"); 1560 assert(getOperand(0)->getType()->isPointerTy() && 1561 "Ptr must have pointer type!"); 1562 assert(getOperand(1)->getType() == 1563 cast<PointerType>(getOperand(0)->getType())->getElementType() 1564 && "Ptr must be a pointer to Val type!"); 1565 assert(Ordering != AtomicOrdering::NotAtomic && 1566 "AtomicRMW instructions must be atomic!"); 1567 } 1568 1569 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1570 AtomicOrdering Ordering, 1571 SyncScope::ID SSID, 1572 Instruction *InsertBefore) 1573 : Instruction(Val->getType(), AtomicRMW, 1574 OperandTraits<AtomicRMWInst>::op_begin(this), 1575 OperandTraits<AtomicRMWInst>::operands(this), 1576 InsertBefore) { 1577 Init(Operation, Ptr, Val, Ordering, SSID); 1578 } 1579 1580 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1581 AtomicOrdering Ordering, 1582 SyncScope::ID SSID, 1583 BasicBlock *InsertAtEnd) 1584 : Instruction(Val->getType(), AtomicRMW, 1585 OperandTraits<AtomicRMWInst>::op_begin(this), 1586 OperandTraits<AtomicRMWInst>::operands(this), 1587 InsertAtEnd) { 1588 Init(Operation, Ptr, Val, Ordering, SSID); 1589 } 1590 1591 StringRef AtomicRMWInst::getOperationName(BinOp Op) { 1592 switch (Op) { 1593 case AtomicRMWInst::Xchg: 1594 return "xchg"; 1595 case AtomicRMWInst::Add: 1596 return "add"; 1597 case AtomicRMWInst::Sub: 1598 return "sub"; 1599 case AtomicRMWInst::And: 1600 return "and"; 1601 case AtomicRMWInst::Nand: 1602 return "nand"; 1603 case AtomicRMWInst::Or: 1604 return "or"; 1605 case AtomicRMWInst::Xor: 1606 return "xor"; 1607 case AtomicRMWInst::Max: 1608 return "max"; 1609 case AtomicRMWInst::Min: 1610 return "min"; 1611 case AtomicRMWInst::UMax: 1612 return "umax"; 1613 case AtomicRMWInst::UMin: 1614 return "umin"; 1615 case AtomicRMWInst::FAdd: 1616 return "fadd"; 1617 case AtomicRMWInst::FSub: 1618 return "fsub"; 1619 case AtomicRMWInst::BAD_BINOP: 1620 return "<invalid operation>"; 1621 } 1622 1623 llvm_unreachable("invalid atomicrmw operation"); 1624 } 1625 1626 //===----------------------------------------------------------------------===// 1627 // FenceInst Implementation 1628 //===----------------------------------------------------------------------===// 1629 1630 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1631 SyncScope::ID SSID, 1632 Instruction *InsertBefore) 1633 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) { 1634 setOrdering(Ordering); 1635 setSyncScopeID(SSID); 1636 } 1637 1638 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1639 SyncScope::ID SSID, 1640 BasicBlock *InsertAtEnd) 1641 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) { 1642 setOrdering(Ordering); 1643 setSyncScopeID(SSID); 1644 } 1645 1646 //===----------------------------------------------------------------------===// 1647 // GetElementPtrInst Implementation 1648 //===----------------------------------------------------------------------===// 1649 1650 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList, 1651 const Twine &Name) { 1652 assert(getNumOperands() == 1 + IdxList.size() && 1653 "NumOperands not initialized?"); 1654 Op<0>() = Ptr; 1655 llvm::copy(IdxList, op_begin() + 1); 1656 setName(Name); 1657 } 1658 1659 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) 1660 : Instruction(GEPI.getType(), GetElementPtr, 1661 OperandTraits<GetElementPtrInst>::op_end(this) - 1662 GEPI.getNumOperands(), 1663 GEPI.getNumOperands()), 1664 SourceElementType(GEPI.SourceElementType), 1665 ResultElementType(GEPI.ResultElementType) { 1666 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin()); 1667 SubclassOptionalData = GEPI.SubclassOptionalData; 1668 } 1669 1670 Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, Value *Idx) { 1671 if (auto Struct = dyn_cast<StructType>(Ty)) { 1672 if (!Struct->indexValid(Idx)) 1673 return nullptr; 1674 return Struct->getTypeAtIndex(Idx); 1675 } 1676 if (!Idx->getType()->isIntOrIntVectorTy()) 1677 return nullptr; 1678 if (auto Array = dyn_cast<ArrayType>(Ty)) 1679 return Array->getElementType(); 1680 if (auto Vector = dyn_cast<VectorType>(Ty)) 1681 return Vector->getElementType(); 1682 return nullptr; 1683 } 1684 1685 Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, uint64_t Idx) { 1686 if (auto Struct = dyn_cast<StructType>(Ty)) { 1687 if (Idx >= Struct->getNumElements()) 1688 return nullptr; 1689 return Struct->getElementType(Idx); 1690 } 1691 if (auto Array = dyn_cast<ArrayType>(Ty)) 1692 return Array->getElementType(); 1693 if (auto Vector = dyn_cast<VectorType>(Ty)) 1694 return Vector->getElementType(); 1695 return nullptr; 1696 } 1697 1698 template <typename IndexTy> 1699 static Type *getIndexedTypeInternal(Type *Ty, ArrayRef<IndexTy> IdxList) { 1700 if (IdxList.empty()) 1701 return Ty; 1702 for (IndexTy V : IdxList.slice(1)) { 1703 Ty = GetElementPtrInst::getTypeAtIndex(Ty, V); 1704 if (!Ty) 1705 return Ty; 1706 } 1707 return Ty; 1708 } 1709 1710 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) { 1711 return getIndexedTypeInternal(Ty, IdxList); 1712 } 1713 1714 Type *GetElementPtrInst::getIndexedType(Type *Ty, 1715 ArrayRef<Constant *> IdxList) { 1716 return getIndexedTypeInternal(Ty, IdxList); 1717 } 1718 1719 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) { 1720 return getIndexedTypeInternal(Ty, IdxList); 1721 } 1722 1723 /// hasAllZeroIndices - Return true if all of the indices of this GEP are 1724 /// zeros. If so, the result pointer and the first operand have the same 1725 /// value, just potentially different types. 1726 bool GetElementPtrInst::hasAllZeroIndices() const { 1727 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1728 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { 1729 if (!CI->isZero()) return false; 1730 } else { 1731 return false; 1732 } 1733 } 1734 return true; 1735 } 1736 1737 /// hasAllConstantIndices - Return true if all of the indices of this GEP are 1738 /// constant integers. If so, the result pointer and the first operand have 1739 /// a constant offset between them. 1740 bool GetElementPtrInst::hasAllConstantIndices() const { 1741 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1742 if (!isa<ConstantInt>(getOperand(i))) 1743 return false; 1744 } 1745 return true; 1746 } 1747 1748 void GetElementPtrInst::setIsInBounds(bool B) { 1749 cast<GEPOperator>(this)->setIsInBounds(B); 1750 } 1751 1752 bool GetElementPtrInst::isInBounds() const { 1753 return cast<GEPOperator>(this)->isInBounds(); 1754 } 1755 1756 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL, 1757 APInt &Offset) const { 1758 // Delegate to the generic GEPOperator implementation. 1759 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset); 1760 } 1761 1762 //===----------------------------------------------------------------------===// 1763 // ExtractElementInst Implementation 1764 //===----------------------------------------------------------------------===// 1765 1766 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1767 const Twine &Name, 1768 Instruction *InsertBef) 1769 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1770 ExtractElement, 1771 OperandTraits<ExtractElementInst>::op_begin(this), 1772 2, InsertBef) { 1773 assert(isValidOperands(Val, Index) && 1774 "Invalid extractelement instruction operands!"); 1775 Op<0>() = Val; 1776 Op<1>() = Index; 1777 setName(Name); 1778 } 1779 1780 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1781 const Twine &Name, 1782 BasicBlock *InsertAE) 1783 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1784 ExtractElement, 1785 OperandTraits<ExtractElementInst>::op_begin(this), 1786 2, InsertAE) { 1787 assert(isValidOperands(Val, Index) && 1788 "Invalid extractelement instruction operands!"); 1789 1790 Op<0>() = Val; 1791 Op<1>() = Index; 1792 setName(Name); 1793 } 1794 1795 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { 1796 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy()) 1797 return false; 1798 return true; 1799 } 1800 1801 //===----------------------------------------------------------------------===// 1802 // InsertElementInst Implementation 1803 //===----------------------------------------------------------------------===// 1804 1805 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1806 const Twine &Name, 1807 Instruction *InsertBef) 1808 : Instruction(Vec->getType(), InsertElement, 1809 OperandTraits<InsertElementInst>::op_begin(this), 1810 3, InsertBef) { 1811 assert(isValidOperands(Vec, Elt, Index) && 1812 "Invalid insertelement instruction operands!"); 1813 Op<0>() = Vec; 1814 Op<1>() = Elt; 1815 Op<2>() = Index; 1816 setName(Name); 1817 } 1818 1819 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1820 const Twine &Name, 1821 BasicBlock *InsertAE) 1822 : Instruction(Vec->getType(), InsertElement, 1823 OperandTraits<InsertElementInst>::op_begin(this), 1824 3, InsertAE) { 1825 assert(isValidOperands(Vec, Elt, Index) && 1826 "Invalid insertelement instruction operands!"); 1827 1828 Op<0>() = Vec; 1829 Op<1>() = Elt; 1830 Op<2>() = Index; 1831 setName(Name); 1832 } 1833 1834 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 1835 const Value *Index) { 1836 if (!Vec->getType()->isVectorTy()) 1837 return false; // First operand of insertelement must be vector type. 1838 1839 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) 1840 return false;// Second operand of insertelement must be vector element type. 1841 1842 if (!Index->getType()->isIntegerTy()) 1843 return false; // Third operand of insertelement must be i32. 1844 return true; 1845 } 1846 1847 //===----------------------------------------------------------------------===// 1848 // ShuffleVectorInst Implementation 1849 //===----------------------------------------------------------------------===// 1850 1851 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1852 const Twine &Name, 1853 Instruction *InsertBefore) 1854 : Instruction( 1855 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1856 cast<VectorType>(Mask->getType())->getElementCount()), 1857 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1858 OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) { 1859 assert(isValidOperands(V1, V2, Mask) && 1860 "Invalid shuffle vector instruction operands!"); 1861 1862 Op<0>() = V1; 1863 Op<1>() = V2; 1864 SmallVector<int, 16> MaskArr; 1865 getShuffleMask(cast<Constant>(Mask), MaskArr); 1866 setShuffleMask(MaskArr); 1867 setName(Name); 1868 } 1869 1870 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1871 const Twine &Name, BasicBlock *InsertAtEnd) 1872 : Instruction( 1873 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1874 cast<VectorType>(Mask->getType())->getElementCount()), 1875 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1876 OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) { 1877 assert(isValidOperands(V1, V2, Mask) && 1878 "Invalid shuffle vector instruction operands!"); 1879 1880 Op<0>() = V1; 1881 Op<1>() = V2; 1882 SmallVector<int, 16> MaskArr; 1883 getShuffleMask(cast<Constant>(Mask), MaskArr); 1884 setShuffleMask(MaskArr); 1885 setName(Name); 1886 } 1887 1888 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, 1889 const Twine &Name, 1890 Instruction *InsertBefore) 1891 : Instruction( 1892 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1893 Mask.size(), isa<ScalableVectorType>(V1->getType())), 1894 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1895 OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) { 1896 assert(isValidOperands(V1, V2, Mask) && 1897 "Invalid shuffle vector instruction operands!"); 1898 Op<0>() = V1; 1899 Op<1>() = V2; 1900 setShuffleMask(Mask); 1901 setName(Name); 1902 } 1903 1904 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, 1905 const Twine &Name, BasicBlock *InsertAtEnd) 1906 : Instruction( 1907 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1908 Mask.size(), isa<ScalableVectorType>(V1->getType())), 1909 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1910 OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) { 1911 assert(isValidOperands(V1, V2, Mask) && 1912 "Invalid shuffle vector instruction operands!"); 1913 1914 Op<0>() = V1; 1915 Op<1>() = V2; 1916 setShuffleMask(Mask); 1917 setName(Name); 1918 } 1919 1920 void ShuffleVectorInst::commute() { 1921 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 1922 int NumMaskElts = ShuffleMask.size(); 1923 SmallVector<int, 16> NewMask(NumMaskElts); 1924 for (int i = 0; i != NumMaskElts; ++i) { 1925 int MaskElt = getMaskValue(i); 1926 if (MaskElt == UndefMaskElem) { 1927 NewMask[i] = UndefMaskElem; 1928 continue; 1929 } 1930 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask"); 1931 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts; 1932 NewMask[i] = MaskElt; 1933 } 1934 setShuffleMask(NewMask); 1935 Op<0>().swap(Op<1>()); 1936 } 1937 1938 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 1939 ArrayRef<int> Mask) { 1940 // V1 and V2 must be vectors of the same type. 1941 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType()) 1942 return false; 1943 1944 // Make sure the mask elements make sense. 1945 int V1Size = cast<VectorType>(V1->getType())->getElementCount().Min; 1946 for (int Elem : Mask) 1947 if (Elem != UndefMaskElem && Elem >= V1Size * 2) 1948 return false; 1949 1950 if (isa<ScalableVectorType>(V1->getType())) 1951 if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !is_splat(Mask)) 1952 return false; 1953 1954 return true; 1955 } 1956 1957 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 1958 const Value *Mask) { 1959 // V1 and V2 must be vectors of the same type. 1960 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType()) 1961 return false; 1962 1963 // Mask must be vector of i32, and must be the same kind of vector as the 1964 // input vectors 1965 auto *MaskTy = dyn_cast<VectorType>(Mask->getType()); 1966 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) || 1967 isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType())) 1968 return false; 1969 1970 // Check to see if Mask is valid. 1971 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask)) 1972 return true; 1973 1974 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) { 1975 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1976 for (Value *Op : MV->operands()) { 1977 if (auto *CI = dyn_cast<ConstantInt>(Op)) { 1978 if (CI->uge(V1Size*2)) 1979 return false; 1980 } else if (!isa<UndefValue>(Op)) { 1981 return false; 1982 } 1983 } 1984 return true; 1985 } 1986 1987 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 1988 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1989 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i) 1990 if (CDS->getElementAsInteger(i) >= V1Size*2) 1991 return false; 1992 return true; 1993 } 1994 1995 return false; 1996 } 1997 1998 void ShuffleVectorInst::getShuffleMask(const Constant *Mask, 1999 SmallVectorImpl<int> &Result) { 2000 unsigned NumElts = cast<VectorType>(Mask->getType())->getElementCount().Min; 2001 if (isa<ConstantAggregateZero>(Mask)) { 2002 Result.resize(NumElts, 0); 2003 return; 2004 } 2005 Result.reserve(NumElts); 2006 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 2007 for (unsigned i = 0; i != NumElts; ++i) 2008 Result.push_back(CDS->getElementAsInteger(i)); 2009 return; 2010 } 2011 for (unsigned i = 0; i != NumElts; ++i) { 2012 Constant *C = Mask->getAggregateElement(i); 2013 Result.push_back(isa<UndefValue>(C) ? -1 : 2014 cast<ConstantInt>(C)->getZExtValue()); 2015 } 2016 } 2017 2018 void ShuffleVectorInst::setShuffleMask(ArrayRef<int> Mask) { 2019 ShuffleMask.assign(Mask.begin(), Mask.end()); 2020 ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType()); 2021 } 2022 Constant *ShuffleVectorInst::convertShuffleMaskForBitcode(ArrayRef<int> Mask, 2023 Type *ResultTy) { 2024 Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext()); 2025 if (isa<ScalableVectorType>(ResultTy)) { 2026 assert(is_splat(Mask) && "Unexpected shuffle"); 2027 Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true); 2028 if (Mask[0] == 0) 2029 return Constant::getNullValue(VecTy); 2030 return UndefValue::get(VecTy); 2031 } 2032 SmallVector<Constant *, 16> MaskConst; 2033 for (int Elem : Mask) { 2034 if (Elem == UndefMaskElem) 2035 MaskConst.push_back(UndefValue::get(Int32Ty)); 2036 else 2037 MaskConst.push_back(ConstantInt::get(Int32Ty, Elem)); 2038 } 2039 return ConstantVector::get(MaskConst); 2040 } 2041 2042 static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) { 2043 assert(!Mask.empty() && "Shuffle mask must contain elements"); 2044 bool UsesLHS = false; 2045 bool UsesRHS = false; 2046 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) { 2047 if (Mask[i] == -1) 2048 continue; 2049 assert(Mask[i] >= 0 && Mask[i] < (NumOpElts * 2) && 2050 "Out-of-bounds shuffle mask element"); 2051 UsesLHS |= (Mask[i] < NumOpElts); 2052 UsesRHS |= (Mask[i] >= NumOpElts); 2053 if (UsesLHS && UsesRHS) 2054 return false; 2055 } 2056 // Allow for degenerate case: completely undef mask means neither source is used. 2057 return UsesLHS || UsesRHS; 2058 } 2059 2060 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) { 2061 // We don't have vector operand size information, so assume operands are the 2062 // same size as the mask. 2063 return isSingleSourceMaskImpl(Mask, Mask.size()); 2064 } 2065 2066 static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) { 2067 if (!isSingleSourceMaskImpl(Mask, NumOpElts)) 2068 return false; 2069 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) { 2070 if (Mask[i] == -1) 2071 continue; 2072 if (Mask[i] != i && Mask[i] != (NumOpElts + i)) 2073 return false; 2074 } 2075 return true; 2076 } 2077 2078 bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) { 2079 // We don't have vector operand size information, so assume operands are the 2080 // same size as the mask. 2081 return isIdentityMaskImpl(Mask, Mask.size()); 2082 } 2083 2084 bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) { 2085 if (!isSingleSourceMask(Mask)) 2086 return false; 2087 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 2088 if (Mask[i] == -1) 2089 continue; 2090 if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i)) 2091 return false; 2092 } 2093 return true; 2094 } 2095 2096 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) { 2097 if (!isSingleSourceMask(Mask)) 2098 return false; 2099 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 2100 if (Mask[i] == -1) 2101 continue; 2102 if (Mask[i] != 0 && Mask[i] != NumElts) 2103 return false; 2104 } 2105 return true; 2106 } 2107 2108 bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) { 2109 // Select is differentiated from identity. It requires using both sources. 2110 if (isSingleSourceMask(Mask)) 2111 return false; 2112 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 2113 if (Mask[i] == -1) 2114 continue; 2115 if (Mask[i] != i && Mask[i] != (NumElts + i)) 2116 return false; 2117 } 2118 return true; 2119 } 2120 2121 bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) { 2122 // Example masks that will return true: 2123 // v1 = <a, b, c, d> 2124 // v2 = <e, f, g, h> 2125 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g> 2126 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h> 2127 2128 // 1. The number of elements in the mask must be a power-of-2 and at least 2. 2129 int NumElts = Mask.size(); 2130 if (NumElts < 2 || !isPowerOf2_32(NumElts)) 2131 return false; 2132 2133 // 2. The first element of the mask must be either a 0 or a 1. 2134 if (Mask[0] != 0 && Mask[0] != 1) 2135 return false; 2136 2137 // 3. The difference between the first 2 elements must be equal to the 2138 // number of elements in the mask. 2139 if ((Mask[1] - Mask[0]) != NumElts) 2140 return false; 2141 2142 // 4. The difference between consecutive even-numbered and odd-numbered 2143 // elements must be equal to 2. 2144 for (int i = 2; i < NumElts; ++i) { 2145 int MaskEltVal = Mask[i]; 2146 if (MaskEltVal == -1) 2147 return false; 2148 int MaskEltPrevVal = Mask[i - 2]; 2149 if (MaskEltVal - MaskEltPrevVal != 2) 2150 return false; 2151 } 2152 return true; 2153 } 2154 2155 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask, 2156 int NumSrcElts, int &Index) { 2157 // Must extract from a single source. 2158 if (!isSingleSourceMaskImpl(Mask, NumSrcElts)) 2159 return false; 2160 2161 // Must be smaller (else this is an Identity shuffle). 2162 if (NumSrcElts <= (int)Mask.size()) 2163 return false; 2164 2165 // Find start of extraction, accounting that we may start with an UNDEF. 2166 int SubIndex = -1; 2167 for (int i = 0, e = Mask.size(); i != e; ++i) { 2168 int M = Mask[i]; 2169 if (M < 0) 2170 continue; 2171 int Offset = (M % NumSrcElts) - i; 2172 if (0 <= SubIndex && SubIndex != Offset) 2173 return false; 2174 SubIndex = Offset; 2175 } 2176 2177 if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) { 2178 Index = SubIndex; 2179 return true; 2180 } 2181 return false; 2182 } 2183 2184 bool ShuffleVectorInst::isIdentityWithPadding() const { 2185 if (isa<UndefValue>(Op<2>())) 2186 return false; 2187 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 2188 int NumMaskElts = cast<VectorType>(getType())->getNumElements(); 2189 if (NumMaskElts <= NumOpElts) 2190 return false; 2191 2192 // The first part of the mask must choose elements from exactly 1 source op. 2193 ArrayRef<int> Mask = getShuffleMask(); 2194 if (!isIdentityMaskImpl(Mask, NumOpElts)) 2195 return false; 2196 2197 // All extending must be with undef elements. 2198 for (int i = NumOpElts; i < NumMaskElts; ++i) 2199 if (Mask[i] != -1) 2200 return false; 2201 2202 return true; 2203 } 2204 2205 bool ShuffleVectorInst::isIdentityWithExtract() const { 2206 if (isa<UndefValue>(Op<2>())) 2207 return false; 2208 2209 // FIXME: Not currently possible to express a shuffle mask for a scalable 2210 // vector for this case 2211 if (isa<ScalableVectorType>(getType())) 2212 return false; 2213 2214 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); 2215 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements(); 2216 if (NumMaskElts >= NumOpElts) 2217 return false; 2218 2219 return isIdentityMaskImpl(getShuffleMask(), NumOpElts); 2220 } 2221 2222 bool ShuffleVectorInst::isConcat() const { 2223 // Vector concatenation is differentiated from identity with padding. 2224 if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()) || 2225 isa<UndefValue>(Op<2>())) 2226 return false; 2227 2228 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 2229 int NumMaskElts = getType()->getNumElements(); 2230 if (NumMaskElts != NumOpElts * 2) 2231 return false; 2232 2233 // Use the mask length rather than the operands' vector lengths here. We 2234 // already know that the shuffle returns a vector twice as long as the inputs, 2235 // and neither of the inputs are undef vectors. If the mask picks consecutive 2236 // elements from both inputs, then this is a concatenation of the inputs. 2237 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts); 2238 } 2239 2240 //===----------------------------------------------------------------------===// 2241 // InsertValueInst Class 2242 //===----------------------------------------------------------------------===// 2243 2244 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 2245 const Twine &Name) { 2246 assert(getNumOperands() == 2 && "NumOperands not initialized?"); 2247 2248 // There's no fundamental reason why we require at least one index 2249 // (other than weirdness with &*IdxBegin being invalid; see 2250 // getelementptr's init routine for example). But there's no 2251 // present need to support it. 2252 assert(!Idxs.empty() && "InsertValueInst must have at least one index"); 2253 2254 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) == 2255 Val->getType() && "Inserted value must match indexed type!"); 2256 Op<0>() = Agg; 2257 Op<1>() = Val; 2258 2259 Indices.append(Idxs.begin(), Idxs.end()); 2260 setName(Name); 2261 } 2262 2263 InsertValueInst::InsertValueInst(const InsertValueInst &IVI) 2264 : Instruction(IVI.getType(), InsertValue, 2265 OperandTraits<InsertValueInst>::op_begin(this), 2), 2266 Indices(IVI.Indices) { 2267 Op<0>() = IVI.getOperand(0); 2268 Op<1>() = IVI.getOperand(1); 2269 SubclassOptionalData = IVI.SubclassOptionalData; 2270 } 2271 2272 //===----------------------------------------------------------------------===// 2273 // ExtractValueInst Class 2274 //===----------------------------------------------------------------------===// 2275 2276 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) { 2277 assert(getNumOperands() == 1 && "NumOperands not initialized?"); 2278 2279 // There's no fundamental reason why we require at least one index. 2280 // But there's no present need to support it. 2281 assert(!Idxs.empty() && "ExtractValueInst must have at least one index"); 2282 2283 Indices.append(Idxs.begin(), Idxs.end()); 2284 setName(Name); 2285 } 2286 2287 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) 2288 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), 2289 Indices(EVI.Indices) { 2290 SubclassOptionalData = EVI.SubclassOptionalData; 2291 } 2292 2293 // getIndexedType - Returns the type of the element that would be extracted 2294 // with an extractvalue instruction with the specified parameters. 2295 // 2296 // A null type is returned if the indices are invalid for the specified 2297 // pointer type. 2298 // 2299 Type *ExtractValueInst::getIndexedType(Type *Agg, 2300 ArrayRef<unsigned> Idxs) { 2301 for (unsigned Index : Idxs) { 2302 // We can't use CompositeType::indexValid(Index) here. 2303 // indexValid() always returns true for arrays because getelementptr allows 2304 // out-of-bounds indices. Since we don't allow those for extractvalue and 2305 // insertvalue we need to check array indexing manually. 2306 // Since the only other types we can index into are struct types it's just 2307 // as easy to check those manually as well. 2308 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) { 2309 if (Index >= AT->getNumElements()) 2310 return nullptr; 2311 Agg = AT->getElementType(); 2312 } else if (StructType *ST = dyn_cast<StructType>(Agg)) { 2313 if (Index >= ST->getNumElements()) 2314 return nullptr; 2315 Agg = ST->getElementType(Index); 2316 } else { 2317 // Not a valid type to index into. 2318 return nullptr; 2319 } 2320 } 2321 return const_cast<Type*>(Agg); 2322 } 2323 2324 //===----------------------------------------------------------------------===// 2325 // UnaryOperator Class 2326 //===----------------------------------------------------------------------===// 2327 2328 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2329 Type *Ty, const Twine &Name, 2330 Instruction *InsertBefore) 2331 : UnaryInstruction(Ty, iType, S, InsertBefore) { 2332 Op<0>() = S; 2333 setName(Name); 2334 AssertOK(); 2335 } 2336 2337 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2338 Type *Ty, const Twine &Name, 2339 BasicBlock *InsertAtEnd) 2340 : UnaryInstruction(Ty, iType, S, InsertAtEnd) { 2341 Op<0>() = S; 2342 setName(Name); 2343 AssertOK(); 2344 } 2345 2346 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2347 const Twine &Name, 2348 Instruction *InsertBefore) { 2349 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore); 2350 } 2351 2352 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2353 const Twine &Name, 2354 BasicBlock *InsertAtEnd) { 2355 UnaryOperator *Res = Create(Op, S, Name); 2356 InsertAtEnd->getInstList().push_back(Res); 2357 return Res; 2358 } 2359 2360 void UnaryOperator::AssertOK() { 2361 Value *LHS = getOperand(0); 2362 (void)LHS; // Silence warnings. 2363 #ifndef NDEBUG 2364 switch (getOpcode()) { 2365 case FNeg: 2366 assert(getType() == LHS->getType() && 2367 "Unary operation should return same type as operand!"); 2368 assert(getType()->isFPOrFPVectorTy() && 2369 "Tried to create a floating-point operation on a " 2370 "non-floating-point type!"); 2371 break; 2372 default: llvm_unreachable("Invalid opcode provided"); 2373 } 2374 #endif 2375 } 2376 2377 //===----------------------------------------------------------------------===// 2378 // BinaryOperator Class 2379 //===----------------------------------------------------------------------===// 2380 2381 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2382 Type *Ty, const Twine &Name, 2383 Instruction *InsertBefore) 2384 : Instruction(Ty, iType, 2385 OperandTraits<BinaryOperator>::op_begin(this), 2386 OperandTraits<BinaryOperator>::operands(this), 2387 InsertBefore) { 2388 Op<0>() = S1; 2389 Op<1>() = S2; 2390 setName(Name); 2391 AssertOK(); 2392 } 2393 2394 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2395 Type *Ty, const Twine &Name, 2396 BasicBlock *InsertAtEnd) 2397 : Instruction(Ty, iType, 2398 OperandTraits<BinaryOperator>::op_begin(this), 2399 OperandTraits<BinaryOperator>::operands(this), 2400 InsertAtEnd) { 2401 Op<0>() = S1; 2402 Op<1>() = S2; 2403 setName(Name); 2404 AssertOK(); 2405 } 2406 2407 void BinaryOperator::AssertOK() { 2408 Value *LHS = getOperand(0), *RHS = getOperand(1); 2409 (void)LHS; (void)RHS; // Silence warnings. 2410 assert(LHS->getType() == RHS->getType() && 2411 "Binary operator operand types must match!"); 2412 #ifndef NDEBUG 2413 switch (getOpcode()) { 2414 case Add: case Sub: 2415 case Mul: 2416 assert(getType() == LHS->getType() && 2417 "Arithmetic operation should return same type as operands!"); 2418 assert(getType()->isIntOrIntVectorTy() && 2419 "Tried to create an integer operation on a non-integer type!"); 2420 break; 2421 case FAdd: case FSub: 2422 case FMul: 2423 assert(getType() == LHS->getType() && 2424 "Arithmetic operation should return same type as operands!"); 2425 assert(getType()->isFPOrFPVectorTy() && 2426 "Tried to create a floating-point operation on a " 2427 "non-floating-point type!"); 2428 break; 2429 case UDiv: 2430 case SDiv: 2431 assert(getType() == LHS->getType() && 2432 "Arithmetic operation should return same type as operands!"); 2433 assert(getType()->isIntOrIntVectorTy() && 2434 "Incorrect operand type (not integer) for S/UDIV"); 2435 break; 2436 case FDiv: 2437 assert(getType() == LHS->getType() && 2438 "Arithmetic operation should return same type as operands!"); 2439 assert(getType()->isFPOrFPVectorTy() && 2440 "Incorrect operand type (not floating point) for FDIV"); 2441 break; 2442 case URem: 2443 case SRem: 2444 assert(getType() == LHS->getType() && 2445 "Arithmetic operation should return same type as operands!"); 2446 assert(getType()->isIntOrIntVectorTy() && 2447 "Incorrect operand type (not integer) for S/UREM"); 2448 break; 2449 case FRem: 2450 assert(getType() == LHS->getType() && 2451 "Arithmetic operation should return same type as operands!"); 2452 assert(getType()->isFPOrFPVectorTy() && 2453 "Incorrect operand type (not floating point) for FREM"); 2454 break; 2455 case Shl: 2456 case LShr: 2457 case AShr: 2458 assert(getType() == LHS->getType() && 2459 "Shift operation should return same type as operands!"); 2460 assert(getType()->isIntOrIntVectorTy() && 2461 "Tried to create a shift operation on a non-integral type!"); 2462 break; 2463 case And: case Or: 2464 case Xor: 2465 assert(getType() == LHS->getType() && 2466 "Logical operation should return same type as operands!"); 2467 assert(getType()->isIntOrIntVectorTy() && 2468 "Tried to create a logical operation on a non-integral type!"); 2469 break; 2470 default: llvm_unreachable("Invalid opcode provided"); 2471 } 2472 #endif 2473 } 2474 2475 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2476 const Twine &Name, 2477 Instruction *InsertBefore) { 2478 assert(S1->getType() == S2->getType() && 2479 "Cannot create binary operator with two operands of differing type!"); 2480 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); 2481 } 2482 2483 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2484 const Twine &Name, 2485 BasicBlock *InsertAtEnd) { 2486 BinaryOperator *Res = Create(Op, S1, S2, Name); 2487 InsertAtEnd->getInstList().push_back(Res); 2488 return Res; 2489 } 2490 2491 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2492 Instruction *InsertBefore) { 2493 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2494 return new BinaryOperator(Instruction::Sub, 2495 zero, Op, 2496 Op->getType(), Name, InsertBefore); 2497 } 2498 2499 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2500 BasicBlock *InsertAtEnd) { 2501 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2502 return new BinaryOperator(Instruction::Sub, 2503 zero, Op, 2504 Op->getType(), Name, InsertAtEnd); 2505 } 2506 2507 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2508 Instruction *InsertBefore) { 2509 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2510 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore); 2511 } 2512 2513 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2514 BasicBlock *InsertAtEnd) { 2515 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2516 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd); 2517 } 2518 2519 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2520 Instruction *InsertBefore) { 2521 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2522 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore); 2523 } 2524 2525 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2526 BasicBlock *InsertAtEnd) { 2527 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2528 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd); 2529 } 2530 2531 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2532 Instruction *InsertBefore) { 2533 Constant *C = Constant::getAllOnesValue(Op->getType()); 2534 return new BinaryOperator(Instruction::Xor, Op, C, 2535 Op->getType(), Name, InsertBefore); 2536 } 2537 2538 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2539 BasicBlock *InsertAtEnd) { 2540 Constant *AllOnes = Constant::getAllOnesValue(Op->getType()); 2541 return new BinaryOperator(Instruction::Xor, Op, AllOnes, 2542 Op->getType(), Name, InsertAtEnd); 2543 } 2544 2545 // Exchange the two operands to this instruction. This instruction is safe to 2546 // use on any binary instruction and does not modify the semantics of the 2547 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode 2548 // is changed. 2549 bool BinaryOperator::swapOperands() { 2550 if (!isCommutative()) 2551 return true; // Can't commute operands 2552 Op<0>().swap(Op<1>()); 2553 return false; 2554 } 2555 2556 //===----------------------------------------------------------------------===// 2557 // FPMathOperator Class 2558 //===----------------------------------------------------------------------===// 2559 2560 float FPMathOperator::getFPAccuracy() const { 2561 const MDNode *MD = 2562 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath); 2563 if (!MD) 2564 return 0.0; 2565 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0)); 2566 return Accuracy->getValueAPF().convertToFloat(); 2567 } 2568 2569 //===----------------------------------------------------------------------===// 2570 // CastInst Class 2571 //===----------------------------------------------------------------------===// 2572 2573 // Just determine if this cast only deals with integral->integral conversion. 2574 bool CastInst::isIntegerCast() const { 2575 switch (getOpcode()) { 2576 default: return false; 2577 case Instruction::ZExt: 2578 case Instruction::SExt: 2579 case Instruction::Trunc: 2580 return true; 2581 case Instruction::BitCast: 2582 return getOperand(0)->getType()->isIntegerTy() && 2583 getType()->isIntegerTy(); 2584 } 2585 } 2586 2587 bool CastInst::isLosslessCast() const { 2588 // Only BitCast can be lossless, exit fast if we're not BitCast 2589 if (getOpcode() != Instruction::BitCast) 2590 return false; 2591 2592 // Identity cast is always lossless 2593 Type *SrcTy = getOperand(0)->getType(); 2594 Type *DstTy = getType(); 2595 if (SrcTy == DstTy) 2596 return true; 2597 2598 // Pointer to pointer is always lossless. 2599 if (SrcTy->isPointerTy()) 2600 return DstTy->isPointerTy(); 2601 return false; // Other types have no identity values 2602 } 2603 2604 /// This function determines if the CastInst does not require any bits to be 2605 /// changed in order to effect the cast. Essentially, it identifies cases where 2606 /// no code gen is necessary for the cast, hence the name no-op cast. For 2607 /// example, the following are all no-op casts: 2608 /// # bitcast i32* %x to i8* 2609 /// # bitcast <2 x i32> %x to <4 x i16> 2610 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only 2611 /// Determine if the described cast is a no-op. 2612 bool CastInst::isNoopCast(Instruction::CastOps Opcode, 2613 Type *SrcTy, 2614 Type *DestTy, 2615 const DataLayout &DL) { 2616 switch (Opcode) { 2617 default: llvm_unreachable("Invalid CastOp"); 2618 case Instruction::Trunc: 2619 case Instruction::ZExt: 2620 case Instruction::SExt: 2621 case Instruction::FPTrunc: 2622 case Instruction::FPExt: 2623 case Instruction::UIToFP: 2624 case Instruction::SIToFP: 2625 case Instruction::FPToUI: 2626 case Instruction::FPToSI: 2627 case Instruction::AddrSpaceCast: 2628 // TODO: Target informations may give a more accurate answer here. 2629 return false; 2630 case Instruction::BitCast: 2631 return true; // BitCast never modifies bits. 2632 case Instruction::PtrToInt: 2633 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() == 2634 DestTy->getScalarSizeInBits(); 2635 case Instruction::IntToPtr: 2636 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() == 2637 SrcTy->getScalarSizeInBits(); 2638 } 2639 } 2640 2641 bool CastInst::isNoopCast(const DataLayout &DL) const { 2642 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL); 2643 } 2644 2645 /// This function determines if a pair of casts can be eliminated and what 2646 /// opcode should be used in the elimination. This assumes that there are two 2647 /// instructions like this: 2648 /// * %F = firstOpcode SrcTy %x to MidTy 2649 /// * %S = secondOpcode MidTy %F to DstTy 2650 /// The function returns a resultOpcode so these two casts can be replaced with: 2651 /// * %Replacement = resultOpcode %SrcTy %x to DstTy 2652 /// If no such cast is permitted, the function returns 0. 2653 unsigned CastInst::isEliminableCastPair( 2654 Instruction::CastOps firstOp, Instruction::CastOps secondOp, 2655 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, 2656 Type *DstIntPtrTy) { 2657 // Define the 144 possibilities for these two cast instructions. The values 2658 // in this matrix determine what to do in a given situation and select the 2659 // case in the switch below. The rows correspond to firstOp, the columns 2660 // correspond to secondOp. In looking at the table below, keep in mind 2661 // the following cast properties: 2662 // 2663 // Size Compare Source Destination 2664 // Operator Src ? Size Type Sign Type Sign 2665 // -------- ------------ ------------------- --------------------- 2666 // TRUNC > Integer Any Integral Any 2667 // ZEXT < Integral Unsigned Integer Any 2668 // SEXT < Integral Signed Integer Any 2669 // FPTOUI n/a FloatPt n/a Integral Unsigned 2670 // FPTOSI n/a FloatPt n/a Integral Signed 2671 // UITOFP n/a Integral Unsigned FloatPt n/a 2672 // SITOFP n/a Integral Signed FloatPt n/a 2673 // FPTRUNC > FloatPt n/a FloatPt n/a 2674 // FPEXT < FloatPt n/a FloatPt n/a 2675 // PTRTOINT n/a Pointer n/a Integral Unsigned 2676 // INTTOPTR n/a Integral Unsigned Pointer n/a 2677 // BITCAST = FirstClass n/a FirstClass n/a 2678 // ADDRSPCST n/a Pointer n/a Pointer n/a 2679 // 2680 // NOTE: some transforms are safe, but we consider them to be non-profitable. 2681 // For example, we could merge "fptoui double to i32" + "zext i32 to i64", 2682 // into "fptoui double to i64", but this loses information about the range 2683 // of the produced value (we no longer know the top-part is all zeros). 2684 // Further this conversion is often much more expensive for typical hardware, 2685 // and causes issues when building libgcc. We disallow fptosi+sext for the 2686 // same reason. 2687 const unsigned numCastOps = 2688 Instruction::CastOpsEnd - Instruction::CastOpsBegin; 2689 static const uint8_t CastResults[numCastOps][numCastOps] = { 2690 // T F F U S F F P I B A -+ 2691 // R Z S P P I I T P 2 N T S | 2692 // U E E 2 2 2 2 R E I T C C +- secondOp 2693 // N X X U S F F N X N 2 V V | 2694 // C T T I I P P C T T P T T -+ 2695 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+ 2696 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt | 2697 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt | 2698 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI | 2699 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI | 2700 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp 2701 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP | 2702 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc | 2703 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt | 2704 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt | 2705 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr | 2706 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast | 2707 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+ 2708 }; 2709 2710 // TODO: This logic could be encoded into the table above and handled in the 2711 // switch below. 2712 // If either of the casts are a bitcast from scalar to vector, disallow the 2713 // merging. However, any pair of bitcasts are allowed. 2714 bool IsFirstBitcast = (firstOp == Instruction::BitCast); 2715 bool IsSecondBitcast = (secondOp == Instruction::BitCast); 2716 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast; 2717 2718 // Check if any of the casts convert scalars <-> vectors. 2719 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) || 2720 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy))) 2721 if (!AreBothBitcasts) 2722 return 0; 2723 2724 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] 2725 [secondOp-Instruction::CastOpsBegin]; 2726 switch (ElimCase) { 2727 case 0: 2728 // Categorically disallowed. 2729 return 0; 2730 case 1: 2731 // Allowed, use first cast's opcode. 2732 return firstOp; 2733 case 2: 2734 // Allowed, use second cast's opcode. 2735 return secondOp; 2736 case 3: 2737 // No-op cast in second op implies firstOp as long as the DestTy 2738 // is integer and we are not converting between a vector and a 2739 // non-vector type. 2740 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy()) 2741 return firstOp; 2742 return 0; 2743 case 4: 2744 // No-op cast in second op implies firstOp as long as the DestTy 2745 // is floating point. 2746 if (DstTy->isFloatingPointTy()) 2747 return firstOp; 2748 return 0; 2749 case 5: 2750 // No-op cast in first op implies secondOp as long as the SrcTy 2751 // is an integer. 2752 if (SrcTy->isIntegerTy()) 2753 return secondOp; 2754 return 0; 2755 case 6: 2756 // No-op cast in first op implies secondOp as long as the SrcTy 2757 // is a floating point. 2758 if (SrcTy->isFloatingPointTy()) 2759 return secondOp; 2760 return 0; 2761 case 7: { 2762 // Cannot simplify if address spaces are different! 2763 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2764 return 0; 2765 2766 unsigned MidSize = MidTy->getScalarSizeInBits(); 2767 // We can still fold this without knowing the actual sizes as long we 2768 // know that the intermediate pointer is the largest possible 2769 // pointer size. 2770 // FIXME: Is this always true? 2771 if (MidSize == 64) 2772 return Instruction::BitCast; 2773 2774 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size. 2775 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy) 2776 return 0; 2777 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits(); 2778 if (MidSize >= PtrSize) 2779 return Instruction::BitCast; 2780 return 0; 2781 } 2782 case 8: { 2783 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size 2784 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) 2785 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) 2786 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2787 unsigned DstSize = DstTy->getScalarSizeInBits(); 2788 if (SrcSize == DstSize) 2789 return Instruction::BitCast; 2790 else if (SrcSize < DstSize) 2791 return firstOp; 2792 return secondOp; 2793 } 2794 case 9: 2795 // zext, sext -> zext, because sext can't sign extend after zext 2796 return Instruction::ZExt; 2797 case 11: { 2798 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize 2799 if (!MidIntPtrTy) 2800 return 0; 2801 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits(); 2802 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2803 unsigned DstSize = DstTy->getScalarSizeInBits(); 2804 if (SrcSize <= PtrSize && SrcSize == DstSize) 2805 return Instruction::BitCast; 2806 return 0; 2807 } 2808 case 12: 2809 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS 2810 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS 2811 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2812 return Instruction::AddrSpaceCast; 2813 return Instruction::BitCast; 2814 case 13: 2815 // FIXME: this state can be merged with (1), but the following assert 2816 // is useful to check the correcteness of the sequence due to semantic 2817 // change of bitcast. 2818 assert( 2819 SrcTy->isPtrOrPtrVectorTy() && 2820 MidTy->isPtrOrPtrVectorTy() && 2821 DstTy->isPtrOrPtrVectorTy() && 2822 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() && 2823 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2824 "Illegal addrspacecast, bitcast sequence!"); 2825 // Allowed, use first cast's opcode 2826 return firstOp; 2827 case 14: 2828 // bitcast, addrspacecast -> addrspacecast if the element type of 2829 // bitcast's source is the same as that of addrspacecast's destination. 2830 if (SrcTy->getScalarType()->getPointerElementType() == 2831 DstTy->getScalarType()->getPointerElementType()) 2832 return Instruction::AddrSpaceCast; 2833 return 0; 2834 case 15: 2835 // FIXME: this state can be merged with (1), but the following assert 2836 // is useful to check the correcteness of the sequence due to semantic 2837 // change of bitcast. 2838 assert( 2839 SrcTy->isIntOrIntVectorTy() && 2840 MidTy->isPtrOrPtrVectorTy() && 2841 DstTy->isPtrOrPtrVectorTy() && 2842 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2843 "Illegal inttoptr, bitcast sequence!"); 2844 // Allowed, use first cast's opcode 2845 return firstOp; 2846 case 16: 2847 // FIXME: this state can be merged with (2), but the following assert 2848 // is useful to check the correcteness of the sequence due to semantic 2849 // change of bitcast. 2850 assert( 2851 SrcTy->isPtrOrPtrVectorTy() && 2852 MidTy->isPtrOrPtrVectorTy() && 2853 DstTy->isIntOrIntVectorTy() && 2854 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() && 2855 "Illegal bitcast, ptrtoint sequence!"); 2856 // Allowed, use second cast's opcode 2857 return secondOp; 2858 case 17: 2859 // (sitofp (zext x)) -> (uitofp x) 2860 return Instruction::UIToFP; 2861 case 99: 2862 // Cast combination can't happen (error in input). This is for all cases 2863 // where the MidTy is not the same for the two cast instructions. 2864 llvm_unreachable("Invalid Cast Combination"); 2865 default: 2866 llvm_unreachable("Error in CastResults table!!!"); 2867 } 2868 } 2869 2870 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2871 const Twine &Name, Instruction *InsertBefore) { 2872 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2873 // Construct and return the appropriate CastInst subclass 2874 switch (op) { 2875 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); 2876 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); 2877 case SExt: return new SExtInst (S, Ty, Name, InsertBefore); 2878 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); 2879 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); 2880 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); 2881 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); 2882 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); 2883 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); 2884 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); 2885 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); 2886 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); 2887 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore); 2888 default: llvm_unreachable("Invalid opcode provided"); 2889 } 2890 } 2891 2892 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2893 const Twine &Name, BasicBlock *InsertAtEnd) { 2894 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2895 // Construct and return the appropriate CastInst subclass 2896 switch (op) { 2897 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); 2898 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); 2899 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); 2900 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); 2901 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); 2902 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); 2903 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); 2904 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); 2905 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); 2906 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); 2907 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); 2908 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); 2909 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd); 2910 default: llvm_unreachable("Invalid opcode provided"); 2911 } 2912 } 2913 2914 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2915 const Twine &Name, 2916 Instruction *InsertBefore) { 2917 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2918 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2919 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); 2920 } 2921 2922 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2923 const Twine &Name, 2924 BasicBlock *InsertAtEnd) { 2925 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2926 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2927 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); 2928 } 2929 2930 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2931 const Twine &Name, 2932 Instruction *InsertBefore) { 2933 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2934 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2935 return Create(Instruction::SExt, S, Ty, Name, InsertBefore); 2936 } 2937 2938 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2939 const Twine &Name, 2940 BasicBlock *InsertAtEnd) { 2941 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2942 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2943 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); 2944 } 2945 2946 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2947 const Twine &Name, 2948 Instruction *InsertBefore) { 2949 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2950 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2951 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); 2952 } 2953 2954 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2955 const Twine &Name, 2956 BasicBlock *InsertAtEnd) { 2957 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2958 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2959 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); 2960 } 2961 2962 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2963 const Twine &Name, 2964 BasicBlock *InsertAtEnd) { 2965 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2966 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2967 "Invalid cast"); 2968 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2969 assert((!Ty->isVectorTy() || 2970 cast<VectorType>(Ty)->getNumElements() == 2971 cast<VectorType>(S->getType())->getNumElements()) && 2972 "Invalid cast"); 2973 2974 if (Ty->isIntOrIntVectorTy()) 2975 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); 2976 2977 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd); 2978 } 2979 2980 /// Create a BitCast or a PtrToInt cast instruction 2981 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2982 const Twine &Name, 2983 Instruction *InsertBefore) { 2984 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2985 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2986 "Invalid cast"); 2987 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2988 assert((!Ty->isVectorTy() || 2989 cast<VectorType>(Ty)->getNumElements() == 2990 cast<VectorType>(S->getType())->getNumElements()) && 2991 "Invalid cast"); 2992 2993 if (Ty->isIntOrIntVectorTy()) 2994 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2995 2996 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore); 2997 } 2998 2999 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 3000 Value *S, Type *Ty, 3001 const Twine &Name, 3002 BasicBlock *InsertAtEnd) { 3003 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 3004 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 3005 3006 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 3007 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd); 3008 3009 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 3010 } 3011 3012 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 3013 Value *S, Type *Ty, 3014 const Twine &Name, 3015 Instruction *InsertBefore) { 3016 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 3017 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 3018 3019 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 3020 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore); 3021 3022 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3023 } 3024 3025 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty, 3026 const Twine &Name, 3027 Instruction *InsertBefore) { 3028 if (S->getType()->isPointerTy() && Ty->isIntegerTy()) 3029 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 3030 if (S->getType()->isIntegerTy() && Ty->isPointerTy()) 3031 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore); 3032 3033 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3034 } 3035 3036 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 3037 bool isSigned, const Twine &Name, 3038 Instruction *InsertBefore) { 3039 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 3040 "Invalid integer cast"); 3041 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3042 unsigned DstBits = Ty->getScalarSizeInBits(); 3043 Instruction::CastOps opcode = 3044 (SrcBits == DstBits ? Instruction::BitCast : 3045 (SrcBits > DstBits ? Instruction::Trunc : 3046 (isSigned ? Instruction::SExt : Instruction::ZExt))); 3047 return Create(opcode, C, Ty, Name, InsertBefore); 3048 } 3049 3050 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 3051 bool isSigned, const Twine &Name, 3052 BasicBlock *InsertAtEnd) { 3053 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 3054 "Invalid cast"); 3055 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3056 unsigned DstBits = Ty->getScalarSizeInBits(); 3057 Instruction::CastOps opcode = 3058 (SrcBits == DstBits ? Instruction::BitCast : 3059 (SrcBits > DstBits ? Instruction::Trunc : 3060 (isSigned ? Instruction::SExt : Instruction::ZExt))); 3061 return Create(opcode, C, Ty, Name, InsertAtEnd); 3062 } 3063 3064 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 3065 const Twine &Name, 3066 Instruction *InsertBefore) { 3067 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 3068 "Invalid cast"); 3069 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3070 unsigned DstBits = Ty->getScalarSizeInBits(); 3071 Instruction::CastOps opcode = 3072 (SrcBits == DstBits ? Instruction::BitCast : 3073 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 3074 return Create(opcode, C, Ty, Name, InsertBefore); 3075 } 3076 3077 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 3078 const Twine &Name, 3079 BasicBlock *InsertAtEnd) { 3080 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 3081 "Invalid cast"); 3082 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3083 unsigned DstBits = Ty->getScalarSizeInBits(); 3084 Instruction::CastOps opcode = 3085 (SrcBits == DstBits ? Instruction::BitCast : 3086 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 3087 return Create(opcode, C, Ty, Name, InsertAtEnd); 3088 } 3089 3090 // Check whether it is valid to call getCastOpcode for these types. 3091 // This routine must be kept in sync with getCastOpcode. 3092 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) { 3093 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 3094 return false; 3095 3096 if (SrcTy == DestTy) 3097 return true; 3098 3099 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 3100 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 3101 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 3102 // An element by element cast. Valid if casting the elements is valid. 3103 SrcTy = SrcVecTy->getElementType(); 3104 DestTy = DestVecTy->getElementType(); 3105 } 3106 3107 // Get the bit sizes, we'll need these 3108 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3109 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3110 3111 // Run through the possibilities ... 3112 if (DestTy->isIntegerTy()) { // Casting to integral 3113 if (SrcTy->isIntegerTy()) // Casting from integral 3114 return true; 3115 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 3116 return true; 3117 if (SrcTy->isVectorTy()) // Casting from vector 3118 return DestBits == SrcBits; 3119 // Casting from something else 3120 return SrcTy->isPointerTy(); 3121 } 3122 if (DestTy->isFloatingPointTy()) { // Casting to floating pt 3123 if (SrcTy->isIntegerTy()) // Casting from integral 3124 return true; 3125 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 3126 return true; 3127 if (SrcTy->isVectorTy()) // Casting from vector 3128 return DestBits == SrcBits; 3129 // Casting from something else 3130 return false; 3131 } 3132 if (DestTy->isVectorTy()) // Casting to vector 3133 return DestBits == SrcBits; 3134 if (DestTy->isPointerTy()) { // Casting to pointer 3135 if (SrcTy->isPointerTy()) // Casting from pointer 3136 return true; 3137 return SrcTy->isIntegerTy(); // Casting from integral 3138 } 3139 if (DestTy->isX86_MMXTy()) { 3140 if (SrcTy->isVectorTy()) 3141 return DestBits == SrcBits; // 64-bit vector to MMX 3142 return false; 3143 } // Casting to something else 3144 return false; 3145 } 3146 3147 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) { 3148 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 3149 return false; 3150 3151 if (SrcTy == DestTy) 3152 return true; 3153 3154 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 3155 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) { 3156 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) { 3157 // An element by element cast. Valid if casting the elements is valid. 3158 SrcTy = SrcVecTy->getElementType(); 3159 DestTy = DestVecTy->getElementType(); 3160 } 3161 } 3162 } 3163 3164 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) { 3165 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) { 3166 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace(); 3167 } 3168 } 3169 3170 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3171 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3172 3173 // Could still have vectors of pointers if the number of elements doesn't 3174 // match 3175 if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0) 3176 return false; 3177 3178 if (SrcBits != DestBits) 3179 return false; 3180 3181 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy()) 3182 return false; 3183 3184 return true; 3185 } 3186 3187 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, 3188 const DataLayout &DL) { 3189 // ptrtoint and inttoptr are not allowed on non-integral pointers 3190 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy)) 3191 if (auto *IntTy = dyn_cast<IntegerType>(DestTy)) 3192 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 3193 !DL.isNonIntegralPointerType(PtrTy)); 3194 if (auto *PtrTy = dyn_cast<PointerType>(DestTy)) 3195 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy)) 3196 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 3197 !DL.isNonIntegralPointerType(PtrTy)); 3198 3199 return isBitCastable(SrcTy, DestTy); 3200 } 3201 3202 // Provide a way to get a "cast" where the cast opcode is inferred from the 3203 // types and size of the operand. This, basically, is a parallel of the 3204 // logic in the castIsValid function below. This axiom should hold: 3205 // castIsValid( getCastOpcode(Val, Ty), Val, Ty) 3206 // should not assert in castIsValid. In other words, this produces a "correct" 3207 // casting opcode for the arguments passed to it. 3208 // This routine must be kept in sync with isCastable. 3209 Instruction::CastOps 3210 CastInst::getCastOpcode( 3211 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) { 3212 Type *SrcTy = Src->getType(); 3213 3214 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && 3215 "Only first class types are castable!"); 3216 3217 if (SrcTy == DestTy) 3218 return BitCast; 3219 3220 // FIXME: Check address space sizes here 3221 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 3222 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 3223 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 3224 // An element by element cast. Find the appropriate opcode based on the 3225 // element types. 3226 SrcTy = SrcVecTy->getElementType(); 3227 DestTy = DestVecTy->getElementType(); 3228 } 3229 3230 // Get the bit sizes, we'll need these 3231 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3232 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3233 3234 // Run through the possibilities ... 3235 if (DestTy->isIntegerTy()) { // Casting to integral 3236 if (SrcTy->isIntegerTy()) { // Casting from integral 3237 if (DestBits < SrcBits) 3238 return Trunc; // int -> smaller int 3239 else if (DestBits > SrcBits) { // its an extension 3240 if (SrcIsSigned) 3241 return SExt; // signed -> SEXT 3242 else 3243 return ZExt; // unsigned -> ZEXT 3244 } else { 3245 return BitCast; // Same size, No-op cast 3246 } 3247 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3248 if (DestIsSigned) 3249 return FPToSI; // FP -> sint 3250 else 3251 return FPToUI; // FP -> uint 3252 } else if (SrcTy->isVectorTy()) { 3253 assert(DestBits == SrcBits && 3254 "Casting vector to integer of different width"); 3255 return BitCast; // Same size, no-op cast 3256 } else { 3257 assert(SrcTy->isPointerTy() && 3258 "Casting from a value that is not first-class type"); 3259 return PtrToInt; // ptr -> int 3260 } 3261 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt 3262 if (SrcTy->isIntegerTy()) { // Casting from integral 3263 if (SrcIsSigned) 3264 return SIToFP; // sint -> FP 3265 else 3266 return UIToFP; // uint -> FP 3267 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3268 if (DestBits < SrcBits) { 3269 return FPTrunc; // FP -> smaller FP 3270 } else if (DestBits > SrcBits) { 3271 return FPExt; // FP -> larger FP 3272 } else { 3273 return BitCast; // same size, no-op cast 3274 } 3275 } else if (SrcTy->isVectorTy()) { 3276 assert(DestBits == SrcBits && 3277 "Casting vector to floating point of different width"); 3278 return BitCast; // same size, no-op cast 3279 } 3280 llvm_unreachable("Casting pointer or non-first class to float"); 3281 } else if (DestTy->isVectorTy()) { 3282 assert(DestBits == SrcBits && 3283 "Illegal cast to vector (wrong type or size)"); 3284 return BitCast; 3285 } else if (DestTy->isPointerTy()) { 3286 if (SrcTy->isPointerTy()) { 3287 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace()) 3288 return AddrSpaceCast; 3289 return BitCast; // ptr -> ptr 3290 } else if (SrcTy->isIntegerTy()) { 3291 return IntToPtr; // int -> ptr 3292 } 3293 llvm_unreachable("Casting pointer to other than pointer or int"); 3294 } else if (DestTy->isX86_MMXTy()) { 3295 if (SrcTy->isVectorTy()) { 3296 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX"); 3297 return BitCast; // 64-bit vector to MMX 3298 } 3299 llvm_unreachable("Illegal cast to X86_MMX"); 3300 } 3301 llvm_unreachable("Casting to type that is not first-class"); 3302 } 3303 3304 //===----------------------------------------------------------------------===// 3305 // CastInst SubClass Constructors 3306 //===----------------------------------------------------------------------===// 3307 3308 /// Check that the construction parameters for a CastInst are correct. This 3309 /// could be broken out into the separate constructors but it is useful to have 3310 /// it in one place and to eliminate the redundant code for getting the sizes 3311 /// of the types involved. 3312 bool 3313 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { 3314 // Check for type sanity on the arguments 3315 Type *SrcTy = S->getType(); 3316 3317 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() || 3318 SrcTy->isAggregateType() || DstTy->isAggregateType()) 3319 return false; 3320 3321 // Get the size of the types in bits, and whether we are dealing 3322 // with vector types, we'll need this later. 3323 bool SrcIsVec = isa<VectorType>(SrcTy); 3324 bool DstIsVec = isa<VectorType>(DstTy); 3325 unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits(); 3326 unsigned DstScalarBitSize = DstTy->getScalarSizeInBits(); 3327 3328 // If these are vector types, get the lengths of the vectors (using zero for 3329 // scalar types means that checking that vector lengths match also checks that 3330 // scalars are not being converted to vectors or vectors to scalars). 3331 ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount() 3332 : ElementCount(0, false); 3333 ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount() 3334 : ElementCount(0, false); 3335 3336 // Switch on the opcode provided 3337 switch (op) { 3338 default: return false; // This is an input error 3339 case Instruction::Trunc: 3340 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3341 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize; 3342 case Instruction::ZExt: 3343 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3344 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3345 case Instruction::SExt: 3346 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3347 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3348 case Instruction::FPTrunc: 3349 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3350 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize; 3351 case Instruction::FPExt: 3352 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3353 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3354 case Instruction::UIToFP: 3355 case Instruction::SIToFP: 3356 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() && 3357 SrcEC == DstEC; 3358 case Instruction::FPToUI: 3359 case Instruction::FPToSI: 3360 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() && 3361 SrcEC == DstEC; 3362 case Instruction::PtrToInt: 3363 if (SrcEC != DstEC) 3364 return false; 3365 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy(); 3366 case Instruction::IntToPtr: 3367 if (SrcEC != DstEC) 3368 return false; 3369 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy(); 3370 case Instruction::BitCast: { 3371 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3372 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3373 3374 // BitCast implies a no-op cast of type only. No bits change. 3375 // However, you can't cast pointers to anything but pointers. 3376 if (!SrcPtrTy != !DstPtrTy) 3377 return false; 3378 3379 // For non-pointer cases, the cast is okay if the source and destination bit 3380 // widths are identical. 3381 if (!SrcPtrTy) 3382 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); 3383 3384 // If both are pointers then the address spaces must match. 3385 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) 3386 return false; 3387 3388 // A vector of pointers must have the same number of elements. 3389 if (SrcIsVec && DstIsVec) 3390 return SrcEC == DstEC; 3391 if (SrcIsVec) 3392 return SrcEC == ElementCount(1, false); 3393 if (DstIsVec) 3394 return DstEC == ElementCount(1, false); 3395 3396 return true; 3397 } 3398 case Instruction::AddrSpaceCast: { 3399 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3400 if (!SrcPtrTy) 3401 return false; 3402 3403 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3404 if (!DstPtrTy) 3405 return false; 3406 3407 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 3408 return false; 3409 3410 return SrcEC == DstEC; 3411 } 3412 } 3413 } 3414 3415 TruncInst::TruncInst( 3416 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3417 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) { 3418 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3419 } 3420 3421 TruncInst::TruncInst( 3422 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3423 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 3424 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3425 } 3426 3427 ZExtInst::ZExtInst( 3428 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3429 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) { 3430 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3431 } 3432 3433 ZExtInst::ZExtInst( 3434 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3435 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 3436 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3437 } 3438 SExtInst::SExtInst( 3439 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3440 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 3441 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3442 } 3443 3444 SExtInst::SExtInst( 3445 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3446 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 3447 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3448 } 3449 3450 FPTruncInst::FPTruncInst( 3451 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3452 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 3453 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3454 } 3455 3456 FPTruncInst::FPTruncInst( 3457 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3458 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 3459 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3460 } 3461 3462 FPExtInst::FPExtInst( 3463 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3464 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 3465 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3466 } 3467 3468 FPExtInst::FPExtInst( 3469 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3470 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 3471 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3472 } 3473 3474 UIToFPInst::UIToFPInst( 3475 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3476 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 3477 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3478 } 3479 3480 UIToFPInst::UIToFPInst( 3481 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3482 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 3483 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3484 } 3485 3486 SIToFPInst::SIToFPInst( 3487 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3488 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 3489 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3490 } 3491 3492 SIToFPInst::SIToFPInst( 3493 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3494 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 3495 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3496 } 3497 3498 FPToUIInst::FPToUIInst( 3499 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3500 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 3501 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3502 } 3503 3504 FPToUIInst::FPToUIInst( 3505 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3506 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 3507 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3508 } 3509 3510 FPToSIInst::FPToSIInst( 3511 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3512 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 3513 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3514 } 3515 3516 FPToSIInst::FPToSIInst( 3517 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3518 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 3519 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3520 } 3521 3522 PtrToIntInst::PtrToIntInst( 3523 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3524 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 3525 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3526 } 3527 3528 PtrToIntInst::PtrToIntInst( 3529 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3530 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 3531 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3532 } 3533 3534 IntToPtrInst::IntToPtrInst( 3535 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3536 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 3537 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3538 } 3539 3540 IntToPtrInst::IntToPtrInst( 3541 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3542 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 3543 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3544 } 3545 3546 BitCastInst::BitCastInst( 3547 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3548 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 3549 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3550 } 3551 3552 BitCastInst::BitCastInst( 3553 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3554 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 3555 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3556 } 3557 3558 AddrSpaceCastInst::AddrSpaceCastInst( 3559 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3560 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) { 3561 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3562 } 3563 3564 AddrSpaceCastInst::AddrSpaceCastInst( 3565 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3566 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) { 3567 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3568 } 3569 3570 //===----------------------------------------------------------------------===// 3571 // CmpInst Classes 3572 //===----------------------------------------------------------------------===// 3573 3574 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3575 Value *RHS, const Twine &Name, Instruction *InsertBefore, 3576 Instruction *FlagsSource) 3577 : Instruction(ty, op, 3578 OperandTraits<CmpInst>::op_begin(this), 3579 OperandTraits<CmpInst>::operands(this), 3580 InsertBefore) { 3581 Op<0>() = LHS; 3582 Op<1>() = RHS; 3583 setPredicate((Predicate)predicate); 3584 setName(Name); 3585 if (FlagsSource) 3586 copyIRFlags(FlagsSource); 3587 } 3588 3589 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3590 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd) 3591 : Instruction(ty, op, 3592 OperandTraits<CmpInst>::op_begin(this), 3593 OperandTraits<CmpInst>::operands(this), 3594 InsertAtEnd) { 3595 Op<0>() = LHS; 3596 Op<1>() = RHS; 3597 setPredicate((Predicate)predicate); 3598 setName(Name); 3599 } 3600 3601 CmpInst * 3602 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3603 const Twine &Name, Instruction *InsertBefore) { 3604 if (Op == Instruction::ICmp) { 3605 if (InsertBefore) 3606 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), 3607 S1, S2, Name); 3608 else 3609 return new ICmpInst(CmpInst::Predicate(predicate), 3610 S1, S2, Name); 3611 } 3612 3613 if (InsertBefore) 3614 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), 3615 S1, S2, Name); 3616 else 3617 return new FCmpInst(CmpInst::Predicate(predicate), 3618 S1, S2, Name); 3619 } 3620 3621 CmpInst * 3622 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3623 const Twine &Name, BasicBlock *InsertAtEnd) { 3624 if (Op == Instruction::ICmp) { 3625 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3626 S1, S2, Name); 3627 } 3628 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3629 S1, S2, Name); 3630 } 3631 3632 void CmpInst::swapOperands() { 3633 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3634 IC->swapOperands(); 3635 else 3636 cast<FCmpInst>(this)->swapOperands(); 3637 } 3638 3639 bool CmpInst::isCommutative() const { 3640 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3641 return IC->isCommutative(); 3642 return cast<FCmpInst>(this)->isCommutative(); 3643 } 3644 3645 bool CmpInst::isEquality() const { 3646 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3647 return IC->isEquality(); 3648 return cast<FCmpInst>(this)->isEquality(); 3649 } 3650 3651 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { 3652 switch (pred) { 3653 default: llvm_unreachable("Unknown cmp predicate!"); 3654 case ICMP_EQ: return ICMP_NE; 3655 case ICMP_NE: return ICMP_EQ; 3656 case ICMP_UGT: return ICMP_ULE; 3657 case ICMP_ULT: return ICMP_UGE; 3658 case ICMP_UGE: return ICMP_ULT; 3659 case ICMP_ULE: return ICMP_UGT; 3660 case ICMP_SGT: return ICMP_SLE; 3661 case ICMP_SLT: return ICMP_SGE; 3662 case ICMP_SGE: return ICMP_SLT; 3663 case ICMP_SLE: return ICMP_SGT; 3664 3665 case FCMP_OEQ: return FCMP_UNE; 3666 case FCMP_ONE: return FCMP_UEQ; 3667 case FCMP_OGT: return FCMP_ULE; 3668 case FCMP_OLT: return FCMP_UGE; 3669 case FCMP_OGE: return FCMP_ULT; 3670 case FCMP_OLE: return FCMP_UGT; 3671 case FCMP_UEQ: return FCMP_ONE; 3672 case FCMP_UNE: return FCMP_OEQ; 3673 case FCMP_UGT: return FCMP_OLE; 3674 case FCMP_ULT: return FCMP_OGE; 3675 case FCMP_UGE: return FCMP_OLT; 3676 case FCMP_ULE: return FCMP_OGT; 3677 case FCMP_ORD: return FCMP_UNO; 3678 case FCMP_UNO: return FCMP_ORD; 3679 case FCMP_TRUE: return FCMP_FALSE; 3680 case FCMP_FALSE: return FCMP_TRUE; 3681 } 3682 } 3683 3684 StringRef CmpInst::getPredicateName(Predicate Pred) { 3685 switch (Pred) { 3686 default: return "unknown"; 3687 case FCmpInst::FCMP_FALSE: return "false"; 3688 case FCmpInst::FCMP_OEQ: return "oeq"; 3689 case FCmpInst::FCMP_OGT: return "ogt"; 3690 case FCmpInst::FCMP_OGE: return "oge"; 3691 case FCmpInst::FCMP_OLT: return "olt"; 3692 case FCmpInst::FCMP_OLE: return "ole"; 3693 case FCmpInst::FCMP_ONE: return "one"; 3694 case FCmpInst::FCMP_ORD: return "ord"; 3695 case FCmpInst::FCMP_UNO: return "uno"; 3696 case FCmpInst::FCMP_UEQ: return "ueq"; 3697 case FCmpInst::FCMP_UGT: return "ugt"; 3698 case FCmpInst::FCMP_UGE: return "uge"; 3699 case FCmpInst::FCMP_ULT: return "ult"; 3700 case FCmpInst::FCMP_ULE: return "ule"; 3701 case FCmpInst::FCMP_UNE: return "une"; 3702 case FCmpInst::FCMP_TRUE: return "true"; 3703 case ICmpInst::ICMP_EQ: return "eq"; 3704 case ICmpInst::ICMP_NE: return "ne"; 3705 case ICmpInst::ICMP_SGT: return "sgt"; 3706 case ICmpInst::ICMP_SGE: return "sge"; 3707 case ICmpInst::ICMP_SLT: return "slt"; 3708 case ICmpInst::ICMP_SLE: return "sle"; 3709 case ICmpInst::ICMP_UGT: return "ugt"; 3710 case ICmpInst::ICMP_UGE: return "uge"; 3711 case ICmpInst::ICMP_ULT: return "ult"; 3712 case ICmpInst::ICMP_ULE: return "ule"; 3713 } 3714 } 3715 3716 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { 3717 switch (pred) { 3718 default: llvm_unreachable("Unknown icmp predicate!"); 3719 case ICMP_EQ: case ICMP_NE: 3720 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 3721 return pred; 3722 case ICMP_UGT: return ICMP_SGT; 3723 case ICMP_ULT: return ICMP_SLT; 3724 case ICMP_UGE: return ICMP_SGE; 3725 case ICMP_ULE: return ICMP_SLE; 3726 } 3727 } 3728 3729 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { 3730 switch (pred) { 3731 default: llvm_unreachable("Unknown icmp predicate!"); 3732 case ICMP_EQ: case ICMP_NE: 3733 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 3734 return pred; 3735 case ICMP_SGT: return ICMP_UGT; 3736 case ICMP_SLT: return ICMP_ULT; 3737 case ICMP_SGE: return ICMP_UGE; 3738 case ICMP_SLE: return ICMP_ULE; 3739 } 3740 } 3741 3742 CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) { 3743 switch (pred) { 3744 default: llvm_unreachable("Unknown or unsupported cmp predicate!"); 3745 case ICMP_SGT: return ICMP_SGE; 3746 case ICMP_SLT: return ICMP_SLE; 3747 case ICMP_SGE: return ICMP_SGT; 3748 case ICMP_SLE: return ICMP_SLT; 3749 case ICMP_UGT: return ICMP_UGE; 3750 case ICMP_ULT: return ICMP_ULE; 3751 case ICMP_UGE: return ICMP_UGT; 3752 case ICMP_ULE: return ICMP_ULT; 3753 3754 case FCMP_OGT: return FCMP_OGE; 3755 case FCMP_OLT: return FCMP_OLE; 3756 case FCMP_OGE: return FCMP_OGT; 3757 case FCMP_OLE: return FCMP_OLT; 3758 case FCMP_UGT: return FCMP_UGE; 3759 case FCMP_ULT: return FCMP_ULE; 3760 case FCMP_UGE: return FCMP_UGT; 3761 case FCMP_ULE: return FCMP_ULT; 3762 } 3763 } 3764 3765 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { 3766 switch (pred) { 3767 default: llvm_unreachable("Unknown cmp predicate!"); 3768 case ICMP_EQ: case ICMP_NE: 3769 return pred; 3770 case ICMP_SGT: return ICMP_SLT; 3771 case ICMP_SLT: return ICMP_SGT; 3772 case ICMP_SGE: return ICMP_SLE; 3773 case ICMP_SLE: return ICMP_SGE; 3774 case ICMP_UGT: return ICMP_ULT; 3775 case ICMP_ULT: return ICMP_UGT; 3776 case ICMP_UGE: return ICMP_ULE; 3777 case ICMP_ULE: return ICMP_UGE; 3778 3779 case FCMP_FALSE: case FCMP_TRUE: 3780 case FCMP_OEQ: case FCMP_ONE: 3781 case FCMP_UEQ: case FCMP_UNE: 3782 case FCMP_ORD: case FCMP_UNO: 3783 return pred; 3784 case FCMP_OGT: return FCMP_OLT; 3785 case FCMP_OLT: return FCMP_OGT; 3786 case FCMP_OGE: return FCMP_OLE; 3787 case FCMP_OLE: return FCMP_OGE; 3788 case FCMP_UGT: return FCMP_ULT; 3789 case FCMP_ULT: return FCMP_UGT; 3790 case FCMP_UGE: return FCMP_ULE; 3791 case FCMP_ULE: return FCMP_UGE; 3792 } 3793 } 3794 3795 CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) { 3796 switch (pred) { 3797 case ICMP_SGT: return ICMP_SGE; 3798 case ICMP_SLT: return ICMP_SLE; 3799 case ICMP_UGT: return ICMP_UGE; 3800 case ICMP_ULT: return ICMP_ULE; 3801 case FCMP_OGT: return FCMP_OGE; 3802 case FCMP_OLT: return FCMP_OLE; 3803 case FCMP_UGT: return FCMP_UGE; 3804 case FCMP_ULT: return FCMP_ULE; 3805 default: return pred; 3806 } 3807 } 3808 3809 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) { 3810 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!"); 3811 3812 switch (pred) { 3813 default: 3814 llvm_unreachable("Unknown predicate!"); 3815 case CmpInst::ICMP_ULT: 3816 return CmpInst::ICMP_SLT; 3817 case CmpInst::ICMP_ULE: 3818 return CmpInst::ICMP_SLE; 3819 case CmpInst::ICMP_UGT: 3820 return CmpInst::ICMP_SGT; 3821 case CmpInst::ICMP_UGE: 3822 return CmpInst::ICMP_SGE; 3823 } 3824 } 3825 3826 bool CmpInst::isUnsigned(Predicate predicate) { 3827 switch (predicate) { 3828 default: return false; 3829 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 3830 case ICmpInst::ICMP_UGE: return true; 3831 } 3832 } 3833 3834 bool CmpInst::isSigned(Predicate predicate) { 3835 switch (predicate) { 3836 default: return false; 3837 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 3838 case ICmpInst::ICMP_SGE: return true; 3839 } 3840 } 3841 3842 bool CmpInst::isOrdered(Predicate predicate) { 3843 switch (predicate) { 3844 default: return false; 3845 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 3846 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 3847 case FCmpInst::FCMP_ORD: return true; 3848 } 3849 } 3850 3851 bool CmpInst::isUnordered(Predicate predicate) { 3852 switch (predicate) { 3853 default: return false; 3854 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 3855 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 3856 case FCmpInst::FCMP_UNO: return true; 3857 } 3858 } 3859 3860 bool CmpInst::isTrueWhenEqual(Predicate predicate) { 3861 switch(predicate) { 3862 default: return false; 3863 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE: 3864 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true; 3865 } 3866 } 3867 3868 bool CmpInst::isFalseWhenEqual(Predicate predicate) { 3869 switch(predicate) { 3870 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT: 3871 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true; 3872 default: return false; 3873 } 3874 } 3875 3876 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3877 // If the predicates match, then we know the first condition implies the 3878 // second is true. 3879 if (Pred1 == Pred2) 3880 return true; 3881 3882 switch (Pred1) { 3883 default: 3884 break; 3885 case ICMP_EQ: 3886 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true. 3887 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE || 3888 Pred2 == ICMP_SLE; 3889 case ICMP_UGT: // A >u B implies A != B and A >=u B are true. 3890 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE; 3891 case ICMP_ULT: // A <u B implies A != B and A <=u B are true. 3892 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE; 3893 case ICMP_SGT: // A >s B implies A != B and A >=s B are true. 3894 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE; 3895 case ICMP_SLT: // A <s B implies A != B and A <=s B are true. 3896 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE; 3897 } 3898 return false; 3899 } 3900 3901 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3902 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2)); 3903 } 3904 3905 //===----------------------------------------------------------------------===// 3906 // SwitchInst Implementation 3907 //===----------------------------------------------------------------------===// 3908 3909 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) { 3910 assert(Value && Default && NumReserved); 3911 ReservedSpace = NumReserved; 3912 setNumHungOffUseOperands(2); 3913 allocHungoffUses(ReservedSpace); 3914 3915 Op<0>() = Value; 3916 Op<1>() = Default; 3917 } 3918 3919 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3920 /// switch on and a default destination. The number of additional cases can 3921 /// be specified here to make memory allocation more efficient. This 3922 /// constructor can also autoinsert before another instruction. 3923 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3924 Instruction *InsertBefore) 3925 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3926 nullptr, 0, InsertBefore) { 3927 init(Value, Default, 2+NumCases*2); 3928 } 3929 3930 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3931 /// switch on and a default destination. The number of additional cases can 3932 /// be specified here to make memory allocation more efficient. This 3933 /// constructor also autoinserts at the end of the specified BasicBlock. 3934 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3935 BasicBlock *InsertAtEnd) 3936 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3937 nullptr, 0, InsertAtEnd) { 3938 init(Value, Default, 2+NumCases*2); 3939 } 3940 3941 SwitchInst::SwitchInst(const SwitchInst &SI) 3942 : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) { 3943 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands()); 3944 setNumHungOffUseOperands(SI.getNumOperands()); 3945 Use *OL = getOperandList(); 3946 const Use *InOL = SI.getOperandList(); 3947 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) { 3948 OL[i] = InOL[i]; 3949 OL[i+1] = InOL[i+1]; 3950 } 3951 SubclassOptionalData = SI.SubclassOptionalData; 3952 } 3953 3954 /// addCase - Add an entry to the switch instruction... 3955 /// 3956 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { 3957 unsigned NewCaseIdx = getNumCases(); 3958 unsigned OpNo = getNumOperands(); 3959 if (OpNo+2 > ReservedSpace) 3960 growOperands(); // Get more space! 3961 // Initialize some new operands. 3962 assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); 3963 setNumHungOffUseOperands(OpNo+2); 3964 CaseHandle Case(this, NewCaseIdx); 3965 Case.setValue(OnVal); 3966 Case.setSuccessor(Dest); 3967 } 3968 3969 /// removeCase - This method removes the specified case and its successor 3970 /// from the switch instruction. 3971 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) { 3972 unsigned idx = I->getCaseIndex(); 3973 3974 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!"); 3975 3976 unsigned NumOps = getNumOperands(); 3977 Use *OL = getOperandList(); 3978 3979 // Overwrite this case with the end of the list. 3980 if (2 + (idx + 1) * 2 != NumOps) { 3981 OL[2 + idx * 2] = OL[NumOps - 2]; 3982 OL[2 + idx * 2 + 1] = OL[NumOps - 1]; 3983 } 3984 3985 // Nuke the last value. 3986 OL[NumOps-2].set(nullptr); 3987 OL[NumOps-2+1].set(nullptr); 3988 setNumHungOffUseOperands(NumOps-2); 3989 3990 return CaseIt(this, idx); 3991 } 3992 3993 /// growOperands - grow operands - This grows the operand list in response 3994 /// to a push_back style of operation. This grows the number of ops by 3 times. 3995 /// 3996 void SwitchInst::growOperands() { 3997 unsigned e = getNumOperands(); 3998 unsigned NumOps = e*3; 3999 4000 ReservedSpace = NumOps; 4001 growHungoffUses(ReservedSpace); 4002 } 4003 4004 MDNode * 4005 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) { 4006 if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof)) 4007 if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0))) 4008 if (MDName->getString() == "branch_weights") 4009 return ProfileData; 4010 return nullptr; 4011 } 4012 4013 MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() { 4014 assert(Changed && "called only if metadata has changed"); 4015 4016 if (!Weights) 4017 return nullptr; 4018 4019 assert(SI.getNumSuccessors() == Weights->size() && 4020 "num of prof branch_weights must accord with num of successors"); 4021 4022 bool AllZeroes = 4023 all_of(Weights.getValue(), [](uint32_t W) { return W == 0; }); 4024 4025 if (AllZeroes || Weights.getValue().size() < 2) 4026 return nullptr; 4027 4028 return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights); 4029 } 4030 4031 void SwitchInstProfUpdateWrapper::init() { 4032 MDNode *ProfileData = getProfBranchWeightsMD(SI); 4033 if (!ProfileData) 4034 return; 4035 4036 if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) { 4037 llvm_unreachable("number of prof branch_weights metadata operands does " 4038 "not correspond to number of succesors"); 4039 } 4040 4041 SmallVector<uint32_t, 8> Weights; 4042 for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) { 4043 ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI)); 4044 uint32_t CW = C->getValue().getZExtValue(); 4045 Weights.push_back(CW); 4046 } 4047 this->Weights = std::move(Weights); 4048 } 4049 4050 SwitchInst::CaseIt 4051 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) { 4052 if (Weights) { 4053 assert(SI.getNumSuccessors() == Weights->size() && 4054 "num of prof branch_weights must accord with num of successors"); 4055 Changed = true; 4056 // Copy the last case to the place of the removed one and shrink. 4057 // This is tightly coupled with the way SwitchInst::removeCase() removes 4058 // the cases in SwitchInst::removeCase(CaseIt). 4059 Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back(); 4060 Weights.getValue().pop_back(); 4061 } 4062 return SI.removeCase(I); 4063 } 4064 4065 void SwitchInstProfUpdateWrapper::addCase( 4066 ConstantInt *OnVal, BasicBlock *Dest, 4067 SwitchInstProfUpdateWrapper::CaseWeightOpt W) { 4068 SI.addCase(OnVal, Dest); 4069 4070 if (!Weights && W && *W) { 4071 Changed = true; 4072 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0); 4073 Weights.getValue()[SI.getNumSuccessors() - 1] = *W; 4074 } else if (Weights) { 4075 Changed = true; 4076 Weights.getValue().push_back(W ? *W : 0); 4077 } 4078 if (Weights) 4079 assert(SI.getNumSuccessors() == Weights->size() && 4080 "num of prof branch_weights must accord with num of successors"); 4081 } 4082 4083 SymbolTableList<Instruction>::iterator 4084 SwitchInstProfUpdateWrapper::eraseFromParent() { 4085 // Instruction is erased. Mark as unchanged to not touch it in the destructor. 4086 Changed = false; 4087 if (Weights) 4088 Weights->resize(0); 4089 return SI.eraseFromParent(); 4090 } 4091 4092 SwitchInstProfUpdateWrapper::CaseWeightOpt 4093 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) { 4094 if (!Weights) 4095 return None; 4096 return Weights.getValue()[idx]; 4097 } 4098 4099 void SwitchInstProfUpdateWrapper::setSuccessorWeight( 4100 unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) { 4101 if (!W) 4102 return; 4103 4104 if (!Weights && *W) 4105 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0); 4106 4107 if (Weights) { 4108 auto &OldW = Weights.getValue()[idx]; 4109 if (*W != OldW) { 4110 Changed = true; 4111 OldW = *W; 4112 } 4113 } 4114 } 4115 4116 SwitchInstProfUpdateWrapper::CaseWeightOpt 4117 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI, 4118 unsigned idx) { 4119 if (MDNode *ProfileData = getProfBranchWeightsMD(SI)) 4120 if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1) 4121 return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1)) 4122 ->getValue() 4123 .getZExtValue(); 4124 4125 return None; 4126 } 4127 4128 //===----------------------------------------------------------------------===// 4129 // IndirectBrInst Implementation 4130 //===----------------------------------------------------------------------===// 4131 4132 void IndirectBrInst::init(Value *Address, unsigned NumDests) { 4133 assert(Address && Address->getType()->isPointerTy() && 4134 "Address of indirectbr must be a pointer"); 4135 ReservedSpace = 1+NumDests; 4136 setNumHungOffUseOperands(1); 4137 allocHungoffUses(ReservedSpace); 4138 4139 Op<0>() = Address; 4140 } 4141 4142 4143 /// growOperands - grow operands - This grows the operand list in response 4144 /// to a push_back style of operation. This grows the number of ops by 2 times. 4145 /// 4146 void IndirectBrInst::growOperands() { 4147 unsigned e = getNumOperands(); 4148 unsigned NumOps = e*2; 4149 4150 ReservedSpace = NumOps; 4151 growHungoffUses(ReservedSpace); 4152 } 4153 4154 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 4155 Instruction *InsertBefore) 4156 : Instruction(Type::getVoidTy(Address->getContext()), 4157 Instruction::IndirectBr, nullptr, 0, InsertBefore) { 4158 init(Address, NumCases); 4159 } 4160 4161 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 4162 BasicBlock *InsertAtEnd) 4163 : Instruction(Type::getVoidTy(Address->getContext()), 4164 Instruction::IndirectBr, nullptr, 0, InsertAtEnd) { 4165 init(Address, NumCases); 4166 } 4167 4168 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI) 4169 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr, 4170 nullptr, IBI.getNumOperands()) { 4171 allocHungoffUses(IBI.getNumOperands()); 4172 Use *OL = getOperandList(); 4173 const Use *InOL = IBI.getOperandList(); 4174 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i) 4175 OL[i] = InOL[i]; 4176 SubclassOptionalData = IBI.SubclassOptionalData; 4177 } 4178 4179 /// addDestination - Add a destination. 4180 /// 4181 void IndirectBrInst::addDestination(BasicBlock *DestBB) { 4182 unsigned OpNo = getNumOperands(); 4183 if (OpNo+1 > ReservedSpace) 4184 growOperands(); // Get more space! 4185 // Initialize some new operands. 4186 assert(OpNo < ReservedSpace && "Growing didn't work!"); 4187 setNumHungOffUseOperands(OpNo+1); 4188 getOperandList()[OpNo] = DestBB; 4189 } 4190 4191 /// removeDestination - This method removes the specified successor from the 4192 /// indirectbr instruction. 4193 void IndirectBrInst::removeDestination(unsigned idx) { 4194 assert(idx < getNumOperands()-1 && "Successor index out of range!"); 4195 4196 unsigned NumOps = getNumOperands(); 4197 Use *OL = getOperandList(); 4198 4199 // Replace this value with the last one. 4200 OL[idx+1] = OL[NumOps-1]; 4201 4202 // Nuke the last value. 4203 OL[NumOps-1].set(nullptr); 4204 setNumHungOffUseOperands(NumOps-1); 4205 } 4206 4207 //===----------------------------------------------------------------------===// 4208 // FreezeInst Implementation 4209 //===----------------------------------------------------------------------===// 4210 4211 FreezeInst::FreezeInst(Value *S, 4212 const Twine &Name, Instruction *InsertBefore) 4213 : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) { 4214 setName(Name); 4215 } 4216 4217 FreezeInst::FreezeInst(Value *S, 4218 const Twine &Name, BasicBlock *InsertAtEnd) 4219 : UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) { 4220 setName(Name); 4221 } 4222 4223 //===----------------------------------------------------------------------===// 4224 // cloneImpl() implementations 4225 //===----------------------------------------------------------------------===// 4226 4227 // Define these methods here so vtables don't get emitted into every translation 4228 // unit that uses these classes. 4229 4230 GetElementPtrInst *GetElementPtrInst::cloneImpl() const { 4231 return new (getNumOperands()) GetElementPtrInst(*this); 4232 } 4233 4234 UnaryOperator *UnaryOperator::cloneImpl() const { 4235 return Create(getOpcode(), Op<0>()); 4236 } 4237 4238 BinaryOperator *BinaryOperator::cloneImpl() const { 4239 return Create(getOpcode(), Op<0>(), Op<1>()); 4240 } 4241 4242 FCmpInst *FCmpInst::cloneImpl() const { 4243 return new FCmpInst(getPredicate(), Op<0>(), Op<1>()); 4244 } 4245 4246 ICmpInst *ICmpInst::cloneImpl() const { 4247 return new ICmpInst(getPredicate(), Op<0>(), Op<1>()); 4248 } 4249 4250 ExtractValueInst *ExtractValueInst::cloneImpl() const { 4251 return new ExtractValueInst(*this); 4252 } 4253 4254 InsertValueInst *InsertValueInst::cloneImpl() const { 4255 return new InsertValueInst(*this); 4256 } 4257 4258 AllocaInst *AllocaInst::cloneImpl() const { 4259 AllocaInst *Result = 4260 new AllocaInst(getAllocatedType(), getType()->getAddressSpace(), 4261 getOperand(0), getAlign()); 4262 Result->setUsedWithInAlloca(isUsedWithInAlloca()); 4263 Result->setSwiftError(isSwiftError()); 4264 return Result; 4265 } 4266 4267 LoadInst *LoadInst::cloneImpl() const { 4268 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(), 4269 getAlign(), getOrdering(), getSyncScopeID()); 4270 } 4271 4272 StoreInst *StoreInst::cloneImpl() const { 4273 return new StoreInst(getOperand(0), getOperand(1), isVolatile(), getAlign(), 4274 getOrdering(), getSyncScopeID()); 4275 } 4276 4277 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const { 4278 AtomicCmpXchgInst *Result = 4279 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2), 4280 getSuccessOrdering(), getFailureOrdering(), 4281 getSyncScopeID()); 4282 Result->setVolatile(isVolatile()); 4283 Result->setWeak(isWeak()); 4284 return Result; 4285 } 4286 4287 AtomicRMWInst *AtomicRMWInst::cloneImpl() const { 4288 AtomicRMWInst *Result = 4289 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1), 4290 getOrdering(), getSyncScopeID()); 4291 Result->setVolatile(isVolatile()); 4292 return Result; 4293 } 4294 4295 FenceInst *FenceInst::cloneImpl() const { 4296 return new FenceInst(getContext(), getOrdering(), getSyncScopeID()); 4297 } 4298 4299 TruncInst *TruncInst::cloneImpl() const { 4300 return new TruncInst(getOperand(0), getType()); 4301 } 4302 4303 ZExtInst *ZExtInst::cloneImpl() const { 4304 return new ZExtInst(getOperand(0), getType()); 4305 } 4306 4307 SExtInst *SExtInst::cloneImpl() const { 4308 return new SExtInst(getOperand(0), getType()); 4309 } 4310 4311 FPTruncInst *FPTruncInst::cloneImpl() const { 4312 return new FPTruncInst(getOperand(0), getType()); 4313 } 4314 4315 FPExtInst *FPExtInst::cloneImpl() const { 4316 return new FPExtInst(getOperand(0), getType()); 4317 } 4318 4319 UIToFPInst *UIToFPInst::cloneImpl() const { 4320 return new UIToFPInst(getOperand(0), getType()); 4321 } 4322 4323 SIToFPInst *SIToFPInst::cloneImpl() const { 4324 return new SIToFPInst(getOperand(0), getType()); 4325 } 4326 4327 FPToUIInst *FPToUIInst::cloneImpl() const { 4328 return new FPToUIInst(getOperand(0), getType()); 4329 } 4330 4331 FPToSIInst *FPToSIInst::cloneImpl() const { 4332 return new FPToSIInst(getOperand(0), getType()); 4333 } 4334 4335 PtrToIntInst *PtrToIntInst::cloneImpl() const { 4336 return new PtrToIntInst(getOperand(0), getType()); 4337 } 4338 4339 IntToPtrInst *IntToPtrInst::cloneImpl() const { 4340 return new IntToPtrInst(getOperand(0), getType()); 4341 } 4342 4343 BitCastInst *BitCastInst::cloneImpl() const { 4344 return new BitCastInst(getOperand(0), getType()); 4345 } 4346 4347 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const { 4348 return new AddrSpaceCastInst(getOperand(0), getType()); 4349 } 4350 4351 CallInst *CallInst::cloneImpl() const { 4352 if (hasOperandBundles()) { 4353 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4354 return new(getNumOperands(), DescriptorBytes) CallInst(*this); 4355 } 4356 return new(getNumOperands()) CallInst(*this); 4357 } 4358 4359 SelectInst *SelectInst::cloneImpl() const { 4360 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4361 } 4362 4363 VAArgInst *VAArgInst::cloneImpl() const { 4364 return new VAArgInst(getOperand(0), getType()); 4365 } 4366 4367 ExtractElementInst *ExtractElementInst::cloneImpl() const { 4368 return ExtractElementInst::Create(getOperand(0), getOperand(1)); 4369 } 4370 4371 InsertElementInst *InsertElementInst::cloneImpl() const { 4372 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4373 } 4374 4375 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const { 4376 return new ShuffleVectorInst(getOperand(0), getOperand(1), getShuffleMask()); 4377 } 4378 4379 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); } 4380 4381 LandingPadInst *LandingPadInst::cloneImpl() const { 4382 return new LandingPadInst(*this); 4383 } 4384 4385 ReturnInst *ReturnInst::cloneImpl() const { 4386 return new(getNumOperands()) ReturnInst(*this); 4387 } 4388 4389 BranchInst *BranchInst::cloneImpl() const { 4390 return new(getNumOperands()) BranchInst(*this); 4391 } 4392 4393 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); } 4394 4395 IndirectBrInst *IndirectBrInst::cloneImpl() const { 4396 return new IndirectBrInst(*this); 4397 } 4398 4399 InvokeInst *InvokeInst::cloneImpl() const { 4400 if (hasOperandBundles()) { 4401 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4402 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this); 4403 } 4404 return new(getNumOperands()) InvokeInst(*this); 4405 } 4406 4407 CallBrInst *CallBrInst::cloneImpl() const { 4408 if (hasOperandBundles()) { 4409 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4410 return new (getNumOperands(), DescriptorBytes) CallBrInst(*this); 4411 } 4412 return new (getNumOperands()) CallBrInst(*this); 4413 } 4414 4415 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); } 4416 4417 CleanupReturnInst *CleanupReturnInst::cloneImpl() const { 4418 return new (getNumOperands()) CleanupReturnInst(*this); 4419 } 4420 4421 CatchReturnInst *CatchReturnInst::cloneImpl() const { 4422 return new (getNumOperands()) CatchReturnInst(*this); 4423 } 4424 4425 CatchSwitchInst *CatchSwitchInst::cloneImpl() const { 4426 return new CatchSwitchInst(*this); 4427 } 4428 4429 FuncletPadInst *FuncletPadInst::cloneImpl() const { 4430 return new (getNumOperands()) FuncletPadInst(*this); 4431 } 4432 4433 UnreachableInst *UnreachableInst::cloneImpl() const { 4434 LLVMContext &Context = getContext(); 4435 return new UnreachableInst(Context); 4436 } 4437 4438 FreezeInst *FreezeInst::cloneImpl() const { 4439 return new FreezeInst(getOperand(0)); 4440 } 4441