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