1//===- MachineLoopInfo.cpp - Natural Loop Calculator ----------------------===//
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
7//===----------------------------------------------------------------------===//
9// This file defines the MachineLoopInfo class that is used to identify natural
10// loops and determine the loop depth of various nodes of the CFG. Note that
11// the loops identified may actually be several natural loops that share the
12// same header node... not just a single natural loop.
14//===----------------------------------------------------------------------===//
21#include "llvm/Config/llvm-config.h"
30// Explicitly instantiate methods in LoopInfoImpl.h for MI-level Loops.
47 OS <<
"Machine loop info for machine function '" << MF.
getName() <<
"':\n";
58 "Machine Natural Loop Construction",
true,
true)
61 "Machine Natural Loop Construction",
true,
true)
72 MachineFunctionAnalysisManager::Invalidator &) {
73 // Check whether the analysis, all analyses on functions, or the function's
74 // CFG have been preserved.
76 return !PAC.preserved() &&
133 // Try the pre-header first.
135 if (
const BasicBlock *PHeadBB = PHeadMBB->getBasicBlock())
136 if (
DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
139 // If we have no pre-header or there are no instructions with debug
140 // info in it, try the header.
142 if (
const BasicBlock *HeadBB = HeadMBB->getBasicBlock())
143 return HeadBB->getTerminator()->getDebugLoc();
150 bool FindMultiLoopPreheader)
const {
154 if (!SpeculativePreheader)
160 // Find the predecessor of the header that is not the latch block.
171 // Check if the preheader candidate is a successor of any other loop
172 // headers. We want to avoid having two loop setups in the same block.
173 if (!FindMultiLoopPreheader) {
178 if (
T &&
T->getHeader() == S)
188 // Go through the latch blocks and check the terminator for the metadata
191 for (
const auto *
MBB : LatchesBlocks) {
192 const auto *BB =
MBB->getBasicBlock();
195 const auto *TI = BB->getTerminator();
199 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
205 else if (MD != LoopID)
216bool MachineLoop::isLoopInvariantImplicitPhysReg(
Register Reg)
const {
220 if (
MRI->isConstantPhysReg(Reg))
229 MRI->def_instructions(Reg),
241 // The instruction is loop invariant if all of its operands are.
247 if (Reg == 0)
continue;
249 if (ExcludeReg == Reg)
252 // An instruction that uses or defines a physical register can't e.g. be
253 // hoisted, so mark this as not invariant.
254 if (Reg.isPhysical()) {
256 // If the physreg has no defs anywhere, it's just an ambient register
257 // and we can freely move its uses. Alternatively, if it's allocatable,
258 // it could get allocated to something with a def during allocation.
259 // However, if the physreg is known to always be caller saved/restored
260 // then this use is safe to hoist.
261 if (!isLoopInvariantImplicitPhysReg(Reg) &&
262 !(
TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *
I.getMF())) &&
263 !
TII->isIgnorableUse(MO))
265 // Otherwise it's safe to move.
267 }
else if (!MO.isDead()) {
268 // A def that isn't dead can't be moved.
271 // If the reg is live into the loop, we can't hoist an instruction
272 // which would clobber it.
281 "Machine instr not mapped for this vreg?!");
283 // If the loop contains the definition of an operand, then the instruction
284 // isn't loop invariant.
289 // If we got this far, the instruction is loop invariant!
293#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
#define LLVM_EXPORT_TEMPLATE
const HexagonInstrInfo * TII
Register const TargetRegisterInfo * TRI
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Represents analyses that only rely on functions' control flow.
Instances of this class are used to represent loops that are detected in the flow graph.
bool contains(const MachineLoop *L) const
MachineBasicBlock * getLoopLatch() const
MachineBasicBlock * getHeader() const
void getLoopLatches(SmallVectorImpl< MachineBasicBlock * > &LoopLatches) const
void print(raw_ostream &OS, bool Verbose=false, bool PrintNested=true, unsigned Depth=0) const
MachineBasicBlock * getLoopPreheader() const
MachineBasicBlock * getExitingBlock() const
bool isLoopExiting(const MachineBasicBlock *BB) const
This class builds and contains all of the top-level loop structures in the specified function.
void analyze(const DominatorTreeBase< MachineBasicBlock, false > &DomTree)
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
const MDOperand & getOperand(unsigned I) const
unsigned getNumOperands() const
Return number of MDNode operands.
unsigned pred_size() const
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineFunctionPass(char &ID)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
BasicBlockListType::iterator iterator
Representation of each machine instruction.
Analysis pass that exposes the MachineLoopInfo for a machine function.
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
bool runOnMachineFunction(MachineFunction &F) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
MachineLoopInfoWrapperPass()
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
LLVM_ABI void calculate(MachineDominatorTree &MDT)
Calculate the natural loop information.
LLVM_ABI bool invalidate(MachineFunction &, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
LLVM_ABI MachineBasicBlock * findLoopPreheader(MachineLoop *L, bool SpeculativePreheader=false, bool FindMultiLoopPreheader=false) const
Find the block that either is the loop preheader, or could speculatively be used as the preheader.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI MachineBasicBlock * findLoopControlBlock() const
Find the block that contains the loop control variable and the loop test.
LLVM_ABI MDNode * getLoopID() const
Find the llvm.loop metadata for this loop.
LLVM_ABI DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
LLVM_ABI void dump() const
LLVM_ABI MachineBasicBlock * getBottomBlock()
Return the "bottom" block in the loop, which is the last block in the linear layout,...
LLVM_ABI bool isLoopInvariant(MachineInstr &I, const Register ExcludeReg=0) const
Returns true if the instruction is loop invariant.
LLVM_ABI MachineBasicBlock * getTopBlock()
Return the "top" block in the loop, which is the first block in the linear layout,...
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Wrapper class representing virtual and physical registers.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual bool shouldAnalyzePhysregInMachineLoopInfo(MCRegister R) const
Returns true if MachineLoopInfo should analyze the given physreg for loop invariance.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
self_iterator getIterator()
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI void initializeMachineLoopInfoWrapperPassPass(PassRegistry &)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
A special type used by analysis passes to provide an address that identifies that particular analysis...