97 #define DEBUG_TYPE "loop-versioning-licm" 105 cl::desc(
"LoopVersioningLICM's minimum allowed percentage" 106 "of possible invariant instructions per loop"),
111 "licm-versioning-max-depth-threshold",
113 "LoopVersioningLICM's threshold for maximum allowed loop nest/depth"),
118 struct LoopVersioningLICM :
public LoopPass {
143 StringRef getPassName()
const override {
return "Loop Versioning for LICM"; }
150 LoadAndStoreCounter = 0;
151 InvariantCounter = 0;
152 IsReadOnlyLoop =
true;
159 AutoResetter(LoopVersioningLICM &LVLICM) : LVLICM(LVLICM) {}
160 ~AutoResetter() { LVLICM.reset(); }
163 LoopVersioningLICM &LVLICM;
180 Loop *CurLoop =
nullptr;
183 std::unique_ptr<AliasSetTracker> CurAST;
186 unsigned LoopDepthThreshold;
189 float InvariantThreshold;
192 unsigned LoadAndStoreCounter = 0;
195 unsigned InvariantCounter = 0;
198 bool IsReadOnlyLoop =
true;
203 bool isLegalForVersioning();
204 bool legalLoopStructure();
205 bool legalLoopInstructions();
206 bool legalLoopMemoryAccesses();
207 bool isLoopAlreadyVisited();
208 void setNoAliasToLoop(
Loop *VerLoop);
215 bool LoopVersioningLICM::legalLoopStructure() {
217 if (!CurLoop->isLoopSimplifyForm()) {
222 if (!CurLoop->getSubLoops().empty()) {
227 if (CurLoop->getNumBackEdges() != 1) {
232 if (!CurLoop->getExitingBlock()) {
239 if (CurLoop->getExitingBlock() != CurLoop->getLoopLatch()) {
245 if (CurLoop->isAnnotatedParallel()) {
250 if (CurLoop->getLoopDepth() > LoopDepthThreshold) {
256 const SCEV *ExitCount = SE->getBackedgeTakenCount(CurLoop);
257 if (ExitCount == SE->getCouldNotCompute()) {
266 bool LoopVersioningLICM::legalLoopMemoryAccesses() {
267 bool HasMayAlias =
false;
268 bool TypeSafety =
false;
282 for (
const auto &
I : *CurAST) {
292 bool TypeCheck =
true;
295 HasMod |= AS.
isMod();
296 for (
const auto &A : AS) {
297 Value *Ptr = A.getValue();
299 TypeCheck = (TypeCheck && (SomePtr->
getType() == Ptr->
getType()));
302 TypeSafety |= TypeCheck;
330 bool LoopVersioningLICM::instructionSafeForVersioning(
Instruction *
I) {
331 assert(I !=
nullptr &&
"Null instruction found!");
333 if (
auto *Call = dyn_cast<CallBase>(I)) {
334 if (Call->isConvergent() || Call->cannotDuplicate()) {
339 if (!AA->doesNotAccessMemory(Call)) {
347 LLVM_DEBUG(
dbgs() <<
" May throw instruction found in loop body\n");
358 LoadAndStoreCounter++;
361 if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
372 LoadAndStoreCounter++;
375 if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
378 IsReadOnlyLoop =
false;
385 bool LoopVersioningLICM::legalLoopInstructions() {
387 LoadAndStoreCounter = 0;
388 InvariantCounter = 0;
389 IsReadOnlyLoop =
true;
393 for (
auto *Block : CurLoop->getBlocks())
394 for (
auto &Inst : *Block) {
396 if (!instructionSafeForVersioning(&Inst)) {
399 <<
" Unsafe Loop Instruction";
405 LAI = &LAA->getInfo(CurLoop);
407 if (LAI->getRuntimePointerChecking()->getChecks().empty()) {
412 if (LAI->getNumRuntimePointerChecks() >
415 dbgs() <<
" LAA: Runtime checks are more than threshold !!\n");
418 CurLoop->getStartLoc(),
419 CurLoop->getHeader())
420 <<
"Number of runtime checks " 421 <<
NV(
"RuntimeChecks", LAI->getNumRuntimePointerChecks())
422 <<
" exceeds threshold " 428 if (!InvariantCounter) {
433 if (IsReadOnlyLoop) {
439 if (InvariantCounter * 100 < InvariantThreshold * LoadAndStoreCounter) {
442 <<
" Invariant load & store are less then defined threshold\n");
444 << ((InvariantCounter * 100) / LoadAndStoreCounter)
447 << InvariantThreshold <<
"%\n");
450 CurLoop->getStartLoc(),
451 CurLoop->getHeader())
452 <<
"Invariant load & store " 453 <<
NV(
"LoadAndStoreCounter",
454 ((InvariantCounter * 100) / LoadAndStoreCounter))
455 <<
" are less then defined threshold " 456 <<
NV(
"Threshold", InvariantThreshold);
466 bool LoopVersioningLICM::isLoopAlreadyVisited() {
478 bool LoopVersioningLICM::isLegalForVersioning() {
482 if (isLoopAlreadyVisited()) {
484 dbgs() <<
" Revisiting loop in LoopVersioningLICM not allowed.\n\n");
488 if (!legalLoopStructure()) {
490 dbgs() <<
" Loop structure not suitable for LoopVersioningLICM\n\n");
493 CurLoop->getStartLoc(),
494 CurLoop->getHeader())
495 <<
" Unsafe Loop structure";
500 if (!legalLoopInstructions()) {
503 <<
" Loop instructions not suitable for LoopVersioningLICM\n\n");
507 if (!legalLoopMemoryAccesses()) {
510 <<
" Loop memory access not suitable for LoopVersioningLICM\n\n");
513 CurLoop->getStartLoc(),
514 CurLoop->getHeader())
515 <<
" Unsafe Loop memory access";
520 LLVM_DEBUG(
dbgs() <<
" Loop Versioning found to be beneficial\n\n");
523 CurLoop->getStartLoc(), CurLoop->getHeader())
524 <<
" Versioned loop for LICM." 525 <<
" Number of runtime checks we had to insert " 526 <<
NV(
"RuntimeChecks", LAI->getNumRuntimePointerChecks());
536 void LoopVersioningLICM::setNoAliasToLoop(
Loop *VerLoop) {
541 MDNode *NewDomain = MDB.createAnonymousAliasScopeDomain(
"LVDomain");
544 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
547 for (
auto *Block : CurLoop->getBlocks()) {
548 for (
auto &Inst : *Block) {
550 if (!Inst.mayReadFromMemory() && !Inst.mayWriteToMemory())
556 LLVMContext::MD_noalias,
561 LLVMContext::MD_alias_scope,
571 AutoResetter Resetter(*
this);
581 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
582 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
583 LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
584 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
591 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
597 bool Changed =
false;
602 if (isLegalForVersioning()) {
606 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
617 "llvm.mem.parallel_loop_access");
619 setNoAliasToLoop(LVer.getVersionedLoop());
628 "Loop Versioning For LICM",
false,
false)
Legacy wrapper pass to provide the GlobalsAAResult object.
Pass interface - Implemented by all 'passes'.
static unsigned RuntimeMemoryCheckThreshold
performing memory disambiguation checks at runtime do not make more than this number of comparisons...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
DiagnosticInfoOptimizationBase::Argument NV
This class represents lattice values for constants.
This is the interface for a simple mod/ref and alias analysis over globals.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static cl::opt< float > LVInvarThreshold("licm-versioning-invariant-threshold", cl::desc("LoopVersioningLICM's minimum allowed percentage" "of possible invariant instructions per loop"), cl::init(25), cl::Hidden)
Threshold minimum allowed percentage for possible invariant instructions in a loop.
void push_back(const T &Elt)
The main scalar evolution driver.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
INITIALIZE_PASS_BEGIN(LoopVersioningLICM, "loop-versioning-licm", "Loop Versioning For LICM", false, false) INITIALIZE_PASS_END(LoopVersioningLICM
LLVMContext & getContext() const
All values hold a context through their type.
An instruction for reading from memory.
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...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static const char * LICMVersioningMetaData
Type * getType() const
All values are typed, get the type of this value.
static cl::opt< unsigned > LVLoopDepthThreshold("licm-versioning-max-depth-threshold", cl::desc("LoopVersioningLICM's threshold for maximum allowed loop nest/depth"), cl::init(2), cl::Hidden)
Threshold for maximum allowed loop nest/depth.
An instruction for storing to memory.
void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
initializer< Ty > init(const Ty &Val)
This analysis provides dependence information for the memory accesses of a loop.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool mayThrow() const
Return true if this instruction may throw an exception.
Represent the analysis usage information of a pass.
Value * getPointerOperand()
Pass * createLoopVersioningLICMPass()
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
The transformation should not be applied.
void initializeLoopVersioningLICMPass(PassRegistry &)
AnalysisUsage & addRequiredID(const void *ID)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Drive the analysis of memory accesses in the loop.
static cl::opt< bool > NoAliases("riscv-no-aliases", cl::desc("Disable the emission of assembler pseudo instructions"), cl::init(false), cl::Hidden)
void setPreservesCFG()
This function should be called by the pass, iff they do not:
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
static MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
Optional< const MDOperand * > findStringMetadataForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for loop.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
TransformationMode hasLICMVersioningTransformation(Loop *L)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
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 isForwardingAliasSet() const
Return true if this alias set should be ignored as part of the AliasSetTracker object.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Value * getPointerOperand()
loop versioning Loop Versioning For LICM