blob: 5e7627f017d69262306929dbd9e250fe4dc4941c [file] [log] [blame]
Sam Parker2200a9b2019-07-31 07:32:03 +00001//===- ARMParallelDSP.cpp - Parallel DSP Pass -----------------------------===//
Sjoerd Meijerc89ca552018-06-28 12:55:29 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sjoerd Meijerc89ca552018-06-28 12:55:29 +00006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Armv6 introduced instructions to perform 32-bit SIMD operations. The
11/// purpose of this pass is do some IR pattern matching to create ACLE
12/// DSP intrinsics, which map on these 32-bit SIMD operations.
Sjoerd Meijer53449da2018-07-11 12:36:25 +000013/// This pass runs only when unaligned accesses is supported/enabled.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000014//
15//===----------------------------------------------------------------------===//
16
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +000017#include "llvm/ADT/Statistic.h"
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000018#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/Analysis/AliasAnalysis.h"
20#include "llvm/Analysis/LoopAccessAnalysis.h"
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000021#include "llvm/IR/Instructions.h"
22#include "llvm/IR/NoFolder.h"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000025#include "llvm/Pass.h"
26#include "llvm/PassRegistry.h"
27#include "llvm/PassSupport.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/IR/PatternMatch.h"
30#include "llvm/CodeGen/TargetPassConfig.h"
31#include "ARM.h"
32#include "ARMSubtarget.h"
33
34using namespace llvm;
35using namespace PatternMatch;
36
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +000037#define DEBUG_TYPE "arm-parallel-dsp"
38
39STATISTIC(NumSMLAD , "Number of smlad instructions generated");
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000040
Sjoerd Meijer3c859b32018-08-14 07:43:49 +000041static cl::opt<bool>
42DisableParallelDSP("disable-arm-parallel-dsp", cl::Hidden, cl::init(false),
43 cl::desc("Disable the ARM Parallel DSP pass"));
44
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000045namespace {
Sam Parker89a37992018-07-23 15:25:59 +000046 struct OpChain;
Sam Parker414dd1c2019-07-29 08:41:51 +000047 struct MulCandidate;
Sam Parker85ad78b2019-07-11 07:47:50 +000048 class Reduction;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000049
Sam Parker414dd1c2019-07-29 08:41:51 +000050 using MulCandList = SmallVector<std::unique_ptr<MulCandidate>, 8>;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000051 using ReductionList = SmallVector<Reduction, 8>;
52 using ValueList = SmallVector<Value*, 8>;
Sam Parker4c4ff132019-03-14 11:14:13 +000053 using MemInstList = SmallVector<LoadInst*, 8>;
Sam Parker414dd1c2019-07-29 08:41:51 +000054 using PMACPair = std::pair<MulCandidate*,MulCandidate*>;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000055 using PMACPairList = SmallVector<PMACPair, 8>;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000056
Sam Parker414dd1c2019-07-29 08:41:51 +000057 // 'MulCandidate' holds the multiplication instructions that are candidates
Sam Parker3da59e52019-07-26 14:11:40 +000058 // for parallel execution.
Sam Parker414dd1c2019-07-29 08:41:51 +000059 struct MulCandidate {
Sam Parker89a37992018-07-23 15:25:59 +000060 Instruction *Root;
Sam Parker414dd1c2019-07-29 08:41:51 +000061 MemInstList VecLd; // Container for loads to widen.
62 Value* LHS;
63 Value* RHS;
Sam Parker3da59e52019-07-26 14:11:40 +000064 bool Exchange = false;
Sam Parker89a37992018-07-23 15:25:59 +000065 bool ReadOnly = true;
66
Sam Parker414dd1c2019-07-29 08:41:51 +000067 MulCandidate(Instruction *I, ValueList &lhs, ValueList &rhs) :
68 Root(I), LHS(lhs.front()), RHS(rhs.front()) { }
Sam Parker89a37992018-07-23 15:25:59 +000069
Sam Parker414dd1c2019-07-29 08:41:51 +000070 bool HasTwoLoadInputs() const {
71 return isa<LoadInst>(LHS) && isa<LoadInst>(RHS);
72 }
Sam Parker7ca8c6f2019-08-01 08:17:51 +000073
74 LoadInst *getBaseLoad() const {
75 return cast<LoadInst>(LHS);
76 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000077 };
78
Sam Parker85ad78b2019-07-11 07:47:50 +000079 /// Represent a sequence of multiply-accumulate operations with the aim to
80 /// perform the multiplications in parallel.
81 class Reduction {
82 Instruction *Root = nullptr;
83 Value *Acc = nullptr;
Sam Parker414dd1c2019-07-29 08:41:51 +000084 MulCandList Muls;
Sam Parker85ad78b2019-07-11 07:47:50 +000085 PMACPairList MulPairs;
86 SmallPtrSet<Instruction*, 4> Adds;
87
88 public:
89 Reduction() = delete;
90
91 Reduction (Instruction *Add) : Root(Add) { }
92
93 /// Record an Add instruction that is a part of the this reduction.
94 void InsertAdd(Instruction *I) { Adds.insert(I); }
95
Sam Parker414dd1c2019-07-29 08:41:51 +000096 /// Record a MulCandidate, rooted at a Mul instruction, that is a part of
Sam Parker85ad78b2019-07-11 07:47:50 +000097 /// this reduction.
98 void InsertMul(Instruction *I, ValueList &LHS, ValueList &RHS) {
Sam Parker414dd1c2019-07-29 08:41:51 +000099 Muls.push_back(make_unique<MulCandidate>(I, LHS, RHS));
Sam Parker85ad78b2019-07-11 07:47:50 +0000100 }
101
102 /// Add the incoming accumulator value, returns true if a value had not
103 /// already been added. Returning false signals to the user that this
104 /// reduction already has a value to initialise the accumulator.
105 bool InsertAcc(Value *V) {
106 if (Acc)
107 return false;
108 Acc = V;
109 return true;
110 }
111
Sam Parker414dd1c2019-07-29 08:41:51 +0000112 /// Set two MulCandidates, rooted at muls, that can be executed as a single
Sam Parker85ad78b2019-07-11 07:47:50 +0000113 /// parallel operation.
Sam Parker414dd1c2019-07-29 08:41:51 +0000114 void AddMulPair(MulCandidate *Mul0, MulCandidate *Mul1) {
Sam Parker85ad78b2019-07-11 07:47:50 +0000115 MulPairs.push_back(std::make_pair(Mul0, Mul1));
116 }
117
118 /// Return true if enough mul operations are found that can be executed in
119 /// parallel.
120 bool CreateParallelPairs();
121
122 /// Return the add instruction which is the root of the reduction.
123 Instruction *getRoot() { return Root; }
124
Sam Parker7ca8c6f2019-08-01 08:17:51 +0000125 bool is64Bit() const { return Root->getType()->isIntegerTy(64); }
126
Sam Parker85ad78b2019-07-11 07:47:50 +0000127 /// Return the incoming value to be accumulated. This maybe null.
128 Value *getAccumulator() { return Acc; }
129
130 /// Return the set of adds that comprise the reduction.
131 SmallPtrSetImpl<Instruction*> &getAdds() { return Adds; }
132
Sam Parker414dd1c2019-07-29 08:41:51 +0000133 /// Return the MulCandidate, rooted at mul instruction, that comprise the
Sam Parker85ad78b2019-07-11 07:47:50 +0000134 /// the reduction.
Sam Parker414dd1c2019-07-29 08:41:51 +0000135 MulCandList &getMuls() { return Muls; }
Sam Parker85ad78b2019-07-11 07:47:50 +0000136
Sam Parker414dd1c2019-07-29 08:41:51 +0000137 /// Return the MulCandidate, rooted at mul instructions, that have been
Sam Parker85ad78b2019-07-11 07:47:50 +0000138 /// paired for parallel execution.
139 PMACPairList &getMulPairs() { return MulPairs; }
140
141 /// To finalise, replace the uses of the root with the intrinsic call.
142 void UpdateRoot(Instruction *SMLAD) {
143 Root->replaceAllUsesWith(SMLAD);
144 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000145 };
146
Sam Parker4c4ff132019-03-14 11:14:13 +0000147 class WidenedLoad {
148 LoadInst *NewLd = nullptr;
149 SmallVector<LoadInst*, 4> Loads;
150
151 public:
152 WidenedLoad(SmallVectorImpl<LoadInst*> &Lds, LoadInst *Wide)
153 : NewLd(Wide) {
154 for (auto *I : Lds)
155 Loads.push_back(I);
156 }
157 LoadInst *getLoad() {
158 return NewLd;
159 }
160 };
161
Sam Parker2200a9b2019-07-31 07:32:03 +0000162 class ARMParallelDSP : public FunctionPass {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000163 ScalarEvolution *SE;
164 AliasAnalysis *AA;
165 TargetLibraryInfo *TLI;
166 DominatorTree *DT;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000167 const DataLayout *DL;
168 Module *M;
Sam Parker453ba912018-11-09 09:18:00 +0000169 std::map<LoadInst*, LoadInst*> LoadPairs;
Sam Parker85ad78b2019-07-11 07:47:50 +0000170 SmallPtrSet<LoadInst*, 4> OffsetLoads;
Sam Parker4c4ff132019-03-14 11:14:13 +0000171 std::map<LoadInst*, std::unique_ptr<WidenedLoad>> WideLoads;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000172
Sam Parker85ad78b2019-07-11 07:47:50 +0000173 template<unsigned>
174 bool IsNarrowSequence(Value *V, ValueList &VL);
175
Sam Parkera33e3112019-05-13 09:23:32 +0000176 bool RecordMemoryOps(BasicBlock *BB);
Sam Parker85ad78b2019-07-11 07:47:50 +0000177 void InsertParallelMACs(Reduction &Reduction);
Fangrui Song68169342018-07-03 19:12:27 +0000178 bool AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1, MemInstList &VecMem);
Sam Parkera33e3112019-05-13 09:23:32 +0000179 LoadInst* CreateWideLoad(SmallVectorImpl<LoadInst*> &Loads,
180 IntegerType *LoadTy);
Sam Parker85ad78b2019-07-11 07:47:50 +0000181 bool CreateParallelPairs(Reduction &R);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000182
183 /// Try to match and generate: SMLAD, SMLADX - Signed Multiply Accumulate
184 /// Dual performs two signed 16x16-bit multiplications. It adds the
185 /// products to a 32-bit accumulate operand. Optionally, the instruction can
186 /// exchange the halfwords of the second operand before performing the
187 /// arithmetic.
Sam Parker2200a9b2019-07-31 07:32:03 +0000188 bool MatchSMLAD(Function &F);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000189
190 public:
191 static char ID;
192
Sam Parker2200a9b2019-07-31 07:32:03 +0000193 ARMParallelDSP() : FunctionPass(ID) { }
Sam Parkera33e3112019-05-13 09:23:32 +0000194
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000195 void getAnalysisUsage(AnalysisUsage &AU) const override {
Sam Parker2200a9b2019-07-31 07:32:03 +0000196 FunctionPass::getAnalysisUsage(AU);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000197 AU.addRequired<AssumptionCacheTracker>();
198 AU.addRequired<ScalarEvolutionWrapperPass>();
199 AU.addRequired<AAResultsWrapperPass>();
200 AU.addRequired<TargetLibraryInfoWrapperPass>();
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000201 AU.addRequired<DominatorTreeWrapperPass>();
202 AU.addRequired<TargetPassConfig>();
Sam Parker2200a9b2019-07-31 07:32:03 +0000203 AU.addPreserved<ScalarEvolutionWrapperPass>();
204 AU.addPreserved<GlobalsAAWrapperPass>();
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000205 AU.setPreservesCFG();
206 }
207
Sam Parker2200a9b2019-07-31 07:32:03 +0000208 bool runOnFunction(Function &F) override {
Sjoerd Meijer3c859b32018-08-14 07:43:49 +0000209 if (DisableParallelDSP)
210 return false;
Sam Parker2200a9b2019-07-31 07:32:03 +0000211 if (skipFunction(F))
Eli Friedmanb27fc952019-07-23 20:48:46 +0000212 return false;
213
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000214 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
215 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
216 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
217 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000218 auto &TPC = getAnalysis<TargetPassConfig>();
219
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000220 M = F.getParent();
221 DL = &M->getDataLayout();
222
223 auto &TM = TPC.getTM<TargetMachine>();
224 auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
225
226 if (!ST->allowsUnalignedMem()) {
227 LLVM_DEBUG(dbgs() << "Unaligned memory access not supported: not "
228 "running pass ARMParallelDSP\n");
229 return false;
230 }
231
232 if (!ST->hasDSP()) {
233 LLVM_DEBUG(dbgs() << "DSP extension not enabled: not running pass "
234 "ARMParallelDSP\n");
235 return false;
236 }
237
Sam Parker9e730202019-03-15 10:19:32 +0000238 if (!ST->isLittle()) {
239 LLVM_DEBUG(dbgs() << "Only supporting little endian: not running pass "
Sam Parkera33e3112019-05-13 09:23:32 +0000240 << "ARMParallelDSP\n");
Sam Parker9e730202019-03-15 10:19:32 +0000241 return false;
242 }
243
Sam Parkera023c7a2018-09-12 09:17:44 +0000244 LLVM_DEBUG(dbgs() << "\n== Parallel DSP pass ==\n");
245 LLVM_DEBUG(dbgs() << " - " << F.getName() << "\n\n");
Sam Parker453ba912018-11-09 09:18:00 +0000246
Sam Parker2200a9b2019-07-31 07:32:03 +0000247 bool Changes = MatchSMLAD(F);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000248 return Changes;
249 }
250 };
251}
252
Sam Parkerffc16812018-07-03 12:44:16 +0000253template<typename MemInst>
254static bool AreSequentialAccesses(MemInst *MemOp0, MemInst *MemOp1,
Sam Parker453ba912018-11-09 09:18:00 +0000255 const DataLayout &DL, ScalarEvolution &SE) {
Sam Parker4c4ff132019-03-14 11:14:13 +0000256 if (isConsecutiveAccess(MemOp0, MemOp1, DL, SE))
Sam Parkerffc16812018-07-03 12:44:16 +0000257 return true;
Sam Parkerffc16812018-07-03 12:44:16 +0000258 return false;
259}
260
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000261bool ARMParallelDSP::AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1,
Sam Parkerffc16812018-07-03 12:44:16 +0000262 MemInstList &VecMem) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000263 if (!Ld0 || !Ld1)
264 return false;
265
Sam Parker4c4ff132019-03-14 11:14:13 +0000266 if (!LoadPairs.count(Ld0) || LoadPairs[Ld0] != Ld1)
267 return false;
268
269 LLVM_DEBUG(dbgs() << "Loads are sequential and valid:\n";
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000270 dbgs() << "Ld0:"; Ld0->dump();
271 dbgs() << "Ld1:"; Ld1->dump();
272 );
273
Sam Parker453ba912018-11-09 09:18:00 +0000274 VecMem.clear();
275 VecMem.push_back(Ld0);
276 VecMem.push_back(Ld1);
277 return true;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000278}
279
Sam Parker85ad78b2019-07-11 07:47:50 +0000280// MaxBitwidth: the maximum supported bitwidth of the elements in the DSP
281// instructions, which is set to 16. So here we should collect all i8 and i16
282// narrow operations.
283// TODO: we currently only collect i16, and will support i8 later, so that's
284// why we check that types are equal to MaxBitWidth, and not <= MaxBitWidth.
285template<unsigned MaxBitWidth>
286bool ARMParallelDSP::IsNarrowSequence(Value *V, ValueList &VL) {
Sam Parker74400652019-07-26 10:57:42 +0000287 if (auto *SExt = dyn_cast<SExtInst>(V)) {
288 if (SExt->getSrcTy()->getIntegerBitWidth() != MaxBitWidth)
Sam Parker85ad78b2019-07-11 07:47:50 +0000289 return false;
290
Sam Parker74400652019-07-26 10:57:42 +0000291 if (auto *Ld = dyn_cast<LoadInst>(SExt->getOperand(0))) {
Sam Parker85ad78b2019-07-11 07:47:50 +0000292 // Check that these load could be paired.
293 if (!LoadPairs.count(Ld) && !OffsetLoads.count(Ld))
294 return false;
295
Sam Parker74400652019-07-26 10:57:42 +0000296 VL.push_back(Ld);
297 VL.push_back(SExt);
Sam Parker85ad78b2019-07-11 07:47:50 +0000298 return true;
299 }
300 }
301 return false;
302}
303
Sam Parkera33e3112019-05-13 09:23:32 +0000304/// Iterate through the block and record base, offset pairs of loads which can
305/// be widened into a single load.
306bool ARMParallelDSP::RecordMemoryOps(BasicBlock *BB) {
Sam Parker453ba912018-11-09 09:18:00 +0000307 SmallVector<LoadInst*, 8> Loads;
Sam Parkera33e3112019-05-13 09:23:32 +0000308 SmallVector<Instruction*, 8> Writes;
Sam Parker2200a9b2019-07-31 07:32:03 +0000309 LoadPairs.clear();
310 WideLoads.clear();
Sam Parkera33e3112019-05-13 09:23:32 +0000311
312 // Collect loads and instruction that may write to memory. For now we only
313 // record loads which are simple, sign-extended and have a single user.
314 // TODO: Allow zero-extended loads.
Sam Parker4c4ff132019-03-14 11:14:13 +0000315 for (auto &I : *BB) {
Sam Parkera33e3112019-05-13 09:23:32 +0000316 if (I.mayWriteToMemory())
317 Writes.push_back(&I);
Sam Parker453ba912018-11-09 09:18:00 +0000318 auto *Ld = dyn_cast<LoadInst>(&I);
Sam Parker4c4ff132019-03-14 11:14:13 +0000319 if (!Ld || !Ld->isSimple() ||
320 !Ld->hasOneUse() || !isa<SExtInst>(Ld->user_back()))
Sam Parker453ba912018-11-09 09:18:00 +0000321 continue;
322 Loads.push_back(Ld);
323 }
324
Sam Parkera33e3112019-05-13 09:23:32 +0000325 using InstSet = std::set<Instruction*>;
326 using DepMap = std::map<Instruction*, InstSet>;
327 DepMap RAWDeps;
328
329 // Record any writes that may alias a load.
330 const auto Size = LocationSize::unknown();
331 for (auto Read : Loads) {
332 for (auto Write : Writes) {
333 MemoryLocation ReadLoc =
334 MemoryLocation(Read->getPointerOperand(), Size);
335
336 if (!isModOrRefSet(intersectModRef(AA->getModRefInfo(Write, ReadLoc),
337 ModRefInfo::ModRef)))
338 continue;
339 if (DT->dominates(Write, Read))
340 RAWDeps[Read].insert(Write);
341 }
342 }
343
344 // Check whether there's not a write between the two loads which would
345 // prevent them from being safely merged.
346 auto SafeToPair = [&](LoadInst *Base, LoadInst *Offset) {
347 LoadInst *Dominator = DT->dominates(Base, Offset) ? Base : Offset;
348 LoadInst *Dominated = DT->dominates(Base, Offset) ? Offset : Base;
349
350 if (RAWDeps.count(Dominated)) {
351 InstSet &WritesBefore = RAWDeps[Dominated];
352
353 for (auto Before : WritesBefore) {
354
355 // We can't move the second load backward, past a write, to merge
356 // with the first load.
357 if (DT->dominates(Dominator, Before))
358 return false;
359 }
360 }
361 return true;
362 };
363
364 // Record base, offset load pairs.
365 for (auto *Base : Loads) {
366 for (auto *Offset : Loads) {
367 if (Base == Offset)
Sam Parker453ba912018-11-09 09:18:00 +0000368 continue;
369
Sam Parkera33e3112019-05-13 09:23:32 +0000370 if (AreSequentialAccesses<LoadInst>(Base, Offset, *DL, *SE) &&
371 SafeToPair(Base, Offset)) {
372 LoadPairs[Base] = Offset;
Sam Parker85ad78b2019-07-11 07:47:50 +0000373 OffsetLoads.insert(Offset);
Sam Parker4c4ff132019-03-14 11:14:13 +0000374 break;
Sam Parker453ba912018-11-09 09:18:00 +0000375 }
376 }
377 }
Sam Parker4c4ff132019-03-14 11:14:13 +0000378
379 LLVM_DEBUG(if (!LoadPairs.empty()) {
380 dbgs() << "Consecutive load pairs:\n";
381 for (auto &MapIt : LoadPairs) {
382 LLVM_DEBUG(dbgs() << *MapIt.first << ", "
383 << *MapIt.second << "\n");
384 }
385 });
Sam Parker453ba912018-11-09 09:18:00 +0000386 return LoadPairs.size() > 1;
387}
388
Sam Parker2200a9b2019-07-31 07:32:03 +0000389// The pass needs to identify integer add/sub reductions of 16-bit vector
Sam Parker85ad78b2019-07-11 07:47:50 +0000390// multiplications.
391// To use SMLAD:
392// 1) we first need to find integer add then look for this pattern:
393//
394// acc0 = ...
395// ld0 = load i16
396// sext0 = sext i16 %ld0 to i32
397// ld1 = load i16
398// sext1 = sext i16 %ld1 to i32
399// mul0 = mul %sext0, %sext1
400// ld2 = load i16
401// sext2 = sext i16 %ld2 to i32
402// ld3 = load i16
403// sext3 = sext i16 %ld3 to i32
404// mul1 = mul i32 %sext2, %sext3
405// add0 = add i32 %mul0, %acc0
406// acc1 = add i32 %add0, %mul1
407//
408// Which can be selected to:
409//
410// ldr r0
411// ldr r1
412// smlad r2, r0, r1, r2
413//
414// If constants are used instead of loads, these will need to be hoisted
415// out and into a register.
416//
417// If loop invariants are used instead of loads, these need to be packed
418// before the loop begins.
419//
Sam Parker2200a9b2019-07-31 07:32:03 +0000420bool ARMParallelDSP::MatchSMLAD(Function &F) {
Sam Parker85ad78b2019-07-11 07:47:50 +0000421 // Search recursively back through the operands to find a tree of values that
422 // form a multiply-accumulate chain. The search records the Add and Mul
423 // instructions that form the reduction and allows us to find a single value
424 // to be used as the initial input to the accumlator.
Sam Parker2200a9b2019-07-31 07:32:03 +0000425 std::function<bool(Value*, BasicBlock*, Reduction&)> Search = [&]
426 (Value *V, BasicBlock *BB, Reduction &R) -> bool {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000427
Sam Parker85ad78b2019-07-11 07:47:50 +0000428 // If we find a non-instruction, try to use it as the initial accumulator
429 // value. This may have already been found during the search in which case
430 // this function will return false, signaling a search fail.
431 auto *I = dyn_cast<Instruction>(V);
432 if (!I)
433 return R.InsertAcc(V);
Sam Parker453ba912018-11-09 09:18:00 +0000434
Sam Parker2200a9b2019-07-31 07:32:03 +0000435 if (I->getParent() != BB)
436 return false;
437
Sam Parker85ad78b2019-07-11 07:47:50 +0000438 switch (I->getOpcode()) {
439 default:
440 break;
441 case Instruction::PHI:
442 // Could be the accumulator value.
443 return R.InsertAcc(V);
444 case Instruction::Add: {
445 // Adds should be adding together two muls, or another add and a mul to
446 // be within the mac chain. One of the operands may also be the
447 // accumulator value at which point we should stop searching.
Sam Parker2200a9b2019-07-31 07:32:03 +0000448 bool ValidLHS = Search(I->getOperand(0), BB, R);
449 bool ValidRHS = Search(I->getOperand(1), BB, R);
Sam Parker85ad78b2019-07-11 07:47:50 +0000450 if (!ValidLHS && !ValidLHS)
451 return false;
452 else if (ValidLHS && ValidRHS) {
453 R.InsertAdd(I);
454 return true;
455 } else {
456 R.InsertAdd(I);
457 return R.InsertAcc(I);
458 }
459 }
460 case Instruction::Mul: {
461 Value *MulOp0 = I->getOperand(0);
462 Value *MulOp1 = I->getOperand(1);
463 if (isa<SExtInst>(MulOp0) && isa<SExtInst>(MulOp1)) {
464 ValueList LHS;
465 ValueList RHS;
466 if (IsNarrowSequence<16>(MulOp0, LHS) &&
467 IsNarrowSequence<16>(MulOp1, RHS)) {
468 R.InsertMul(I, LHS, RHS);
469 return true;
470 }
471 }
472 return false;
473 }
474 case Instruction::SExt:
Sam Parker2200a9b2019-07-31 07:32:03 +0000475 return Search(I->getOperand(0), BB, R);
Sam Parker85ad78b2019-07-11 07:47:50 +0000476 }
477 return false;
478 };
479
480 bool Changed = false;
Sam Parker85ad78b2019-07-11 07:47:50 +0000481
Sam Parker2200a9b2019-07-31 07:32:03 +0000482 for (auto &BB : F) {
483 SmallPtrSet<Instruction*, 4> AllAdds;
484 if (!RecordMemoryOps(&BB))
Sam Parker85ad78b2019-07-11 07:47:50 +0000485 continue;
486
Sam Parker2200a9b2019-07-31 07:32:03 +0000487 for (Instruction &I : reverse(BB)) {
488 if (I.getOpcode() != Instruction::Add)
489 continue;
Sam Parker85ad78b2019-07-11 07:47:50 +0000490
Sam Parker2200a9b2019-07-31 07:32:03 +0000491 if (AllAdds.count(&I))
492 continue;
Sam Parker85ad78b2019-07-11 07:47:50 +0000493
Sam Parker2200a9b2019-07-31 07:32:03 +0000494 const auto *Ty = I.getType();
495 if (!Ty->isIntegerTy(32) && !Ty->isIntegerTy(64))
496 continue;
Sam Parker85ad78b2019-07-11 07:47:50 +0000497
Sam Parker2200a9b2019-07-31 07:32:03 +0000498 Reduction R(&I);
499 if (!Search(&I, &BB, R))
500 continue;
Sam Parker85ad78b2019-07-11 07:47:50 +0000501
Sam Parker2200a9b2019-07-31 07:32:03 +0000502 if (!CreateParallelPairs(R))
503 continue;
504
505 InsertParallelMACs(R);
506 Changed = true;
507 AllAdds.insert(R.getAdds().begin(), R.getAdds().end());
508 }
Sam Parker85ad78b2019-07-11 07:47:50 +0000509 }
510
511 return Changed;
512}
513
514bool ARMParallelDSP::CreateParallelPairs(Reduction &R) {
515
516 // Not enough mul operations to make a pair.
517 if (R.getMuls().size() < 2)
518 return false;
519
520 // Check that the muls operate directly upon sign extended loads.
Sam Parker414dd1c2019-07-29 08:41:51 +0000521 for (auto &MulCand : R.getMuls()) {
522 if (!MulCand->HasTwoLoadInputs())
Sam Parker85ad78b2019-07-11 07:47:50 +0000523 return false;
Sam Parker85ad78b2019-07-11 07:47:50 +0000524 }
525
Sam Parker414dd1c2019-07-29 08:41:51 +0000526 auto CanPair = [&](Reduction &R, MulCandidate *PMul0, MulCandidate *PMul1) {
Sam Parker453ba912018-11-09 09:18:00 +0000527 // The first elements of each vector should be loads with sexts. If we
528 // find that its two pairs of consecutive loads, then these can be
529 // transformed into two wider loads and the users can be replaced with
530 // DSP intrinsics.
Sam Parker414dd1c2019-07-29 08:41:51 +0000531 auto Ld0 = static_cast<LoadInst*>(PMul0->LHS);
532 auto Ld1 = static_cast<LoadInst*>(PMul1->LHS);
533 auto Ld2 = static_cast<LoadInst*>(PMul0->RHS);
534 auto Ld3 = static_cast<LoadInst*>(PMul1->RHS);
Sam Parker453ba912018-11-09 09:18:00 +0000535
Sam Parker414dd1c2019-07-29 08:41:51 +0000536 LLVM_DEBUG(dbgs() << "Loads:\n"
537 << " - " << *Ld0 << "\n"
538 << " - " << *Ld1 << "\n"
539 << " - " << *Ld2 << "\n"
540 << " - " << *Ld3 << "\n");
Sam Parker453ba912018-11-09 09:18:00 +0000541
Sam Parker414dd1c2019-07-29 08:41:51 +0000542 if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd)) {
543 if (AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
Sam Parker453ba912018-11-09 09:18:00 +0000544 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
Sam Parker414dd1c2019-07-29 08:41:51 +0000545 R.AddMulPair(PMul0, PMul1);
546 return true;
547 } else if (AreSequentialLoads(Ld3, Ld2, PMul1->VecLd)) {
548 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
549 LLVM_DEBUG(dbgs() << " exchanging Ld2 and Ld3\n");
550 PMul1->Exchange = true;
551 R.AddMulPair(PMul0, PMul1);
Sam Parker453ba912018-11-09 09:18:00 +0000552 return true;
553 }
Sam Parker414dd1c2019-07-29 08:41:51 +0000554 } else if (AreSequentialLoads(Ld1, Ld0, PMul0->VecLd) &&
555 AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
556 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
557 LLVM_DEBUG(dbgs() << " exchanging Ld0 and Ld1\n");
558 LLVM_DEBUG(dbgs() << " and swapping muls\n");
559 PMul0->Exchange = true;
560 // Only the second operand can be exchanged, so swap the muls.
561 R.AddMulPair(PMul1, PMul0);
562 return true;
Sam Parker453ba912018-11-09 09:18:00 +0000563 }
564 return false;
565 };
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000566
Sam Parker414dd1c2019-07-29 08:41:51 +0000567 MulCandList &Muls = R.getMuls();
Sam Parker85ad78b2019-07-11 07:47:50 +0000568 const unsigned Elems = Muls.size();
Sam Parkera023c7a2018-09-12 09:17:44 +0000569 SmallPtrSet<const Instruction*, 4> Paired;
570 for (unsigned i = 0; i < Elems; ++i) {
Sam Parker414dd1c2019-07-29 08:41:51 +0000571 MulCandidate *PMul0 = static_cast<MulCandidate*>(Muls[i].get());
Sam Parkera023c7a2018-09-12 09:17:44 +0000572 if (Paired.count(PMul0->Root))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000573 continue;
574
Sam Parkera023c7a2018-09-12 09:17:44 +0000575 for (unsigned j = 0; j < Elems; ++j) {
576 if (i == j)
577 continue;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000578
Sam Parker414dd1c2019-07-29 08:41:51 +0000579 MulCandidate *PMul1 = static_cast<MulCandidate*>(Muls[j].get());
Sam Parkera023c7a2018-09-12 09:17:44 +0000580 if (Paired.count(PMul1->Root))
581 continue;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000582
Sam Parkera023c7a2018-09-12 09:17:44 +0000583 const Instruction *Mul0 = PMul0->Root;
584 const Instruction *Mul1 = PMul1->Root;
585 if (Mul0 == Mul1)
586 continue;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000587
Sam Parkera023c7a2018-09-12 09:17:44 +0000588 assert(PMul0 != PMul1 && "expected different chains");
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000589
Sam Parker85ad78b2019-07-11 07:47:50 +0000590 if (CanPair(R, PMul0, PMul1)) {
Sam Parkera023c7a2018-09-12 09:17:44 +0000591 Paired.insert(Mul0);
592 Paired.insert(Mul1);
593 break;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000594 }
595 }
596 }
Sam Parker85ad78b2019-07-11 07:47:50 +0000597 return !R.getMulPairs().empty();
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000598}
599
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000600
Sam Parker85ad78b2019-07-11 07:47:50 +0000601void ARMParallelDSP::InsertParallelMACs(Reduction &R) {
602
Sam Parker7ca8c6f2019-08-01 08:17:51 +0000603 auto CreateSMLAD = [&](LoadInst* WideLd0, LoadInst *WideLd1,
604 Value *Acc, bool Exchange,
605 Instruction *InsertAfter) {
Sam Parker85ad78b2019-07-11 07:47:50 +0000606 // Replace the reduction chain with an intrinsic call
Sam Parker85ad78b2019-07-11 07:47:50 +0000607
608 Value* Args[] = { WideLd0, WideLd1, Acc };
609 Function *SMLAD = nullptr;
610 if (Exchange)
611 SMLAD = Acc->getType()->isIntegerTy(32) ?
612 Intrinsic::getDeclaration(M, Intrinsic::arm_smladx) :
613 Intrinsic::getDeclaration(M, Intrinsic::arm_smlaldx);
614 else
615 SMLAD = Acc->getType()->isIntegerTy(32) ?
616 Intrinsic::getDeclaration(M, Intrinsic::arm_smlad) :
617 Intrinsic::getDeclaration(M, Intrinsic::arm_smlald);
618
619 IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
620 ++BasicBlock::iterator(InsertAfter));
621 Instruction *Call = Builder.CreateCall(SMLAD, Args);
622 NumSMLAD++;
623 return Call;
624 };
625
626 Instruction *InsertAfter = R.getRoot();
627 Value *Acc = R.getAccumulator();
628 if (!Acc)
629 Acc = ConstantInt::get(IntegerType::get(M->getContext(), 32), 0);
630
Sam Parker7ca8c6f2019-08-01 08:17:51 +0000631 IntegerType *Ty = IntegerType::get(M->getContext(), 32);
Sam Parker85ad78b2019-07-11 07:47:50 +0000632 LLVM_DEBUG(dbgs() << "Root: " << *InsertAfter << "\n"
633 << "Acc: " << *Acc << "\n");
634 for (auto &Pair : R.getMulPairs()) {
Sam Parker7ca8c6f2019-08-01 08:17:51 +0000635 MulCandidate *LHSMul = Pair.first;
636 MulCandidate *RHSMul = Pair.second;
Sam Parker85ad78b2019-07-11 07:47:50 +0000637 LLVM_DEBUG(dbgs() << "Muls:\n"
Sam Parker7ca8c6f2019-08-01 08:17:51 +0000638 << "- " << *LHSMul->Root << "\n"
639 << "- " << *RHSMul->Root << "\n");
640 LoadInst *BaseLHS = LHSMul->getBaseLoad();
641 LoadInst *BaseRHS = RHSMul->getBaseLoad();
642 LoadInst *WideLHS = WideLoads.count(BaseLHS) ?
643 WideLoads[BaseLHS]->getLoad() : CreateWideLoad(LHSMul->VecLd, Ty);
644 LoadInst *WideRHS = WideLoads.count(BaseRHS) ?
645 WideLoads[BaseRHS]->getLoad() : CreateWideLoad(RHSMul->VecLd, Ty);
Sam Parkera023c7a2018-09-12 09:17:44 +0000646
Sam Parker7ca8c6f2019-08-01 08:17:51 +0000647 Acc = CreateSMLAD(WideLHS, WideRHS, Acc, RHSMul->Exchange, InsertAfter);
Sam Parker85ad78b2019-07-11 07:47:50 +0000648 InsertAfter = cast<Instruction>(Acc);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000649 }
Sam Parker85ad78b2019-07-11 07:47:50 +0000650 R.UpdateRoot(cast<Instruction>(Acc));
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000651}
652
Sam Parkera33e3112019-05-13 09:23:32 +0000653LoadInst* ARMParallelDSP::CreateWideLoad(SmallVectorImpl<LoadInst*> &Loads,
654 IntegerType *LoadTy) {
Sam Parker4c4ff132019-03-14 11:14:13 +0000655 assert(Loads.size() == 2 && "currently only support widening two loads");
Sam Parkera33e3112019-05-13 09:23:32 +0000656
657 LoadInst *Base = Loads[0];
658 LoadInst *Offset = Loads[1];
659
660 Instruction *BaseSExt = dyn_cast<SExtInst>(Base->user_back());
661 Instruction *OffsetSExt = dyn_cast<SExtInst>(Offset->user_back());
662
663 assert((BaseSExt && OffsetSExt)
664 && "Loads should have a single, extending, user");
665
666 std::function<void(Value*, Value*)> MoveBefore =
667 [&](Value *A, Value *B) -> void {
668 if (!isa<Instruction>(A) || !isa<Instruction>(B))
669 return;
670
671 auto *Source = cast<Instruction>(A);
672 auto *Sink = cast<Instruction>(B);
673
674 if (DT->dominates(Source, Sink) ||
675 Source->getParent() != Sink->getParent() ||
676 isa<PHINode>(Source) || isa<PHINode>(Sink))
677 return;
678
679 Source->moveBefore(Sink);
Sam Parkeraeb21b92019-07-24 09:38:39 +0000680 for (auto &Op : Source->operands())
681 MoveBefore(Op, Source);
Sam Parkera33e3112019-05-13 09:23:32 +0000682 };
683
684 // Insert the load at the point of the original dominating load.
685 LoadInst *DomLoad = DT->dominates(Base, Offset) ? Base : Offset;
686 IRBuilder<NoFolder> IRB(DomLoad->getParent(),
687 ++BasicBlock::iterator(DomLoad));
688
689 // Bitcast the pointer to a wider type and create the wide load, while making
690 // sure to maintain the original alignment as this prevents ldrd from being
691 // generated when it could be illegal due to memory alignment.
692 const unsigned AddrSpace = DomLoad->getPointerAddressSpace();
693 Value *VecPtr = IRB.CreateBitCast(Base->getPointerOperand(),
Eli Friedmanb09c7782018-10-18 19:34:30 +0000694 LoadTy->getPointerTo(AddrSpace));
Sam Parker4c4ff132019-03-14 11:14:13 +0000695 LoadInst *WideLoad = IRB.CreateAlignedLoad(LoadTy, VecPtr,
Sam Parkera33e3112019-05-13 09:23:32 +0000696 Base->getAlignment());
Sam Parker4c4ff132019-03-14 11:14:13 +0000697
Sam Parkera33e3112019-05-13 09:23:32 +0000698 // Make sure everything is in the correct order in the basic block.
699 MoveBefore(Base->getPointerOperand(), VecPtr);
700 MoveBefore(VecPtr, WideLoad);
Sam Parker4c4ff132019-03-14 11:14:13 +0000701
702 // From the wide load, create two values that equal the original two loads.
Sam Parkera33e3112019-05-13 09:23:32 +0000703 // Loads[0] needs trunc while Loads[1] needs a lshr and trunc.
704 // TODO: Support big-endian as well.
705 Value *Bottom = IRB.CreateTrunc(WideLoad, Base->getType());
706 BaseSExt->setOperand(0, Bottom);
Sam Parker4c4ff132019-03-14 11:14:13 +0000707
Sam Parkera33e3112019-05-13 09:23:32 +0000708 IntegerType *OffsetTy = cast<IntegerType>(Offset->getType());
709 Value *ShiftVal = ConstantInt::get(LoadTy, OffsetTy->getBitWidth());
Sam Parker4c4ff132019-03-14 11:14:13 +0000710 Value *Top = IRB.CreateLShr(WideLoad, ShiftVal);
Sam Parkera33e3112019-05-13 09:23:32 +0000711 Value *Trunc = IRB.CreateTrunc(Top, OffsetTy);
712 OffsetSExt->setOperand(0, Trunc);
Sam Parker4c4ff132019-03-14 11:14:13 +0000713
Sam Parkera33e3112019-05-13 09:23:32 +0000714 WideLoads.emplace(std::make_pair(Base,
Sam Parker4c4ff132019-03-14 11:14:13 +0000715 make_unique<WidenedLoad>(Loads, WideLoad)));
716 return WideLoad;
Eli Friedmanb09c7782018-10-18 19:34:30 +0000717}
718
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000719Pass *llvm::createARMParallelDSPPass() {
720 return new ARMParallelDSP();
721}
722
723char ARMParallelDSP::ID = 0;
724
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000725INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp",
Sam Parker2200a9b2019-07-31 07:32:03 +0000726 "Transform functions to use DSP intrinsics", false, false)
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000727INITIALIZE_PASS_END(ARMParallelDSP, "arm-parallel-dsp",
Sam Parker2200a9b2019-07-31 07:32:03 +0000728 "Transform functions to use DSP intrinsics", false, false)