29#include "llvm/IR/IntrinsicsARM.h"
41#define DEBUG_TYPE "arm-parallel-dsp"
43STATISTIC(NumSMLAD ,
"Number of smlad instructions generated");
59 bool Exchange =
false;
66 bool HasTwoLoadInputs()
const {
70 LoadInst *getBaseLoad()
const {
82 SetVector<Instruction*> Adds;
90 void InsertAdd(Instruction *
I) { Adds.insert(
I); }
95 auto GetMulOperand = [](
Value *
V) -> Instruction* {
98 if (
I->getOpcode() == Instruction::Mul)
101 if (
I->getOpcode() == Instruction::Mul)
110 Muls.push_back(std::make_unique<MulCandidate>(
I,
LHS,
RHS));
113 for (
auto *
Add : Adds) {
116 if (
auto *
Mul = GetMulOperand(
Add->getOperand(0)))
118 if (
auto *
Mul = GetMulOperand(
Add->getOperand(1)))
126 bool InsertAcc(
Value *
V) {
135 void AddMulPair(MulCandidate *Mul0, MulCandidate *Mul1,
136 bool Exchange =
false) {
138 << *Mul0->Root <<
"\n"
139 << *Mul1->Root <<
"\n");
143 Mul1->Exchange =
true;
144 MulPairs.push_back(std::make_pair(Mul0, Mul1));
150 bool is64Bit()
const {
return Root->getType()->isIntegerTy(64); }
155 Value *getAccumulator() {
return Acc; }
158 SetVector<Instruction*> &getAdds() {
return Adds; }
162 MulCandList &getMuls() {
return Muls; }
166 MulPairList &getMulPairs() {
return MulPairs; }
169 void UpdateRoot(Instruction *SMLAD) {
170 Root->replaceAllUsesWith(SMLAD);
175 for (
auto *
Add : Adds)
177 for (
auto &
Mul : Muls)
179 <<
" " << *
Mul->LHS <<
"\n"
180 <<
" " << *
Mul->RHS <<
"\n");
187 LoadInst *NewLd =
nullptr;
191 WidenedLoad(SmallVectorImpl<LoadInst*> &Lds, LoadInst *Wide)
195 LoadInst *getLoad() {
203 TargetLibraryInfo *TLI;
205 const DataLayout *DL;
207 const ARMOptions *CLOpts;
208 std::map<LoadInst*, LoadInst*> LoadPairs;
209 SmallPtrSet<LoadInst*, 4> OffsetLoads;
210 std::map<LoadInst*, std::unique_ptr<WidenedLoad>> WideLoads;
213 bool IsNarrowSequence(
Value *
V);
215 bool RecordMemoryOps(BasicBlock *BB);
217 bool AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1, MemInstList &VecMem);
218 LoadInst* CreateWideLoad(MemInstList &Loads, IntegerType *LoadTy);
231 ARMParallelDSP() : FunctionPass(ID) { }
233 void getAnalysisUsage(AnalysisUsage &AU)
const override {
234 FunctionPass::getAnalysisUsage(AU);
249 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
250 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
251 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
F);
252 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
253 auto &TPC = getAnalysis<TargetPassConfig>();
256 DL = &M->getDataLayout();
258 auto &TM = TPC.getTM<TargetMachine>();
259 auto *
ST = &TM.getSubtarget<ARMSubtarget>(
F);
260 CLOpts = &
ST->getCLOpts();
261 if (CLOpts->disable_arm_parallel_dsp)
264 if (!
ST->allowsUnalignedMem()) {
265 LLVM_DEBUG(
dbgs() <<
"Unaligned memory access not supported: not "
266 "running pass ARMParallelDSP\n");
271 LLVM_DEBUG(
dbgs() <<
"DSP extension not enabled: not running pass "
276 if (!
ST->isLittle()) {
277 LLVM_DEBUG(
dbgs() <<
"Only supporting little endian: not running pass "
278 <<
"ARMParallelDSP\n");
285 bool Changes = MatchSMLAD(
F);
292 MemInstList &VecMem) {
296 auto It = LoadPairs.find(Ld0);
297 if (It == LoadPairs.end() || It->second != Ld1)
306 VecMem.push_back(Ld0);
307 VecMem.push_back(Ld1);
316template<
unsigned MaxBitW
idth>
317bool ARMParallelDSP::IsNarrowSequence(
Value *
V) {
319 if (SExt->getSrcTy()->getIntegerBitWidth() != MaxBitWidth)
324 return LoadPairs.count(Ld) || OffsetLoads.
count(Ld);
332bool ARMParallelDSP::RecordMemoryOps(BasicBlock *BB) {
334 SmallVector<Instruction*, 8> Writes;
341 for (
auto &
I : *BB) {
342 if (
I.mayWriteToMemory())
345 if (!Ld || !Ld->isSimple() ||
351 if (Loads.
empty() || Loads.
size() > CLOpts->parallel_dsp_load_limit)
354 using InstSet = std::set<Instruction*>;
355 using DepMap = std::map<Instruction*, InstSet>;
360 for (
auto *
Write : Writes) {
361 for (
auto *
Read : Loads) {
362 MemoryLocation ReadLoc =
363 MemoryLocation(
Read->getPointerOperand(),
Size);
374 auto SafeToPair = [&](LoadInst *
Base, LoadInst *
Offset) {
376 LoadInst *Dominator = BaseFirst ?
Base :
Offset;
377 LoadInst *Dominated = BaseFirst ?
Offset :
Base;
379 if (
auto It = RAWDeps.find(Dominated); It != RAWDeps.end()) {
380 InstSet &WritesBefore = It->second;
382 for (
auto *Before : WritesBefore) {
393 for (
auto *
Base : Loads) {
394 for (
auto *
Offset : Loads) {
408 dbgs() <<
"Consecutive load pairs:\n";
409 for (auto &MapIt : LoadPairs) {
410 LLVM_DEBUG(dbgs() << *MapIt.first <<
", "
411 << *MapIt.second <<
"\n");
414 return LoadPairs.size() > 1;
427 return R.InsertAcc(
V);
429 if (
I->getParent() != BB)
432 switch (
I->getOpcode()) {
435 case Instruction::PHI:
437 return R.InsertAcc(
V);
438 case Instruction::Add: {
445 bool ValidLHS = Search(
LHS, BB, R);
446 bool ValidRHS = Search(
RHS, BB, R);
448 if (ValidLHS && ValidRHS)
452 if (
R.getRoot() ==
I)
455 return R.InsertAcc(
I);
457 case Instruction::Mul: {
458 Value *MulOp0 =
I->getOperand(0);
459 Value *MulOp1 =
I->getOperand(1);
460 return IsNarrowSequence<16>(MulOp0) && IsNarrowSequence<16>(MulOp1);
462 case Instruction::SExt:
463 return Search(
I->getOperand(0), BB, R);
499bool ARMParallelDSP::MatchSMLAD(
Function &
F) {
503 SmallPtrSet<Instruction*, 4> AllAdds;
504 if (!RecordMemoryOps(&BB))
507 for (Instruction &
I :
reverse(BB)) {
508 if (
I.getOpcode() != Instruction::Add)
514 const auto *Ty =
I.getType();
515 if (!Ty->isIntegerTy(32) && !Ty->isIntegerTy(64))
519 if (!Search(&
I, &BB, R))
525 if (!CreateParallelPairs(R))
528 InsertParallelMACs(R);
531 LLVM_DEBUG(
dbgs() <<
"BB after inserting parallel MACs:\n" << BB);
538bool ARMParallelDSP::CreateParallelPairs(
Reduction &R) {
541 if (
R.getMuls().size() < 2)
545 for (
auto &MulCand :
R.getMuls()) {
546 if (!MulCand->HasTwoLoadInputs())
550 auto CanPair = [&](
Reduction &
R, MulCandidate *PMul0, MulCandidate *PMul1) {
555 auto Ld0 =
static_cast<LoadInst*
>(PMul0->LHS);
556 auto Ld1 =
static_cast<LoadInst*
>(PMul1->LHS);
557 auto Ld2 =
static_cast<LoadInst*
>(PMul0->RHS);
558 auto Ld3 =
static_cast<LoadInst*
>(PMul1->RHS);
561 if (Ld0 == Ld2 || Ld1 == Ld3)
564 if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd)) {
565 if (AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
567 R.AddMulPair(PMul0, PMul1);
569 }
else if (AreSequentialLoads(Ld3, Ld2, PMul1->VecLd)) {
572 R.AddMulPair(PMul0, PMul1,
true);
575 }
else if (AreSequentialLoads(Ld1, Ld0, PMul0->VecLd) &&
576 AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
581 R.AddMulPair(PMul1, PMul0,
true);
587 MulCandList &Muls =
R.getMuls();
588 const unsigned Elems = Muls.size();
589 for (
unsigned i = 0; i < Elems; ++i) {
590 MulCandidate *PMul0 =
static_cast<MulCandidate*
>(Muls[i].get());
594 for (
unsigned j = 0;
j < Elems; ++
j) {
598 MulCandidate *PMul1 =
static_cast<MulCandidate*
>(Muls[
j].get());
607 assert(PMul0 != PMul1 &&
"expected different chains");
609 if (CanPair(R, PMul0, PMul1))
613 return !
R.getMulPairs().empty();
616void ARMParallelDSP::InsertParallelMACs(
Reduction &R) {
618 auto CreateSMLAD = [&](LoadInst* WideLd0, LoadInst *WideLd1,
623 Value*
Args[] = { WideLd0, WideLd1, Acc };
631 SMLAD = Acc->
getType()->isIntegerTy(32)
644 "expected at least one instruction");
657 Value *Acc =
R.getAccumulator();
662 MulCandList &MulCands =
R.getMuls();
663 for (
auto &MulCand : MulCands) {
671 assert(
R.is64Bit() &&
"expected 64-bit result");
684 Builder.SetInsertPoint(GetInsertPoint(
Mul, Acc));
685 Acc = Builder.CreateAdd(
Mul, Acc);
692 }
else if (Acc->
getType() !=
R.getType()) {
693 Builder.SetInsertPoint(
R.getRoot());
694 Acc = Builder.CreateSExt(Acc,
R.getType());
698 llvm::sort(
R.getMulPairs(), [](
auto &PairA,
auto &PairB) {
699 const Instruction *A = PairA.first->Root;
700 const Instruction *B = PairB.first->Root;
701 return A->comesBefore(B);
705 for (
auto &Pair :
R.getMulPairs()) {
706 MulCandidate *LHSMul = Pair.first;
707 MulCandidate *RHSMul = Pair.second;
708 LoadInst *BaseLHS = LHSMul->getBaseLoad();
709 LoadInst *BaseRHS = RHSMul->getBaseLoad();
710 auto LIt = WideLoads.find(BaseLHS);
711 LoadInst *WideLHS = LIt != WideLoads.end()
712 ? LIt->second->getLoad()
713 : CreateWideLoad(LHSMul->VecLd, Ty);
714 auto RIt = WideLoads.find(BaseRHS);
715 LoadInst *WideRHS = RIt != WideLoads.end()
716 ? RIt->second->getLoad()
717 : CreateWideLoad(RHSMul->VecLd, Ty);
719 Instruction *InsertAfter = GetInsertPoint(WideLHS, WideRHS);
720 InsertAfter = GetInsertPoint(InsertAfter, Acc);
721 Acc = CreateSMLAD(WideLHS, WideRHS, Acc, RHSMul->Exchange, InsertAfter);
726LoadInst* ARMParallelDSP::CreateWideLoad(MemInstList &Loads,
727 IntegerType *LoadTy) {
728 assert(Loads.size() == 2 &&
"currently only support widening two loads");
730 LoadInst *
Base = Loads[0];
731 LoadInst *
Offset = Loads[1];
736 assert((BaseSExt && OffsetSExt)
737 &&
"Loads should have a single, extending, user");
739 std::function<void(
Value*,
Value*)> MoveBefore =
748 Source->getParent() != Sink->getParent() ||
752 Source->moveBefore(Sink->getIterator());
754 MoveBefore(
Op, Source);
764 Value *VecPtr =
Base->getPointerOperand();
765 LoadInst *WideLoad = IRB.CreateAlignedLoad(LoadTy, VecPtr,
Base->getAlign());
768 MoveBefore(
Base->getPointerOperand(), VecPtr);
769 MoveBefore(VecPtr, WideLoad);
774 Value *Bottom = IRB.CreateTrunc(WideLoad,
Base->getType());
775 Value *NewBaseSExt = IRB.CreateSExt(Bottom, BaseSExt->
getType());
780 Value *Top = IRB.CreateLShr(WideLoad, ShiftVal);
781 Value *
Trunc = IRB.CreateTrunc(Top, OffsetTy);
787 <<
"Created Wide Load:\n"
790 << *NewBaseSExt <<
"\n"
793 << *NewOffsetSExt <<
"\n");
794 WideLoads.emplace(std::make_pair(
Base,
795 std::make_unique<WidenedLoad>(Loads, WideLoad)));
800 return new ARMParallelDSP();
803char ARMParallelDSP::ID = 0;
806 "Transform functions to use DSP intrinsics",
false,
false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static DeltaTreeNode * getRoot(void *Root)
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
Module.h This file contains the declarations for the Module class.
loop Loop Strength Reduction
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
Target-Independent Code Generator Pass Configuration Options pass.
static bool is64Bit(const char *name)
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
PointerType * getType() const
Global values are always pointers.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
An instruction for reading from memory.
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
Pass interface - Implemented by all 'passes'.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto reverse(ContainerTy &&C)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
bool isModOrRefSet(const ModRefInfo MRI)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
@ Mul
Product of integers.
LLVM_ABI 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.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Pass * createARMParallelDSPPass()
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.