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