blob: 30b02b3c0fbbc8c8a5370f0df5b87e4f89bcac2c [file] [log] [blame]
Sjoerd Meijerc89ca552018-06-28 12:55:29 +00001//===- ParallelDSP.cpp - Parallel DSP Pass --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// Armv6 introduced instructions to perform 32-bit SIMD operations. The
12/// purpose of this pass is do some IR pattern matching to create ACLE
13/// DSP intrinsics, which map on these 32-bit SIMD operations.
Sjoerd Meijer53449da2018-07-11 12:36:25 +000014/// This pass runs only when unaligned accesses is supported/enabled.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000015//
16//===----------------------------------------------------------------------===//
17
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +000018#include "llvm/ADT/Statistic.h"
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000019#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/LoopAccessAnalysis.h"
22#include "llvm/Analysis/LoopPass.h"
23#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/NoFolder.h"
26#include "llvm/Transforms/Scalar.h"
27#include "llvm/Transforms/Utils/BasicBlockUtils.h"
28#include "llvm/Transforms/Utils/LoopUtils.h"
29#include "llvm/Pass.h"
30#include "llvm/PassRegistry.h"
31#include "llvm/PassSupport.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/IR/PatternMatch.h"
34#include "llvm/CodeGen/TargetPassConfig.h"
35#include "ARM.h"
36#include "ARMSubtarget.h"
37
38using namespace llvm;
39using namespace PatternMatch;
40
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +000041#define DEBUG_TYPE "arm-parallel-dsp"
42
43STATISTIC(NumSMLAD , "Number of smlad instructions generated");
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000044
Sjoerd Meijer3c859b32018-08-14 07:43:49 +000045static cl::opt<bool>
46DisableParallelDSP("disable-arm-parallel-dsp", cl::Hidden, cl::init(false),
47 cl::desc("Disable the ARM Parallel DSP pass"));
48
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000049namespace {
Sam Parker89a37992018-07-23 15:25:59 +000050 struct OpChain;
51 struct BinOpChain;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000052 struct Reduction;
53
Fangrui Song58407ca2018-07-23 17:43:21 +000054 using OpChainList = SmallVector<std::unique_ptr<OpChain>, 8>;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000055 using ReductionList = SmallVector<Reduction, 8>;
56 using ValueList = SmallVector<Value*, 8>;
Sam Parkerffc16812018-07-03 12:44:16 +000057 using MemInstList = SmallVector<Instruction*, 8>;
Sam Parker89a37992018-07-23 15:25:59 +000058 using PMACPair = std::pair<BinOpChain*,BinOpChain*>;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000059 using PMACPairList = SmallVector<PMACPair, 8>;
60 using Instructions = SmallVector<Instruction*,16>;
61 using MemLocList = SmallVector<MemoryLocation, 4>;
62
Sam Parker89a37992018-07-23 15:25:59 +000063 struct OpChain {
64 Instruction *Root;
65 ValueList AllValues;
66 MemInstList VecLd; // List of all load instructions.
67 MemLocList MemLocs; // All memory locations read by this tree.
68 bool ReadOnly = true;
69
70 OpChain(Instruction *I, ValueList &vl) : Root(I), AllValues(vl) { }
Jordan Rupprechte5daf612018-07-23 17:38:05 +000071 virtual ~OpChain() = default;
Sam Parker89a37992018-07-23 15:25:59 +000072
73 void SetMemoryLocations() {
74 const auto Size = MemoryLocation::UnknownSize;
75 for (auto *V : AllValues) {
76 if (auto *I = dyn_cast<Instruction>(V)) {
77 if (I->mayWriteToMemory())
78 ReadOnly = false;
79 if (auto *Ld = dyn_cast<LoadInst>(V))
80 MemLocs.push_back(MemoryLocation(Ld->getPointerOperand(), Size));
81 }
82 }
83 }
84
85 unsigned size() const { return AllValues.size(); }
86 };
87
88 // 'BinOpChain' and 'Reduction' are just some bookkeeping data structures.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000089 // 'Reduction' contains the phi-node and accumulator statement from where we
Sam Parker89a37992018-07-23 15:25:59 +000090 // start pattern matching, and 'BinOpChain' the multiplication
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000091 // instructions that are candidates for parallel execution.
Sam Parker89a37992018-07-23 15:25:59 +000092 struct BinOpChain : public OpChain {
93 ValueList LHS; // List of all (narrow) left hand operands.
94 ValueList RHS; // List of all (narrow) right hand operands.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000095
Sam Parker89a37992018-07-23 15:25:59 +000096 BinOpChain(Instruction *I, ValueList &lhs, ValueList &rhs) :
97 OpChain(I, lhs), LHS(lhs), RHS(rhs) {
98 for (auto *V : RHS)
99 AllValues.push_back(V);
100 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000101 };
102
103 struct Reduction {
104 PHINode *Phi; // The Phi-node from where we start
105 // pattern matching.
106 Instruction *AccIntAdd; // The accumulating integer add statement,
107 // i.e, the reduction statement.
108
Sam Parker89a37992018-07-23 15:25:59 +0000109 OpChainList MACCandidates; // The MAC candidates associated with
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000110 // this reduction statement.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000111 Reduction (PHINode *P, Instruction *Acc) : Phi(P), AccIntAdd(Acc) { };
112 };
113
114 class ARMParallelDSP : public LoopPass {
115 ScalarEvolution *SE;
116 AliasAnalysis *AA;
117 TargetLibraryInfo *TLI;
118 DominatorTree *DT;
119 LoopInfo *LI;
120 Loop *L;
121 const DataLayout *DL;
122 Module *M;
123
124 bool InsertParallelMACs(Reduction &Reduction, PMACPairList &PMACPairs);
Fangrui Song68169342018-07-03 19:12:27 +0000125 bool AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1, MemInstList &VecMem);
Sam Parker89a37992018-07-23 15:25:59 +0000126 PMACPairList CreateParallelMACPairs(OpChainList &Candidates);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000127 Instruction *CreateSMLADCall(LoadInst *VecLd0, LoadInst *VecLd1,
128 Instruction *Acc, Instruction *InsertAfter);
129
130 /// Try to match and generate: SMLAD, SMLADX - Signed Multiply Accumulate
131 /// Dual performs two signed 16x16-bit multiplications. It adds the
132 /// products to a 32-bit accumulate operand. Optionally, the instruction can
133 /// exchange the halfwords of the second operand before performing the
134 /// arithmetic.
135 bool MatchSMLAD(Function &F);
136
137 public:
138 static char ID;
139
140 ARMParallelDSP() : LoopPass(ID) { }
141
142 void getAnalysisUsage(AnalysisUsage &AU) const override {
143 LoopPass::getAnalysisUsage(AU);
144 AU.addRequired<AssumptionCacheTracker>();
145 AU.addRequired<ScalarEvolutionWrapperPass>();
146 AU.addRequired<AAResultsWrapperPass>();
147 AU.addRequired<TargetLibraryInfoWrapperPass>();
148 AU.addRequired<LoopInfoWrapperPass>();
149 AU.addRequired<DominatorTreeWrapperPass>();
150 AU.addRequired<TargetPassConfig>();
151 AU.addPreserved<LoopInfoWrapperPass>();
152 AU.setPreservesCFG();
153 }
154
155 bool runOnLoop(Loop *TheLoop, LPPassManager &) override {
Sjoerd Meijer3c859b32018-08-14 07:43:49 +0000156 if (DisableParallelDSP)
157 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000158 L = TheLoop;
159 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
160 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
161 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
162 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
163 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
164 auto &TPC = getAnalysis<TargetPassConfig>();
165
166 BasicBlock *Header = TheLoop->getHeader();
167 if (!Header)
168 return false;
169
170 // TODO: We assume the loop header and latch to be the same block.
171 // This is not a fundamental restriction, but lifting this would just
172 // require more work to do the transformation and then patch up the CFG.
173 if (Header != TheLoop->getLoopLatch()) {
174 LLVM_DEBUG(dbgs() << "The loop header is not the loop latch: not "
175 "running pass ARMParallelDSP\n");
176 return false;
177 }
178
179 Function &F = *Header->getParent();
180 M = F.getParent();
181 DL = &M->getDataLayout();
182
183 auto &TM = TPC.getTM<TargetMachine>();
184 auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
185
186 if (!ST->allowsUnalignedMem()) {
187 LLVM_DEBUG(dbgs() << "Unaligned memory access not supported: not "
188 "running pass ARMParallelDSP\n");
189 return false;
190 }
191
192 if (!ST->hasDSP()) {
193 LLVM_DEBUG(dbgs() << "DSP extension not enabled: not running pass "
194 "ARMParallelDSP\n");
195 return false;
196 }
197
198 LoopAccessInfo LAI(L, SE, TLI, AA, DT, LI);
199 bool Changes = false;
200
201 LLVM_DEBUG(dbgs() << "\n== Parallel DSP pass ==\n\n");
202 Changes = MatchSMLAD(F);
203 return Changes;
204 }
205 };
206}
207
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000208// MaxBitwidth: the maximum supported bitwidth of the elements in the DSP
209// instructions, which is set to 16. So here we should collect all i8 and i16
210// narrow operations.
211// TODO: we currently only collect i16, and will support i8 later, so that's
212// why we check that types are equal to MaxBitWidth, and not <= MaxBitWidth.
213template<unsigned MaxBitWidth>
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000214static bool IsNarrowSequence(Value *V, ValueList &VL) {
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000215 LLVM_DEBUG(dbgs() << "Is narrow sequence? "; V->dump());
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000216 ConstantInt *CInt;
217
218 if (match(V, m_ConstantInt(CInt))) {
219 // TODO: if a constant is used, it needs to fit within the bit width.
220 return false;
221 }
222
223 auto *I = dyn_cast<Instruction>(V);
224 if (!I)
225 return false;
226
227 Value *Val, *LHS, *RHS;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000228 if (match(V, m_Trunc(m_Value(Val)))) {
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000229 if (cast<TruncInst>(I)->getDestTy()->getIntegerBitWidth() == MaxBitWidth)
230 return IsNarrowSequence<MaxBitWidth>(Val, VL);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000231 } else if (match(V, m_Add(m_Value(LHS), m_Value(RHS)))) {
232 // TODO: we need to implement sadd16/sadd8 for this, which enables to
233 // also do the rewrite for smlad8.ll, but it is unsupported for now.
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000234 LLVM_DEBUG(dbgs() << "No, unsupported Op:\t"; I->dump());
235 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000236 } else if (match(V, m_ZExtOrSExt(m_Value(Val)))) {
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000237 if (cast<CastInst>(I)->getSrcTy()->getIntegerBitWidth() != MaxBitWidth) {
238 LLVM_DEBUG(dbgs() << "No, wrong SrcTy size: " <<
239 cast<CastInst>(I)->getSrcTy()->getIntegerBitWidth() << "\n");
240 return false;
241 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000242
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000243 if (match(Val, m_Load(m_Value()))) {
244 LLVM_DEBUG(dbgs() << "Yes, found narrow Load:\t"; Val->dump());
245 VL.push_back(Val);
246 VL.push_back(I);
247 return true;
248 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000249 }
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000250 LLVM_DEBUG(dbgs() << "No, unsupported Op:\t"; I->dump());
251 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000252}
253
254// Element-by-element comparison of Value lists returning true if they are
255// instructions with the same opcode or constants with the same value.
256static bool AreSymmetrical(const ValueList &VL0,
257 const ValueList &VL1) {
258 if (VL0.size() != VL1.size()) {
259 LLVM_DEBUG(dbgs() << "Muls are mismatching operand list lengths: "
260 << VL0.size() << " != " << VL1.size() << "\n");
261 return false;
262 }
263
264 const unsigned Pairs = VL0.size();
265 LLVM_DEBUG(dbgs() << "Number of operand pairs: " << Pairs << "\n");
266
267 for (unsigned i = 0; i < Pairs; ++i) {
268 const Value *V0 = VL0[i];
269 const Value *V1 = VL1[i];
270 const auto *Inst0 = dyn_cast<Instruction>(V0);
271 const auto *Inst1 = dyn_cast<Instruction>(V1);
272
273 LLVM_DEBUG(dbgs() << "Pair " << i << ":\n";
274 dbgs() << "mul1: "; V0->dump();
275 dbgs() << "mul2: "; V1->dump());
276
277 if (!Inst0 || !Inst1)
278 return false;
279
280 if (Inst0->isSameOperationAs(Inst1)) {
281 LLVM_DEBUG(dbgs() << "OK: same operation found!\n");
282 continue;
283 }
284
285 const APInt *C0, *C1;
286 if (!(match(V0, m_APInt(C0)) && match(V1, m_APInt(C1)) && C0 == C1))
287 return false;
288 }
289
290 LLVM_DEBUG(dbgs() << "OK: found symmetrical operand lists.\n");
291 return true;
292}
293
Sam Parkerffc16812018-07-03 12:44:16 +0000294template<typename MemInst>
295static bool AreSequentialAccesses(MemInst *MemOp0, MemInst *MemOp1,
296 MemInstList &VecMem, const DataLayout &DL,
297 ScalarEvolution &SE) {
298 if (!MemOp0->isSimple() || !MemOp1->isSimple()) {
299 LLVM_DEBUG(dbgs() << "No, not touching volatile access\n");
300 return false;
301 }
302 if (isConsecutiveAccess(MemOp0, MemOp1, DL, SE)) {
303 VecMem.push_back(MemOp0);
304 VecMem.push_back(MemOp1);
305 LLVM_DEBUG(dbgs() << "OK: accesses are consecutive.\n");
306 return true;
307 }
308 LLVM_DEBUG(dbgs() << "No, accesses aren't consecutive.\n");
309 return false;
310}
311
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000312bool ARMParallelDSP::AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1,
Sam Parkerffc16812018-07-03 12:44:16 +0000313 MemInstList &VecMem) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000314 if (!Ld0 || !Ld1)
315 return false;
316
317 LLVM_DEBUG(dbgs() << "Are consecutive loads:\n";
318 dbgs() << "Ld0:"; Ld0->dump();
319 dbgs() << "Ld1:"; Ld1->dump();
320 );
321
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000322 if (!Ld0->hasOneUse() || !Ld1->hasOneUse()) {
323 LLVM_DEBUG(dbgs() << "No, load has more than one use.\n");
324 return false;
325 }
Sam Parkerffc16812018-07-03 12:44:16 +0000326
327 return AreSequentialAccesses<LoadInst>(Ld0, Ld1, VecMem, *DL, *SE);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000328}
329
330PMACPairList
Sam Parker89a37992018-07-23 15:25:59 +0000331ARMParallelDSP::CreateParallelMACPairs(OpChainList &Candidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000332 const unsigned Elems = Candidates.size();
333 PMACPairList PMACPairs;
334
335 if (Elems < 2)
336 return PMACPairs;
337
338 // TODO: for now we simply try to match consecutive pairs i and i+1.
339 // We can compare all elements, but then we need to compare and evaluate
340 // different solutions.
341 for(unsigned i=0; i<Elems-1; i+=2) {
Fangrui Song58407ca2018-07-23 17:43:21 +0000342 BinOpChain *PMul0 = static_cast<BinOpChain*>(Candidates[i].get());
343 BinOpChain *PMul1 = static_cast<BinOpChain*>(Candidates[i+1].get());
Sam Parker89a37992018-07-23 15:25:59 +0000344 const Instruction *Mul0 = PMul0->Root;
345 const Instruction *Mul1 = PMul1->Root;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000346
347 if (Mul0 == Mul1)
348 continue;
349
350 LLVM_DEBUG(dbgs() << "\nCheck parallel muls:\n";
351 dbgs() << "- "; Mul0->dump();
352 dbgs() << "- "; Mul1->dump());
353
Sam Parker89a37992018-07-23 15:25:59 +0000354 const ValueList &Mul0_LHS = PMul0->LHS;
355 const ValueList &Mul0_RHS = PMul0->RHS;
356 const ValueList &Mul1_LHS = PMul1->LHS;
357 const ValueList &Mul1_RHS = PMul1->RHS;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000358
Sam Parker89a37992018-07-23 15:25:59 +0000359 if (!AreSymmetrical(Mul0_LHS, Mul1_LHS) ||
360 !AreSymmetrical(Mul0_RHS, Mul1_RHS))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000361 continue;
362
363 LLVM_DEBUG(dbgs() << "OK: mul operands list match:\n");
364 // The first elements of each vector should be loads with sexts. If we find
365 // that its two pairs of consecutive loads, then these can be transformed
366 // into two wider loads and the users can be replaced with DSP
367 // intrinsics.
Sam Parker89a37992018-07-23 15:25:59 +0000368 for (unsigned x = 0; x < Mul0_LHS.size(); x += 2) {
369 auto *Ld0 = dyn_cast<LoadInst>(Mul0_LHS[x]);
370 auto *Ld1 = dyn_cast<LoadInst>(Mul1_LHS[x]);
371 auto *Ld2 = dyn_cast<LoadInst>(Mul0_RHS[x]);
372 auto *Ld3 = dyn_cast<LoadInst>(Mul1_RHS[x]);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000373
374 LLVM_DEBUG(dbgs() << "Looking at operands " << x << ":\n";
Sam Parker89a37992018-07-23 15:25:59 +0000375 dbgs() << "\t mul1: "; Mul0_LHS[x]->dump();
376 dbgs() << "\t mul2: "; Mul1_LHS[x]->dump();
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000377 dbgs() << "and operands " << x + 2 << ":\n";
Sam Parker89a37992018-07-23 15:25:59 +0000378 dbgs() << "\t mul1: "; Mul0_RHS[x]->dump();
379 dbgs() << "\t mul2: "; Mul1_RHS[x]->dump());
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000380
Sam Parker89a37992018-07-23 15:25:59 +0000381 if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd) &&
382 AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000383 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
Sam Parker89a37992018-07-23 15:25:59 +0000384 PMACPairs.push_back(std::make_pair(PMul0, PMul1));
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000385 }
386 }
387 }
388 return PMACPairs;
389}
390
391bool ARMParallelDSP::InsertParallelMACs(Reduction &Reduction,
392 PMACPairList &PMACPairs) {
393 Instruction *Acc = Reduction.Phi;
394 Instruction *InsertAfter = Reduction.AccIntAdd;
395
396 for (auto &Pair : PMACPairs) {
397 LLVM_DEBUG(dbgs() << "Found parallel MACs!!\n";
Sam Parker89a37992018-07-23 15:25:59 +0000398 dbgs() << "- "; Pair.first->Root->dump();
399 dbgs() << "- "; Pair.second->Root->dump());
Sam Parkerffc16812018-07-03 12:44:16 +0000400 auto *VecLd0 = cast<LoadInst>(Pair.first->VecLd[0]);
401 auto *VecLd1 = cast<LoadInst>(Pair.second->VecLd[0]);
402 Acc = CreateSMLADCall(VecLd0, VecLd1, Acc, InsertAfter);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000403 InsertAfter = Acc;
404 }
405
406 if (Acc != Reduction.Phi) {
407 LLVM_DEBUG(dbgs() << "Replace Accumulate: "; Acc->dump());
408 Reduction.AccIntAdd->replaceAllUsesWith(Acc);
409 return true;
410 }
411 return false;
412}
413
Sam Parker89a37992018-07-23 15:25:59 +0000414static void MatchReductions(Function &F, Loop *TheLoop, BasicBlock *Header,
415 ReductionList &Reductions) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000416 RecurrenceDescriptor RecDesc;
417 const bool HasFnNoNaNAttr =
418 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
419 const BasicBlock *Latch = TheLoop->getLoopLatch();
420
421 // We need a preheader as getIncomingValueForBlock assumes there is one.
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000422 if (!TheLoop->getLoopPreheader()) {
423 LLVM_DEBUG(dbgs() << "No preheader found, bailing out\n");
Sam Parker89a37992018-07-23 15:25:59 +0000424 return;
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000425 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000426
427 for (PHINode &Phi : Header->phis()) {
428 const auto *Ty = Phi.getType();
429 if (!Ty->isIntegerTy(32))
430 continue;
431
432 const bool IsReduction =
433 RecurrenceDescriptor::AddReductionVar(&Phi,
434 RecurrenceDescriptor::RK_IntegerAdd,
435 TheLoop, HasFnNoNaNAttr, RecDesc);
436 if (!IsReduction)
437 continue;
438
439 Instruction *Acc = dyn_cast<Instruction>(Phi.getIncomingValueForBlock(Latch));
440 if (!Acc)
441 continue;
442
443 Reductions.push_back(Reduction(&Phi, Acc));
444 }
445
446 LLVM_DEBUG(
447 dbgs() << "\nAccumulating integer additions (reductions) found:\n";
Sam Parker89a37992018-07-23 15:25:59 +0000448 for (auto &R : Reductions) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000449 dbgs() << "- "; R.Phi->dump();
450 dbgs() << "-> "; R.AccIntAdd->dump();
451 }
452 );
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000453}
454
Sam Parker89a37992018-07-23 15:25:59 +0000455static void AddMACCandidate(OpChainList &Candidates,
456 const Instruction *Acc,
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000457 Value *MulOp0, Value *MulOp1, int MulOpNum) {
458 Instruction *Mul = dyn_cast<Instruction>(Acc->getOperand(MulOpNum));
459 LLVM_DEBUG(dbgs() << "OK, found acc mul:\t"; Mul->dump());
Sam Parker89a37992018-07-23 15:25:59 +0000460 ValueList LHS;
461 ValueList RHS;
462 if (IsNarrowSequence<16>(MulOp0, LHS) &&
463 IsNarrowSequence<16>(MulOp1, RHS)) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000464 LLVM_DEBUG(dbgs() << "OK, found narrow mul: "; Mul->dump());
Fangrui Song58407ca2018-07-23 17:43:21 +0000465 Candidates.push_back(make_unique<BinOpChain>(Mul, LHS, RHS));
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000466 }
467}
468
Sam Parker89a37992018-07-23 15:25:59 +0000469static void MatchParallelMACSequences(Reduction &R,
470 OpChainList &Candidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000471 const Instruction *Acc = R.AccIntAdd;
472 Value *A, *MulOp0, *MulOp1;
473 LLVM_DEBUG(dbgs() << "\n- Analysing:\t"; Acc->dump());
474
475 // Pattern 1: the accumulator is the RHS of the mul.
476 while(match(Acc, m_Add(m_Mul(m_Value(MulOp0), m_Value(MulOp1)),
477 m_Value(A)))){
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000478 AddMACCandidate(Candidates, Acc, MulOp0, MulOp1, 0);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000479 Acc = dyn_cast<Instruction>(A);
480 }
481 // Pattern 2: the accumulator is the LHS of the mul.
482 while(match(Acc, m_Add(m_Value(A),
483 m_Mul(m_Value(MulOp0), m_Value(MulOp1))))) {
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000484 AddMACCandidate(Candidates, Acc, MulOp0, MulOp1, 1);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000485 Acc = dyn_cast<Instruction>(A);
486 }
487
488 // The last mul in the chain has a slightly different pattern:
489 // the mul is the first operand
490 if (match(Acc, m_Add(m_Mul(m_Value(MulOp0), m_Value(MulOp1)), m_Value(A))))
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000491 AddMACCandidate(Candidates, Acc, MulOp0, MulOp1, 0);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000492
493 // Because we start at the bottom of the chain, and we work our way up,
494 // the muls are added in reverse program order to the list.
495 std::reverse(Candidates.begin(), Candidates.end());
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000496}
497
498// Collects all instructions that are not part of the MAC chains, which is the
499// set of instructions that can potentially alias with the MAC operands.
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000500static void AliasCandidates(BasicBlock *Header, Instructions &Reads,
501 Instructions &Writes) {
502 for (auto &I : *Header) {
503 if (I.mayReadFromMemory())
504 Reads.push_back(&I);
505 if (I.mayWriteToMemory())
506 Writes.push_back(&I);
507 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000508}
509
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000510// Check whether statements in the basic block that write to memory alias with
511// the memory locations accessed by the MAC-chains.
512// TODO: we need the read statements when we accept more complicated chains.
513static bool AreAliased(AliasAnalysis *AA, Instructions &Reads,
Sam Parker89a37992018-07-23 15:25:59 +0000514 Instructions &Writes, OpChainList &MACCandidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000515 LLVM_DEBUG(dbgs() << "Alias checks:\n");
Fangrui Song58407ca2018-07-23 17:43:21 +0000516 for (auto &MAC : MACCandidates) {
Sam Parker89a37992018-07-23 15:25:59 +0000517 LLVM_DEBUG(dbgs() << "mul: "; MAC->Root->dump());
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000518
519 // At the moment, we allow only simple chains that only consist of reads,
520 // accumulate their result with an integer add, and thus that don't write
521 // memory, and simply bail if they do.
Sam Parker89a37992018-07-23 15:25:59 +0000522 if (!MAC->ReadOnly)
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000523 return true;
524
525 // Now for all writes in the basic block, check that they don't alias with
526 // the memory locations accessed by our MAC-chain:
527 for (auto *I : Writes) {
528 LLVM_DEBUG(dbgs() << "- "; I->dump());
Sam Parker89a37992018-07-23 15:25:59 +0000529 assert(MAC->MemLocs.size() >= 2 && "expecting at least 2 memlocs");
530 for (auto &MemLoc : MAC->MemLocs) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000531 if (isModOrRefSet(intersectModRef(AA->getModRefInfo(I, MemLoc),
532 ModRefInfo::ModRef))) {
533 LLVM_DEBUG(dbgs() << "Yes, aliases found\n");
534 return true;
535 }
536 }
537 }
538 }
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000539
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000540 LLVM_DEBUG(dbgs() << "OK: no aliases found!\n");
541 return false;
542}
543
Sam Parker89a37992018-07-23 15:25:59 +0000544static bool CheckMACMemory(OpChainList &Candidates) {
Fangrui Song58407ca2018-07-23 17:43:21 +0000545 for (auto &C : Candidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000546 // A mul has 2 operands, and a narrow op consist of sext and a load; thus
547 // we expect at least 4 items in this operand value list.
Sam Parker89a37992018-07-23 15:25:59 +0000548 if (C->size() < 4) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000549 LLVM_DEBUG(dbgs() << "Operand list too short.\n");
550 return false;
551 }
Sam Parker89a37992018-07-23 15:25:59 +0000552 C->SetMemoryLocations();
Fangrui Song58407ca2018-07-23 17:43:21 +0000553 ValueList &LHS = static_cast<BinOpChain*>(C.get())->LHS;
554 ValueList &RHS = static_cast<BinOpChain*>(C.get())->RHS;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000555
Sam Parker89a37992018-07-23 15:25:59 +0000556 // Use +=2 to skip over the expected extend instructions.
557 for (unsigned i = 0, e = LHS.size(); i < e; i += 2) {
558 if (!isa<LoadInst>(LHS[i]) || !isa<LoadInst>(RHS[i]))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000559 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000560 }
561 }
562 return true;
563}
564
565// Loop Pass that needs to identify integer add/sub reductions of 16-bit vector
566// multiplications.
567// To use SMLAD:
568// 1) we first need to find integer add reduction PHIs,
569// 2) then from the PHI, look for this pattern:
570//
571// acc0 = phi i32 [0, %entry], [%acc1, %loop.body]
572// ld0 = load i16
573// sext0 = sext i16 %ld0 to i32
574// ld1 = load i16
575// sext1 = sext i16 %ld1 to i32
576// mul0 = mul %sext0, %sext1
577// ld2 = load i16
578// sext2 = sext i16 %ld2 to i32
579// ld3 = load i16
580// sext3 = sext i16 %ld3 to i32
581// mul1 = mul i32 %sext2, %sext3
582// add0 = add i32 %mul0, %acc0
583// acc1 = add i32 %add0, %mul1
584//
585// Which can be selected to:
586//
587// ldr.h r0
588// ldr.h r1
589// smlad r2, r0, r1, r2
590//
591// If constants are used instead of loads, these will need to be hoisted
592// out and into a register.
593//
594// If loop invariants are used instead of loads, these need to be packed
595// before the loop begins.
596//
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000597bool ARMParallelDSP::MatchSMLAD(Function &F) {
598 BasicBlock *Header = L->getHeader();
599 LLVM_DEBUG(dbgs() << "= Matching SMLAD =\n";
600 dbgs() << "Header block:\n"; Header->dump();
601 dbgs() << "Loop info:\n\n"; L->dump());
602
603 bool Changed = false;
Sam Parker89a37992018-07-23 15:25:59 +0000604 ReductionList Reductions;
605 MatchReductions(F, L, Header, Reductions);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000606
607 for (auto &R : Reductions) {
Sam Parker89a37992018-07-23 15:25:59 +0000608 OpChainList MACCandidates;
609 MatchParallelMACSequences(R, MACCandidates);
610 if (!CheckMACMemory(MACCandidates))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000611 continue;
Sam Parker89a37992018-07-23 15:25:59 +0000612
Fangrui Song58407ca2018-07-23 17:43:21 +0000613 R.MACCandidates = std::move(MACCandidates);
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000614
615 LLVM_DEBUG(dbgs() << "MAC candidates:\n";
616 for (auto &M : R.MACCandidates)
Sam Parker89a37992018-07-23 15:25:59 +0000617 M->Root->dump();
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000618 dbgs() << "\n";);
619 }
620
621 // Collect all instructions that may read or write memory. Our alias
622 // analysis checks bail out if any of these instructions aliases with an
623 // instruction from the MAC-chain.
624 Instructions Reads, Writes;
625 AliasCandidates(Header, Reads, Writes);
626
627 for (auto &R : Reductions) {
628 if (AreAliased(AA, Reads, Writes, R.MACCandidates))
629 return false;
630 PMACPairList PMACPairs = CreateParallelMACPairs(R.MACCandidates);
631 Changed |= InsertParallelMACs(R, PMACPairs);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000632 }
633
634 LLVM_DEBUG(if (Changed) dbgs() << "Header block:\n"; Header->dump(););
635 return Changed;
636}
637
638static void CreateLoadIns(IRBuilder<NoFolder> &IRB, Instruction *Acc,
639 LoadInst **VecLd) {
640 const Type *AccTy = Acc->getType();
641 const unsigned AddrSpace = (*VecLd)->getPointerAddressSpace();
642
643 Value *VecPtr = IRB.CreateBitCast((*VecLd)->getPointerOperand(),
644 AccTy->getPointerTo(AddrSpace));
645 *VecLd = IRB.CreateAlignedLoad(VecPtr, (*VecLd)->getAlignment());
646}
647
648Instruction *ARMParallelDSP::CreateSMLADCall(LoadInst *VecLd0, LoadInst *VecLd1,
649 Instruction *Acc,
650 Instruction *InsertAfter) {
651 LLVM_DEBUG(dbgs() << "Create SMLAD intrinsic using:\n";
652 dbgs() << "- "; VecLd0->dump();
653 dbgs() << "- "; VecLd1->dump();
654 dbgs() << "- "; Acc->dump());
655
656 IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
657 ++BasicBlock::iterator(InsertAfter));
658
659 // Replace the reduction chain with an intrinsic call
660 CreateLoadIns(Builder, Acc, &VecLd0);
661 CreateLoadIns(Builder, Acc, &VecLd1);
662 Value* Args[] = { VecLd0, VecLd1, Acc };
663 Function *SMLAD = Intrinsic::getDeclaration(M, Intrinsic::arm_smlad);
664 CallInst *Call = Builder.CreateCall(SMLAD, Args);
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000665 NumSMLAD++;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000666 return Call;
667}
668
669Pass *llvm::createARMParallelDSPPass() {
670 return new ARMParallelDSP();
671}
672
673char ARMParallelDSP::ID = 0;
674
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000675INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp",
Simon Pilgrimc09b5e32018-06-28 18:37:16 +0000676 "Transform loops to use DSP intrinsics", false, false)
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000677INITIALIZE_PASS_END(ARMParallelDSP, "arm-parallel-dsp",
Simon Pilgrimc09b5e32018-06-28 18:37:16 +0000678 "Transform loops to use DSP intrinsics", false, false)