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