xref: /llvm-project/llvm/lib/CodeGen/HardwareLoops.cpp (revision 67f9dc60b8daf69a7119a92b9f525eece0887e4f)
1 //===-- HardwareLoops.cpp - Target Independent Hardware Loops --*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// Insert hardware loop intrinsics into loops which are deemed profitable by
10 /// the target, by querying TargetTransformInfo. A hardware loop comprises of
11 /// two intrinsics: one, outside the loop, to set the loop iteration count and
12 /// another, in the exit block, to decrement the counter. The decremented value
13 /// can either be carried through the loop via a phi or handled in some opaque
14 /// way by the target.
15 ///
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Pass.h"
19 #include "llvm/PassRegistry.h"
20 #include "llvm/PassSupport.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/CFG.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/LoopIterator.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Analysis/ScalarEvolutionExpander.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/TargetPassConfig.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Transforms/Utils.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include "llvm/Transforms/Utils/LoopUtils.h"
45 
46 #define DEBUG_TYPE "hardware-loops"
47 
48 #define HW_LOOPS_NAME "Hardware Loop Insertion"
49 
50 using namespace llvm;
51 
52 static cl::opt<bool>
53 ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false),
54                    cl::desc("Force hardware loops intrinsics to be inserted"));
55 
56 static cl::opt<bool>
57 ForceHardwareLoopPHI(
58   "force-hardware-loop-phi", cl::Hidden, cl::init(false),
59   cl::desc("Force hardware loop counter to be updated through a phi"));
60 
61 static cl::opt<bool>
62 ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false),
63                 cl::desc("Force allowance of nested hardware loops"));
64 
65 static cl::opt<unsigned>
66 LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1),
67             cl::desc("Set the loop decrement value"));
68 
69 static cl::opt<unsigned>
70 CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32),
71                 cl::desc("Set the loop counter bitwidth"));
72 
73 STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
74 
75 namespace {
76 
77   using TTI = TargetTransformInfo;
78 
79   class HardwareLoops : public FunctionPass {
80   public:
81     static char ID;
82 
83     HardwareLoops() : FunctionPass(ID) {
84       initializeHardwareLoopsPass(*PassRegistry::getPassRegistry());
85     }
86 
87     bool runOnFunction(Function &F) override;
88 
89     void getAnalysisUsage(AnalysisUsage &AU) const override {
90       AU.addRequired<LoopInfoWrapperPass>();
91       AU.addPreserved<LoopInfoWrapperPass>();
92       AU.addRequired<DominatorTreeWrapperPass>();
93       AU.addPreserved<DominatorTreeWrapperPass>();
94       AU.addRequired<ScalarEvolutionWrapperPass>();
95       AU.addRequired<AssumptionCacheTracker>();
96       AU.addRequired<TargetTransformInfoWrapperPass>();
97     }
98 
99     // Try to convert the given Loop into a hardware loop.
100     bool TryConvertLoop(Loop *L);
101 
102     // Given that the target believes the loop to be profitable, try to
103     // convert it.
104     bool TryConvertLoop(TTI::HardwareLoopInfo &HWLoopInfo);
105 
106   private:
107     ScalarEvolution *SE = nullptr;
108     LoopInfo *LI = nullptr;
109     const DataLayout *DL = nullptr;
110     const TargetTransformInfo *TTI = nullptr;
111     DominatorTree *DT = nullptr;
112     bool PreserveLCSSA = false;
113     AssumptionCache *AC = nullptr;
114     TargetLibraryInfo *LibInfo = nullptr;
115     Module *M = nullptr;
116     bool MadeChange = false;
117   };
118 
119   class HardwareLoop {
120     // Expand the trip count scev into a value that we can use.
121     Value *InitLoopCount(BasicBlock *BB);
122 
123     // Insert the set_loop_iteration intrinsic.
124     void InsertIterationSetup(Value *LoopCountInit, BasicBlock *BB);
125 
126     // Insert the loop_decrement intrinsic.
127     void InsertLoopDec();
128 
129     // Insert the loop_decrement_reg intrinsic.
130     Instruction *InsertLoopRegDec(Value *EltsRem);
131 
132     // If the target requires the counter value to be updated in the loop,
133     // insert a phi to hold the value. The intended purpose is for use by
134     // loop_decrement_reg.
135     PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
136 
137     // Create a new cmp, that checks the returned value of loop_decrement*,
138     // and update the exit branch to use it.
139     void UpdateBranch(Value *EltsRem);
140 
141   public:
142     HardwareLoop(TTI::HardwareLoopInfo &Info, ScalarEvolution &SE,
143                  const DataLayout &DL) :
144       SE(SE), DL(DL), L(Info.L), M(L->getHeader()->getModule()),
145       ExitCount(Info.ExitCount),
146       CountType(Info.CountType),
147       ExitBranch(Info.ExitBranch),
148       LoopDecrement(Info.LoopDecrement),
149       UsePHICounter(Info.CounterInReg) { }
150 
151     void Create();
152 
153   private:
154     ScalarEvolution &SE;
155     const DataLayout &DL;
156     Loop *L                 = nullptr;
157     Module *M               = nullptr;
158     const SCEV *ExitCount   = nullptr;
159     Type *CountType         = nullptr;
160     BranchInst *ExitBranch  = nullptr;
161     Value *LoopDecrement      = nullptr;
162     bool UsePHICounter      = false;
163   };
164 }
165 
166 char HardwareLoops::ID = 0;
167 
168 bool HardwareLoops::runOnFunction(Function &F) {
169   if (skipFunction(F))
170     return false;
171 
172   LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
173 
174   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
175   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
176   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
177   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
178   DL = &F.getParent()->getDataLayout();
179   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
180   LibInfo = TLIP ? &TLIP->getTLI() : nullptr;
181   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
182   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
183   M = F.getParent();
184 
185   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
186     Loop *L = *I;
187     if (!L->getParentLoop())
188       TryConvertLoop(L);
189   }
190 
191   return MadeChange;
192 }
193 
194 // Return true if the search should stop, which will be when an inner loop is
195 // converted and the parent loop doesn't support containing a hardware loop.
196 bool HardwareLoops::TryConvertLoop(Loop *L) {
197   // Process nested loops first.
198   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
199     if (TryConvertLoop(*I))
200       return true; // Stop search.
201 
202   // Bail out if the loop has irreducible control flow.
203   LoopBlocksRPO RPOT(L);
204   RPOT.perform(LI);
205   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI))
206     return false;
207 
208   TTI::HardwareLoopInfo HWLoopInfo(L);
209   if (TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo) ||
210       ForceHardwareLoops) {
211 
212     // Allow overriding of the counter width and loop decrement value.
213     if (CounterBitWidth.getNumOccurrences())
214       HWLoopInfo.CountType =
215         IntegerType::get(M->getContext(), CounterBitWidth);
216 
217     if (LoopDecrement.getNumOccurrences())
218       HWLoopInfo.LoopDecrement =
219         ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
220 
221     MadeChange |= TryConvertLoop(HWLoopInfo);
222     return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
223   }
224 
225   return false;
226 }
227 
228 bool HardwareLoops::TryConvertLoop(TTI::HardwareLoopInfo &HWLoopInfo) {
229 
230   Loop *L = HWLoopInfo.L;
231   LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
232 
233   SmallVector<BasicBlock*, 4> ExitingBlocks;
234   L->getExitingBlocks(ExitingBlocks);
235 
236   for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
237        IE = ExitingBlocks.end(); I != IE; ++I) {
238     const SCEV *EC = SE->getExitCount(L, *I);
239     if (isa<SCEVCouldNotCompute>(EC))
240       continue;
241     if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
242       if (ConstEC->getValue()->isZero())
243         continue;
244     } else if (!SE->isLoopInvariant(EC, L))
245       continue;
246 
247     if (SE->getTypeSizeInBits(EC->getType()) >
248         HWLoopInfo.CountType->getBitWidth())
249       continue;
250 
251     // If this exiting block is contained in a nested loop, it is not eligible
252     // for insertion of the branch-and-decrement since the inner loop would
253     // end up messing up the value in the CTR.
254     if (!HWLoopInfo.IsNestingLegal && LI->getLoopFor(*I) != L &&
255         !ForceNestedLoop)
256       continue;
257 
258     // We now have a loop-invariant count of loop iterations (which is not the
259     // constant zero) for which we know that this loop will not exit via this
260     // existing block.
261 
262     // We need to make sure that this block will run on every loop iteration.
263     // For this to be true, we must dominate all blocks with backedges. Such
264     // blocks are in-loop predecessors to the header block.
265     bool NotAlways = false;
266     for (pred_iterator PI = pred_begin(L->getHeader()),
267          PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
268       if (!L->contains(*PI))
269         continue;
270 
271       if (!DT->dominates(*I, *PI)) {
272         NotAlways = true;
273         break;
274       }
275     }
276 
277     if (NotAlways)
278       continue;
279 
280     // Make sure this blocks ends with a conditional branch.
281     Instruction *TI = (*I)->getTerminator();
282     if (!TI)
283       continue;
284 
285     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
286       if (!BI->isConditional())
287         continue;
288 
289       HWLoopInfo.ExitBranch = BI;
290     } else
291       continue;
292 
293     // Note that this block may not be the loop latch block, even if the loop
294     // has a latch block.
295     HWLoopInfo.ExitBlock = *I;
296     HWLoopInfo.ExitCount = EC;
297     break;
298   }
299 
300   if (!HWLoopInfo.ExitBlock)
301     return false;
302 
303   BasicBlock *Preheader = L->getLoopPreheader();
304 
305   // If we don't have a preheader, then insert one.
306   if (!Preheader)
307     Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
308   if (!Preheader)
309     return false;
310 
311   HardwareLoop HWLoop(HWLoopInfo, *SE, *DL);
312   HWLoop.Create();
313   ++NumHWLoops;
314   return true;
315 }
316 
317 void HardwareLoop::Create() {
318   LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
319   BasicBlock *BeginBB = L->getLoopPreheader();
320   Value *LoopCountInit = InitLoopCount(BeginBB);
321   if (!LoopCountInit)
322     return;
323 
324   InsertIterationSetup(LoopCountInit, BeginBB);
325 
326   if (UsePHICounter || ForceHardwareLoopPHI) {
327     Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
328     Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec);
329     LoopDec->setOperand(0, EltsRem);
330     UpdateBranch(LoopDec);
331   } else
332     InsertLoopDec();
333 
334   // Run through the basic blocks of the loop and see if any of them have dead
335   // PHIs that can be removed.
336   for (auto I : L->blocks())
337     DeleteDeadPHIs(I);
338 }
339 
340 Value *HardwareLoop::InitLoopCount(BasicBlock *BB) {
341   SCEVExpander SCEVE(SE, DL, "loopcnt");
342   if (!ExitCount->getType()->isPointerTy() &&
343       ExitCount->getType() != CountType)
344     ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
345 
346   ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
347 
348   if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) {
349     LLVM_DEBUG(dbgs() << "HWLoops: Bailing, unsafe to expand ExitCount "
350                << *ExitCount << "\n");
351     return nullptr;
352   }
353 
354   Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
355                                      BB->getTerminator());
356   LLVM_DEBUG(dbgs() << "HWLoops: Loop Count: " << *Count << "\n");
357   return Count;
358 }
359 
360 void HardwareLoop::InsertIterationSetup(Value *LoopCountInit,
361                                         BasicBlock *BB) {
362   IRBuilder<> Builder(BB->getTerminator());
363   Type *Ty = LoopCountInit->getType();
364   Function *LoopIter =
365     Intrinsic::getDeclaration(M, Intrinsic::set_loop_iterations, Ty);
366   Builder.CreateCall(LoopIter, LoopCountInit);
367 }
368 
369 void HardwareLoop::InsertLoopDec() {
370   IRBuilder<> CondBuilder(ExitBranch);
371 
372   Function *DecFunc =
373     Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
374                               LoopDecrement->getType());
375   Value *Ops[] = { LoopDecrement };
376   Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
377   Value *OldCond = ExitBranch->getCondition();
378   ExitBranch->setCondition(NewCond);
379 
380   // The false branch must exit the loop.
381   if (!L->contains(ExitBranch->getSuccessor(0)))
382     ExitBranch->swapSuccessors();
383 
384   // The old condition may be dead now, and may have even created a dead PHI
385   // (the original induction variable).
386   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
387 
388   LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
389 }
390 
391 Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
392   IRBuilder<> CondBuilder(ExitBranch);
393 
394   Function *DecFunc =
395       Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
396                                 { EltsRem->getType(), EltsRem->getType(),
397                                   LoopDecrement->getType()
398                                 });
399   Value *Ops[] = { EltsRem, LoopDecrement };
400   Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
401 
402   LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
403   return cast<Instruction>(Call);
404 }
405 
406 PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
407   BasicBlock *Preheader = L->getLoopPreheader();
408   BasicBlock *Header = L->getHeader();
409   BasicBlock *Latch = ExitBranch->getParent();
410   IRBuilder<> Builder(Header->getFirstNonPHI());
411   PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
412   Index->addIncoming(NumElts, Preheader);
413   Index->addIncoming(EltsRem, Latch);
414   LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
415   return Index;
416 }
417 
418 void HardwareLoop::UpdateBranch(Value *EltsRem) {
419   IRBuilder<> CondBuilder(ExitBranch);
420   Value *NewCond =
421     CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
422   Value *OldCond = ExitBranch->getCondition();
423   ExitBranch->setCondition(NewCond);
424 
425   // The false branch must exit the loop.
426   if (!L->contains(ExitBranch->getSuccessor(0)))
427     ExitBranch->swapSuccessors();
428 
429   // The old condition may be dead now, and may have even created a dead PHI
430   // (the original induction variable).
431   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
432 }
433 
434 INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
435 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
436 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
437 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
438 INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
439 
440 FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }
441