47 #define DEBUG_TYPE "hardware-loops" 49 #define HW_LOOPS_NAME "Hardware Loop Insertion" 55 cl::desc(
"Force hardware loops intrinsics to be inserted"));
60 cl::desc(
"Force hardware loop counter to be updated through a phi"));
64 cl::desc(
"Force allowance of nested hardware loops"));
68 cl::desc(
"Set the loop decrement value"));
72 cl::desc(
"Set the loop counter bitwidth"));
77 cl::desc(
"Force generation of loop guard intrinsic"));
79 STATISTIC(NumHWLoops,
"Number of loops converted to hardware loops");
84 dbgs() <<
"HWLoops: " << DebugMsg;
107 R <<
"hardware-loop not created: ";
143 bool TryConvertLoop(
Loop *L);
156 bool PreserveLCSSA =
false;
160 bool MadeChange =
false;
165 Value *InitLoopCount();
168 void InsertIterationSetup(
Value *LoopCountInit);
171 void InsertLoopDec();
183 void UpdateBranch(
Value *EltsRem);
189 SE(SE), DL(DL), ORE(ORE), L(Info.
L), M(L->getHeader()->getModule()),
205 const SCEV *ExitCount =
nullptr;
206 Type *CountType =
nullptr;
209 bool UsePHICounter =
false;
210 bool UseLoopGuard =
false;
223 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
224 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
225 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
226 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
228 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
229 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
230 LibInfo = TLIP ? &TLIP->getTLI(F) :
nullptr;
231 PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
232 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
246 bool HardwareLoops::TryConvertLoop(
Loop *L) {
249 if (TryConvertLoop(*
I)) {
250 reportHWLoopFailure(
"nested hardware-loops not supported",
"HWLoopNested",
258 reportHWLoopFailure(
"cannot analyze loop, irreducible control flow",
259 "HWLoopCannotAnalyze", ORE, L);
264 !TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo)) {
265 reportHWLoopFailure(
"it's not profitable to create a hardware-loop",
266 "HWLoopNotProfitable", ORE, L);
279 MadeChange |= TryConvertLoop(HWLoopInfo);
285 Loop *L = HWLoopInfo.
L;
286 LLVM_DEBUG(
dbgs() <<
"HWLoops: Try to convert profitable loop: " << *L);
293 reportHWLoopFailure(
"loop is not a candidate",
"HWLoopNoCandidate", ORE, L);
299 "Hardware Loop must have set exit info.");
309 HardwareLoop HWLoop(HWLoopInfo, *SE, *DL, ORE);
315 void HardwareLoop::Create() {
318 Value *LoopCountInit = InitLoopCount();
319 if (!LoopCountInit) {
320 reportHWLoopFailure(
"could not safely create a loop count expression",
321 "HWLoopNotSafe", ORE, L);
325 InsertIterationSetup(LoopCountInit);
328 Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
329 Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec);
331 UpdateBranch(LoopDec);
351 if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition()))
356 auto ICmp = cast<ICmpInst>(BI->getCondition());
358 if (!ICmp->isEquality())
361 auto IsCompareZero = [](
ICmpInst *ICmp,
Value *Count,
unsigned OpIdx) {
362 if (
auto *Const = dyn_cast<ConstantInt>(ICmp->
getOperand(OpIdx)))
363 return Const->isZero() && ICmp->
getOperand(OpIdx ^ 1) == Count;
367 if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1))
371 if (BI->getSuccessor(SuccIdx) != Preheader)
377 Value *HardwareLoop::InitLoopCount() {
378 LLVM_DEBUG(
dbgs() <<
"HWLoops: Initialising loop counter value:\n");
383 if (!ExitCount->getType()->isPointerTy() &&
384 ExitCount->getType() != CountType)
385 ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
387 ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
394 SE.getZero(ExitCount->getType()))) {
398 UseLoopGuard =
false;
407 << *ExitCount <<
"\n");
424 <<
" - Expanded Count in " << BB->
getName() <<
"\n" 425 <<
" - Will insert set counter intrinsic into: " 426 << BeginBB->getName() <<
"\n");
430 void HardwareLoop::InsertIterationSetup(
Value *LoopCountInit) {
434 Intrinsic::test_set_loop_iterations : Intrinsic::set_loop_iterations;
436 Value *SetCount = Builder.CreateCall(LoopIter, LoopCountInit);
440 assert((isa<BranchInst>(BeginBB->getTerminator()) &&
441 cast<BranchInst>(BeginBB->getTerminator())->isConditional()) &&
442 "Expected conditional branch");
443 auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator());
444 LoopGuard->setCondition(SetCount);
446 LoopGuard->swapSuccessors();
449 << *SetCount <<
"\n");
452 void HardwareLoop::InsertLoopDec() {
460 Value *OldCond = ExitBranch->getCondition();
461 ExitBranch->setCondition(NewCond);
464 if (!L->
contains(ExitBranch->getSuccessor(0)))
465 ExitBranch->swapSuccessors();
471 LLVM_DEBUG(
dbgs() <<
"HWLoops: Inserted loop dec: " << *NewCond <<
"\n");
485 LLVM_DEBUG(
dbgs() <<
"HWLoops: Inserted loop dec: " << *Call <<
"\n");
486 return cast<Instruction>(Call);
495 Index->addIncoming(NumElts, Preheader);
496 Index->addIncoming(EltsRem, Latch);
501 void HardwareLoop::UpdateBranch(
Value *EltsRem) {
505 Value *OldCond = ExitBranch->getCondition();
506 ExitBranch->setCondition(NewCond);
509 if (!L->
contains(ExitBranch->getSuccessor(0)))
510 ExitBranch->swapSuccessors();
A parsed version of the target data layout string in and methods for querying it. ...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are d...
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
STATISTIC(NumFunctions, "Total number of functions")
static cl::opt< bool > ForceGuardLoopEntry("force-hardware-loop-guard", cl::Hidden, cl::init(false), cl::desc("Force generation of loop guard intrinsic"))
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...
void initializeHardwareLoopsPass(PassRegistry &)
FunctionPass * createHardwareLoopsPass()
Create Hardware Loop pass.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
std::vector< Loop *>::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
BlockT * getHeader() const
static cl::opt< unsigned > CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32), cl::desc("Set the loop counter bitwidth"))
std::vector< Loop *>::const_iterator iterator
Type * getType() const
All values are typed, get the type of this value.
bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Examine each PHI in the given block and delete it if it is dead.
static cl::opt< bool > ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false), cl::desc("Force hardware loops intrinsics to be inserted"))
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
Analysis containing CSE Info
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static OptimizationRemarkAnalysis createHWLoopAnalysis(StringRef RemarkName, Loop *L, Instruction *I)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< bool > ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false), cl::desc("Force allowance of nested hardware loops"))
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
static cl::opt< unsigned > LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1), cl::desc("Set the loop decrement value"))
FunctionPass class - This class is used to implement most global optimizations.
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"))
Attributes of a target dependent hardware loop.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Provides information about what library functions are available for the current target.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool canAnalyze(LoopInfo &LI)
This class uses information about analyze scalars to rewrite expressions in canonical form...
static bool CanGenerateTest(Loop *L, Value *Count)
LoopT * getParentLoop() const
Predicate getPredicate() const
Return the predicate for this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
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...
static void debugHWLoopFailure(const StringRef DebugMsg, Instruction *I)
The legacy pass manager's analysis pass to compute loop information.
StringRef - Represent a constant reference to a string, i.e.
Legacy analysis pass which computes a DominatorTree.
bool isHardwareLoopCandidate(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, bool ForceNestedLoop=false, bool ForceHardwareLoopPHI=false)
iterator_range< block_iterator > blocks() const
const BasicBlock * getParent() const