HardwareLoops.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/AssumptionCache.h"
  19. #include "llvm/Analysis/LoopInfo.h"
  20. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  21. #include "llvm/Analysis/ScalarEvolution.h"
  22. #include "llvm/Analysis/TargetLibraryInfo.h"
  23. #include "llvm/Analysis/TargetTransformInfo.h"
  24. #include "llvm/CodeGen/Passes.h"
  25. #include "llvm/CodeGen/TargetPassConfig.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/IRBuilder.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/Value.h"
  34. #include "llvm/InitializePasses.h"
  35. #include "llvm/Pass.h"
  36. #include "llvm/PassRegistry.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Transforms/Scalar.h"
  40. #include "llvm/Transforms/Utils.h"
  41. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  42. #include "llvm/Transforms/Utils/Local.h"
  43. #include "llvm/Transforms/Utils/LoopUtils.h"
  44. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  45. #define DEBUG_TYPE "hardware-loops"
  46. #define HW_LOOPS_NAME "Hardware Loop Insertion"
  47. using namespace llvm;
  48. static cl::opt<bool>
  49. ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false),
  50. cl::desc("Force hardware loops intrinsics to be inserted"));
  51. static cl::opt<bool>
  52. ForceHardwareLoopPHI(
  53. "force-hardware-loop-phi", cl::Hidden, cl::init(false),
  54. cl::desc("Force hardware loop counter to be updated through a phi"));
  55. static cl::opt<bool>
  56. ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false),
  57. cl::desc("Force allowance of nested hardware loops"));
  58. static cl::opt<unsigned>
  59. LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1),
  60. cl::desc("Set the loop decrement value"));
  61. static cl::opt<unsigned>
  62. CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32),
  63. cl::desc("Set the loop counter bitwidth"));
  64. static cl::opt<bool>
  65. ForceGuardLoopEntry(
  66. "force-hardware-loop-guard", cl::Hidden, cl::init(false),
  67. cl::desc("Force generation of loop guard intrinsic"));
  68. STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
  69. #ifndef NDEBUG
  70. static void debugHWLoopFailure(const StringRef DebugMsg,
  71. Instruction *I) {
  72. dbgs() << "HWLoops: " << DebugMsg;
  73. if (I)
  74. dbgs() << ' ' << *I;
  75. else
  76. dbgs() << '.';
  77. dbgs() << '\n';
  78. }
  79. #endif
  80. static OptimizationRemarkAnalysis
  81. createHWLoopAnalysis(StringRef RemarkName, Loop *L, Instruction *I) {
  82. Value *CodeRegion = L->getHeader();
  83. DebugLoc DL = L->getStartLoc();
  84. if (I) {
  85. CodeRegion = I->getParent();
  86. // If there is no debug location attached to the instruction, revert back to
  87. // using the loop's.
  88. if (I->getDebugLoc())
  89. DL = I->getDebugLoc();
  90. }
  91. OptimizationRemarkAnalysis R(DEBUG_TYPE, RemarkName, DL, CodeRegion);
  92. R << "hardware-loop not created: ";
  93. return R;
  94. }
  95. namespace {
  96. void reportHWLoopFailure(const StringRef Msg, const StringRef ORETag,
  97. OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I = nullptr) {
  98. LLVM_DEBUG(debugHWLoopFailure(Msg, I));
  99. ORE->emit(createHWLoopAnalysis(ORETag, TheLoop, I) << Msg);
  100. }
  101. using TTI = TargetTransformInfo;
  102. class HardwareLoops : public FunctionPass {
  103. public:
  104. static char ID;
  105. HardwareLoops() : FunctionPass(ID) {
  106. initializeHardwareLoopsPass(*PassRegistry::getPassRegistry());
  107. }
  108. bool runOnFunction(Function &F) override;
  109. void getAnalysisUsage(AnalysisUsage &AU) const override {
  110. AU.addRequired<LoopInfoWrapperPass>();
  111. AU.addPreserved<LoopInfoWrapperPass>();
  112. AU.addRequired<DominatorTreeWrapperPass>();
  113. AU.addPreserved<DominatorTreeWrapperPass>();
  114. AU.addRequired<ScalarEvolutionWrapperPass>();
  115. AU.addRequired<AssumptionCacheTracker>();
  116. AU.addRequired<TargetTransformInfoWrapperPass>();
  117. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  118. }
  119. // Try to convert the given Loop into a hardware loop.
  120. bool TryConvertLoop(Loop *L);
  121. // Given that the target believes the loop to be profitable, try to
  122. // convert it.
  123. bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo);
  124. private:
  125. ScalarEvolution *SE = nullptr;
  126. LoopInfo *LI = nullptr;
  127. const DataLayout *DL = nullptr;
  128. OptimizationRemarkEmitter *ORE = nullptr;
  129. const TargetTransformInfo *TTI = nullptr;
  130. DominatorTree *DT = nullptr;
  131. bool PreserveLCSSA = false;
  132. AssumptionCache *AC = nullptr;
  133. TargetLibraryInfo *LibInfo = nullptr;
  134. Module *M = nullptr;
  135. bool MadeChange = false;
  136. };
  137. class HardwareLoop {
  138. // Expand the trip count scev into a value that we can use.
  139. Value *InitLoopCount();
  140. // Insert the set_loop_iteration intrinsic.
  141. Value *InsertIterationSetup(Value *LoopCountInit);
  142. // Insert the loop_decrement intrinsic.
  143. void InsertLoopDec();
  144. // Insert the loop_decrement_reg intrinsic.
  145. Instruction *InsertLoopRegDec(Value *EltsRem);
  146. // If the target requires the counter value to be updated in the loop,
  147. // insert a phi to hold the value. The intended purpose is for use by
  148. // loop_decrement_reg.
  149. PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
  150. // Create a new cmp, that checks the returned value of loop_decrement*,
  151. // and update the exit branch to use it.
  152. void UpdateBranch(Value *EltsRem);
  153. public:
  154. HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE,
  155. const DataLayout &DL,
  156. OptimizationRemarkEmitter *ORE) :
  157. SE(SE), DL(DL), ORE(ORE), L(Info.L), M(L->getHeader()->getModule()),
  158. ExitCount(Info.ExitCount),
  159. CountType(Info.CountType),
  160. ExitBranch(Info.ExitBranch),
  161. LoopDecrement(Info.LoopDecrement),
  162. UsePHICounter(Info.CounterInReg),
  163. UseLoopGuard(Info.PerformEntryTest) { }
  164. void Create();
  165. private:
  166. ScalarEvolution &SE;
  167. const DataLayout &DL;
  168. OptimizationRemarkEmitter *ORE = nullptr;
  169. Loop *L = nullptr;
  170. Module *M = nullptr;
  171. const SCEV *ExitCount = nullptr;
  172. Type *CountType = nullptr;
  173. BranchInst *ExitBranch = nullptr;
  174. Value *LoopDecrement = nullptr;
  175. bool UsePHICounter = false;
  176. bool UseLoopGuard = false;
  177. BasicBlock *BeginBB = nullptr;
  178. };
  179. }
  180. char HardwareLoops::ID = 0;
  181. bool HardwareLoops::runOnFunction(Function &F) {
  182. if (skipFunction(F))
  183. return false;
  184. LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
  185. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  186. SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  187. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  188. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  189. DL = &F.getParent()->getDataLayout();
  190. ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  191. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  192. LibInfo = TLIP ? &TLIP->getTLI(F) : nullptr;
  193. PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
  194. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  195. M = F.getParent();
  196. for (Loop *L : *LI)
  197. if (L->isOutermost())
  198. TryConvertLoop(L);
  199. return MadeChange;
  200. }
  201. // Return true if the search should stop, which will be when an inner loop is
  202. // converted and the parent loop doesn't support containing a hardware loop.
  203. bool HardwareLoops::TryConvertLoop(Loop *L) {
  204. // Process nested loops first.
  205. bool AnyChanged = false;
  206. for (Loop *SL : *L)
  207. AnyChanged |= TryConvertLoop(SL);
  208. if (AnyChanged) {
  209. reportHWLoopFailure("nested hardware-loops not supported", "HWLoopNested",
  210. ORE, L);
  211. return true; // Stop search.
  212. }
  213. LLVM_DEBUG(dbgs() << "HWLoops: Loop " << L->getHeader()->getName() << "\n");
  214. HardwareLoopInfo HWLoopInfo(L);
  215. if (!HWLoopInfo.canAnalyze(*LI)) {
  216. reportHWLoopFailure("cannot analyze loop, irreducible control flow",
  217. "HWLoopCannotAnalyze", ORE, L);
  218. return false;
  219. }
  220. if (!ForceHardwareLoops &&
  221. !TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo)) {
  222. reportHWLoopFailure("it's not profitable to create a hardware-loop",
  223. "HWLoopNotProfitable", ORE, L);
  224. return false;
  225. }
  226. // Allow overriding of the counter width and loop decrement value.
  227. if (CounterBitWidth.getNumOccurrences())
  228. HWLoopInfo.CountType =
  229. IntegerType::get(M->getContext(), CounterBitWidth);
  230. if (LoopDecrement.getNumOccurrences())
  231. HWLoopInfo.LoopDecrement =
  232. ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
  233. MadeChange |= TryConvertLoop(HWLoopInfo);
  234. return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
  235. }
  236. bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) {
  237. Loop *L = HWLoopInfo.L;
  238. LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
  239. if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop,
  240. ForceHardwareLoopPHI)) {
  241. // TODO: there can be many reasons a loop is not considered a
  242. // candidate, so we should let isHardwareLoopCandidate fill in the
  243. // reason and then report a better message here.
  244. reportHWLoopFailure("loop is not a candidate", "HWLoopNoCandidate", ORE, L);
  245. return false;
  246. }
  247. assert(
  248. (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) &&
  249. "Hardware Loop must have set exit info.");
  250. BasicBlock *Preheader = L->getLoopPreheader();
  251. // If we don't have a preheader, then insert one.
  252. if (!Preheader)
  253. Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
  254. if (!Preheader)
  255. return false;
  256. HardwareLoop HWLoop(HWLoopInfo, *SE, *DL, ORE);
  257. HWLoop.Create();
  258. ++NumHWLoops;
  259. return true;
  260. }
  261. void HardwareLoop::Create() {
  262. LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
  263. Value *LoopCountInit = InitLoopCount();
  264. if (!LoopCountInit) {
  265. reportHWLoopFailure("could not safely create a loop count expression",
  266. "HWLoopNotSafe", ORE, L);
  267. return;
  268. }
  269. Value *Setup = InsertIterationSetup(LoopCountInit);
  270. if (UsePHICounter || ForceHardwareLoopPHI) {
  271. Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
  272. Value *EltsRem = InsertPHICounter(Setup, LoopDec);
  273. LoopDec->setOperand(0, EltsRem);
  274. UpdateBranch(LoopDec);
  275. } else
  276. InsertLoopDec();
  277. // Run through the basic blocks of the loop and see if any of them have dead
  278. // PHIs that can be removed.
  279. for (auto I : L->blocks())
  280. DeleteDeadPHIs(I);
  281. }
  282. static bool CanGenerateTest(Loop *L, Value *Count) {
  283. BasicBlock *Preheader = L->getLoopPreheader();
  284. if (!Preheader->getSinglePredecessor())
  285. return false;
  286. BasicBlock *Pred = Preheader->getSinglePredecessor();
  287. if (!isa<BranchInst>(Pred->getTerminator()))
  288. return false;
  289. auto *BI = cast<BranchInst>(Pred->getTerminator());
  290. if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition()))
  291. return false;
  292. // Check that the icmp is checking for equality of Count and zero and that
  293. // a non-zero value results in entering the loop.
  294. auto ICmp = cast<ICmpInst>(BI->getCondition());
  295. LLVM_DEBUG(dbgs() << " - Found condition: " << *ICmp << "\n");
  296. if (!ICmp->isEquality())
  297. return false;
  298. auto IsCompareZero = [](ICmpInst *ICmp, Value *Count, unsigned OpIdx) {
  299. if (auto *Const = dyn_cast<ConstantInt>(ICmp->getOperand(OpIdx)))
  300. return Const->isZero() && ICmp->getOperand(OpIdx ^ 1) == Count;
  301. return false;
  302. };
  303. // Check if Count is a zext.
  304. Value *CountBefZext =
  305. isa<ZExtInst>(Count) ? cast<ZExtInst>(Count)->getOperand(0) : nullptr;
  306. if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1) &&
  307. !IsCompareZero(ICmp, CountBefZext, 0) &&
  308. !IsCompareZero(ICmp, CountBefZext, 1))
  309. return false;
  310. unsigned SuccIdx = ICmp->getPredicate() == ICmpInst::ICMP_NE ? 0 : 1;
  311. if (BI->getSuccessor(SuccIdx) != Preheader)
  312. return false;
  313. return true;
  314. }
  315. Value *HardwareLoop::InitLoopCount() {
  316. LLVM_DEBUG(dbgs() << "HWLoops: Initialising loop counter value:\n");
  317. // Can we replace a conditional branch with an intrinsic that sets the
  318. // loop counter and tests that is not zero?
  319. SCEVExpander SCEVE(SE, DL, "loopcnt");
  320. if (!ExitCount->getType()->isPointerTy() &&
  321. ExitCount->getType() != CountType)
  322. ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
  323. ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
  324. // If we're trying to use the 'test and set' form of the intrinsic, we need
  325. // to replace a conditional branch that is controlling entry to the loop. It
  326. // is likely (guaranteed?) that the preheader has an unconditional branch to
  327. // the loop header, so also check if it has a single predecessor.
  328. if (SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
  329. SE.getZero(ExitCount->getType()))) {
  330. LLVM_DEBUG(dbgs() << " - Attempting to use test.set counter.\n");
  331. UseLoopGuard |= ForceGuardLoopEntry;
  332. } else
  333. UseLoopGuard = false;
  334. BasicBlock *BB = L->getLoopPreheader();
  335. if (UseLoopGuard && BB->getSinglePredecessor() &&
  336. cast<BranchInst>(BB->getTerminator())->isUnconditional()) {
  337. BasicBlock *Predecessor = BB->getSinglePredecessor();
  338. // If it's not safe to create a while loop then don't force it and create a
  339. // do-while loop instead
  340. if (!isSafeToExpandAt(ExitCount, Predecessor->getTerminator(), SE))
  341. UseLoopGuard = false;
  342. else
  343. BB = Predecessor;
  344. }
  345. if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) {
  346. LLVM_DEBUG(dbgs() << "- Bailing, unsafe to expand ExitCount "
  347. << *ExitCount << "\n");
  348. return nullptr;
  349. }
  350. Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
  351. BB->getTerminator());
  352. // FIXME: We've expanded Count where we hope to insert the counter setting
  353. // intrinsic. But, in the case of the 'test and set' form, we may fallback to
  354. // the just 'set' form and in which case the insertion block is most likely
  355. // different. It means there will be instruction(s) in a block that possibly
  356. // aren't needed. The isLoopEntryGuardedByCond is trying to avoid this issue,
  357. // but it's doesn't appear to work in all cases.
  358. UseLoopGuard = UseLoopGuard && CanGenerateTest(L, Count);
  359. BeginBB = UseLoopGuard ? BB : L->getLoopPreheader();
  360. LLVM_DEBUG(dbgs() << " - Loop Count: " << *Count << "\n"
  361. << " - Expanded Count in " << BB->getName() << "\n"
  362. << " - Will insert set counter intrinsic into: "
  363. << BeginBB->getName() << "\n");
  364. return Count;
  365. }
  366. Value* HardwareLoop::InsertIterationSetup(Value *LoopCountInit) {
  367. IRBuilder<> Builder(BeginBB->getTerminator());
  368. Type *Ty = LoopCountInit->getType();
  369. bool UsePhi = UsePHICounter || ForceHardwareLoopPHI;
  370. Intrinsic::ID ID = UseLoopGuard
  371. ? (UsePhi ? Intrinsic::test_start_loop_iterations
  372. : Intrinsic::test_set_loop_iterations)
  373. : (UsePhi ? Intrinsic::start_loop_iterations
  374. : Intrinsic::set_loop_iterations);
  375. Function *LoopIter = Intrinsic::getDeclaration(M, ID, Ty);
  376. Value *LoopSetup = Builder.CreateCall(LoopIter, LoopCountInit);
  377. // Use the return value of the intrinsic to control the entry of the loop.
  378. if (UseLoopGuard) {
  379. assert((isa<BranchInst>(BeginBB->getTerminator()) &&
  380. cast<BranchInst>(BeginBB->getTerminator())->isConditional()) &&
  381. "Expected conditional branch");
  382. Value *SetCount =
  383. UsePhi ? Builder.CreateExtractValue(LoopSetup, 1) : LoopSetup;
  384. auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator());
  385. LoopGuard->setCondition(SetCount);
  386. if (LoopGuard->getSuccessor(0) != L->getLoopPreheader())
  387. LoopGuard->swapSuccessors();
  388. }
  389. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop counter: " << *LoopSetup
  390. << "\n");
  391. if (UsePhi && UseLoopGuard)
  392. LoopSetup = Builder.CreateExtractValue(LoopSetup, 0);
  393. return !UsePhi ? LoopCountInit : LoopSetup;
  394. }
  395. void HardwareLoop::InsertLoopDec() {
  396. IRBuilder<> CondBuilder(ExitBranch);
  397. Function *DecFunc =
  398. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
  399. LoopDecrement->getType());
  400. Value *Ops[] = { LoopDecrement };
  401. Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
  402. Value *OldCond = ExitBranch->getCondition();
  403. ExitBranch->setCondition(NewCond);
  404. // The false branch must exit the loop.
  405. if (!L->contains(ExitBranch->getSuccessor(0)))
  406. ExitBranch->swapSuccessors();
  407. // The old condition may be dead now, and may have even created a dead PHI
  408. // (the original induction variable).
  409. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  410. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
  411. }
  412. Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
  413. IRBuilder<> CondBuilder(ExitBranch);
  414. Function *DecFunc =
  415. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
  416. { EltsRem->getType() });
  417. Value *Ops[] = { EltsRem, LoopDecrement };
  418. Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
  419. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
  420. return cast<Instruction>(Call);
  421. }
  422. PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
  423. BasicBlock *Preheader = L->getLoopPreheader();
  424. BasicBlock *Header = L->getHeader();
  425. BasicBlock *Latch = ExitBranch->getParent();
  426. IRBuilder<> Builder(Header->getFirstNonPHI());
  427. PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
  428. Index->addIncoming(NumElts, Preheader);
  429. Index->addIncoming(EltsRem, Latch);
  430. LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
  431. return Index;
  432. }
  433. void HardwareLoop::UpdateBranch(Value *EltsRem) {
  434. IRBuilder<> CondBuilder(ExitBranch);
  435. Value *NewCond =
  436. CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
  437. Value *OldCond = ExitBranch->getCondition();
  438. ExitBranch->setCondition(NewCond);
  439. // The false branch must exit the loop.
  440. if (!L->contains(ExitBranch->getSuccessor(0)))
  441. ExitBranch->swapSuccessors();
  442. // The old condition may be dead now, and may have even created a dead PHI
  443. // (the original induction variable).
  444. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  445. }
  446. INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  447. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  448. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  449. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  450. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  451. INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  452. FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }