LLVM 22.0.0git
HardwareLoops.cpp
Go to the documentation of this file.
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
19#include "llvm/ADT/Statistic.h"
27#include "llvm/CodeGen/Passes.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/Constants.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Value.h"
35#include "llvm/Pass.h"
36#include "llvm/PassRegistry.h"
38#include "llvm/Support/Debug.h"
44
45#define DEBUG_TYPE "hardware-loops"
46
47#define HW_LOOPS_NAME "Hardware Loop Insertion"
48
49using namespace llvm;
50
51static cl::opt<bool>
52ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false),
53 cl::desc("Force hardware loops intrinsics to be inserted"));
54
55static cl::opt<bool>
57 "force-hardware-loop-phi", cl::Hidden, cl::init(false),
58 cl::desc("Force hardware loop counter to be updated through a phi"));
59
60static cl::opt<bool>
61ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false),
62 cl::desc("Force allowance of nested hardware loops"));
63
65LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1),
66 cl::desc("Set the loop decrement value"));
67
69CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32),
70 cl::desc("Set the loop counter bitwidth"));
71
72static cl::opt<bool>
74 "force-hardware-loop-guard", cl::Hidden, cl::init(false),
75 cl::desc("Force generation of loop guard intrinsic"));
76
77STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
78
79#ifndef NDEBUG
80static void debugHWLoopFailure(const StringRef DebugMsg,
81 Instruction *I) {
82 dbgs() << "HWLoops: " << DebugMsg;
83 if (I)
84 dbgs() << ' ' << *I;
85 else
86 dbgs() << '.';
87 dbgs() << '\n';
88}
89#endif
90
93 BasicBlock *CodeRegion = L->getHeader();
94 DebugLoc DL = L->getStartLoc();
95
96 if (I) {
97 CodeRegion = I->getParent();
98 // If there is no debug location attached to the instruction, revert back to
99 // using the loop's.
100 if (I->getDebugLoc())
101 DL = I->getDebugLoc();
102 }
103
104 OptimizationRemarkAnalysis R(DEBUG_TYPE, RemarkName, DL, CodeRegion);
105 R << "hardware-loop not created: ";
106 return R;
107}
108
109namespace {
110
111 void reportHWLoopFailure(const StringRef Msg, const StringRef ORETag,
112 OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I = nullptr) {
114 ORE->emit(createHWLoopAnalysis(ORETag, TheLoop, I) << Msg);
115 }
116
117 using TTI = TargetTransformInfo;
118
119 class HardwareLoopsLegacy : public FunctionPass {
120 public:
121 static char ID;
122
123 HardwareLoopsLegacy() : FunctionPass(ID) {
125 }
126
127 bool runOnFunction(Function &F) override;
128
129 void getAnalysisUsage(AnalysisUsage &AU) const override {
130 AU.addRequired<LoopInfoWrapperPass>();
131 AU.addPreserved<LoopInfoWrapperPass>();
132 AU.addRequired<DominatorTreeWrapperPass>();
133 AU.addPreserved<DominatorTreeWrapperPass>();
134 AU.addRequired<ScalarEvolutionWrapperPass>();
135 AU.addPreserved<ScalarEvolutionWrapperPass>();
136 AU.addRequired<AssumptionCacheTracker>();
137 AU.addRequired<TargetTransformInfoWrapperPass>();
138 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
139 AU.addPreserved<BranchProbabilityInfoWrapperPass>();
140 }
141 };
142
143 class HardwareLoopsImpl {
144 public:
145 HardwareLoopsImpl(ScalarEvolution &SE, LoopInfo &LI, bool PreserveLCSSA,
146 DominatorTree &DT, const TargetTransformInfo &TTI,
147 TargetLibraryInfo *TLI, AssumptionCache &AC,
148 OptimizationRemarkEmitter *ORE, HardwareLoopOptions &Opts)
149 : SE(SE), LI(LI), PreserveLCSSA(PreserveLCSSA), DT(DT), TTI(TTI),
150 TLI(TLI), AC(AC), ORE(ORE), Opts(Opts) {}
151
152 bool run(Function &F);
153
154 private:
155 // Try to convert the given Loop into a hardware loop.
156 bool TryConvertLoop(Loop *L, LLVMContext &Ctx);
157
158 // Given that the target believes the loop to be profitable, try to
159 // convert it.
160 bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo);
161
162 ScalarEvolution &SE;
163 LoopInfo &LI;
164 bool PreserveLCSSA;
165 DominatorTree &DT;
166 const TargetTransformInfo &TTI;
167 TargetLibraryInfo *TLI = nullptr;
168 AssumptionCache &AC;
169 OptimizationRemarkEmitter *ORE;
170 HardwareLoopOptions &Opts;
171 bool MadeChange = false;
172 };
173
174 class HardwareLoop {
175 // Expand the trip count scev into a value that we can use.
176 Value *InitLoopCount();
177
178 // Insert the set_loop_iteration intrinsic.
179 Value *InsertIterationSetup(Value *LoopCountInit);
180
181 // Insert the loop_decrement intrinsic.
182 void InsertLoopDec();
183
184 // Insert the loop_decrement_reg intrinsic.
185 Instruction *InsertLoopRegDec(Value *EltsRem);
186
187 // If the target requires the counter value to be updated in the loop,
188 // insert a phi to hold the value. The intended purpose is for use by
189 // loop_decrement_reg.
190 PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
191
192 // Create a new cmp, that checks the returned value of loop_decrement*,
193 // and update the exit branch to use it.
194 void UpdateBranch(Value *EltsRem);
195
196 public:
197 HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE,
198 OptimizationRemarkEmitter *ORE, HardwareLoopOptions &Opts)
199 : SE(SE), ORE(ORE), Opts(Opts), L(Info.L),
200 M(L->getHeader()->getModule()), ExitCount(Info.ExitCount),
201 CountType(Info.CountType), ExitBranch(Info.ExitBranch),
202 LoopDecrement(Info.LoopDecrement), UsePHICounter(Info.CounterInReg),
203 UseLoopGuard(Info.PerformEntryTest) {}
204
205 void Create();
206
207 private:
208 ScalarEvolution &SE;
209 OptimizationRemarkEmitter *ORE = nullptr;
210 HardwareLoopOptions &Opts;
211 Loop *L = nullptr;
212 Module *M = nullptr;
213 const SCEV *ExitCount = nullptr;
214 Type *CountType = nullptr;
215 BranchInst *ExitBranch = nullptr;
216 Value *LoopDecrement = nullptr;
217 bool UsePHICounter = false;
218 bool UseLoopGuard = false;
219 BasicBlock *BeginBB = nullptr;
220 };
221}
222
223char HardwareLoopsLegacy::ID = 0;
224
225bool HardwareLoopsLegacy::runOnFunction(Function &F) {
226 if (skipFunction(F))
227 return false;
228
229 LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
230
231 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
232 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
233 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
234 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
235 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
236 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
237 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
238 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
239 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
240
241 HardwareLoopOptions Opts;
250 if (LoopDecrement.getNumOccurrences())
252 if (CounterBitWidth.getNumOccurrences())
254
255 HardwareLoopsImpl Impl(SE, LI, PreserveLCSSA, DT, TTI, TLI, AC, ORE, Opts);
256 return Impl.run(F);
257}
258
261 auto &LI = AM.getResult<LoopAnalysis>(F);
262 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
263 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
264 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
265 auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
266 auto &AC = AM.getResult<AssumptionAnalysis>(F);
268
269 HardwareLoopsImpl Impl(SE, LI, true, DT, TTI, TLI, AC, ORE, Opts);
270 bool Changed = Impl.run(F);
271 if (!Changed)
272 return PreservedAnalyses::all();
273
279 return PA;
280}
281
282bool HardwareLoopsImpl::run(Function &F) {
283 LLVMContext &Ctx = F.getContext();
284 for (Loop *L : LI)
285 if (L->isOutermost())
286 TryConvertLoop(L, Ctx);
287 return MadeChange;
288}
289
290// Return true if the search should stop, which will be when an inner loop is
291// converted and the parent loop doesn't support containing a hardware loop.
292bool HardwareLoopsImpl::TryConvertLoop(Loop *L, LLVMContext &Ctx) {
293 // Process nested loops first.
294 bool AnyChanged = false;
295 for (Loop *SL : *L)
296 AnyChanged |= TryConvertLoop(SL, Ctx);
297 if (AnyChanged) {
298 reportHWLoopFailure("nested hardware-loops not supported", "HWLoopNested",
299 ORE, L);
300 return true; // Stop search.
301 }
302
303 LLVM_DEBUG(dbgs() << "HWLoops: Loop " << L->getHeader()->getName() << "\n");
304
305 HardwareLoopInfo HWLoopInfo(L);
306 if (!HWLoopInfo.canAnalyze(LI)) {
307 reportHWLoopFailure("cannot analyze loop, irreducible control flow",
308 "HWLoopCannotAnalyze", ORE, L);
309 return false;
310 }
311
312 if (!Opts.Force &&
313 !TTI.isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) {
314 reportHWLoopFailure("it's not profitable to create a hardware-loop",
315 "HWLoopNotProfitable", ORE, L);
316 return false;
317 }
318
319 // Allow overriding of the counter width and loop decrement value.
320 if (Opts.Bitwidth.has_value()) {
321 HWLoopInfo.CountType = IntegerType::get(Ctx, Opts.Bitwidth.value());
322 }
323
324 if (Opts.Decrement.has_value())
325 HWLoopInfo.LoopDecrement =
326 ConstantInt::get(HWLoopInfo.CountType, Opts.Decrement.value());
327
328 MadeChange |= TryConvertLoop(HWLoopInfo);
329 return MadeChange && (!HWLoopInfo.IsNestingLegal && !Opts.ForceNested);
330}
331
332bool HardwareLoopsImpl::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) {
333
334 Loop *L = HWLoopInfo.L;
335 LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
336
337 if (!HWLoopInfo.isHardwareLoopCandidate(SE, LI, DT, Opts.getForceNested(),
338 Opts.getForcePhi())) {
339 // TODO: there can be many reasons a loop is not considered a
340 // candidate, so we should let isHardwareLoopCandidate fill in the
341 // reason and then report a better message here.
342 reportHWLoopFailure("loop is not a candidate", "HWLoopNoCandidate", ORE, L);
343 return false;
344 }
345
346 assert(
347 (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) &&
348 "Hardware Loop must have set exit info.");
349
350 BasicBlock *Preheader = L->getLoopPreheader();
351
352 // If we don't have a preheader, then insert one.
353 if (!Preheader)
354 Preheader = InsertPreheaderForLoop(L, &DT, &LI, nullptr, PreserveLCSSA);
355 if (!Preheader)
356 return false;
357
358 HardwareLoop HWLoop(HWLoopInfo, SE, ORE, Opts);
359 HWLoop.Create();
360 ++NumHWLoops;
361 return true;
362}
363
364void HardwareLoop::Create() {
365 LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
366
367 Value *LoopCountInit = InitLoopCount();
368 if (!LoopCountInit) {
369 reportHWLoopFailure("could not safely create a loop count expression",
370 "HWLoopNotSafe", ORE, L);
371 return;
372 }
373
374 Value *Setup = InsertIterationSetup(LoopCountInit);
375
376 if (UsePHICounter || Opts.ForcePhi) {
377 Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
378 Value *EltsRem = InsertPHICounter(Setup, LoopDec);
379 LoopDec->setOperand(0, EltsRem);
380 UpdateBranch(LoopDec);
381 } else
382 InsertLoopDec();
383
384 // Run through the basic blocks of the loop and see if any of them have dead
385 // PHIs that can be removed.
386 for (auto *I : L->blocks())
388}
389
390static bool CanGenerateTest(Loop *L, Value *Count) {
391 BasicBlock *Preheader = L->getLoopPreheader();
392 if (!Preheader->getSinglePredecessor())
393 return false;
394
395 BasicBlock *Pred = Preheader->getSinglePredecessor();
396 if (!isa<BranchInst>(Pred->getTerminator()))
397 return false;
398
399 auto *BI = cast<BranchInst>(Pred->getTerminator());
400 if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition()))
401 return false;
402
403 // Check that the icmp is checking for equality of Count and zero and that
404 // a non-zero value results in entering the loop.
405 auto ICmp = cast<ICmpInst>(BI->getCondition());
406 LLVM_DEBUG(dbgs() << " - Found condition: " << *ICmp << "\n");
407 if (!ICmp->isEquality())
408 return false;
409
410 auto IsCompareZero = [](ICmpInst *ICmp, Value *Count, unsigned OpIdx) {
411 if (auto *Const = dyn_cast<ConstantInt>(ICmp->getOperand(OpIdx)))
412 return Const->isZero() && ICmp->getOperand(OpIdx ^ 1) == Count;
413 return false;
414 };
415
416 // Check if Count is a zext.
417 Value *CountBefZext =
418 isa<ZExtInst>(Count) ? cast<ZExtInst>(Count)->getOperand(0) : nullptr;
419
420 if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1) &&
421 !IsCompareZero(ICmp, CountBefZext, 0) &&
422 !IsCompareZero(ICmp, CountBefZext, 1))
423 return false;
424
425 unsigned SuccIdx = ICmp->getPredicate() == ICmpInst::ICMP_NE ? 0 : 1;
426 if (BI->getSuccessor(SuccIdx) != Preheader)
427 return false;
428
429 return true;
430}
431
432Value *HardwareLoop::InitLoopCount() {
433 LLVM_DEBUG(dbgs() << "HWLoops: Initialising loop counter value:\n");
434 // Can we replace a conditional branch with an intrinsic that sets the
435 // loop counter and tests that is not zero?
436
437 SCEVExpander SCEVE(SE, "loopcnt");
438 if (!ExitCount->getType()->isPointerTy() &&
439 ExitCount->getType() != CountType)
440 ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
441
442 ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
443
444 // If we're trying to use the 'test and set' form of the intrinsic, we need
445 // to replace a conditional branch that is controlling entry to the loop. It
446 // is likely (guaranteed?) that the preheader has an unconditional branch to
447 // the loop header, so also check if it has a single predecessor.
448 if (SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
449 SE.getZero(ExitCount->getType()))) {
450 LLVM_DEBUG(dbgs() << " - Attempting to use test.set counter.\n");
451 if (Opts.ForceGuard)
452 UseLoopGuard = true;
453 } else
454 UseLoopGuard = false;
455
456 BasicBlock *BB = L->getLoopPreheader();
457 if (UseLoopGuard && BB->getSinglePredecessor() &&
458 cast<BranchInst>(BB->getTerminator())->isUnconditional()) {
459 BasicBlock *Predecessor = BB->getSinglePredecessor();
460 // If it's not safe to create a while loop then don't force it and create a
461 // do-while loop instead
462 if (!SCEVE.isSafeToExpandAt(ExitCount, Predecessor->getTerminator()))
463 UseLoopGuard = false;
464 else
465 BB = Predecessor;
466 }
467
468 if (!SCEVE.isSafeToExpandAt(ExitCount, BB->getTerminator())) {
469 LLVM_DEBUG(dbgs() << "- Bailing, unsafe to expand ExitCount "
470 << *ExitCount << "\n");
471 return nullptr;
472 }
473
474 Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
475 BB->getTerminator());
476
477 // FIXME: We've expanded Count where we hope to insert the counter setting
478 // intrinsic. But, in the case of the 'test and set' form, we may fallback to
479 // the just 'set' form and in which case the insertion block is most likely
480 // different. It means there will be instruction(s) in a block that possibly
481 // aren't needed. The isLoopEntryGuardedByCond is trying to avoid this issue,
482 // but it's doesn't appear to work in all cases.
483
484 UseLoopGuard = UseLoopGuard && CanGenerateTest(L, Count);
485 BeginBB = UseLoopGuard ? BB : L->getLoopPreheader();
486 LLVM_DEBUG(dbgs() << " - Loop Count: " << *Count << "\n"
487 << " - Expanded Count in " << BB->getName() << "\n"
488 << " - Will insert set counter intrinsic into: "
489 << BeginBB->getName() << "\n");
490 return Count;
491}
492
493Value* HardwareLoop::InsertIterationSetup(Value *LoopCountInit) {
494 IRBuilder<> Builder(BeginBB->getTerminator());
495 if (BeginBB->getParent()->getAttributes().hasFnAttr(Attribute::StrictFP))
496 Builder.setIsFPConstrained(true);
497 Type *Ty = LoopCountInit->getType();
498 bool UsePhi = UsePHICounter || Opts.ForcePhi;
499 Intrinsic::ID ID = UseLoopGuard
500 ? (UsePhi ? Intrinsic::test_start_loop_iterations
501 : Intrinsic::test_set_loop_iterations)
502 : (UsePhi ? Intrinsic::start_loop_iterations
503 : Intrinsic::set_loop_iterations);
504 Value *LoopSetup = Builder.CreateIntrinsic(ID, Ty, LoopCountInit);
505
506 // Use the return value of the intrinsic to control the entry of the loop.
507 if (UseLoopGuard) {
508 assert((isa<BranchInst>(BeginBB->getTerminator()) &&
509 cast<BranchInst>(BeginBB->getTerminator())->isConditional()) &&
510 "Expected conditional branch");
511
512 Value *SetCount =
513 UsePhi ? Builder.CreateExtractValue(LoopSetup, 1) : LoopSetup;
514 auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator());
515 LoopGuard->setCondition(SetCount);
516 if (LoopGuard->getSuccessor(0) != L->getLoopPreheader())
517 LoopGuard->swapSuccessors();
518 }
519 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop counter: " << *LoopSetup
520 << "\n");
521 if (UsePhi && UseLoopGuard)
522 LoopSetup = Builder.CreateExtractValue(LoopSetup, 0);
523 return !UsePhi ? LoopCountInit : LoopSetup;
524}
525
526void HardwareLoop::InsertLoopDec() {
527 IRBuilder<> CondBuilder(ExitBranch);
528 if (ExitBranch->getParent()->getParent()->getAttributes().hasFnAttr(
529 Attribute::StrictFP))
530 CondBuilder.setIsFPConstrained(true);
531
532 Value *Ops[] = { LoopDecrement };
533 Value *NewCond = CondBuilder.CreateIntrinsic(Intrinsic::loop_decrement,
534 LoopDecrement->getType(), Ops);
535 Value *OldCond = ExitBranch->getCondition();
536 ExitBranch->setCondition(NewCond);
537
538 // The false branch must exit the loop.
539 if (!L->contains(ExitBranch->getSuccessor(0)))
540 ExitBranch->swapSuccessors();
541
542 // The old condition may be dead now, and may have even created a dead PHI
543 // (the original induction variable).
545
546 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
547}
548
549Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
550 IRBuilder<> CondBuilder(ExitBranch);
551 if (ExitBranch->getParent()->getParent()->getAttributes().hasFnAttr(
552 Attribute::StrictFP))
553 CondBuilder.setIsFPConstrained(true);
554
555 Value *Ops[] = { EltsRem, LoopDecrement };
556 Value *Call = CondBuilder.CreateIntrinsic(Intrinsic::loop_decrement_reg,
557 {EltsRem->getType()}, Ops);
558
559 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
560 return cast<Instruction>(Call);
561}
562
563PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
564 BasicBlock *Preheader = L->getLoopPreheader();
565 BasicBlock *Header = L->getHeader();
566 BasicBlock *Latch = ExitBranch->getParent();
567 IRBuilder<> Builder(Header, Header->getFirstNonPHIIt());
568 PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
569 Index->addIncoming(NumElts, Preheader);
570 Index->addIncoming(EltsRem, Latch);
571 LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
572 return Index;
573}
574
575void HardwareLoop::UpdateBranch(Value *EltsRem) {
576 IRBuilder<> CondBuilder(ExitBranch);
577 Value *NewCond =
578 CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
579 Value *OldCond = ExitBranch->getCondition();
580 ExitBranch->setCondition(NewCond);
581
582 // The false branch must exit the loop.
583 if (!L->contains(ExitBranch->getSuccessor(0)))
584 ExitBranch->swapSuccessors();
585
586 // The old condition may be dead now, and may have even created a dead PHI
587 // (the original induction variable).
589}
590
591INITIALIZE_PASS_BEGIN(HardwareLoopsLegacy, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
592INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
593INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
594INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
595INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
596INITIALIZE_PASS_END(HardwareLoopsLegacy, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
597
598FunctionPass *llvm::createHardwareLoopsLegacyPass() { return new HardwareLoopsLegacy(); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
static cl::opt< bool > ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false), cl::desc("Force allowance of nested hardware loops"))
#define HW_LOOPS_NAME
static cl::opt< unsigned > CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32), cl::desc("Set the loop counter bitwidth"))
static OptimizationRemarkAnalysis createHWLoopAnalysis(StringRef RemarkName, Loop *L, Instruction *I)
static cl::opt< bool > ForceGuardLoopEntry("force-hardware-loop-guard", cl::Hidden, cl::init(false), cl::desc("Force generation of loop guard intrinsic"))
static void debugHWLoopFailure(const StringRef DebugMsg, Instruction *I)
static cl::opt< unsigned > LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1), cl::desc("Set the loop decrement value"))
static cl::opt< bool > ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false), cl::desc("Force hardware loops intrinsics to be inserted"))
static bool CanGenerateTest(Loop *L, Value *Count)
static cl::opt< bool > ForceHardwareLoopPHI("force-hardware-loop-phi", cl::Hidden, cl::init(false), cl::desc("Force hardware loop counter to be updated through a phi"))
Defines an IR pass for the creation of hardware loops.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
MachineInstr unsigned OpIdx
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
This pass exposes codegen information to IR-level passes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
A function analysis which provides an AssumptionCache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
void setCondition(Value *V)
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
BasicBlock * getSuccessor(unsigned i) const
Value * getCondition() const
Analysis pass which computes BranchProbabilityInfo.
@ ICMP_NE
not equal
Definition InstrTypes.h:698
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:765
A debug info location.
Definition DebugLoc.h:123
Analysis pass which computes a DominatorTree.
Definition Dominators.h:283
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:352
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This instruction compares its operands according to the predicate given to the constructor.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:318
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:569
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, AssumptionCache &AC, TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo) const
Query the target whether it would be profitable to convert the given loop into a hardware loop.
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:237
Value * getOperand(unsigned i) const
Definition User.h:232
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
int getNumOccurrences() const
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:533
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI char & LCSSAID
Definition LCSSA.cpp:526
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Examine each PHI in the given block and delete it if it is dead.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void initializeHardwareLoopsLegacyPass(PassRegistry &)
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI FunctionPass * createHardwareLoopsLegacyPass()
Create Hardware Loop pass.
LLVM_ABI bool isHardwareLoopCandidate(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, bool ForceNestedLoop=false, bool ForceHardwareLoopPHI=false)
std::optional< bool > Force
HardwareLoopOptions & setForceNested(bool Force)
std::optional< bool > ForceGuard
std::optional< unsigned > Decrement
HardwareLoopOptions & setDecrement(unsigned Count)
HardwareLoopOptions & setForceGuard(bool Force)
HardwareLoopOptions & setForce(bool Force)
HardwareLoopOptions & setCounterBitwidth(unsigned Width)
std::optional< unsigned > Bitwidth
HardwareLoopOptions & setForcePhi(bool Force)
std::optional< bool > ForcePhi
std::optional< bool > ForceNested