26 #include "llvm/IR/IntrinsicsARM.h" 39 #define DEBUG_TYPE "arm-parallel-dsp" 41 STATISTIC(NumSMLAD ,
"Number of smlad instructions generated");
45 cl::desc(
"Disable the ARM Parallel DSP pass"));
49 cl::desc(
"Limit the number of loads analysed"));
65 bool Exchange =
false;
71 Root(I), LHS(lhs), RHS(rhs) { }
73 bool HasTwoLoadInputs()
const {
74 return isa<LoadInst>(LHS) && isa<LoadInst>(RHS);
103 if (
auto *SExt = dyn_cast<SExtInst>(V)) {
104 if (
auto *I = dyn_cast<Instruction>(SExt->getOperand(0)))
107 }
else if (
auto *I = dyn_cast<Instruction>(V)) {
117 Muls.push_back(std::make_unique<MulCandidate>(I, LHS, RHS));
120 for (
auto *
Add : Adds) {
123 if (
auto *Mul = GetMulOperand(
Add->getOperand(0)))
125 if (
auto *Mul = GetMulOperand(
Add->getOperand(1)))
133 bool InsertAcc(
Value *V) {
142 void AddMulPair(MulCandidate *Mul0, MulCandidate *Mul1,
143 bool Exchange =
false) {
145 << *Mul0->Root <<
"\n" 146 << *Mul1->Root <<
"\n");
150 Mul1->Exchange =
true;
151 MulPairs.push_back(std::make_pair(Mul0, Mul1));
156 bool CreateParallelPairs();
166 Value *getAccumulator() {
return Acc; }
173 MulCandList &getMuls() {
return Muls; }
177 MulPairList &getMulPairs() {
return MulPairs; }
186 for (
auto *
Add : Adds)
188 for (
auto &Mul : Muls)
190 <<
" " << *Mul->LHS <<
"\n" 191 <<
" " << *Mul->RHS <<
"\n");
219 std::map<LoadInst*, LoadInst*> LoadPairs;
221 std::map<LoadInst*, std::unique_ptr<WidenedLoad>> WideLoads;
224 bool IsNarrowSequence(
Value *V);
263 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
264 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
265 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
266 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
267 auto &TPC = getAnalysis<TargetPassConfig>();
270 DL = &M->getDataLayout();
275 if (!ST->allowsUnalignedMem()) {
276 LLVM_DEBUG(
dbgs() <<
"Unaligned memory access not supported: not " 277 "running pass ARMParallelDSP\n");
282 LLVM_DEBUG(
dbgs() <<
"DSP extension not enabled: not running pass " 287 if (!ST->isLittle()) {
288 LLVM_DEBUG(
dbgs() <<
"Only supporting little endian: not running pass " 289 <<
"ARMParallelDSP\n");
296 bool Changes = MatchSMLAD(F);
302 template<
typename MemInst>
311 MemInstList &VecMem) {
315 if (!LoadPairs.count(Ld0) || LoadPairs[Ld0] != Ld1)
324 VecMem.push_back(Ld0);
325 VecMem.push_back(Ld1);
334 template<
unsigned MaxBitW
idth>
335 bool ARMParallelDSP::IsNarrowSequence(
Value *V) {
336 if (
auto *SExt = dyn_cast<SExtInst>(V)) {
337 if (SExt->getSrcTy()->getIntegerBitWidth() != MaxBitWidth)
340 if (
auto *Ld = dyn_cast<LoadInst>(SExt->getOperand(0))) {
342 return LoadPairs.count(Ld) || OffsetLoads.
count(Ld);
350 bool ARMParallelDSP::RecordMemoryOps(
BasicBlock *BB) {
360 for (
auto &I : *BB) {
364 if (!Ld || !Ld->isSimple() ||
365 !Ld->hasOneUse() || !isa<SExtInst>(Ld->user_back()))
373 using InstSet = std::set<Instruction*>;
374 using DepMap = std::map<Instruction*, InstSet>;
379 for (
auto Write : Writes) {
380 for (
auto Read : Loads) {
388 RAWDeps[Read].insert(Write);
398 if (RAWDeps.count(Dominated)) {
399 InstSet &WritesBefore = RAWDeps[Dominated];
401 for (
auto Before : WritesBefore) {
404 if (OrderedBB.
dominates(Dominator, Before))
412 for (
auto *Base : Loads) {
413 for (
auto *
Offset : Loads) {
417 if (AreSequentialAccesses<LoadInst>(Base,
Offset, *DL, *SE) &&
418 SafeToPair(Base,
Offset)) {
427 dbgs() <<
"Consecutive load pairs:\n";
428 for (
auto &MapIt : LoadPairs) {
430 << *MapIt.second <<
"\n");
433 return LoadPairs.size() > 1;
446 return R.InsertAcc(V);
454 case Instruction::PHI:
456 return R.InsertAcc(V);
464 bool ValidLHS = Search(LHS, BB, R);
465 bool ValidRHS = Search(RHS, BB, R);
467 if (ValidLHS && ValidRHS)
470 return R.InsertAcc(I);
472 case Instruction::Mul: {
475 return IsNarrowSequence<16>(MulOp0) && IsNarrowSequence<16>(MulOp1);
477 case Instruction::SExt:
514 bool ARMParallelDSP::MatchSMLAD(
Function &F) {
515 bool Changed =
false;
519 if (!RecordMemoryOps(&BB))
526 if (AllAdds.
count(&I))
530 if (!Ty->isIntegerTy(32) && !Ty->isIntegerTy(64))
534 if (!Search(&I, &BB, R))
540 if (!CreateParallelPairs(R))
543 InsertParallelMACs(R);
545 AllAdds.
insert(R.getAdds().begin(), R.getAdds().end());
552 bool ARMParallelDSP::CreateParallelPairs(
Reduction &R) {
555 if (R.getMuls().size() < 2)
559 for (
auto &MulCand : R.getMuls()) {
560 if (!MulCand->HasTwoLoadInputs())
564 auto CanPair = [&](
Reduction &R, MulCandidate *PMul0, MulCandidate *PMul1) {
569 auto Ld0 =
static_cast<LoadInst*
>(PMul0->LHS);
570 auto Ld1 =
static_cast<LoadInst*
>(PMul1->LHS);
571 auto Ld2 =
static_cast<LoadInst*
>(PMul0->RHS);
572 auto Ld3 =
static_cast<LoadInst*
>(PMul1->RHS);
574 if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd)) {
575 if (AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
577 R.AddMulPair(PMul0, PMul1);
579 }
else if (AreSequentialLoads(Ld3, Ld2, PMul1->VecLd)) {
582 R.AddMulPair(PMul0, PMul1,
true);
585 }
else if (AreSequentialLoads(Ld1, Ld0, PMul0->VecLd) &&
586 AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
591 R.AddMulPair(PMul1, PMul0,
true);
597 MulCandList &Muls = R.getMuls();
598 const unsigned Elems = Muls.size();
599 for (
unsigned i = 0; i < Elems; ++i) {
600 MulCandidate *PMul0 =
static_cast<MulCandidate*
>(Muls[i].get());
604 for (
unsigned j = 0; j < Elems; ++j) {
608 MulCandidate *PMul1 =
static_cast<MulCandidate*
>(Muls[j].get());
617 assert(PMul0 != PMul1 &&
"expected different chains");
619 if (CanPair(R, PMul0, PMul1))
623 return !R.getMulPairs().empty();
626 void ARMParallelDSP::InsertParallelMACs(
Reduction &R) {
629 Value *Acc,
bool Exchange,
633 Value*
Args[] = { WideLd0, WideLd1, Acc };
646 Instruction *Call = Builder.CreateCall(SMLAD, Args);
653 assert((isa<Instruction>(A) || isa<Instruction>(
B)) &&
654 "expected at least one instruction");
657 if (!isa<Instruction>(A))
659 else if (!isa<Instruction>(
B))
662 V = DT->
dominates(cast<Instruction>(A), cast<Instruction>(
B)) ?
B : A;
667 Value *Acc = R.getAccumulator();
672 MulCandList &MulCands = R.getMuls();
673 for (
auto &MulCand : MulCands) {
677 Instruction *Mul = cast<Instruction>(MulCand->Root);
678 LLVM_DEBUG(
dbgs() <<
"Accumulating unpaired mul: " << *Mul <<
"\n");
680 if (R.getType() != Mul->
getType()) {
681 assert(R.is64Bit() &&
"expected 64-bit result");
683 Mul = cast<Instruction>(Builder.CreateSExt(Mul, R.getRoot()->getType()));
694 Builder.SetInsertPoint(GetInsertPoint(Mul, Acc));
695 Acc = Builder.CreateAdd(Mul, Acc);
702 }
else if (Acc->
getType() != R.getType()) {
703 Builder.SetInsertPoint(R.getRoot());
704 Acc = Builder.CreateSExt(Acc, R.getType());
709 llvm::sort(R.getMulPairs(), [&OrderedBB](
auto &PairA,
auto &PairB) {
712 return OrderedBB.dominates(A, B);
716 for (
auto &Pair : R.getMulPairs()) {
717 MulCandidate *LHSMul = Pair.first;
718 MulCandidate *RHSMul = Pair.second;
719 LoadInst *BaseLHS = LHSMul->getBaseLoad();
720 LoadInst *BaseRHS = RHSMul->getBaseLoad();
721 LoadInst *WideLHS = WideLoads.count(BaseLHS) ?
722 WideLoads[BaseLHS]->getLoad() : CreateWideLoad(LHSMul->VecLd, Ty);
723 LoadInst *WideRHS = WideLoads.count(BaseRHS) ?
724 WideLoads[BaseRHS]->getLoad() : CreateWideLoad(RHSMul->VecLd, Ty);
726 Instruction *InsertAfter = GetInsertPoint(WideLHS, WideRHS);
727 InsertAfter = GetInsertPoint(InsertAfter, Acc);
728 Acc = CreateSMLAD(WideLHS, WideRHS, Acc, RHSMul->Exchange, InsertAfter);
730 R.UpdateRoot(cast<Instruction>(Acc));
733 LoadInst* ARMParallelDSP::CreateWideLoad(MemInstList &Loads,
735 assert(Loads.size() == 2 &&
"currently only support widening two loads");
743 assert((BaseSExt && OffsetSExt)
744 &&
"Loads should have a single, extending, user");
746 std::function<void(Value*, Value*)> MoveBefore =
748 if (!isa<Instruction>(A) || !isa<Instruction>(
B))
751 auto *
Source = cast<Instruction>(A);
752 auto *
Sink = cast<Instruction>(
B);
755 Source->getParent() != Sink->getParent() ||
756 isa<PHINode>(
Source) || isa<PHINode>(Sink))
773 Value *VecPtr = IRB.CreateBitCast(Base->getPointerOperand(),
775 LoadInst *WideLoad = IRB.CreateAlignedLoad(LoadTy, VecPtr,
776 Base->getAlignment());
779 MoveBefore(Base->getPointerOperand(), VecPtr);
780 MoveBefore(VecPtr, WideLoad);
785 Value *Bottom = IRB.CreateTrunc(WideLoad, Base->
getType());
786 Value *NewBaseSExt = IRB.CreateSExt(Bottom, BaseSExt->
getType());
791 Value *Top = IRB.CreateLShr(WideLoad, ShiftVal);
792 Value *Trunc = IRB.CreateTrunc(Top, OffsetTy);
793 Value *NewOffsetSExt = IRB.CreateSExt(Trunc, OffsetSExt->
getType());
797 << *Base <<
"\n" << *Offset <<
"\n" 798 <<
"Created Wide Load:\n" 801 << *NewBaseSExt <<
"\n" 804 << *NewOffsetSExt <<
"\n");
805 WideLoads.emplace(std::make_pair(Base,
806 std::make_unique<WidenedLoad>(Loads, WideLoad)));
811 return new ARMParallelDSP();
817 "Transform functions to use DSP intrinsics",
false,
false)
Legacy wrapper pass to provide the GlobalsAAResult object.
The access may reference and may modify the value stored in memory.
Pass interface - Implemented by all 'passes'.
A parsed version of the target data layout string in and methods for querying it. ...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp", "Transform functions to use DSP intrinsics", false, false) INITIALIZE_PASS_END(ARMParallelDSP
This class represents lattice values for constants.
static cl::opt< bool > DisableParallelDSP("disable-arm-parallel-dsp", cl::Hidden, cl::init(false), cl::desc("Disable the ARM Parallel DSP pass"))
A Module instance is used to store all the information related to an LLVM module. ...
static constexpr LocationSize unknown()
void push_back(const T &Elt)
The main scalar evolution driver.
static bool AreSequentialAccesses(MemInst *MemOp0, MemInst *MemOp1, const DataLayout &DL, ScalarEvolution &SE)
bool dominates(const Instruction *A, const Instruction *B)
Find out whether A dominates B, meaning whether A comes before B in BB.
An immutable pass that tracks lazily created AssumptionCache objects.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
static cl::opt< unsigned > NumLoadLimit("arm-parallel-dsp-load-limit", cl::Hidden, cl::init(16), cl::desc("Limit the number of loads analysed"))
STATISTIC(NumFunctions, "Total number of functions")
This class represents a sign extension of integer types.
An instruction for reading from memory.
void dump() const
Support for debugging, callable in GDB: V->dump()
AnalysisUsage & addRequired()
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Target-Independent Code Generator Pass Configuration Options.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Pass * createARMParallelDSPPass()
Move duplicate certain instructions close to their use
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
arm parallel Transform functions to use DSP intrinsics
Represent the analysis usage information of a pass.
amdgpu propagate attributes Late propagate attributes from kernels to functions
FunctionPass class - This class is used to implement most global optimizations.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Class to represent integer types.
static wasm::ValType getType(const TargetRegisterClass *RC)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void sort(IteratorTy Start, IteratorTy End)
Representation for a specific memory location.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
InstListType::iterator iterator
Instruction iterators...
loop Loop Strength Reduction
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
LLVM_NODISCARD ModRefInfo intersectModRef(const ModRefInfo MRI1, const ModRefInfo MRI2)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
A vector that has set insertion semantics.
Primary interface to the complete machine description for the target machine.
Legacy analysis pass which computes a DominatorTree.
LLVM_NODISCARD bool isModOrRefSet(const ModRefInfo MRI)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
static bool is64Bit(const char *name)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PointerType * getType() const
Global values are always pointers.
const BasicBlock * getParent() const