1 //===- HexagonLoopIdiomRecognition.cpp ------------------------------------===//
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 #define DEBUG_TYPE "hexagon-lir"
11 
12 #include "llvm/ADT/APInt.h"
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SetVector.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/MemoryLocation.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Analysis/ScalarEvolutionExpander.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DebugLoc.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/InstrTypes.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/IntrinsicInst.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/PatternMatch.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/IR/User.h"
49 #include "llvm/IR/Value.h"
50 #include "llvm/Pass.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/KnownBits.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Scalar.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include <algorithm>
61 #include <array>
62 #include <cassert>
63 #include <cstdint>
64 #include <cstdlib>
65 #include <deque>
66 #include <functional>
67 #include <iterator>
68 #include <map>
69 #include <set>
70 #include <utility>
71 #include <vector>
72 
73 using namespace llvm;
74 
75 static cl::opt<bool> DisableMemcpyIdiom("disable-memcpy-idiom",
76   cl::Hidden, cl::init(false),
77   cl::desc("Disable generation of memcpy in loop idiom recognition"));
78 
79 static cl::opt<bool> DisableMemmoveIdiom("disable-memmove-idiom",
80   cl::Hidden, cl::init(false),
81   cl::desc("Disable generation of memmove in loop idiom recognition"));
82 
83 static cl::opt<unsigned> RuntimeMemSizeThreshold("runtime-mem-idiom-threshold",
84   cl::Hidden, cl::init(0), cl::desc("Threshold (in bytes) for the runtime "
85   "check guarding the memmove."));
86 
87 static cl::opt<unsigned> CompileTimeMemSizeThreshold(
88   "compile-time-mem-idiom-threshold", cl::Hidden, cl::init(64),
89   cl::desc("Threshold (in bytes) to perform the transformation, if the "
90     "runtime loop count (mem transfer size) is known at compile-time."));
91 
92 static cl::opt<bool> OnlyNonNestedMemmove("only-nonnested-memmove-idiom",
93   cl::Hidden, cl::init(true),
94   cl::desc("Only enable generating memmove in non-nested loops"));
95 
96 cl::opt<bool> HexagonVolatileMemcpy("disable-hexagon-volatile-memcpy",
97   cl::Hidden, cl::init(false),
98   cl::desc("Enable Hexagon-specific memcpy for volatile destination."));
99 
100 static cl::opt<unsigned> SimplifyLimit("hlir-simplify-limit", cl::init(10000),
101   cl::Hidden, cl::desc("Maximum number of simplification steps in HLIR"));
102 
103 static const char *HexagonVolatileMemcpyName
104   = "hexagon_memcpy_forward_vp4cp4n2";
105 
106 
107 namespace llvm {
108 
109   void initializeHexagonLoopIdiomRecognizePass(PassRegistry&);
110   Pass *createHexagonLoopIdiomPass();
111 
112 } // end namespace llvm
113 
114 namespace {
115 
116   class HexagonLoopIdiomRecognize : public LoopPass {
117   public:
118     static char ID;
119 
120     explicit HexagonLoopIdiomRecognize() : LoopPass(ID) {
121       initializeHexagonLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
122     }
123 
124     StringRef getPassName() const override {
125       return "Recognize Hexagon-specific loop idioms";
126     }
127 
128    void getAnalysisUsage(AnalysisUsage &AU) const override {
129       AU.addRequired<LoopInfoWrapperPass>();
130       AU.addRequiredID(LoopSimplifyID);
131       AU.addRequiredID(LCSSAID);
132       AU.addRequired<AAResultsWrapperPass>();
133       AU.addPreserved<AAResultsWrapperPass>();
134       AU.addRequired<ScalarEvolutionWrapperPass>();
135       AU.addRequired<DominatorTreeWrapperPass>();
136       AU.addRequired<TargetLibraryInfoWrapperPass>();
137       AU.addPreserved<TargetLibraryInfoWrapperPass>();
138     }
139 
140     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
141 
142   private:
143     unsigned getStoreSizeInBytes(StoreInst *SI);
144     int getSCEVStride(const SCEVAddRecExpr *StoreEv);
145     bool isLegalStore(Loop *CurLoop, StoreInst *SI);
146     void collectStores(Loop *CurLoop, BasicBlock *BB,
147         SmallVectorImpl<StoreInst*> &Stores);
148     bool processCopyingStore(Loop *CurLoop, StoreInst *SI, const SCEV *BECount);
149     bool coverLoop(Loop *L, SmallVectorImpl<Instruction*> &Insts) const;
150     bool runOnLoopBlock(Loop *CurLoop, BasicBlock *BB, const SCEV *BECount,
151         SmallVectorImpl<BasicBlock*> &ExitBlocks);
152     bool runOnCountableLoop(Loop *L);
153 
154     AliasAnalysis *AA;
155     const DataLayout *DL;
156     DominatorTree *DT;
157     LoopInfo *LF;
158     const TargetLibraryInfo *TLI;
159     ScalarEvolution *SE;
160     bool HasMemcpy, HasMemmove;
161   };
162 
163   struct Simplifier {
164     struct Rule {
165       using FuncType = std::function<Value* (Instruction*, LLVMContext&)>;
166       Rule(StringRef N, FuncType F) : Name(N), Fn(F) {}
167       StringRef Name;   // For debugging.
168       FuncType Fn;
169     };
170 
171     void addRule(StringRef N, const Rule::FuncType &F) {
172       Rules.push_back(Rule(N, F));
173     }
174 
175   private:
176     struct WorkListType {
177       WorkListType() = default;
178 
179       void push_back(Value* V) {
180         // Do not push back duplicates.
181         if (!S.count(V)) { Q.push_back(V); S.insert(V); }
182       }
183 
184       Value *pop_front_val() {
185         Value *V = Q.front(); Q.pop_front(); S.erase(V);
186         return V;
187       }
188 
189       bool empty() const { return Q.empty(); }
190 
191     private:
192       std::deque<Value*> Q;
193       std::set<Value*> S;
194     };
195 
196     using ValueSetType = std::set<Value *>;
197 
198     std::vector<Rule> Rules;
199 
200   public:
201     struct Context {
202       using ValueMapType = DenseMap<Value *, Value *>;
203 
204       Value *Root;
205       ValueSetType Used;    // The set of all cloned values used by Root.
206       ValueSetType Clones;  // The set of all cloned values.
207       LLVMContext &Ctx;
208 
209       Context(Instruction *Exp)
210         : Ctx(Exp->getParent()->getParent()->getContext()) {
211         initialize(Exp);
212       }
213 
214       ~Context() { cleanup(); }
215 
216       void print(raw_ostream &OS, const Value *V) const;
217       Value *materialize(BasicBlock *B, BasicBlock::iterator At);
218 
219     private:
220       friend struct Simplifier;
221 
222       void initialize(Instruction *Exp);
223       void cleanup();
224 
225       template <typename FuncT> void traverse(Value *V, FuncT F);
226       void record(Value *V);
227       void use(Value *V);
228       void unuse(Value *V);
229 
230       bool equal(const Instruction *I, const Instruction *J) const;
231       Value *find(Value *Tree, Value *Sub) const;
232       Value *subst(Value *Tree, Value *OldV, Value *NewV);
233       void replace(Value *OldV, Value *NewV);
234       void link(Instruction *I, BasicBlock *B, BasicBlock::iterator At);
235     };
236 
237     Value *simplify(Context &C);
238   };
239 
240   struct PE {
241     PE(const Simplifier::Context &c, Value *v = nullptr) : C(c), V(v) {}
242 
243     const Simplifier::Context &C;
244     const Value *V;
245   };
246 
247   raw_ostream &operator<< (raw_ostream &OS, const PE &P) LLVM_ATTRIBUTE_USED;
248   raw_ostream &operator<< (raw_ostream &OS, const PE &P) {
249     P.C.print(OS, P.V ? P.V : P.C.Root);
250     return OS;
251   }
252 
253 } // end anonymous namespace
254 
255 char HexagonLoopIdiomRecognize::ID = 0;
256 
257 INITIALIZE_PASS_BEGIN(HexagonLoopIdiomRecognize, "hexagon-loop-idiom",
258     "Recognize Hexagon-specific loop idioms", false, false)
259 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
260 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
261 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
262 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
263 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
264 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
265 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
266 INITIALIZE_PASS_END(HexagonLoopIdiomRecognize, "hexagon-loop-idiom",
267     "Recognize Hexagon-specific loop idioms", false, false)
268 
269 template <typename FuncT>
270 void Simplifier::Context::traverse(Value *V, FuncT F) {
271   WorkListType Q;
272   Q.push_back(V);
273 
274   while (!Q.empty()) {
275     Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
276     if (!U || U->getParent())
277       continue;
278     if (!F(U))
279       continue;
280     for (Value *Op : U->operands())
281       Q.push_back(Op);
282   }
283 }
284 
285 void Simplifier::Context::print(raw_ostream &OS, const Value *V) const {
286   const auto *U = dyn_cast<const Instruction>(V);
287   if (!U) {
288     OS << V << '(' << *V << ')';
289     return;
290   }
291 
292   if (U->getParent()) {
293     OS << U << '(';
294     U->printAsOperand(OS, true);
295     OS << ')';
296     return;
297   }
298 
299   unsigned N = U->getNumOperands();
300   if (N != 0)
301     OS << U << '(';
302   OS << U->getOpcodeName();
303   for (const Value *Op : U->operands()) {
304     OS << ' ';
305     print(OS, Op);
306   }
307   if (N != 0)
308     OS << ')';
309 }
310 
311 void Simplifier::Context::initialize(Instruction *Exp) {
312   // Perform a deep clone of the expression, set Root to the root
313   // of the clone, and build a map from the cloned values to the
314   // original ones.
315   ValueMapType M;
316   BasicBlock *Block = Exp->getParent();
317   WorkListType Q;
318   Q.push_back(Exp);
319 
320   while (!Q.empty()) {
321     Value *V = Q.pop_front_val();
322     if (M.find(V) != M.end())
323       continue;
324     if (Instruction *U = dyn_cast<Instruction>(V)) {
325       if (isa<PHINode>(U) || U->getParent() != Block)
326         continue;
327       for (Value *Op : U->operands())
328         Q.push_back(Op);
329       M.insert({U, U->clone()});
330     }
331   }
332 
333   for (std::pair<Value*,Value*> P : M) {
334     Instruction *U = cast<Instruction>(P.second);
335     for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
336       auto F = M.find(U->getOperand(i));
337       if (F != M.end())
338         U->setOperand(i, F->second);
339     }
340   }
341 
342   auto R = M.find(Exp);
343   assert(R != M.end());
344   Root = R->second;
345 
346   record(Root);
347   use(Root);
348 }
349 
350 void Simplifier::Context::record(Value *V) {
351   auto Record = [this](Instruction *U) -> bool {
352     Clones.insert(U);
353     return true;
354   };
355   traverse(V, Record);
356 }
357 
358 void Simplifier::Context::use(Value *V) {
359   auto Use = [this](Instruction *U) -> bool {
360     Used.insert(U);
361     return true;
362   };
363   traverse(V, Use);
364 }
365 
366 void Simplifier::Context::unuse(Value *V) {
367   if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != nullptr)
368     return;
369 
370   auto Unuse = [this](Instruction *U) -> bool {
371     if (!U->use_empty())
372       return false;
373     Used.erase(U);
374     return true;
375   };
376   traverse(V, Unuse);
377 }
378 
379 Value *Simplifier::Context::subst(Value *Tree, Value *OldV, Value *NewV) {
380   if (Tree == OldV)
381     return NewV;
382   if (OldV == NewV)
383     return Tree;
384 
385   WorkListType Q;
386   Q.push_back(Tree);
387   while (!Q.empty()) {
388     Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
389     // If U is not an instruction, or it's not a clone, skip it.
390     if (!U || U->getParent())
391       continue;
392     for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
393       Value *Op = U->getOperand(i);
394       if (Op == OldV) {
395         U->setOperand(i, NewV);
396         unuse(OldV);
397       } else {
398         Q.push_back(Op);
399       }
400     }
401   }
402   return Tree;
403 }
404 
405 void Simplifier::Context::replace(Value *OldV, Value *NewV) {
406   if (Root == OldV) {
407     Root = NewV;
408     use(Root);
409     return;
410   }
411 
412   // NewV may be a complex tree that has just been created by one of the
413   // transformation rules. We need to make sure that it is commoned with
414   // the existing Root to the maximum extent possible.
415   // Identify all subtrees of NewV (including NewV itself) that have
416   // equivalent counterparts in Root, and replace those subtrees with
417   // these counterparts.
418   WorkListType Q;
419   Q.push_back(NewV);
420   while (!Q.empty()) {
421     Value *V = Q.pop_front_val();
422     Instruction *U = dyn_cast<Instruction>(V);
423     if (!U || U->getParent())
424       continue;
425     if (Value *DupV = find(Root, V)) {
426       if (DupV != V)
427         NewV = subst(NewV, V, DupV);
428     } else {
429       for (Value *Op : U->operands())
430         Q.push_back(Op);
431     }
432   }
433 
434   // Now, simply replace OldV with NewV in Root.
435   Root = subst(Root, OldV, NewV);
436   use(Root);
437 }
438 
439 void Simplifier::Context::cleanup() {
440   for (Value *V : Clones) {
441     Instruction *U = cast<Instruction>(V);
442     if (!U->getParent())
443       U->dropAllReferences();
444   }
445 
446   for (Value *V : Clones) {
447     Instruction *U = cast<Instruction>(V);
448     if (!U->getParent())
449       U->deleteValue();
450   }
451 }
452 
453 bool Simplifier::Context::equal(const Instruction *I,
454                                 const Instruction *J) const {
455   if (I == J)
456     return true;
457   if (!I->isSameOperationAs(J))
458     return false;
459   if (isa<PHINode>(I))
460     return I->isIdenticalTo(J);
461 
462   for (unsigned i = 0, n = I->getNumOperands(); i != n; ++i) {
463     Value *OpI = I->getOperand(i), *OpJ = J->getOperand(i);
464     if (OpI == OpJ)
465       continue;
466     auto *InI = dyn_cast<const Instruction>(OpI);
467     auto *InJ = dyn_cast<const Instruction>(OpJ);
468     if (InI && InJ) {
469       if (!equal(InI, InJ))
470         return false;
471     } else if (InI != InJ || !InI)
472       return false;
473   }
474   return true;
475 }
476 
477 Value *Simplifier::Context::find(Value *Tree, Value *Sub) const {
478   Instruction *SubI = dyn_cast<Instruction>(Sub);
479   WorkListType Q;
480   Q.push_back(Tree);
481 
482   while (!Q.empty()) {
483     Value *V = Q.pop_front_val();
484     if (V == Sub)
485       return V;
486     Instruction *U = dyn_cast<Instruction>(V);
487     if (!U || U->getParent())
488       continue;
489     if (SubI && equal(SubI, U))
490       return U;
491     assert(!isa<PHINode>(U));
492     for (Value *Op : U->operands())
493       Q.push_back(Op);
494   }
495   return nullptr;
496 }
497 
498 void Simplifier::Context::link(Instruction *I, BasicBlock *B,
499       BasicBlock::iterator At) {
500   if (I->getParent())
501     return;
502 
503   for (Value *Op : I->operands()) {
504     if (Instruction *OpI = dyn_cast<Instruction>(Op))
505       link(OpI, B, At);
506   }
507 
508   B->getInstList().insert(At, I);
509 }
510 
511 Value *Simplifier::Context::materialize(BasicBlock *B,
512       BasicBlock::iterator At) {
513   if (Instruction *RootI = dyn_cast<Instruction>(Root))
514     link(RootI, B, At);
515   return Root;
516 }
517 
518 Value *Simplifier::simplify(Context &C) {
519   WorkListType Q;
520   Q.push_back(C.Root);
521   unsigned Count = 0;
522   const unsigned Limit = SimplifyLimit;
523 
524   while (!Q.empty()) {
525     if (Count++ >= Limit)
526       break;
527     Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
528     if (!U || U->getParent() || !C.Used.count(U))
529       continue;
530     bool Changed = false;
531     for (Rule &R : Rules) {
532       Value *W = R.Fn(U, C.Ctx);
533       if (!W)
534         continue;
535       Changed = true;
536       C.record(W);
537       C.replace(U, W);
538       Q.push_back(C.Root);
539       break;
540     }
541     if (!Changed) {
542       for (Value *Op : U->operands())
543         Q.push_back(Op);
544     }
545   }
546   return Count < Limit ? C.Root : nullptr;
547 }
548 
549 //===----------------------------------------------------------------------===//
550 //
551 //          Implementation of PolynomialMultiplyRecognize
552 //
553 //===----------------------------------------------------------------------===//
554 
555 namespace {
556 
557   class PolynomialMultiplyRecognize {
558   public:
559     explicit PolynomialMultiplyRecognize(Loop *loop, const DataLayout &dl,
560         const DominatorTree &dt, const TargetLibraryInfo &tli,
561         ScalarEvolution &se)
562       : CurLoop(loop), DL(dl), DT(dt), TLI(tli), SE(se) {}
563 
564     bool recognize();
565 
566   private:
567     using ValueSeq = SetVector<Value *>;
568 
569     IntegerType *getPmpyType() const {
570       LLVMContext &Ctx = CurLoop->getHeader()->getParent()->getContext();
571       return IntegerType::get(Ctx, 32);
572     }
573 
574     bool isPromotableTo(Value *V, IntegerType *Ty);
575     void promoteTo(Instruction *In, IntegerType *DestTy, BasicBlock *LoopB);
576     bool promoteTypes(BasicBlock *LoopB, BasicBlock *ExitB);
577 
578     Value *getCountIV(BasicBlock *BB);
579     bool findCycle(Value *Out, Value *In, ValueSeq &Cycle);
580     void classifyCycle(Instruction *DivI, ValueSeq &Cycle, ValueSeq &Early,
581           ValueSeq &Late);
582     bool classifyInst(Instruction *UseI, ValueSeq &Early, ValueSeq &Late);
583     bool commutesWithShift(Instruction *I);
584     bool highBitsAreZero(Value *V, unsigned IterCount);
585     bool keepsHighBitsZero(Value *V, unsigned IterCount);
586     bool isOperandShifted(Instruction *I, Value *Op);
587     bool convertShiftsToLeft(BasicBlock *LoopB, BasicBlock *ExitB,
588           unsigned IterCount);
589     void cleanupLoopBody(BasicBlock *LoopB);
590 
591     struct ParsedValues {
592       ParsedValues() = default;
593 
594       Value *M = nullptr;
595       Value *P = nullptr;
596       Value *Q = nullptr;
597       Value *R = nullptr;
598       Value *X = nullptr;
599       Instruction *Res = nullptr;
600       unsigned IterCount = 0;
601       bool Left = false;
602       bool Inv = false;
603     };
604 
605     bool matchLeftShift(SelectInst *SelI, Value *CIV, ParsedValues &PV);
606     bool matchRightShift(SelectInst *SelI, ParsedValues &PV);
607     bool scanSelect(SelectInst *SI, BasicBlock *LoopB, BasicBlock *PrehB,
608           Value *CIV, ParsedValues &PV, bool PreScan);
609     unsigned getInverseMxN(unsigned QP);
610     Value *generate(BasicBlock::iterator At, ParsedValues &PV);
611 
612     void setupSimplifier();
613 
614     Simplifier Simp;
615     Loop *CurLoop;
616     const DataLayout &DL;
617     const DominatorTree &DT;
618     const TargetLibraryInfo &TLI;
619     ScalarEvolution &SE;
620   };
621 
622 } // end anonymous namespace
623 
624 Value *PolynomialMultiplyRecognize::getCountIV(BasicBlock *BB) {
625   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
626   if (std::distance(PI, PE) != 2)
627     return nullptr;
628   BasicBlock *PB = (*PI == BB) ? *std::next(PI) : *PI;
629 
630   for (auto I = BB->begin(), E = BB->end(); I != E && isa<PHINode>(I); ++I) {
631     auto *PN = cast<PHINode>(I);
632     Value *InitV = PN->getIncomingValueForBlock(PB);
633     if (!isa<ConstantInt>(InitV) || !cast<ConstantInt>(InitV)->isZero())
634       continue;
635     Value *IterV = PN->getIncomingValueForBlock(BB);
636     if (!isa<BinaryOperator>(IterV))
637       continue;
638     auto *BO = dyn_cast<BinaryOperator>(IterV);
639     if (BO->getOpcode() != Instruction::Add)
640       continue;
641     Value *IncV = nullptr;
642     if (BO->getOperand(0) == PN)
643       IncV = BO->getOperand(1);
644     else if (BO->getOperand(1) == PN)
645       IncV = BO->getOperand(0);
646     if (IncV == nullptr)
647       continue;
648 
649     if (auto *T = dyn_cast<ConstantInt>(IncV))
650       if (T->getZExtValue() == 1)
651         return PN;
652   }
653   return nullptr;
654 }
655 
656 static void replaceAllUsesOfWithIn(Value *I, Value *J, BasicBlock *BB) {
657   for (auto UI = I->user_begin(), UE = I->user_end(); UI != UE;) {
658     Use &TheUse = UI.getUse();
659     ++UI;
660     if (auto *II = dyn_cast<Instruction>(TheUse.getUser()))
661       if (BB == II->getParent())
662         II->replaceUsesOfWith(I, J);
663   }
664 }
665 
666 bool PolynomialMultiplyRecognize::matchLeftShift(SelectInst *SelI,
667       Value *CIV, ParsedValues &PV) {
668   // Match the following:
669   //   select (X & (1 << i)) != 0 ? R ^ (Q << i) : R
670   //   select (X & (1 << i)) == 0 ? R : R ^ (Q << i)
671   // The condition may also check for equality with the masked value, i.e
672   //   select (X & (1 << i)) == (1 << i) ? R ^ (Q << i) : R
673   //   select (X & (1 << i)) != (1 << i) ? R : R ^ (Q << i);
674 
675   Value *CondV = SelI->getCondition();
676   Value *TrueV = SelI->getTrueValue();
677   Value *FalseV = SelI->getFalseValue();
678 
679   using namespace PatternMatch;
680 
681   CmpInst::Predicate P;
682   Value *A = nullptr, *B = nullptr, *C = nullptr;
683 
684   if (!match(CondV, m_ICmp(P, m_And(m_Value(A), m_Value(B)), m_Value(C))) &&
685       !match(CondV, m_ICmp(P, m_Value(C), m_And(m_Value(A), m_Value(B)))))
686     return false;
687   if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
688     return false;
689   // Matched: select (A & B) == C ? ... : ...
690   //          select (A & B) != C ? ... : ...
691 
692   Value *X = nullptr, *Sh1 = nullptr;
693   // Check (A & B) for (X & (1 << i)):
694   if (match(A, m_Shl(m_One(), m_Specific(CIV)))) {
695     Sh1 = A;
696     X = B;
697   } else if (match(B, m_Shl(m_One(), m_Specific(CIV)))) {
698     Sh1 = B;
699     X = A;
700   } else {
701     // TODO: Could also check for an induction variable containing single
702     // bit shifted left by 1 in each iteration.
703     return false;
704   }
705 
706   bool TrueIfZero;
707 
708   // Check C against the possible values for comparison: 0 and (1 << i):
709   if (match(C, m_Zero()))
710     TrueIfZero = (P == CmpInst::ICMP_EQ);
711   else if (C == Sh1)
712     TrueIfZero = (P == CmpInst::ICMP_NE);
713   else
714     return false;
715 
716   // So far, matched:
717   //   select (X & (1 << i)) ? ... : ...
718   // including variations of the check against zero/non-zero value.
719 
720   Value *ShouldSameV = nullptr, *ShouldXoredV = nullptr;
721   if (TrueIfZero) {
722     ShouldSameV = TrueV;
723     ShouldXoredV = FalseV;
724   } else {
725     ShouldSameV = FalseV;
726     ShouldXoredV = TrueV;
727   }
728 
729   Value *Q = nullptr, *R = nullptr, *Y = nullptr, *Z = nullptr;
730   Value *T = nullptr;
731   if (match(ShouldXoredV, m_Xor(m_Value(Y), m_Value(Z)))) {
732     // Matched: select +++ ? ... : Y ^ Z
733     //          select +++ ? Y ^ Z : ...
734     // where +++ denotes previously checked matches.
735     if (ShouldSameV == Y)
736       T = Z;
737     else if (ShouldSameV == Z)
738       T = Y;
739     else
740       return false;
741     R = ShouldSameV;
742     // Matched: select +++ ? R : R ^ T
743     //          select +++ ? R ^ T : R
744     // depending on TrueIfZero.
745 
746   } else if (match(ShouldSameV, m_Zero())) {
747     // Matched: select +++ ? 0 : ...
748     //          select +++ ? ... : 0
749     if (!SelI->hasOneUse())
750       return false;
751     T = ShouldXoredV;
752     // Matched: select +++ ? 0 : T
753     //          select +++ ? T : 0
754 
755     Value *U = *SelI->user_begin();
756     if (!match(U, m_Xor(m_Specific(SelI), m_Value(R))) &&
757         !match(U, m_Xor(m_Value(R), m_Specific(SelI))))
758       return false;
759     // Matched: xor (select +++ ? 0 : T), R
760     //          xor (select +++ ? T : 0), R
761   } else
762     return false;
763 
764   // The xor input value T is isolated into its own match so that it could
765   // be checked against an induction variable containing a shifted bit
766   // (todo).
767   // For now, check against (Q << i).
768   if (!match(T, m_Shl(m_Value(Q), m_Specific(CIV))) &&
769       !match(T, m_Shl(m_ZExt(m_Value(Q)), m_ZExt(m_Specific(CIV)))))
770     return false;
771   // Matched: select +++ ? R : R ^ (Q << i)
772   //          select +++ ? R ^ (Q << i) : R
773 
774   PV.X = X;
775   PV.Q = Q;
776   PV.R = R;
777   PV.Left = true;
778   return true;
779 }
780 
781 bool PolynomialMultiplyRecognize::matchRightShift(SelectInst *SelI,
782       ParsedValues &PV) {
783   // Match the following:
784   //   select (X & 1) != 0 ? (R >> 1) ^ Q : (R >> 1)
785   //   select (X & 1) == 0 ? (R >> 1) : (R >> 1) ^ Q
786   // The condition may also check for equality with the masked value, i.e
787   //   select (X & 1) == 1 ? (R >> 1) ^ Q : (R >> 1)
788   //   select (X & 1) != 1 ? (R >> 1) : (R >> 1) ^ Q
789 
790   Value *CondV = SelI->getCondition();
791   Value *TrueV = SelI->getTrueValue();
792   Value *FalseV = SelI->getFalseValue();
793 
794   using namespace PatternMatch;
795 
796   Value *C = nullptr;
797   CmpInst::Predicate P;
798   bool TrueIfZero;
799 
800   if (match(CondV, m_ICmp(P, m_Value(C), m_Zero())) ||
801       match(CondV, m_ICmp(P, m_Zero(), m_Value(C)))) {
802     if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
803       return false;
804     // Matched: select C == 0 ? ... : ...
805     //          select C != 0 ? ... : ...
806     TrueIfZero = (P == CmpInst::ICMP_EQ);
807   } else if (match(CondV, m_ICmp(P, m_Value(C), m_One())) ||
808              match(CondV, m_ICmp(P, m_One(), m_Value(C)))) {
809     if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
810       return false;
811     // Matched: select C == 1 ? ... : ...
812     //          select C != 1 ? ... : ...
813     TrueIfZero = (P == CmpInst::ICMP_NE);
814   } else
815     return false;
816 
817   Value *X = nullptr;
818   if (!match(C, m_And(m_Value(X), m_One())) &&
819       !match(C, m_And(m_One(), m_Value(X))))
820     return false;
821   // Matched: select (X & 1) == +++ ? ... : ...
822   //          select (X & 1) != +++ ? ... : ...
823 
824   Value *R = nullptr, *Q = nullptr;
825   if (TrueIfZero) {
826     // The select's condition is true if the tested bit is 0.
827     // TrueV must be the shift, FalseV must be the xor.
828     if (!match(TrueV, m_LShr(m_Value(R), m_One())))
829       return false;
830     // Matched: select +++ ? (R >> 1) : ...
831     if (!match(FalseV, m_Xor(m_Specific(TrueV), m_Value(Q))) &&
832         !match(FalseV, m_Xor(m_Value(Q), m_Specific(TrueV))))
833       return false;
834     // Matched: select +++ ? (R >> 1) : (R >> 1) ^ Q
835     // with commuting ^.
836   } else {
837     // The select's condition is true if the tested bit is 1.
838     // TrueV must be the xor, FalseV must be the shift.
839     if (!match(FalseV, m_LShr(m_Value(R), m_One())))
840       return false;
841     // Matched: select +++ ? ... : (R >> 1)
842     if (!match(TrueV, m_Xor(m_Specific(FalseV), m_Value(Q))) &&
843         !match(TrueV, m_Xor(m_Value(Q), m_Specific(FalseV))))
844       return false;
845     // Matched: select +++ ? (R >> 1) ^ Q : (R >> 1)
846     // with commuting ^.
847   }
848 
849   PV.X = X;
850   PV.Q = Q;
851   PV.R = R;
852   PV.Left = false;
853   return true;
854 }
855 
856 bool PolynomialMultiplyRecognize::scanSelect(SelectInst *SelI,
857       BasicBlock *LoopB, BasicBlock *PrehB, Value *CIV, ParsedValues &PV,
858       bool PreScan) {
859   using namespace PatternMatch;
860 
861   // The basic pattern for R = P.Q is:
862   // for i = 0..31
863   //   R = phi (0, R')
864   //   if (P & (1 << i))        ; test-bit(P, i)
865   //     R' = R ^ (Q << i)
866   //
867   // Similarly, the basic pattern for R = (P/Q).Q - P
868   // for i = 0..31
869   //   R = phi(P, R')
870   //   if (R & (1 << i))
871   //     R' = R ^ (Q << i)
872 
873   // There exist idioms, where instead of Q being shifted left, P is shifted
874   // right. This produces a result that is shifted right by 32 bits (the
875   // non-shifted result is 64-bit).
876   //
877   // For R = P.Q, this would be:
878   // for i = 0..31
879   //   R = phi (0, R')
880   //   if ((P >> i) & 1)
881   //     R' = (R >> 1) ^ Q      ; R is cycled through the loop, so it must
882   //   else                     ; be shifted by 1, not i.
883   //     R' = R >> 1
884   //
885   // And for the inverse:
886   // for i = 0..31
887   //   R = phi (P, R')
888   //   if (R & 1)
889   //     R' = (R >> 1) ^ Q
890   //   else
891   //     R' = R >> 1
892 
893   // The left-shifting idioms share the same pattern:
894   //   select (X & (1 << i)) ? R ^ (Q << i) : R
895   // Similarly for right-shifting idioms:
896   //   select (X & 1) ? (R >> 1) ^ Q
897 
898   if (matchLeftShift(SelI, CIV, PV)) {
899     // If this is a pre-scan, getting this far is sufficient.
900     if (PreScan)
901       return true;
902 
903     // Need to make sure that the SelI goes back into R.
904     auto *RPhi = dyn_cast<PHINode>(PV.R);
905     if (!RPhi)
906       return false;
907     if (SelI != RPhi->getIncomingValueForBlock(LoopB))
908       return false;
909     PV.Res = SelI;
910 
911     // If X is loop invariant, it must be the input polynomial, and the
912     // idiom is the basic polynomial multiply.
913     if (CurLoop->isLoopInvariant(PV.X)) {
914       PV.P = PV.X;
915       PV.Inv = false;
916     } else {
917       // X is not loop invariant. If X == R, this is the inverse pmpy.
918       // Otherwise, check for an xor with an invariant value. If the
919       // variable argument to the xor is R, then this is still a valid
920       // inverse pmpy.
921       PV.Inv = true;
922       if (PV.X != PV.R) {
923         Value *Var = nullptr, *Inv = nullptr, *X1 = nullptr, *X2 = nullptr;
924         if (!match(PV.X, m_Xor(m_Value(X1), m_Value(X2))))
925           return false;
926         auto *I1 = dyn_cast<Instruction>(X1);
927         auto *I2 = dyn_cast<Instruction>(X2);
928         if (!I1 || I1->getParent() != LoopB) {
929           Var = X2;
930           Inv = X1;
931         } else if (!I2 || I2->getParent() != LoopB) {
932           Var = X1;
933           Inv = X2;
934         } else
935           return false;
936         if (Var != PV.R)
937           return false;
938         PV.M = Inv;
939       }
940       // The input polynomial P still needs to be determined. It will be
941       // the entry value of R.
942       Value *EntryP = RPhi->getIncomingValueForBlock(PrehB);
943       PV.P = EntryP;
944     }
945 
946     return true;
947   }
948 
949   if (matchRightShift(SelI, PV)) {
950     // If this is an inverse pattern, the Q polynomial must be known at
951     // compile time.
952     if (PV.Inv && !isa<ConstantInt>(PV.Q))
953       return false;
954     if (PreScan)
955       return true;
956     // There is no exact matching of right-shift pmpy.
957     return false;
958   }
959 
960   return false;
961 }
962 
963 bool PolynomialMultiplyRecognize::isPromotableTo(Value *Val,
964       IntegerType *DestTy) {
965   IntegerType *T = dyn_cast<IntegerType>(Val->getType());
966   if (!T || T->getBitWidth() > DestTy->getBitWidth())
967     return false;
968   if (T->getBitWidth() == DestTy->getBitWidth())
969     return true;
970   // Non-instructions are promotable. The reason why an instruction may not
971   // be promotable is that it may produce a different result if its operands
972   // and the result are promoted, for example, it may produce more non-zero
973   // bits. While it would still be possible to represent the proper result
974   // in a wider type, it may require adding additional instructions (which
975   // we don't want to do).
976   Instruction *In = dyn_cast<Instruction>(Val);
977   if (!In)
978     return true;
979   // The bitwidth of the source type is smaller than the destination.
980   // Check if the individual operation can be promoted.
981   switch (In->getOpcode()) {
982     case Instruction::PHI:
983     case Instruction::ZExt:
984     case Instruction::And:
985     case Instruction::Or:
986     case Instruction::Xor:
987     case Instruction::LShr: // Shift right is ok.
988     case Instruction::Select:
989       return true;
990     case Instruction::ICmp:
991       if (CmpInst *CI = cast<CmpInst>(In))
992         return CI->isEquality() || CI->isUnsigned();
993       llvm_unreachable("Cast failed unexpectedly");
994     case Instruction::Add:
995       return In->hasNoSignedWrap() && In->hasNoUnsignedWrap();
996   }
997   return false;
998 }
999 
1000 void PolynomialMultiplyRecognize::promoteTo(Instruction *In,
1001       IntegerType *DestTy, BasicBlock *LoopB) {
1002   // Leave boolean values alone.
1003   if (!In->getType()->isIntegerTy(1))
1004     In->mutateType(DestTy);
1005   unsigned DestBW = DestTy->getBitWidth();
1006 
1007   // Handle PHIs.
1008   if (PHINode *P = dyn_cast<PHINode>(In)) {
1009     unsigned N = P->getNumIncomingValues();
1010     for (unsigned i = 0; i != N; ++i) {
1011       BasicBlock *InB = P->getIncomingBlock(i);
1012       if (InB == LoopB)
1013         continue;
1014       Value *InV = P->getIncomingValue(i);
1015       IntegerType *Ty = cast<IntegerType>(InV->getType());
1016       // Do not promote values in PHI nodes of type i1.
1017       if (Ty != P->getType()) {
1018         // If the value type does not match the PHI type, the PHI type
1019         // must have been promoted.
1020         assert(Ty->getBitWidth() < DestBW);
1021         InV = IRBuilder<>(InB->getTerminator()).CreateZExt(InV, DestTy);
1022         P->setIncomingValue(i, InV);
1023       }
1024     }
1025   } else if (ZExtInst *Z = dyn_cast<ZExtInst>(In)) {
1026     Value *Op = Z->getOperand(0);
1027     if (Op->getType() == Z->getType())
1028       Z->replaceAllUsesWith(Op);
1029     Z->eraseFromParent();
1030     return;
1031   }
1032 
1033   // Promote immediates.
1034   for (unsigned i = 0, n = In->getNumOperands(); i != n; ++i) {
1035     if (ConstantInt *CI = dyn_cast<ConstantInt>(In->getOperand(i)))
1036       if (CI->getType()->getBitWidth() < DestBW)
1037         In->setOperand(i, ConstantInt::get(DestTy, CI->getZExtValue()));
1038   }
1039 }
1040 
1041 bool PolynomialMultiplyRecognize::promoteTypes(BasicBlock *LoopB,
1042       BasicBlock *ExitB) {
1043   assert(LoopB);
1044   // Skip loops where the exit block has more than one predecessor. The values
1045   // coming from the loop block will be promoted to another type, and so the
1046   // values coming into the exit block from other predecessors would also have
1047   // to be promoted.
1048   if (!ExitB || (ExitB->getSinglePredecessor() != LoopB))
1049     return false;
1050   IntegerType *DestTy = getPmpyType();
1051   // Check if the exit values have types that are no wider than the type
1052   // that we want to promote to.
1053   unsigned DestBW = DestTy->getBitWidth();
1054   for (Instruction &In : *ExitB) {
1055     PHINode *P = dyn_cast<PHINode>(&In);
1056     if (!P)
1057       break;
1058     if (P->getNumIncomingValues() != 1)
1059       return false;
1060     assert(P->getIncomingBlock(0) == LoopB);
1061     IntegerType *T = dyn_cast<IntegerType>(P->getType());
1062     if (!T || T->getBitWidth() > DestBW)
1063       return false;
1064   }
1065 
1066   // Check all instructions in the loop.
1067   for (Instruction &In : *LoopB)
1068     if (!In.isTerminator() && !isPromotableTo(&In, DestTy))
1069       return false;
1070 
1071   // Perform the promotion.
1072   std::vector<Instruction*> LoopIns;
1073   std::transform(LoopB->begin(), LoopB->end(), std::back_inserter(LoopIns),
1074                  [](Instruction &In) { return &In; });
1075   for (Instruction *In : LoopIns)
1076     promoteTo(In, DestTy, LoopB);
1077 
1078   // Fix up the PHI nodes in the exit block.
1079   Instruction *EndI = ExitB->getFirstNonPHI();
1080   BasicBlock::iterator End = EndI ? EndI->getIterator() : ExitB->end();
1081   for (auto I = ExitB->begin(); I != End; ++I) {
1082     PHINode *P = dyn_cast<PHINode>(I);
1083     if (!P)
1084       break;
1085     Type *Ty0 = P->getIncomingValue(0)->getType();
1086     Type *PTy = P->getType();
1087     if (PTy != Ty0) {
1088       assert(Ty0 == DestTy);
1089       // In order to create the trunc, P must have the promoted type.
1090       P->mutateType(Ty0);
1091       Value *T = IRBuilder<>(ExitB, End).CreateTrunc(P, PTy);
1092       // In order for the RAUW to work, the types of P and T must match.
1093       P->mutateType(PTy);
1094       P->replaceAllUsesWith(T);
1095       // Final update of the P's type.
1096       P->mutateType(Ty0);
1097       cast<Instruction>(T)->setOperand(0, P);
1098     }
1099   }
1100 
1101   return true;
1102 }
1103 
1104 bool PolynomialMultiplyRecognize::findCycle(Value *Out, Value *In,
1105       ValueSeq &Cycle) {
1106   // Out = ..., In, ...
1107   if (Out == In)
1108     return true;
1109 
1110   auto *BB = cast<Instruction>(Out)->getParent();
1111   bool HadPhi = false;
1112 
1113   for (auto U : Out->users()) {
1114     auto *I = dyn_cast<Instruction>(&*U);
1115     if (I == nullptr || I->getParent() != BB)
1116       continue;
1117     // Make sure that there are no multi-iteration cycles, e.g.
1118     //   p1 = phi(p2)
1119     //   p2 = phi(p1)
1120     // The cycle p1->p2->p1 would span two loop iterations.
1121     // Check that there is only one phi in the cycle.
1122     bool IsPhi = isa<PHINode>(I);
1123     if (IsPhi && HadPhi)
1124       return false;
1125     HadPhi |= IsPhi;
1126     if (Cycle.count(I))
1127       return false;
1128     Cycle.insert(I);
1129     if (findCycle(I, In, Cycle))
1130       break;
1131     Cycle.remove(I);
1132   }
1133   return !Cycle.empty();
1134 }
1135 
1136 void PolynomialMultiplyRecognize::classifyCycle(Instruction *DivI,
1137       ValueSeq &Cycle, ValueSeq &Early, ValueSeq &Late) {
1138   // All the values in the cycle that are between the phi node and the
1139   // divider instruction will be classified as "early", all other values
1140   // will be "late".
1141 
1142   bool IsE = true;
1143   unsigned I, N = Cycle.size();
1144   for (I = 0; I < N; ++I) {
1145     Value *V = Cycle[I];
1146     if (DivI == V)
1147       IsE = false;
1148     else if (!isa<PHINode>(V))
1149       continue;
1150     // Stop if found either.
1151     break;
1152   }
1153   // "I" is the index of either DivI or the phi node, whichever was first.
1154   // "E" is "false" or "true" respectively.
1155   ValueSeq &First = !IsE ? Early : Late;
1156   for (unsigned J = 0; J < I; ++J)
1157     First.insert(Cycle[J]);
1158 
1159   ValueSeq &Second = IsE ? Early : Late;
1160   Second.insert(Cycle[I]);
1161   for (++I; I < N; ++I) {
1162     Value *V = Cycle[I];
1163     if (DivI == V || isa<PHINode>(V))
1164       break;
1165     Second.insert(V);
1166   }
1167 
1168   for (; I < N; ++I)
1169     First.insert(Cycle[I]);
1170 }
1171 
1172 bool PolynomialMultiplyRecognize::classifyInst(Instruction *UseI,
1173       ValueSeq &Early, ValueSeq &Late) {
1174   // Select is an exception, since the condition value does not have to be
1175   // classified in the same way as the true/false values. The true/false
1176   // values do have to be both early or both late.
1177   if (UseI->getOpcode() == Instruction::Select) {
1178     Value *TV = UseI->getOperand(1), *FV = UseI->getOperand(2);
1179     if (Early.count(TV) || Early.count(FV)) {
1180       if (Late.count(TV) || Late.count(FV))
1181         return false;
1182       Early.insert(UseI);
1183     } else if (Late.count(TV) || Late.count(FV)) {
1184       if (Early.count(TV) || Early.count(FV))
1185         return false;
1186       Late.insert(UseI);
1187     }
1188     return true;
1189   }
1190 
1191   // Not sure what would be the example of this, but the code below relies
1192   // on having at least one operand.
1193   if (UseI->getNumOperands() == 0)
1194     return true;
1195 
1196   bool AE = true, AL = true;
1197   for (auto &I : UseI->operands()) {
1198     if (Early.count(&*I))
1199       AL = false;
1200     else if (Late.count(&*I))
1201       AE = false;
1202   }
1203   // If the operands appear "all early" and "all late" at the same time,
1204   // then it means that none of them are actually classified as either.
1205   // This is harmless.
1206   if (AE && AL)
1207     return true;
1208   // Conversely, if they are neither "all early" nor "all late", then
1209   // we have a mixture of early and late operands that is not a known
1210   // exception.
1211   if (!AE && !AL)
1212     return false;
1213 
1214   // Check that we have covered the two special cases.
1215   assert(AE != AL);
1216 
1217   if (AE)
1218     Early.insert(UseI);
1219   else
1220     Late.insert(UseI);
1221   return true;
1222 }
1223 
1224 bool PolynomialMultiplyRecognize::commutesWithShift(Instruction *I) {
1225   switch (I->getOpcode()) {
1226     case Instruction::And:
1227     case Instruction::Or:
1228     case Instruction::Xor:
1229     case Instruction::LShr:
1230     case Instruction::Shl:
1231     case Instruction::Select:
1232     case Instruction::ICmp:
1233     case Instruction::PHI:
1234       break;
1235     default:
1236       return false;
1237   }
1238   return true;
1239 }
1240 
1241 bool PolynomialMultiplyRecognize::highBitsAreZero(Value *V,
1242       unsigned IterCount) {
1243   auto *T = dyn_cast<IntegerType>(V->getType());
1244   if (!T)
1245     return false;
1246 
1247   KnownBits Known(T->getBitWidth());
1248   computeKnownBits(V, Known, DL);
1249   return Known.countMinLeadingZeros() >= IterCount;
1250 }
1251 
1252 bool PolynomialMultiplyRecognize::keepsHighBitsZero(Value *V,
1253       unsigned IterCount) {
1254   // Assume that all inputs to the value have the high bits zero.
1255   // Check if the value itself preserves the zeros in the high bits.
1256   if (auto *C = dyn_cast<ConstantInt>(V))
1257     return C->getValue().countLeadingZeros() >= IterCount;
1258 
1259   if (auto *I = dyn_cast<Instruction>(V)) {
1260     switch (I->getOpcode()) {
1261       case Instruction::And:
1262       case Instruction::Or:
1263       case Instruction::Xor:
1264       case Instruction::LShr:
1265       case Instruction::Select:
1266       case Instruction::ICmp:
1267       case Instruction::PHI:
1268       case Instruction::ZExt:
1269         return true;
1270     }
1271   }
1272 
1273   return false;
1274 }
1275 
1276 bool PolynomialMultiplyRecognize::isOperandShifted(Instruction *I, Value *Op) {
1277   unsigned Opc = I->getOpcode();
1278   if (Opc == Instruction::Shl || Opc == Instruction::LShr)
1279     return Op != I->getOperand(1);
1280   return true;
1281 }
1282 
1283 bool PolynomialMultiplyRecognize::convertShiftsToLeft(BasicBlock *LoopB,
1284       BasicBlock *ExitB, unsigned IterCount) {
1285   Value *CIV = getCountIV(LoopB);
1286   if (CIV == nullptr)
1287     return false;
1288   auto *CIVTy = dyn_cast<IntegerType>(CIV->getType());
1289   if (CIVTy == nullptr)
1290     return false;
1291 
1292   ValueSeq RShifts;
1293   ValueSeq Early, Late, Cycled;
1294 
1295   // Find all value cycles that contain logical right shifts by 1.
1296   for (Instruction &I : *LoopB) {
1297     using namespace PatternMatch;
1298 
1299     Value *V = nullptr;
1300     if (!match(&I, m_LShr(m_Value(V), m_One())))
1301       continue;
1302     ValueSeq C;
1303     if (!findCycle(&I, V, C))
1304       continue;
1305 
1306     // Found a cycle.
1307     C.insert(&I);
1308     classifyCycle(&I, C, Early, Late);
1309     Cycled.insert(C.begin(), C.end());
1310     RShifts.insert(&I);
1311   }
1312 
1313   // Find the set of all values affected by the shift cycles, i.e. all
1314   // cycled values, and (recursively) all their users.
1315   ValueSeq Users(Cycled.begin(), Cycled.end());
1316   for (unsigned i = 0; i < Users.size(); ++i) {
1317     Value *V = Users[i];
1318     if (!isa<IntegerType>(V->getType()))
1319       return false;
1320     auto *R = cast<Instruction>(V);
1321     // If the instruction does not commute with shifts, the loop cannot
1322     // be unshifted.
1323     if (!commutesWithShift(R))
1324       return false;
1325     for (auto I = R->user_begin(), E = R->user_end(); I != E; ++I) {
1326       auto *T = cast<Instruction>(*I);
1327       // Skip users from outside of the loop. They will be handled later.
1328       // Also, skip the right-shifts and phi nodes, since they mix early
1329       // and late values.
1330       if (T->getParent() != LoopB || RShifts.count(T) || isa<PHINode>(T))
1331         continue;
1332 
1333       Users.insert(T);
1334       if (!classifyInst(T, Early, Late))
1335         return false;
1336     }
1337   }
1338 
1339   if (Users.empty())
1340     return false;
1341 
1342   // Verify that high bits remain zero.
1343   ValueSeq Internal(Users.begin(), Users.end());
1344   ValueSeq Inputs;
1345   for (unsigned i = 0; i < Internal.size(); ++i) {
1346     auto *R = dyn_cast<Instruction>(Internal[i]);
1347     if (!R)
1348       continue;
1349     for (Value *Op : R->operands()) {
1350       auto *T = dyn_cast<Instruction>(Op);
1351       if (T && T->getParent() != LoopB)
1352         Inputs.insert(Op);
1353       else
1354         Internal.insert(Op);
1355     }
1356   }
1357   for (Value *V : Inputs)
1358     if (!highBitsAreZero(V, IterCount))
1359       return false;
1360   for (Value *V : Internal)
1361     if (!keepsHighBitsZero(V, IterCount))
1362       return false;
1363 
1364   // Finally, the work can be done. Unshift each user.
1365   IRBuilder<> IRB(LoopB);
1366   std::map<Value*,Value*> ShiftMap;
1367 
1368   using CastMapType = std::map<std::pair<Value *, Type *>, Value *>;
1369 
1370   CastMapType CastMap;
1371 
1372   auto upcast = [] (CastMapType &CM, IRBuilder<> &IRB, Value *V,
1373         IntegerType *Ty) -> Value* {
1374     auto H = CM.find(std::make_pair(V, Ty));
1375     if (H != CM.end())
1376       return H->second;
1377     Value *CV = IRB.CreateIntCast(V, Ty, false);
1378     CM.insert(std::make_pair(std::make_pair(V, Ty), CV));
1379     return CV;
1380   };
1381 
1382   for (auto I = LoopB->begin(), E = LoopB->end(); I != E; ++I) {
1383     using namespace PatternMatch;
1384 
1385     if (isa<PHINode>(I) || !Users.count(&*I))
1386       continue;
1387 
1388     // Match lshr x, 1.
1389     Value *V = nullptr;
1390     if (match(&*I, m_LShr(m_Value(V), m_One()))) {
1391       replaceAllUsesOfWithIn(&*I, V, LoopB);
1392       continue;
1393     }
1394     // For each non-cycled operand, replace it with the corresponding
1395     // value shifted left.
1396     for (auto &J : I->operands()) {
1397       Value *Op = J.get();
1398       if (!isOperandShifted(&*I, Op))
1399         continue;
1400       if (Users.count(Op))
1401         continue;
1402       // Skip shifting zeros.
1403       if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
1404         continue;
1405       // Check if we have already generated a shift for this value.
1406       auto F = ShiftMap.find(Op);
1407       Value *W = (F != ShiftMap.end()) ? F->second : nullptr;
1408       if (W == nullptr) {
1409         IRB.SetInsertPoint(&*I);
1410         // First, the shift amount will be CIV or CIV+1, depending on
1411         // whether the value is early or late. Instead of creating CIV+1,
1412         // do a single shift of the value.
1413         Value *ShAmt = CIV, *ShVal = Op;
1414         auto *VTy = cast<IntegerType>(ShVal->getType());
1415         auto *ATy = cast<IntegerType>(ShAmt->getType());
1416         if (Late.count(&*I))
1417           ShVal = IRB.CreateShl(Op, ConstantInt::get(VTy, 1));
1418         // Second, the types of the shifted value and the shift amount
1419         // must match.
1420         if (VTy != ATy) {
1421           if (VTy->getBitWidth() < ATy->getBitWidth())
1422             ShVal = upcast(CastMap, IRB, ShVal, ATy);
1423           else
1424             ShAmt = upcast(CastMap, IRB, ShAmt, VTy);
1425         }
1426         // Ready to generate the shift and memoize it.
1427         W = IRB.CreateShl(ShVal, ShAmt);
1428         ShiftMap.insert(std::make_pair(Op, W));
1429       }
1430       I->replaceUsesOfWith(Op, W);
1431     }
1432   }
1433 
1434   // Update the users outside of the loop to account for having left
1435   // shifts. They would normally be shifted right in the loop, so shift
1436   // them right after the loop exit.
1437   // Take advantage of the loop-closed SSA form, which has all the post-
1438   // loop values in phi nodes.
1439   IRB.SetInsertPoint(ExitB, ExitB->getFirstInsertionPt());
1440   for (auto P = ExitB->begin(), Q = ExitB->end(); P != Q; ++P) {
1441     if (!isa<PHINode>(P))
1442       break;
1443     auto *PN = cast<PHINode>(P);
1444     Value *U = PN->getIncomingValueForBlock(LoopB);
1445     if (!Users.count(U))
1446       continue;
1447     Value *S = IRB.CreateLShr(PN, ConstantInt::get(PN->getType(), IterCount));
1448     PN->replaceAllUsesWith(S);
1449     // The above RAUW will create
1450     //   S = lshr S, IterCount
1451     // so we need to fix it back into
1452     //   S = lshr PN, IterCount
1453     cast<User>(S)->replaceUsesOfWith(S, PN);
1454   }
1455 
1456   return true;
1457 }
1458 
1459 void PolynomialMultiplyRecognize::cleanupLoopBody(BasicBlock *LoopB) {
1460   for (auto &I : *LoopB)
1461     if (Value *SV = SimplifyInstruction(&I, {DL, &TLI, &DT}))
1462       I.replaceAllUsesWith(SV);
1463 
1464   for (auto I = LoopB->begin(), N = I; I != LoopB->end(); I = N) {
1465     N = std::next(I);
1466     RecursivelyDeleteTriviallyDeadInstructions(&*I, &TLI);
1467   }
1468 }
1469 
1470 unsigned PolynomialMultiplyRecognize::getInverseMxN(unsigned QP) {
1471   // Arrays of coefficients of Q and the inverse, C.
1472   // Q[i] = coefficient at x^i.
1473   std::array<char,32> Q, C;
1474 
1475   for (unsigned i = 0; i < 32; ++i) {
1476     Q[i] = QP & 1;
1477     QP >>= 1;
1478   }
1479   assert(Q[0] == 1);
1480 
1481   // Find C, such that
1482   // (Q[n]*x^n + ... + Q[1]*x + Q[0]) * (C[n]*x^n + ... + C[1]*x + C[0]) = 1
1483   //
1484   // For it to have a solution, Q[0] must be 1. Since this is Z2[x], the
1485   // operations * and + are & and ^ respectively.
1486   //
1487   // Find C[i] recursively, by comparing i-th coefficient in the product
1488   // with 0 (or 1 for i=0).
1489   //
1490   // C[0] = 1, since C[0] = Q[0], and Q[0] = 1.
1491   C[0] = 1;
1492   for (unsigned i = 1; i < 32; ++i) {
1493     // Solve for C[i] in:
1494     //   C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i]Q[0] = 0
1495     // This is equivalent to
1496     //   C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i] = 0
1497     // which is
1498     //   C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] = C[i]
1499     unsigned T = 0;
1500     for (unsigned j = 0; j < i; ++j)
1501       T = T ^ (C[j] & Q[i-j]);
1502     C[i] = T;
1503   }
1504 
1505   unsigned QV = 0;
1506   for (unsigned i = 0; i < 32; ++i)
1507     if (C[i])
1508       QV |= (1 << i);
1509 
1510   return QV;
1511 }
1512 
1513 Value *PolynomialMultiplyRecognize::generate(BasicBlock::iterator At,
1514       ParsedValues &PV) {
1515   IRBuilder<> B(&*At);
1516   Module *M = At->getParent()->getParent()->getParent();
1517   Value *PMF = Intrinsic::getDeclaration(M, Intrinsic::hexagon_M4_pmpyw);
1518 
1519   Value *P = PV.P, *Q = PV.Q, *P0 = P;
1520   unsigned IC = PV.IterCount;
1521 
1522   if (PV.M != nullptr)
1523     P0 = P = B.CreateXor(P, PV.M);
1524 
1525   // Create a bit mask to clear the high bits beyond IterCount.
1526   auto *BMI = ConstantInt::get(P->getType(), APInt::getLowBitsSet(32, IC));
1527 
1528   if (PV.IterCount != 32)
1529     P = B.CreateAnd(P, BMI);
1530 
1531   if (PV.Inv) {
1532     auto *QI = dyn_cast<ConstantInt>(PV.Q);
1533     assert(QI && QI->getBitWidth() <= 32);
1534 
1535     // Again, clearing bits beyond IterCount.
1536     unsigned M = (1 << PV.IterCount) - 1;
1537     unsigned Tmp = (QI->getZExtValue() | 1) & M;
1538     unsigned QV = getInverseMxN(Tmp) & M;
1539     auto *QVI = ConstantInt::get(QI->getType(), QV);
1540     P = B.CreateCall(PMF, {P, QVI});
1541     P = B.CreateTrunc(P, QI->getType());
1542     if (IC != 32)
1543       P = B.CreateAnd(P, BMI);
1544   }
1545 
1546   Value *R = B.CreateCall(PMF, {P, Q});
1547 
1548   if (PV.M != nullptr)
1549     R = B.CreateXor(R, B.CreateIntCast(P0, R->getType(), false));
1550 
1551   return R;
1552 }
1553 
1554 static bool hasZeroSignBit(const Value *V) {
1555   if (const auto *CI = dyn_cast<const ConstantInt>(V))
1556     return (CI->getType()->getSignBit() & CI->getSExtValue()) == 0;
1557   const Instruction *I = dyn_cast<const Instruction>(V);
1558   if (!I)
1559     return false;
1560   switch (I->getOpcode()) {
1561     case Instruction::LShr:
1562       if (const auto SI = dyn_cast<const ConstantInt>(I->getOperand(1)))
1563         return SI->getZExtValue() > 0;
1564       return false;
1565     case Instruction::Or:
1566     case Instruction::Xor:
1567       return hasZeroSignBit(I->getOperand(0)) &&
1568              hasZeroSignBit(I->getOperand(1));
1569     case Instruction::And:
1570       return hasZeroSignBit(I->getOperand(0)) ||
1571              hasZeroSignBit(I->getOperand(1));
1572   }
1573   return false;
1574 }
1575 
1576 void PolynomialMultiplyRecognize::setupSimplifier() {
1577   Simp.addRule("sink-zext",
1578     // Sink zext past bitwise operations.
1579     [](Instruction *I, LLVMContext &Ctx) -> Value* {
1580       if (I->getOpcode() != Instruction::ZExt)
1581         return nullptr;
1582       Instruction *T = dyn_cast<Instruction>(I->getOperand(0));
1583       if (!T)
1584         return nullptr;
1585       switch (T->getOpcode()) {
1586         case Instruction::And:
1587         case Instruction::Or:
1588         case Instruction::Xor:
1589           break;
1590         default:
1591           return nullptr;
1592       }
1593       IRBuilder<> B(Ctx);
1594       return B.CreateBinOp(cast<BinaryOperator>(T)->getOpcode(),
1595                            B.CreateZExt(T->getOperand(0), I->getType()),
1596                            B.CreateZExt(T->getOperand(1), I->getType()));
1597     });
1598   Simp.addRule("xor/and -> and/xor",
1599     // (xor (and x a) (and y a)) -> (and (xor x y) a)
1600     [](Instruction *I, LLVMContext &Ctx) -> Value* {
1601       if (I->getOpcode() != Instruction::Xor)
1602         return nullptr;
1603       Instruction *And0 = dyn_cast<Instruction>(I->getOperand(0));
1604       Instruction *And1 = dyn_cast<Instruction>(I->getOperand(1));
1605       if (!And0 || !And1)
1606         return nullptr;
1607       if (And0->getOpcode() != Instruction::And ||
1608           And1->getOpcode() != Instruction::And)
1609         return nullptr;
1610       if (And0->getOperand(1) != And1->getOperand(1))
1611         return nullptr;
1612       IRBuilder<> B(Ctx);
1613       return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1->getOperand(0)),
1614                          And0->getOperand(1));
1615     });
1616   Simp.addRule("sink binop into select",
1617     // (Op (select c x y) z) -> (select c (Op x z) (Op y z))
1618     // (Op x (select c y z)) -> (select c (Op x y) (Op x z))
1619     [](Instruction *I, LLVMContext &Ctx) -> Value* {
1620       BinaryOperator *BO = dyn_cast<BinaryOperator>(I);
1621       if (!BO)
1622         return nullptr;
1623       Instruction::BinaryOps Op = BO->getOpcode();
1624       if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(0))) {
1625         IRBuilder<> B(Ctx);
1626         Value *X = Sel->getTrueValue(), *Y = Sel->getFalseValue();
1627         Value *Z = BO->getOperand(1);
1628         return B.CreateSelect(Sel->getCondition(),
1629                               B.CreateBinOp(Op, X, Z),
1630                               B.CreateBinOp(Op, Y, Z));
1631       }
1632       if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(1))) {
1633         IRBuilder<> B(Ctx);
1634         Value *X = BO->getOperand(0);
1635         Value *Y = Sel->getTrueValue(), *Z = Sel->getFalseValue();
1636         return B.CreateSelect(Sel->getCondition(),
1637                               B.CreateBinOp(Op, X, Y),
1638                               B.CreateBinOp(Op, X, Z));
1639       }
1640       return nullptr;
1641     });
1642   Simp.addRule("fold select-select",
1643     // (select c (select c x y) z) -> (select c x z)
1644     // (select c x (select c y z)) -> (select c x z)
1645     [](Instruction *I, LLVMContext &Ctx) -> Value* {
1646       SelectInst *Sel = dyn_cast<SelectInst>(I);
1647       if (!Sel)
1648         return nullptr;
1649       IRBuilder<> B(Ctx);
1650       Value *C = Sel->getCondition();
1651       if (SelectInst *Sel0 = dyn_cast<SelectInst>(Sel->getTrueValue())) {
1652         if (Sel0->getCondition() == C)
1653           return B.CreateSelect(C, Sel0->getTrueValue(), Sel->getFalseValue());
1654       }
1655       if (SelectInst *Sel1 = dyn_cast<SelectInst>(Sel->getFalseValue())) {
1656         if (Sel1->getCondition() == C)
1657           return B.CreateSelect(C, Sel->getTrueValue(), Sel1->getFalseValue());
1658       }
1659       return nullptr;
1660     });
1661   Simp.addRule("or-signbit -> xor-signbit",
1662     // (or (lshr x 1) 0x800.0) -> (xor (lshr x 1) 0x800.0)
1663     [](Instruction *I, LLVMContext &Ctx) -> Value* {
1664       if (I->getOpcode() != Instruction::Or)
1665         return nullptr;
1666       ConstantInt *Msb = dyn_cast<ConstantInt>(I->getOperand(1));
1667       if (!Msb || Msb->getZExtValue() != Msb->getType()->getSignBit())
1668         return nullptr;
1669       if (!hasZeroSignBit(I->getOperand(0)))
1670         return nullptr;
1671       return IRBuilder<>(Ctx).CreateXor(I->getOperand(0), Msb);
1672     });
1673   Simp.addRule("sink lshr into binop",
1674     // (lshr (BitOp x y) c) -> (BitOp (lshr x c) (lshr y c))
1675     [](Instruction *I, LLVMContext &Ctx) -> Value* {
1676       if (I->getOpcode() != Instruction::LShr)
1677         return nullptr;
1678       BinaryOperator *BitOp = dyn_cast<BinaryOperator>(I->getOperand(0));
1679       if (!BitOp)
1680         return nullptr;
1681       switch (BitOp->getOpcode()) {
1682         case Instruction::And:
1683         case Instruction::Or:
1684         case Instruction::Xor:
1685           break;
1686         default:
1687           return nullptr;
1688       }
1689       IRBuilder<> B(Ctx);
1690       Value *S = I->getOperand(1);
1691       return B.CreateBinOp(BitOp->getOpcode(),
1692                 B.CreateLShr(BitOp->getOperand(0), S),
1693                 B.CreateLShr(BitOp->getOperand(1), S));
1694     });
1695   Simp.addRule("expose bitop-const",
1696     // (BitOp1 (BitOp2 x a) b) -> (BitOp2 x (BitOp1 a b))
1697     [](Instruction *I, LLVMContext &Ctx) -> Value* {
1698       auto IsBitOp = [](unsigned Op) -> bool {
1699         switch (Op) {
1700           case Instruction::And:
1701           case Instruction::Or:
1702           case Instruction::Xor:
1703             return true;
1704         }
1705         return false;
1706       };
1707       BinaryOperator *BitOp1 = dyn_cast<BinaryOperator>(I);
1708       if (!BitOp1 || !IsBitOp(BitOp1->getOpcode()))
1709         return nullptr;
1710       BinaryOperator *BitOp2 = dyn_cast<BinaryOperator>(BitOp1->getOperand(0));
1711       if (!BitOp2 || !IsBitOp(BitOp2->getOpcode()))
1712         return nullptr;
1713       ConstantInt *CA = dyn_cast<ConstantInt>(BitOp2->getOperand(1));
1714       ConstantInt *CB = dyn_cast<ConstantInt>(BitOp1->getOperand(1));
1715       if (!CA || !CB)
1716         return nullptr;
1717       IRBuilder<> B(Ctx);
1718       Value *X = BitOp2->getOperand(0);
1719       return B.CreateBinOp(BitOp2->getOpcode(), X,
1720                 B.CreateBinOp(BitOp1->getOpcode(), CA, CB));
1721     });
1722 }
1723 
1724 bool PolynomialMultiplyRecognize::recognize() {
1725   DEBUG(dbgs() << "Starting PolynomialMultiplyRecognize on loop\n"
1726                << *CurLoop << '\n');
1727   // Restrictions:
1728   // - The loop must consist of a single block.
1729   // - The iteration count must be known at compile-time.
1730   // - The loop must have an induction variable starting from 0, and
1731   //   incremented in each iteration of the loop.
1732   BasicBlock *LoopB = CurLoop->getHeader();
1733   DEBUG(dbgs() << "Loop header:\n" << *LoopB);
1734 
1735   if (LoopB != CurLoop->getLoopLatch())
1736     return false;
1737   BasicBlock *ExitB = CurLoop->getExitBlock();
1738   if (ExitB == nullptr)
1739     return false;
1740   BasicBlock *EntryB = CurLoop->getLoopPreheader();
1741   if (EntryB == nullptr)
1742     return false;
1743 
1744   unsigned IterCount = 0;
1745   const SCEV *CT = SE.getBackedgeTakenCount(CurLoop);
1746   if (isa<SCEVCouldNotCompute>(CT))
1747     return false;
1748   if (auto *CV = dyn_cast<SCEVConstant>(CT))
1749     IterCount = CV->getValue()->getZExtValue() + 1;
1750 
1751   Value *CIV = getCountIV(LoopB);
1752   ParsedValues PV;
1753   PV.IterCount = IterCount;
1754   DEBUG(dbgs() << "Loop IV: " << *CIV << "\nIterCount: " << IterCount << '\n');
1755 
1756   setupSimplifier();
1757 
1758   // Perform a preliminary scan of select instructions to see if any of them
1759   // looks like a generator of the polynomial multiply steps. Assume that a
1760   // loop can only contain a single transformable operation, so stop the
1761   // traversal after the first reasonable candidate was found.
1762   // XXX: Currently this approach can modify the loop before being 100% sure
1763   // that the transformation can be carried out.
1764   bool FoundPreScan = false;
1765   auto FeedsPHI = [LoopB](const Value *V) -> bool {
1766     for (const Value *U : V->users()) {
1767       if (const auto *P = dyn_cast<const PHINode>(U))
1768         if (P->getParent() == LoopB)
1769           return true;
1770     }
1771     return false;
1772   };
1773   for (Instruction &In : *LoopB) {
1774     SelectInst *SI = dyn_cast<SelectInst>(&In);
1775     if (!SI || !FeedsPHI(SI))
1776       continue;
1777 
1778     Simplifier::Context C(SI);
1779     Value *T = Simp.simplify(C);
1780     SelectInst *SelI = (T && isa<SelectInst>(T)) ? cast<SelectInst>(T) : SI;
1781     DEBUG(dbgs() << "scanSelect(pre-scan): " << PE(C, SelI) << '\n');
1782     if (scanSelect(SelI, LoopB, EntryB, CIV, PV, true)) {
1783       FoundPreScan = true;
1784       if (SelI != SI) {
1785         Value *NewSel = C.materialize(LoopB, SI->getIterator());
1786         SI->replaceAllUsesWith(NewSel);
1787         RecursivelyDeleteTriviallyDeadInstructions(SI, &TLI);
1788       }
1789       break;
1790     }
1791   }
1792 
1793   if (!FoundPreScan) {
1794     DEBUG(dbgs() << "Have not found candidates for pmpy\n");
1795     return false;
1796   }
1797 
1798   if (!PV.Left) {
1799     // The right shift version actually only returns the higher bits of
1800     // the result (each iteration discards the LSB). If we want to convert it
1801     // to a left-shifting loop, the working data type must be at least as
1802     // wide as the target's pmpy instruction.
1803     if (!promoteTypes(LoopB, ExitB))
1804       return false;
1805     if (!convertShiftsToLeft(LoopB, ExitB, IterCount))
1806       return false;
1807     cleanupLoopBody(LoopB);
1808   }
1809 
1810   // Scan the loop again, find the generating select instruction.
1811   bool FoundScan = false;
1812   for (Instruction &In : *LoopB) {
1813     SelectInst *SelI = dyn_cast<SelectInst>(&In);
1814     if (!SelI)
1815       continue;
1816     DEBUG(dbgs() << "scanSelect: " << *SelI << '\n');
1817     FoundScan = scanSelect(SelI, LoopB, EntryB, CIV, PV, false);
1818     if (FoundScan)
1819       break;
1820   }
1821   assert(FoundScan);
1822 
1823   DEBUG({
1824     StringRef PP = (PV.M ? "(P+M)" : "P");
1825     if (!PV.Inv)
1826       dbgs() << "Found pmpy idiom: R = " << PP << ".Q\n";
1827     else
1828       dbgs() << "Found inverse pmpy idiom: R = (" << PP << "/Q).Q) + "
1829              << PP << "\n";
1830     dbgs() << "  Res:" << *PV.Res << "\n  P:" << *PV.P << "\n";
1831     if (PV.M)
1832       dbgs() << "  M:" << *PV.M << "\n";
1833     dbgs() << "  Q:" << *PV.Q << "\n";
1834     dbgs() << "  Iteration count:" << PV.IterCount << "\n";
1835   });
1836 
1837   BasicBlock::iterator At(EntryB->getTerminator());
1838   Value *PM = generate(At, PV);
1839   if (PM == nullptr)
1840     return false;
1841 
1842   if (PM->getType() != PV.Res->getType())
1843     PM = IRBuilder<>(&*At).CreateIntCast(PM, PV.Res->getType(), false);
1844 
1845   PV.Res->replaceAllUsesWith(PM);
1846   PV.Res->eraseFromParent();
1847   return true;
1848 }
1849 
1850 unsigned HexagonLoopIdiomRecognize::getStoreSizeInBytes(StoreInst *SI) {
1851   uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
1852   assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
1853          "Don't overflow unsigned.");
1854   return (unsigned)SizeInBits >> 3;
1855 }
1856 
1857 int HexagonLoopIdiomRecognize::getSCEVStride(const SCEVAddRecExpr *S) {
1858   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1859     return SC->getAPInt().getSExtValue();
1860   return 0;
1861 }
1862 
1863 bool HexagonLoopIdiomRecognize::isLegalStore(Loop *CurLoop, StoreInst *SI) {
1864   // Allow volatile stores if HexagonVolatileMemcpy is enabled.
1865   if (!(SI->isVolatile() && HexagonVolatileMemcpy) && !SI->isSimple())
1866     return false;
1867 
1868   Value *StoredVal = SI->getValueOperand();
1869   Value *StorePtr = SI->getPointerOperand();
1870 
1871   // Reject stores that are so large that they overflow an unsigned.
1872   uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
1873   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
1874     return false;
1875 
1876   // See if the pointer expression is an AddRec like {base,+,1} on the current
1877   // loop, which indicates a strided store.  If we have something else, it's a
1878   // random store we can't handle.
1879   auto *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1880   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
1881     return false;
1882 
1883   // Check to see if the stride matches the size of the store.  If so, then we
1884   // know that every byte is touched in the loop.
1885   int Stride = getSCEVStride(StoreEv);
1886   if (Stride == 0)
1887     return false;
1888   unsigned StoreSize = getStoreSizeInBytes(SI);
1889   if (StoreSize != unsigned(std::abs(Stride)))
1890     return false;
1891 
1892   // The store must be feeding a non-volatile load.
1893   LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
1894   if (!LI || !LI->isSimple())
1895     return false;
1896 
1897   // See if the pointer expression is an AddRec like {base,+,1} on the current
1898   // loop, which indicates a strided load.  If we have something else, it's a
1899   // random load we can't handle.
1900   Value *LoadPtr = LI->getPointerOperand();
1901   auto *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1902   if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
1903     return false;
1904 
1905   // The store and load must share the same stride.
1906   if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
1907     return false;
1908 
1909   // Success.  This store can be converted into a memcpy.
1910   return true;
1911 }
1912 
1913 /// mayLoopAccessLocation - Return true if the specified loop might access the
1914 /// specified pointer location, which is a loop-strided access.  The 'Access'
1915 /// argument specifies what the verboten forms of access are (read or write).
1916 static bool
1917 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
1918                       const SCEV *BECount, unsigned StoreSize,
1919                       AliasAnalysis &AA,
1920                       SmallPtrSetImpl<Instruction *> &Ignored) {
1921   // Get the location that may be stored across the loop.  Since the access
1922   // is strided positively through memory, we say that the modified location
1923   // starts at the pointer and has infinite size.
1924   uint64_t AccessSize = MemoryLocation::UnknownSize;
1925 
1926   // If the loop iterates a fixed number of times, we can refine the access
1927   // size to be exactly the size of the memset, which is (BECount+1)*StoreSize
1928   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
1929     AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
1930 
1931   // TODO: For this to be really effective, we have to dive into the pointer
1932   // operand in the store.  Store to &A[i] of 100 will always return may alias
1933   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
1934   // which will then no-alias a store to &A[100].
1935   MemoryLocation StoreLoc(Ptr, AccessSize);
1936 
1937   for (auto *B : L->blocks())
1938     for (auto &I : *B)
1939       if (Ignored.count(&I) == 0 && (AA.getModRefInfo(&I, StoreLoc) & Access))
1940         return true;
1941 
1942   return false;
1943 }
1944 
1945 void HexagonLoopIdiomRecognize::collectStores(Loop *CurLoop, BasicBlock *BB,
1946       SmallVectorImpl<StoreInst*> &Stores) {
1947   Stores.clear();
1948   for (Instruction &I : *BB)
1949     if (StoreInst *SI = dyn_cast<StoreInst>(&I))
1950       if (isLegalStore(CurLoop, SI))
1951         Stores.push_back(SI);
1952 }
1953 
1954 bool HexagonLoopIdiomRecognize::processCopyingStore(Loop *CurLoop,
1955       StoreInst *SI, const SCEV *BECount) {
1956   assert((SI->isSimple() || (SI->isVolatile() && HexagonVolatileMemcpy)) &&
1957          "Expected only non-volatile stores, or Hexagon-specific memcpy"
1958          "to volatile destination.");
1959 
1960   Value *StorePtr = SI->getPointerOperand();
1961   auto *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1962   unsigned Stride = getSCEVStride(StoreEv);
1963   unsigned StoreSize = getStoreSizeInBytes(SI);
1964   if (Stride != StoreSize)
1965     return false;
1966 
1967   // See if the pointer expression is an AddRec like {base,+,1} on the current
1968   // loop, which indicates a strided load.  If we have something else, it's a
1969   // random load we can't handle.
1970   LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
1971   auto *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
1972 
1973   // The trip count of the loop and the base pointer of the addrec SCEV is
1974   // guaranteed to be loop invariant, which means that it should dominate the
1975   // header.  This allows us to insert code for it in the preheader.
1976   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1977   Instruction *ExpPt = Preheader->getTerminator();
1978   IRBuilder<> Builder(ExpPt);
1979   SCEVExpander Expander(*SE, *DL, "hexagon-loop-idiom");
1980 
1981   Type *IntPtrTy = Builder.getIntPtrTy(*DL, SI->getPointerAddressSpace());
1982 
1983   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
1984   // this into a memcpy/memmove in the loop preheader now if we want.  However,
1985   // this would be unsafe to do if there is anything else in the loop that may
1986   // read or write the memory region we're storing to.  For memcpy, this
1987   // includes the load that feeds the stores.  Check for an alias by generating
1988   // the base address and checking everything.
1989   Value *StoreBasePtr = Expander.expandCodeFor(StoreEv->getStart(),
1990       Builder.getInt8PtrTy(SI->getPointerAddressSpace()), ExpPt);
1991   Value *LoadBasePtr = nullptr;
1992 
1993   bool Overlap = false;
1994   bool DestVolatile = SI->isVolatile();
1995   Type *BECountTy = BECount->getType();
1996 
1997   if (DestVolatile) {
1998     // The trip count must fit in i32, since it is the type of the "num_words"
1999     // argument to hexagon_memcpy_forward_vp4cp4n2.
2000     if (StoreSize != 4 || DL->getTypeSizeInBits(BECountTy) > 32) {
2001 CleanupAndExit:
2002       // If we generated new code for the base pointer, clean up.
2003       Expander.clear();
2004       if (StoreBasePtr && (LoadBasePtr != StoreBasePtr)) {
2005         RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
2006         StoreBasePtr = nullptr;
2007       }
2008       if (LoadBasePtr) {
2009         RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
2010         LoadBasePtr = nullptr;
2011       }
2012       return false;
2013     }
2014   }
2015 
2016   SmallPtrSet<Instruction*, 2> Ignore1;
2017   Ignore1.insert(SI);
2018   if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
2019                             StoreSize, *AA, Ignore1)) {
2020     // Check if the load is the offending instruction.
2021     Ignore1.insert(LI);
2022     if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
2023                               StoreSize, *AA, Ignore1)) {
2024       // Still bad. Nothing we can do.
2025       goto CleanupAndExit;
2026     }
2027     // It worked with the load ignored.
2028     Overlap = true;
2029   }
2030 
2031   if (!Overlap) {
2032     if (DisableMemcpyIdiom || !HasMemcpy)
2033       goto CleanupAndExit;
2034   } else {
2035     // Don't generate memmove if this function will be inlined. This is
2036     // because the caller will undergo this transformation after inlining.
2037     Function *Func = CurLoop->getHeader()->getParent();
2038     if (Func->hasFnAttribute(Attribute::AlwaysInline))
2039       goto CleanupAndExit;
2040 
2041     // In case of a memmove, the call to memmove will be executed instead
2042     // of the loop, so we need to make sure that there is nothing else in
2043     // the loop than the load, store and instructions that these two depend
2044     // on.
2045     SmallVector<Instruction*,2> Insts;
2046     Insts.push_back(SI);
2047     Insts.push_back(LI);
2048     if (!coverLoop(CurLoop, Insts))
2049       goto CleanupAndExit;
2050 
2051     if (DisableMemmoveIdiom || !HasMemmove)
2052       goto CleanupAndExit;
2053     bool IsNested = CurLoop->getParentLoop() != nullptr;
2054     if (IsNested && OnlyNonNestedMemmove)
2055       goto CleanupAndExit;
2056   }
2057 
2058   // For a memcpy, we have to make sure that the input array is not being
2059   // mutated by the loop.
2060   LoadBasePtr = Expander.expandCodeFor(LoadEv->getStart(),
2061       Builder.getInt8PtrTy(LI->getPointerAddressSpace()), ExpPt);
2062 
2063   SmallPtrSet<Instruction*, 2> Ignore2;
2064   Ignore2.insert(SI);
2065   if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
2066                             *AA, Ignore2))
2067     goto CleanupAndExit;
2068 
2069   // Check the stride.
2070   bool StridePos = getSCEVStride(LoadEv) >= 0;
2071 
2072   // Currently, the volatile memcpy only emulates traversing memory forward.
2073   if (!StridePos && DestVolatile)
2074     goto CleanupAndExit;
2075 
2076   bool RuntimeCheck = (Overlap || DestVolatile);
2077 
2078   BasicBlock *ExitB;
2079   if (RuntimeCheck) {
2080     // The runtime check needs a single exit block.
2081     SmallVector<BasicBlock*, 8> ExitBlocks;
2082     CurLoop->getUniqueExitBlocks(ExitBlocks);
2083     if (ExitBlocks.size() != 1)
2084       goto CleanupAndExit;
2085     ExitB = ExitBlocks[0];
2086   }
2087 
2088   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
2089   // pointer size if it isn't already.
2090   LLVMContext &Ctx = SI->getContext();
2091   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
2092   unsigned Alignment = std::min(SI->getAlignment(), LI->getAlignment());
2093   DebugLoc DLoc = SI->getDebugLoc();
2094 
2095   const SCEV *NumBytesS =
2096       SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
2097   if (StoreSize != 1)
2098     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
2099                                SCEV::FlagNUW);
2100   Value *NumBytes = Expander.expandCodeFor(NumBytesS, IntPtrTy, ExpPt);
2101   if (Instruction *In = dyn_cast<Instruction>(NumBytes))
2102     if (Value *Simp = SimplifyInstruction(In, {*DL, TLI, DT}))
2103       NumBytes = Simp;
2104 
2105   CallInst *NewCall;
2106 
2107   if (RuntimeCheck) {
2108     unsigned Threshold = RuntimeMemSizeThreshold;
2109     if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) {
2110       uint64_t C = CI->getZExtValue();
2111       if (Threshold != 0 && C < Threshold)
2112         goto CleanupAndExit;
2113       if (C < CompileTimeMemSizeThreshold)
2114         goto CleanupAndExit;
2115     }
2116 
2117     BasicBlock *Header = CurLoop->getHeader();
2118     Function *Func = Header->getParent();
2119     Loop *ParentL = LF->getLoopFor(Preheader);
2120     StringRef HeaderName = Header->getName();
2121 
2122     // Create a new (empty) preheader, and update the PHI nodes in the
2123     // header to use the new preheader.
2124     BasicBlock *NewPreheader = BasicBlock::Create(Ctx, HeaderName+".rtli.ph",
2125                                                   Func, Header);
2126     if (ParentL)
2127       ParentL->addBasicBlockToLoop(NewPreheader, *LF);
2128     IRBuilder<>(NewPreheader).CreateBr(Header);
2129     for (auto &In : *Header) {
2130       PHINode *PN = dyn_cast<PHINode>(&In);
2131       if (!PN)
2132         break;
2133       int bx = PN->getBasicBlockIndex(Preheader);
2134       if (bx >= 0)
2135         PN->setIncomingBlock(bx, NewPreheader);
2136     }
2137     DT->addNewBlock(NewPreheader, Preheader);
2138     DT->changeImmediateDominator(Header, NewPreheader);
2139 
2140     // Check for safe conditions to execute memmove.
2141     // If stride is positive, copying things from higher to lower addresses
2142     // is equivalent to memmove.  For negative stride, it's the other way
2143     // around.  Copying forward in memory with positive stride may not be
2144     // same as memmove since we may be copying values that we just stored
2145     // in some previous iteration.
2146     Value *LA = Builder.CreatePtrToInt(LoadBasePtr, IntPtrTy);
2147     Value *SA = Builder.CreatePtrToInt(StoreBasePtr, IntPtrTy);
2148     Value *LowA = StridePos ? SA : LA;
2149     Value *HighA = StridePos ? LA : SA;
2150     Value *CmpA = Builder.CreateICmpULT(LowA, HighA);
2151     Value *Cond = CmpA;
2152 
2153     // Check for distance between pointers. Since the case LowA < HighA
2154     // is checked for above, assume LowA >= HighA.
2155     Value *Dist = Builder.CreateSub(LowA, HighA);
2156     Value *CmpD = Builder.CreateICmpSLE(NumBytes, Dist);
2157     Value *CmpEither = Builder.CreateOr(Cond, CmpD);
2158     Cond = CmpEither;
2159 
2160     if (Threshold != 0) {
2161       Type *Ty = NumBytes->getType();
2162       Value *Thr = ConstantInt::get(Ty, Threshold);
2163       Value *CmpB = Builder.CreateICmpULT(Thr, NumBytes);
2164       Value *CmpBoth = Builder.CreateAnd(Cond, CmpB);
2165       Cond = CmpBoth;
2166     }
2167     BasicBlock *MemmoveB = BasicBlock::Create(Ctx, Header->getName()+".rtli",
2168                                               Func, NewPreheader);
2169     if (ParentL)
2170       ParentL->addBasicBlockToLoop(MemmoveB, *LF);
2171     Instruction *OldT = Preheader->getTerminator();
2172     Builder.CreateCondBr(Cond, MemmoveB, NewPreheader);
2173     OldT->eraseFromParent();
2174     Preheader->setName(Preheader->getName()+".old");
2175     DT->addNewBlock(MemmoveB, Preheader);
2176     // Find the new immediate dominator of the exit block.
2177     BasicBlock *ExitD = Preheader;
2178     for (auto PI = pred_begin(ExitB), PE = pred_end(ExitB); PI != PE; ++PI) {
2179       BasicBlock *PB = *PI;
2180       ExitD = DT->findNearestCommonDominator(ExitD, PB);
2181       if (!ExitD)
2182         break;
2183     }
2184     // If the prior immediate dominator of ExitB was dominated by the
2185     // old preheader, then the old preheader becomes the new immediate
2186     // dominator.  Otherwise don't change anything (because the newly
2187     // added blocks are dominated by the old preheader).
2188     if (ExitD && DT->dominates(Preheader, ExitD)) {
2189       DomTreeNode *BN = DT->getNode(ExitB);
2190       DomTreeNode *DN = DT->getNode(ExitD);
2191       BN->setIDom(DN);
2192     }
2193 
2194     // Add a call to memmove to the conditional block.
2195     IRBuilder<> CondBuilder(MemmoveB);
2196     CondBuilder.CreateBr(ExitB);
2197     CondBuilder.SetInsertPoint(MemmoveB->getTerminator());
2198 
2199     if (DestVolatile) {
2200       Type *Int32Ty = Type::getInt32Ty(Ctx);
2201       Type *Int32PtrTy = Type::getInt32PtrTy(Ctx);
2202       Type *VoidTy = Type::getVoidTy(Ctx);
2203       Module *M = Func->getParent();
2204       Constant *CF = M->getOrInsertFunction(HexagonVolatileMemcpyName, VoidTy,
2205                                             Int32PtrTy, Int32PtrTy, Int32Ty);
2206       Function *Fn = cast<Function>(CF);
2207       Fn->setLinkage(Function::ExternalLinkage);
2208 
2209       const SCEV *OneS = SE->getConstant(Int32Ty, 1);
2210       const SCEV *BECount32 = SE->getTruncateOrZeroExtend(BECount, Int32Ty);
2211       const SCEV *NumWordsS = SE->getAddExpr(BECount32, OneS, SCEV::FlagNUW);
2212       Value *NumWords = Expander.expandCodeFor(NumWordsS, Int32Ty,
2213                                                MemmoveB->getTerminator());
2214       if (Instruction *In = dyn_cast<Instruction>(NumWords))
2215         if (Value *Simp = SimplifyInstruction(In, {*DL, TLI, DT}))
2216           NumWords = Simp;
2217 
2218       Value *Op0 = (StoreBasePtr->getType() == Int32PtrTy)
2219                       ? StoreBasePtr
2220                       : CondBuilder.CreateBitCast(StoreBasePtr, Int32PtrTy);
2221       Value *Op1 = (LoadBasePtr->getType() == Int32PtrTy)
2222                       ? LoadBasePtr
2223                       : CondBuilder.CreateBitCast(LoadBasePtr, Int32PtrTy);
2224       NewCall = CondBuilder.CreateCall(Fn, {Op0, Op1, NumWords});
2225     } else {
2226       NewCall = CondBuilder.CreateMemMove(StoreBasePtr, LoadBasePtr,
2227                                           NumBytes, Alignment);
2228     }
2229   } else {
2230     NewCall = Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr,
2231                                    NumBytes, Alignment);
2232     // Okay, the memcpy has been formed.  Zap the original store and
2233     // anything that feeds into it.
2234     RecursivelyDeleteTriviallyDeadInstructions(SI, TLI);
2235   }
2236 
2237   NewCall->setDebugLoc(DLoc);
2238 
2239   DEBUG(dbgs() << "  Formed " << (Overlap ? "memmove: " : "memcpy: ")
2240                << *NewCall << "\n"
2241                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
2242                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
2243 
2244   return true;
2245 }
2246 
2247 // \brief Check if the instructions in Insts, together with their dependencies
2248 // cover the loop in the sense that the loop could be safely eliminated once
2249 // the instructions in Insts are removed.
2250 bool HexagonLoopIdiomRecognize::coverLoop(Loop *L,
2251       SmallVectorImpl<Instruction*> &Insts) const {
2252   SmallSet<BasicBlock*,8> LoopBlocks;
2253   for (auto *B : L->blocks())
2254     LoopBlocks.insert(B);
2255 
2256   SetVector<Instruction*> Worklist(Insts.begin(), Insts.end());
2257 
2258   // Collect all instructions from the loop that the instructions in Insts
2259   // depend on (plus their dependencies, etc.).  These instructions will
2260   // constitute the expression trees that feed those in Insts, but the trees
2261   // will be limited only to instructions contained in the loop.
2262   for (unsigned i = 0; i < Worklist.size(); ++i) {
2263     Instruction *In = Worklist[i];
2264     for (auto I = In->op_begin(), E = In->op_end(); I != E; ++I) {
2265       Instruction *OpI = dyn_cast<Instruction>(I);
2266       if (!OpI)
2267         continue;
2268       BasicBlock *PB = OpI->getParent();
2269       if (!LoopBlocks.count(PB))
2270         continue;
2271       Worklist.insert(OpI);
2272     }
2273   }
2274 
2275   // Scan all instructions in the loop, if any of them have a user outside
2276   // of the loop, or outside of the expressions collected above, then either
2277   // the loop has a side-effect visible outside of it, or there are
2278   // instructions in it that are not involved in the original set Insts.
2279   for (auto *B : L->blocks()) {
2280     for (auto &In : *B) {
2281       if (isa<BranchInst>(In) || isa<DbgInfoIntrinsic>(In))
2282         continue;
2283       if (!Worklist.count(&In) && In.mayHaveSideEffects())
2284         return false;
2285       for (const auto &K : In.users()) {
2286         Instruction *UseI = dyn_cast<Instruction>(K);
2287         if (!UseI)
2288           continue;
2289         BasicBlock *UseB = UseI->getParent();
2290         if (LF->getLoopFor(UseB) != L)
2291           return false;
2292       }
2293     }
2294   }
2295 
2296   return true;
2297 }
2298 
2299 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
2300 /// with the specified backedge count.  This block is known to be in the current
2301 /// loop and not in any subloops.
2302 bool HexagonLoopIdiomRecognize::runOnLoopBlock(Loop *CurLoop, BasicBlock *BB,
2303       const SCEV *BECount, SmallVectorImpl<BasicBlock*> &ExitBlocks) {
2304   // We can only promote stores in this block if they are unconditionally
2305   // executed in the loop.  For a block to be unconditionally executed, it has
2306   // to dominate all the exit blocks of the loop.  Verify this now.
2307   auto DominatedByBB = [this,BB] (BasicBlock *EB) -> bool {
2308     return DT->dominates(BB, EB);
2309   };
2310   if (!std::all_of(ExitBlocks.begin(), ExitBlocks.end(), DominatedByBB))
2311     return false;
2312 
2313   bool MadeChange = false;
2314   // Look for store instructions, which may be optimized to memset/memcpy.
2315   SmallVector<StoreInst*,8> Stores;
2316   collectStores(CurLoop, BB, Stores);
2317 
2318   // Optimize the store into a memcpy, if it feeds an similarly strided load.
2319   for (auto &SI : Stores)
2320     MadeChange |= processCopyingStore(CurLoop, SI, BECount);
2321 
2322   return MadeChange;
2323 }
2324 
2325 bool HexagonLoopIdiomRecognize::runOnCountableLoop(Loop *L) {
2326   PolynomialMultiplyRecognize PMR(L, *DL, *DT, *TLI, *SE);
2327   if (PMR.recognize())
2328     return true;
2329 
2330   if (!HasMemcpy && !HasMemmove)
2331     return false;
2332 
2333   const SCEV *BECount = SE->getBackedgeTakenCount(L);
2334   assert(!isa<SCEVCouldNotCompute>(BECount) &&
2335          "runOnCountableLoop() called on a loop without a predictable"
2336          "backedge-taken count");
2337 
2338   SmallVector<BasicBlock *, 8> ExitBlocks;
2339   L->getUniqueExitBlocks(ExitBlocks);
2340 
2341   bool Changed = false;
2342 
2343   // Scan all the blocks in the loop that are not in subloops.
2344   for (auto *BB : L->getBlocks()) {
2345     // Ignore blocks in subloops.
2346     if (LF->getLoopFor(BB) != L)
2347       continue;
2348     Changed |= runOnLoopBlock(L, BB, BECount, ExitBlocks);
2349   }
2350 
2351   return Changed;
2352 }
2353 
2354 bool HexagonLoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
2355   const Module &M = *L->getHeader()->getParent()->getParent();
2356   if (Triple(M.getTargetTriple()).getArch() != Triple::hexagon)
2357     return false;
2358 
2359   if (skipLoop(L))
2360     return false;
2361 
2362   // If the loop could not be converted to canonical form, it must have an
2363   // indirectbr in it, just give up.
2364   if (!L->getLoopPreheader())
2365     return false;
2366 
2367   // Disable loop idiom recognition if the function's name is a common idiom.
2368   StringRef Name = L->getHeader()->getParent()->getName();
2369   if (Name == "memset" || Name == "memcpy" || Name == "memmove")
2370     return false;
2371 
2372   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2373   DL = &L->getHeader()->getModule()->getDataLayout();
2374   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2375   LF = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2376   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2377   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2378 
2379   HasMemcpy = TLI->has(LibFunc_memcpy);
2380   HasMemmove = TLI->has(LibFunc_memmove);
2381 
2382   if (SE->hasLoopInvariantBackedgeTakenCount(L))
2383     return runOnCountableLoop(L);
2384   return false;
2385 }
2386 
2387 Pass *llvm::createHexagonLoopIdiomPass() {
2388   return new HexagonLoopIdiomRecognize();
2389 }
2390