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