xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/HardwareLoops.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
10b57cec5SDimitry Andric //===-- HardwareLoops.cpp - Target Independent Hardware Loops --*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric /// \file
90b57cec5SDimitry Andric /// Insert hardware loop intrinsics into loops which are deemed profitable by
100b57cec5SDimitry Andric /// the target, by querying TargetTransformInfo. A hardware loop comprises of
110b57cec5SDimitry Andric /// two intrinsics: one, outside the loop, to set the loop iteration count and
120b57cec5SDimitry Andric /// another, in the exit block, to decrement the counter. The decremented value
130b57cec5SDimitry Andric /// can either be carried through the loop via a phi or handled in some opaque
140b57cec5SDimitry Andric /// way by the target.
150b57cec5SDimitry Andric ///
160b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric #include "llvm/Pass.h"
190b57cec5SDimitry Andric #include "llvm/PassRegistry.h"
200b57cec5SDimitry Andric #include "llvm/PassSupport.h"
210b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpander.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
290b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
300b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
310b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
320b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
330b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
340b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
350b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
360b57cec5SDimitry Andric #include "llvm/IR/Value.h"
370b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
380b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h"
390b57cec5SDimitry Andric #include "llvm/Transforms/Utils.h"
400b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
410b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
420b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric #define DEBUG_TYPE "hardware-loops"
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric #define HW_LOOPS_NAME "Hardware Loop Insertion"
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric using namespace llvm;
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric static cl::opt<bool>
510b57cec5SDimitry Andric ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false),
520b57cec5SDimitry Andric                    cl::desc("Force hardware loops intrinsics to be inserted"));
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric static cl::opt<bool>
550b57cec5SDimitry Andric ForceHardwareLoopPHI(
560b57cec5SDimitry Andric   "force-hardware-loop-phi", cl::Hidden, cl::init(false),
570b57cec5SDimitry Andric   cl::desc("Force hardware loop counter to be updated through a phi"));
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric static cl::opt<bool>
600b57cec5SDimitry Andric ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false),
610b57cec5SDimitry Andric                 cl::desc("Force allowance of nested hardware loops"));
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric static cl::opt<unsigned>
640b57cec5SDimitry Andric LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1),
650b57cec5SDimitry Andric             cl::desc("Set the loop decrement value"));
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric static cl::opt<unsigned>
680b57cec5SDimitry Andric CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32),
690b57cec5SDimitry Andric                 cl::desc("Set the loop counter bitwidth"));
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric static cl::opt<bool>
720b57cec5SDimitry Andric ForceGuardLoopEntry(
730b57cec5SDimitry Andric   "force-hardware-loop-guard", cl::Hidden, cl::init(false),
740b57cec5SDimitry Andric   cl::desc("Force generation of loop guard intrinsic"));
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric namespace {
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric   using TTI = TargetTransformInfo;
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric   class HardwareLoops : public FunctionPass {
830b57cec5SDimitry Andric   public:
840b57cec5SDimitry Andric     static char ID;
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric     HardwareLoops() : FunctionPass(ID) {
870b57cec5SDimitry Andric       initializeHardwareLoopsPass(*PassRegistry::getPassRegistry());
880b57cec5SDimitry Andric     }
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric     bool runOnFunction(Function &F) override;
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
930b57cec5SDimitry Andric       AU.addRequired<LoopInfoWrapperPass>();
940b57cec5SDimitry Andric       AU.addPreserved<LoopInfoWrapperPass>();
950b57cec5SDimitry Andric       AU.addRequired<DominatorTreeWrapperPass>();
960b57cec5SDimitry Andric       AU.addPreserved<DominatorTreeWrapperPass>();
970b57cec5SDimitry Andric       AU.addRequired<ScalarEvolutionWrapperPass>();
980b57cec5SDimitry Andric       AU.addRequired<AssumptionCacheTracker>();
990b57cec5SDimitry Andric       AU.addRequired<TargetTransformInfoWrapperPass>();
1000b57cec5SDimitry Andric     }
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric     // Try to convert the given Loop into a hardware loop.
1030b57cec5SDimitry Andric     bool TryConvertLoop(Loop *L);
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric     // Given that the target believes the loop to be profitable, try to
1060b57cec5SDimitry Andric     // convert it.
1070b57cec5SDimitry Andric     bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo);
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   private:
1100b57cec5SDimitry Andric     ScalarEvolution *SE = nullptr;
1110b57cec5SDimitry Andric     LoopInfo *LI = nullptr;
1120b57cec5SDimitry Andric     const DataLayout *DL = nullptr;
1130b57cec5SDimitry Andric     const TargetTransformInfo *TTI = nullptr;
1140b57cec5SDimitry Andric     DominatorTree *DT = nullptr;
1150b57cec5SDimitry Andric     bool PreserveLCSSA = false;
1160b57cec5SDimitry Andric     AssumptionCache *AC = nullptr;
1170b57cec5SDimitry Andric     TargetLibraryInfo *LibInfo = nullptr;
1180b57cec5SDimitry Andric     Module *M = nullptr;
1190b57cec5SDimitry Andric     bool MadeChange = false;
1200b57cec5SDimitry Andric   };
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric   class HardwareLoop {
1230b57cec5SDimitry Andric     // Expand the trip count scev into a value that we can use.
1240b57cec5SDimitry Andric     Value *InitLoopCount();
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric     // Insert the set_loop_iteration intrinsic.
1270b57cec5SDimitry Andric     void InsertIterationSetup(Value *LoopCountInit);
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric     // Insert the loop_decrement intrinsic.
1300b57cec5SDimitry Andric     void InsertLoopDec();
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric     // Insert the loop_decrement_reg intrinsic.
1330b57cec5SDimitry Andric     Instruction *InsertLoopRegDec(Value *EltsRem);
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric     // If the target requires the counter value to be updated in the loop,
1360b57cec5SDimitry Andric     // insert a phi to hold the value. The intended purpose is for use by
1370b57cec5SDimitry Andric     // loop_decrement_reg.
1380b57cec5SDimitry Andric     PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric     // Create a new cmp, that checks the returned value of loop_decrement*,
1410b57cec5SDimitry Andric     // and update the exit branch to use it.
1420b57cec5SDimitry Andric     void UpdateBranch(Value *EltsRem);
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   public:
1450b57cec5SDimitry Andric     HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE,
1460b57cec5SDimitry Andric                  const DataLayout &DL) :
1470b57cec5SDimitry Andric       SE(SE), DL(DL), L(Info.L), M(L->getHeader()->getModule()),
1480b57cec5SDimitry Andric       ExitCount(Info.ExitCount),
1490b57cec5SDimitry Andric       CountType(Info.CountType),
1500b57cec5SDimitry Andric       ExitBranch(Info.ExitBranch),
1510b57cec5SDimitry Andric       LoopDecrement(Info.LoopDecrement),
1520b57cec5SDimitry Andric       UsePHICounter(Info.CounterInReg),
1530b57cec5SDimitry Andric       UseLoopGuard(Info.PerformEntryTest) { }
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric     void Create();
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric   private:
1580b57cec5SDimitry Andric     ScalarEvolution &SE;
1590b57cec5SDimitry Andric     const DataLayout &DL;
1600b57cec5SDimitry Andric     Loop *L                 = nullptr;
1610b57cec5SDimitry Andric     Module *M               = nullptr;
1620b57cec5SDimitry Andric     const SCEV *ExitCount   = nullptr;
1630b57cec5SDimitry Andric     Type *CountType         = nullptr;
1640b57cec5SDimitry Andric     BranchInst *ExitBranch  = nullptr;
1650b57cec5SDimitry Andric     Value *LoopDecrement    = nullptr;
1660b57cec5SDimitry Andric     bool UsePHICounter      = false;
1670b57cec5SDimitry Andric     bool UseLoopGuard       = false;
1680b57cec5SDimitry Andric     BasicBlock *BeginBB     = nullptr;
1690b57cec5SDimitry Andric   };
1700b57cec5SDimitry Andric }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric char HardwareLoops::ID = 0;
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric bool HardwareLoops::runOnFunction(Function &F) {
1750b57cec5SDimitry Andric   if (skipFunction(F))
1760b57cec5SDimitry Andric     return false;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1810b57cec5SDimitry Andric   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1820b57cec5SDimitry Andric   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1830b57cec5SDimitry Andric   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1840b57cec5SDimitry Andric   DL = &F.getParent()->getDataLayout();
1850b57cec5SDimitry Andric   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
186*8bcb0991SDimitry Andric   LibInfo = TLIP ? &TLIP->getTLI(F) : nullptr;
1870b57cec5SDimitry Andric   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1880b57cec5SDimitry Andric   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1890b57cec5SDimitry Andric   M = F.getParent();
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
1920b57cec5SDimitry Andric     Loop *L = *I;
1930b57cec5SDimitry Andric     if (!L->getParentLoop())
1940b57cec5SDimitry Andric       TryConvertLoop(L);
1950b57cec5SDimitry Andric   }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   return MadeChange;
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric // Return true if the search should stop, which will be when an inner loop is
2010b57cec5SDimitry Andric // converted and the parent loop doesn't support containing a hardware loop.
2020b57cec5SDimitry Andric bool HardwareLoops::TryConvertLoop(Loop *L) {
2030b57cec5SDimitry Andric   // Process nested loops first.
2040b57cec5SDimitry Andric   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2050b57cec5SDimitry Andric     if (TryConvertLoop(*I))
2060b57cec5SDimitry Andric       return true; // Stop search.
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   HardwareLoopInfo HWLoopInfo(L);
2090b57cec5SDimitry Andric   if (!HWLoopInfo.canAnalyze(*LI))
2100b57cec5SDimitry Andric     return false;
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   if (TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo) ||
2130b57cec5SDimitry Andric       ForceHardwareLoops) {
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric     // Allow overriding of the counter width and loop decrement value.
2160b57cec5SDimitry Andric     if (CounterBitWidth.getNumOccurrences())
2170b57cec5SDimitry Andric       HWLoopInfo.CountType =
2180b57cec5SDimitry Andric         IntegerType::get(M->getContext(), CounterBitWidth);
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric     if (LoopDecrement.getNumOccurrences())
2210b57cec5SDimitry Andric       HWLoopInfo.LoopDecrement =
2220b57cec5SDimitry Andric         ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric     MadeChange |= TryConvertLoop(HWLoopInfo);
2250b57cec5SDimitry Andric     return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
2260b57cec5SDimitry Andric   }
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   return false;
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) {
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   Loop *L = HWLoopInfo.L;
2340b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop,
2370b57cec5SDimitry Andric                                           ForceHardwareLoopPHI))
2380b57cec5SDimitry Andric     return false;
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   assert(
2410b57cec5SDimitry Andric       (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) &&
2420b57cec5SDimitry Andric       "Hardware Loop must have set exit info.");
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   BasicBlock *Preheader = L->getLoopPreheader();
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   // If we don't have a preheader, then insert one.
2470b57cec5SDimitry Andric   if (!Preheader)
2480b57cec5SDimitry Andric     Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
2490b57cec5SDimitry Andric   if (!Preheader)
2500b57cec5SDimitry Andric     return false;
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric   HardwareLoop HWLoop(HWLoopInfo, *SE, *DL);
2530b57cec5SDimitry Andric   HWLoop.Create();
2540b57cec5SDimitry Andric   ++NumHWLoops;
2550b57cec5SDimitry Andric   return true;
2560b57cec5SDimitry Andric }
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric void HardwareLoop::Create() {
2590b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   Value *LoopCountInit = InitLoopCount();
2620b57cec5SDimitry Andric   if (!LoopCountInit)
2630b57cec5SDimitry Andric     return;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   InsertIterationSetup(LoopCountInit);
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   if (UsePHICounter || ForceHardwareLoopPHI) {
2680b57cec5SDimitry Andric     Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
2690b57cec5SDimitry Andric     Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec);
2700b57cec5SDimitry Andric     LoopDec->setOperand(0, EltsRem);
2710b57cec5SDimitry Andric     UpdateBranch(LoopDec);
2720b57cec5SDimitry Andric   } else
2730b57cec5SDimitry Andric     InsertLoopDec();
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   // Run through the basic blocks of the loop and see if any of them have dead
2760b57cec5SDimitry Andric   // PHIs that can be removed.
2770b57cec5SDimitry Andric   for (auto I : L->blocks())
2780b57cec5SDimitry Andric     DeleteDeadPHIs(I);
2790b57cec5SDimitry Andric }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric static bool CanGenerateTest(Loop *L, Value *Count) {
2820b57cec5SDimitry Andric   BasicBlock *Preheader = L->getLoopPreheader();
2830b57cec5SDimitry Andric   if (!Preheader->getSinglePredecessor())
2840b57cec5SDimitry Andric     return false;
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   BasicBlock *Pred = Preheader->getSinglePredecessor();
2870b57cec5SDimitry Andric   if (!isa<BranchInst>(Pred->getTerminator()))
2880b57cec5SDimitry Andric     return false;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   auto *BI = cast<BranchInst>(Pred->getTerminator());
2910b57cec5SDimitry Andric   if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition()))
2920b57cec5SDimitry Andric     return false;
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   // Check that the icmp is checking for equality of Count and zero and that
2950b57cec5SDimitry Andric   // a non-zero value results in entering the loop.
2960b57cec5SDimitry Andric   auto ICmp = cast<ICmpInst>(BI->getCondition());
2970b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << " - Found condition: " << *ICmp << "\n");
2980b57cec5SDimitry Andric   if (!ICmp->isEquality())
2990b57cec5SDimitry Andric     return false;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   auto IsCompareZero = [](ICmpInst *ICmp, Value *Count, unsigned OpIdx) {
3020b57cec5SDimitry Andric     if (auto *Const = dyn_cast<ConstantInt>(ICmp->getOperand(OpIdx)))
3030b57cec5SDimitry Andric       return Const->isZero() && ICmp->getOperand(OpIdx ^ 1) == Count;
3040b57cec5SDimitry Andric     return false;
3050b57cec5SDimitry Andric   };
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric   if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1))
3080b57cec5SDimitry Andric     return false;
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   unsigned SuccIdx = ICmp->getPredicate() == ICmpInst::ICMP_NE ? 0 : 1;
3110b57cec5SDimitry Andric   if (BI->getSuccessor(SuccIdx) != Preheader)
3120b57cec5SDimitry Andric     return false;
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   return true;
3150b57cec5SDimitry Andric }
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric Value *HardwareLoop::InitLoopCount() {
3180b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Initialising loop counter value:\n");
3190b57cec5SDimitry Andric   // Can we replace a conditional branch with an intrinsic that sets the
3200b57cec5SDimitry Andric   // loop counter and tests that is not zero?
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric   SCEVExpander SCEVE(SE, DL, "loopcnt");
3230b57cec5SDimitry Andric   if (!ExitCount->getType()->isPointerTy() &&
3240b57cec5SDimitry Andric       ExitCount->getType() != CountType)
3250b57cec5SDimitry Andric     ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   // If we're trying to use the 'test and set' form of the intrinsic, we need
3300b57cec5SDimitry Andric   // to replace a conditional branch that is controlling entry to the loop. It
3310b57cec5SDimitry Andric   // is likely (guaranteed?) that the preheader has an unconditional branch to
3320b57cec5SDimitry Andric   // the loop header, so also check if it has a single predecessor.
3330b57cec5SDimitry Andric   if (SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
3340b57cec5SDimitry Andric                                   SE.getZero(ExitCount->getType()))) {
3350b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " - Attempting to use test.set counter.\n");
3360b57cec5SDimitry Andric     UseLoopGuard |= ForceGuardLoopEntry;
3370b57cec5SDimitry Andric   } else
3380b57cec5SDimitry Andric     UseLoopGuard = false;
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   BasicBlock *BB = L->getLoopPreheader();
3410b57cec5SDimitry Andric   if (UseLoopGuard && BB->getSinglePredecessor() &&
3420b57cec5SDimitry Andric       cast<BranchInst>(BB->getTerminator())->isUnconditional())
3430b57cec5SDimitry Andric     BB = BB->getSinglePredecessor();
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) {
3460b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "- Bailing, unsafe to expand ExitCount "
3470b57cec5SDimitry Andric                << *ExitCount << "\n");
3480b57cec5SDimitry Andric     return nullptr;
3490b57cec5SDimitry Andric   }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
3520b57cec5SDimitry Andric                                      BB->getTerminator());
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric   // FIXME: We've expanded Count where we hope to insert the counter setting
3550b57cec5SDimitry Andric   // intrinsic. But, in the case of the 'test and set' form, we may fallback to
3560b57cec5SDimitry Andric   // the just 'set' form and in which case the insertion block is most likely
3570b57cec5SDimitry Andric   // different. It means there will be instruction(s) in a block that possibly
3580b57cec5SDimitry Andric   // aren't needed. The isLoopEntryGuardedByCond is trying to avoid this issue,
3590b57cec5SDimitry Andric   // but it's doesn't appear to work in all cases.
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   UseLoopGuard = UseLoopGuard && CanGenerateTest(L, Count);
3620b57cec5SDimitry Andric   BeginBB = UseLoopGuard ? BB : L->getLoopPreheader();
3630b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << " - Loop Count: " << *Count << "\n"
3640b57cec5SDimitry Andric              << " - Expanded Count in " << BB->getName() << "\n"
3650b57cec5SDimitry Andric              << " - Will insert set counter intrinsic into: "
3660b57cec5SDimitry Andric              << BeginBB->getName() << "\n");
3670b57cec5SDimitry Andric   return Count;
3680b57cec5SDimitry Andric }
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric void HardwareLoop::InsertIterationSetup(Value *LoopCountInit) {
3710b57cec5SDimitry Andric   IRBuilder<> Builder(BeginBB->getTerminator());
3720b57cec5SDimitry Andric   Type *Ty = LoopCountInit->getType();
3730b57cec5SDimitry Andric   Intrinsic::ID ID = UseLoopGuard ?
3740b57cec5SDimitry Andric     Intrinsic::test_set_loop_iterations : Intrinsic::set_loop_iterations;
3750b57cec5SDimitry Andric   Function *LoopIter = Intrinsic::getDeclaration(M, ID, Ty);
3760b57cec5SDimitry Andric   Value *SetCount = Builder.CreateCall(LoopIter, LoopCountInit);
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   // Use the return value of the intrinsic to control the entry of the loop.
3790b57cec5SDimitry Andric   if (UseLoopGuard) {
3800b57cec5SDimitry Andric     assert((isa<BranchInst>(BeginBB->getTerminator()) &&
3810b57cec5SDimitry Andric             cast<BranchInst>(BeginBB->getTerminator())->isConditional()) &&
3820b57cec5SDimitry Andric            "Expected conditional branch");
3830b57cec5SDimitry Andric     auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator());
3840b57cec5SDimitry Andric     LoopGuard->setCondition(SetCount);
3850b57cec5SDimitry Andric     if (LoopGuard->getSuccessor(0) != L->getLoopPreheader())
3860b57cec5SDimitry Andric       LoopGuard->swapSuccessors();
3870b57cec5SDimitry Andric   }
3880b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop counter: "
3890b57cec5SDimitry Andric              << *SetCount << "\n");
3900b57cec5SDimitry Andric }
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric void HardwareLoop::InsertLoopDec() {
3930b57cec5SDimitry Andric   IRBuilder<> CondBuilder(ExitBranch);
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   Function *DecFunc =
3960b57cec5SDimitry Andric     Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
3970b57cec5SDimitry Andric                               LoopDecrement->getType());
3980b57cec5SDimitry Andric   Value *Ops[] = { LoopDecrement };
3990b57cec5SDimitry Andric   Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
4000b57cec5SDimitry Andric   Value *OldCond = ExitBranch->getCondition();
4010b57cec5SDimitry Andric   ExitBranch->setCondition(NewCond);
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric   // The false branch must exit the loop.
4040b57cec5SDimitry Andric   if (!L->contains(ExitBranch->getSuccessor(0)))
4050b57cec5SDimitry Andric     ExitBranch->swapSuccessors();
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   // The old condition may be dead now, and may have even created a dead PHI
4080b57cec5SDimitry Andric   // (the original induction variable).
4090b57cec5SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
4150b57cec5SDimitry Andric   IRBuilder<> CondBuilder(ExitBranch);
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   Function *DecFunc =
4180b57cec5SDimitry Andric       Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
4190b57cec5SDimitry Andric                                 { EltsRem->getType(), EltsRem->getType(),
4200b57cec5SDimitry Andric                                   LoopDecrement->getType()
4210b57cec5SDimitry Andric                                 });
4220b57cec5SDimitry Andric   Value *Ops[] = { EltsRem, LoopDecrement };
4230b57cec5SDimitry Andric   Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
4260b57cec5SDimitry Andric   return cast<Instruction>(Call);
4270b57cec5SDimitry Andric }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
4300b57cec5SDimitry Andric   BasicBlock *Preheader = L->getLoopPreheader();
4310b57cec5SDimitry Andric   BasicBlock *Header = L->getHeader();
4320b57cec5SDimitry Andric   BasicBlock *Latch = ExitBranch->getParent();
4330b57cec5SDimitry Andric   IRBuilder<> Builder(Header->getFirstNonPHI());
4340b57cec5SDimitry Andric   PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
4350b57cec5SDimitry Andric   Index->addIncoming(NumElts, Preheader);
4360b57cec5SDimitry Andric   Index->addIncoming(EltsRem, Latch);
4370b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
4380b57cec5SDimitry Andric   return Index;
4390b57cec5SDimitry Andric }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric void HardwareLoop::UpdateBranch(Value *EltsRem) {
4420b57cec5SDimitry Andric   IRBuilder<> CondBuilder(ExitBranch);
4430b57cec5SDimitry Andric   Value *NewCond =
4440b57cec5SDimitry Andric     CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
4450b57cec5SDimitry Andric   Value *OldCond = ExitBranch->getCondition();
4460b57cec5SDimitry Andric   ExitBranch->setCondition(NewCond);
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric   // The false branch must exit the loop.
4490b57cec5SDimitry Andric   if (!L->contains(ExitBranch->getSuccessor(0)))
4500b57cec5SDimitry Andric     ExitBranch->swapSuccessors();
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   // The old condition may be dead now, and may have even created a dead PHI
4530b57cec5SDimitry Andric   // (the original induction variable).
4540b57cec5SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
4550b57cec5SDimitry Andric }
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
4580b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4590b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
4600b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
4610b57cec5SDimitry Andric INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }
464