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