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