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