blob: c1e9604d98b0a80ee395c0df8c864cf04c0589e4 [file] [log] [blame]
Sam Parkerc5ef5022019-06-07 07:35:30 +00001//===-- 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
Sam Parkerc5ef5022019-06-07 07:35:30 +000018#include "llvm/PassRegistry.h"
19#include "llvm/PassSupport.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/AssumptionCache.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000022#include "llvm/Analysis/LoopInfo.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000023#include "llvm/Analysis/ScalarEvolution.h"
24#include "llvm/Analysis/ScalarEvolutionExpander.h"
25#include "llvm/Analysis/TargetTransformInfo.h"
26#include "llvm/CodeGen/Passes.h"
27#include "llvm/CodeGen/TargetPassConfig.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Constants.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Value.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Transforms/Scalar.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Transforms/Utils/Local.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000040
41#define DEBUG_TYPE "hardware-loops"
42
43#define HW_LOOPS_NAME "Hardware Loop Insertion"
44
45using namespace llvm;
46
47static cl::opt<bool>
48ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false),
49 cl::desc("Force hardware loops intrinsics to be inserted"));
50
51static cl::opt<bool>
52ForceHardwareLoopPHI(
53 "force-hardware-loop-phi", cl::Hidden, cl::init(false),
54 cl::desc("Force hardware loop counter to be updated through a phi"));
55
56static cl::opt<bool>
57ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false),
58 cl::desc("Force allowance of nested hardware loops"));
59
60static cl::opt<unsigned>
61LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1),
62 cl::desc("Set the loop decrement value"));
63
64static cl::opt<unsigned>
65CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32),
66 cl::desc("Set the loop counter bitwidth"));
67
Sam Parker9a92be12019-06-28 07:38:16 +000068static cl::opt<bool>
69ForceGuardLoopEntry(
70 "force-hardware-loop-guard", cl::Hidden, cl::init(false),
71 cl::desc("Force generation of loop guard intrinsic"));
72
Sam Parkerc5ef5022019-06-07 07:35:30 +000073STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
74
75namespace {
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.
Chen Zhengc5b918d2019-06-19 01:26:31 +0000104 bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000105
106 private:
107 ScalarEvolution *SE = nullptr;
108 LoopInfo *LI = nullptr;
109 const DataLayout *DL = nullptr;
110 const TargetTransformInfo *TTI = nullptr;
111 DominatorTree *DT = nullptr;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000112 AssumptionCache *AC = nullptr;
113 TargetLibraryInfo *LibInfo = nullptr;
114 Module *M = nullptr;
115 bool MadeChange = false;
116 };
117
118 class HardwareLoop {
119 // Expand the trip count scev into a value that we can use.
Sam Parker9a92be12019-06-28 07:38:16 +0000120 Value *InitLoopCount();
Sam Parkerc5ef5022019-06-07 07:35:30 +0000121
122 // Insert the set_loop_iteration intrinsic.
Sam Parker9a92be12019-06-28 07:38:16 +0000123 void InsertIterationSetup(Value *LoopCountInit);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000124
125 // Insert the loop_decrement intrinsic.
126 void InsertLoopDec();
127
128 // Insert the loop_decrement_reg intrinsic.
129 Instruction *InsertLoopRegDec(Value *EltsRem);
130
131 // If the target requires the counter value to be updated in the loop,
132 // insert a phi to hold the value. The intended purpose is for use by
133 // loop_decrement_reg.
134 PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
135
136 // Create a new cmp, that checks the returned value of loop_decrement*,
137 // and update the exit branch to use it.
138 void UpdateBranch(Value *EltsRem);
139
140 public:
Chen Zhengc5b918d2019-06-19 01:26:31 +0000141 HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE,
Sam Parkerc5ef5022019-06-07 07:35:30 +0000142 const DataLayout &DL) :
143 SE(SE), DL(DL), L(Info.L), M(L->getHeader()->getModule()),
144 ExitCount(Info.ExitCount),
145 CountType(Info.CountType),
146 ExitBranch(Info.ExitBranch),
147 LoopDecrement(Info.LoopDecrement),
Sam Parker9a92be12019-06-28 07:38:16 +0000148 UsePHICounter(Info.CounterInReg),
149 UseLoopGuard(Info.PerformEntryTest) { }
Sam Parkerc5ef5022019-06-07 07:35:30 +0000150
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;
Sam Parker9a92be12019-06-28 07:38:16 +0000161 Value *LoopDecrement = nullptr;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000162 bool UsePHICounter = false;
Sam Parker9a92be12019-06-28 07:38:16 +0000163 bool UseLoopGuard = false;
164 BasicBlock *BeginBB = nullptr;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000165 };
166}
167
168char HardwareLoops::ID = 0;
169
170bool HardwareLoops::runOnFunction(Function &F) {
171 if (skipFunction(F))
172 return false;
173
174 LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
175
176 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
177 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
178 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
179 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
180 DL = &F.getParent()->getDataLayout();
181 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
182 LibInfo = TLIP ? &TLIP->getTLI() : nullptr;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000183 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
184 M = F.getParent();
185
186 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
187 Loop *L = *I;
188 if (!L->getParentLoop())
189 TryConvertLoop(L);
190 }
191
192 return MadeChange;
193}
194
195// Return true if the search should stop, which will be when an inner loop is
196// converted and the parent loop doesn't support containing a hardware loop.
197bool HardwareLoops::TryConvertLoop(Loop *L) {
198 // Process nested loops first.
199 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
200 if (TryConvertLoop(*I))
201 return true; // Stop search.
202
Chen Zhengc5b918d2019-06-19 01:26:31 +0000203 HardwareLoopInfo HWLoopInfo(L);
Chen Zhengaa999522019-06-26 12:02:43 +0000204 if (!HWLoopInfo.canAnalyze(*LI))
205 return false;
206
207 if (TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo) ||
Sam Parkerc5ef5022019-06-07 07:35:30 +0000208 ForceHardwareLoops) {
209
210 // Allow overriding of the counter width and loop decrement value.
211 if (CounterBitWidth.getNumOccurrences())
212 HWLoopInfo.CountType =
213 IntegerType::get(M->getContext(), CounterBitWidth);
214
215 if (LoopDecrement.getNumOccurrences())
216 HWLoopInfo.LoopDecrement =
217 ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
218
219 MadeChange |= TryConvertLoop(HWLoopInfo);
220 return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
221 }
222
223 return false;
224}
225
Chen Zhengc5b918d2019-06-19 01:26:31 +0000226bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) {
Sam Parkerc5ef5022019-06-07 07:35:30 +0000227
Chen Zhengd9555732019-07-09 14:56:17 +0000228 LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: "
229 << *HWLoopInfo.L);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000230
Chen Zhengc5b918d2019-06-19 01:26:31 +0000231 if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop,
Chen Zhengd9555732019-07-09 14:56:17 +0000232 ForceHardwareLoopPHI,
233 ForceGuardLoopEntry))
Sam Parkerc5ef5022019-06-07 07:35:30 +0000234 return false;
235
Chen Zhengc5b918d2019-06-19 01:26:31 +0000236 assert(
237 (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) &&
238 "Hardware Loop must have set exit info.");
239
Chen Zhengd9555732019-07-09 14:56:17 +0000240 // Now start to converting...
Sam Parkerc5ef5022019-06-07 07:35:30 +0000241 HardwareLoop HWLoop(HWLoopInfo, *SE, *DL);
242 HWLoop.Create();
243 ++NumHWLoops;
244 return true;
245}
246
247void HardwareLoop::Create() {
248 LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
Chen Zhengd9555732019-07-09 14:56:17 +0000249
Sam Parker9a92be12019-06-28 07:38:16 +0000250 Value *LoopCountInit = InitLoopCount();
Chen Zhengd9555732019-07-09 14:56:17 +0000251
252 assert(LoopCountInit && "Hardware Loop must have a loop count");
Sam Parkerc5ef5022019-06-07 07:35:30 +0000253
Sam Parker9a92be12019-06-28 07:38:16 +0000254 InsertIterationSetup(LoopCountInit);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000255
256 if (UsePHICounter || ForceHardwareLoopPHI) {
257 Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
258 Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec);
259 LoopDec->setOperand(0, EltsRem);
260 UpdateBranch(LoopDec);
261 } else
262 InsertLoopDec();
263
264 // Run through the basic blocks of the loop and see if any of them have dead
265 // PHIs that can be removed.
266 for (auto I : L->blocks())
267 DeleteDeadPHIs(I);
268}
269
Sam Parker9a92be12019-06-28 07:38:16 +0000270static bool CanGenerateTest(Loop *L, Value *Count) {
271 BasicBlock *Preheader = L->getLoopPreheader();
272 if (!Preheader->getSinglePredecessor())
273 return false;
274
275 BasicBlock *Pred = Preheader->getSinglePredecessor();
276 if (!isa<BranchInst>(Pred->getTerminator()))
277 return false;
278
279 auto *BI = cast<BranchInst>(Pred->getTerminator());
280 if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition()))
281 return false;
282
283 // Check that the icmp is checking for equality of Count and zero and that
284 // a non-zero value results in entering the loop.
285 auto ICmp = cast<ICmpInst>(BI->getCondition());
Sam Parker98722692019-07-01 08:21:28 +0000286 LLVM_DEBUG(dbgs() << " - Found condition: " << *ICmp << "\n");
Sam Parker9a92be12019-06-28 07:38:16 +0000287 if (!ICmp->isEquality())
288 return false;
289
290 auto IsCompareZero = [](ICmpInst *ICmp, Value *Count, unsigned OpIdx) {
291 if (auto *Const = dyn_cast<ConstantInt>(ICmp->getOperand(OpIdx)))
292 return Const->isZero() && ICmp->getOperand(OpIdx ^ 1) == Count;
293 return false;
294 };
295
296 if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1))
297 return false;
298
299 unsigned SuccIdx = ICmp->getPredicate() == ICmpInst::ICMP_NE ? 0 : 1;
300 if (BI->getSuccessor(SuccIdx) != Preheader)
301 return false;
302
303 return true;
304}
305
306Value *HardwareLoop::InitLoopCount() {
307 LLVM_DEBUG(dbgs() << "HWLoops: Initialising loop counter value:\n");
308 // Can we replace a conditional branch with an intrinsic that sets the
309 // loop counter and tests that is not zero?
310
Sam Parkerc5ef5022019-06-07 07:35:30 +0000311 SCEVExpander SCEVE(SE, DL, "loopcnt");
Sam Parkerc5ef5022019-06-07 07:35:30 +0000312
Sam Parker9a92be12019-06-28 07:38:16 +0000313 // If we're trying to use the 'test and set' form of the intrinsic, we need
314 // to replace a conditional branch that is controlling entry to the loop. It
315 // is likely (guaranteed?) that the preheader has an unconditional branch to
316 // the loop header, so also check if it has a single predecessor.
317 if (SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
Chen Zhengd9555732019-07-09 14:56:17 +0000318 SE.getZero(ExitCount->getType())))
Sam Parker9a92be12019-06-28 07:38:16 +0000319 UseLoopGuard |= ForceGuardLoopEntry;
Chen Zhengd9555732019-07-09 14:56:17 +0000320 else
Sam Parker9a92be12019-06-28 07:38:16 +0000321 UseLoopGuard = false;
322
323 BasicBlock *BB = L->getLoopPreheader();
324 if (UseLoopGuard && BB->getSinglePredecessor() &&
Chen Zhengd9555732019-07-09 14:56:17 +0000325 cast<BranchInst>(BB->getTerminator())->isUnconditional()) {
326 LLVM_DEBUG(dbgs() << " - Attempting to use test.set counter.\n");
Sam Parker9a92be12019-06-28 07:38:16 +0000327 BB = BB->getSinglePredecessor();
Sam Parkerc5ef5022019-06-07 07:35:30 +0000328 }
329
330 Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
331 BB->getTerminator());
Sam Parker9a92be12019-06-28 07:38:16 +0000332
333 // FIXME: We've expanded Count where we hope to insert the counter setting
334 // intrinsic. But, in the case of the 'test and set' form, we may fallback to
335 // the just 'set' form and in which case the insertion block is most likely
336 // different. It means there will be instruction(s) in a block that possibly
337 // aren't needed. The isLoopEntryGuardedByCond is trying to avoid this issue,
338 // but it's doesn't appear to work in all cases.
339
340 UseLoopGuard = UseLoopGuard && CanGenerateTest(L, Count);
341 BeginBB = UseLoopGuard ? BB : L->getLoopPreheader();
342 LLVM_DEBUG(dbgs() << " - Loop Count: " << *Count << "\n"
343 << " - Expanded Count in " << BB->getName() << "\n"
344 << " - Will insert set counter intrinsic into: "
345 << BeginBB->getName() << "\n");
Sam Parkerc5ef5022019-06-07 07:35:30 +0000346 return Count;
347}
348
Sam Parker9a92be12019-06-28 07:38:16 +0000349void HardwareLoop::InsertIterationSetup(Value *LoopCountInit) {
350 IRBuilder<> Builder(BeginBB->getTerminator());
Sam Parkerc5ef5022019-06-07 07:35:30 +0000351 Type *Ty = LoopCountInit->getType();
Sam Parker9a92be12019-06-28 07:38:16 +0000352 Intrinsic::ID ID = UseLoopGuard ?
353 Intrinsic::test_set_loop_iterations : Intrinsic::set_loop_iterations;
354 Function *LoopIter = Intrinsic::getDeclaration(M, ID, Ty);
355 Value *SetCount = Builder.CreateCall(LoopIter, LoopCountInit);
356
357 // Use the return value of the intrinsic to control the entry of the loop.
358 if (UseLoopGuard) {
359 assert((isa<BranchInst>(BeginBB->getTerminator()) &&
360 cast<BranchInst>(BeginBB->getTerminator())->isConditional()) &&
361 "Expected conditional branch");
362 auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator());
363 LoopGuard->setCondition(SetCount);
364 if (LoopGuard->getSuccessor(0) != L->getLoopPreheader())
365 LoopGuard->swapSuccessors();
366 }
367 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop counter: "
368 << *SetCount << "\n");
Sam Parkerc5ef5022019-06-07 07:35:30 +0000369}
370
371void HardwareLoop::InsertLoopDec() {
372 IRBuilder<> CondBuilder(ExitBranch);
373
374 Function *DecFunc =
375 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
376 LoopDecrement->getType());
377 Value *Ops[] = { LoopDecrement };
378 Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
379 Value *OldCond = ExitBranch->getCondition();
380 ExitBranch->setCondition(NewCond);
381
382 // The false branch must exit the loop.
383 if (!L->contains(ExitBranch->getSuccessor(0)))
384 ExitBranch->swapSuccessors();
385
386 // The old condition may be dead now, and may have even created a dead PHI
387 // (the original induction variable).
388 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
389
390 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
391}
392
393Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
394 IRBuilder<> CondBuilder(ExitBranch);
395
396 Function *DecFunc =
397 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
398 { EltsRem->getType(), EltsRem->getType(),
399 LoopDecrement->getType()
400 });
401 Value *Ops[] = { EltsRem, LoopDecrement };
402 Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
403
404 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
405 return cast<Instruction>(Call);
406}
407
408PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
409 BasicBlock *Preheader = L->getLoopPreheader();
410 BasicBlock *Header = L->getHeader();
411 BasicBlock *Latch = ExitBranch->getParent();
412 IRBuilder<> Builder(Header->getFirstNonPHI());
413 PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
414 Index->addIncoming(NumElts, Preheader);
415 Index->addIncoming(EltsRem, Latch);
416 LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
417 return Index;
418}
419
420void HardwareLoop::UpdateBranch(Value *EltsRem) {
421 IRBuilder<> CondBuilder(ExitBranch);
422 Value *NewCond =
423 CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
424 Value *OldCond = ExitBranch->getCondition();
425 ExitBranch->setCondition(NewCond);
426
427 // The false branch must exit the loop.
428 if (!L->contains(ExitBranch->getSuccessor(0)))
429 ExitBranch->swapSuccessors();
430
431 // The old condition may be dead now, and may have even created a dead PHI
432 // (the original induction variable).
433 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
434}
435
436INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
437INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
438INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
439INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
440INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
441
442FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }