1 //===- ARMParallelDSP.cpp - Parallel DSP Pass -----------------------------===//
2 //
3 // 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
6 //
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.
13 /// This pass runs only when unaligned accesses is supported/enabled.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "ARM.h"
18 #include "ARMSubtarget.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/GlobalsModRef.h"
24 #include "llvm/Analysis/LoopAccessAnalysis.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicsARM.h"
29 #include "llvm/IR/NoFolder.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Pass.h"
32 #include "llvm/PassRegistry.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 
37 using namespace llvm;
38 using namespace PatternMatch;
39 
40 #define DEBUG_TYPE "arm-parallel-dsp"
41 
42 STATISTIC(NumSMLAD , "Number of smlad instructions generated");
43 
44 static cl::opt<bool>
45 DisableParallelDSP("disable-arm-parallel-dsp", cl::Hidden, cl::init(false),
46                    cl::desc("Disable the ARM Parallel DSP pass"));
47 
48 static cl::opt<unsigned>
49 NumLoadLimit("arm-parallel-dsp-load-limit", cl::Hidden, cl::init(16),
50              cl::desc("Limit the number of loads analysed"));
51 
52 namespace {
53   struct MulCandidate;
54   class Reduction;
55 
56   using MulCandList = SmallVector<std::unique_ptr<MulCandidate>, 8>;
57   using MemInstList = SmallVectorImpl<LoadInst*>;
58   using MulPairList = SmallVector<std::pair<MulCandidate*, MulCandidate*>, 8>;
59 
60   // 'MulCandidate' holds the multiplication instructions that are candidates
61   // for parallel execution.
62   struct MulCandidate {
63     Instruction   *Root;
64     Value*        LHS;
65     Value*        RHS;
66     bool          Exchange = false;
67     bool          ReadOnly = true;
68     bool          Paired = false;
69     SmallVector<LoadInst*, 2> VecLd;    // Container for loads to widen.
70 
71     MulCandidate(Instruction *I, Value *lhs, Value *rhs) :
72       Root(I), LHS(lhs), RHS(rhs) { }
73 
74     bool HasTwoLoadInputs() const {
75       return isa<LoadInst>(LHS) && isa<LoadInst>(RHS);
76     }
77 
78     LoadInst *getBaseLoad() const {
79       return VecLd.front();
80     }
81   };
82 
83   /// Represent a sequence of multiply-accumulate operations with the aim to
84   /// perform the multiplications in parallel.
85   class Reduction {
86     Instruction     *Root = nullptr;
87     Value           *Acc = nullptr;
88     MulCandList     Muls;
89     MulPairList        MulPairs;
90     SetVector<Instruction*> Adds;
91 
92   public:
93     Reduction() = delete;
94 
95     Reduction (Instruction *Add) : Root(Add) { }
96 
97     /// Record an Add instruction that is a part of the this reduction.
98     void InsertAdd(Instruction *I) { Adds.insert(I); }
99 
100     /// Create MulCandidates, each rooted at a Mul instruction, that is a part
101     /// of this reduction.
102     void InsertMuls() {
103       auto GetMulOperand = [](Value *V) -> Instruction* {
104         if (auto *SExt = dyn_cast<SExtInst>(V)) {
105           if (auto *I = dyn_cast<Instruction>(SExt->getOperand(0)))
106             if (I->getOpcode() == Instruction::Mul)
107               return I;
108         } else if (auto *I = dyn_cast<Instruction>(V)) {
109           if (I->getOpcode() == Instruction::Mul)
110             return I;
111         }
112         return nullptr;
113       };
114 
115       auto InsertMul = [this](Instruction *I) {
116         Value *LHS = cast<Instruction>(I->getOperand(0))->getOperand(0);
117         Value *RHS = cast<Instruction>(I->getOperand(1))->getOperand(0);
118         Muls.push_back(std::make_unique<MulCandidate>(I, LHS, RHS));
119       };
120 
121       for (auto *Add : Adds) {
122         if (Add == Acc)
123           continue;
124         if (auto *Mul = GetMulOperand(Add->getOperand(0)))
125           InsertMul(Mul);
126         if (auto *Mul = GetMulOperand(Add->getOperand(1)))
127           InsertMul(Mul);
128       }
129     }
130 
131     /// Add the incoming accumulator value, returns true if a value had not
132     /// already been added. Returning false signals to the user that this
133     /// reduction already has a value to initialise the accumulator.
134     bool InsertAcc(Value *V) {
135       if (Acc)
136         return false;
137       Acc = V;
138       return true;
139     }
140 
141     /// Set two MulCandidates, rooted at muls, that can be executed as a single
142     /// parallel operation.
143     void AddMulPair(MulCandidate *Mul0, MulCandidate *Mul1,
144                     bool Exchange = false) {
145       LLVM_DEBUG(dbgs() << "Pairing:\n"
146                  << *Mul0->Root << "\n"
147                  << *Mul1->Root << "\n");
148       Mul0->Paired = true;
149       Mul1->Paired = true;
150       if (Exchange)
151         Mul1->Exchange = true;
152       MulPairs.push_back(std::make_pair(Mul0, Mul1));
153     }
154 
155     /// Return true if enough mul operations are found that can be executed in
156     /// parallel.
157     bool CreateParallelPairs();
158 
159     /// Return the add instruction which is the root of the reduction.
160     Instruction *getRoot() { return Root; }
161 
162     bool is64Bit() const { return Root->getType()->isIntegerTy(64); }
163 
164     Type *getType() const { return Root->getType(); }
165 
166     /// Return the incoming value to be accumulated. This maybe null.
167     Value *getAccumulator() { return Acc; }
168 
169     /// Return the set of adds that comprise the reduction.
170     SetVector<Instruction*> &getAdds() { return Adds; }
171 
172     /// Return the MulCandidate, rooted at mul instruction, that comprise the
173     /// the reduction.
174     MulCandList &getMuls() { return Muls; }
175 
176     /// Return the MulCandidate, rooted at mul instructions, that have been
177     /// paired for parallel execution.
178     MulPairList &getMulPairs() { return MulPairs; }
179 
180     /// To finalise, replace the uses of the root with the intrinsic call.
181     void UpdateRoot(Instruction *SMLAD) {
182       Root->replaceAllUsesWith(SMLAD);
183     }
184 
185     void dump() {
186       LLVM_DEBUG(dbgs() << "Reduction:\n";
187         for (auto *Add : Adds)
188           LLVM_DEBUG(dbgs() << *Add << "\n");
189         for (auto &Mul : Muls)
190           LLVM_DEBUG(dbgs() << *Mul->Root << "\n"
191                      << "  " << *Mul->LHS << "\n"
192                      << "  " << *Mul->RHS << "\n");
193         LLVM_DEBUG(if (Acc) dbgs() << "Acc in: " << *Acc << "\n")
194       );
195     }
196   };
197 
198   class WidenedLoad {
199     LoadInst *NewLd = nullptr;
200     SmallVector<LoadInst*, 4> Loads;
201 
202   public:
203     WidenedLoad(SmallVectorImpl<LoadInst*> &Lds, LoadInst *Wide)
204       : NewLd(Wide) {
205       for (auto *I : Lds)
206         Loads.push_back(I);
207     }
208     LoadInst *getLoad() {
209       return NewLd;
210     }
211   };
212 
213   class ARMParallelDSP : public FunctionPass {
214     ScalarEvolution   *SE;
215     AliasAnalysis     *AA;
216     TargetLibraryInfo *TLI;
217     DominatorTree     *DT;
218     const DataLayout  *DL;
219     Module            *M;
220     std::map<LoadInst*, LoadInst*> LoadPairs;
221     SmallPtrSet<LoadInst*, 4> OffsetLoads;
222     std::map<LoadInst*, std::unique_ptr<WidenedLoad>> WideLoads;
223 
224     template<unsigned>
225     bool IsNarrowSequence(Value *V);
226     bool Search(Value *V, BasicBlock *BB, Reduction &R);
227     bool RecordMemoryOps(BasicBlock *BB);
228     void InsertParallelMACs(Reduction &Reduction);
229     bool AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1, MemInstList &VecMem);
230     LoadInst* CreateWideLoad(MemInstList &Loads, IntegerType *LoadTy);
231     bool CreateParallelPairs(Reduction &R);
232 
233     /// Try to match and generate: SMLAD, SMLADX - Signed Multiply Accumulate
234     /// Dual performs two signed 16x16-bit multiplications. It adds the
235     /// products to a 32-bit accumulate operand. Optionally, the instruction can
236     /// exchange the halfwords of the second operand before performing the
237     /// arithmetic.
238     bool MatchSMLAD(Function &F);
239 
240   public:
241     static char ID;
242 
243     ARMParallelDSP() : FunctionPass(ID) { }
244 
245     void getAnalysisUsage(AnalysisUsage &AU) const override {
246       FunctionPass::getAnalysisUsage(AU);
247       AU.addRequired<AssumptionCacheTracker>();
248       AU.addRequired<ScalarEvolutionWrapperPass>();
249       AU.addRequired<AAResultsWrapperPass>();
250       AU.addRequired<TargetLibraryInfoWrapperPass>();
251       AU.addRequired<DominatorTreeWrapperPass>();
252       AU.addRequired<TargetPassConfig>();
253       AU.addPreserved<ScalarEvolutionWrapperPass>();
254       AU.addPreserved<GlobalsAAWrapperPass>();
255       AU.setPreservesCFG();
256     }
257 
258     bool runOnFunction(Function &F) override {
259       if (DisableParallelDSP)
260         return false;
261       if (skipFunction(F))
262         return false;
263 
264       SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
265       AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
266       TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
267       DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
268       auto &TPC = getAnalysis<TargetPassConfig>();
269 
270       M = F.getParent();
271       DL = &M->getDataLayout();
272 
273       auto &TM = TPC.getTM<TargetMachine>();
274       auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
275 
276       if (!ST->allowsUnalignedMem()) {
277         LLVM_DEBUG(dbgs() << "Unaligned memory access not supported: not "
278                              "running pass ARMParallelDSP\n");
279         return false;
280       }
281 
282       if (!ST->hasDSP()) {
283         LLVM_DEBUG(dbgs() << "DSP extension not enabled: not running pass "
284                              "ARMParallelDSP\n");
285         return false;
286       }
287 
288       if (!ST->isLittle()) {
289         LLVM_DEBUG(dbgs() << "Only supporting little endian: not running pass "
290                           << "ARMParallelDSP\n");
291         return false;
292       }
293 
294       LLVM_DEBUG(dbgs() << "\n== Parallel DSP pass ==\n");
295       LLVM_DEBUG(dbgs() << " - " << F.getName() << "\n\n");
296 
297       bool Changes = MatchSMLAD(F);
298       return Changes;
299     }
300   };
301 }
302 
303 template<typename MemInst>
304 static bool AreSequentialAccesses(MemInst *MemOp0, MemInst *MemOp1,
305                                   const DataLayout &DL, ScalarEvolution &SE) {
306   if (isConsecutiveAccess(MemOp0, MemOp1, DL, SE))
307     return true;
308   return false;
309 }
310 
311 bool ARMParallelDSP::AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1,
312                                         MemInstList &VecMem) {
313   if (!Ld0 || !Ld1)
314     return false;
315 
316   if (!LoadPairs.count(Ld0) || LoadPairs[Ld0] != Ld1)
317     return false;
318 
319   LLVM_DEBUG(dbgs() << "Loads are sequential and valid:\n";
320     dbgs() << "Ld0:"; Ld0->dump();
321     dbgs() << "Ld1:"; Ld1->dump();
322   );
323 
324   VecMem.clear();
325   VecMem.push_back(Ld0);
326   VecMem.push_back(Ld1);
327   return true;
328 }
329 
330 // MaxBitwidth: the maximum supported bitwidth of the elements in the DSP
331 // instructions, which is set to 16. So here we should collect all i8 and i16
332 // narrow operations.
333 // TODO: we currently only collect i16, and will support i8 later, so that's
334 // why we check that types are equal to MaxBitWidth, and not <= MaxBitWidth.
335 template<unsigned MaxBitWidth>
336 bool ARMParallelDSP::IsNarrowSequence(Value *V) {
337   if (auto *SExt = dyn_cast<SExtInst>(V)) {
338     if (SExt->getSrcTy()->getIntegerBitWidth() != MaxBitWidth)
339       return false;
340 
341     if (auto *Ld = dyn_cast<LoadInst>(SExt->getOperand(0))) {
342       // Check that this load could be paired.
343       return LoadPairs.count(Ld) || OffsetLoads.count(Ld);
344     }
345   }
346   return false;
347 }
348 
349 /// Iterate through the block and record base, offset pairs of loads which can
350 /// be widened into a single load.
351 bool ARMParallelDSP::RecordMemoryOps(BasicBlock *BB) {
352   SmallVector<LoadInst*, 8> Loads;
353   SmallVector<Instruction*, 8> Writes;
354   LoadPairs.clear();
355   WideLoads.clear();
356 
357   // Collect loads and instruction that may write to memory. For now we only
358   // record loads which are simple, sign-extended and have a single user.
359   // TODO: Allow zero-extended loads.
360   for (auto &I : *BB) {
361     if (I.mayWriteToMemory())
362       Writes.push_back(&I);
363     auto *Ld = dyn_cast<LoadInst>(&I);
364     if (!Ld || !Ld->isSimple() ||
365         !Ld->hasOneUse() || !isa<SExtInst>(Ld->user_back()))
366       continue;
367     Loads.push_back(Ld);
368   }
369 
370   if (Loads.empty() || Loads.size() > NumLoadLimit)
371     return false;
372 
373   using InstSet = std::set<Instruction*>;
374   using DepMap = std::map<Instruction*, InstSet>;
375   DepMap RAWDeps;
376 
377   // Record any writes that may alias a load.
378   const auto Size = LocationSize::beforeOrAfterPointer();
379   for (auto Write : Writes) {
380     for (auto Read : Loads) {
381       MemoryLocation ReadLoc =
382         MemoryLocation(Read->getPointerOperand(), Size);
383 
384       if (!isModOrRefSet(intersectModRef(AA->getModRefInfo(Write, ReadLoc),
385           ModRefInfo::ModRef)))
386         continue;
387       if (Write->comesBefore(Read))
388         RAWDeps[Read].insert(Write);
389     }
390   }
391 
392   // Check whether there's not a write between the two loads which would
393   // prevent them from being safely merged.
394   auto SafeToPair = [&](LoadInst *Base, LoadInst *Offset) {
395     bool BaseFirst = Base->comesBefore(Offset);
396     LoadInst *Dominator = BaseFirst ? Base : Offset;
397     LoadInst *Dominated = BaseFirst ? Offset : Base;
398 
399     if (RAWDeps.count(Dominated)) {
400       InstSet &WritesBefore = RAWDeps[Dominated];
401 
402       for (auto Before : WritesBefore) {
403         // We can't move the second load backward, past a write, to merge
404         // with the first load.
405         if (Dominator->comesBefore(Before))
406           return false;
407       }
408     }
409     return true;
410   };
411 
412   // Record base, offset load pairs.
413   for (auto *Base : Loads) {
414     for (auto *Offset : Loads) {
415       if (Base == Offset || OffsetLoads.count(Offset))
416         continue;
417 
418       if (AreSequentialAccesses<LoadInst>(Base, Offset, *DL, *SE) &&
419           SafeToPair(Base, Offset)) {
420         LoadPairs[Base] = Offset;
421         OffsetLoads.insert(Offset);
422         break;
423       }
424     }
425   }
426 
427   LLVM_DEBUG(if (!LoadPairs.empty()) {
428                dbgs() << "Consecutive load pairs:\n";
429                for (auto &MapIt : LoadPairs) {
430                  LLVM_DEBUG(dbgs() << *MapIt.first << ", "
431                             << *MapIt.second << "\n");
432                }
433              });
434   return LoadPairs.size() > 1;
435 }
436 
437 // Search recursively back through the operands to find a tree of values that
438 // form a multiply-accumulate chain. The search records the Add and Mul
439 // instructions that form the reduction and allows us to find a single value
440 // to be used as the initial input to the accumlator.
441 bool ARMParallelDSP::Search(Value *V, BasicBlock *BB, Reduction &R) {
442   // If we find a non-instruction, try to use it as the initial accumulator
443   // value. This may have already been found during the search in which case
444   // this function will return false, signaling a search fail.
445   auto *I = dyn_cast<Instruction>(V);
446   if (!I)
447     return R.InsertAcc(V);
448 
449   if (I->getParent() != BB)
450     return false;
451 
452   switch (I->getOpcode()) {
453   default:
454     break;
455   case Instruction::PHI:
456     // Could be the accumulator value.
457     return R.InsertAcc(V);
458   case Instruction::Add: {
459     // Adds should be adding together two muls, or another add and a mul to
460     // be within the mac chain. One of the operands may also be the
461     // accumulator value at which point we should stop searching.
462     R.InsertAdd(I);
463     Value *LHS = I->getOperand(0);
464     Value *RHS = I->getOperand(1);
465     bool ValidLHS = Search(LHS, BB, R);
466     bool ValidRHS = Search(RHS, BB, R);
467 
468     if (ValidLHS && ValidRHS)
469       return true;
470 
471     return R.InsertAcc(I);
472   }
473   case Instruction::Mul: {
474     Value *MulOp0 = I->getOperand(0);
475     Value *MulOp1 = I->getOperand(1);
476     return IsNarrowSequence<16>(MulOp0) && IsNarrowSequence<16>(MulOp1);
477   }
478   case Instruction::SExt:
479     return Search(I->getOperand(0), BB, R);
480   }
481   return false;
482 }
483 
484 // The pass needs to identify integer add/sub reductions of 16-bit vector
485 // multiplications.
486 // To use SMLAD:
487 // 1) we first need to find integer add then look for this pattern:
488 //
489 // acc0 = ...
490 // ld0 = load i16
491 // sext0 = sext i16 %ld0 to i32
492 // ld1 = load i16
493 // sext1 = sext i16 %ld1 to i32
494 // mul0 = mul %sext0, %sext1
495 // ld2 = load i16
496 // sext2 = sext i16 %ld2 to i32
497 // ld3 = load i16
498 // sext3 = sext i16 %ld3 to i32
499 // mul1 = mul i32 %sext2, %sext3
500 // add0 = add i32 %mul0, %acc0
501 // acc1 = add i32 %add0, %mul1
502 //
503 // Which can be selected to:
504 //
505 // ldr r0
506 // ldr r1
507 // smlad r2, r0, r1, r2
508 //
509 // If constants are used instead of loads, these will need to be hoisted
510 // out and into a register.
511 //
512 // If loop invariants are used instead of loads, these need to be packed
513 // before the loop begins.
514 //
515 bool ARMParallelDSP::MatchSMLAD(Function &F) {
516   bool Changed = false;
517 
518   for (auto &BB : F) {
519     SmallPtrSet<Instruction*, 4> AllAdds;
520     if (!RecordMemoryOps(&BB))
521       continue;
522 
523     for (Instruction &I : reverse(BB)) {
524       if (I.getOpcode() != Instruction::Add)
525         continue;
526 
527       if (AllAdds.count(&I))
528         continue;
529 
530       const auto *Ty = I.getType();
531       if (!Ty->isIntegerTy(32) && !Ty->isIntegerTy(64))
532         continue;
533 
534       Reduction R(&I);
535       if (!Search(&I, &BB, R))
536         continue;
537 
538       R.InsertMuls();
539       LLVM_DEBUG(dbgs() << "After search, Reduction:\n"; R.dump());
540 
541       if (!CreateParallelPairs(R))
542         continue;
543 
544       InsertParallelMACs(R);
545       Changed = true;
546       AllAdds.insert(R.getAdds().begin(), R.getAdds().end());
547     }
548   }
549 
550   return Changed;
551 }
552 
553 bool ARMParallelDSP::CreateParallelPairs(Reduction &R) {
554 
555   // Not enough mul operations to make a pair.
556   if (R.getMuls().size() < 2)
557     return false;
558 
559   // Check that the muls operate directly upon sign extended loads.
560   for (auto &MulCand : R.getMuls()) {
561     if (!MulCand->HasTwoLoadInputs())
562       return false;
563   }
564 
565   auto CanPair = [&](Reduction &R, MulCandidate *PMul0, MulCandidate *PMul1) {
566     // The first elements of each vector should be loads with sexts. If we
567     // find that its two pairs of consecutive loads, then these can be
568     // transformed into two wider loads and the users can be replaced with
569     // DSP intrinsics.
570     auto Ld0 = static_cast<LoadInst*>(PMul0->LHS);
571     auto Ld1 = static_cast<LoadInst*>(PMul1->LHS);
572     auto Ld2 = static_cast<LoadInst*>(PMul0->RHS);
573     auto Ld3 = static_cast<LoadInst*>(PMul1->RHS);
574 
575     // Check that each mul is operating on two different loads.
576     if (Ld0 == Ld2 || Ld1 == Ld3)
577       return false;
578 
579     if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd)) {
580       if (AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
581         LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
582         R.AddMulPair(PMul0, PMul1);
583         return true;
584       } else if (AreSequentialLoads(Ld3, Ld2, PMul1->VecLd)) {
585         LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
586         LLVM_DEBUG(dbgs() << "    exchanging Ld2 and Ld3\n");
587         R.AddMulPair(PMul0, PMul1, true);
588         return true;
589       }
590     } else if (AreSequentialLoads(Ld1, Ld0, PMul0->VecLd) &&
591                AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
592       LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
593       LLVM_DEBUG(dbgs() << "    exchanging Ld0 and Ld1\n");
594       LLVM_DEBUG(dbgs() << "    and swapping muls\n");
595       // Only the second operand can be exchanged, so swap the muls.
596       R.AddMulPair(PMul1, PMul0, true);
597       return true;
598     }
599     return false;
600   };
601 
602   MulCandList &Muls = R.getMuls();
603   const unsigned Elems = Muls.size();
604   for (unsigned i = 0; i < Elems; ++i) {
605     MulCandidate *PMul0 = static_cast<MulCandidate*>(Muls[i].get());
606     if (PMul0->Paired)
607       continue;
608 
609     for (unsigned j = 0; j < Elems; ++j) {
610       if (i == j)
611         continue;
612 
613       MulCandidate *PMul1 = static_cast<MulCandidate*>(Muls[j].get());
614       if (PMul1->Paired)
615         continue;
616 
617       const Instruction *Mul0 = PMul0->Root;
618       const Instruction *Mul1 = PMul1->Root;
619       if (Mul0 == Mul1)
620         continue;
621 
622       assert(PMul0 != PMul1 && "expected different chains");
623 
624       if (CanPair(R, PMul0, PMul1))
625         break;
626     }
627   }
628   return !R.getMulPairs().empty();
629 }
630 
631 void ARMParallelDSP::InsertParallelMACs(Reduction &R) {
632 
633   auto CreateSMLAD = [&](LoadInst* WideLd0, LoadInst *WideLd1,
634                          Value *Acc, bool Exchange,
635                          Instruction *InsertAfter) {
636     // Replace the reduction chain with an intrinsic call
637 
638     Value* Args[] = { WideLd0, WideLd1, Acc };
639     Function *SMLAD = nullptr;
640     if (Exchange)
641       SMLAD = Acc->getType()->isIntegerTy(32) ?
642         Intrinsic::getDeclaration(M, Intrinsic::arm_smladx) :
643         Intrinsic::getDeclaration(M, Intrinsic::arm_smlaldx);
644     else
645       SMLAD = Acc->getType()->isIntegerTy(32) ?
646         Intrinsic::getDeclaration(M, Intrinsic::arm_smlad) :
647         Intrinsic::getDeclaration(M, Intrinsic::arm_smlald);
648 
649     IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
650                                 BasicBlock::iterator(InsertAfter));
651     Instruction *Call = Builder.CreateCall(SMLAD, Args);
652     NumSMLAD++;
653     return Call;
654   };
655 
656   // Return the instruction after the dominated instruction.
657   auto GetInsertPoint = [this](Value *A, Value *B) {
658     assert((isa<Instruction>(A) || isa<Instruction>(B)) &&
659            "expected at least one instruction");
660 
661     Value *V = nullptr;
662     if (!isa<Instruction>(A))
663       V = B;
664     else if (!isa<Instruction>(B))
665       V = A;
666     else
667       V = DT->dominates(cast<Instruction>(A), cast<Instruction>(B)) ? B : A;
668 
669     return &*++BasicBlock::iterator(cast<Instruction>(V));
670   };
671 
672   Value *Acc = R.getAccumulator();
673 
674   // For any muls that were discovered but not paired, accumulate their values
675   // as before.
676   IRBuilder<NoFolder> Builder(R.getRoot()->getParent());
677   MulCandList &MulCands = R.getMuls();
678   for (auto &MulCand : MulCands) {
679     if (MulCand->Paired)
680       continue;
681 
682     Instruction *Mul = cast<Instruction>(MulCand->Root);
683     LLVM_DEBUG(dbgs() << "Accumulating unpaired mul: " << *Mul << "\n");
684 
685     if (R.getType() != Mul->getType()) {
686       assert(R.is64Bit() && "expected 64-bit result");
687       Builder.SetInsertPoint(&*++BasicBlock::iterator(Mul));
688       Mul = cast<Instruction>(Builder.CreateSExt(Mul, R.getRoot()->getType()));
689     }
690 
691     if (!Acc) {
692       Acc = Mul;
693       continue;
694     }
695 
696     // If Acc is the original incoming value to the reduction, it could be a
697     // phi. But the phi will dominate Mul, meaning that Mul will be the
698     // insertion point.
699     Builder.SetInsertPoint(GetInsertPoint(Mul, Acc));
700     Acc = Builder.CreateAdd(Mul, Acc);
701   }
702 
703   if (!Acc) {
704     Acc = R.is64Bit() ?
705       ConstantInt::get(IntegerType::get(M->getContext(), 64), 0) :
706       ConstantInt::get(IntegerType::get(M->getContext(), 32), 0);
707   } else if (Acc->getType() != R.getType()) {
708     Builder.SetInsertPoint(R.getRoot());
709     Acc = Builder.CreateSExt(Acc, R.getType());
710   }
711 
712   // Roughly sort the mul pairs in their program order.
713   llvm::sort(R.getMulPairs(), [](auto &PairA, auto &PairB) {
714     const Instruction *A = PairA.first->Root;
715     const Instruction *B = PairB.first->Root;
716     return A->comesBefore(B);
717   });
718 
719   IntegerType *Ty = IntegerType::get(M->getContext(), 32);
720   for (auto &Pair : R.getMulPairs()) {
721     MulCandidate *LHSMul = Pair.first;
722     MulCandidate *RHSMul = Pair.second;
723     LoadInst *BaseLHS = LHSMul->getBaseLoad();
724     LoadInst *BaseRHS = RHSMul->getBaseLoad();
725     LoadInst *WideLHS = WideLoads.count(BaseLHS) ?
726       WideLoads[BaseLHS]->getLoad() : CreateWideLoad(LHSMul->VecLd, Ty);
727     LoadInst *WideRHS = WideLoads.count(BaseRHS) ?
728       WideLoads[BaseRHS]->getLoad() : CreateWideLoad(RHSMul->VecLd, Ty);
729 
730     Instruction *InsertAfter = GetInsertPoint(WideLHS, WideRHS);
731     InsertAfter = GetInsertPoint(InsertAfter, Acc);
732     Acc = CreateSMLAD(WideLHS, WideRHS, Acc, RHSMul->Exchange, InsertAfter);
733   }
734   R.UpdateRoot(cast<Instruction>(Acc));
735 }
736 
737 LoadInst* ARMParallelDSP::CreateWideLoad(MemInstList &Loads,
738                                          IntegerType *LoadTy) {
739   assert(Loads.size() == 2 && "currently only support widening two loads");
740 
741   LoadInst *Base = Loads[0];
742   LoadInst *Offset = Loads[1];
743 
744   Instruction *BaseSExt = dyn_cast<SExtInst>(Base->user_back());
745   Instruction *OffsetSExt = dyn_cast<SExtInst>(Offset->user_back());
746 
747   assert((BaseSExt && OffsetSExt)
748          && "Loads should have a single, extending, user");
749 
750   std::function<void(Value*, Value*)> MoveBefore =
751     [&](Value *A, Value *B) -> void {
752       if (!isa<Instruction>(A) || !isa<Instruction>(B))
753         return;
754 
755       auto *Source = cast<Instruction>(A);
756       auto *Sink = cast<Instruction>(B);
757 
758       if (DT->dominates(Source, Sink) ||
759           Source->getParent() != Sink->getParent() ||
760           isa<PHINode>(Source) || isa<PHINode>(Sink))
761         return;
762 
763       Source->moveBefore(Sink);
764       for (auto &Op : Source->operands())
765         MoveBefore(Op, Source);
766     };
767 
768   // Insert the load at the point of the original dominating load.
769   LoadInst *DomLoad = DT->dominates(Base, Offset) ? Base : Offset;
770   IRBuilder<NoFolder> IRB(DomLoad->getParent(),
771                           ++BasicBlock::iterator(DomLoad));
772 
773   // Bitcast the pointer to a wider type and create the wide load, while making
774   // sure to maintain the original alignment as this prevents ldrd from being
775   // generated when it could be illegal due to memory alignment.
776   const unsigned AddrSpace = DomLoad->getPointerAddressSpace();
777   Value *VecPtr = IRB.CreateBitCast(Base->getPointerOperand(),
778                                     LoadTy->getPointerTo(AddrSpace));
779   LoadInst *WideLoad = IRB.CreateAlignedLoad(LoadTy, VecPtr, Base->getAlign());
780 
781   // Make sure everything is in the correct order in the basic block.
782   MoveBefore(Base->getPointerOperand(), VecPtr);
783   MoveBefore(VecPtr, WideLoad);
784 
785   // From the wide load, create two values that equal the original two loads.
786   // Loads[0] needs trunc while Loads[1] needs a lshr and trunc.
787   // TODO: Support big-endian as well.
788   Value *Bottom = IRB.CreateTrunc(WideLoad, Base->getType());
789   Value *NewBaseSExt = IRB.CreateSExt(Bottom, BaseSExt->getType());
790   BaseSExt->replaceAllUsesWith(NewBaseSExt);
791 
792   IntegerType *OffsetTy = cast<IntegerType>(Offset->getType());
793   Value *ShiftVal = ConstantInt::get(LoadTy, OffsetTy->getBitWidth());
794   Value *Top = IRB.CreateLShr(WideLoad, ShiftVal);
795   Value *Trunc = IRB.CreateTrunc(Top, OffsetTy);
796   Value *NewOffsetSExt = IRB.CreateSExt(Trunc, OffsetSExt->getType());
797   OffsetSExt->replaceAllUsesWith(NewOffsetSExt);
798 
799   LLVM_DEBUG(dbgs() << "From Base and Offset:\n"
800              << *Base << "\n" << *Offset << "\n"
801              << "Created Wide Load:\n"
802              << *WideLoad << "\n"
803              << *Bottom << "\n"
804              << *NewBaseSExt << "\n"
805              << *Top << "\n"
806              << *Trunc << "\n"
807              << *NewOffsetSExt << "\n");
808   WideLoads.emplace(std::make_pair(Base,
809                                    std::make_unique<WidenedLoad>(Loads, WideLoad)));
810   return WideLoad;
811 }
812 
813 Pass *llvm::createARMParallelDSPPass() {
814   return new ARMParallelDSP();
815 }
816 
817 char ARMParallelDSP::ID = 0;
818 
819 INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp",
820                 "Transform functions to use DSP intrinsics", false, false)
821 INITIALIZE_PASS_END(ARMParallelDSP, "arm-parallel-dsp",
822                 "Transform functions to use DSP intrinsics", false, false)
823