41 #define DEBUG_TYPE "arm-parallel-dsp" 43 STATISTIC(NumSMLAD ,
"Number of smlad instructions generated");
54 using PMACPair = std::pair<BinOpChain*,BinOpChain*>;
66 OpChain(
Instruction *
I, ValueList &vl) : Root(I), AllValues(vl) { }
67 virtual ~OpChain() =
default;
69 void SetMemoryLocations() {
71 for (
auto *V : AllValues) {
72 if (
auto *
I = dyn_cast<Instruction>(V)) {
73 if (
I->mayWriteToMemory())
75 if (
auto *Ld = dyn_cast<LoadInst>(V))
81 unsigned size()
const {
return AllValues.size(); }
88 struct BinOpChain :
public OpChain {
92 BinOpChain(
Instruction *
I, ValueList &lhs, ValueList &rhs) :
93 OpChain(I, lhs), LHS(lhs), RHS(rhs) {
95 AllValues.push_back(V);
105 OpChainList MACCandidates;
110 class ARMParallelDSP :
public LoopPass {
122 PMACPairList CreateParallelMACPairs(OpChainList &Candidates);
153 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
154 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
155 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
156 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
157 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
158 auto &TPC = getAnalysis<TargetPassConfig>();
168 LLVM_DEBUG(
dbgs() <<
"The loop header is not the loop latch: not " 169 "running pass ARMParallelDSP\n");
180 if (!ST->allowsUnalignedMem()) {
181 LLVM_DEBUG(
dbgs() <<
"Unaligned memory access not supported: not " 182 "running pass ARMParallelDSP\n");
187 LLVM_DEBUG(
dbgs() <<
"DSP extension not enabled: not running pass " 193 bool Changes =
false;
196 Changes = MatchSMLAD(F);
207 template<
unsigned MaxBitW
idth>
221 Value *Val, *LHS, *RHS;
223 if (cast<TruncInst>(I)->getDestTy()->getIntegerBitWidth() == MaxBitWidth)
224 return IsNarrowSequence<MaxBitWidth>(Val, VL);
231 if (cast<CastInst>(I)->getSrcTy()->getIntegerBitWidth() != MaxBitWidth) {
233 cast<CastInst>(I)->getSrcTy()->getIntegerBitWidth() <<
"\n");
251 const ValueList &VL1) {
252 if (VL0.size() != VL1.size()) {
253 LLVM_DEBUG(
dbgs() <<
"Muls are mismatching operand list lengths: " 254 << VL0.size() <<
" != " << VL1.size() <<
"\n");
258 const unsigned Pairs = VL0.size();
259 LLVM_DEBUG(
dbgs() <<
"Number of operand pairs: " << Pairs <<
"\n");
261 for (
unsigned i = 0; i < Pairs; ++i) {
262 const Value *V0 = VL0[i];
263 const Value *V1 = VL1[i];
271 if (!Inst0 || !Inst1)
274 if (Inst0->isSameOperationAs(Inst1)) {
279 const APInt *C0, *C1;
288 template<
typename MemInst>
292 if (!MemOp0->isSimple() || !MemOp1->isSimple()) {
297 VecMem.push_back(MemOp0);
298 VecMem.push_back(MemOp1);
307 MemInstList &VecMem) {
321 return AreSequentialAccesses<LoadInst>(Ld0, Ld1, VecMem, *DL, *SE);
325 ARMParallelDSP::CreateParallelMACPairs(OpChainList &Candidates) {
326 const unsigned Elems = Candidates.size();
327 PMACPairList PMACPairs;
335 for(
unsigned i=0; i<Elems-1; i+=2) {
336 BinOpChain *PMul0 =
static_cast<BinOpChain*
>(Candidates[i].get());
337 BinOpChain *PMul1 =
static_cast<BinOpChain*
>(Candidates[i+1].get());
348 const ValueList &Mul0_LHS = PMul0->LHS;
349 const ValueList &Mul0_RHS = PMul0->RHS;
350 const ValueList &Mul1_LHS = PMul1->LHS;
351 const ValueList &Mul1_RHS = PMul1->RHS;
362 for (
unsigned x = 0; x < Mul0_LHS.size(); x += 2) {
369 dbgs() <<
"\t mul1: "; Mul0_LHS[x]->dump();
370 dbgs() <<
"\t mul2: "; Mul1_LHS[x]->dump();
371 dbgs() <<
"and operands " << x + 2 <<
":\n";
372 dbgs() <<
"\t mul1: "; Mul0_RHS[x]->dump();
373 dbgs() <<
"\t mul2: "; Mul1_RHS[x]->dump());
375 if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd) &&
376 AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
378 PMACPairs.push_back(std::make_pair(PMul0, PMul1));
386 PMACPairList &PMACPairs) {
390 for (
auto &Pair : PMACPairs) {
392 dbgs() <<
"- "; Pair.first->Root->dump();
393 dbgs() <<
"- "; Pair.second->Root->dump());
394 auto *VecLd0 = cast<LoadInst>(Pair.first->VecLd[0]);
395 auto *VecLd1 = cast<LoadInst>(Pair.second->VecLd[0]);
396 Acc = CreateSMLADCall(VecLd0, VecLd1, Acc, InsertAfter);
400 if (Acc != Reduction.Phi) {
402 Reduction.AccIntAdd->replaceAllUsesWith(Acc);
409 ReductionList &Reductions) {
411 const bool HasFnNoNaNAttr =
422 const auto *Ty = Phi.getType();
423 if (!Ty->isIntegerTy(32))
426 const bool IsReduction =
429 TheLoop, HasFnNoNaNAttr, RecDesc);
437 Reductions.push_back(
Reduction(&Phi, Acc));
441 dbgs() <<
"\nAccumulating integer additions (reductions) found:\n";
442 for (
auto &R : Reductions) {
443 dbgs() <<
"- "; R.Phi->dump();
444 dbgs() <<
"-> "; R.AccIntAdd->dump();
456 if (IsNarrowSequence<16>(MulOp0, LHS) &&
457 IsNarrowSequence<16>(MulOp1, RHS)) {
459 Candidates.push_back(make_unique<BinOpChain>(Mul, LHS, RHS));
464 OpChainList &Candidates) {
466 Value *A, *MulOp0, *MulOp1;
495 Instructions &Writes) {
496 for (
auto &I : *Header) {
500 Writes.push_back(&I);
508 Instructions &Writes, OpChainList &MACCandidates) {
510 for (
auto &MAC : MACCandidates) {
521 for (
auto *I : Writes) {
523 assert(MAC->MemLocs.size() >= 2 &&
"expecting at least 2 memlocs");
524 for (
auto &MemLoc : MAC->MemLocs) {
539 for (
auto &
C : Candidates) {
546 C->SetMemoryLocations();
547 ValueList &LHS =
static_cast<BinOpChain*
>(
C.get())->LHS;
548 ValueList &RHS =
static_cast<BinOpChain*
>(
C.get())->RHS;
551 for (
unsigned i = 0, e = LHS.size(); i < e; i += 2) {
552 if (!isa<LoadInst>(LHS[i]) || !isa<LoadInst>(RHS[i]))
591 bool ARMParallelDSP::MatchSMLAD(
Function &F) {
594 dbgs() <<
"Header block:\n"; Header->
dump();
595 dbgs() <<
"Loop info:\n\n"; L->
dump());
597 bool Changed =
false;
598 ReductionList Reductions;
601 for (
auto &R : Reductions) {
602 OpChainList MACCandidates;
607 R.MACCandidates = std::move(MACCandidates);
610 for (
auto &M : R.MACCandidates)
618 Instructions Reads, Writes;
621 for (
auto &R : Reductions) {
622 if (
AreAliased(AA, Reads, Writes, R.MACCandidates))
624 PMACPairList PMACPairs = CreateParallelMACPairs(R.MACCandidates);
625 Changed |= InsertParallelMACs(R, PMACPairs);
658 CallInst *Call = Builder.CreateCall(SMLAD, Args);
664 return new ARMParallelDSP();
670 "Transform loops to use DSP intrinsics",
false,
false)
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. ...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Compute iterated dominance frontiers using a linear time algorithm.
A Module instance is used to store all the information related to an LLVM module. ...
static bool AddReductionVar(PHINode *Phi, RecurrenceKind Kind, Loop *TheLoop, bool HasFunNoNaNAttr, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Returns true if Phi is a reduction of type Kind and adds it to the RecurrenceDescriptor.
static bool AreAliased(AliasAnalysis *AA, Instructions &Reads, Instructions &Writes, OpChainList &MACCandidates)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
The main scalar evolution driver.
static bool AreSymmetrical(const ValueList &VL0, const ValueList &VL1)
This class represents a function call, abstracting a target machine's calling convention.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
STATISTIC(NumFunctions, "Total number of functions")
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp", "Transform loops to use DSP intrinsics", false, false) INITIALIZE_PASS_END(ARMParallelDSP
void dump() const
Support for debugging, callable in GDB: V->dump()
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
arm parallel Transform loops to use DSP intrinsics
Target-Independent Code Generator Pass Configuration Options.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BlockT * getHeader() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
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.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
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.
Pass * createARMParallelDSPPass()
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
static bool AreSequentialAccesses(MemInst *MemOp0, MemInst *MemOp1, MemInstList &VecMem, const DataLayout &DL, ScalarEvolution &SE)
LLVM Basic Block Representation.
static bool IsNarrowSequence(Value *V, ValueList &VL)
The instances of the Type class are immutable: once they are created, they are never changed...
static void AliasCandidates(BasicBlock *Header, Instructions &Reads, Instructions &Writes)
void dump() const
Dump the module to stderr (for debugging).
Represent the analysis usage information of a pass.
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, CastClass_match< OpTy, Instruction::SExt > > m_ZExtOrSExt(const OpTy &Op)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
LoadClass_match< OpTy > m_Load(const OpTy &Op)
Matches LoadInst.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Representation for a specific memory location.
This is the shared class of boolean and integer constants.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Provides information about what library functions are available for the current target.
Drive the analysis of memory accesses in the loop.
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.
Class for arbitrary precision integers.
ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
InstListType::iterator iterator
Instruction iterators...
loop Loop Strength Reduction
StringRef getValueAsString() const
Return the attribute's value as a string.
Represents a single loop in the control flow graph.
LLVM_NODISCARD ModRefInfo intersectModRef(const ModRefInfo MRI1, const ModRefInfo MRI2)
bool mayReadFromMemory() const
Return true if this instruction may read memory.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LoadInst * CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name)
Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly, instead of converting the strin...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
static void AddMACCandidate(OpChainList &Candidates, const Instruction *Acc, Value *MulOp0, Value *MulOp1, int MulOpNum)
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
static void MatchParallelMACSequences(Reduction &R, OpChainList &Candidates)
Primary interface to the complete machine description for the target machine.
The legacy pass manager's analysis pass to compute loop information.
bool hasOneUse() const
Return true if there is exactly one user of this value.
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...
static bool CheckMACMemory(OpChainList &Candidates)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static void CreateLoadIns(IRBuilder< NoFolder > &IRB, Instruction *Acc, LoadInst **VecLd)
const BasicBlock * getParent() const
static void MatchReductions(Function &F, Loop *TheLoop, BasicBlock *Header, ReductionList &Reductions)