| //===- Instructions.cpp - Implement the LLVM instructions -----------------===// |
| // |
| // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| // See https://llvm.org/LICENSE.txt for license information. |
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| // |
| //===----------------------------------------------------------------------===// |
| // |
| // This file implements all of the non-inline methods for the LLVM instruction |
| // classes. |
| // |
| //===----------------------------------------------------------------------===// |
| |
| #include "llvm/IR/Instructions.h" |
| #include "LLVMContextImpl.h" |
| #include "llvm/ADT/None.h" |
| #include "llvm/ADT/SmallVector.h" |
| #include "llvm/ADT/Twine.h" |
| #include "llvm/IR/Attributes.h" |
| #include "llvm/IR/BasicBlock.h" |
| #include "llvm/IR/Constant.h" |
| #include "llvm/IR/Constants.h" |
| #include "llvm/IR/DataLayout.h" |
| #include "llvm/IR/DerivedTypes.h" |
| #include "llvm/IR/Function.h" |
| #include "llvm/IR/InstrTypes.h" |
| #include "llvm/IR/Instruction.h" |
| #include "llvm/IR/Intrinsics.h" |
| #include "llvm/IR/LLVMContext.h" |
| #include "llvm/IR/MDBuilder.h" |
| #include "llvm/IR/Metadata.h" |
| #include "llvm/IR/Module.h" |
| #include "llvm/IR/Operator.h" |
| #include "llvm/IR/Type.h" |
| #include "llvm/IR/Value.h" |
| #include "llvm/Support/AtomicOrdering.h" |
| #include "llvm/Support/Casting.h" |
| #include "llvm/Support/ErrorHandling.h" |
| #include "llvm/Support/MathExtras.h" |
| #include "llvm/Support/TypeSize.h" |
| #include <algorithm> |
| #include <cassert> |
| #include <cstdint> |
| #include <vector> |
| |
| using namespace llvm; |
| |
| static cl::opt<bool> DisableI2pP2iOpt( |
| "disable-i2p-p2i-opt", cl::init(false), |
| cl::desc("Disables inttoptr/ptrtoint roundtrip optimization")); |
| |
| //===----------------------------------------------------------------------===// |
| // AllocaInst Class |
| //===----------------------------------------------------------------------===// |
| |
| Optional<TypeSize> |
| AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const { |
| TypeSize Size = DL.getTypeAllocSizeInBits(getAllocatedType()); |
| if (isArrayAllocation()) { |
| auto *C = dyn_cast<ConstantInt>(getArraySize()); |
| if (!C) |
| return None; |
| assert(!Size.isScalable() && "Array elements cannot have a scalable size"); |
| Size *= C->getZExtValue(); |
| } |
| return Size; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // SelectInst Class |
| //===----------------------------------------------------------------------===// |
| |
| /// areInvalidOperands - Return a string if the specified operands are invalid |
| /// for a select operation, otherwise return null. |
| const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { |
| if (Op1->getType() != Op2->getType()) |
| return "both values to select must have same type"; |
| |
| if (Op1->getType()->isTokenTy()) |
| return "select values cannot have token type"; |
| |
| if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { |
| // Vector select. |
| if (VT->getElementType() != Type::getInt1Ty(Op0->getContext())) |
| return "vector select condition element type must be i1"; |
| VectorType *ET = dyn_cast<VectorType>(Op1->getType()); |
| if (!ET) |
| return "selected values for vector select must be vectors"; |
| if (ET->getElementCount() != VT->getElementCount()) |
| return "vector select requires selected vectors to have " |
| "the same vector length as select condition"; |
| } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) { |
| return "select condition must be i1 or <n x i1>"; |
| } |
| return nullptr; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // PHINode Class |
| //===----------------------------------------------------------------------===// |
| |
| PHINode::PHINode(const PHINode &PN) |
| : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()), |
| ReservedSpace(PN.getNumOperands()) { |
| allocHungoffUses(PN.getNumOperands()); |
| std::copy(PN.op_begin(), PN.op_end(), op_begin()); |
| std::copy(PN.block_begin(), PN.block_end(), block_begin()); |
| SubclassOptionalData = PN.SubclassOptionalData; |
| } |
| |
| // removeIncomingValue - Remove an incoming value. This is useful if a |
| // predecessor basic block is deleted. |
| Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { |
| Value *Removed = getIncomingValue(Idx); |
| |
| // Move everything after this operand down. |
| // |
| // FIXME: we could just swap with the end of the list, then erase. However, |
| // clients might not expect this to happen. The code as it is thrashes the |
| // use/def lists, which is kinda lame. |
| std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx); |
| std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx); |
| |
| // Nuke the last value. |
| Op<-1>().set(nullptr); |
| setNumHungOffUseOperands(getNumOperands() - 1); |
| |
| // If the PHI node is dead, because it has zero entries, nuke it now. |
| if (getNumOperands() == 0 && DeletePHIIfEmpty) { |
| // If anyone is using this PHI, make them use a dummy value instead... |
| replaceAllUsesWith(UndefValue::get(getType())); |
| eraseFromParent(); |
| } |
| return Removed; |
| } |
| |
| /// growOperands - grow operands - This grows the operand list in response |
| /// to a push_back style of operation. This grows the number of ops by 1.5 |
| /// times. |
| /// |
| void PHINode::growOperands() { |
| unsigned e = getNumOperands(); |
| unsigned NumOps = e + e / 2; |
| if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common. |
| |
| ReservedSpace = NumOps; |
| growHungoffUses(ReservedSpace, /* IsPhi */ true); |
| } |
| |
| /// hasConstantValue - If the specified PHI node always merges together the same |
| /// value, return the value, otherwise return null. |
| Value *PHINode::hasConstantValue() const { |
| // Exploit the fact that phi nodes always have at least one entry. |
| Value *ConstantValue = getIncomingValue(0); |
| for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i) |
| if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) { |
| if (ConstantValue != this) |
| return nullptr; // Incoming values not all the same. |
| // The case where the first value is this PHI. |
| ConstantValue = getIncomingValue(i); |
| } |
| if (ConstantValue == this) |
| return UndefValue::get(getType()); |
| return ConstantValue; |
| } |
| |
| /// hasConstantOrUndefValue - Whether the specified PHI node always merges |
| /// together the same value, assuming that undefs result in the same value as |
| /// non-undefs. |
| /// Unlike \ref hasConstantValue, this does not return a value because the |
| /// unique non-undef incoming value need not dominate the PHI node. |
| bool PHINode::hasConstantOrUndefValue() const { |
| Value *ConstantValue = nullptr; |
| for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) { |
| Value *Incoming = getIncomingValue(i); |
| if (Incoming != this && !isa<UndefValue>(Incoming)) { |
| if (ConstantValue && ConstantValue != Incoming) |
| return false; |
| ConstantValue = Incoming; |
| } |
| } |
| return true; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // LandingPadInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
| const Twine &NameStr, Instruction *InsertBefore) |
| : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) { |
| init(NumReservedValues, NameStr); |
| } |
| |
| LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
| const Twine &NameStr, BasicBlock *InsertAtEnd) |
| : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) { |
| init(NumReservedValues, NameStr); |
| } |
| |
| LandingPadInst::LandingPadInst(const LandingPadInst &LP) |
| : Instruction(LP.getType(), Instruction::LandingPad, nullptr, |
| LP.getNumOperands()), |
| ReservedSpace(LP.getNumOperands()) { |
| allocHungoffUses(LP.getNumOperands()); |
| Use *OL = getOperandList(); |
| const Use *InOL = LP.getOperandList(); |
| for (unsigned I = 0, E = ReservedSpace; I != E; ++I) |
| OL[I] = InOL[I]; |
| |
| setCleanup(LP.isCleanup()); |
| } |
| |
| LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, |
| const Twine &NameStr, |
| Instruction *InsertBefore) { |
| return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore); |
| } |
| |
| LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, |
| const Twine &NameStr, |
| BasicBlock *InsertAtEnd) { |
| return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd); |
| } |
| |
| void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) { |
| ReservedSpace = NumReservedValues; |
| setNumHungOffUseOperands(0); |
| allocHungoffUses(ReservedSpace); |
| setName(NameStr); |
| setCleanup(false); |
| } |
| |
| /// growOperands - grow operands - This grows the operand list in response to a |
| /// push_back style of operation. This grows the number of ops by 2 times. |
| void LandingPadInst::growOperands(unsigned Size) { |
| unsigned e = getNumOperands(); |
| if (ReservedSpace >= e + Size) return; |
| ReservedSpace = (std::max(e, 1U) + Size / 2) * 2; |
| growHungoffUses(ReservedSpace); |
| } |
| |
| void LandingPadInst::addClause(Constant *Val) { |
| unsigned OpNo = getNumOperands(); |
| growOperands(1); |
| assert(OpNo < ReservedSpace && "Growing didn't work!"); |
| setNumHungOffUseOperands(getNumOperands() + 1); |
| getOperandList()[OpNo] = Val; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // CallBase Implementation |
| //===----------------------------------------------------------------------===// |
| |
| CallBase *CallBase::Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles, |
| Instruction *InsertPt) { |
| switch (CB->getOpcode()) { |
| case Instruction::Call: |
| return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt); |
| case Instruction::Invoke: |
| return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt); |
| case Instruction::CallBr: |
| return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt); |
| default: |
| llvm_unreachable("Unknown CallBase sub-class!"); |
| } |
| } |
| |
| CallBase *CallBase::Create(CallBase *CI, OperandBundleDef OpB, |
| Instruction *InsertPt) { |
| SmallVector<OperandBundleDef, 2> OpDefs; |
| for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) { |
| auto ChildOB = CI->getOperandBundleAt(i); |
| if (ChildOB.getTagName() != OpB.getTag()) |
| OpDefs.emplace_back(ChildOB); |
| } |
| OpDefs.emplace_back(OpB); |
| return CallBase::Create(CI, OpDefs, InsertPt); |
| } |
| |
| |
| Function *CallBase::getCaller() { return getParent()->getParent(); } |
| |
| unsigned CallBase::getNumSubclassExtraOperandsDynamic() const { |
| assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!"); |
| return cast<CallBrInst>(this)->getNumIndirectDests() + 1; |
| } |
| |
| bool CallBase::isIndirectCall() const { |
| const Value *V = getCalledOperand(); |
| if (isa<Function>(V) || isa<Constant>(V)) |
| return false; |
| return !isInlineAsm(); |
| } |
| |
| /// Tests if this call site must be tail call optimized. Only a CallInst can |
| /// be tail call optimized. |
| bool CallBase::isMustTailCall() const { |
| if (auto *CI = dyn_cast<CallInst>(this)) |
| return CI->isMustTailCall(); |
| return false; |
| } |
| |
| /// Tests if this call site is marked as a tail call. |
| bool CallBase::isTailCall() const { |
| if (auto *CI = dyn_cast<CallInst>(this)) |
| return CI->isTailCall(); |
| return false; |
| } |
| |
| Intrinsic::ID CallBase::getIntrinsicID() const { |
| if (auto *F = getCalledFunction()) |
| return F->getIntrinsicID(); |
| return Intrinsic::not_intrinsic; |
| } |
| |
| bool CallBase::isReturnNonNull() const { |
| if (hasRetAttr(Attribute::NonNull)) |
| return true; |
| |
| if (getRetDereferenceableBytes() > 0 && |
| !NullPointerIsDefined(getCaller(), getType()->getPointerAddressSpace())) |
| return true; |
| |
| return false; |
| } |
| |
| Value *CallBase::getReturnedArgOperand() const { |
| unsigned Index; |
| |
| if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index)) |
| return getArgOperand(Index - AttributeList::FirstArgIndex); |
| if (const Function *F = getCalledFunction()) |
| if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index)) |
| return getArgOperand(Index - AttributeList::FirstArgIndex); |
| |
| return nullptr; |
| } |
| |
| /// Determine whether the argument or parameter has the given attribute. |
| bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const { |
| assert(ArgNo < arg_size() && "Param index out of bounds!"); |
| |
| if (Attrs.hasParamAttr(ArgNo, Kind)) |
| return true; |
| if (const Function *F = getCalledFunction()) |
| return F->getAttributes().hasParamAttr(ArgNo, Kind); |
| return false; |
| } |
| |
| bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const { |
| Value *V = getCalledOperand(); |
| if (auto *CE = dyn_cast<ConstantExpr>(V)) |
| if (CE->getOpcode() == BitCast) |
| V = CE->getOperand(0); |
| |
| if (auto *F = dyn_cast<Function>(V)) |
| return F->getAttributes().hasFnAttr(Kind); |
| |
| return false; |
| } |
| |
| bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const { |
| Value *V = getCalledOperand(); |
| if (auto *CE = dyn_cast<ConstantExpr>(V)) |
| if (CE->getOpcode() == BitCast) |
| V = CE->getOperand(0); |
| |
| if (auto *F = dyn_cast<Function>(V)) |
| return F->getAttributes().hasFnAttr(Kind); |
| |
| return false; |
| } |
| |
| void CallBase::getOperandBundlesAsDefs( |
| SmallVectorImpl<OperandBundleDef> &Defs) const { |
| for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) |
| Defs.emplace_back(getOperandBundleAt(i)); |
| } |
| |
| CallBase::op_iterator |
| CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles, |
| const unsigned BeginIndex) { |
| auto It = op_begin() + BeginIndex; |
| for (auto &B : Bundles) |
| It = std::copy(B.input_begin(), B.input_end(), It); |
| |
| auto *ContextImpl = getContext().pImpl; |
| auto BI = Bundles.begin(); |
| unsigned CurrentIndex = BeginIndex; |
| |
| for (auto &BOI : bundle_op_infos()) { |
| assert(BI != Bundles.end() && "Incorrect allocation?"); |
| |
| BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag()); |
| BOI.Begin = CurrentIndex; |
| BOI.End = CurrentIndex + BI->input_size(); |
| CurrentIndex = BOI.End; |
| BI++; |
| } |
| |
| assert(BI == Bundles.end() && "Incorrect allocation?"); |
| |
| return It; |
| } |
| |
| CallBase::BundleOpInfo &CallBase::getBundleOpInfoForOperand(unsigned OpIdx) { |
| /// When there isn't many bundles, we do a simple linear search. |
| /// Else fallback to a binary-search that use the fact that bundles usually |
| /// have similar number of argument to get faster convergence. |
| if (bundle_op_info_end() - bundle_op_info_begin() < 8) { |
| for (auto &BOI : bundle_op_infos()) |
| if (BOI.Begin <= OpIdx && OpIdx < BOI.End) |
| return BOI; |
| |
| llvm_unreachable("Did not find operand bundle for operand!"); |
| } |
| |
| assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles"); |
| assert(bundle_op_info_end() - bundle_op_info_begin() > 0 && |
| OpIdx < std::prev(bundle_op_info_end())->End && |
| "The Idx isn't in the operand bundle"); |
| |
| /// We need a decimal number below and to prevent using floating point numbers |
| /// we use an intergal value multiplied by this constant. |
| constexpr unsigned NumberScaling = 1024; |
| |
| bundle_op_iterator Begin = bundle_op_info_begin(); |
| bundle_op_iterator End = bundle_op_info_end(); |
| bundle_op_iterator Current = Begin; |
| |
| while (Begin != End) { |
| unsigned ScaledOperandPerBundle = |
| NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin); |
| Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) / |
| ScaledOperandPerBundle); |
| if (Current >= End) |
| Current = std::prev(End); |
| assert(Current < End && Current >= Begin && |
| "the operand bundle doesn't cover every value in the range"); |
| if (OpIdx >= Current->Begin && OpIdx < Current->End) |
| break; |
| if (OpIdx >= Current->End) |
| Begin = Current + 1; |
| else |
| End = Current; |
| } |
| |
| assert(OpIdx >= Current->Begin && OpIdx < Current->End && |
| "the operand bundle doesn't cover every value in the range"); |
| return *Current; |
| } |
| |
| CallBase *CallBase::addOperandBundle(CallBase *CB, uint32_t ID, |
| OperandBundleDef OB, |
| Instruction *InsertPt) { |
| if (CB->getOperandBundle(ID)) |
| return CB; |
| |
| SmallVector<OperandBundleDef, 1> Bundles; |
| CB->getOperandBundlesAsDefs(Bundles); |
| Bundles.push_back(OB); |
| return Create(CB, Bundles, InsertPt); |
| } |
| |
| CallBase *CallBase::removeOperandBundle(CallBase *CB, uint32_t ID, |
| Instruction *InsertPt) { |
| SmallVector<OperandBundleDef, 1> Bundles; |
| bool CreateNew = false; |
| |
| for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) { |
| auto Bundle = CB->getOperandBundleAt(I); |
| if (Bundle.getTagID() == ID) { |
| CreateNew = true; |
| continue; |
| } |
| Bundles.emplace_back(Bundle); |
| } |
| |
| return CreateNew ? Create(CB, Bundles, InsertPt) : CB; |
| } |
| |
| bool CallBase::hasReadingOperandBundles() const { |
| // Implementation note: this is a conservative implementation of operand |
| // bundle semantics, where *any* non-assume operand bundle forces a callsite |
| // to be at least readonly. |
| return hasOperandBundles() && getIntrinsicID() != Intrinsic::assume; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // CallInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, |
| ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) { |
| this->FTy = FTy; |
| assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 && |
| "NumOperands not set up?"); |
| |
| #ifndef NDEBUG |
| assert((Args.size() == FTy->getNumParams() || |
| (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && |
| "Calling a function with bad signature!"); |
| |
| for (unsigned i = 0; i != Args.size(); ++i) |
| assert((i >= FTy->getNumParams() || |
| FTy->getParamType(i) == Args[i]->getType()) && |
| "Calling a function with a bad signature!"); |
| #endif |
| |
| // Set operands in order of their index to match use-list-order |
| // prediction. |
| llvm::copy(Args, op_begin()); |
| setCalledOperand(Func); |
| |
| auto It = populateBundleOperandInfos(Bundles, Args.size()); |
| (void)It; |
| assert(It + 1 == op_end() && "Should add up!"); |
| |
| setName(NameStr); |
| } |
| |
| void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) { |
| this->FTy = FTy; |
| assert(getNumOperands() == 1 && "NumOperands not set up?"); |
| setCalledOperand(Func); |
| |
| assert(FTy->getNumParams() == 0 && "Calling a function with bad signature"); |
| |
| setName(NameStr); |
| } |
| |
| CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name, |
| Instruction *InsertBefore) |
| : CallBase(Ty->getReturnType(), Instruction::Call, |
| OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) { |
| init(Ty, Func, Name); |
| } |
| |
| CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name, |
| BasicBlock *InsertAtEnd) |
| : CallBase(Ty->getReturnType(), Instruction::Call, |
| OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) { |
| init(Ty, Func, Name); |
| } |
| |
| CallInst::CallInst(const CallInst &CI) |
| : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call, |
| OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(), |
| CI.getNumOperands()) { |
| setTailCallKind(CI.getTailCallKind()); |
| setCallingConv(CI.getCallingConv()); |
| |
| std::copy(CI.op_begin(), CI.op_end(), op_begin()); |
| std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(), |
| bundle_op_info_begin()); |
| SubclassOptionalData = CI.SubclassOptionalData; |
| } |
| |
| CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB, |
| Instruction *InsertPt) { |
| std::vector<Value *> Args(CI->arg_begin(), CI->arg_end()); |
| |
| auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(), |
| Args, OpB, CI->getName(), InsertPt); |
| NewCI->setTailCallKind(CI->getTailCallKind()); |
| NewCI->setCallingConv(CI->getCallingConv()); |
| NewCI->SubclassOptionalData = CI->SubclassOptionalData; |
| NewCI->setAttributes(CI->getAttributes()); |
| NewCI->setDebugLoc(CI->getDebugLoc()); |
| return NewCI; |
| } |
| |
| // Update profile weight for call instruction by scaling it using the ratio |
| // of S/T. The meaning of "branch_weights" meta data for call instruction is |
| // transfered to represent call count. |
| void CallInst::updateProfWeight(uint64_t S, uint64_t T) { |
| auto *ProfileData = getMetadata(LLVMContext::MD_prof); |
| if (ProfileData == nullptr) |
| return; |
| |
| auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0)); |
| if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") && |
| !ProfDataName->getString().equals("VP"))) |
| return; |
| |
| if (T == 0) { |
| LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in " |
| "div by 0. Ignoring. Likely the function " |
| << getParent()->getParent()->getName() |
| << " has 0 entry count, and contains call instructions " |
| "with non-zero prof info."); |
| return; |
| } |
| |
| MDBuilder MDB(getContext()); |
| SmallVector<Metadata *, 3> Vals; |
| Vals.push_back(ProfileData->getOperand(0)); |
| APInt APS(128, S), APT(128, T); |
| if (ProfDataName->getString().equals("branch_weights") && |
| ProfileData->getNumOperands() > 0) { |
| // Using APInt::div may be expensive, but most cases should fit 64 bits. |
| APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1)) |
| ->getValue() |
| .getZExtValue()); |
| Val *= APS; |
| Vals.push_back(MDB.createConstant( |
| ConstantInt::get(Type::getInt32Ty(getContext()), |
| Val.udiv(APT).getLimitedValue(UINT32_MAX)))); |
| } else if (ProfDataName->getString().equals("VP")) |
| for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) { |
| // The first value is the key of the value profile, which will not change. |
| Vals.push_back(ProfileData->getOperand(i)); |
| uint64_t Count = |
| mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1)) |
| ->getValue() |
| .getZExtValue(); |
| // Don't scale the magic number. |
| if (Count == NOMORE_ICP_MAGICNUM) { |
| Vals.push_back(ProfileData->getOperand(i + 1)); |
| continue; |
| } |
| // Using APInt::div may be expensive, but most cases should fit 64 bits. |
| APInt Val(128, Count); |
| Val *= APS; |
| Vals.push_back(MDB.createConstant( |
| ConstantInt::get(Type::getInt64Ty(getContext()), |
| Val.udiv(APT).getLimitedValue()))); |
| } |
| setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals)); |
| } |
| |
| /// IsConstantOne - Return true only if val is constant int 1 |
| static bool IsConstantOne(Value *val) { |
| assert(val && "IsConstantOne does not work with nullptr val"); |
| const ConstantInt *CVal = dyn_cast<ConstantInt>(val); |
| return CVal && CVal->isOne(); |
| } |
| |
| static Instruction *createMalloc(Instruction *InsertBefore, |
| BasicBlock *InsertAtEnd, Type *IntPtrTy, |
| Type *AllocTy, Value *AllocSize, |
| Value *ArraySize, |
| ArrayRef<OperandBundleDef> OpB, |
| Function *MallocF, const Twine &Name) { |
| assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && |
| "createMalloc needs either InsertBefore or InsertAtEnd"); |
| |
| // malloc(type) becomes: |
| // bitcast (i8* malloc(typeSize)) to type* |
| // malloc(type, arraySize) becomes: |
| // bitcast (i8* malloc(typeSize*arraySize)) to type* |
| if (!ArraySize) |
| ArraySize = ConstantInt::get(IntPtrTy, 1); |
| else if (ArraySize->getType() != IntPtrTy) { |
| if (InsertBefore) |
| ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, |
| "", InsertBefore); |
| else |
| ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, |
| "", InsertAtEnd); |
| } |
| |
| if (!IsConstantOne(ArraySize)) { |
| if (IsConstantOne(AllocSize)) { |
| AllocSize = ArraySize; // Operand * 1 = Operand |
| } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) { |
| Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy, |
| false /*ZExt*/); |
| // Malloc arg is constant product of type size and array size |
| AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize)); |
| } else { |
| // Multiply type size by the array size... |
| if (InsertBefore) |
| AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, |
| "mallocsize", InsertBefore); |
| else |
| AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, |
| "mallocsize", InsertAtEnd); |
| } |
| } |
| |
| assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size"); |
| // Create the call to Malloc. |
| BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; |
| Module *M = BB->getParent()->getParent(); |
| Type *BPTy = Type::getInt8PtrTy(BB->getContext()); |
| FunctionCallee MallocFunc = MallocF; |
| if (!MallocFunc) |
| // prototype malloc as "void *malloc(size_t)" |
| MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy); |
| PointerType *AllocPtrType = PointerType::getUnqual(AllocTy); |
| CallInst *MCall = nullptr; |
| Instruction *Result = nullptr; |
| if (InsertBefore) { |
| MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall", |
| InsertBefore); |
| Result = MCall; |
| if (Result->getType() != AllocPtrType) |
| // Create a cast instruction to convert to the right type... |
| Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore); |
| } else { |
| MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall"); |
| Result = MCall; |
| if (Result->getType() != AllocPtrType) { |
| InsertAtEnd->getInstList().push_back(MCall); |
| // Create a cast instruction to convert to the right type... |
| Result = new BitCastInst(MCall, AllocPtrType, Name); |
| } |
| } |
| MCall->setTailCall(); |
| if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) { |
| MCall->setCallingConv(F->getCallingConv()); |
| if (!F->returnDoesNotAlias()) |
| F->setReturnDoesNotAlias(); |
| } |
| assert(!MCall->getType()->isVoidTy() && "Malloc has void return type"); |
| |
| return Result; |
| } |
| |
| /// CreateMalloc - Generate the IR for a call to malloc: |
| /// 1. Compute the malloc call's argument as the specified type's size, |
| /// possibly multiplied by the array size if the array size is not |
| /// constant 1. |
| /// 2. Call malloc with that argument. |
| /// 3. Bitcast the result of the malloc call to the specified type. |
| Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, |
| Type *IntPtrTy, Type *AllocTy, |
| Value *AllocSize, Value *ArraySize, |
| Function *MallocF, |
| const Twine &Name) { |
| return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, |
| ArraySize, None, MallocF, Name); |
| } |
| Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, |
| Type *IntPtrTy, Type *AllocTy, |
| Value *AllocSize, Value *ArraySize, |
| ArrayRef<OperandBundleDef> OpB, |
| Function *MallocF, |
| const Twine &Name) { |
| return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, |
| ArraySize, OpB, MallocF, Name); |
| } |
| |
| /// CreateMalloc - Generate the IR for a call to malloc: |
| /// 1. Compute the malloc call's argument as the specified type's size, |
| /// possibly multiplied by the array size if the array size is not |
| /// constant 1. |
| /// 2. Call malloc with that argument. |
| /// 3. Bitcast the result of the malloc call to the specified type. |
| /// Note: This function does not add the bitcast to the basic block, that is the |
| /// responsibility of the caller. |
| Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, |
| Type *IntPtrTy, Type *AllocTy, |
| Value *AllocSize, Value *ArraySize, |
| Function *MallocF, const Twine &Name) { |
| return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, |
| ArraySize, None, MallocF, Name); |
| } |
| Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, |
| Type *IntPtrTy, Type *AllocTy, |
| Value *AllocSize, Value *ArraySize, |
| ArrayRef<OperandBundleDef> OpB, |
| Function *MallocF, const Twine &Name) { |
| return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, |
| ArraySize, OpB, MallocF, Name); |
| } |
| |
| static Instruction *createFree(Value *Source, |
| ArrayRef<OperandBundleDef> Bundles, |
| Instruction *InsertBefore, |
| BasicBlock *InsertAtEnd) { |
| assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && |
| "createFree needs either InsertBefore or InsertAtEnd"); |
| assert(Source->getType()->isPointerTy() && |
| "Can not free something of nonpointer type!"); |
| |
| BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; |
| Module *M = BB->getParent()->getParent(); |
| |
| Type *VoidTy = Type::getVoidTy(M->getContext()); |
| Type *IntPtrTy = Type::getInt8PtrTy(M->getContext()); |
| // prototype free as "void free(void*)" |
| FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy); |
| CallInst *Result = nullptr; |
| Value *PtrCast = Source; |
| if (InsertBefore) { |
| if (Source->getType() != IntPtrTy) |
| PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore); |
| Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore); |
| } else { |
| if (Source->getType() != IntPtrTy) |
| PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd); |
| Result = CallInst::Create(FreeFunc, PtrCast, Bundles, ""); |
| } |
| Result->setTailCall(); |
| if (Function *F = dyn_cast<Function>(FreeFunc.getCallee())) |
| Result->setCallingConv(F->getCallingConv()); |
| |
| return Result; |
| } |
| |
| /// CreateFree - Generate the IR for a call to the builtin free function. |
| Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) { |
| return createFree(Source, None, InsertBefore, nullptr); |
| } |
| Instruction *CallInst::CreateFree(Value *Source, |
| ArrayRef<OperandBundleDef> Bundles, |
| Instruction *InsertBefore) { |
| return createFree(Source, Bundles, InsertBefore, nullptr); |
| } |
| |
| /// CreateFree - Generate the IR for a call to the builtin free function. |
| /// Note: This function does not add the call to the basic block, that is the |
| /// responsibility of the caller. |
| Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) { |
| Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd); |
| assert(FreeCall && "CreateFree did not create a CallInst"); |
| return FreeCall; |
| } |
| Instruction *CallInst::CreateFree(Value *Source, |
| ArrayRef<OperandBundleDef> Bundles, |
| BasicBlock *InsertAtEnd) { |
| Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd); |
| assert(FreeCall && "CreateFree did not create a CallInst"); |
| return FreeCall; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // InvokeInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal, |
| BasicBlock *IfException, ArrayRef<Value *> Args, |
| ArrayRef<OperandBundleDef> Bundles, |
| const Twine &NameStr) { |
| this->FTy = FTy; |
| |
| assert((int)getNumOperands() == |
| ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) && |
| "NumOperands not set up?"); |
| |
| #ifndef NDEBUG |
| assert(((Args.size() == FTy->getNumParams()) || |
| (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && |
| "Invoking a function with bad signature"); |
| |
| for (unsigned i = 0, e = Args.size(); i != e; i++) |
| assert((i >= FTy->getNumParams() || |
| FTy->getParamType(i) == Args[i]->getType()) && |
| "Invoking a function with a bad signature!"); |
| #endif |
| |
| // Set operands in order of their index to match use-list-order |
| // prediction. |
| llvm::copy(Args, op_begin()); |
| setNormalDest(IfNormal); |
| setUnwindDest(IfException); |
| setCalledOperand(Fn); |
| |
| auto It = populateBundleOperandInfos(Bundles, Args.size()); |
| (void)It; |
| assert(It + 3 == op_end() && "Should add up!"); |
| |
| setName(NameStr); |
| } |
| |
| InvokeInst::InvokeInst(const InvokeInst &II) |
| : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke, |
| OperandTraits<CallBase>::op_end(this) - II.getNumOperands(), |
| II.getNumOperands()) { |
| setCallingConv(II.getCallingConv()); |
| std::copy(II.op_begin(), II.op_end(), op_begin()); |
| std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(), |
| bundle_op_info_begin()); |
| SubclassOptionalData = II.SubclassOptionalData; |
| } |
| |
| InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB, |
| Instruction *InsertPt) { |
| std::vector<Value *> Args(II->arg_begin(), II->arg_end()); |
| |
| auto *NewII = InvokeInst::Create( |
| II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(), |
| II->getUnwindDest(), Args, OpB, II->getName(), InsertPt); |
| NewII->setCallingConv(II->getCallingConv()); |
| NewII->SubclassOptionalData = II->SubclassOptionalData; |
| NewII->setAttributes(II->getAttributes()); |
| NewII->setDebugLoc(II->getDebugLoc()); |
| return NewII; |
| } |
| |
| LandingPadInst *InvokeInst::getLandingPadInst() const { |
| return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI()); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // CallBrInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough, |
| ArrayRef<BasicBlock *> IndirectDests, |
| ArrayRef<Value *> Args, |
| ArrayRef<OperandBundleDef> Bundles, |
| const Twine &NameStr) { |
| this->FTy = FTy; |
| |
| assert((int)getNumOperands() == |
| ComputeNumOperands(Args.size(), IndirectDests.size(), |
| CountBundleInputs(Bundles)) && |
| "NumOperands not set up?"); |
| |
| #ifndef NDEBUG |
| assert(((Args.size() == FTy->getNumParams()) || |
| (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && |
| "Calling a function with bad signature"); |
| |
| for (unsigned i = 0, e = Args.size(); i != e; i++) |
| assert((i >= FTy->getNumParams() || |
| FTy->getParamType(i) == Args[i]->getType()) && |
| "Calling a function with a bad signature!"); |
| #endif |
| |
| // Set operands in order of their index to match use-list-order |
| // prediction. |
| std::copy(Args.begin(), Args.end(), op_begin()); |
| NumIndirectDests = IndirectDests.size(); |
| setDefaultDest(Fallthrough); |
| for (unsigned i = 0; i != NumIndirectDests; ++i) |
| setIndirectDest(i, IndirectDests[i]); |
| setCalledOperand(Fn); |
| |
| auto It = populateBundleOperandInfos(Bundles, Args.size()); |
| (void)It; |
| assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!"); |
| |
| setName(NameStr); |
| } |
| |
| void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) { |
| assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr"); |
| if (BasicBlock *OldBB = getIndirectDest(i)) { |
| BlockAddress *Old = BlockAddress::get(OldBB); |
| BlockAddress *New = BlockAddress::get(B); |
| for (unsigned ArgNo = 0, e = arg_size(); ArgNo != e; ++ArgNo) |
| if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old) |
| setArgOperand(ArgNo, New); |
| } |
| } |
| |
| CallBrInst::CallBrInst(const CallBrInst &CBI) |
| : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr, |
| OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(), |
| CBI.getNumOperands()) { |
| setCallingConv(CBI.getCallingConv()); |
| std::copy(CBI.op_begin(), CBI.op_end(), op_begin()); |
| std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(), |
| bundle_op_info_begin()); |
| SubclassOptionalData = CBI.SubclassOptionalData; |
| NumIndirectDests = CBI.NumIndirectDests; |
| } |
| |
| CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB, |
| Instruction *InsertPt) { |
| std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end()); |
| |
| auto *NewCBI = CallBrInst::Create( |
| CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(), |
| CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt); |
| NewCBI->setCallingConv(CBI->getCallingConv()); |
| NewCBI->SubclassOptionalData = CBI->SubclassOptionalData; |
| NewCBI->setAttributes(CBI->getAttributes()); |
| NewCBI->setDebugLoc(CBI->getDebugLoc()); |
| NewCBI->NumIndirectDests = CBI->NumIndirectDests; |
| return NewCBI; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // ReturnInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| ReturnInst::ReturnInst(const ReturnInst &RI) |
| : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret, |
| OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(), |
| RI.getNumOperands()) { |
| if (RI.getNumOperands()) |
| Op<0>() = RI.Op<0>(); |
| SubclassOptionalData = RI.SubclassOptionalData; |
| } |
| |
| ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore) |
| : Instruction(Type::getVoidTy(C), Instruction::Ret, |
| OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, |
| InsertBefore) { |
| if (retVal) |
| Op<0>() = retVal; |
| } |
| |
| ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(C), Instruction::Ret, |
| OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, |
| InsertAtEnd) { |
| if (retVal) |
| Op<0>() = retVal; |
| } |
| |
| ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(Context), Instruction::Ret, |
| OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {} |
| |
| //===----------------------------------------------------------------------===// |
| // ResumeInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| ResumeInst::ResumeInst(const ResumeInst &RI) |
| : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume, |
| OperandTraits<ResumeInst>::op_begin(this), 1) { |
| Op<0>() = RI.Op<0>(); |
| } |
| |
| ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore) |
| : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume, |
| OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) { |
| Op<0>() = Exn; |
| } |
| |
| ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume, |
| OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) { |
| Op<0>() = Exn; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // CleanupReturnInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI) |
| : Instruction(CRI.getType(), Instruction::CleanupRet, |
| OperandTraits<CleanupReturnInst>::op_end(this) - |
| CRI.getNumOperands(), |
| CRI.getNumOperands()) { |
| setSubclassData<Instruction::OpaqueField>( |
| CRI.getSubclassData<Instruction::OpaqueField>()); |
| Op<0>() = CRI.Op<0>(); |
| if (CRI.hasUnwindDest()) |
| Op<1>() = CRI.Op<1>(); |
| } |
| |
| void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) { |
| if (UnwindBB) |
| setSubclassData<UnwindDestField>(true); |
| |
| Op<0>() = CleanupPad; |
| if (UnwindBB) |
| Op<1>() = UnwindBB; |
| } |
| |
| CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, |
| unsigned Values, Instruction *InsertBefore) |
| : Instruction(Type::getVoidTy(CleanupPad->getContext()), |
| Instruction::CleanupRet, |
| OperandTraits<CleanupReturnInst>::op_end(this) - Values, |
| Values, InsertBefore) { |
| init(CleanupPad, UnwindBB); |
| } |
| |
| CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, |
| unsigned Values, BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(CleanupPad->getContext()), |
| Instruction::CleanupRet, |
| OperandTraits<CleanupReturnInst>::op_end(this) - Values, |
| Values, InsertAtEnd) { |
| init(CleanupPad, UnwindBB); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // CatchReturnInst Implementation |
| //===----------------------------------------------------------------------===// |
| void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) { |
| Op<0>() = CatchPad; |
| Op<1>() = BB; |
| } |
| |
| CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI) |
| : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet, |
| OperandTraits<CatchReturnInst>::op_begin(this), 2) { |
| Op<0>() = CRI.Op<0>(); |
| Op<1>() = CRI.Op<1>(); |
| } |
| |
| CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, |
| Instruction *InsertBefore) |
| : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, |
| OperandTraits<CatchReturnInst>::op_begin(this), 2, |
| InsertBefore) { |
| init(CatchPad, BB); |
| } |
| |
| CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, |
| BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, |
| OperandTraits<CatchReturnInst>::op_begin(this), 2, |
| InsertAtEnd) { |
| init(CatchPad, BB); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // CatchSwitchInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
| unsigned NumReservedValues, |
| const Twine &NameStr, |
| Instruction *InsertBefore) |
| : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, |
| InsertBefore) { |
| if (UnwindDest) |
| ++NumReservedValues; |
| init(ParentPad, UnwindDest, NumReservedValues + 1); |
| setName(NameStr); |
| } |
| |
| CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
| unsigned NumReservedValues, |
| const Twine &NameStr, BasicBlock *InsertAtEnd) |
| : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, |
| InsertAtEnd) { |
| if (UnwindDest) |
| ++NumReservedValues; |
| init(ParentPad, UnwindDest, NumReservedValues + 1); |
| setName(NameStr); |
| } |
| |
| CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI) |
| : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr, |
| CSI.getNumOperands()) { |
| init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands()); |
| setNumHungOffUseOperands(ReservedSpace); |
| Use *OL = getOperandList(); |
| const Use *InOL = CSI.getOperandList(); |
| for (unsigned I = 1, E = ReservedSpace; I != E; ++I) |
| OL[I] = InOL[I]; |
| } |
| |
| void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest, |
| unsigned NumReservedValues) { |
| assert(ParentPad && NumReservedValues); |
| |
| ReservedSpace = NumReservedValues; |
| setNumHungOffUseOperands(UnwindDest ? 2 : 1); |
| allocHungoffUses(ReservedSpace); |
| |
| Op<0>() = ParentPad; |
| if (UnwindDest) { |
| setSubclassData<UnwindDestField>(true); |
| setUnwindDest(UnwindDest); |
| } |
| } |
| |
| /// growOperands - grow operands - This grows the operand list in response to a |
| /// push_back style of operation. This grows the number of ops by 2 times. |
| void CatchSwitchInst::growOperands(unsigned Size) { |
| unsigned NumOperands = getNumOperands(); |
| assert(NumOperands >= 1); |
| if (ReservedSpace >= NumOperands + Size) |
| return; |
| ReservedSpace = (NumOperands + Size / 2) * 2; |
| growHungoffUses(ReservedSpace); |
| } |
| |
| void CatchSwitchInst::addHandler(BasicBlock *Handler) { |
| unsigned OpNo = getNumOperands(); |
| growOperands(1); |
| assert(OpNo < ReservedSpace && "Growing didn't work!"); |
| setNumHungOffUseOperands(getNumOperands() + 1); |
| getOperandList()[OpNo] = Handler; |
| } |
| |
| void CatchSwitchInst::removeHandler(handler_iterator HI) { |
| // Move all subsequent handlers up one. |
| Use *EndDst = op_end() - 1; |
| for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst) |
| *CurDst = *(CurDst + 1); |
| // Null out the last handler use. |
| *EndDst = nullptr; |
| |
| setNumHungOffUseOperands(getNumOperands() - 1); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // FuncletPadInst Implementation |
| //===----------------------------------------------------------------------===// |
| void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args, |
| const Twine &NameStr) { |
| assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?"); |
| llvm::copy(Args, op_begin()); |
| setParentPad(ParentPad); |
| setName(NameStr); |
| } |
| |
| FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI) |
| : Instruction(FPI.getType(), FPI.getOpcode(), |
| OperandTraits<FuncletPadInst>::op_end(this) - |
| FPI.getNumOperands(), |
| FPI.getNumOperands()) { |
| std::copy(FPI.op_begin(), FPI.op_end(), op_begin()); |
| setParentPad(FPI.getParentPad()); |
| } |
| |
| FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, |
| ArrayRef<Value *> Args, unsigned Values, |
| const Twine &NameStr, Instruction *InsertBefore) |
| : Instruction(ParentPad->getType(), Op, |
| OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, |
| InsertBefore) { |
| init(ParentPad, Args, NameStr); |
| } |
| |
| FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, |
| ArrayRef<Value *> Args, unsigned Values, |
| const Twine &NameStr, BasicBlock *InsertAtEnd) |
| : Instruction(ParentPad->getType(), Op, |
| OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, |
| InsertAtEnd) { |
| init(ParentPad, Args, NameStr); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // UnreachableInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| UnreachableInst::UnreachableInst(LLVMContext &Context, |
| Instruction *InsertBefore) |
| : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, |
| 0, InsertBefore) {} |
| UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, |
| 0, InsertAtEnd) {} |
| |
| //===----------------------------------------------------------------------===// |
| // BranchInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| void BranchInst::AssertOK() { |
| if (isConditional()) |
| assert(getCondition()->getType()->isIntegerTy(1) && |
| "May only branch on boolean predicates!"); |
| } |
| |
| BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) |
| : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, |
| OperandTraits<BranchInst>::op_end(this) - 1, 1, |
| InsertBefore) { |
| assert(IfTrue && "Branch destination may not be null!"); |
| Op<-1>() = IfTrue; |
| } |
| |
| BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
| Instruction *InsertBefore) |
| : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, |
| OperandTraits<BranchInst>::op_end(this) - 3, 3, |
| InsertBefore) { |
| // Assign in order of operand index to make use-list order predictable. |
| Op<-3>() = Cond; |
| Op<-2>() = IfFalse; |
| Op<-1>() = IfTrue; |
| #ifndef NDEBUG |
| AssertOK(); |
| #endif |
| } |
| |
| BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, |
| OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) { |
| assert(IfTrue && "Branch destination may not be null!"); |
| Op<-1>() = IfTrue; |
| } |
| |
| BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
| BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, |
| OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) { |
| // Assign in order of operand index to make use-list order predictable. |
| Op<-3>() = Cond; |
| Op<-2>() = IfFalse; |
| Op<-1>() = IfTrue; |
| #ifndef NDEBUG |
| AssertOK(); |
| #endif |
| } |
| |
| BranchInst::BranchInst(const BranchInst &BI) |
| : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br, |
| OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), |
| BI.getNumOperands()) { |
| // Assign in order of operand index to make use-list order predictable. |
| if (BI.getNumOperands() != 1) { |
| assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!"); |
| Op<-3>() = BI.Op<-3>(); |
| Op<-2>() = BI.Op<-2>(); |
| } |
| Op<-1>() = BI.Op<-1>(); |
| SubclassOptionalData = BI.SubclassOptionalData; |
| } |
| |
| void BranchInst::swapSuccessors() { |
| assert(isConditional() && |
| "Cannot swap successors of an unconditional branch"); |
| Op<-1>().swap(Op<-2>()); |
| |
| // Update profile metadata if present and it matches our structural |
| // expectations. |
| swapProfMetadata(); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // AllocaInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| static Value *getAISize(LLVMContext &Context, Value *Amt) { |
| if (!Amt) |
| Amt = ConstantInt::get(Type::getInt32Ty(Context), 1); |
| else { |
| assert(!isa<BasicBlock>(Amt) && |
| "Passed basic block into allocation size parameter! Use other ctor"); |
| assert(Amt->getType()->isIntegerTy() && |
| "Allocation array size is not an integer!"); |
| } |
| return Amt; |
| } |
| |
| static Align computeAllocaDefaultAlign(Type *Ty, BasicBlock *BB) { |
| assert(BB && "Insertion BB cannot be null when alignment not provided!"); |
| assert(BB->getParent() && |
| "BB must be in a Function when alignment not provided!"); |
| const DataLayout &DL = BB->getModule()->getDataLayout(); |
| return DL.getPrefTypeAlign(Ty); |
| } |
| |
| static Align computeAllocaDefaultAlign(Type *Ty, Instruction *I) { |
| assert(I && "Insertion position cannot be null when alignment not provided!"); |
| return computeAllocaDefaultAlign(Ty, I->getParent()); |
| } |
| |
| AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, |
| Instruction *InsertBefore) |
| : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {} |
| |
| AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, |
| BasicBlock *InsertAtEnd) |
| : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {} |
| |
| AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
| const Twine &Name, Instruction *InsertBefore) |
| : AllocaInst(Ty, AddrSpace, ArraySize, |
| computeAllocaDefaultAlign(Ty, InsertBefore), Name, |
| InsertBefore) {} |
| |
| AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
| const Twine &Name, BasicBlock *InsertAtEnd) |
| : AllocaInst(Ty, AddrSpace, ArraySize, |
| computeAllocaDefaultAlign(Ty, InsertAtEnd), Name, |
| InsertAtEnd) {} |
| |
| AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
| Align Align, const Twine &Name, |
| Instruction *InsertBefore) |
| : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, |
| getAISize(Ty->getContext(), ArraySize), InsertBefore), |
| AllocatedType(Ty) { |
| setAlignment(Align); |
| assert(!Ty->isVoidTy() && "Cannot allocate void!"); |
| setName(Name); |
| } |
| |
| AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
| Align Align, const Twine &Name, BasicBlock *InsertAtEnd) |
| : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, |
| getAISize(Ty->getContext(), ArraySize), InsertAtEnd), |
| AllocatedType(Ty) { |
| setAlignment(Align); |
| assert(!Ty->isVoidTy() && "Cannot allocate void!"); |
| setName(Name); |
| } |
| |
| |
| bool AllocaInst::isArrayAllocation() const { |
| if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) |
| return !CI->isOne(); |
| return true; |
| } |
| |
| /// isStaticAlloca - Return true if this alloca is in the entry block of the |
| /// function and is a constant size. If so, the code generator will fold it |
| /// into the prolog/epilog code, so it is basically free. |
| bool AllocaInst::isStaticAlloca() const { |
| // Must be constant size. |
| if (!isa<ConstantInt>(getArraySize())) return false; |
| |
| // Must be in the entry block. |
| const BasicBlock *Parent = getParent(); |
| return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca(); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // LoadInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| void LoadInst::AssertOK() { |
| assert(getOperand(0)->getType()->isPointerTy() && |
| "Ptr must have pointer type."); |
| assert(!(isAtomic() && getAlignment() == 0) && |
| "Alignment required for atomic load"); |
| } |
| |
| static Align computeLoadStoreDefaultAlign(Type *Ty, BasicBlock *BB) { |
| assert(BB && "Insertion BB cannot be null when alignment not provided!"); |
| assert(BB->getParent() && |
| "BB must be in a Function when alignment not provided!"); |
| const DataLayout &DL = BB->getModule()->getDataLayout(); |
| return DL.getABITypeAlign(Ty); |
| } |
| |
| static Align computeLoadStoreDefaultAlign(Type *Ty, Instruction *I) { |
| assert(I && "Insertion position cannot be null when alignment not provided!"); |
| return computeLoadStoreDefaultAlign(Ty, I->getParent()); |
| } |
| |
| LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, |
| Instruction *InsertBef) |
| : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {} |
| |
| LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, |
| BasicBlock *InsertAE) |
| : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {} |
| |
| LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, |
| Instruction *InsertBef) |
| : LoadInst(Ty, Ptr, Name, isVolatile, |
| computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {} |
| |
| LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, |
| BasicBlock *InsertAE) |
| : LoadInst(Ty, Ptr, Name, isVolatile, |
| computeLoadStoreDefaultAlign(Ty, InsertAE), InsertAE) {} |
| |
| LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, |
| Align Align, Instruction *InsertBef) |
| : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, |
| SyncScope::System, InsertBef) {} |
| |
| LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, |
| Align Align, BasicBlock *InsertAE) |
| : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, |
| SyncScope::System, InsertAE) {} |
| |
| LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, |
| Align Align, AtomicOrdering Order, SyncScope::ID SSID, |
| Instruction *InsertBef) |
| : UnaryInstruction(Ty, Load, Ptr, InsertBef) { |
| assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty)); |
| setVolatile(isVolatile); |
| setAlignment(Align); |
| setAtomic(Order, SSID); |
| AssertOK(); |
| setName(Name); |
| } |
| |
| LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, |
| Align Align, AtomicOrdering Order, SyncScope::ID SSID, |
| BasicBlock *InsertAE) |
| : UnaryInstruction(Ty, Load, Ptr, InsertAE) { |
| assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty)); |
| setVolatile(isVolatile); |
| setAlignment(Align); |
| setAtomic(Order, SSID); |
| AssertOK(); |
| setName(Name); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // StoreInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| void StoreInst::AssertOK() { |
| assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); |
| assert(getOperand(1)->getType()->isPointerTy() && |
| "Ptr must have pointer type!"); |
| assert(cast<PointerType>(getOperand(1)->getType()) |
| ->isOpaqueOrPointeeTypeMatches(getOperand(0)->getType()) && |
| "Ptr must be a pointer to Val type!"); |
| assert(!(isAtomic() && getAlignment() == 0) && |
| "Alignment required for atomic store"); |
| } |
| |
| StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) |
| : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {} |
| |
| StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) |
| : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {} |
| |
| StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, |
| Instruction *InsertBefore) |
| : StoreInst(val, addr, isVolatile, |
| computeLoadStoreDefaultAlign(val->getType(), InsertBefore), |
| InsertBefore) {} |
| |
| StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, |
| BasicBlock *InsertAtEnd) |
| : StoreInst(val, addr, isVolatile, |
| computeLoadStoreDefaultAlign(val->getType(), InsertAtEnd), |
| InsertAtEnd) {} |
| |
| StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, |
| Instruction *InsertBefore) |
| : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, |
| SyncScope::System, InsertBefore) {} |
| |
| StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, |
| BasicBlock *InsertAtEnd) |
| : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, |
| SyncScope::System, InsertAtEnd) {} |
| |
| StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, |
| AtomicOrdering Order, SyncScope::ID SSID, |
| Instruction *InsertBefore) |
| : Instruction(Type::getVoidTy(val->getContext()), Store, |
| OperandTraits<StoreInst>::op_begin(this), |
| OperandTraits<StoreInst>::operands(this), InsertBefore) { |
| Op<0>() = val; |
| Op<1>() = addr; |
| setVolatile(isVolatile); |
| setAlignment(Align); |
| setAtomic(Order, SSID); |
| AssertOK(); |
| } |
| |
| StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align, |
| AtomicOrdering Order, SyncScope::ID SSID, |
| BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(val->getContext()), Store, |
| OperandTraits<StoreInst>::op_begin(this), |
| OperandTraits<StoreInst>::operands(this), InsertAtEnd) { |
| Op<0>() = val; |
| Op<1>() = addr; |
| setVolatile(isVolatile); |
| setAlignment(Align); |
| setAtomic(Order, SSID); |
| AssertOK(); |
| } |
| |
| |
| //===----------------------------------------------------------------------===// |
| // AtomicCmpXchgInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal, |
| Align Alignment, AtomicOrdering SuccessOrdering, |
| AtomicOrdering FailureOrdering, |
| SyncScope::ID SSID) { |
| Op<0>() = Ptr; |
| Op<1>() = Cmp; |
| Op<2>() = NewVal; |
| setSuccessOrdering(SuccessOrdering); |
| setFailureOrdering(FailureOrdering); |
| setSyncScopeID(SSID); |
| setAlignment(Alignment); |
| |
| assert(getOperand(0) && getOperand(1) && getOperand(2) && |
| "All operands must be non-null!"); |
| assert(getOperand(0)->getType()->isPointerTy() && |
| "Ptr must have pointer type!"); |
| assert(cast<PointerType>(getOperand(0)->getType()) |
| ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) && |
| "Ptr must be a pointer to Cmp type!"); |
| assert(cast<PointerType>(getOperand(0)->getType()) |
| ->isOpaqueOrPointeeTypeMatches(getOperand(2)->getType()) && |
| "Ptr must be a pointer to NewVal type!"); |
| assert(getOperand(1)->getType() == getOperand(2)->getType() && |
| "Cmp type and NewVal type must be same!"); |
| } |
| |
| AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, |
| Align Alignment, |
| AtomicOrdering SuccessOrdering, |
| AtomicOrdering FailureOrdering, |
| SyncScope::ID SSID, |
| Instruction *InsertBefore) |
| : Instruction( |
| StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), |
| AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), |
| OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) { |
| Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID); |
| } |
| |
| AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, |
| Align Alignment, |
| AtomicOrdering SuccessOrdering, |
| AtomicOrdering FailureOrdering, |
| SyncScope::ID SSID, |
| BasicBlock *InsertAtEnd) |
| : Instruction( |
| StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), |
| AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), |
| OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) { |
| Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // AtomicRMWInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val, |
| Align Alignment, AtomicOrdering Ordering, |
| SyncScope::ID SSID) { |
| Op<0>() = Ptr; |
| Op<1>() = Val; |
| setOperation(Operation); |
| setOrdering(Ordering); |
| setSyncScopeID(SSID); |
| setAlignment(Alignment); |
| |
| assert(getOperand(0) && getOperand(1) && |
| "All operands must be non-null!"); |
| assert(getOperand(0)->getType()->isPointerTy() && |
| "Ptr must have pointer type!"); |
| assert(cast<PointerType>(getOperand(0)->getType()) |
| ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) && |
| "Ptr must be a pointer to Val type!"); |
| assert(Ordering != AtomicOrdering::NotAtomic && |
| "AtomicRMW instructions must be atomic!"); |
| } |
| |
| AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, |
| Align Alignment, AtomicOrdering Ordering, |
| SyncScope::ID SSID, Instruction *InsertBefore) |
| : Instruction(Val->getType(), AtomicRMW, |
| OperandTraits<AtomicRMWInst>::op_begin(this), |
| OperandTraits<AtomicRMWInst>::operands(this), InsertBefore) { |
| Init(Operation, Ptr, Val, Alignment, Ordering, SSID); |
| } |
| |
| AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, |
| Align Alignment, AtomicOrdering Ordering, |
| SyncScope::ID SSID, BasicBlock *InsertAtEnd) |
| : Instruction(Val->getType(), AtomicRMW, |
| OperandTraits<AtomicRMWInst>::op_begin(this), |
| OperandTraits<AtomicRMWInst>::operands(this), InsertAtEnd) { |
| Init(Operation, Ptr, Val, Alignment, Ordering, SSID); |
| } |
| |
| StringRef AtomicRMWInst::getOperationName(BinOp Op) { |
| switch (Op) { |
| case AtomicRMWInst::Xchg: |
| return "xchg"; |
| case AtomicRMWInst::Add: |
| return "add"; |
| case AtomicRMWInst::Sub: |
| return "sub"; |
| case AtomicRMWInst::And: |
| return "and"; |
| case AtomicRMWInst::Nand: |
| return "nand"; |
| case AtomicRMWInst::Or: |
| return "or"; |
| case AtomicRMWInst::Xor: |
| return "xor"; |
| case AtomicRMWInst::Max: |
| return "max"; |
| case AtomicRMWInst::Min: |
| return "min"; |
| case AtomicRMWInst::UMax: |
| return "umax"; |
| case AtomicRMWInst::UMin: |
| return "umin"; |
| case AtomicRMWInst::FAdd: |
| return "fadd"; |
| case AtomicRMWInst::FSub: |
| return "fsub"; |
| case AtomicRMWInst::BAD_BINOP: |
| return "<invalid operation>"; |
| } |
| |
| llvm_unreachable("invalid atomicrmw operation"); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // FenceInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, |
| SyncScope::ID SSID, |
| Instruction *InsertBefore) |
| : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) { |
| setOrdering(Ordering); |
| setSyncScopeID(SSID); |
| } |
| |
| FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, |
| SyncScope::ID SSID, |
| BasicBlock *InsertAtEnd) |
| : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) { |
| setOrdering(Ordering); |
| setSyncScopeID(SSID); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // GetElementPtrInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList, |
| const Twine &Name) { |
| assert(getNumOperands() == 1 + IdxList.size() && |
| "NumOperands not initialized?"); |
| Op<0>() = Ptr; |
| llvm::copy(IdxList, op_begin() + 1); |
| setName(Name); |
| } |
| |
| GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) |
| : Instruction(GEPI.getType(), GetElementPtr, |
| OperandTraits<GetElementPtrInst>::op_end(this) - |
| GEPI.getNumOperands(), |
| GEPI.getNumOperands()), |
| SourceElementType(GEPI.SourceElementType), |
| ResultElementType(GEPI.ResultElementType) { |
| std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin()); |
| SubclassOptionalData = GEPI.SubclassOptionalData; |
| } |
| |
| Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, Value *Idx) { |
| if (auto *Struct = dyn_cast<StructType>(Ty)) { |
| if (!Struct->indexValid(Idx)) |
| return nullptr; |
| return Struct->getTypeAtIndex(Idx); |
| } |
| if (!Idx->getType()->isIntOrIntVectorTy()) |
| return nullptr; |
| if (auto *Array = dyn_cast<ArrayType>(Ty)) |
| return Array->getElementType(); |
| if (auto *Vector = dyn_cast<VectorType>(Ty)) |
| return Vector->getElementType(); |
| return nullptr; |
| } |
| |
| Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, uint64_t Idx) { |
| if (auto *Struct = dyn_cast<StructType>(Ty)) { |
| if (Idx >= Struct->getNumElements()) |
| return nullptr; |
| return Struct->getElementType(Idx); |
| } |
| if (auto *Array = dyn_cast<ArrayType>(Ty)) |
| return Array->getElementType(); |
| if (auto *Vector = dyn_cast<VectorType>(Ty)) |
| return Vector->getElementType(); |
| return nullptr; |
| } |
| |
| template <typename IndexTy> |
| static Type *getIndexedTypeInternal(Type *Ty, ArrayRef<IndexTy> IdxList) { |
| if (IdxList.empty()) |
| return Ty; |
| for (IndexTy V : IdxList.slice(1)) { |
| Ty = GetElementPtrInst::getTypeAtIndex(Ty, V); |
| if (!Ty) |
| return Ty; |
| } |
| return Ty; |
| } |
| |
| Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) { |
| return getIndexedTypeInternal(Ty, IdxList); |
| } |
| |
| Type *GetElementPtrInst::getIndexedType(Type *Ty, |
| ArrayRef<Constant *> IdxList) { |
| return getIndexedTypeInternal(Ty, IdxList); |
| } |
| |
| Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) { |
| return getIndexedTypeInternal(Ty, IdxList); |
| } |
| |
| /// hasAllZeroIndices - Return true if all of the indices of this GEP are |
| /// zeros. If so, the result pointer and the first operand have the same |
| /// value, just potentially different types. |
| bool GetElementPtrInst::hasAllZeroIndices() const { |
| for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
| if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { |
| if (!CI->isZero()) return false; |
| } else { |
| return false; |
| } |
| } |
| return true; |
| } |
| |
| /// hasAllConstantIndices - Return true if all of the indices of this GEP are |
| /// constant integers. If so, the result pointer and the first operand have |
| /// a constant offset between them. |
| bool GetElementPtrInst::hasAllConstantIndices() const { |
| for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
| if (!isa<ConstantInt>(getOperand(i))) |
| return false; |
| } |
| return true; |
| } |
| |
| void GetElementPtrInst::setIsInBounds(bool B) { |
| cast<GEPOperator>(this)->setIsInBounds(B); |
| } |
| |
| bool GetElementPtrInst::isInBounds() const { |
| return cast<GEPOperator>(this)->isInBounds(); |
| } |
| |
| bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL, |
| APInt &Offset) const { |
| // Delegate to the generic GEPOperator implementation. |
| return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset); |
| } |
| |
| bool GetElementPtrInst::collectOffset( |
| const DataLayout &DL, unsigned BitWidth, |
| MapVector<Value *, APInt> &VariableOffsets, |
| APInt &ConstantOffset) const { |
| // Delegate to the generic GEPOperator implementation. |
| return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets, |
| ConstantOffset); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // ExtractElementInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, |
| const Twine &Name, |
| Instruction *InsertBef) |
| : Instruction(cast<VectorType>(Val->getType())->getElementType(), |
| ExtractElement, |
| OperandTraits<ExtractElementInst>::op_begin(this), |
| 2, InsertBef) { |
| assert(isValidOperands(Val, Index) && |
| "Invalid extractelement instruction operands!"); |
| Op<0>() = Val; |
| Op<1>() = Index; |
| setName(Name); |
| } |
| |
| ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, |
| const Twine &Name, |
| BasicBlock *InsertAE) |
| : Instruction(cast<VectorType>(Val->getType())->getElementType(), |
| ExtractElement, |
| OperandTraits<ExtractElementInst>::op_begin(this), |
| 2, InsertAE) { |
| assert(isValidOperands(Val, Index) && |
| "Invalid extractelement instruction operands!"); |
| |
| Op<0>() = Val; |
| Op<1>() = Index; |
| setName(Name); |
| } |
| |
| bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { |
| if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy()) |
| return false; |
| return true; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // InsertElementInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, |
| const Twine &Name, |
| Instruction *InsertBef) |
| : Instruction(Vec->getType(), InsertElement, |
| OperandTraits<InsertElementInst>::op_begin(this), |
| 3, InsertBef) { |
| assert(isValidOperands(Vec, Elt, Index) && |
| "Invalid insertelement instruction operands!"); |
| Op<0>() = Vec; |
| Op<1>() = Elt; |
| Op<2>() = Index; |
| setName(Name); |
| } |
| |
| InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, |
| const Twine &Name, |
| BasicBlock *InsertAE) |
| : Instruction(Vec->getType(), InsertElement, |
| OperandTraits<InsertElementInst>::op_begin(this), |
| 3, InsertAE) { |
| assert(isValidOperands(Vec, Elt, Index) && |
| "Invalid insertelement instruction operands!"); |
| |
| Op<0>() = Vec; |
| Op<1>() = Elt; |
| Op<2>() = Index; |
| setName(Name); |
| } |
| |
| bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, |
| const Value *Index) { |
| if (!Vec->getType()->isVectorTy()) |
| return false; // First operand of insertelement must be vector type. |
| |
| if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) |
| return false;// Second operand of insertelement must be vector element type. |
| |
| if (!Index->getType()->isIntegerTy()) |
| return false; // Third operand of insertelement must be i32. |
| return true; |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // ShuffleVectorInst Implementation |
| //===----------------------------------------------------------------------===// |
| |
| static Value *createPlaceholderForShuffleVector(Value *V) { |
| assert(V && "Cannot create placeholder of nullptr V"); |
| return PoisonValue::get(V->getType()); |
| } |
| |
| ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name, |
| Instruction *InsertBefore) |
| : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name, |
| InsertBefore) {} |
| |
| ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name, |
| BasicBlock *InsertAtEnd) |
| : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name, |
| InsertAtEnd) {} |
| |
| ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask, |
| const Twine &Name, |
| Instruction *InsertBefore) |
| : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name, |
| InsertBefore) {} |
| |
| ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask, |
| const Twine &Name, BasicBlock *InsertAtEnd) |
| : ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name, |
| InsertAtEnd) {} |
| |
| ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
| const Twine &Name, |
| Instruction *InsertBefore) |
| : Instruction( |
| VectorType::get(cast<VectorType>(V1->getType())->getElementType(), |
| cast<VectorType>(Mask->getType())->getElementCount()), |
| ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), |
| OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) { |
| assert(isValidOperands(V1, V2, Mask) && |
| "Invalid shuffle vector instruction operands!"); |
| |
| Op<0>() = V1; |
| Op<1>() = V2; |
| SmallVector<int, 16> MaskArr; |
| getShuffleMask(cast<Constant>(Mask), MaskArr); |
| setShuffleMask(MaskArr); |
| setName(Name); |
| } |
| |
| ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
| const Twine &Name, BasicBlock *InsertAtEnd) |
| : Instruction( |
| VectorType::get(cast<VectorType>(V1->getType())->getElementType(), |
| cast<VectorType>(Mask->getType())->getElementCount()), |
| ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), |
| OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) { |
| assert(isValidOperands(V1, V2, Mask) && |
| "Invalid shuffle vector instruction operands!"); |
| |
| Op<0>() = V1; |
| Op<1>() = V2; |
| SmallVector<int, 16> MaskArr; |
| getShuffleMask(cast<Constant>(Mask), MaskArr); |
| setShuffleMask(MaskArr); |
| setName(Name); |
| } |
| |
| ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
| const Twine &Name, |
| Instruction *InsertBefore) |
| : Instruction( |
| VectorType::get(cast<VectorType>(V1->getType())->getElementType(), |
| Mask.size(), isa<ScalableVectorType>(V1->getType())), |
| ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), |
| OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) { |
| assert(isValidOperands(V1, V2, Mask) && |
| "Invalid shuffle vector instruction operands!"); |
| Op<0>() = V1; |
| Op<1>() = V2; |
| setShuffleMask(Mask); |
| setName(Name); |
| } |
| |
| ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
| const Twine &Name, BasicBlock *InsertAtEnd) |
| : Instruction( |
| VectorType::get(cast<VectorType>(V1->getType())->getElementType(), |
| Mask.size(), isa<ScalableVectorType>(V1->getType())), |
| ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), |
| OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) { |
| assert(isValidOperands(V1, V2, Mask) && |
| "Invalid shuffle vector instruction operands!"); |
| |
| Op<0>() = V1; |
| Op<1>() = V2; |
| setShuffleMask(Mask); |
| setName(Name); |
| } |
| |
| void ShuffleVectorInst::commute() { |
| int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
| int NumMaskElts = ShuffleMask.size(); |
| SmallVector<int, 16> NewMask(NumMaskElts); |
| for (int i = 0; i != NumMaskElts; ++i) { |
| int MaskElt = getMaskValue(i); |
| if (MaskElt == UndefMaskElem) { |
| NewMask[i] = UndefMaskElem; |
| continue; |
| } |
| assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask"); |
| MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts; |
| NewMask[i] = MaskElt; |
| } |
| setShuffleMask(NewMask); |
| Op<0>().swap(Op<1>()); |
| } |
| |
| bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, |
| ArrayRef<int> Mask) { |
| // V1 and V2 must be vectors of the same type. |
| if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType()) |
| return false; |
| |
| // Make sure the mask elements make sense. |
| int V1Size = |
| cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue(); |
| for (int Elem : Mask) |
| if (Elem != UndefMaskElem && Elem >= V1Size * 2) |
| return false; |
| |
| if (isa<ScalableVectorType>(V1->getType())) |
| if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !is_splat(Mask)) |
| return false; |
| |
| return true; |
| } |
| |
| bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, |
| const Value *Mask) { |
| // V1 and V2 must be vectors of the same type. |
| if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType()) |
| return false; |
| |
| // Mask must be vector of i32, and must be the same kind of vector as the |
| // input vectors |
| auto *MaskTy = dyn_cast<VectorType>(Mask->getType()); |
| if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) || |
| isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType())) |
| return false; |
| |
| // Check to see if Mask is valid. |
| if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask)) |
| return true; |
| |
| if (const auto *MV = dyn_cast<ConstantVector>(Mask)) { |
| unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements(); |
| for (Value *Op : MV->operands()) { |
| if (auto *CI = dyn_cast<ConstantInt>(Op)) { |
| if (CI->uge(V1Size*2)) |
| return false; |
| } else if (!isa<UndefValue>(Op)) { |
| return false; |
| } |
| } |
| return true; |
| } |
| |
| if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { |
| unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements(); |
| for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements(); |
| i != e; ++i) |
| if (CDS->getElementAsInteger(i) >= V1Size*2) |
| return false; |
| return true; |
| } |
| |
| return false; |
| } |
| |
| void ShuffleVectorInst::getShuffleMask(const Constant *Mask, |
| SmallVectorImpl<int> &Result) { |
| ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount(); |
| |
| if (isa<ConstantAggregateZero>(Mask)) { |
| Result.resize(EC.getKnownMinValue(), 0); |
| return; |
| } |
| |
| Result.reserve(EC.getKnownMinValue()); |
| |
| if (EC.isScalable()) { |
| assert((isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) && |
| "Scalable vector shuffle mask must be undef or zeroinitializer"); |
| int MaskVal = isa<UndefValue>(Mask) ? -1 : 0; |
| for (unsigned I = 0; I < EC.getKnownMinValue(); ++I) |
| Result.emplace_back(MaskVal); |
| return; |
| } |
| |
| unsigned NumElts = EC.getKnownMinValue(); |
| |
| if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { |
| for (unsigned i = 0; i != NumElts; ++i) |
| Result.push_back(CDS->getElementAsInteger(i)); |
| return; |
| } |
| for (unsigned i = 0; i != NumElts; ++i) { |
| Constant *C = Mask->getAggregateElement(i); |
| Result.push_back(isa<UndefValue>(C) ? -1 : |
| cast<ConstantInt>(C)->getZExtValue()); |
| } |
| } |
| |
| void ShuffleVectorInst::setShuffleMask(ArrayRef<int> Mask) { |
| ShuffleMask.assign(Mask.begin(), Mask.end()); |
| ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType()); |
| } |
| |
| Constant *ShuffleVectorInst::convertShuffleMaskForBitcode(ArrayRef<int> Mask, |
| Type *ResultTy) { |
| Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext()); |
| if (isa<ScalableVectorType>(ResultTy)) { |
| assert(is_splat(Mask) && "Unexpected shuffle"); |
| Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true); |
| if (Mask[0] == 0) |
| return Constant::getNullValue(VecTy); |
| return UndefValue::get(VecTy); |
| } |
| SmallVector<Constant *, 16> MaskConst; |
| for (int Elem : Mask) { |
| if (Elem == UndefMaskElem) |
| MaskConst.push_back(UndefValue::get(Int32Ty)); |
| else |
| MaskConst.push_back(ConstantInt::get(Int32Ty, Elem)); |
| } |
| return ConstantVector::get(MaskConst); |
| } |
| |
| static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) { |
| assert(!Mask.empty() && "Shuffle mask must contain elements"); |
| bool UsesLHS = false; |
| bool UsesRHS = false; |
| for (int I : Mask) { |
| if (I == -1) |
| continue; |
| assert(I >= 0 && I < (NumOpElts * 2) && |
| "Out-of-bounds shuffle mask element"); |
| UsesLHS |= (I < NumOpElts); |
| UsesRHS |= (I >= NumOpElts); |
| if (UsesLHS && UsesRHS) |
| return false; |
| } |
| // Allow for degenerate case: completely undef mask means neither source is used. |
| return UsesLHS || UsesRHS; |
| } |
| |
| bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) { |
| // We don't have vector operand size information, so assume operands are the |
| // same size as the mask. |
| return isSingleSourceMaskImpl(Mask, Mask.size()); |
| } |
| |
| static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) { |
| if (!isSingleSourceMaskImpl(Mask, NumOpElts)) |
| return false; |
| for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) { |
| if (Mask[i] == -1) |
| continue; |
| if (Mask[i] != i && Mask[i] != (NumOpElts + i)) |
| return false; |
| } |
| return true; |
| } |
| |
| bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) { |
| // We don't have vector operand size information, so assume operands are the |
| // same size as the mask. |
| return isIdentityMaskImpl(Mask, Mask.size()); |
| } |
| |
| bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) { |
| if (!isSingleSourceMask(Mask)) |
| return false; |
| for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { |
| if (Mask[i] == -1) |
| continue; |
| if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i)) |
| return false; |
| } |
| return true; |
| } |
| |
| bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) { |
| if (!isSingleSourceMask(Mask)) |
| return false; |
| for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { |
| if (Mask[i] == -1) |
| continue; |
| if (Mask[i] != 0 && Mask[i] != NumElts) |
| return false; |
| } |
| return true; |
| } |
| |
| bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) { |
| // Select is differentiated from identity. It requires using both sources. |
| if (isSingleSourceMask(Mask)) |
| return false; |
| for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { |
| if (Mask[i] == -1) |
| continue; |
| if (Mask[i] != i && Mask[i] != (NumElts + i)) |
| return false; |
| } |
| return true; |
| } |
| |
| bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) { |
| // Example masks that will return true: |
| // v1 = <a, b, c, d> |
| // v2 = <e, f, g, h> |
| // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g> |
| // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h> |
| |
| // 1. The number of elements in the mask must be a power-of-2 and at least 2. |
| int NumElts = Mask.size(); |
| if (NumElts < 2 || !isPowerOf2_32(NumElts)) |
| return false; |
| |
| // 2. The first element of the mask must be either a 0 or a 1. |
| if (Mask[0] != 0 && Mask[0] != 1) |
| return false; |
| |
| // 3. The difference between the first 2 elements must be equal to the |
| // number of elements in the mask. |
| if ((Mask[1] - Mask[0]) != NumElts) |
| return false; |
| |
| // 4. The difference between consecutive even-numbered and odd-numbered |
| // elements must be equal to 2. |
| for (int i = 2; i < NumElts; ++i) { |
| int MaskEltVal = Mask[i]; |
| if (MaskEltVal == -1) |
| return false; |
| int MaskEltPrevVal = Mask[i - 2]; |
| if (MaskEltVal - MaskEltPrevVal != 2) |
| return false; |
| } |
| return true; |
| } |
| |
| bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask, |
| int NumSrcElts, int &Index) { |
| // Must extract from a single source. |
| if (!isSingleSourceMaskImpl(Mask, NumSrcElts)) |
| return false; |
| |
| // Must be smaller (else this is an Identity shuffle). |
| if (NumSrcElts <= (int)Mask.size()) |
| return false; |
| |
| // Find start of extraction, accounting that we may start with an UNDEF. |
| int SubIndex = -1; |
| for (int i = 0, e = Mask.size(); i != e; ++i) { |
| int M = Mask[i]; |
| if (M < 0) |
| continue; |
| int Offset = (M % NumSrcElts) - i; |
| if (0 <= SubIndex && SubIndex != Offset) |
| return false; |
| SubIndex = Offset; |
| } |
| |
| if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) { |
| Index = SubIndex; |
| return true; |
| } |
| return false; |
| } |
| |
| bool ShuffleVectorInst::isInsertSubvectorMask(ArrayRef<int> Mask, |
| int NumSrcElts, int &NumSubElts, |
| int &Index) { |
| int NumMaskElts = Mask.size(); |
| |
| // Don't try to match if we're shuffling to a smaller size. |
| if (NumMaskElts < NumSrcElts) |
| return false; |
| |
| // TODO: We don't recognize self-insertion/widening. |
| if (isSingleSourceMaskImpl(Mask, NumSrcElts)) |
| return false; |
| |
| // Determine which mask elements are attributed to which source. |
| APInt UndefElts = APInt::getZero(NumMaskElts); |
| APInt Src0Elts = APInt::getZero(NumMaskElts); |
| APInt Src1Elts = APInt::getZero(NumMaskElts); |
| bool Src0Identity = true; |
| bool Src1Identity = true; |
| |
| for (int i = 0; i != NumMaskElts; ++i) { |
| int M = Mask[i]; |
| if (M < 0) { |
| UndefElts.setBit(i); |
| continue; |
| } |
| if (M < NumSrcElts) { |
| Src0Elts.setBit(i); |
| Src0Identity &= (M == i); |
| continue; |
| } |
| Src1Elts.setBit(i); |
| Src1Identity &= (M == (i + NumSrcElts)); |
| continue; |
| } |
| assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() && |
| "unknown shuffle elements"); |
| assert(!Src0Elts.isZero() && !Src1Elts.isZero() && |
| "2-source shuffle not found"); |
| |
| // Determine lo/hi span ranges. |
| // TODO: How should we handle undefs at the start of subvector insertions? |
| int Src0Lo = Src0Elts.countTrailingZeros(); |
| int Src1Lo = Src1Elts.countTrailingZeros(); |
| int Src0Hi = NumMaskElts - Src0Elts.countLeadingZeros(); |
| int Src1Hi = NumMaskElts - Src1Elts.countLeadingZeros(); |
| |
| // If src0 is in place, see if the src1 elements is inplace within its own |
| // span. |
| if (Src0Identity) { |
| int NumSub1Elts = Src1Hi - Src1Lo; |
| ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts); |
| if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) { |
| NumSubElts = NumSub1Elts; |
| Index = Src1Lo; |
| return true; |
| } |
| } |
| |
| // If src1 is in place, see if the src0 elements is inplace within its own |
| // span. |
| if (Src1Identity) { |
| int NumSub0Elts = Src0Hi - Src0Lo; |
| ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts); |
| if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) { |
| NumSubElts = NumSub0Elts; |
| Index = Src0Lo; |
| return true; |
| } |
| } |
| |
| return false; |
| } |
| |
| bool ShuffleVectorInst::isIdentityWithPadding() const { |
| if (isa<UndefValue>(Op<2>())) |
| return false; |
| |
| // FIXME: Not currently possible to express a shuffle mask for a scalable |
| // vector for this case. |
| if (isa<ScalableVectorType>(getType())) |
| return false; |
| |
| int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
| int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements(); |
| if (NumMaskElts <= NumOpElts) |
| return false; |
| |
| // The first part of the mask must choose elements from exactly 1 source op. |
| ArrayRef<int> Mask = getShuffleMask(); |
| if (!isIdentityMaskImpl(Mask, NumOpElts)) |
| return false; |
| |
| // All extending must be with undef elements. |
| for (int i = NumOpElts; i < NumMaskElts; ++i) |
| if (Mask[i] != -1) |
| return false; |
| |
| return true; |
| } |
| |
| bool ShuffleVectorInst::isIdentityWithExtract() const { |
| if (isa<UndefValue>(Op<2>())) |
| return false; |
| |
| // FIXME: Not currently possible to express a shuffle mask for a scalable |
| // vector for this case. |
| if (isa<ScalableVectorType>(getType())) |
| return false; |
| |
| int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
| int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements(); |
| if (NumMaskElts >= NumOpElts) |
| return false; |
| |
| return isIdentityMaskImpl(getShuffleMask(), NumOpElts); |
| } |
| |
| bool ShuffleVectorInst::isConcat() const { |
| // Vector concatenation is differentiated from identity with padding. |
| if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()) || |
| isa<UndefValue>(Op<2>())) |
| return false; |
| |
| // FIXME: Not currently possible to express a shuffle mask for a scalable |
| // vector for this case. |
| if (isa<ScalableVectorType>(getType())) |
| return false; |
| |
| int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
| int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements(); |
| if (NumMaskElts != NumOpElts * 2) |
| return false; |
| |
| // Use the mask length rather than the operands' vector lengths here. We |
| // already know that the shuffle returns a vector twice as long as the inputs, |
| // and neither of the inputs are undef vectors. If the mask picks consecutive |
| // elements from both inputs, then this is a concatenation of the inputs. |
| return isIdentityMaskImpl(getShuffleMask(), NumMaskElts); |
| } |
| |
| static bool isReplicationMaskWithParams(ArrayRef<int> Mask, |
| int ReplicationFactor, int VF) { |
| assert(Mask.size() == (unsigned)ReplicationFactor * VF && |
| "Unexpected mask size."); |
| |
| for (int CurrElt : seq(0, VF)) { |
| ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor); |
| assert(CurrSubMask.size() == (unsigned)ReplicationFactor && |
| "Run out of mask?"); |
| Mask = Mask.drop_front(ReplicationFactor); |
| if (!all_of(CurrSubMask, [CurrElt](int MaskElt) { |
| return MaskElt == UndefMaskElem || MaskElt == CurrElt; |
| })) |
| return false; |
| } |
| assert(Mask.empty() && "Did not consume the whole mask?"); |
| |
| return true; |
| } |
| |
| bool ShuffleVectorInst::isReplicationMask(ArrayRef<int> Mask, |
| int &ReplicationFactor, int &VF) { |
| // undef-less case is trivial. |
| if (none_of(Mask, [](int MaskElt) { return MaskElt == UndefMaskElem; })) { |
| ReplicationFactor = |
| Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size(); |
| if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0) |
| return false; |
| VF = Mask.size() / ReplicationFactor; |
| return isReplicationMaskWithParams(Mask, ReplicationFactor, VF); |
| } |
| |
| // However, if the mask contains undef's, we have to enumerate possible tuples |
| // and pick one. There are bounds on replication factor: [1, mask size] |
| // (where RF=1 is an identity shuffle, RF=mask size is a broadcast shuffle) |
| // Additionally, mask size is a replication factor multiplied by vector size, |
| // which further significantly reduces the search space. |
| |
| // Before doing that, let's perform basic correctness checking first. |
| int Largest = -1; |
| for (int MaskElt : Mask) { |
| if (MaskElt == UndefMaskElem) |
| continue; |
| // Elements must be in non-decreasing order. |
| if (MaskElt < Largest) |
| return false; |
| Largest = std::max(Largest, MaskElt); |
| } |
| |
| // Prefer larger replication factor if all else equal. |
| for (int PossibleReplicationFactor : |
| reverse(seq_inclusive<unsigned>(1, Mask.size()))) { |
| if (Mask.size() % PossibleReplicationFactor != 0) |
| continue; |
| int PossibleVF = Mask.size() / PossibleReplicationFactor; |
| if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor, |
| PossibleVF)) |
| continue; |
| ReplicationFactor = PossibleReplicationFactor; |
| VF = PossibleVF; |
| return true; |
| } |
| |
| return false; |
| } |
| |
| bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor, |
| int &VF) const { |
| // Not possible to express a shuffle mask for a scalable vector for this |
| // case. |
| if (isa<ScalableVectorType>(getType())) |
| return false; |
| |
| VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
|