1 //===- ParallelDSP.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 "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/LoopAccessAnalysis.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/NoFolder.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/Transforms/Utils/LoopUtils.h"
28 #include "llvm/Pass.h"
29 #include "llvm/PassRegistry.h"
30 #include "llvm/PassSupport.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "ARM.h"
35 #include "ARMSubtarget.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 namespace {
49   struct OpChain;
50   struct BinOpChain;
51   struct Reduction;
52 
53   using OpChainList     = SmallVector<std::unique_ptr<OpChain>, 8>;
54   using ReductionList   = SmallVector<Reduction, 8>;
55   using ValueList       = SmallVector<Value*, 8>;
56   using MemInstList     = SmallVector<LoadInst*, 8>;
57   using PMACPair        = std::pair<BinOpChain*,BinOpChain*>;
58   using PMACPairList    = SmallVector<PMACPair, 8>;
59   using Instructions    = SmallVector<Instruction*,16>;
60   using MemLocList      = SmallVector<MemoryLocation, 4>;
61 
62   struct OpChain {
63     Instruction   *Root;
64     ValueList     AllValues;
65     MemInstList   VecLd;    // List of all load instructions.
66     MemLocList    MemLocs;  // All memory locations read by this tree.
67     bool          ReadOnly = true;
68 
69     OpChain(Instruction *I, ValueList &vl) : Root(I), AllValues(vl) { }
70     virtual ~OpChain() = default;
71 
72     void SetMemoryLocations() {
73       const auto Size = LocationSize::unknown();
74       for (auto *V : AllValues) {
75         if (auto *I = dyn_cast<Instruction>(V)) {
76           if (I->mayWriteToMemory())
77             ReadOnly = false;
78           if (auto *Ld = dyn_cast<LoadInst>(V))
79             MemLocs.push_back(MemoryLocation(Ld->getPointerOperand(), Size));
80         }
81       }
82     }
83 
84     unsigned size() const { return AllValues.size(); }
85   };
86 
87   // 'BinOpChain' and 'Reduction' are just some bookkeeping data structures.
88   // 'Reduction' contains the phi-node and accumulator statement from where we
89   // start pattern matching, and 'BinOpChain' the multiplication
90   // instructions that are candidates for parallel execution.
91   struct BinOpChain : public OpChain {
92     ValueList     LHS;      // List of all (narrow) left hand operands.
93     ValueList     RHS;      // List of all (narrow) right hand operands.
94     bool Exchange = false;
95 
96     BinOpChain(Instruction *I, ValueList &lhs, ValueList &rhs) :
97       OpChain(I, lhs), LHS(lhs), RHS(rhs) {
98         for (auto *V : RHS)
99           AllValues.push_back(V);
100       }
101 
102     bool AreSymmetrical(BinOpChain *Other);
103   };
104 
105   struct Reduction {
106     PHINode         *Phi;             // The Phi-node from where we start
107                                       // pattern matching.
108     Instruction     *AccIntAdd;       // The accumulating integer add statement,
109                                       // i.e, the reduction statement.
110     OpChainList     MACCandidates;    // The MAC candidates associated with
111                                       // this reduction statement.
112     PMACPairList    PMACPairs;
113     Reduction (PHINode *P, Instruction *Acc) : Phi(P), AccIntAdd(Acc) { };
114   };
115 
116   class WidenedLoad {
117     LoadInst *NewLd = nullptr;
118     SmallVector<LoadInst*, 4> Loads;
119 
120   public:
121     WidenedLoad(SmallVectorImpl<LoadInst*> &Lds, LoadInst *Wide)
122       : NewLd(Wide) {
123       for (auto *I : Lds)
124         Loads.push_back(I);
125     }
126     LoadInst *getLoad() {
127       return NewLd;
128     }
129   };
130 
131   class ARMParallelDSP : public LoopPass {
132     ScalarEvolution   *SE;
133     AliasAnalysis     *AA;
134     TargetLibraryInfo *TLI;
135     DominatorTree     *DT;
136     LoopInfo          *LI;
137     Loop              *L;
138     const DataLayout  *DL;
139     Module            *M;
140     std::map<LoadInst*, LoadInst*> LoadPairs;
141     std::map<LoadInst*, std::unique_ptr<WidenedLoad>> WideLoads;
142 
143     bool RecordSequentialLoads(BasicBlock *BB);
144     bool InsertParallelMACs(Reduction &Reduction);
145     bool AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1, MemInstList &VecMem);
146     LoadInst* CreateLoadIns(IRBuilder<NoFolder> &IRB,
147                             SmallVectorImpl<LoadInst*> &Loads,
148                             IntegerType *LoadTy);
149     void CreateParallelMACPairs(Reduction &R);
150     Instruction *CreateSMLADCall(SmallVectorImpl<LoadInst*> &VecLd0,
151                                  SmallVectorImpl<LoadInst*> &VecLd1,
152                                  Instruction *Acc, bool Exchange,
153                                  Instruction *InsertAfter);
154 
155     /// Try to match and generate: SMLAD, SMLADX - Signed Multiply Accumulate
156     /// Dual performs two signed 16x16-bit multiplications. It adds the
157     /// products to a 32-bit accumulate operand. Optionally, the instruction can
158     /// exchange the halfwords of the second operand before performing the
159     /// arithmetic.
160     bool MatchSMLAD(Function &F);
161 
162   public:
163     static char ID;
164 
165     ARMParallelDSP() : LoopPass(ID) { }
166 
167     void getAnalysisUsage(AnalysisUsage &AU) const override {
168       LoopPass::getAnalysisUsage(AU);
169       AU.addRequired<AssumptionCacheTracker>();
170       AU.addRequired<ScalarEvolutionWrapperPass>();
171       AU.addRequired<AAResultsWrapperPass>();
172       AU.addRequired<TargetLibraryInfoWrapperPass>();
173       AU.addRequired<LoopInfoWrapperPass>();
174       AU.addRequired<DominatorTreeWrapperPass>();
175       AU.addRequired<TargetPassConfig>();
176       AU.addPreserved<LoopInfoWrapperPass>();
177       AU.setPreservesCFG();
178     }
179 
180     bool runOnLoop(Loop *TheLoop, LPPassManager &) override {
181       if (DisableParallelDSP)
182         return false;
183       L = TheLoop;
184       SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
185       AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
186       TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
187       DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
188       LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
189       auto &TPC = getAnalysis<TargetPassConfig>();
190 
191       BasicBlock *Header = TheLoop->getHeader();
192       if (!Header)
193         return false;
194 
195       // TODO: We assume the loop header and latch to be the same block.
196       // This is not a fundamental restriction, but lifting this would just
197       // require more work to do the transformation and then patch up the CFG.
198       if (Header != TheLoop->getLoopLatch()) {
199         LLVM_DEBUG(dbgs() << "The loop header is not the loop latch: not "
200                              "running pass ARMParallelDSP\n");
201         return false;
202       }
203 
204       Function &F = *Header->getParent();
205       M = F.getParent();
206       DL = &M->getDataLayout();
207 
208       auto &TM = TPC.getTM<TargetMachine>();
209       auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
210 
211       if (!ST->allowsUnalignedMem()) {
212         LLVM_DEBUG(dbgs() << "Unaligned memory access not supported: not "
213                              "running pass ARMParallelDSP\n");
214         return false;
215       }
216 
217       if (!ST->hasDSP()) {
218         LLVM_DEBUG(dbgs() << "DSP extension not enabled: not running pass "
219                              "ARMParallelDSP\n");
220         return false;
221       }
222 
223       LoopAccessInfo LAI(L, SE, TLI, AA, DT, LI);
224 
225       LLVM_DEBUG(dbgs() << "\n== Parallel DSP pass ==\n");
226       LLVM_DEBUG(dbgs() << " - " << F.getName() << "\n\n");
227 
228       if (!RecordSequentialLoads(Header)) {
229         LLVM_DEBUG(dbgs() << " - No sequential loads found.\n");
230         return false;
231       }
232 
233       bool Changes = MatchSMLAD(F);
234       return Changes;
235     }
236   };
237 }
238 
239 // MaxBitwidth: the maximum supported bitwidth of the elements in the DSP
240 // instructions, which is set to 16. So here we should collect all i8 and i16
241 // narrow operations.
242 // TODO: we currently only collect i16, and will support i8 later, so that's
243 // why we check that types are equal to MaxBitWidth, and not <= MaxBitWidth.
244 template<unsigned MaxBitWidth>
245 static bool IsNarrowSequence(Value *V, ValueList &VL) {
246   ConstantInt *CInt;
247 
248   if (match(V, m_ConstantInt(CInt))) {
249     // TODO: if a constant is used, it needs to fit within the bit width.
250     return false;
251   }
252 
253   auto *I = dyn_cast<Instruction>(V);
254   if (!I)
255    return false;
256 
257   Value *Val, *LHS, *RHS;
258   if (match(V, m_Trunc(m_Value(Val)))) {
259     if (cast<TruncInst>(I)->getDestTy()->getIntegerBitWidth() == MaxBitWidth)
260       return IsNarrowSequence<MaxBitWidth>(Val, VL);
261   } else if (match(V, m_Add(m_Value(LHS), m_Value(RHS)))) {
262     // TODO: we need to implement sadd16/sadd8 for this, which enables to
263     // also do the rewrite for smlad8.ll, but it is unsupported for now.
264     return false;
265   } else if (match(V, m_ZExtOrSExt(m_Value(Val)))) {
266     if (cast<CastInst>(I)->getSrcTy()->getIntegerBitWidth() != MaxBitWidth)
267       return false;
268 
269     if (match(Val, m_Load(m_Value()))) {
270       VL.push_back(Val);
271       VL.push_back(I);
272       return true;
273     }
274   }
275   return false;
276 }
277 
278 template<typename MemInst>
279 static bool AreSequentialAccesses(MemInst *MemOp0, MemInst *MemOp1,
280                                   const DataLayout &DL, ScalarEvolution &SE) {
281   if (isConsecutiveAccess(MemOp0, MemOp1, DL, SE))
282     return true;
283   return false;
284 }
285 
286 bool ARMParallelDSP::AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1,
287                                         MemInstList &VecMem) {
288   if (!Ld0 || !Ld1)
289     return false;
290 
291   if (!LoadPairs.count(Ld0) || LoadPairs[Ld0] != Ld1)
292     return false;
293 
294   LLVM_DEBUG(dbgs() << "Loads are sequential and valid:\n";
295     dbgs() << "Ld0:"; Ld0->dump();
296     dbgs() << "Ld1:"; Ld1->dump();
297   );
298 
299   VecMem.clear();
300   VecMem.push_back(Ld0);
301   VecMem.push_back(Ld1);
302   return true;
303 }
304 
305 /// Iterate through the block and record base, offset pairs of loads as well as
306 /// maximal sequences of sequential loads.
307 bool ARMParallelDSP::RecordSequentialLoads(BasicBlock *BB) {
308   SmallVector<LoadInst*, 8> Loads;
309   for (auto &I : *BB) {
310     auto *Ld = dyn_cast<LoadInst>(&I);
311     if (!Ld || !Ld->isSimple() ||
312         !Ld->hasOneUse() || !isa<SExtInst>(Ld->user_back()))
313       continue;
314     Loads.push_back(Ld);
315   }
316 
317   for (auto *Ld0 : Loads) {
318     for (auto *Ld1 : Loads) {
319       if (Ld0 == Ld1)
320         continue;
321 
322       if (AreSequentialAccesses<LoadInst>(Ld0, Ld1, *DL, *SE)) {
323         LoadPairs[Ld0] = Ld1;
324         break;
325       }
326     }
327   }
328 
329   LLVM_DEBUG(if (!LoadPairs.empty()) {
330                dbgs() << "Consecutive load pairs:\n";
331                for (auto &MapIt : LoadPairs) {
332                  LLVM_DEBUG(dbgs() << *MapIt.first << ", "
333                             << *MapIt.second << "\n");
334                }
335              });
336   return LoadPairs.size() > 1;
337 }
338 
339 void ARMParallelDSP::CreateParallelMACPairs(Reduction &R) {
340   OpChainList &Candidates = R.MACCandidates;
341   PMACPairList &PMACPairs = R.PMACPairs;
342   const unsigned Elems = Candidates.size();
343 
344   if (Elems < 2)
345     return;
346 
347   auto CanPair = [&](BinOpChain *PMul0, BinOpChain *PMul1) {
348     if (!PMul0->AreSymmetrical(PMul1))
349       return false;
350 
351     // The first elements of each vector should be loads with sexts. If we
352     // find that its two pairs of consecutive loads, then these can be
353     // transformed into two wider loads and the users can be replaced with
354     // DSP intrinsics.
355     for (unsigned x = 0; x < PMul0->LHS.size(); x += 2) {
356       auto *Ld0 = dyn_cast<LoadInst>(PMul0->LHS[x]);
357       auto *Ld1 = dyn_cast<LoadInst>(PMul1->LHS[x]);
358       auto *Ld2 = dyn_cast<LoadInst>(PMul0->RHS[x]);
359       auto *Ld3 = dyn_cast<LoadInst>(PMul1->RHS[x]);
360 
361       if (!Ld0 || !Ld1 || !Ld2 || !Ld3)
362         return false;
363 
364       LLVM_DEBUG(dbgs() << "Loads:\n"
365                  << " - " << *Ld0 << "\n"
366                  << " - " << *Ld1 << "\n"
367                  << " - " << *Ld2 << "\n"
368                  << " - " << *Ld3 << "\n");
369 
370       if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd)) {
371         if (AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
372           LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
373           PMACPairs.push_back(std::make_pair(PMul0, PMul1));
374           return true;
375         } else if (AreSequentialLoads(Ld3, Ld2, PMul1->VecLd)) {
376           LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
377           LLVM_DEBUG(dbgs() << "    exchanging Ld2 and Ld3\n");
378           PMul1->Exchange = true;
379           PMACPairs.push_back(std::make_pair(PMul0, PMul1));
380           return true;
381         }
382       } else if (AreSequentialLoads(Ld1, Ld0, PMul0->VecLd) &&
383                  AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
384         LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
385         LLVM_DEBUG(dbgs() << "    exchanging Ld0 and Ld1\n");
386         LLVM_DEBUG(dbgs() << "    and swapping muls\n");
387         PMul0->Exchange = true;
388         // Only the second operand can be exchanged, so swap the muls.
389         PMACPairs.push_back(std::make_pair(PMul1, PMul0));
390         return true;
391       }
392     }
393     return false;
394   };
395 
396   SmallPtrSet<const Instruction*, 4> Paired;
397   for (unsigned i = 0; i < Elems; ++i) {
398     BinOpChain *PMul0 = static_cast<BinOpChain*>(Candidates[i].get());
399     if (Paired.count(PMul0->Root))
400       continue;
401 
402     for (unsigned j = 0; j < Elems; ++j) {
403       if (i == j)
404         continue;
405 
406       BinOpChain *PMul1 = static_cast<BinOpChain*>(Candidates[j].get());
407       if (Paired.count(PMul1->Root))
408         continue;
409 
410       const Instruction *Mul0 = PMul0->Root;
411       const Instruction *Mul1 = PMul1->Root;
412       if (Mul0 == Mul1)
413         continue;
414 
415       assert(PMul0 != PMul1 && "expected different chains");
416 
417       if (CanPair(PMul0, PMul1)) {
418         Paired.insert(Mul0);
419         Paired.insert(Mul1);
420         break;
421       }
422     }
423   }
424 }
425 
426 bool ARMParallelDSP::InsertParallelMACs(Reduction &Reduction) {
427   Instruction *Acc = Reduction.Phi;
428   Instruction *InsertAfter = Reduction.AccIntAdd;
429 
430   for (auto &Pair : Reduction.PMACPairs) {
431     BinOpChain *PMul0 = Pair.first;
432     BinOpChain *PMul1 = Pair.second;
433     LLVM_DEBUG(dbgs() << "Found parallel MACs!!\n";
434                dbgs() << "- "; PMul0->Root->dump();
435                dbgs() << "- "; PMul1->Root->dump());
436 
437     Acc = CreateSMLADCall(PMul0->VecLd, PMul1->VecLd, Acc, PMul1->Exchange,
438                           InsertAfter);
439     InsertAfter = Acc;
440   }
441 
442   if (Acc != Reduction.Phi) {
443     LLVM_DEBUG(dbgs() << "Replace Accumulate: "; Acc->dump());
444     Reduction.AccIntAdd->replaceAllUsesWith(Acc);
445     return true;
446   }
447   return false;
448 }
449 
450 static void MatchReductions(Function &F, Loop *TheLoop, BasicBlock *Header,
451                             ReductionList &Reductions) {
452   RecurrenceDescriptor RecDesc;
453   const bool HasFnNoNaNAttr =
454     F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
455   const BasicBlock *Latch = TheLoop->getLoopLatch();
456 
457   // We need a preheader as getIncomingValueForBlock assumes there is one.
458   if (!TheLoop->getLoopPreheader()) {
459     LLVM_DEBUG(dbgs() << "No preheader found, bailing out\n");
460     return;
461   }
462 
463   for (PHINode &Phi : Header->phis()) {
464     const auto *Ty = Phi.getType();
465     if (!Ty->isIntegerTy(32) && !Ty->isIntegerTy(64))
466       continue;
467 
468     const bool IsReduction =
469       RecurrenceDescriptor::AddReductionVar(&Phi,
470                                             RecurrenceDescriptor::RK_IntegerAdd,
471                                             TheLoop, HasFnNoNaNAttr, RecDesc);
472     if (!IsReduction)
473       continue;
474 
475     Instruction *Acc = dyn_cast<Instruction>(Phi.getIncomingValueForBlock(Latch));
476     if (!Acc)
477       continue;
478 
479     Reductions.push_back(Reduction(&Phi, Acc));
480   }
481 
482   LLVM_DEBUG(
483     dbgs() << "\nAccumulating integer additions (reductions) found:\n";
484     for (auto &R : Reductions) {
485       dbgs() << "-  "; R.Phi->dump();
486       dbgs() << "-> "; R.AccIntAdd->dump();
487     }
488   );
489 }
490 
491 static void AddMACCandidate(OpChainList &Candidates,
492                             Instruction *Mul,
493                             Value *MulOp0, Value *MulOp1) {
494   assert(Mul->getOpcode() == Instruction::Mul &&
495          "expected mul instruction");
496   ValueList LHS;
497   ValueList RHS;
498   if (IsNarrowSequence<16>(MulOp0, LHS) &&
499       IsNarrowSequence<16>(MulOp1, RHS)) {
500     Candidates.push_back(make_unique<BinOpChain>(Mul, LHS, RHS));
501   }
502 }
503 
504 static void MatchParallelMACSequences(Reduction &R,
505                                       OpChainList &Candidates) {
506   Instruction *Acc = R.AccIntAdd;
507   LLVM_DEBUG(dbgs() << "\n- Analysing:\t" << *Acc << "\n");
508 
509   // Returns false to signal the search should be stopped.
510   std::function<bool(Value*)> Match =
511     [&Candidates, &Match](Value *V) -> bool {
512 
513     auto *I = dyn_cast<Instruction>(V);
514     if (!I)
515       return false;
516 
517     switch (I->getOpcode()) {
518     case Instruction::Add:
519       if (Match(I->getOperand(0)) || (Match(I->getOperand(1))))
520         return true;
521       break;
522     case Instruction::Mul: {
523       Value *MulOp0 = I->getOperand(0);
524       Value *MulOp1 = I->getOperand(1);
525       if (isa<SExtInst>(MulOp0) && isa<SExtInst>(MulOp1))
526         AddMACCandidate(Candidates, I, MulOp0, MulOp1);
527       return false;
528     }
529     case Instruction::SExt:
530       return Match(I->getOperand(0));
531     }
532     return false;
533   };
534 
535   while (Match (Acc));
536   LLVM_DEBUG(dbgs() << "Finished matching MAC sequences, found "
537              << Candidates.size() << " candidates.\n");
538 }
539 
540 // Collects all instructions that are not part of the MAC chains, which is the
541 // set of instructions that can potentially alias with the MAC operands.
542 static void AliasCandidates(BasicBlock *Header, Instructions &Reads,
543                             Instructions &Writes) {
544   for (auto &I : *Header) {
545     if (I.mayReadFromMemory())
546       Reads.push_back(&I);
547     if (I.mayWriteToMemory())
548       Writes.push_back(&I);
549   }
550 }
551 
552 // Check whether statements in the basic block that write to memory alias with
553 // the memory locations accessed by the MAC-chains.
554 // TODO: we need the read statements when we accept more complicated chains.
555 static bool AreAliased(AliasAnalysis *AA, Instructions &Reads,
556                        Instructions &Writes, OpChainList &MACCandidates) {
557   LLVM_DEBUG(dbgs() << "Alias checks:\n");
558   for (auto &MAC : MACCandidates) {
559     LLVM_DEBUG(dbgs() << "mul: "; MAC->Root->dump());
560 
561     // At the moment, we allow only simple chains that only consist of reads,
562     // accumulate their result with an integer add, and thus that don't write
563     // memory, and simply bail if they do.
564     if (!MAC->ReadOnly)
565       return true;
566 
567     // Now for all writes in the basic block, check that they don't alias with
568     // the memory locations accessed by our MAC-chain:
569     for (auto *I : Writes) {
570       LLVM_DEBUG(dbgs() << "- "; I->dump());
571       assert(MAC->MemLocs.size() >= 2 && "expecting at least 2 memlocs");
572       for (auto &MemLoc : MAC->MemLocs) {
573         if (isModOrRefSet(intersectModRef(AA->getModRefInfo(I, MemLoc),
574                                           ModRefInfo::ModRef))) {
575           LLVM_DEBUG(dbgs() << "Yes, aliases found\n");
576           return true;
577         }
578       }
579     }
580   }
581 
582   LLVM_DEBUG(dbgs() << "OK: no aliases found!\n");
583   return false;
584 }
585 
586 static bool CheckMACMemory(OpChainList &Candidates) {
587   for (auto &C : Candidates) {
588     // A mul has 2 operands, and a narrow op consist of sext and a load; thus
589     // we expect at least 4 items in this operand value list.
590     if (C->size() < 4) {
591       LLVM_DEBUG(dbgs() << "Operand list too short.\n");
592       return false;
593     }
594     C->SetMemoryLocations();
595     ValueList &LHS = static_cast<BinOpChain*>(C.get())->LHS;
596     ValueList &RHS = static_cast<BinOpChain*>(C.get())->RHS;
597 
598     // Use +=2 to skip over the expected extend instructions.
599     for (unsigned i = 0, e = LHS.size(); i < e; i += 2) {
600       if (!isa<LoadInst>(LHS[i]) || !isa<LoadInst>(RHS[i]))
601         return false;
602     }
603   }
604   return true;
605 }
606 
607 // Loop Pass that needs to identify integer add/sub reductions of 16-bit vector
608 // multiplications.
609 // To use SMLAD:
610 // 1) we first need to find integer add reduction PHIs,
611 // 2) then from the PHI, look for this pattern:
612 //
613 // acc0 = phi i32 [0, %entry], [%acc1, %loop.body]
614 // ld0 = load i16
615 // sext0 = sext i16 %ld0 to i32
616 // ld1 = load i16
617 // sext1 = sext i16 %ld1 to i32
618 // mul0 = mul %sext0, %sext1
619 // ld2 = load i16
620 // sext2 = sext i16 %ld2 to i32
621 // ld3 = load i16
622 // sext3 = sext i16 %ld3 to i32
623 // mul1 = mul i32 %sext2, %sext3
624 // add0 = add i32 %mul0, %acc0
625 // acc1 = add i32 %add0, %mul1
626 //
627 // Which can be selected to:
628 //
629 // ldr.h r0
630 // ldr.h r1
631 // smlad r2, r0, r1, r2
632 //
633 // If constants are used instead of loads, these will need to be hoisted
634 // out and into a register.
635 //
636 // If loop invariants are used instead of loads, these need to be packed
637 // before the loop begins.
638 //
639 bool ARMParallelDSP::MatchSMLAD(Function &F) {
640   BasicBlock *Header = L->getHeader();
641   LLVM_DEBUG(dbgs() << "= Matching SMLAD =\n";
642              dbgs() << "Header block:\n"; Header->dump();
643              dbgs() << "Loop info:\n\n"; L->dump());
644 
645   bool Changed = false;
646   ReductionList Reductions;
647   MatchReductions(F, L, Header, Reductions);
648 
649   for (auto &R : Reductions) {
650     OpChainList MACCandidates;
651     MatchParallelMACSequences(R, MACCandidates);
652     if (!CheckMACMemory(MACCandidates))
653       continue;
654 
655     R.MACCandidates = std::move(MACCandidates);
656 
657     LLVM_DEBUG(dbgs() << "MAC candidates:\n";
658       for (auto &M : R.MACCandidates)
659         M->Root->dump();
660       dbgs() << "\n";);
661   }
662 
663   // Collect all instructions that may read or write memory. Our alias
664   // analysis checks bail out if any of these instructions aliases with an
665   // instruction from the MAC-chain.
666   Instructions Reads, Writes;
667   AliasCandidates(Header, Reads, Writes);
668 
669   for (auto &R : Reductions) {
670     if (AreAliased(AA, Reads, Writes, R.MACCandidates))
671       return false;
672     CreateParallelMACPairs(R);
673     Changed |= InsertParallelMACs(R);
674   }
675 
676   LLVM_DEBUG(if (Changed) dbgs() << "Header block:\n"; Header->dump(););
677   return Changed;
678 }
679 
680 LoadInst* ARMParallelDSP::CreateLoadIns(IRBuilder<NoFolder> &IRB,
681                                         SmallVectorImpl<LoadInst*> &Loads,
682                                         IntegerType *LoadTy) {
683   assert(Loads.size() == 2 && "currently only support widening two loads");
684 
685   const unsigned AddrSpace = Loads[0]->getPointerAddressSpace();
686   Value *VecPtr = IRB.CreateBitCast(Loads[0]->getPointerOperand(),
687                                     LoadTy->getPointerTo(AddrSpace));
688   LoadInst *WideLoad = IRB.CreateAlignedLoad(LoadTy, VecPtr,
689                                              Loads[0]->getAlignment());
690   // Fix up users, Loads[0] needs trunc while Loads[1] needs a lshr and trunc.
691   Instruction *SExt0 = dyn_cast<SExtInst>(Loads[0]->user_back());
692   Instruction *SExt1 = dyn_cast<SExtInst>(Loads[1]->user_back());
693 
694   assert((Loads[0]->hasOneUse() && Loads[1]->hasOneUse() && SExt0 && SExt1) &&
695          "Loads should have a single, extending, user");
696 
697   std::function<void(Instruction*, Instruction*)> MoveAfter =
698     [&](Instruction* Source, Instruction* Sink) -> void {
699     if (DT->dominates(Source, Sink) ||
700         Source->getParent() != Sink->getParent() ||
701         isa<PHINode>(Source) || isa<PHINode>(Sink))
702       return;
703 
704     Sink->moveAfter(Source);
705     for (auto &U : Sink->uses())
706       MoveAfter(Sink, cast<Instruction>(U.getUser()));
707   };
708 
709   // From the wide load, create two values that equal the original two loads.
710   Value *Bottom = IRB.CreateTrunc(WideLoad, Loads[0]->getType());
711   SExt0->setOperand(0, Bottom);
712   if (auto *I = dyn_cast<Instruction>(Bottom)) {
713     I->moveAfter(WideLoad);
714     MoveAfter(I, SExt0);
715   }
716 
717   IntegerType *Ld1Ty = cast<IntegerType>(Loads[1]->getType());
718   Value *ShiftVal = ConstantInt::get(LoadTy, Ld1Ty->getBitWidth());
719   Value *Top = IRB.CreateLShr(WideLoad, ShiftVal);
720   if (auto *I = dyn_cast<Instruction>(Top))
721     MoveAfter(WideLoad, I);
722 
723   Value *Trunc = IRB.CreateTrunc(Top, Ld1Ty);
724   SExt1->setOperand(0, Trunc);
725   if (auto *I = dyn_cast<Instruction>(Trunc))
726     MoveAfter(I, SExt1);
727 
728   WideLoads.emplace(std::make_pair(Loads[0],
729                                    make_unique<WidenedLoad>(Loads, WideLoad)));
730   return WideLoad;
731 }
732 
733 Instruction *ARMParallelDSP::CreateSMLADCall(SmallVectorImpl<LoadInst*> &VecLd0,
734                                              SmallVectorImpl<LoadInst*> &VecLd1,
735                                              Instruction *Acc, bool Exchange,
736                                              Instruction *InsertAfter) {
737   LLVM_DEBUG(dbgs() << "Create SMLAD intrinsic using:\n"
738              << "- " << *VecLd0[0] << "\n"
739              << "- " << *VecLd0[1] << "\n"
740              << "- " << *VecLd1[0] << "\n"
741              << "- " << *VecLd1[1] << "\n"
742              << "- " << *Acc << "\n"
743              << "- Exchange: " << Exchange << "\n");
744 
745   IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
746                               ++BasicBlock::iterator(InsertAfter));
747 
748   // Replace the reduction chain with an intrinsic call
749   IntegerType *Ty = IntegerType::get(M->getContext(), 32);
750   LoadInst *WideLd0 = WideLoads.count(VecLd0[0]) ?
751     WideLoads[VecLd0[0]]->getLoad() : CreateLoadIns(Builder, VecLd0, Ty);
752   LoadInst *WideLd1 = WideLoads.count(VecLd1[0]) ?
753     WideLoads[VecLd1[0]]->getLoad() : CreateLoadIns(Builder, VecLd1, Ty);
754   Value* Args[] = { WideLd0, WideLd1, Acc };
755   Function *SMLAD = nullptr;
756   if (Exchange)
757     SMLAD = Acc->getType()->isIntegerTy(32) ?
758       Intrinsic::getDeclaration(M, Intrinsic::arm_smladx) :
759       Intrinsic::getDeclaration(M, Intrinsic::arm_smlaldx);
760   else
761     SMLAD = Acc->getType()->isIntegerTy(32) ?
762       Intrinsic::getDeclaration(M, Intrinsic::arm_smlad) :
763       Intrinsic::getDeclaration(M, Intrinsic::arm_smlald);
764   CallInst *Call = Builder.CreateCall(SMLAD, Args);
765   NumSMLAD++;
766   return Call;
767 }
768 
769 // Compare the value lists in Other to this chain.
770 bool BinOpChain::AreSymmetrical(BinOpChain *Other) {
771   // Element-by-element comparison of Value lists returning true if they are
772   // instructions with the same opcode or constants with the same value.
773   auto CompareValueList = [](const ValueList &VL0,
774                              const ValueList &VL1) {
775     if (VL0.size() != VL1.size()) {
776       LLVM_DEBUG(dbgs() << "Muls are mismatching operand list lengths: "
777                         << VL0.size() << " != " << VL1.size() << "\n");
778       return false;
779     }
780 
781     const unsigned Pairs = VL0.size();
782 
783     for (unsigned i = 0; i < Pairs; ++i) {
784       const Value *V0 = VL0[i];
785       const Value *V1 = VL1[i];
786       const auto *Inst0 = dyn_cast<Instruction>(V0);
787       const auto *Inst1 = dyn_cast<Instruction>(V1);
788 
789       if (!Inst0 || !Inst1)
790         return false;
791 
792       if (Inst0->isSameOperationAs(Inst1))
793         continue;
794 
795       const APInt *C0, *C1;
796       if (!(match(V0, m_APInt(C0)) && match(V1, m_APInt(C1)) && C0 == C1))
797         return false;
798     }
799 
800     return true;
801   };
802 
803   return CompareValueList(LHS, Other->LHS) &&
804          CompareValueList(RHS, Other->RHS);
805 }
806 
807 Pass *llvm::createARMParallelDSPPass() {
808   return new ARMParallelDSP();
809 }
810 
811 char ARMParallelDSP::ID = 0;
812 
813 INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp",
814                 "Transform loops to use DSP intrinsics", false, false)
815 INITIALIZE_PASS_END(ARMParallelDSP, "arm-parallel-dsp",
816                 "Transform loops to use DSP intrinsics", false, false)
817