33633ae073f959bcdec203cff4492c15d291f26a
[oota-llvm.git] / lib / Transforms / Scalar / LoopIdiomRecognize.cpp
1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
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 // This pass implements an idiom recognizer that transforms simple loops into a
11 // non-loop form.  In cases that this kicks in, it can be a significant
12 // performance win.
13 //
14 //===----------------------------------------------------------------------===//
15 //
16 // TODO List:
17 //
18 // Future loop memory idioms to recognize:
19 //   memcmp, memmove, strlen, etc.
20 // Future floating point idioms to recognize in -ffast-math mode:
21 //   fpowi
22 // Future integer operation idioms to recognize:
23 //   ctpop, ctlz, cttz
24 //
25 // Beware that isel's default lowering for ctpop is highly inefficient for
26 // i64 and larger types when i64 is legal and the value has few bits set.  It
27 // would be good to enhance isel to emit a loop for ctpop in this case.
28 //
29 // We should enhance the memset/memcpy recognition to handle multiple stores in
30 // the loop.  This would handle things like:
31 //   void foo(_Complex float *P)
32 //     for (i) { __real__(*P) = 0;  __imag__(*P) = 0; }
33 //
34 // We should enhance this to handle negative strides through memory.
35 // Alternatively (and perhaps better) we could rely on an earlier pass to force
36 // forward iteration through memory, which is generally better for cache
37 // behavior.  Negative strides *do* happen for memset/memcpy loops.
38 //
39 // This could recognize common matrix multiplies and dot product idioms and
40 // replace them with calls to BLAS (if linked in??).
41 //
42 //===----------------------------------------------------------------------===//
43
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Analysis/AliasAnalysis.h"
47 #include "llvm/Analysis/LoopPass.h"
48 #include "llvm/Analysis/ScalarEvolutionExpander.h"
49 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
50 #include "llvm/Analysis/TargetLibraryInfo.h"
51 #include "llvm/Analysis/TargetTransformInfo.h"
52 #include "llvm/Analysis/ValueTracking.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Transforms/Utils/Local.h"
61 using namespace llvm;
62
63 #define DEBUG_TYPE "loop-idiom"
64
65 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
66 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
67
68 namespace {
69
70 class LoopIdiomRecognize;
71
72 /// This class is to recoginize idioms of population-count conducted in
73 /// a noncountable loop. Currently it only recognizes this pattern:
74 /// \code
75 ///   while(x) {cnt++; ...; x &= x - 1; ...}
76 /// \endcode
77 class NclPopcountRecognize {
78   LoopIdiomRecognize &LIR;
79   Loop *CurLoop;
80   BasicBlock *PreCondBB;
81
82   typedef IRBuilder<> IRBuilderTy;
83
84 public:
85   explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
86   bool recognize();
87
88 private:
89   /// Take a glimpse of the loop to see if we need to go ahead recoginizing
90   /// the idiom.
91   bool preliminaryScreen();
92
93   /// Check if the given conditional branch is based on the comparison
94   /// between a variable and zero, and if the variable is non-zero, the
95   /// control yields to the loop entry. If the branch matches the behavior,
96   /// the variable involved in the comparion is returned. This function will
97   /// be called to see if the precondition and postcondition of the loop
98   /// are in desirable form.
99   Value *matchCondition(BranchInst *Br, BasicBlock *NonZeroTarget) const;
100
101   /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
102   /// is set to the instruction counting the population bit. 2) \p CntPhi
103   /// is set to the corresponding phi node. 3) \p Var is set to the value
104   /// whose population bits are being counted.
105   bool detectIdiom(Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
106
107   /// Insert ctpop intrinsic function and some obviously dead instructions.
108   void transform(Instruction *CntInst, PHINode *CntPhi, Value *Var);
109
110   /// Create llvm.ctpop.* intrinsic function.
111   CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
112 };
113
114 class LoopIdiomRecognize : public LoopPass {
115   Loop *CurLoop;
116   DominatorTree *DT;
117   ScalarEvolution *SE;
118   TargetLibraryInfo *TLI;
119   const TargetTransformInfo *TTI;
120
121 public:
122   static char ID;
123   explicit LoopIdiomRecognize() : LoopPass(ID) {
124     initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
125     DT = nullptr;
126     SE = nullptr;
127     TLI = nullptr;
128     TTI = nullptr;
129   }
130
131   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
132   bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
133                       SmallVectorImpl<BasicBlock *> &ExitBlocks);
134
135   bool processLoopStore(StoreInst *SI, const SCEV *BECount);
136   bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
137
138   bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
139                                unsigned StoreAlignment, Value *SplatValue,
140                                Instruction *TheStore, const SCEVAddRecExpr *Ev,
141                                const SCEV *BECount);
142   bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
143                                   const SCEVAddRecExpr *StoreEv,
144                                   const SCEVAddRecExpr *LoadEv,
145                                   const SCEV *BECount);
146
147   /// This transformation requires natural loop information & requires that
148   /// loop preheaders be inserted into the CFG.
149   ///
150   void getAnalysisUsage(AnalysisUsage &AU) const override {
151     AU.addRequired<LoopInfoWrapperPass>();
152     AU.addPreserved<LoopInfoWrapperPass>();
153     AU.addRequiredID(LoopSimplifyID);
154     AU.addPreservedID(LoopSimplifyID);
155     AU.addRequiredID(LCSSAID);
156     AU.addPreservedID(LCSSAID);
157     AU.addRequired<AliasAnalysis>();
158     AU.addPreserved<AliasAnalysis>();
159     AU.addRequired<ScalarEvolution>();
160     AU.addPreserved<ScalarEvolution>();
161     AU.addPreserved<DominatorTreeWrapperPass>();
162     AU.addRequired<DominatorTreeWrapperPass>();
163     AU.addRequired<TargetLibraryInfoWrapperPass>();
164     AU.addRequired<TargetTransformInfoWrapperPass>();
165   }
166
167   DominatorTree *getDominatorTree() {
168     return DT ? DT
169               : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
170   }
171
172   ScalarEvolution *getScalarEvolution() {
173     return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
174   }
175
176   TargetLibraryInfo *getTargetLibraryInfo() {
177     if (!TLI)
178       TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
179
180     return TLI;
181   }
182
183   const TargetTransformInfo *getTargetTransformInfo() {
184     return TTI ? TTI
185                : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
186                       *CurLoop->getHeader()->getParent()));
187   }
188
189   Loop *getLoop() const { return CurLoop; }
190
191 private:
192   bool runOnNoncountableLoop();
193   bool runOnCountableLoop();
194 };
195
196 } // End anonymous namespace.
197
198 char LoopIdiomRecognize::ID = 0;
199 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
200                       false, false)
201 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
202 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
203 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
204 INITIALIZE_PASS_DEPENDENCY(LCSSA)
205 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
206 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
207 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
208 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
209 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
210                     false, false)
211
212 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
213
214 /// deleteDeadInstruction - Delete this instruction.  Before we do, go through
215 /// and zero out all the operands of this instruction.  If any of them become
216 /// dead, delete them and the computation tree that feeds them.
217 ///
218 static void deleteDeadInstruction(Instruction *I,
219                                   const TargetLibraryInfo *TLI) {
220   SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
221   I->replaceAllUsesWith(UndefValue::get(I->getType()));
222   I->eraseFromParent();
223   for (Value *Op : Operands)
224     RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
225 }
226
227 //===----------------------------------------------------------------------===//
228 //
229 //          Implementation of NclPopcountRecognize
230 //
231 //===----------------------------------------------------------------------===//
232
233 NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR)
234     : LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {}
235
236 bool NclPopcountRecognize::preliminaryScreen() {
237   const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
238   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
239     return false;
240
241   // Counting population are usually conducted by few arithmetic instructions.
242   // Such instructions can be easilly "absorbed" by vacant slots in a
243   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
244   // in a compact loop.
245
246   // Give up if the loop has multiple blocks or multiple backedges.
247   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
248     return false;
249
250   BasicBlock *LoopBody = *(CurLoop->block_begin());
251   if (LoopBody->size() >= 20) {
252     // The loop is too big, bail out.
253     return false;
254   }
255
256   // It should have a preheader containing nothing but an unconditional branch.
257   BasicBlock *PH = CurLoop->getLoopPreheader();
258   if (!PH)
259     return false;
260   if (&PH->front() != PH->getTerminator())
261     return false;
262   auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
263   if (!EntryBI || EntryBI->isConditional())
264     return false;
265
266   // It should have a precondition block where the generated popcount instrinsic
267   // function can be inserted.
268   PreCondBB = PH->getSinglePredecessor();
269   if (!PreCondBB)
270     return false;
271   auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
272   if (!PreCondBI || PreCondBI->isUnconditional())
273     return false;
274
275   return true;
276 }
277
278 Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
279                                             BasicBlock *LoopEntry) const {
280   if (!Br || !Br->isConditional())
281     return nullptr;
282
283   ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
284   if (!Cond)
285     return nullptr;
286
287   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
288   if (!CmpZero || !CmpZero->isZero())
289     return nullptr;
290
291   ICmpInst::Predicate Pred = Cond->getPredicate();
292   if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
293       (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
294     return Cond->getOperand(0);
295
296   return nullptr;
297 }
298
299 bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst, PHINode *&CntPhi,
300                                        Value *&Var) const {
301   // Following code tries to detect this idiom:
302   //
303   //    if (x0 != 0)
304   //      goto loop-exit // the precondition of the loop
305   //    cnt0 = init-val;
306   //    do {
307   //       x1 = phi (x0, x2);
308   //       cnt1 = phi(cnt0, cnt2);
309   //
310   //       cnt2 = cnt1 + 1;
311   //        ...
312   //       x2 = x1 & (x1 - 1);
313   //        ...
314   //    } while(x != 0);
315   //
316   // loop-exit:
317   //
318
319   // step 1: Check to see if the look-back branch match this pattern:
320   //    "if (a!=0) goto loop-entry".
321   BasicBlock *LoopEntry;
322   Instruction *DefX2, *CountInst;
323   Value *VarX1, *VarX0;
324   PHINode *PhiX, *CountPhi;
325
326   DefX2 = CountInst = nullptr;
327   VarX1 = VarX0 = nullptr;
328   PhiX = CountPhi = nullptr;
329   LoopEntry = *(CurLoop->block_begin());
330
331   // step 1: Check if the loop-back branch is in desirable form.
332   {
333     if (Value *T = matchCondition(
334             dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
335       DefX2 = dyn_cast<Instruction>(T);
336     else
337       return false;
338   }
339
340   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
341   {
342     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
343       return false;
344
345     BinaryOperator *SubOneOp;
346
347     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
348       VarX1 = DefX2->getOperand(1);
349     else {
350       VarX1 = DefX2->getOperand(0);
351       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
352     }
353     if (!SubOneOp)
354       return false;
355
356     Instruction *SubInst = cast<Instruction>(SubOneOp);
357     ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
358     if (!Dec ||
359         !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
360           (SubInst->getOpcode() == Instruction::Add &&
361            Dec->isAllOnesValue()))) {
362       return false;
363     }
364   }
365
366   // step 3: Check the recurrence of variable X
367   {
368     PhiX = dyn_cast<PHINode>(VarX1);
369     if (!PhiX ||
370         (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
371       return false;
372     }
373   }
374
375   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
376   {
377     CountInst = nullptr;
378     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
379                               IterE = LoopEntry->end();
380          Iter != IterE; Iter++) {
381       Instruction *Inst = Iter;
382       if (Inst->getOpcode() != Instruction::Add)
383         continue;
384
385       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
386       if (!Inc || !Inc->isOne())
387         continue;
388
389       PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
390       if (!Phi || Phi->getParent() != LoopEntry)
391         continue;
392
393       // Check if the result of the instruction is live of the loop.
394       bool LiveOutLoop = false;
395       for (User *U : Inst->users()) {
396         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
397           LiveOutLoop = true;
398           break;
399         }
400       }
401
402       if (LiveOutLoop) {
403         CountInst = Inst;
404         CountPhi = Phi;
405         break;
406       }
407     }
408
409     if (!CountInst)
410       return false;
411   }
412
413   // step 5: check if the precondition is in this form:
414   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
415   {
416     auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
417     Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
418     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
419       return false;
420
421     CntInst = CountInst;
422     CntPhi = CountPhi;
423     Var = T;
424   }
425
426   return true;
427 }
428
429 void NclPopcountRecognize::transform(Instruction *CntInst, PHINode *CntPhi,
430                                      Value *Var) {
431
432   ScalarEvolution *SE = LIR.getScalarEvolution();
433   TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
434   BasicBlock *PreHead = CurLoop->getLoopPreheader();
435   auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
436   const DebugLoc DL = CntInst->getDebugLoc();
437
438   // Assuming before transformation, the loop is following:
439   //  if (x) // the precondition
440   //     do { cnt++; x &= x - 1; } while(x);
441
442   // Step 1: Insert the ctpop instruction at the end of the precondition block
443   IRBuilderTy Builder(PreCondBr);
444   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
445   {
446     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
447     NewCount = PopCntZext =
448         Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
449
450     if (NewCount != PopCnt)
451       (cast<Instruction>(NewCount))->setDebugLoc(DL);
452
453     // TripCnt is exactly the number of iterations the loop has
454     TripCnt = NewCount;
455
456     // If the population counter's initial value is not zero, insert Add Inst.
457     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
458     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
459     if (!InitConst || !InitConst->isZero()) {
460       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
461       (cast<Instruction>(NewCount))->setDebugLoc(DL);
462     }
463   }
464
465   // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
466   //   "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
467   //   function would be partial dead code, and downstream passes will drag
468   //   it back from the precondition block to the preheader.
469   {
470     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
471
472     Value *Opnd0 = PopCntZext;
473     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
474     if (PreCond->getOperand(0) != Var)
475       std::swap(Opnd0, Opnd1);
476
477     ICmpInst *NewPreCond = cast<ICmpInst>(
478         Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
479     PreCondBr->setCondition(NewPreCond);
480
481     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
482   }
483
484   // Step 3: Note that the population count is exactly the trip count of the
485   // loop in question, which enble us to to convert the loop from noncountable
486   // loop into a countable one. The benefit is twofold:
487   //
488   //  - If the loop only counts population, the entire loop become dead after
489   //    the transformation. It is lots easier to prove a countable loop dead
490   //    than to prove a noncountable one. (In some C dialects, a infite loop
491   //    isn't dead even if it computes nothing useful. In general, DCE needs
492   //    to prove a noncountable loop finite before safely delete it.)
493   //
494   //  - If the loop also performs something else, it remains alive.
495   //    Since it is transformed to countable form, it can be aggressively
496   //    optimized by some optimizations which are in general not applicable
497   //    to a noncountable loop.
498   //
499   // After this step, this loop (conceptually) would look like following:
500   //   newcnt = __builtin_ctpop(x);
501   //   t = newcnt;
502   //   if (x)
503   //     do { cnt++; x &= x-1; t--) } while (t > 0);
504   BasicBlock *Body = *(CurLoop->block_begin());
505   {
506     auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
507     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
508     Type *Ty = TripCnt->getType();
509
510     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
511
512     Builder.SetInsertPoint(LbCond);
513     Value *Opnd1 = cast<Value>(TcPhi);
514     Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
515     Instruction *TcDec = cast<Instruction>(
516         Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
517
518     TcPhi->addIncoming(TripCnt, PreHead);
519     TcPhi->addIncoming(TcDec, Body);
520
521     CmpInst::Predicate Pred =
522         (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
523     LbCond->setPredicate(Pred);
524     LbCond->setOperand(0, TcDec);
525     LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
526   }
527
528   // Step 4: All the references to the original population counter outside
529   //  the loop are replaced with the NewCount -- the value returned from
530   //  __builtin_ctpop().
531   CntInst->replaceUsesOutsideBlock(NewCount, Body);
532
533   // step 5: Forget the "non-computable" trip-count SCEV associated with the
534   //   loop. The loop would otherwise not be deleted even if it becomes empty.
535   SE->forgetLoop(CurLoop);
536 }
537
538 CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
539                                                       Value *Val, DebugLoc DL) {
540   Value *Ops[] = {Val};
541   Type *Tys[] = {Val->getType()};
542
543   Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
544   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
545   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
546   CI->setDebugLoc(DL);
547
548   return CI;
549 }
550
551 /// recognize - detect population count idiom in a non-countable loop. If
552 ///   detected, transform the relevant code to popcount intrinsic function
553 ///   call, and return true; otherwise, return false.
554 bool NclPopcountRecognize::recognize() {
555
556   if (!LIR.getTargetTransformInfo())
557     return false;
558
559   LIR.getScalarEvolution();
560
561   if (!preliminaryScreen())
562     return false;
563
564   Instruction *CntInst;
565   PHINode *CntPhi;
566   Value *Val;
567   if (!detectIdiom(CntInst, CntPhi, Val))
568     return false;
569
570   transform(CntInst, CntPhi, Val);
571   return true;
572 }
573
574 //===----------------------------------------------------------------------===//
575 //
576 //          Implementation of LoopIdiomRecognize
577 //
578 //===----------------------------------------------------------------------===//
579
580 bool LoopIdiomRecognize::runOnCountableLoop() {
581   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
582   assert(!isa<SCEVCouldNotCompute>(BECount) &&
583          "runOnCountableLoop() called on a loop without a predictable"
584          "backedge-taken count");
585
586   // If this loop executes exactly one time, then it should be peeled, not
587   // optimized by this pass.
588   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
589     if (BECst->getValue()->getValue() == 0)
590       return false;
591
592   // set DT
593   (void)getDominatorTree();
594
595   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
596   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
597
598   // set TLI
599   (void)getTargetLibraryInfo();
600
601   SmallVector<BasicBlock *, 8> ExitBlocks;
602   CurLoop->getUniqueExitBlocks(ExitBlocks);
603
604   DEBUG(dbgs() << "loop-idiom Scanning: F["
605                << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
606                << CurLoop->getHeader()->getName() << "\n");
607
608   bool MadeChange = false;
609   // Scan all the blocks in the loop that are not in subloops.
610   for (auto *BB : CurLoop->getBlocks()) {
611     // Ignore blocks in subloops.
612     if (LI.getLoopFor(BB) != CurLoop)
613       continue;
614
615     MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
616   }
617   return MadeChange;
618 }
619
620 bool LoopIdiomRecognize::runOnNoncountableLoop() {
621   NclPopcountRecognize Popcount(*this);
622   if (Popcount.recognize())
623     return true;
624
625   return false;
626 }
627
628 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
629   if (skipOptnoneFunction(L))
630     return false;
631
632   CurLoop = L;
633
634   // If the loop could not be converted to canonical form, it must have an
635   // indirectbr in it, just give up.
636   if (!L->getLoopPreheader())
637     return false;
638
639   // Disable loop idiom recognition if the function's name is a common idiom.
640   StringRef Name = L->getHeader()->getParent()->getName();
641   if (Name == "memset" || Name == "memcpy")
642     return false;
643
644   SE = &getAnalysis<ScalarEvolution>();
645   if (SE->hasLoopInvariantBackedgeTakenCount(L))
646     return runOnCountableLoop();
647   return runOnNoncountableLoop();
648 }
649
650 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
651 /// with the specified backedge count.  This block is known to be in the current
652 /// loop and not in any subloops.
653 bool LoopIdiomRecognize::runOnLoopBlock(
654     BasicBlock *BB, const SCEV *BECount,
655     SmallVectorImpl<BasicBlock *> &ExitBlocks) {
656   // We can only promote stores in this block if they are unconditionally
657   // executed in the loop.  For a block to be unconditionally executed, it has
658   // to dominate all the exit blocks of the loop.  Verify this now.
659   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
660     if (!DT->dominates(BB, ExitBlocks[i]))
661       return false;
662
663   bool MadeChange = false;
664   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
665     Instruction *Inst = I++;
666     // Look for store instructions, which may be optimized to memset/memcpy.
667     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
668       WeakVH InstPtr(I);
669       if (!processLoopStore(SI, BECount))
670         continue;
671       MadeChange = true;
672
673       // If processing the store invalidated our iterator, start over from the
674       // top of the block.
675       if (!InstPtr)
676         I = BB->begin();
677       continue;
678     }
679
680     // Look for memset instructions, which may be optimized to a larger memset.
681     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
682       WeakVH InstPtr(I);
683       if (!processLoopMemSet(MSI, BECount))
684         continue;
685       MadeChange = true;
686
687       // If processing the memset invalidated our iterator, start over from the
688       // top of the block.
689       if (!InstPtr)
690         I = BB->begin();
691       continue;
692     }
693   }
694
695   return MadeChange;
696 }
697
698 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
699 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
700   if (!SI->isSimple())
701     return false;
702
703   Value *StoredVal = SI->getValueOperand();
704   Value *StorePtr = SI->getPointerOperand();
705
706   // Reject stores that are so large that they overflow an unsigned.
707   auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
708   uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
709   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
710     return false;
711
712   // See if the pointer expression is an AddRec like {base,+,1} on the current
713   // loop, which indicates a strided store.  If we have something else, it's a
714   // random store we can't handle.
715   const SCEVAddRecExpr *StoreEv =
716       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
717   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
718     return false;
719
720   // Check to see if the stride matches the size of the store.  If so, then we
721   // know that every byte is touched in the loop.
722   unsigned StoreSize = (unsigned)SizeInBits >> 3;
723   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
724
725   if (!Stride || StoreSize != Stride->getValue()->getValue()) {
726     // TODO: Could also handle negative stride here someday, that will require
727     // the validity check in mayLoopAccessLocation to be updated though.
728     // Enable this to print exact negative strides.
729     if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
730       dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
731       dbgs() << "BB: " << *SI->getParent();
732     }
733
734     return false;
735   }
736
737   // See if we can optimize just this store in isolation.
738   if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
739                               StoredVal, SI, StoreEv, BECount))
740     return true;
741
742   // If the stored value is a strided load in the same loop with the same stride
743   // this this may be transformable into a memcpy.  This kicks in for stuff like
744   //   for (i) A[i] = B[i];
745   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
746     const SCEVAddRecExpr *LoadEv =
747         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
748     if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
749         StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
750       if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
751         return true;
752   }
753   // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
754
755   return false;
756 }
757
758 /// processLoopMemSet - See if this memset can be promoted to a large memset.
759 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
760                                            const SCEV *BECount) {
761   // We can only handle non-volatile memsets with a constant size.
762   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
763     return false;
764
765   // If we're not allowed to hack on memset, we fail.
766   if (!TLI->has(LibFunc::memset))
767     return false;
768
769   Value *Pointer = MSI->getDest();
770
771   // See if the pointer expression is an AddRec like {base,+,1} on the current
772   // loop, which indicates a strided store.  If we have something else, it's a
773   // random store we can't handle.
774   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
775   if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
776     return false;
777
778   // Reject memsets that are so large that they overflow an unsigned.
779   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
780   if ((SizeInBytes >> 32) != 0)
781     return false;
782
783   // Check to see if the stride matches the size of the memset.  If so, then we
784   // know that every byte is touched in the loop.
785   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
786
787   // TODO: Could also handle negative stride here someday, that will require the
788   // validity check in mayLoopAccessLocation to be updated though.
789   if (!Stride || MSI->getLength() != Stride->getValue())
790     return false;
791
792   return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
793                                  MSI->getAlignment(), MSI->getValue(), MSI, Ev,
794                                  BECount);
795 }
796
797 /// mayLoopAccessLocation - Return true if the specified loop might access the
798 /// specified pointer location, which is a loop-strided access.  The 'Access'
799 /// argument specifies what the verboten forms of access are (read or write).
800 static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
801                                   const SCEV *BECount, unsigned StoreSize,
802                                   AliasAnalysis &AA,
803                                   Instruction *IgnoredStore) {
804   // Get the location that may be stored across the loop.  Since the access is
805   // strided positively through memory, we say that the modified location starts
806   // at the pointer and has infinite size.
807   uint64_t AccessSize = MemoryLocation::UnknownSize;
808
809   // If the loop iterates a fixed number of times, we can refine the access size
810   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
811   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
812     AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
813
814   // TODO: For this to be really effective, we have to dive into the pointer
815   // operand in the store.  Store to &A[i] of 100 will always return may alias
816   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
817   // which will then no-alias a store to &A[100].
818   MemoryLocation StoreLoc(Ptr, AccessSize);
819
820   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
821        ++BI)
822     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
823       if (&*I != IgnoredStore && (AA.getModRefInfo(I, StoreLoc) & Access))
824         return true;
825
826   return false;
827 }
828
829 /// getMemSetPatternValue - If a strided store of the specified value is safe to
830 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
831 /// be passed in.  Otherwise, return null.
832 ///
833 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
834 /// just replicate their input array and then pass on to memset_pattern16.
835 static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
836   // If the value isn't a constant, we can't promote it to being in a constant
837   // array.  We could theoretically do a store to an alloca or something, but
838   // that doesn't seem worthwhile.
839   Constant *C = dyn_cast<Constant>(V);
840   if (!C)
841     return nullptr;
842
843   // Only handle simple values that are a power of two bytes in size.
844   uint64_t Size = DL.getTypeSizeInBits(V->getType());
845   if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
846     return nullptr;
847
848   // Don't care enough about darwin/ppc to implement this.
849   if (DL.isBigEndian())
850     return nullptr;
851
852   // Convert to size in bytes.
853   Size /= 8;
854
855   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
856   // if the top and bottom are the same (e.g. for vectors and large integers).
857   if (Size > 16)
858     return nullptr;
859
860   // If the constant is exactly 16 bytes, just use it.
861   if (Size == 16)
862     return C;
863
864   // Otherwise, we'll use an array of the constants.
865   unsigned ArraySize = 16 / Size;
866   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
867   return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
868 }
869
870 /// processLoopStridedStore - We see a strided store of some value.  If we can
871 /// transform this into a memset or memset_pattern in the loop preheader, do so.
872 bool LoopIdiomRecognize::processLoopStridedStore(
873     Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
874     Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
875     const SCEV *BECount) {
876
877   // If the stored value is a byte-wise value (like i32 -1), then it may be
878   // turned into a memset of i8 -1, assuming that all the consecutive bytes
879   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
880   // but it can be turned into memset_pattern if the target supports it.
881   Value *SplatValue = isBytewiseValue(StoredVal);
882   Constant *PatternValue = nullptr;
883   auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
884   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
885
886   // If we're allowed to form a memset, and the stored value would be acceptable
887   // for memset, use it.
888   if (SplatValue && TLI->has(LibFunc::memset) &&
889       // Verify that the stored value is loop invariant.  If not, we can't
890       // promote the memset.
891       CurLoop->isLoopInvariant(SplatValue)) {
892     // Keep and use SplatValue.
893     PatternValue = nullptr;
894   } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
895              (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
896     // Don't create memset_pattern16s with address spaces.
897     // It looks like we can use PatternValue!
898     SplatValue = nullptr;
899   } else {
900     // Otherwise, this isn't an idiom we can transform.  For example, we can't
901     // do anything with a 3-byte store.
902     return false;
903   }
904
905   // The trip count of the loop and the base pointer of the addrec SCEV is
906   // guaranteed to be loop invariant, which means that it should dominate the
907   // header.  This allows us to insert code for it in the preheader.
908   BasicBlock *Preheader = CurLoop->getLoopPreheader();
909   IRBuilder<> Builder(Preheader->getTerminator());
910   SCEVExpander Expander(*SE, DL, "loop-idiom");
911
912   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
913
914   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
915   // this into a memset in the loop preheader now if we want.  However, this
916   // would be unsafe to do if there is anything else in the loop that may read
917   // or write to the aliased location.  Check for any overlap by generating the
918   // base pointer and checking the region.
919   Value *BasePtr = Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
920                                           Preheader->getTerminator());
921
922   if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
923                             getAnalysis<AliasAnalysis>(), TheStore)) {
924     Expander.clear();
925     // If we generated new code for the base pointer, clean up.
926     RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
927     return false;
928   }
929
930   // Okay, everything looks good, insert the memset.
931
932   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
933   // pointer size if it isn't already.
934   Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
935   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
936
937   const SCEV *NumBytesS =
938       SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), SCEV::FlagNUW);
939   if (StoreSize != 1) {
940     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
941                                SCEV::FlagNUW);
942   }
943
944   Value *NumBytes =
945       Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
946
947   CallInst *NewCall;
948   if (SplatValue) {
949     NewCall =
950         Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
951   } else {
952     // Everything is emitted in default address space
953     Type *Int8PtrTy = DestInt8PtrTy;
954
955     Module *M = TheStore->getParent()->getParent()->getParent();
956     Value *MSP =
957         M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
958                                Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
959
960     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
961     // an constant array of 16-bytes.  Plop the value into a mergable global.
962     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
963                                             GlobalValue::PrivateLinkage,
964                                             PatternValue, ".memset_pattern");
965     GV->setUnnamedAddr(true); // Ok to merge these.
966     GV->setAlignment(16);
967     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
968     NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
969   }
970
971   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
972                << "    from store to: " << *Ev << " at: " << *TheStore << "\n");
973   NewCall->setDebugLoc(TheStore->getDebugLoc());
974
975   // Okay, the memset has been formed.  Zap the original store and anything that
976   // feeds into it.
977   deleteDeadInstruction(TheStore, TLI);
978   ++NumMemSet;
979   return true;
980 }
981
982 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
983 /// same-strided load.
984 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
985     StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
986     const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
987   // If we're not allowed to form memcpy, we fail.
988   if (!TLI->has(LibFunc::memcpy))
989     return false;
990
991   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
992
993   // The trip count of the loop and the base pointer of the addrec SCEV is
994   // guaranteed to be loop invariant, which means that it should dominate the
995   // header.  This allows us to insert code for it in the preheader.
996   BasicBlock *Preheader = CurLoop->getLoopPreheader();
997   IRBuilder<> Builder(Preheader->getTerminator());
998   const DataLayout &DL = Preheader->getModule()->getDataLayout();
999   SCEVExpander Expander(*SE, DL, "loop-idiom");
1000
1001   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
1002   // this into a memcpy in the loop preheader now if we want.  However, this
1003   // would be unsafe to do if there is anything else in the loop that may read
1004   // or write the memory region we're storing to.  This includes the load that
1005   // feeds the stores.  Check for an alias by generating the base address and
1006   // checking everything.
1007   Value *StoreBasePtr = Expander.expandCodeFor(
1008       StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1009       Preheader->getTerminator());
1010
1011   if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
1012                             StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1013     Expander.clear();
1014     // If we generated new code for the base pointer, clean up.
1015     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
1016     return false;
1017   }
1018
1019   // For a memcpy, we have to make sure that the input array is not being
1020   // mutated by the loop.
1021   Value *LoadBasePtr = Expander.expandCodeFor(
1022       LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1023       Preheader->getTerminator());
1024
1025   if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
1026                             getAnalysis<AliasAnalysis>(), SI)) {
1027     Expander.clear();
1028     // If we generated new code for the base pointer, clean up.
1029     RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1030     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
1031     return false;
1032   }
1033
1034   // Okay, everything is safe, we can transform this!
1035
1036   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
1037   // pointer size if it isn't already.
1038   Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
1039   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
1040
1041   const SCEV *NumBytesS =
1042       SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1), SCEV::FlagNUW);
1043   if (StoreSize != 1)
1044     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
1045                                SCEV::FlagNUW);
1046
1047   Value *NumBytes =
1048       Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1049
1050   CallInst *NewCall =
1051       Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1052                            std::min(SI->getAlignment(), LI->getAlignment()));
1053   NewCall->setDebugLoc(SI->getDebugLoc());
1054
1055   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
1056                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1057                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
1058
1059   // Okay, the memset has been formed.  Zap the original store and anything that
1060   // feeds into it.
1061   deleteDeadInstruction(SI, TLI);
1062   ++NumMemCpy;
1063   return true;
1064 }