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->getNumElements() != VT->getNumElements()) 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().hasAttribute(AttributeList::FunctionIndex, Kind); 334 return false; 335 } 336 337 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const { 338 if (const Function *F = getCalledFunction()) 339 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex, 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 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1250 Instruction *InsertBefore) 1251 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {} 1252 1253 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1254 BasicBlock *InsertAtEnd) 1255 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {} 1256 1257 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1258 const Twine &Name, Instruction *InsertBefore) 1259 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/None, Name, InsertBefore) { 1260 } 1261 1262 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1263 const Twine &Name, BasicBlock *InsertAtEnd) 1264 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/None, Name, InsertAtEnd) {} 1265 1266 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1267 MaybeAlign Align, const Twine &Name, 1268 Instruction *InsertBefore) 1269 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1270 getAISize(Ty->getContext(), ArraySize), InsertBefore), 1271 AllocatedType(Ty) { 1272 setAlignment(MaybeAlign(Align)); 1273 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1274 setName(Name); 1275 } 1276 1277 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1278 MaybeAlign Align, const Twine &Name, 1279 BasicBlock *InsertAtEnd) 1280 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1281 getAISize(Ty->getContext(), ArraySize), InsertAtEnd), 1282 AllocatedType(Ty) { 1283 setAlignment(Align); 1284 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1285 setName(Name); 1286 } 1287 1288 void AllocaInst::setAlignment(MaybeAlign Align) { 1289 assert((!Align || *Align <= MaximumAlignment) && 1290 "Alignment is greater than MaximumAlignment!"); 1291 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) | 1292 encode(Align)); 1293 if (Align) 1294 assert(getAlignment() == Align->value() && 1295 "Alignment representation error!"); 1296 else 1297 assert(getAlignment() == 0 && "Alignment representation error!"); 1298 } 1299 1300 bool AllocaInst::isArrayAllocation() const { 1301 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) 1302 return !CI->isOne(); 1303 return true; 1304 } 1305 1306 /// isStaticAlloca - Return true if this alloca is in the entry block of the 1307 /// function and is a constant size. If so, the code generator will fold it 1308 /// into the prolog/epilog code, so it is basically free. 1309 bool AllocaInst::isStaticAlloca() const { 1310 // Must be constant size. 1311 if (!isa<ConstantInt>(getArraySize())) return false; 1312 1313 // Must be in the entry block. 1314 const BasicBlock *Parent = getParent(); 1315 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca(); 1316 } 1317 1318 //===----------------------------------------------------------------------===// 1319 // LoadInst Implementation 1320 //===----------------------------------------------------------------------===// 1321 1322 void LoadInst::AssertOK() { 1323 assert(getOperand(0)->getType()->isPointerTy() && 1324 "Ptr must have pointer type."); 1325 assert(!(isAtomic() && getAlignment() == 0) && 1326 "Alignment required for atomic load"); 1327 } 1328 1329 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, 1330 Instruction *InsertBef) 1331 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {} 1332 1333 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, 1334 BasicBlock *InsertAE) 1335 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {} 1336 1337 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1338 Instruction *InsertBef) 1339 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/None, InsertBef) {} 1340 1341 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1342 BasicBlock *InsertAE) 1343 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/None, InsertAE) {} 1344 1345 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1346 MaybeAlign Align, Instruction *InsertBef) 1347 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1348 SyncScope::System, InsertBef) {} 1349 1350 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1351 MaybeAlign Align, BasicBlock *InsertAE) 1352 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1353 SyncScope::System, InsertAE) {} 1354 1355 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1356 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID, 1357 Instruction *InsertBef) 1358 : UnaryInstruction(Ty, Load, Ptr, InsertBef) { 1359 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1360 setVolatile(isVolatile); 1361 setAlignment(MaybeAlign(Align)); 1362 setAtomic(Order, SSID); 1363 AssertOK(); 1364 setName(Name); 1365 } 1366 1367 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1368 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID, 1369 BasicBlock *InsertAE) 1370 : UnaryInstruction(Ty, Load, Ptr, InsertAE) { 1371 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1372 setVolatile(isVolatile); 1373 setAlignment(Align); 1374 setAtomic(Order, SSID); 1375 AssertOK(); 1376 setName(Name); 1377 } 1378 1379 void LoadInst::setAlignment(MaybeAlign Align) { 1380 assert((!Align || *Align <= MaximumAlignment) && 1381 "Alignment is greater than MaximumAlignment!"); 1382 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1383 (encode(Align) << 1)); 1384 assert(getAlign() == Align && "Alignment representation error!"); 1385 } 1386 1387 //===----------------------------------------------------------------------===// 1388 // StoreInst Implementation 1389 //===----------------------------------------------------------------------===// 1390 1391 void StoreInst::AssertOK() { 1392 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); 1393 assert(getOperand(1)->getType()->isPointerTy() && 1394 "Ptr must have pointer type!"); 1395 assert(getOperand(0)->getType() == 1396 cast<PointerType>(getOperand(1)->getType())->getElementType() 1397 && "Ptr must be a pointer to Val type!"); 1398 assert(!(isAtomic() && getAlignment() == 0) && 1399 "Alignment required for atomic store"); 1400 } 1401 1402 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) 1403 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {} 1404 1405 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) 1406 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {} 1407 1408 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1409 Instruction *InsertBefore) 1410 : StoreInst(val, addr, isVolatile, /*Align=*/None, InsertBefore) {} 1411 1412 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1413 BasicBlock *InsertAtEnd) 1414 : StoreInst(val, addr, isVolatile, /*Align=*/None, InsertAtEnd) {} 1415 1416 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, MaybeAlign Align, 1417 Instruction *InsertBefore) 1418 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1419 SyncScope::System, InsertBefore) {} 1420 1421 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, MaybeAlign Align, 1422 BasicBlock *InsertAtEnd) 1423 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1424 SyncScope::System, InsertAtEnd) {} 1425 1426 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, MaybeAlign Align, 1427 AtomicOrdering Order, SyncScope::ID SSID, 1428 Instruction *InsertBefore) 1429 : Instruction(Type::getVoidTy(val->getContext()), Store, 1430 OperandTraits<StoreInst>::op_begin(this), 1431 OperandTraits<StoreInst>::operands(this), InsertBefore) { 1432 Op<0>() = val; 1433 Op<1>() = addr; 1434 setVolatile(isVolatile); 1435 setAlignment(Align); 1436 setAtomic(Order, SSID); 1437 AssertOK(); 1438 } 1439 1440 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, MaybeAlign Align, 1441 AtomicOrdering Order, SyncScope::ID SSID, 1442 BasicBlock *InsertAtEnd) 1443 : Instruction(Type::getVoidTy(val->getContext()), Store, 1444 OperandTraits<StoreInst>::op_begin(this), 1445 OperandTraits<StoreInst>::operands(this), InsertAtEnd) { 1446 Op<0>() = val; 1447 Op<1>() = addr; 1448 setVolatile(isVolatile); 1449 setAlignment(Align); 1450 setAtomic(Order, SSID); 1451 AssertOK(); 1452 } 1453 1454 void StoreInst::setAlignment(MaybeAlign Alignment) { 1455 assert((!Alignment || *Alignment <= MaximumAlignment) && 1456 "Alignment is greater than MaximumAlignment!"); 1457 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1458 (encode(Alignment) << 1)); 1459 assert(getAlign() == Alignment && "Alignment representation error!"); 1460 } 1461 1462 //===----------------------------------------------------------------------===// 1463 // AtomicCmpXchgInst Implementation 1464 //===----------------------------------------------------------------------===// 1465 1466 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal, 1467 AtomicOrdering SuccessOrdering, 1468 AtomicOrdering FailureOrdering, 1469 SyncScope::ID SSID) { 1470 Op<0>() = Ptr; 1471 Op<1>() = Cmp; 1472 Op<2>() = NewVal; 1473 setSuccessOrdering(SuccessOrdering); 1474 setFailureOrdering(FailureOrdering); 1475 setSyncScopeID(SSID); 1476 1477 assert(getOperand(0) && getOperand(1) && getOperand(2) && 1478 "All operands must be non-null!"); 1479 assert(getOperand(0)->getType()->isPointerTy() && 1480 "Ptr must have pointer type!"); 1481 assert(getOperand(1)->getType() == 1482 cast<PointerType>(getOperand(0)->getType())->getElementType() 1483 && "Ptr must be a pointer to Cmp type!"); 1484 assert(getOperand(2)->getType() == 1485 cast<PointerType>(getOperand(0)->getType())->getElementType() 1486 && "Ptr must be a pointer to NewVal type!"); 1487 assert(SuccessOrdering != AtomicOrdering::NotAtomic && 1488 "AtomicCmpXchg instructions must be atomic!"); 1489 assert(FailureOrdering != AtomicOrdering::NotAtomic && 1490 "AtomicCmpXchg instructions must be atomic!"); 1491 assert(!isStrongerThan(FailureOrdering, SuccessOrdering) && 1492 "AtomicCmpXchg failure argument shall be no stronger than the success " 1493 "argument"); 1494 assert(FailureOrdering != AtomicOrdering::Release && 1495 FailureOrdering != AtomicOrdering::AcquireRelease && 1496 "AtomicCmpXchg failure ordering cannot include release semantics"); 1497 } 1498 1499 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1500 AtomicOrdering SuccessOrdering, 1501 AtomicOrdering FailureOrdering, 1502 SyncScope::ID SSID, 1503 Instruction *InsertBefore) 1504 : Instruction( 1505 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1506 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1507 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) { 1508 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID); 1509 } 1510 1511 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1512 AtomicOrdering SuccessOrdering, 1513 AtomicOrdering FailureOrdering, 1514 SyncScope::ID SSID, 1515 BasicBlock *InsertAtEnd) 1516 : Instruction( 1517 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1518 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1519 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) { 1520 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID); 1521 } 1522 1523 //===----------------------------------------------------------------------===// 1524 // AtomicRMWInst Implementation 1525 //===----------------------------------------------------------------------===// 1526 1527 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val, 1528 AtomicOrdering Ordering, 1529 SyncScope::ID SSID) { 1530 Op<0>() = Ptr; 1531 Op<1>() = Val; 1532 setOperation(Operation); 1533 setOrdering(Ordering); 1534 setSyncScopeID(SSID); 1535 1536 assert(getOperand(0) && getOperand(1) && 1537 "All operands must be non-null!"); 1538 assert(getOperand(0)->getType()->isPointerTy() && 1539 "Ptr must have pointer type!"); 1540 assert(getOperand(1)->getType() == 1541 cast<PointerType>(getOperand(0)->getType())->getElementType() 1542 && "Ptr must be a pointer to Val type!"); 1543 assert(Ordering != AtomicOrdering::NotAtomic && 1544 "AtomicRMW instructions must be atomic!"); 1545 } 1546 1547 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1548 AtomicOrdering Ordering, 1549 SyncScope::ID SSID, 1550 Instruction *InsertBefore) 1551 : Instruction(Val->getType(), AtomicRMW, 1552 OperandTraits<AtomicRMWInst>::op_begin(this), 1553 OperandTraits<AtomicRMWInst>::operands(this), 1554 InsertBefore) { 1555 Init(Operation, Ptr, Val, Ordering, SSID); 1556 } 1557 1558 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1559 AtomicOrdering Ordering, 1560 SyncScope::ID SSID, 1561 BasicBlock *InsertAtEnd) 1562 : Instruction(Val->getType(), AtomicRMW, 1563 OperandTraits<AtomicRMWInst>::op_begin(this), 1564 OperandTraits<AtomicRMWInst>::operands(this), 1565 InsertAtEnd) { 1566 Init(Operation, Ptr, Val, Ordering, SSID); 1567 } 1568 1569 StringRef AtomicRMWInst::getOperationName(BinOp Op) { 1570 switch (Op) { 1571 case AtomicRMWInst::Xchg: 1572 return "xchg"; 1573 case AtomicRMWInst::Add: 1574 return "add"; 1575 case AtomicRMWInst::Sub: 1576 return "sub"; 1577 case AtomicRMWInst::And: 1578 return "and"; 1579 case AtomicRMWInst::Nand: 1580 return "nand"; 1581 case AtomicRMWInst::Or: 1582 return "or"; 1583 case AtomicRMWInst::Xor: 1584 return "xor"; 1585 case AtomicRMWInst::Max: 1586 return "max"; 1587 case AtomicRMWInst::Min: 1588 return "min"; 1589 case AtomicRMWInst::UMax: 1590 return "umax"; 1591 case AtomicRMWInst::UMin: 1592 return "umin"; 1593 case AtomicRMWInst::FAdd: 1594 return "fadd"; 1595 case AtomicRMWInst::FSub: 1596 return "fsub"; 1597 case AtomicRMWInst::BAD_BINOP: 1598 return "<invalid operation>"; 1599 } 1600 1601 llvm_unreachable("invalid atomicrmw operation"); 1602 } 1603 1604 //===----------------------------------------------------------------------===// 1605 // FenceInst Implementation 1606 //===----------------------------------------------------------------------===// 1607 1608 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1609 SyncScope::ID SSID, 1610 Instruction *InsertBefore) 1611 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) { 1612 setOrdering(Ordering); 1613 setSyncScopeID(SSID); 1614 } 1615 1616 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1617 SyncScope::ID SSID, 1618 BasicBlock *InsertAtEnd) 1619 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) { 1620 setOrdering(Ordering); 1621 setSyncScopeID(SSID); 1622 } 1623 1624 //===----------------------------------------------------------------------===// 1625 // GetElementPtrInst Implementation 1626 //===----------------------------------------------------------------------===// 1627 1628 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList, 1629 const Twine &Name) { 1630 assert(getNumOperands() == 1 + IdxList.size() && 1631 "NumOperands not initialized?"); 1632 Op<0>() = Ptr; 1633 llvm::copy(IdxList, op_begin() + 1); 1634 setName(Name); 1635 } 1636 1637 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) 1638 : Instruction(GEPI.getType(), GetElementPtr, 1639 OperandTraits<GetElementPtrInst>::op_end(this) - 1640 GEPI.getNumOperands(), 1641 GEPI.getNumOperands()), 1642 SourceElementType(GEPI.SourceElementType), 1643 ResultElementType(GEPI.ResultElementType) { 1644 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin()); 1645 SubclassOptionalData = GEPI.SubclassOptionalData; 1646 } 1647 1648 Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, Value *Idx) { 1649 if (auto Struct = dyn_cast<StructType>(Ty)) { 1650 if (!Struct->indexValid(Idx)) 1651 return nullptr; 1652 return Struct->getTypeAtIndex(Idx); 1653 } 1654 if (!Idx->getType()->isIntOrIntVectorTy()) 1655 return nullptr; 1656 if (auto Array = dyn_cast<ArrayType>(Ty)) 1657 return Array->getElementType(); 1658 if (auto Vector = dyn_cast<VectorType>(Ty)) 1659 return Vector->getElementType(); 1660 return nullptr; 1661 } 1662 1663 Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, uint64_t Idx) { 1664 if (auto Struct = dyn_cast<StructType>(Ty)) { 1665 if (Idx >= Struct->getNumElements()) 1666 return nullptr; 1667 return Struct->getElementType(Idx); 1668 } 1669 if (auto Array = dyn_cast<ArrayType>(Ty)) 1670 return Array->getElementType(); 1671 if (auto Vector = dyn_cast<VectorType>(Ty)) 1672 return Vector->getElementType(); 1673 return nullptr; 1674 } 1675 1676 template <typename IndexTy> 1677 static Type *getIndexedTypeInternal(Type *Ty, ArrayRef<IndexTy> IdxList) { 1678 if (IdxList.empty()) 1679 return Ty; 1680 for (IndexTy V : IdxList.slice(1)) { 1681 Ty = GetElementPtrInst::getTypeAtIndex(Ty, V); 1682 if (!Ty) 1683 return Ty; 1684 } 1685 return Ty; 1686 } 1687 1688 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) { 1689 return getIndexedTypeInternal(Ty, IdxList); 1690 } 1691 1692 Type *GetElementPtrInst::getIndexedType(Type *Ty, 1693 ArrayRef<Constant *> IdxList) { 1694 return getIndexedTypeInternal(Ty, IdxList); 1695 } 1696 1697 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) { 1698 return getIndexedTypeInternal(Ty, IdxList); 1699 } 1700 1701 /// hasAllZeroIndices - Return true if all of the indices of this GEP are 1702 /// zeros. If so, the result pointer and the first operand have the same 1703 /// value, just potentially different types. 1704 bool GetElementPtrInst::hasAllZeroIndices() const { 1705 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1706 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { 1707 if (!CI->isZero()) return false; 1708 } else { 1709 return false; 1710 } 1711 } 1712 return true; 1713 } 1714 1715 /// hasAllConstantIndices - Return true if all of the indices of this GEP are 1716 /// constant integers. If so, the result pointer and the first operand have 1717 /// a constant offset between them. 1718 bool GetElementPtrInst::hasAllConstantIndices() const { 1719 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1720 if (!isa<ConstantInt>(getOperand(i))) 1721 return false; 1722 } 1723 return true; 1724 } 1725 1726 void GetElementPtrInst::setIsInBounds(bool B) { 1727 cast<GEPOperator>(this)->setIsInBounds(B); 1728 } 1729 1730 bool GetElementPtrInst::isInBounds() const { 1731 return cast<GEPOperator>(this)->isInBounds(); 1732 } 1733 1734 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL, 1735 APInt &Offset) const { 1736 // Delegate to the generic GEPOperator implementation. 1737 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset); 1738 } 1739 1740 //===----------------------------------------------------------------------===// 1741 // ExtractElementInst Implementation 1742 //===----------------------------------------------------------------------===// 1743 1744 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1745 const Twine &Name, 1746 Instruction *InsertBef) 1747 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1748 ExtractElement, 1749 OperandTraits<ExtractElementInst>::op_begin(this), 1750 2, InsertBef) { 1751 assert(isValidOperands(Val, Index) && 1752 "Invalid extractelement instruction operands!"); 1753 Op<0>() = Val; 1754 Op<1>() = Index; 1755 setName(Name); 1756 } 1757 1758 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1759 const Twine &Name, 1760 BasicBlock *InsertAE) 1761 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1762 ExtractElement, 1763 OperandTraits<ExtractElementInst>::op_begin(this), 1764 2, InsertAE) { 1765 assert(isValidOperands(Val, Index) && 1766 "Invalid extractelement instruction operands!"); 1767 1768 Op<0>() = Val; 1769 Op<1>() = Index; 1770 setName(Name); 1771 } 1772 1773 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { 1774 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy()) 1775 return false; 1776 return true; 1777 } 1778 1779 //===----------------------------------------------------------------------===// 1780 // InsertElementInst Implementation 1781 //===----------------------------------------------------------------------===// 1782 1783 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1784 const Twine &Name, 1785 Instruction *InsertBef) 1786 : Instruction(Vec->getType(), InsertElement, 1787 OperandTraits<InsertElementInst>::op_begin(this), 1788 3, InsertBef) { 1789 assert(isValidOperands(Vec, Elt, Index) && 1790 "Invalid insertelement instruction operands!"); 1791 Op<0>() = Vec; 1792 Op<1>() = Elt; 1793 Op<2>() = Index; 1794 setName(Name); 1795 } 1796 1797 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1798 const Twine &Name, 1799 BasicBlock *InsertAE) 1800 : Instruction(Vec->getType(), InsertElement, 1801 OperandTraits<InsertElementInst>::op_begin(this), 1802 3, InsertAE) { 1803 assert(isValidOperands(Vec, Elt, Index) && 1804 "Invalid insertelement instruction operands!"); 1805 1806 Op<0>() = Vec; 1807 Op<1>() = Elt; 1808 Op<2>() = Index; 1809 setName(Name); 1810 } 1811 1812 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 1813 const Value *Index) { 1814 if (!Vec->getType()->isVectorTy()) 1815 return false; // First operand of insertelement must be vector type. 1816 1817 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) 1818 return false;// Second operand of insertelement must be vector element type. 1819 1820 if (!Index->getType()->isIntegerTy()) 1821 return false; // Third operand of insertelement must be i32. 1822 return true; 1823 } 1824 1825 //===----------------------------------------------------------------------===// 1826 // ShuffleVectorInst Implementation 1827 //===----------------------------------------------------------------------===// 1828 1829 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1830 const Twine &Name, 1831 Instruction *InsertBefore) 1832 : Instruction( 1833 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1834 cast<VectorType>(Mask->getType())->getElementCount()), 1835 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1836 OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) { 1837 assert(isValidOperands(V1, V2, Mask) && 1838 "Invalid shuffle vector instruction operands!"); 1839 1840 Op<0>() = V1; 1841 Op<1>() = V2; 1842 SmallVector<int, 16> MaskArr; 1843 getShuffleMask(cast<Constant>(Mask), MaskArr); 1844 setShuffleMask(MaskArr); 1845 setName(Name); 1846 } 1847 1848 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1849 const Twine &Name, BasicBlock *InsertAtEnd) 1850 : Instruction( 1851 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1852 cast<VectorType>(Mask->getType())->getElementCount()), 1853 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1854 OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) { 1855 assert(isValidOperands(V1, V2, Mask) && 1856 "Invalid shuffle vector instruction operands!"); 1857 1858 Op<0>() = V1; 1859 Op<1>() = V2; 1860 SmallVector<int, 16> MaskArr; 1861 getShuffleMask(cast<Constant>(Mask), MaskArr); 1862 setShuffleMask(MaskArr); 1863 setName(Name); 1864 } 1865 1866 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, 1867 const Twine &Name, 1868 Instruction *InsertBefore) 1869 : Instruction( 1870 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1871 Mask.size(), isa<ScalableVectorType>(V1->getType())), 1872 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1873 OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) { 1874 assert(isValidOperands(V1, V2, Mask) && 1875 "Invalid shuffle vector instruction operands!"); 1876 Op<0>() = V1; 1877 Op<1>() = V2; 1878 setShuffleMask(Mask); 1879 setName(Name); 1880 } 1881 1882 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, 1883 const Twine &Name, BasicBlock *InsertAtEnd) 1884 : Instruction( 1885 VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1886 Mask.size(), isa<ScalableVectorType>(V1->getType())), 1887 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), 1888 OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) { 1889 assert(isValidOperands(V1, V2, Mask) && 1890 "Invalid shuffle vector instruction operands!"); 1891 1892 Op<0>() = V1; 1893 Op<1>() = V2; 1894 setShuffleMask(Mask); 1895 setName(Name); 1896 } 1897 1898 void ShuffleVectorInst::commute() { 1899 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 1900 int NumMaskElts = ShuffleMask.size(); 1901 SmallVector<int, 16> NewMask(NumMaskElts); 1902 for (int i = 0; i != NumMaskElts; ++i) { 1903 int MaskElt = getMaskValue(i); 1904 if (MaskElt == UndefMaskElem) { 1905 NewMask[i] = UndefMaskElem; 1906 continue; 1907 } 1908 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask"); 1909 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts; 1910 NewMask[i] = MaskElt; 1911 } 1912 setShuffleMask(NewMask); 1913 Op<0>().swap(Op<1>()); 1914 } 1915 1916 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 1917 ArrayRef<int> Mask) { 1918 // V1 and V2 must be vectors of the same type. 1919 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType()) 1920 return false; 1921 1922 // Make sure the mask elements make sense. 1923 int V1Size = cast<VectorType>(V1->getType())->getElementCount().Min; 1924 for (int Elem : Mask) 1925 if (Elem != UndefMaskElem && Elem >= V1Size * 2) 1926 return false; 1927 1928 if (isa<ScalableVectorType>(V1->getType())) 1929 if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !is_splat(Mask)) 1930 return false; 1931 1932 return true; 1933 } 1934 1935 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 1936 const Value *Mask) { 1937 // V1 and V2 must be vectors of the same type. 1938 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType()) 1939 return false; 1940 1941 // Mask must be vector of i32, and must be the same kind of vector as the 1942 // input vectors 1943 auto *MaskTy = dyn_cast<VectorType>(Mask->getType()); 1944 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) || 1945 isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType())) 1946 return false; 1947 1948 // Check to see if Mask is valid. 1949 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask)) 1950 return true; 1951 1952 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) { 1953 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1954 for (Value *Op : MV->operands()) { 1955 if (auto *CI = dyn_cast<ConstantInt>(Op)) { 1956 if (CI->uge(V1Size*2)) 1957 return false; 1958 } else if (!isa<UndefValue>(Op)) { 1959 return false; 1960 } 1961 } 1962 return true; 1963 } 1964 1965 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 1966 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1967 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i) 1968 if (CDS->getElementAsInteger(i) >= V1Size*2) 1969 return false; 1970 return true; 1971 } 1972 1973 return false; 1974 } 1975 1976 void ShuffleVectorInst::getShuffleMask(const Constant *Mask, 1977 SmallVectorImpl<int> &Result) { 1978 unsigned NumElts = cast<VectorType>(Mask->getType())->getElementCount().Min; 1979 if (isa<ConstantAggregateZero>(Mask)) { 1980 Result.resize(NumElts, 0); 1981 return; 1982 } 1983 Result.reserve(NumElts); 1984 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 1985 for (unsigned i = 0; i != NumElts; ++i) 1986 Result.push_back(CDS->getElementAsInteger(i)); 1987 return; 1988 } 1989 for (unsigned i = 0; i != NumElts; ++i) { 1990 Constant *C = Mask->getAggregateElement(i); 1991 Result.push_back(isa<UndefValue>(C) ? -1 : 1992 cast<ConstantInt>(C)->getZExtValue()); 1993 } 1994 } 1995 1996 void ShuffleVectorInst::setShuffleMask(ArrayRef<int> Mask) { 1997 ShuffleMask.assign(Mask.begin(), Mask.end()); 1998 ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType()); 1999 } 2000 Constant *ShuffleVectorInst::convertShuffleMaskForBitcode(ArrayRef<int> Mask, 2001 Type *ResultTy) { 2002 Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext()); 2003 if (isa<ScalableVectorType>(ResultTy)) { 2004 assert(is_splat(Mask) && "Unexpected shuffle"); 2005 Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true); 2006 if (Mask[0] == 0) 2007 return Constant::getNullValue(VecTy); 2008 return UndefValue::get(VecTy); 2009 } 2010 SmallVector<Constant *, 16> MaskConst; 2011 for (int Elem : Mask) { 2012 if (Elem == UndefMaskElem) 2013 MaskConst.push_back(UndefValue::get(Int32Ty)); 2014 else 2015 MaskConst.push_back(ConstantInt::get(Int32Ty, Elem)); 2016 } 2017 return ConstantVector::get(MaskConst); 2018 } 2019 2020 static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) { 2021 assert(!Mask.empty() && "Shuffle mask must contain elements"); 2022 bool UsesLHS = false; 2023 bool UsesRHS = false; 2024 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) { 2025 if (Mask[i] == -1) 2026 continue; 2027 assert(Mask[i] >= 0 && Mask[i] < (NumOpElts * 2) && 2028 "Out-of-bounds shuffle mask element"); 2029 UsesLHS |= (Mask[i] < NumOpElts); 2030 UsesRHS |= (Mask[i] >= NumOpElts); 2031 if (UsesLHS && UsesRHS) 2032 return false; 2033 } 2034 assert((UsesLHS ^ UsesRHS) && "Should have selected from exactly 1 source"); 2035 return true; 2036 } 2037 2038 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) { 2039 // We don't have vector operand size information, so assume operands are the 2040 // same size as the mask. 2041 return isSingleSourceMaskImpl(Mask, Mask.size()); 2042 } 2043 2044 static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) { 2045 if (!isSingleSourceMaskImpl(Mask, NumOpElts)) 2046 return false; 2047 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) { 2048 if (Mask[i] == -1) 2049 continue; 2050 if (Mask[i] != i && Mask[i] != (NumOpElts + i)) 2051 return false; 2052 } 2053 return true; 2054 } 2055 2056 bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) { 2057 // We don't have vector operand size information, so assume operands are the 2058 // same size as the mask. 2059 return isIdentityMaskImpl(Mask, Mask.size()); 2060 } 2061 2062 bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) { 2063 if (!isSingleSourceMask(Mask)) 2064 return false; 2065 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 2066 if (Mask[i] == -1) 2067 continue; 2068 if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i)) 2069 return false; 2070 } 2071 return true; 2072 } 2073 2074 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) { 2075 if (!isSingleSourceMask(Mask)) 2076 return false; 2077 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 2078 if (Mask[i] == -1) 2079 continue; 2080 if (Mask[i] != 0 && Mask[i] != NumElts) 2081 return false; 2082 } 2083 return true; 2084 } 2085 2086 bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) { 2087 // Select is differentiated from identity. It requires using both sources. 2088 if (isSingleSourceMask(Mask)) 2089 return false; 2090 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 2091 if (Mask[i] == -1) 2092 continue; 2093 if (Mask[i] != i && Mask[i] != (NumElts + i)) 2094 return false; 2095 } 2096 return true; 2097 } 2098 2099 bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) { 2100 // Example masks that will return true: 2101 // v1 = <a, b, c, d> 2102 // v2 = <e, f, g, h> 2103 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g> 2104 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h> 2105 2106 // 1. The number of elements in the mask must be a power-of-2 and at least 2. 2107 int NumElts = Mask.size(); 2108 if (NumElts < 2 || !isPowerOf2_32(NumElts)) 2109 return false; 2110 2111 // 2. The first element of the mask must be either a 0 or a 1. 2112 if (Mask[0] != 0 && Mask[0] != 1) 2113 return false; 2114 2115 // 3. The difference between the first 2 elements must be equal to the 2116 // number of elements in the mask. 2117 if ((Mask[1] - Mask[0]) != NumElts) 2118 return false; 2119 2120 // 4. The difference between consecutive even-numbered and odd-numbered 2121 // elements must be equal to 2. 2122 for (int i = 2; i < NumElts; ++i) { 2123 int MaskEltVal = Mask[i]; 2124 if (MaskEltVal == -1) 2125 return false; 2126 int MaskEltPrevVal = Mask[i - 2]; 2127 if (MaskEltVal - MaskEltPrevVal != 2) 2128 return false; 2129 } 2130 return true; 2131 } 2132 2133 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask, 2134 int NumSrcElts, int &Index) { 2135 // Must extract from a single source. 2136 if (!isSingleSourceMaskImpl(Mask, NumSrcElts)) 2137 return false; 2138 2139 // Must be smaller (else this is an Identity shuffle). 2140 if (NumSrcElts <= (int)Mask.size()) 2141 return false; 2142 2143 // Find start of extraction, accounting that we may start with an UNDEF. 2144 int SubIndex = -1; 2145 for (int i = 0, e = Mask.size(); i != e; ++i) { 2146 int M = Mask[i]; 2147 if (M < 0) 2148 continue; 2149 int Offset = (M % NumSrcElts) - i; 2150 if (0 <= SubIndex && SubIndex != Offset) 2151 return false; 2152 SubIndex = Offset; 2153 } 2154 2155 if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) { 2156 Index = SubIndex; 2157 return true; 2158 } 2159 return false; 2160 } 2161 2162 bool ShuffleVectorInst::isIdentityWithPadding() const { 2163 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 2164 int NumMaskElts = cast<VectorType>(getType())->getNumElements(); 2165 if (NumMaskElts <= NumOpElts) 2166 return false; 2167 2168 // The first part of the mask must choose elements from exactly 1 source op. 2169 ArrayRef<int> Mask = getShuffleMask(); 2170 if (!isIdentityMaskImpl(Mask, NumOpElts)) 2171 return false; 2172 2173 // All extending must be with undef elements. 2174 for (int i = NumOpElts; i < NumMaskElts; ++i) 2175 if (Mask[i] != -1) 2176 return false; 2177 2178 return true; 2179 } 2180 2181 bool ShuffleVectorInst::isIdentityWithExtract() const { 2182 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 2183 int NumMaskElts = getType()->getNumElements(); 2184 if (NumMaskElts >= NumOpElts) 2185 return false; 2186 2187 return isIdentityMaskImpl(getShuffleMask(), NumOpElts); 2188 } 2189 2190 bool ShuffleVectorInst::isConcat() const { 2191 // Vector concatenation is differentiated from identity with padding. 2192 if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>())) 2193 return false; 2194 2195 int NumOpElts = cast<VectorType>(Op<0>()->getType())->getNumElements(); 2196 int NumMaskElts = getType()->getNumElements(); 2197 if (NumMaskElts != NumOpElts * 2) 2198 return false; 2199 2200 // Use the mask length rather than the operands' vector lengths here. We 2201 // already know that the shuffle returns a vector twice as long as the inputs, 2202 // and neither of the inputs are undef vectors. If the mask picks consecutive 2203 // elements from both inputs, then this is a concatenation of the inputs. 2204 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts); 2205 } 2206 2207 //===----------------------------------------------------------------------===// 2208 // InsertValueInst Class 2209 //===----------------------------------------------------------------------===// 2210 2211 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 2212 const Twine &Name) { 2213 assert(getNumOperands() == 2 && "NumOperands not initialized?"); 2214 2215 // There's no fundamental reason why we require at least one index 2216 // (other than weirdness with &*IdxBegin being invalid; see 2217 // getelementptr's init routine for example). But there's no 2218 // present need to support it. 2219 assert(!Idxs.empty() && "InsertValueInst must have at least one index"); 2220 2221 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) == 2222 Val->getType() && "Inserted value must match indexed type!"); 2223 Op<0>() = Agg; 2224 Op<1>() = Val; 2225 2226 Indices.append(Idxs.begin(), Idxs.end()); 2227 setName(Name); 2228 } 2229 2230 InsertValueInst::InsertValueInst(const InsertValueInst &IVI) 2231 : Instruction(IVI.getType(), InsertValue, 2232 OperandTraits<InsertValueInst>::op_begin(this), 2), 2233 Indices(IVI.Indices) { 2234 Op<0>() = IVI.getOperand(0); 2235 Op<1>() = IVI.getOperand(1); 2236 SubclassOptionalData = IVI.SubclassOptionalData; 2237 } 2238 2239 //===----------------------------------------------------------------------===// 2240 // ExtractValueInst Class 2241 //===----------------------------------------------------------------------===// 2242 2243 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) { 2244 assert(getNumOperands() == 1 && "NumOperands not initialized?"); 2245 2246 // There's no fundamental reason why we require at least one index. 2247 // But there's no present need to support it. 2248 assert(!Idxs.empty() && "ExtractValueInst must have at least one index"); 2249 2250 Indices.append(Idxs.begin(), Idxs.end()); 2251 setName(Name); 2252 } 2253 2254 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) 2255 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), 2256 Indices(EVI.Indices) { 2257 SubclassOptionalData = EVI.SubclassOptionalData; 2258 } 2259 2260 // getIndexedType - Returns the type of the element that would be extracted 2261 // with an extractvalue instruction with the specified parameters. 2262 // 2263 // A null type is returned if the indices are invalid for the specified 2264 // pointer type. 2265 // 2266 Type *ExtractValueInst::getIndexedType(Type *Agg, 2267 ArrayRef<unsigned> Idxs) { 2268 for (unsigned Index : Idxs) { 2269 // We can't use CompositeType::indexValid(Index) here. 2270 // indexValid() always returns true for arrays because getelementptr allows 2271 // out-of-bounds indices. Since we don't allow those for extractvalue and 2272 // insertvalue we need to check array indexing manually. 2273 // Since the only other types we can index into are struct types it's just 2274 // as easy to check those manually as well. 2275 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) { 2276 if (Index >= AT->getNumElements()) 2277 return nullptr; 2278 Agg = AT->getElementType(); 2279 } else if (StructType *ST = dyn_cast<StructType>(Agg)) { 2280 if (Index >= ST->getNumElements()) 2281 return nullptr; 2282 Agg = ST->getElementType(Index); 2283 } else { 2284 // Not a valid type to index into. 2285 return nullptr; 2286 } 2287 } 2288 return const_cast<Type*>(Agg); 2289 } 2290 2291 //===----------------------------------------------------------------------===// 2292 // UnaryOperator Class 2293 //===----------------------------------------------------------------------===// 2294 2295 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2296 Type *Ty, const Twine &Name, 2297 Instruction *InsertBefore) 2298 : UnaryInstruction(Ty, iType, S, InsertBefore) { 2299 Op<0>() = S; 2300 setName(Name); 2301 AssertOK(); 2302 } 2303 2304 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2305 Type *Ty, const Twine &Name, 2306 BasicBlock *InsertAtEnd) 2307 : UnaryInstruction(Ty, iType, S, InsertAtEnd) { 2308 Op<0>() = S; 2309 setName(Name); 2310 AssertOK(); 2311 } 2312 2313 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2314 const Twine &Name, 2315 Instruction *InsertBefore) { 2316 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore); 2317 } 2318 2319 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2320 const Twine &Name, 2321 BasicBlock *InsertAtEnd) { 2322 UnaryOperator *Res = Create(Op, S, Name); 2323 InsertAtEnd->getInstList().push_back(Res); 2324 return Res; 2325 } 2326 2327 void UnaryOperator::AssertOK() { 2328 Value *LHS = getOperand(0); 2329 (void)LHS; // Silence warnings. 2330 #ifndef NDEBUG 2331 switch (getOpcode()) { 2332 case FNeg: 2333 assert(getType() == LHS->getType() && 2334 "Unary operation should return same type as operand!"); 2335 assert(getType()->isFPOrFPVectorTy() && 2336 "Tried to create a floating-point operation on a " 2337 "non-floating-point type!"); 2338 break; 2339 default: llvm_unreachable("Invalid opcode provided"); 2340 } 2341 #endif 2342 } 2343 2344 //===----------------------------------------------------------------------===// 2345 // BinaryOperator Class 2346 //===----------------------------------------------------------------------===// 2347 2348 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2349 Type *Ty, const Twine &Name, 2350 Instruction *InsertBefore) 2351 : Instruction(Ty, iType, 2352 OperandTraits<BinaryOperator>::op_begin(this), 2353 OperandTraits<BinaryOperator>::operands(this), 2354 InsertBefore) { 2355 Op<0>() = S1; 2356 Op<1>() = S2; 2357 setName(Name); 2358 AssertOK(); 2359 } 2360 2361 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2362 Type *Ty, const Twine &Name, 2363 BasicBlock *InsertAtEnd) 2364 : Instruction(Ty, iType, 2365 OperandTraits<BinaryOperator>::op_begin(this), 2366 OperandTraits<BinaryOperator>::operands(this), 2367 InsertAtEnd) { 2368 Op<0>() = S1; 2369 Op<1>() = S2; 2370 setName(Name); 2371 AssertOK(); 2372 } 2373 2374 void BinaryOperator::AssertOK() { 2375 Value *LHS = getOperand(0), *RHS = getOperand(1); 2376 (void)LHS; (void)RHS; // Silence warnings. 2377 assert(LHS->getType() == RHS->getType() && 2378 "Binary operator operand types must match!"); 2379 #ifndef NDEBUG 2380 switch (getOpcode()) { 2381 case Add: case Sub: 2382 case Mul: 2383 assert(getType() == LHS->getType() && 2384 "Arithmetic operation should return same type as operands!"); 2385 assert(getType()->isIntOrIntVectorTy() && 2386 "Tried to create an integer operation on a non-integer type!"); 2387 break; 2388 case FAdd: case FSub: 2389 case FMul: 2390 assert(getType() == LHS->getType() && 2391 "Arithmetic operation should return same type as operands!"); 2392 assert(getType()->isFPOrFPVectorTy() && 2393 "Tried to create a floating-point operation on a " 2394 "non-floating-point type!"); 2395 break; 2396 case UDiv: 2397 case SDiv: 2398 assert(getType() == LHS->getType() && 2399 "Arithmetic operation should return same type as operands!"); 2400 assert(getType()->isIntOrIntVectorTy() && 2401 "Incorrect operand type (not integer) for S/UDIV"); 2402 break; 2403 case FDiv: 2404 assert(getType() == LHS->getType() && 2405 "Arithmetic operation should return same type as operands!"); 2406 assert(getType()->isFPOrFPVectorTy() && 2407 "Incorrect operand type (not floating point) for FDIV"); 2408 break; 2409 case URem: 2410 case SRem: 2411 assert(getType() == LHS->getType() && 2412 "Arithmetic operation should return same type as operands!"); 2413 assert(getType()->isIntOrIntVectorTy() && 2414 "Incorrect operand type (not integer) for S/UREM"); 2415 break; 2416 case FRem: 2417 assert(getType() == LHS->getType() && 2418 "Arithmetic operation should return same type as operands!"); 2419 assert(getType()->isFPOrFPVectorTy() && 2420 "Incorrect operand type (not floating point) for FREM"); 2421 break; 2422 case Shl: 2423 case LShr: 2424 case AShr: 2425 assert(getType() == LHS->getType() && 2426 "Shift operation should return same type as operands!"); 2427 assert(getType()->isIntOrIntVectorTy() && 2428 "Tried to create a shift operation on a non-integral type!"); 2429 break; 2430 case And: case Or: 2431 case Xor: 2432 assert(getType() == LHS->getType() && 2433 "Logical operation should return same type as operands!"); 2434 assert(getType()->isIntOrIntVectorTy() && 2435 "Tried to create a logical operation on a non-integral type!"); 2436 break; 2437 default: llvm_unreachable("Invalid opcode provided"); 2438 } 2439 #endif 2440 } 2441 2442 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2443 const Twine &Name, 2444 Instruction *InsertBefore) { 2445 assert(S1->getType() == S2->getType() && 2446 "Cannot create binary operator with two operands of differing type!"); 2447 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); 2448 } 2449 2450 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2451 const Twine &Name, 2452 BasicBlock *InsertAtEnd) { 2453 BinaryOperator *Res = Create(Op, S1, S2, Name); 2454 InsertAtEnd->getInstList().push_back(Res); 2455 return Res; 2456 } 2457 2458 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2459 Instruction *InsertBefore) { 2460 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2461 return new BinaryOperator(Instruction::Sub, 2462 zero, Op, 2463 Op->getType(), Name, InsertBefore); 2464 } 2465 2466 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2467 BasicBlock *InsertAtEnd) { 2468 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2469 return new BinaryOperator(Instruction::Sub, 2470 zero, Op, 2471 Op->getType(), Name, InsertAtEnd); 2472 } 2473 2474 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2475 Instruction *InsertBefore) { 2476 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2477 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore); 2478 } 2479 2480 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2481 BasicBlock *InsertAtEnd) { 2482 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2483 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd); 2484 } 2485 2486 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2487 Instruction *InsertBefore) { 2488 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2489 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore); 2490 } 2491 2492 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2493 BasicBlock *InsertAtEnd) { 2494 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2495 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd); 2496 } 2497 2498 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2499 Instruction *InsertBefore) { 2500 Constant *C = Constant::getAllOnesValue(Op->getType()); 2501 return new BinaryOperator(Instruction::Xor, Op, C, 2502 Op->getType(), Name, InsertBefore); 2503 } 2504 2505 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2506 BasicBlock *InsertAtEnd) { 2507 Constant *AllOnes = Constant::getAllOnesValue(Op->getType()); 2508 return new BinaryOperator(Instruction::Xor, Op, AllOnes, 2509 Op->getType(), Name, InsertAtEnd); 2510 } 2511 2512 // Exchange the two operands to this instruction. This instruction is safe to 2513 // use on any binary instruction and does not modify the semantics of the 2514 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode 2515 // is changed. 2516 bool BinaryOperator::swapOperands() { 2517 if (!isCommutative()) 2518 return true; // Can't commute operands 2519 Op<0>().swap(Op<1>()); 2520 return false; 2521 } 2522 2523 //===----------------------------------------------------------------------===// 2524 // FPMathOperator Class 2525 //===----------------------------------------------------------------------===// 2526 2527 float FPMathOperator::getFPAccuracy() const { 2528 const MDNode *MD = 2529 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath); 2530 if (!MD) 2531 return 0.0; 2532 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0)); 2533 return Accuracy->getValueAPF().convertToFloat(); 2534 } 2535 2536 //===----------------------------------------------------------------------===// 2537 // CastInst Class 2538 //===----------------------------------------------------------------------===// 2539 2540 // Just determine if this cast only deals with integral->integral conversion. 2541 bool CastInst::isIntegerCast() const { 2542 switch (getOpcode()) { 2543 default: return false; 2544 case Instruction::ZExt: 2545 case Instruction::SExt: 2546 case Instruction::Trunc: 2547 return true; 2548 case Instruction::BitCast: 2549 return getOperand(0)->getType()->isIntegerTy() && 2550 getType()->isIntegerTy(); 2551 } 2552 } 2553 2554 bool CastInst::isLosslessCast() const { 2555 // Only BitCast can be lossless, exit fast if we're not BitCast 2556 if (getOpcode() != Instruction::BitCast) 2557 return false; 2558 2559 // Identity cast is always lossless 2560 Type *SrcTy = getOperand(0)->getType(); 2561 Type *DstTy = getType(); 2562 if (SrcTy == DstTy) 2563 return true; 2564 2565 // Pointer to pointer is always lossless. 2566 if (SrcTy->isPointerTy()) 2567 return DstTy->isPointerTy(); 2568 return false; // Other types have no identity values 2569 } 2570 2571 /// This function determines if the CastInst does not require any bits to be 2572 /// changed in order to effect the cast. Essentially, it identifies cases where 2573 /// no code gen is necessary for the cast, hence the name no-op cast. For 2574 /// example, the following are all no-op casts: 2575 /// # bitcast i32* %x to i8* 2576 /// # bitcast <2 x i32> %x to <4 x i16> 2577 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only 2578 /// Determine if the described cast is a no-op. 2579 bool CastInst::isNoopCast(Instruction::CastOps Opcode, 2580 Type *SrcTy, 2581 Type *DestTy, 2582 const DataLayout &DL) { 2583 switch (Opcode) { 2584 default: llvm_unreachable("Invalid CastOp"); 2585 case Instruction::Trunc: 2586 case Instruction::ZExt: 2587 case Instruction::SExt: 2588 case Instruction::FPTrunc: 2589 case Instruction::FPExt: 2590 case Instruction::UIToFP: 2591 case Instruction::SIToFP: 2592 case Instruction::FPToUI: 2593 case Instruction::FPToSI: 2594 case Instruction::AddrSpaceCast: 2595 // TODO: Target informations may give a more accurate answer here. 2596 return false; 2597 case Instruction::BitCast: 2598 return true; // BitCast never modifies bits. 2599 case Instruction::PtrToInt: 2600 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() == 2601 DestTy->getScalarSizeInBits(); 2602 case Instruction::IntToPtr: 2603 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() == 2604 SrcTy->getScalarSizeInBits(); 2605 } 2606 } 2607 2608 bool CastInst::isNoopCast(const DataLayout &DL) const { 2609 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL); 2610 } 2611 2612 /// This function determines if a pair of casts can be eliminated and what 2613 /// opcode should be used in the elimination. This assumes that there are two 2614 /// instructions like this: 2615 /// * %F = firstOpcode SrcTy %x to MidTy 2616 /// * %S = secondOpcode MidTy %F to DstTy 2617 /// The function returns a resultOpcode so these two casts can be replaced with: 2618 /// * %Replacement = resultOpcode %SrcTy %x to DstTy 2619 /// If no such cast is permitted, the function returns 0. 2620 unsigned CastInst::isEliminableCastPair( 2621 Instruction::CastOps firstOp, Instruction::CastOps secondOp, 2622 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, 2623 Type *DstIntPtrTy) { 2624 // Define the 144 possibilities for these two cast instructions. The values 2625 // in this matrix determine what to do in a given situation and select the 2626 // case in the switch below. The rows correspond to firstOp, the columns 2627 // correspond to secondOp. In looking at the table below, keep in mind 2628 // the following cast properties: 2629 // 2630 // Size Compare Source Destination 2631 // Operator Src ? Size Type Sign Type Sign 2632 // -------- ------------ ------------------- --------------------- 2633 // TRUNC > Integer Any Integral Any 2634 // ZEXT < Integral Unsigned Integer Any 2635 // SEXT < Integral Signed Integer Any 2636 // FPTOUI n/a FloatPt n/a Integral Unsigned 2637 // FPTOSI n/a FloatPt n/a Integral Signed 2638 // UITOFP n/a Integral Unsigned FloatPt n/a 2639 // SITOFP n/a Integral Signed FloatPt n/a 2640 // FPTRUNC > FloatPt n/a FloatPt n/a 2641 // FPEXT < FloatPt n/a FloatPt n/a 2642 // PTRTOINT n/a Pointer n/a Integral Unsigned 2643 // INTTOPTR n/a Integral Unsigned Pointer n/a 2644 // BITCAST = FirstClass n/a FirstClass n/a 2645 // ADDRSPCST n/a Pointer n/a Pointer n/a 2646 // 2647 // NOTE: some transforms are safe, but we consider them to be non-profitable. 2648 // For example, we could merge "fptoui double to i32" + "zext i32 to i64", 2649 // into "fptoui double to i64", but this loses information about the range 2650 // of the produced value (we no longer know the top-part is all zeros). 2651 // Further this conversion is often much more expensive for typical hardware, 2652 // and causes issues when building libgcc. We disallow fptosi+sext for the 2653 // same reason. 2654 const unsigned numCastOps = 2655 Instruction::CastOpsEnd - Instruction::CastOpsBegin; 2656 static const uint8_t CastResults[numCastOps][numCastOps] = { 2657 // T F F U S F F P I B A -+ 2658 // R Z S P P I I T P 2 N T S | 2659 // U E E 2 2 2 2 R E I T C C +- secondOp 2660 // N X X U S F F N X N 2 V V | 2661 // C T T I I P P C T T P T T -+ 2662 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+ 2663 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt | 2664 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt | 2665 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI | 2666 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI | 2667 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp 2668 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP | 2669 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc | 2670 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt | 2671 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt | 2672 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr | 2673 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast | 2674 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+ 2675 }; 2676 2677 // TODO: This logic could be encoded into the table above and handled in the 2678 // switch below. 2679 // If either of the casts are a bitcast from scalar to vector, disallow the 2680 // merging. However, any pair of bitcasts are allowed. 2681 bool IsFirstBitcast = (firstOp == Instruction::BitCast); 2682 bool IsSecondBitcast = (secondOp == Instruction::BitCast); 2683 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast; 2684 2685 // Check if any of the casts convert scalars <-> vectors. 2686 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) || 2687 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy))) 2688 if (!AreBothBitcasts) 2689 return 0; 2690 2691 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] 2692 [secondOp-Instruction::CastOpsBegin]; 2693 switch (ElimCase) { 2694 case 0: 2695 // Categorically disallowed. 2696 return 0; 2697 case 1: 2698 // Allowed, use first cast's opcode. 2699 return firstOp; 2700 case 2: 2701 // Allowed, use second cast's opcode. 2702 return secondOp; 2703 case 3: 2704 // No-op cast in second op implies firstOp as long as the DestTy 2705 // is integer and we are not converting between a vector and a 2706 // non-vector type. 2707 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy()) 2708 return firstOp; 2709 return 0; 2710 case 4: 2711 // No-op cast in second op implies firstOp as long as the DestTy 2712 // is floating point. 2713 if (DstTy->isFloatingPointTy()) 2714 return firstOp; 2715 return 0; 2716 case 5: 2717 // No-op cast in first op implies secondOp as long as the SrcTy 2718 // is an integer. 2719 if (SrcTy->isIntegerTy()) 2720 return secondOp; 2721 return 0; 2722 case 6: 2723 // No-op cast in first op implies secondOp as long as the SrcTy 2724 // is a floating point. 2725 if (SrcTy->isFloatingPointTy()) 2726 return secondOp; 2727 return 0; 2728 case 7: { 2729 // Cannot simplify if address spaces are different! 2730 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2731 return 0; 2732 2733 unsigned MidSize = MidTy->getScalarSizeInBits(); 2734 // We can still fold this without knowing the actual sizes as long we 2735 // know that the intermediate pointer is the largest possible 2736 // pointer size. 2737 // FIXME: Is this always true? 2738 if (MidSize == 64) 2739 return Instruction::BitCast; 2740 2741 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size. 2742 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy) 2743 return 0; 2744 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits(); 2745 if (MidSize >= PtrSize) 2746 return Instruction::BitCast; 2747 return 0; 2748 } 2749 case 8: { 2750 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size 2751 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) 2752 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) 2753 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2754 unsigned DstSize = DstTy->getScalarSizeInBits(); 2755 if (SrcSize == DstSize) 2756 return Instruction::BitCast; 2757 else if (SrcSize < DstSize) 2758 return firstOp; 2759 return secondOp; 2760 } 2761 case 9: 2762 // zext, sext -> zext, because sext can't sign extend after zext 2763 return Instruction::ZExt; 2764 case 11: { 2765 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize 2766 if (!MidIntPtrTy) 2767 return 0; 2768 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits(); 2769 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2770 unsigned DstSize = DstTy->getScalarSizeInBits(); 2771 if (SrcSize <= PtrSize && SrcSize == DstSize) 2772 return Instruction::BitCast; 2773 return 0; 2774 } 2775 case 12: 2776 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS 2777 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS 2778 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2779 return Instruction::AddrSpaceCast; 2780 return Instruction::BitCast; 2781 case 13: 2782 // FIXME: this state can be merged with (1), but the following assert 2783 // is useful to check the correcteness of the sequence due to semantic 2784 // change of bitcast. 2785 assert( 2786 SrcTy->isPtrOrPtrVectorTy() && 2787 MidTy->isPtrOrPtrVectorTy() && 2788 DstTy->isPtrOrPtrVectorTy() && 2789 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() && 2790 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2791 "Illegal addrspacecast, bitcast sequence!"); 2792 // Allowed, use first cast's opcode 2793 return firstOp; 2794 case 14: 2795 // bitcast, addrspacecast -> addrspacecast if the element type of 2796 // bitcast's source is the same as that of addrspacecast's destination. 2797 if (SrcTy->getScalarType()->getPointerElementType() == 2798 DstTy->getScalarType()->getPointerElementType()) 2799 return Instruction::AddrSpaceCast; 2800 return 0; 2801 case 15: 2802 // FIXME: this state can be merged with (1), but the following assert 2803 // is useful to check the correcteness of the sequence due to semantic 2804 // change of bitcast. 2805 assert( 2806 SrcTy->isIntOrIntVectorTy() && 2807 MidTy->isPtrOrPtrVectorTy() && 2808 DstTy->isPtrOrPtrVectorTy() && 2809 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2810 "Illegal inttoptr, bitcast sequence!"); 2811 // Allowed, use first cast's opcode 2812 return firstOp; 2813 case 16: 2814 // FIXME: this state can be merged with (2), but the following assert 2815 // is useful to check the correcteness of the sequence due to semantic 2816 // change of bitcast. 2817 assert( 2818 SrcTy->isPtrOrPtrVectorTy() && 2819 MidTy->isPtrOrPtrVectorTy() && 2820 DstTy->isIntOrIntVectorTy() && 2821 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() && 2822 "Illegal bitcast, ptrtoint sequence!"); 2823 // Allowed, use second cast's opcode 2824 return secondOp; 2825 case 17: 2826 // (sitofp (zext x)) -> (uitofp x) 2827 return Instruction::UIToFP; 2828 case 99: 2829 // Cast combination can't happen (error in input). This is for all cases 2830 // where the MidTy is not the same for the two cast instructions. 2831 llvm_unreachable("Invalid Cast Combination"); 2832 default: 2833 llvm_unreachable("Error in CastResults table!!!"); 2834 } 2835 } 2836 2837 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2838 const Twine &Name, Instruction *InsertBefore) { 2839 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2840 // Construct and return the appropriate CastInst subclass 2841 switch (op) { 2842 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); 2843 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); 2844 case SExt: return new SExtInst (S, Ty, Name, InsertBefore); 2845 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); 2846 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); 2847 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); 2848 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); 2849 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); 2850 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); 2851 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); 2852 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); 2853 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); 2854 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore); 2855 default: llvm_unreachable("Invalid opcode provided"); 2856 } 2857 } 2858 2859 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2860 const Twine &Name, BasicBlock *InsertAtEnd) { 2861 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2862 // Construct and return the appropriate CastInst subclass 2863 switch (op) { 2864 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); 2865 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); 2866 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); 2867 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); 2868 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); 2869 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); 2870 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); 2871 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); 2872 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); 2873 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); 2874 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); 2875 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); 2876 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd); 2877 default: llvm_unreachable("Invalid opcode provided"); 2878 } 2879 } 2880 2881 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2882 const Twine &Name, 2883 Instruction *InsertBefore) { 2884 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2885 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2886 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); 2887 } 2888 2889 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2890 const Twine &Name, 2891 BasicBlock *InsertAtEnd) { 2892 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2893 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2894 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); 2895 } 2896 2897 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2898 const Twine &Name, 2899 Instruction *InsertBefore) { 2900 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2901 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2902 return Create(Instruction::SExt, S, Ty, Name, InsertBefore); 2903 } 2904 2905 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2906 const Twine &Name, 2907 BasicBlock *InsertAtEnd) { 2908 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2909 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2910 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); 2911 } 2912 2913 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2914 const Twine &Name, 2915 Instruction *InsertBefore) { 2916 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2917 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2918 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); 2919 } 2920 2921 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2922 const Twine &Name, 2923 BasicBlock *InsertAtEnd) { 2924 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2925 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2926 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); 2927 } 2928 2929 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2930 const Twine &Name, 2931 BasicBlock *InsertAtEnd) { 2932 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2933 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2934 "Invalid cast"); 2935 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2936 assert((!Ty->isVectorTy() || 2937 cast<VectorType>(Ty)->getNumElements() == 2938 cast<VectorType>(S->getType())->getNumElements()) && 2939 "Invalid cast"); 2940 2941 if (Ty->isIntOrIntVectorTy()) 2942 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); 2943 2944 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd); 2945 } 2946 2947 /// Create a BitCast or a PtrToInt cast instruction 2948 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2949 const Twine &Name, 2950 Instruction *InsertBefore) { 2951 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2952 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2953 "Invalid cast"); 2954 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2955 assert((!Ty->isVectorTy() || 2956 cast<VectorType>(Ty)->getNumElements() == 2957 cast<VectorType>(S->getType())->getNumElements()) && 2958 "Invalid cast"); 2959 2960 if (Ty->isIntOrIntVectorTy()) 2961 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2962 2963 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore); 2964 } 2965 2966 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 2967 Value *S, Type *Ty, 2968 const Twine &Name, 2969 BasicBlock *InsertAtEnd) { 2970 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2971 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2972 2973 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2974 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd); 2975 2976 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2977 } 2978 2979 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 2980 Value *S, Type *Ty, 2981 const Twine &Name, 2982 Instruction *InsertBefore) { 2983 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2984 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2985 2986 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2987 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore); 2988 2989 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2990 } 2991 2992 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty, 2993 const Twine &Name, 2994 Instruction *InsertBefore) { 2995 if (S->getType()->isPointerTy() && Ty->isIntegerTy()) 2996 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2997 if (S->getType()->isIntegerTy() && Ty->isPointerTy()) 2998 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore); 2999 3000 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 3001 } 3002 3003 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 3004 bool isSigned, const Twine &Name, 3005 Instruction *InsertBefore) { 3006 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 3007 "Invalid integer cast"); 3008 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3009 unsigned DstBits = Ty->getScalarSizeInBits(); 3010 Instruction::CastOps opcode = 3011 (SrcBits == DstBits ? Instruction::BitCast : 3012 (SrcBits > DstBits ? Instruction::Trunc : 3013 (isSigned ? Instruction::SExt : Instruction::ZExt))); 3014 return Create(opcode, C, Ty, Name, InsertBefore); 3015 } 3016 3017 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 3018 bool isSigned, const Twine &Name, 3019 BasicBlock *InsertAtEnd) { 3020 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 3021 "Invalid cast"); 3022 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3023 unsigned DstBits = Ty->getScalarSizeInBits(); 3024 Instruction::CastOps opcode = 3025 (SrcBits == DstBits ? Instruction::BitCast : 3026 (SrcBits > DstBits ? Instruction::Trunc : 3027 (isSigned ? Instruction::SExt : Instruction::ZExt))); 3028 return Create(opcode, C, Ty, Name, InsertAtEnd); 3029 } 3030 3031 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 3032 const Twine &Name, 3033 Instruction *InsertBefore) { 3034 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 3035 "Invalid cast"); 3036 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3037 unsigned DstBits = Ty->getScalarSizeInBits(); 3038 Instruction::CastOps opcode = 3039 (SrcBits == DstBits ? Instruction::BitCast : 3040 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 3041 return Create(opcode, C, Ty, Name, InsertBefore); 3042 } 3043 3044 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 3045 const Twine &Name, 3046 BasicBlock *InsertAtEnd) { 3047 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 3048 "Invalid cast"); 3049 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 3050 unsigned DstBits = Ty->getScalarSizeInBits(); 3051 Instruction::CastOps opcode = 3052 (SrcBits == DstBits ? Instruction::BitCast : 3053 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 3054 return Create(opcode, C, Ty, Name, InsertAtEnd); 3055 } 3056 3057 // Check whether it is valid to call getCastOpcode for these types. 3058 // This routine must be kept in sync with getCastOpcode. 3059 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) { 3060 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 3061 return false; 3062 3063 if (SrcTy == DestTy) 3064 return true; 3065 3066 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 3067 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 3068 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 3069 // An element by element cast. Valid if casting the elements is valid. 3070 SrcTy = SrcVecTy->getElementType(); 3071 DestTy = DestVecTy->getElementType(); 3072 } 3073 3074 // Get the bit sizes, we'll need these 3075 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3076 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3077 3078 // Run through the possibilities ... 3079 if (DestTy->isIntegerTy()) { // Casting to integral 3080 if (SrcTy->isIntegerTy()) // Casting from integral 3081 return true; 3082 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 3083 return true; 3084 if (SrcTy->isVectorTy()) // Casting from vector 3085 return DestBits == SrcBits; 3086 // Casting from something else 3087 return SrcTy->isPointerTy(); 3088 } 3089 if (DestTy->isFloatingPointTy()) { // Casting to floating pt 3090 if (SrcTy->isIntegerTy()) // Casting from integral 3091 return true; 3092 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 3093 return true; 3094 if (SrcTy->isVectorTy()) // Casting from vector 3095 return DestBits == SrcBits; 3096 // Casting from something else 3097 return false; 3098 } 3099 if (DestTy->isVectorTy()) // Casting to vector 3100 return DestBits == SrcBits; 3101 if (DestTy->isPointerTy()) { // Casting to pointer 3102 if (SrcTy->isPointerTy()) // Casting from pointer 3103 return true; 3104 return SrcTy->isIntegerTy(); // Casting from integral 3105 } 3106 if (DestTy->isX86_MMXTy()) { 3107 if (SrcTy->isVectorTy()) 3108 return DestBits == SrcBits; // 64-bit vector to MMX 3109 return false; 3110 } // Casting to something else 3111 return false; 3112 } 3113 3114 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) { 3115 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 3116 return false; 3117 3118 if (SrcTy == DestTy) 3119 return true; 3120 3121 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 3122 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) { 3123 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) { 3124 // An element by element cast. Valid if casting the elements is valid. 3125 SrcTy = SrcVecTy->getElementType(); 3126 DestTy = DestVecTy->getElementType(); 3127 } 3128 } 3129 } 3130 3131 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) { 3132 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) { 3133 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace(); 3134 } 3135 } 3136 3137 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3138 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3139 3140 // Could still have vectors of pointers if the number of elements doesn't 3141 // match 3142 if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0) 3143 return false; 3144 3145 if (SrcBits != DestBits) 3146 return false; 3147 3148 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy()) 3149 return false; 3150 3151 return true; 3152 } 3153 3154 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, 3155 const DataLayout &DL) { 3156 // ptrtoint and inttoptr are not allowed on non-integral pointers 3157 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy)) 3158 if (auto *IntTy = dyn_cast<IntegerType>(DestTy)) 3159 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 3160 !DL.isNonIntegralPointerType(PtrTy)); 3161 if (auto *PtrTy = dyn_cast<PointerType>(DestTy)) 3162 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy)) 3163 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 3164 !DL.isNonIntegralPointerType(PtrTy)); 3165 3166 return isBitCastable(SrcTy, DestTy); 3167 } 3168 3169 // Provide a way to get a "cast" where the cast opcode is inferred from the 3170 // types and size of the operand. This, basically, is a parallel of the 3171 // logic in the castIsValid function below. This axiom should hold: 3172 // castIsValid( getCastOpcode(Val, Ty), Val, Ty) 3173 // should not assert in castIsValid. In other words, this produces a "correct" 3174 // casting opcode for the arguments passed to it. 3175 // This routine must be kept in sync with isCastable. 3176 Instruction::CastOps 3177 CastInst::getCastOpcode( 3178 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) { 3179 Type *SrcTy = Src->getType(); 3180 3181 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && 3182 "Only first class types are castable!"); 3183 3184 if (SrcTy == DestTy) 3185 return BitCast; 3186 3187 // FIXME: Check address space sizes here 3188 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 3189 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 3190 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 3191 // An element by element cast. Find the appropriate opcode based on the 3192 // element types. 3193 SrcTy = SrcVecTy->getElementType(); 3194 DestTy = DestVecTy->getElementType(); 3195 } 3196 3197 // Get the bit sizes, we'll need these 3198 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3199 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3200 3201 // Run through the possibilities ... 3202 if (DestTy->isIntegerTy()) { // Casting to integral 3203 if (SrcTy->isIntegerTy()) { // Casting from integral 3204 if (DestBits < SrcBits) 3205 return Trunc; // int -> smaller int 3206 else if (DestBits > SrcBits) { // its an extension 3207 if (SrcIsSigned) 3208 return SExt; // signed -> SEXT 3209 else 3210 return ZExt; // unsigned -> ZEXT 3211 } else { 3212 return BitCast; // Same size, No-op cast 3213 } 3214 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3215 if (DestIsSigned) 3216 return FPToSI; // FP -> sint 3217 else 3218 return FPToUI; // FP -> uint 3219 } else if (SrcTy->isVectorTy()) { 3220 assert(DestBits == SrcBits && 3221 "Casting vector to integer of different width"); 3222 return BitCast; // Same size, no-op cast 3223 } else { 3224 assert(SrcTy->isPointerTy() && 3225 "Casting from a value that is not first-class type"); 3226 return PtrToInt; // ptr -> int 3227 } 3228 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt 3229 if (SrcTy->isIntegerTy()) { // Casting from integral 3230 if (SrcIsSigned) 3231 return SIToFP; // sint -> FP 3232 else 3233 return UIToFP; // uint -> FP 3234 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3235 if (DestBits < SrcBits) { 3236 return FPTrunc; // FP -> smaller FP 3237 } else if (DestBits > SrcBits) { 3238 return FPExt; // FP -> larger FP 3239 } else { 3240 return BitCast; // same size, no-op cast 3241 } 3242 } else if (SrcTy->isVectorTy()) { 3243 assert(DestBits == SrcBits && 3244 "Casting vector to floating point of different width"); 3245 return BitCast; // same size, no-op cast 3246 } 3247 llvm_unreachable("Casting pointer or non-first class to float"); 3248 } else if (DestTy->isVectorTy()) { 3249 assert(DestBits == SrcBits && 3250 "Illegal cast to vector (wrong type or size)"); 3251 return BitCast; 3252 } else if (DestTy->isPointerTy()) { 3253 if (SrcTy->isPointerTy()) { 3254 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace()) 3255 return AddrSpaceCast; 3256 return BitCast; // ptr -> ptr 3257 } else if (SrcTy->isIntegerTy()) { 3258 return IntToPtr; // int -> ptr 3259 } 3260 llvm_unreachable("Casting pointer to other than pointer or int"); 3261 } else if (DestTy->isX86_MMXTy()) { 3262 if (SrcTy->isVectorTy()) { 3263 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX"); 3264 return BitCast; // 64-bit vector to MMX 3265 } 3266 llvm_unreachable("Illegal cast to X86_MMX"); 3267 } 3268 llvm_unreachable("Casting to type that is not first-class"); 3269 } 3270 3271 //===----------------------------------------------------------------------===// 3272 // CastInst SubClass Constructors 3273 //===----------------------------------------------------------------------===// 3274 3275 /// Check that the construction parameters for a CastInst are correct. This 3276 /// could be broken out into the separate constructors but it is useful to have 3277 /// it in one place and to eliminate the redundant code for getting the sizes 3278 /// of the types involved. 3279 bool 3280 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { 3281 // Check for type sanity on the arguments 3282 Type *SrcTy = S->getType(); 3283 3284 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() || 3285 SrcTy->isAggregateType() || DstTy->isAggregateType()) 3286 return false; 3287 3288 // Get the size of the types in bits, and whether we are dealing 3289 // with vector types, we'll need this later. 3290 bool SrcIsVec = isa<VectorType>(SrcTy); 3291 bool DstIsVec = isa<VectorType>(DstTy); 3292 unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits(); 3293 unsigned DstScalarBitSize = DstTy->getScalarSizeInBits(); 3294 3295 // If these are vector types, get the lengths of the vectors (using zero for 3296 // scalar types means that checking that vector lengths match also checks that 3297 // scalars are not being converted to vectors or vectors to scalars). 3298 ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount() 3299 : ElementCount(0, false); 3300 ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount() 3301 : ElementCount(0, false); 3302 3303 // Switch on the opcode provided 3304 switch (op) { 3305 default: return false; // This is an input error 3306 case Instruction::Trunc: 3307 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3308 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize; 3309 case Instruction::ZExt: 3310 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3311 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3312 case Instruction::SExt: 3313 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3314 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3315 case Instruction::FPTrunc: 3316 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3317 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize; 3318 case Instruction::FPExt: 3319 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3320 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize; 3321 case Instruction::UIToFP: 3322 case Instruction::SIToFP: 3323 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() && 3324 SrcEC == DstEC; 3325 case Instruction::FPToUI: 3326 case Instruction::FPToSI: 3327 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() && 3328 SrcEC == DstEC; 3329 case Instruction::PtrToInt: 3330 if (SrcEC != DstEC) 3331 return false; 3332 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy(); 3333 case Instruction::IntToPtr: 3334 if (SrcEC != DstEC) 3335 return false; 3336 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy(); 3337 case Instruction::BitCast: { 3338 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3339 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3340 3341 // BitCast implies a no-op cast of type only. No bits change. 3342 // However, you can't cast pointers to anything but pointers. 3343 if (!SrcPtrTy != !DstPtrTy) 3344 return false; 3345 3346 // For non-pointer cases, the cast is okay if the source and destination bit 3347 // widths are identical. 3348 if (!SrcPtrTy) 3349 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); 3350 3351 // If both are pointers then the address spaces must match. 3352 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) 3353 return false; 3354 3355 // A vector of pointers must have the same number of elements. 3356 if (SrcIsVec && DstIsVec) 3357 return SrcEC == DstEC; 3358 if (SrcIsVec) 3359 return SrcEC == ElementCount(1, false); 3360 if (DstIsVec) 3361 return DstEC == ElementCount(1, false); 3362 3363 return true; 3364 } 3365 case Instruction::AddrSpaceCast: { 3366 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3367 if (!SrcPtrTy) 3368 return false; 3369 3370 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3371 if (!DstPtrTy) 3372 return false; 3373 3374 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 3375 return false; 3376 3377 return SrcEC == DstEC; 3378 } 3379 } 3380 } 3381 3382 TruncInst::TruncInst( 3383 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3384 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) { 3385 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3386 } 3387 3388 TruncInst::TruncInst( 3389 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3390 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 3391 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3392 } 3393 3394 ZExtInst::ZExtInst( 3395 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3396 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) { 3397 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3398 } 3399 3400 ZExtInst::ZExtInst( 3401 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3402 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 3403 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3404 } 3405 SExtInst::SExtInst( 3406 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3407 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 3408 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3409 } 3410 3411 SExtInst::SExtInst( 3412 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3413 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 3414 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3415 } 3416 3417 FPTruncInst::FPTruncInst( 3418 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3419 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 3420 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3421 } 3422 3423 FPTruncInst::FPTruncInst( 3424 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3425 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 3426 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3427 } 3428 3429 FPExtInst::FPExtInst( 3430 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3431 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 3432 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3433 } 3434 3435 FPExtInst::FPExtInst( 3436 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3437 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 3438 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3439 } 3440 3441 UIToFPInst::UIToFPInst( 3442 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3443 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 3444 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3445 } 3446 3447 UIToFPInst::UIToFPInst( 3448 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3449 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 3450 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3451 } 3452 3453 SIToFPInst::SIToFPInst( 3454 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3455 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 3456 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3457 } 3458 3459 SIToFPInst::SIToFPInst( 3460 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3461 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 3462 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3463 } 3464 3465 FPToUIInst::FPToUIInst( 3466 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3467 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 3468 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3469 } 3470 3471 FPToUIInst::FPToUIInst( 3472 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3473 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 3474 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3475 } 3476 3477 FPToSIInst::FPToSIInst( 3478 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3479 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 3480 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3481 } 3482 3483 FPToSIInst::FPToSIInst( 3484 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3485 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 3486 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3487 } 3488 3489 PtrToIntInst::PtrToIntInst( 3490 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3491 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 3492 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3493 } 3494 3495 PtrToIntInst::PtrToIntInst( 3496 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3497 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 3498 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3499 } 3500 3501 IntToPtrInst::IntToPtrInst( 3502 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3503 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 3504 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3505 } 3506 3507 IntToPtrInst::IntToPtrInst( 3508 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3509 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 3510 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3511 } 3512 3513 BitCastInst::BitCastInst( 3514 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3515 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 3516 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3517 } 3518 3519 BitCastInst::BitCastInst( 3520 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3521 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 3522 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3523 } 3524 3525 AddrSpaceCastInst::AddrSpaceCastInst( 3526 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3527 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) { 3528 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3529 } 3530 3531 AddrSpaceCastInst::AddrSpaceCastInst( 3532 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3533 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) { 3534 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3535 } 3536 3537 //===----------------------------------------------------------------------===// 3538 // CmpInst Classes 3539 //===----------------------------------------------------------------------===// 3540 3541 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3542 Value *RHS, const Twine &Name, Instruction *InsertBefore, 3543 Instruction *FlagsSource) 3544 : Instruction(ty, op, 3545 OperandTraits<CmpInst>::op_begin(this), 3546 OperandTraits<CmpInst>::operands(this), 3547 InsertBefore) { 3548 Op<0>() = LHS; 3549 Op<1>() = RHS; 3550 setPredicate((Predicate)predicate); 3551 setName(Name); 3552 if (FlagsSource) 3553 copyIRFlags(FlagsSource); 3554 } 3555 3556 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3557 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd) 3558 : Instruction(ty, op, 3559 OperandTraits<CmpInst>::op_begin(this), 3560 OperandTraits<CmpInst>::operands(this), 3561 InsertAtEnd) { 3562 Op<0>() = LHS; 3563 Op<1>() = RHS; 3564 setPredicate((Predicate)predicate); 3565 setName(Name); 3566 } 3567 3568 CmpInst * 3569 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3570 const Twine &Name, Instruction *InsertBefore) { 3571 if (Op == Instruction::ICmp) { 3572 if (InsertBefore) 3573 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), 3574 S1, S2, Name); 3575 else 3576 return new ICmpInst(CmpInst::Predicate(predicate), 3577 S1, S2, Name); 3578 } 3579 3580 if (InsertBefore) 3581 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), 3582 S1, S2, Name); 3583 else 3584 return new FCmpInst(CmpInst::Predicate(predicate), 3585 S1, S2, Name); 3586 } 3587 3588 CmpInst * 3589 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3590 const Twine &Name, BasicBlock *InsertAtEnd) { 3591 if (Op == Instruction::ICmp) { 3592 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3593 S1, S2, Name); 3594 } 3595 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3596 S1, S2, Name); 3597 } 3598 3599 void CmpInst::swapOperands() { 3600 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3601 IC->swapOperands(); 3602 else 3603 cast<FCmpInst>(this)->swapOperands(); 3604 } 3605 3606 bool CmpInst::isCommutative() const { 3607 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3608 return IC->isCommutative(); 3609 return cast<FCmpInst>(this)->isCommutative(); 3610 } 3611 3612 bool CmpInst::isEquality() const { 3613 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3614 return IC->isEquality(); 3615 return cast<FCmpInst>(this)->isEquality(); 3616 } 3617 3618 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { 3619 switch (pred) { 3620 default: llvm_unreachable("Unknown cmp predicate!"); 3621 case ICMP_EQ: return ICMP_NE; 3622 case ICMP_NE: return ICMP_EQ; 3623 case ICMP_UGT: return ICMP_ULE; 3624 case ICMP_ULT: return ICMP_UGE; 3625 case ICMP_UGE: return ICMP_ULT; 3626 case ICMP_ULE: return ICMP_UGT; 3627 case ICMP_SGT: return ICMP_SLE; 3628 case ICMP_SLT: return ICMP_SGE; 3629 case ICMP_SGE: return ICMP_SLT; 3630 case ICMP_SLE: return ICMP_SGT; 3631 3632 case FCMP_OEQ: return FCMP_UNE; 3633 case FCMP_ONE: return FCMP_UEQ; 3634 case FCMP_OGT: return FCMP_ULE; 3635 case FCMP_OLT: return FCMP_UGE; 3636 case FCMP_OGE: return FCMP_ULT; 3637 case FCMP_OLE: return FCMP_UGT; 3638 case FCMP_UEQ: return FCMP_ONE; 3639 case FCMP_UNE: return FCMP_OEQ; 3640 case FCMP_UGT: return FCMP_OLE; 3641 case FCMP_ULT: return FCMP_OGE; 3642 case FCMP_UGE: return FCMP_OLT; 3643 case FCMP_ULE: return FCMP_OGT; 3644 case FCMP_ORD: return FCMP_UNO; 3645 case FCMP_UNO: return FCMP_ORD; 3646 case FCMP_TRUE: return FCMP_FALSE; 3647 case FCMP_FALSE: return FCMP_TRUE; 3648 } 3649 } 3650 3651 StringRef CmpInst::getPredicateName(Predicate Pred) { 3652 switch (Pred) { 3653 default: return "unknown"; 3654 case FCmpInst::FCMP_FALSE: return "false"; 3655 case FCmpInst::FCMP_OEQ: return "oeq"; 3656 case FCmpInst::FCMP_OGT: return "ogt"; 3657 case FCmpInst::FCMP_OGE: return "oge"; 3658 case FCmpInst::FCMP_OLT: return "olt"; 3659 case FCmpInst::FCMP_OLE: return "ole"; 3660 case FCmpInst::FCMP_ONE: return "one"; 3661 case FCmpInst::FCMP_ORD: return "ord"; 3662 case FCmpInst::FCMP_UNO: return "uno"; 3663 case FCmpInst::FCMP_UEQ: return "ueq"; 3664 case FCmpInst::FCMP_UGT: return "ugt"; 3665 case FCmpInst::FCMP_UGE: return "uge"; 3666 case FCmpInst::FCMP_ULT: return "ult"; 3667 case FCmpInst::FCMP_ULE: return "ule"; 3668 case FCmpInst::FCMP_UNE: return "une"; 3669 case FCmpInst::FCMP_TRUE: return "true"; 3670 case ICmpInst::ICMP_EQ: return "eq"; 3671 case ICmpInst::ICMP_NE: return "ne"; 3672 case ICmpInst::ICMP_SGT: return "sgt"; 3673 case ICmpInst::ICMP_SGE: return "sge"; 3674 case ICmpInst::ICMP_SLT: return "slt"; 3675 case ICmpInst::ICMP_SLE: return "sle"; 3676 case ICmpInst::ICMP_UGT: return "ugt"; 3677 case ICmpInst::ICMP_UGE: return "uge"; 3678 case ICmpInst::ICMP_ULT: return "ult"; 3679 case ICmpInst::ICMP_ULE: return "ule"; 3680 } 3681 } 3682 3683 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { 3684 switch (pred) { 3685 default: llvm_unreachable("Unknown icmp predicate!"); 3686 case ICMP_EQ: case ICMP_NE: 3687 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 3688 return pred; 3689 case ICMP_UGT: return ICMP_SGT; 3690 case ICMP_ULT: return ICMP_SLT; 3691 case ICMP_UGE: return ICMP_SGE; 3692 case ICMP_ULE: return ICMP_SLE; 3693 } 3694 } 3695 3696 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { 3697 switch (pred) { 3698 default: llvm_unreachable("Unknown icmp predicate!"); 3699 case ICMP_EQ: case ICMP_NE: 3700 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 3701 return pred; 3702 case ICMP_SGT: return ICMP_UGT; 3703 case ICMP_SLT: return ICMP_ULT; 3704 case ICMP_SGE: return ICMP_UGE; 3705 case ICMP_SLE: return ICMP_ULE; 3706 } 3707 } 3708 3709 CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) { 3710 switch (pred) { 3711 default: llvm_unreachable("Unknown or unsupported cmp predicate!"); 3712 case ICMP_SGT: return ICMP_SGE; 3713 case ICMP_SLT: return ICMP_SLE; 3714 case ICMP_SGE: return ICMP_SGT; 3715 case ICMP_SLE: return ICMP_SLT; 3716 case ICMP_UGT: return ICMP_UGE; 3717 case ICMP_ULT: return ICMP_ULE; 3718 case ICMP_UGE: return ICMP_UGT; 3719 case ICMP_ULE: return ICMP_ULT; 3720 3721 case FCMP_OGT: return FCMP_OGE; 3722 case FCMP_OLT: return FCMP_OLE; 3723 case FCMP_OGE: return FCMP_OGT; 3724 case FCMP_OLE: return FCMP_OLT; 3725 case FCMP_UGT: return FCMP_UGE; 3726 case FCMP_ULT: return FCMP_ULE; 3727 case FCMP_UGE: return FCMP_UGT; 3728 case FCMP_ULE: return FCMP_ULT; 3729 } 3730 } 3731 3732 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { 3733 switch (pred) { 3734 default: llvm_unreachable("Unknown cmp predicate!"); 3735 case ICMP_EQ: case ICMP_NE: 3736 return pred; 3737 case ICMP_SGT: return ICMP_SLT; 3738 case ICMP_SLT: return ICMP_SGT; 3739 case ICMP_SGE: return ICMP_SLE; 3740 case ICMP_SLE: return ICMP_SGE; 3741 case ICMP_UGT: return ICMP_ULT; 3742 case ICMP_ULT: return ICMP_UGT; 3743 case ICMP_UGE: return ICMP_ULE; 3744 case ICMP_ULE: return ICMP_UGE; 3745 3746 case FCMP_FALSE: case FCMP_TRUE: 3747 case FCMP_OEQ: case FCMP_ONE: 3748 case FCMP_UEQ: case FCMP_UNE: 3749 case FCMP_ORD: case FCMP_UNO: 3750 return pred; 3751 case FCMP_OGT: return FCMP_OLT; 3752 case FCMP_OLT: return FCMP_OGT; 3753 case FCMP_OGE: return FCMP_OLE; 3754 case FCMP_OLE: return FCMP_OGE; 3755 case FCMP_UGT: return FCMP_ULT; 3756 case FCMP_ULT: return FCMP_UGT; 3757 case FCMP_UGE: return FCMP_ULE; 3758 case FCMP_ULE: return FCMP_UGE; 3759 } 3760 } 3761 3762 CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) { 3763 switch (pred) { 3764 case ICMP_SGT: return ICMP_SGE; 3765 case ICMP_SLT: return ICMP_SLE; 3766 case ICMP_UGT: return ICMP_UGE; 3767 case ICMP_ULT: return ICMP_ULE; 3768 case FCMP_OGT: return FCMP_OGE; 3769 case FCMP_OLT: return FCMP_OLE; 3770 case FCMP_UGT: return FCMP_UGE; 3771 case FCMP_ULT: return FCMP_ULE; 3772 default: return pred; 3773 } 3774 } 3775 3776 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) { 3777 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!"); 3778 3779 switch (pred) { 3780 default: 3781 llvm_unreachable("Unknown predicate!"); 3782 case CmpInst::ICMP_ULT: 3783 return CmpInst::ICMP_SLT; 3784 case CmpInst::ICMP_ULE: 3785 return CmpInst::ICMP_SLE; 3786 case CmpInst::ICMP_UGT: 3787 return CmpInst::ICMP_SGT; 3788 case CmpInst::ICMP_UGE: 3789 return CmpInst::ICMP_SGE; 3790 } 3791 } 3792 3793 bool CmpInst::isUnsigned(Predicate predicate) { 3794 switch (predicate) { 3795 default: return false; 3796 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 3797 case ICmpInst::ICMP_UGE: return true; 3798 } 3799 } 3800 3801 bool CmpInst::isSigned(Predicate predicate) { 3802 switch (predicate) { 3803 default: return false; 3804 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 3805 case ICmpInst::ICMP_SGE: return true; 3806 } 3807 } 3808 3809 bool CmpInst::isOrdered(Predicate predicate) { 3810 switch (predicate) { 3811 default: return false; 3812 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 3813 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 3814 case FCmpInst::FCMP_ORD: return true; 3815 } 3816 } 3817 3818 bool CmpInst::isUnordered(Predicate predicate) { 3819 switch (predicate) { 3820 default: return false; 3821 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 3822 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 3823 case FCmpInst::FCMP_UNO: return true; 3824 } 3825 } 3826 3827 bool CmpInst::isTrueWhenEqual(Predicate predicate) { 3828 switch(predicate) { 3829 default: return false; 3830 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE: 3831 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true; 3832 } 3833 } 3834 3835 bool CmpInst::isFalseWhenEqual(Predicate predicate) { 3836 switch(predicate) { 3837 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT: 3838 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true; 3839 default: return false; 3840 } 3841 } 3842 3843 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3844 // If the predicates match, then we know the first condition implies the 3845 // second is true. 3846 if (Pred1 == Pred2) 3847 return true; 3848 3849 switch (Pred1) { 3850 default: 3851 break; 3852 case ICMP_EQ: 3853 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true. 3854 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE || 3855 Pred2 == ICMP_SLE; 3856 case ICMP_UGT: // A >u B implies A != B and A >=u B are true. 3857 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE; 3858 case ICMP_ULT: // A <u B implies A != B and A <=u B are true. 3859 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE; 3860 case ICMP_SGT: // A >s B implies A != B and A >=s B are true. 3861 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE; 3862 case ICMP_SLT: // A <s B implies A != B and A <=s B are true. 3863 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE; 3864 } 3865 return false; 3866 } 3867 3868 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3869 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2)); 3870 } 3871 3872 //===----------------------------------------------------------------------===// 3873 // SwitchInst Implementation 3874 //===----------------------------------------------------------------------===// 3875 3876 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) { 3877 assert(Value && Default && NumReserved); 3878 ReservedSpace = NumReserved; 3879 setNumHungOffUseOperands(2); 3880 allocHungoffUses(ReservedSpace); 3881 3882 Op<0>() = Value; 3883 Op<1>() = Default; 3884 } 3885 3886 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3887 /// switch on and a default destination. The number of additional cases can 3888 /// be specified here to make memory allocation more efficient. This 3889 /// constructor can also autoinsert before another instruction. 3890 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3891 Instruction *InsertBefore) 3892 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3893 nullptr, 0, InsertBefore) { 3894 init(Value, Default, 2+NumCases*2); 3895 } 3896 3897 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3898 /// switch on and a default destination. The number of additional cases can 3899 /// be specified here to make memory allocation more efficient. This 3900 /// constructor also autoinserts at the end of the specified BasicBlock. 3901 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3902 BasicBlock *InsertAtEnd) 3903 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3904 nullptr, 0, InsertAtEnd) { 3905 init(Value, Default, 2+NumCases*2); 3906 } 3907 3908 SwitchInst::SwitchInst(const SwitchInst &SI) 3909 : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) { 3910 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands()); 3911 setNumHungOffUseOperands(SI.getNumOperands()); 3912 Use *OL = getOperandList(); 3913 const Use *InOL = SI.getOperandList(); 3914 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) { 3915 OL[i] = InOL[i]; 3916 OL[i+1] = InOL[i+1]; 3917 } 3918 SubclassOptionalData = SI.SubclassOptionalData; 3919 } 3920 3921 /// addCase - Add an entry to the switch instruction... 3922 /// 3923 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { 3924 unsigned NewCaseIdx = getNumCases(); 3925 unsigned OpNo = getNumOperands(); 3926 if (OpNo+2 > ReservedSpace) 3927 growOperands(); // Get more space! 3928 // Initialize some new operands. 3929 assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); 3930 setNumHungOffUseOperands(OpNo+2); 3931 CaseHandle Case(this, NewCaseIdx); 3932 Case.setValue(OnVal); 3933 Case.setSuccessor(Dest); 3934 } 3935 3936 /// removeCase - This method removes the specified case and its successor 3937 /// from the switch instruction. 3938 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) { 3939 unsigned idx = I->getCaseIndex(); 3940 3941 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!"); 3942 3943 unsigned NumOps = getNumOperands(); 3944 Use *OL = getOperandList(); 3945 3946 // Overwrite this case with the end of the list. 3947 if (2 + (idx + 1) * 2 != NumOps) { 3948 OL[2 + idx * 2] = OL[NumOps - 2]; 3949 OL[2 + idx * 2 + 1] = OL[NumOps - 1]; 3950 } 3951 3952 // Nuke the last value. 3953 OL[NumOps-2].set(nullptr); 3954 OL[NumOps-2+1].set(nullptr); 3955 setNumHungOffUseOperands(NumOps-2); 3956 3957 return CaseIt(this, idx); 3958 } 3959 3960 /// growOperands - grow operands - This grows the operand list in response 3961 /// to a push_back style of operation. This grows the number of ops by 3 times. 3962 /// 3963 void SwitchInst::growOperands() { 3964 unsigned e = getNumOperands(); 3965 unsigned NumOps = e*3; 3966 3967 ReservedSpace = NumOps; 3968 growHungoffUses(ReservedSpace); 3969 } 3970 3971 MDNode * 3972 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) { 3973 if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof)) 3974 if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0))) 3975 if (MDName->getString() == "branch_weights") 3976 return ProfileData; 3977 return nullptr; 3978 } 3979 3980 MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() { 3981 assert(Changed && "called only if metadata has changed"); 3982 3983 if (!Weights) 3984 return nullptr; 3985 3986 assert(SI.getNumSuccessors() == Weights->size() && 3987 "num of prof branch_weights must accord with num of successors"); 3988 3989 bool AllZeroes = 3990 all_of(Weights.getValue(), [](uint32_t W) { return W == 0; }); 3991 3992 if (AllZeroes || Weights.getValue().size() < 2) 3993 return nullptr; 3994 3995 return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights); 3996 } 3997 3998 void SwitchInstProfUpdateWrapper::init() { 3999 MDNode *ProfileData = getProfBranchWeightsMD(SI); 4000 if (!ProfileData) 4001 return; 4002 4003 if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) { 4004 llvm_unreachable("number of prof branch_weights metadata operands does " 4005 "not correspond to number of succesors"); 4006 } 4007 4008 SmallVector<uint32_t, 8> Weights; 4009 for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) { 4010 ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI)); 4011 uint32_t CW = C->getValue().getZExtValue(); 4012 Weights.push_back(CW); 4013 } 4014 this->Weights = std::move(Weights); 4015 } 4016 4017 SwitchInst::CaseIt 4018 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) { 4019 if (Weights) { 4020 assert(SI.getNumSuccessors() == Weights->size() && 4021 "num of prof branch_weights must accord with num of successors"); 4022 Changed = true; 4023 // Copy the last case to the place of the removed one and shrink. 4024 // This is tightly coupled with the way SwitchInst::removeCase() removes 4025 // the cases in SwitchInst::removeCase(CaseIt). 4026 Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back(); 4027 Weights.getValue().pop_back(); 4028 } 4029 return SI.removeCase(I); 4030 } 4031 4032 void SwitchInstProfUpdateWrapper::addCase( 4033 ConstantInt *OnVal, BasicBlock *Dest, 4034 SwitchInstProfUpdateWrapper::CaseWeightOpt W) { 4035 SI.addCase(OnVal, Dest); 4036 4037 if (!Weights && W && *W) { 4038 Changed = true; 4039 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0); 4040 Weights.getValue()[SI.getNumSuccessors() - 1] = *W; 4041 } else if (Weights) { 4042 Changed = true; 4043 Weights.getValue().push_back(W ? *W : 0); 4044 } 4045 if (Weights) 4046 assert(SI.getNumSuccessors() == Weights->size() && 4047 "num of prof branch_weights must accord with num of successors"); 4048 } 4049 4050 SymbolTableList<Instruction>::iterator 4051 SwitchInstProfUpdateWrapper::eraseFromParent() { 4052 // Instruction is erased. Mark as unchanged to not touch it in the destructor. 4053 Changed = false; 4054 if (Weights) 4055 Weights->resize(0); 4056 return SI.eraseFromParent(); 4057 } 4058 4059 SwitchInstProfUpdateWrapper::CaseWeightOpt 4060 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) { 4061 if (!Weights) 4062 return None; 4063 return Weights.getValue()[idx]; 4064 } 4065 4066 void SwitchInstProfUpdateWrapper::setSuccessorWeight( 4067 unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) { 4068 if (!W) 4069 return; 4070 4071 if (!Weights && *W) 4072 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0); 4073 4074 if (Weights) { 4075 auto &OldW = Weights.getValue()[idx]; 4076 if (*W != OldW) { 4077 Changed = true; 4078 OldW = *W; 4079 } 4080 } 4081 } 4082 4083 SwitchInstProfUpdateWrapper::CaseWeightOpt 4084 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI, 4085 unsigned idx) { 4086 if (MDNode *ProfileData = getProfBranchWeightsMD(SI)) 4087 if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1) 4088 return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1)) 4089 ->getValue() 4090 .getZExtValue(); 4091 4092 return None; 4093 } 4094 4095 //===----------------------------------------------------------------------===// 4096 // IndirectBrInst Implementation 4097 //===----------------------------------------------------------------------===// 4098 4099 void IndirectBrInst::init(Value *Address, unsigned NumDests) { 4100 assert(Address && Address->getType()->isPointerTy() && 4101 "Address of indirectbr must be a pointer"); 4102 ReservedSpace = 1+NumDests; 4103 setNumHungOffUseOperands(1); 4104 allocHungoffUses(ReservedSpace); 4105 4106 Op<0>() = Address; 4107 } 4108 4109 4110 /// growOperands - grow operands - This grows the operand list in response 4111 /// to a push_back style of operation. This grows the number of ops by 2 times. 4112 /// 4113 void IndirectBrInst::growOperands() { 4114 unsigned e = getNumOperands(); 4115 unsigned NumOps = e*2; 4116 4117 ReservedSpace = NumOps; 4118 growHungoffUses(ReservedSpace); 4119 } 4120 4121 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 4122 Instruction *InsertBefore) 4123 : Instruction(Type::getVoidTy(Address->getContext()), 4124 Instruction::IndirectBr, nullptr, 0, InsertBefore) { 4125 init(Address, NumCases); 4126 } 4127 4128 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 4129 BasicBlock *InsertAtEnd) 4130 : Instruction(Type::getVoidTy(Address->getContext()), 4131 Instruction::IndirectBr, nullptr, 0, InsertAtEnd) { 4132 init(Address, NumCases); 4133 } 4134 4135 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI) 4136 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr, 4137 nullptr, IBI.getNumOperands()) { 4138 allocHungoffUses(IBI.getNumOperands()); 4139 Use *OL = getOperandList(); 4140 const Use *InOL = IBI.getOperandList(); 4141 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i) 4142 OL[i] = InOL[i]; 4143 SubclassOptionalData = IBI.SubclassOptionalData; 4144 } 4145 4146 /// addDestination - Add a destination. 4147 /// 4148 void IndirectBrInst::addDestination(BasicBlock *DestBB) { 4149 unsigned OpNo = getNumOperands(); 4150 if (OpNo+1 > ReservedSpace) 4151 growOperands(); // Get more space! 4152 // Initialize some new operands. 4153 assert(OpNo < ReservedSpace && "Growing didn't work!"); 4154 setNumHungOffUseOperands(OpNo+1); 4155 getOperandList()[OpNo] = DestBB; 4156 } 4157 4158 /// removeDestination - This method removes the specified successor from the 4159 /// indirectbr instruction. 4160 void IndirectBrInst::removeDestination(unsigned idx) { 4161 assert(idx < getNumOperands()-1 && "Successor index out of range!"); 4162 4163 unsigned NumOps = getNumOperands(); 4164 Use *OL = getOperandList(); 4165 4166 // Replace this value with the last one. 4167 OL[idx+1] = OL[NumOps-1]; 4168 4169 // Nuke the last value. 4170 OL[NumOps-1].set(nullptr); 4171 setNumHungOffUseOperands(NumOps-1); 4172 } 4173 4174 //===----------------------------------------------------------------------===// 4175 // FreezeInst Implementation 4176 //===----------------------------------------------------------------------===// 4177 4178 FreezeInst::FreezeInst(Value *S, 4179 const Twine &Name, Instruction *InsertBefore) 4180 : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) { 4181 setName(Name); 4182 } 4183 4184 FreezeInst::FreezeInst(Value *S, 4185 const Twine &Name, BasicBlock *InsertAtEnd) 4186 : UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) { 4187 setName(Name); 4188 } 4189 4190 //===----------------------------------------------------------------------===// 4191 // cloneImpl() implementations 4192 //===----------------------------------------------------------------------===// 4193 4194 // Define these methods here so vtables don't get emitted into every translation 4195 // unit that uses these classes. 4196 4197 GetElementPtrInst *GetElementPtrInst::cloneImpl() const { 4198 return new (getNumOperands()) GetElementPtrInst(*this); 4199 } 4200 4201 UnaryOperator *UnaryOperator::cloneImpl() const { 4202 return Create(getOpcode(), Op<0>()); 4203 } 4204 4205 BinaryOperator *BinaryOperator::cloneImpl() const { 4206 return Create(getOpcode(), Op<0>(), Op<1>()); 4207 } 4208 4209 FCmpInst *FCmpInst::cloneImpl() const { 4210 return new FCmpInst(getPredicate(), Op<0>(), Op<1>()); 4211 } 4212 4213 ICmpInst *ICmpInst::cloneImpl() const { 4214 return new ICmpInst(getPredicate(), Op<0>(), Op<1>()); 4215 } 4216 4217 ExtractValueInst *ExtractValueInst::cloneImpl() const { 4218 return new ExtractValueInst(*this); 4219 } 4220 4221 InsertValueInst *InsertValueInst::cloneImpl() const { 4222 return new InsertValueInst(*this); 4223 } 4224 4225 AllocaInst *AllocaInst::cloneImpl() const { 4226 AllocaInst *Result = 4227 new AllocaInst(getAllocatedType(), getType()->getAddressSpace(), 4228 (Value *)getOperand(0), MaybeAlign(getAlignment())); 4229 Result->setUsedWithInAlloca(isUsedWithInAlloca()); 4230 Result->setSwiftError(isSwiftError()); 4231 return Result; 4232 } 4233 4234 LoadInst *LoadInst::cloneImpl() const { 4235 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(), 4236 MaybeAlign(getAlignment()), getOrdering(), 4237 getSyncScopeID()); 4238 } 4239 4240 StoreInst *StoreInst::cloneImpl() const { 4241 return new StoreInst(getOperand(0), getOperand(1), isVolatile(), 4242 MaybeAlign(getAlignment()), getOrdering(), 4243 getSyncScopeID()); 4244 } 4245 4246 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const { 4247 AtomicCmpXchgInst *Result = 4248 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2), 4249 getSuccessOrdering(), getFailureOrdering(), 4250 getSyncScopeID()); 4251 Result->setVolatile(isVolatile()); 4252 Result->setWeak(isWeak()); 4253 return Result; 4254 } 4255 4256 AtomicRMWInst *AtomicRMWInst::cloneImpl() const { 4257 AtomicRMWInst *Result = 4258 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1), 4259 getOrdering(), getSyncScopeID()); 4260 Result->setVolatile(isVolatile()); 4261 return Result; 4262 } 4263 4264 FenceInst *FenceInst::cloneImpl() const { 4265 return new FenceInst(getContext(), getOrdering(), getSyncScopeID()); 4266 } 4267 4268 TruncInst *TruncInst::cloneImpl() const { 4269 return new TruncInst(getOperand(0), getType()); 4270 } 4271 4272 ZExtInst *ZExtInst::cloneImpl() const { 4273 return new ZExtInst(getOperand(0), getType()); 4274 } 4275 4276 SExtInst *SExtInst::cloneImpl() const { 4277 return new SExtInst(getOperand(0), getType()); 4278 } 4279 4280 FPTruncInst *FPTruncInst::cloneImpl() const { 4281 return new FPTruncInst(getOperand(0), getType()); 4282 } 4283 4284 FPExtInst *FPExtInst::cloneImpl() const { 4285 return new FPExtInst(getOperand(0), getType()); 4286 } 4287 4288 UIToFPInst *UIToFPInst::cloneImpl() const { 4289 return new UIToFPInst(getOperand(0), getType()); 4290 } 4291 4292 SIToFPInst *SIToFPInst::cloneImpl() const { 4293 return new SIToFPInst(getOperand(0), getType()); 4294 } 4295 4296 FPToUIInst *FPToUIInst::cloneImpl() const { 4297 return new FPToUIInst(getOperand(0), getType()); 4298 } 4299 4300 FPToSIInst *FPToSIInst::cloneImpl() const { 4301 return new FPToSIInst(getOperand(0), getType()); 4302 } 4303 4304 PtrToIntInst *PtrToIntInst::cloneImpl() const { 4305 return new PtrToIntInst(getOperand(0), getType()); 4306 } 4307 4308 IntToPtrInst *IntToPtrInst::cloneImpl() const { 4309 return new IntToPtrInst(getOperand(0), getType()); 4310 } 4311 4312 BitCastInst *BitCastInst::cloneImpl() const { 4313 return new BitCastInst(getOperand(0), getType()); 4314 } 4315 4316 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const { 4317 return new AddrSpaceCastInst(getOperand(0), getType()); 4318 } 4319 4320 CallInst *CallInst::cloneImpl() const { 4321 if (hasOperandBundles()) { 4322 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4323 return new(getNumOperands(), DescriptorBytes) CallInst(*this); 4324 } 4325 return new(getNumOperands()) CallInst(*this); 4326 } 4327 4328 SelectInst *SelectInst::cloneImpl() const { 4329 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4330 } 4331 4332 VAArgInst *VAArgInst::cloneImpl() const { 4333 return new VAArgInst(getOperand(0), getType()); 4334 } 4335 4336 ExtractElementInst *ExtractElementInst::cloneImpl() const { 4337 return ExtractElementInst::Create(getOperand(0), getOperand(1)); 4338 } 4339 4340 InsertElementInst *InsertElementInst::cloneImpl() const { 4341 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4342 } 4343 4344 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const { 4345 return new ShuffleVectorInst(getOperand(0), getOperand(1), getShuffleMask()); 4346 } 4347 4348 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); } 4349 4350 LandingPadInst *LandingPadInst::cloneImpl() const { 4351 return new LandingPadInst(*this); 4352 } 4353 4354 ReturnInst *ReturnInst::cloneImpl() const { 4355 return new(getNumOperands()) ReturnInst(*this); 4356 } 4357 4358 BranchInst *BranchInst::cloneImpl() const { 4359 return new(getNumOperands()) BranchInst(*this); 4360 } 4361 4362 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); } 4363 4364 IndirectBrInst *IndirectBrInst::cloneImpl() const { 4365 return new IndirectBrInst(*this); 4366 } 4367 4368 InvokeInst *InvokeInst::cloneImpl() const { 4369 if (hasOperandBundles()) { 4370 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4371 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this); 4372 } 4373 return new(getNumOperands()) InvokeInst(*this); 4374 } 4375 4376 CallBrInst *CallBrInst::cloneImpl() const { 4377 if (hasOperandBundles()) { 4378 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4379 return new (getNumOperands(), DescriptorBytes) CallBrInst(*this); 4380 } 4381 return new (getNumOperands()) CallBrInst(*this); 4382 } 4383 4384 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); } 4385 4386 CleanupReturnInst *CleanupReturnInst::cloneImpl() const { 4387 return new (getNumOperands()) CleanupReturnInst(*this); 4388 } 4389 4390 CatchReturnInst *CatchReturnInst::cloneImpl() const { 4391 return new (getNumOperands()) CatchReturnInst(*this); 4392 } 4393 4394 CatchSwitchInst *CatchSwitchInst::cloneImpl() const { 4395 return new CatchSwitchInst(*this); 4396 } 4397 4398 FuncletPadInst *FuncletPadInst::cloneImpl() const { 4399 return new (getNumOperands()) FuncletPadInst(*this); 4400 } 4401 4402 UnreachableInst *UnreachableInst::cloneImpl() const { 4403 LLVMContext &Context = getContext(); 4404 return new UnreachableInst(Context); 4405 } 4406 4407 FreezeInst *FreezeInst::cloneImpl() const { 4408 return new FreezeInst(getOperand(0)); 4409 } 4410