#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSchedule.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/InitializePasses.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCRegister.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <limits>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "machinelicm"
static cl::opt<bool>
AvoidSpeculation("avoid-speculation",
cl::desc("MachineLICM should avoid speculation"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
HoistCheapInsts("hoist-cheap-insts",
cl::desc("MachineLICM should hoist even cheap instructions"),
cl::init(false), cl::Hidden);
static cl::opt<bool>
HoistConstStores("hoist-const-stores",
cl::desc("Hoist invariant stores"),
cl::init(true), cl::Hidden);
static cl::opt<unsigned>
BlockFrequencyRatioThreshold("block-freq-ratio-threshold",
cl::desc("Do not hoist instructions if target"
"block is N times hotter than the source."),
cl::init(100), cl::Hidden);
enum class UseBFI { None, PGO, All };
static cl::opt<UseBFI>
DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks",
cl::desc("Disable hoisting instructions to"
" hotter blocks"),
cl::init(UseBFI::PGO), cl::Hidden,
cl::values(clEnumValN(UseBFI::None, "none",
"disable the feature"),
clEnumValN(UseBFI::PGO, "pgo",
"enable the feature when using profile data"),
clEnumValN(UseBFI::All, "all",
"enable the feature with/wo profile data")));
STATISTIC(NumHoisted,
"Number of machine instructions hoisted out of loops");
STATISTIC(NumLowRP,
"Number of instructions hoisted in low reg pressure situation");
STATISTIC(NumHighLatency,
"Number of high latency instructions hoisted");
STATISTIC(NumCSEed,
"Number of hoisted machine instructions CSEed");
STATISTIC(NumPostRAHoisted,
"Number of machine instructions hoisted out of loops post regalloc");
STATISTIC(NumStoreConst,
"Number of stores of const phys reg hoisted out of loops");
STATISTIC(NumNotHoistedDueToHotness,
"Number of instructions not hoisted due to block frequency");
namespace {
class MachineLICMBase : public MachineFunctionPass {
const TargetInstrInfo *TII;
const TargetLoweringBase *TLI;
const TargetRegisterInfo *TRI;
const MachineFrameInfo *MFI;
MachineRegisterInfo *MRI;
TargetSchedModel SchedModel;
bool PreRegAlloc;
bool HasProfileData;
AliasAnalysis *AA; MachineBlockFrequencyInfo *MBFI; MachineLoopInfo *MLI; MachineDominatorTree *DT;
bool Changed; bool FirstInLoop; MachineLoop *CurLoop; MachineBasicBlock *CurPreheader;
SmallVector<MachineBasicBlock *, 8> ExitBlocks;
bool isExitBlock(const MachineBasicBlock *MBB) const {
return is_contained(ExitBlocks, MBB);
}
SmallSet<Register, 32> RegSeen;
SmallVector<unsigned, 8> RegPressure;
SmallVector<unsigned, 8> RegLimit;
SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
DenseMap<unsigned, std::vector<MachineInstr *>> CSEMap;
enum {
SpeculateFalse = 0,
SpeculateTrue = 1,
SpeculateUnknown = 2
};
unsigned SpeculationState;
public:
MachineLICMBase(char &PassID, bool PreRegAlloc)
: MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
bool runOnMachineFunction(MachineFunction &MF) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineLoopInfo>();
if (DisableHoistingToHotterBlocks != UseBFI::None)
AU.addRequired<MachineBlockFrequencyInfo>();
AU.addRequired<MachineDominatorTree>();
AU.addRequired<AAResultsWrapperPass>();
AU.addPreserved<MachineLoopInfo>();
MachineFunctionPass::getAnalysisUsage(AU);
}
void releaseMemory() override {
RegSeen.clear();
RegPressure.clear();
RegLimit.clear();
BackTrace.clear();
CSEMap.clear();
}
private:
struct CandidateInfo {
MachineInstr *MI;
unsigned Def;
int FI;
CandidateInfo(MachineInstr *mi, unsigned def, int fi)
: MI(mi), Def(def), FI(fi) {}
};
void HoistRegionPostRA();
void HoistPostRA(MachineInstr *MI, unsigned Def);
void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
SmallVectorImpl<CandidateInfo> &Candidates);
void AddToLiveIns(MCRegister Reg);
bool IsLICMCandidate(MachineInstr &I);
bool IsLoopInvariantInst(MachineInstr &I);
bool HasLoopPHIUse(const MachineInstr *MI) const;
bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
Register Reg) const;
bool IsCheapInstruction(MachineInstr &MI) const;
bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
bool Cheap);
void UpdateBackTraceRegPressure(const MachineInstr *MI);
bool IsProfitableToHoist(MachineInstr &MI);
bool IsGuaranteedToExecute(MachineBasicBlock *BB);
bool isTriviallyReMaterializable(const MachineInstr &MI) const;
void EnterScope(MachineBasicBlock *MBB);
void ExitScope(MachineBasicBlock *MBB);
void ExitScopeIfDone(
MachineDomTreeNode *Node,
DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
const DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
void HoistOutOfLoop(MachineDomTreeNode *HeaderN);
void InitRegPressure(MachineBasicBlock *BB);
DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
bool ConsiderSeen,
bool ConsiderUnseenAsDef);
void UpdateRegPressure(const MachineInstr *MI,
bool ConsiderUnseenAsDef = false);
MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
MachineInstr *LookForDuplicate(const MachineInstr *MI,
std::vector<MachineInstr *> &PrevMIs);
bool
EliminateCSE(MachineInstr *MI,
DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI);
bool MayCSE(MachineInstr *MI);
bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
void InitCSEMap(MachineBasicBlock *BB);
bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
MachineBasicBlock *TgtBlock);
MachineBasicBlock *getCurPreheader();
};
class MachineLICM : public MachineLICMBase {
public:
static char ID;
MachineLICM() : MachineLICMBase(ID, false) {
initializeMachineLICMPass(*PassRegistry::getPassRegistry());
}
};
class EarlyMachineLICM : public MachineLICMBase {
public:
static char ID;
EarlyMachineLICM() : MachineLICMBase(ID, true) {
initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
}
};
}
char MachineLICM::ID;
char EarlyMachineLICM::ID;
char &llvm::MachineLICMID = MachineLICM::ID;
char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
"Machine Loop Invariant Code Motion", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
"Machine Loop Invariant Code Motion", false, false)
INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
"Early Machine Loop Invariant Code Motion", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
"Early Machine Loop Invariant Code Motion", false, false)
static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
if (!CurLoop->getLoopPredecessor())
return false;
for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
if (L->getLoopPredecessor())
return false;
return true;
}
bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
if (skipFunction(MF.getFunction()))
return false;
Changed = FirstInLoop = false;
const TargetSubtargetInfo &ST = MF.getSubtarget();
TII = ST.getInstrInfo();
TLI = ST.getTargetLowering();
TRI = ST.getRegisterInfo();
MFI = &MF.getFrameInfo();
MRI = &MF.getRegInfo();
SchedModel.init(&ST);
PreRegAlloc = MRI->isSSA();
HasProfileData = MF.getFunction().hasProfileData();
if (PreRegAlloc)
LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
else
LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
if (PreRegAlloc) {
unsigned NumRPS = TRI->getNumRegPressureSets();
RegPressure.resize(NumRPS);
std::fill(RegPressure.begin(), RegPressure.end(), 0);
RegLimit.resize(NumRPS);
for (unsigned i = 0, e = NumRPS; i != e; ++i)
RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
}
if (DisableHoistingToHotterBlocks != UseBFI::None)
MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
MLI = &getAnalysis<MachineLoopInfo>();
DT = &getAnalysis<MachineDominatorTree>();
AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
while (!Worklist.empty()) {
CurLoop = Worklist.pop_back_val();
CurPreheader = nullptr;
ExitBlocks.clear();
if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
Worklist.append(CurLoop->begin(), CurLoop->end());
continue;
}
CurLoop->getExitBlocks(ExitBlocks);
if (!PreRegAlloc)
HoistRegionPostRA();
else {
MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
FirstInLoop = true;
HoistOutOfLoop(N);
CSEMap.clear();
}
}
return Changed;
}
static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
if (!MI->mayStore())
return false;
if (MI->memoperands_empty())
return true;
for (const MachineMemOperand *MemOp : MI->memoperands()) {
if (!MemOp->isStore() || !MemOp->getPseudoValue())
continue;
if (const FixedStackPseudoSourceValue *Value =
dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
if (Value->getFrameIndex() == FI)
return true;
}
}
return false;
}
void MachineLICMBase::ProcessMI(MachineInstr *MI,
BitVector &PhysRegDefs,
BitVector &PhysRegClobbers,
SmallSet<int, 32> &StoredFIs,
SmallVectorImpl<CandidateInfo> &Candidates) {
bool RuledOut = false;
bool HasNonInvariantUse = false;
unsigned Def = 0;
for (const MachineOperand &MO : MI->operands()) {
if (MO.isFI()) {
int FI = MO.getIndex();
if (!StoredFIs.count(FI) &&
MFI->isSpillSlotObjectIndex(FI) &&
InstructionStoresToFI(MI, FI))
StoredFIs.insert(FI);
HasNonInvariantUse = true;
continue;
}
if (MO.isRegMask()) {
PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
continue;
}
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (!Reg)
continue;
assert(Register::isPhysicalRegister(Reg) &&
"Not expecting virtual register!");
if (!MO.isDef()) {
if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
HasNonInvariantUse = true;
continue;
}
if (MO.isImplicit()) {
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
PhysRegClobbers.set(*AI);
if (!MO.isDead())
RuledOut = true;
continue;
}
if (Def)
RuledOut = true;
else
Def = Reg;
for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
if (PhysRegDefs.test(*AS))
PhysRegClobbers.set(*AS);
}
for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS)
PhysRegDefs.set(*AS);
if (PhysRegClobbers.test(Reg))
RuledOut = true;
}
if (Def && !RuledOut) {
int FI = std::numeric_limits<int>::min();
if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
(TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
Candidates.push_back(CandidateInfo(MI, Def, FI));
}
}
void MachineLICMBase::HoistRegionPostRA() {
MachineBasicBlock *Preheader = getCurPreheader();
if (!Preheader)
return;
unsigned NumRegs = TRI->getNumRegs();
BitVector PhysRegDefs(NumRegs); BitVector PhysRegClobbers(NumRegs);
SmallVector<CandidateInfo, 32> Candidates;
SmallSet<int, 32> StoredFIs;
for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
const MachineLoop *ML = MLI->getLoopFor(BB);
if (ML && ML->getHeader()->isEHPad()) continue;
for (const auto &LI : BB->liveins()) {
for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
PhysRegDefs.set(*AI);
}
SpeculationState = SpeculateUnknown;
for (MachineInstr &MI : *BB)
ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
}
BitVector TermRegs(NumRegs);
MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
if (TI != Preheader->end()) {
for (const MachineOperand &MO : TI->operands()) {
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (!Reg)
continue;
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
TermRegs.set(*AI);
}
}
for (CandidateInfo &Candidate : Candidates) {
if (Candidate.FI != std::numeric_limits<int>::min() &&
StoredFIs.count(Candidate.FI))
continue;
unsigned Def = Candidate.Def;
if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
bool Safe = true;
MachineInstr *MI = Candidate.MI;
for (const MachineOperand &MO : MI->operands()) {
if (!MO.isReg() || MO.isDef() || !MO.getReg())
continue;
Register Reg = MO.getReg();
if (PhysRegDefs.test(Reg) ||
PhysRegClobbers.test(Reg)) {
Safe = false;
break;
}
}
if (Safe)
HoistPostRA(MI, Candidate.Def);
}
}
}
void MachineLICMBase::AddToLiveIns(MCRegister Reg) {
for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
if (!BB->isLiveIn(Reg))
BB->addLiveIn(Reg);
for (MachineInstr &MI : *BB) {
for (MachineOperand &MO : MI.operands()) {
if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
MO.setIsKill(false);
}
}
}
}
void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
MachineBasicBlock *Preheader = getCurPreheader();
LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
<< " from " << printMBBReference(*MI->getParent()) << ": "
<< *MI);
MachineBasicBlock *MBB = MI->getParent();
Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
assert(!MI->isDebugInstr() && "Should not hoist debug inst");
MI->setDebugLoc(DebugLoc());
AddToLiveIns(Def);
++NumPostRAHoisted;
Changed = true;
}
bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
if (SpeculationState != SpeculateUnknown)
return SpeculationState == SpeculateFalse;
if (BB != CurLoop->getHeader()) {
SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
SpeculationState = SpeculateTrue;
return false;
}
}
SpeculationState = SpeculateFalse;
return true;
}
bool MachineLICMBase::isTriviallyReMaterializable(
const MachineInstr &MI) const {
if (!TII->isTriviallyReMaterializable(MI))
return false;
for (const MachineOperand &MO : MI.operands()) {
if (MO.isReg() && MO.isUse() && MO.getReg().isVirtual())
return false;
}
return true;
}
void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
BackTrace.push_back(RegPressure);
}
void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
BackTrace.pop_back();
}
void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
const DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
if (OpenChildren[Node])
return;
for(;;) {
ExitScope(Node->getBlock());
MachineDomTreeNode *Parent = ParentMap.lookup(Node);
if (!Parent || --OpenChildren[Parent] != 0)
break;
Node = Parent;
}
}
void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
MachineBasicBlock *Preheader = getCurPreheader();
if (!Preheader)
return;
SmallVector<MachineDomTreeNode*, 32> Scopes;
SmallVector<MachineDomTreeNode*, 8> WorkList;
DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
WorkList.push_back(HeaderN);
while (!WorkList.empty()) {
MachineDomTreeNode *Node = WorkList.pop_back_val();
assert(Node && "Null dominator tree node?");
MachineBasicBlock *BB = Node->getBlock();
const MachineLoop *ML = MLI->getLoopFor(BB);
if (ML && ML->getHeader()->isEHPad())
continue;
if (!CurLoop->contains(BB))
continue;
Scopes.push_back(Node);
unsigned NumChildren = Node->getNumChildren();
if (BB->succ_size() >= 25)
NumChildren = 0;
OpenChildren[Node] = NumChildren;
if (NumChildren) {
for (MachineDomTreeNode *Child : reverse(Node->children())) {
ParentMap[Child] = Node;
WorkList.push_back(Child);
}
}
}
if (Scopes.size() == 0)
return;
RegSeen.clear();
BackTrace.clear();
InitRegPressure(Preheader);
for (MachineDomTreeNode *Node : Scopes) {
MachineBasicBlock *MBB = Node->getBlock();
EnterScope(MBB);
SpeculationState = SpeculateUnknown;
for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
if (!Hoist(&MI, Preheader))
UpdateRegPressure(&MI);
}
ExitScopeIfDone(Node, OpenChildren, ParentMap);
}
}
static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
}
void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
std::fill(RegPressure.begin(), RegPressure.end(), 0);
if (BB->pred_size() == 1) {
MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
SmallVector<MachineOperand, 4> Cond;
if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
InitRegPressure(*BB->pred_begin());
}
for (const MachineInstr &MI : *BB)
UpdateRegPressure(&MI, true);
}
void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
bool ConsiderUnseenAsDef) {
auto Cost = calcRegisterCost(MI, true, ConsiderUnseenAsDef);
for (const auto &RPIdAndCost : Cost) {
unsigned Class = RPIdAndCost.first;
if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
RegPressure[Class] = 0;
else
RegPressure[Class] += RPIdAndCost.second;
}
}
DenseMap<unsigned, int>
MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
bool ConsiderUnseenAsDef) {
DenseMap<unsigned, int> Cost;
if (MI->isImplicitDef())
return Cost;
for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (!MO.isReg() || MO.isImplicit())
continue;
Register Reg = MO.getReg();
if (!Register::isVirtualRegister(Reg))
continue;
bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
const TargetRegisterClass *RC = MRI->getRegClass(Reg);
RegClassWeight W = TRI->getRegClassWeight(RC);
int RCCost = 0;
if (MO.isDef())
RCCost = W.RegWeight;
else {
bool isKill = isOperandKill(MO, MRI);
if (isNew && !isKill && ConsiderUnseenAsDef)
RCCost = W.RegWeight;
else if (!isNew && isKill)
RCCost = -W.RegWeight;
}
if (RCCost == 0)
continue;
const int *PS = TRI->getRegClassPressureSets(RC);
for (; *PS != -1; ++PS) {
if (Cost.find(*PS) == Cost.end())
Cost[*PS] = RCCost;
else
Cost[*PS] += RCCost;
}
}
return Cost;
}
static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
assert(MI.mayLoad() && "Expected MI that loads!");
if (MI.memoperands_empty())
return true;
for (MachineMemOperand *MemOp : MI.memoperands())
if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
if (PSV->isGOT() || PSV->isConstantPool())
return true;
return false;
}
static bool isInvariantStore(const MachineInstr &MI,
const TargetRegisterInfo *TRI,
const MachineRegisterInfo *MRI) {
bool FoundCallerPresReg = false;
if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
(MI.getNumOperands() == 0))
return false;
for (const MachineOperand &MO : MI.operands()) {
if (MO.isReg()) {
Register Reg = MO.getReg();
if (Register::isVirtualRegister(Reg))
Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
if (Register::isVirtualRegister(Reg))
return false;
if (!TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *MI.getMF()))
return false;
else
FoundCallerPresReg = true;
} else if (!MO.isImm()) {
return false;
}
}
return FoundCallerPresReg;
}
static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
const MachineRegisterInfo *MRI,
const TargetRegisterInfo *TRI) {
if (!MI.isCopy())
return false;
const MachineFunction *MF = MI.getMF();
Register CopySrcReg = MI.getOperand(1).getReg();
if (Register::isVirtualRegister(CopySrcReg))
return false;
if (!TRI->isCallerPreservedPhysReg(CopySrcReg.asMCReg(), *MF))
return false;
Register CopyDstReg = MI.getOperand(0).getReg();
assert(Register::isVirtualRegister(CopyDstReg) &&
"copy dst is not a virtual reg");
for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
return true;
}
return false;
}
bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
bool DontMoveAcrossStore = true;
if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
!(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
LLVM_DEBUG(dbgs() << "LICM: Instruction not safe to move.\n");
return false;
}
if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
!IsGuaranteedToExecute(I.getParent())) {
LLVM_DEBUG(dbgs() << "LICM: Load not guaranteed to execute.\n");
return false;
}
if (I.isConvergent())
return false;
if (!TII->shouldHoist(I, CurLoop))
return false;
return true;
}
bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
if (!IsLICMCandidate(I)) {
LLVM_DEBUG(dbgs() << "LICM: Instruction not a LICM candidate\n");
return false;
}
return CurLoop->isLoopInvariant(I);
}
bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
SmallVector<const MachineInstr*, 8> Work(1, MI);
do {
MI = Work.pop_back_val();
for (const MachineOperand &MO : MI->operands()) {
if (!MO.isReg() || !MO.isDef())
continue;
Register Reg = MO.getReg();
if (!Register::isVirtualRegister(Reg))
continue;
for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
if (UseMI.isPHI()) {
if (CurLoop->contains(&UseMI))
return true;
if (isExitBlock(UseMI.getParent()))
return true;
continue;
}
if (UseMI.isCopy() && CurLoop->contains(&UseMI))
Work.push_back(&UseMI);
}
}
} while (!Work.empty());
return false;
}
bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
Register Reg) const {
if (MRI->use_nodbg_empty(Reg))
return false;
for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
if (UseMI.isCopyLike())
continue;
if (!CurLoop->contains(UseMI.getParent()))
continue;
for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = UseMI.getOperand(i);
if (!MO.isReg() || !MO.isUse())
continue;
Register MOReg = MO.getReg();
if (MOReg != Reg)
continue;
if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
return true;
}
break;
}
return false;
}
bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
return true;
bool isCheap = false;
unsigned NumDefs = MI.getDesc().getNumDefs();
for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
MachineOperand &DefMO = MI.getOperand(i);
if (!DefMO.isReg() || !DefMO.isDef())
continue;
--NumDefs;
Register Reg = DefMO.getReg();
if (Register::isPhysicalRegister(Reg))
continue;
if (!TII->hasLowDefLatency(SchedModel, MI, i))
return false;
isCheap = true;
}
return isCheap;
}
bool
MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
bool CheapInstr) {
for (const auto &RPIdAndCost : Cost) {
if (RPIdAndCost.second <= 0)
continue;
unsigned Class = RPIdAndCost.first;
int Limit = RegLimit[Class];
if (CheapInstr && !HoistCheapInsts)
return true;
for (const auto &RP : BackTrace)
if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
return true;
}
return false;
}
void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
auto Cost = calcRegisterCost(MI, false,
false);
for (auto &RP : BackTrace)
for (const auto &RPIdAndCost : Cost)
RP[RPIdAndCost.first] += RPIdAndCost.second;
}
bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
if (MI.isImplicitDef())
return true;
if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI))
return true;
bool CheapInstr = IsCheapInstruction(MI);
bool CreatesCopy = HasLoopPHIUse(&MI);
if (CheapInstr && CreatesCopy) {
LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
return false;
}
if (isTriviallyReMaterializable(MI))
return true;
for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI.getOperand(i);
if (!MO.isReg() || MO.isImplicit())
continue;
Register Reg = MO.getReg();
if (!Register::isVirtualRegister(Reg))
continue;
if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
++NumHighLatency;
return true;
}
}
auto Cost = calcRegisterCost(&MI, false,
false);
if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
++NumLowRP;
return true;
}
if (CreatesCopy) {
LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
return false;
}
if (AvoidSpeculation &&
(!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
return false;
}
if (!isTriviallyReMaterializable(MI) &&
!MI.isDereferenceableInvariantLoad()) {
LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
return false;
}
return true;
}
MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
if (MI->canFoldAsLoad())
return nullptr;
if (!MI->isDereferenceableInvariantLoad())
return nullptr;
unsigned LoadRegIndex;
unsigned NewOpc =
TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
true,
false,
&LoadRegIndex);
if (NewOpc == 0) return nullptr;
const MCInstrDesc &MID = TII->get(NewOpc);
MachineFunction &MF = *MI->getMF();
const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Register Reg = MRI->createVirtualRegister(RC);
SmallVector<MachineInstr *, 2> NewMIs;
bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
true,
false, NewMIs);
(void)Success;
assert(Success &&
"unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
"succeeded!");
assert(NewMIs.size() == 2 &&
"Unfolded a load into multiple instructions!");
MachineBasicBlock *MBB = MI->getParent();
MachineBasicBlock::iterator Pos = MI;
MBB->insert(Pos, NewMIs[0]);
MBB->insert(Pos, NewMIs[1]);
if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
NewMIs[0]->eraseFromParent();
NewMIs[1]->eraseFromParent();
return nullptr;
}
UpdateRegPressure(NewMIs[1]);
if (MI->shouldUpdateCallSiteInfo())
MF.eraseCallSiteInfo(MI);
MI->eraseFromParent();
return NewMIs[0];
}
void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
for (MachineInstr &MI : *BB)
CSEMap[MI.getOpcode()].push_back(&MI);
}
MachineInstr *
MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
std::vector<MachineInstr *> &PrevMIs) {
for (MachineInstr *PrevMI : PrevMIs)
if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
return PrevMI;
return nullptr;
}
bool MachineLICMBase::EliminateCSE(
MachineInstr *MI,
DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI) {
if (CI == CSEMap.end() || MI->isImplicitDef())
return false;
if (MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
SmallVector<unsigned, 2> Defs;
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
assert((!MO.isReg() || MO.getReg() == 0 ||
!Register::isPhysicalRegister(MO.getReg()) ||
MO.getReg() == Dup->getOperand(i).getReg()) &&
"Instructions with different phys regs are not identical!");
if (MO.isReg() && MO.isDef() &&
!Register::isPhysicalRegister(MO.getReg()))
Defs.push_back(i);
}
SmallVector<const TargetRegisterClass*, 2> OrigRCs;
for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
unsigned Idx = Defs[i];
Register Reg = MI->getOperand(Idx).getReg();
Register DupReg = Dup->getOperand(Idx).getReg();
OrigRCs.push_back(MRI->getRegClass(DupReg));
if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
for (unsigned j = 0; j != i; ++j)
MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
return false;
}
}
for (unsigned Idx : Defs) {
Register Reg = MI->getOperand(Idx).getReg();
Register DupReg = Dup->getOperand(Idx).getReg();
MRI->replaceRegWith(Reg, DupReg);
MRI->clearKillFlags(DupReg);
if (!MRI->use_nodbg_empty(DupReg))
Dup->getOperand(Idx).setIsDead(false);
}
MI->eraseFromParent();
++NumCSEed;
return true;
}
return false;
}
bool MachineLICMBase::MayCSE(MachineInstr *MI) {
unsigned Opcode = MI->getOpcode();
DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
CSEMap.find(Opcode);
if (CI == CSEMap.end() || MI->isImplicitDef())
return false;
return LookForDuplicate(MI, CI->second) != nullptr;
}
bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
MachineBasicBlock *SrcBlock = MI->getParent();
if ((DisableHoistingToHotterBlocks == UseBFI::All ||
(DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
isTgtHotterThanSrc(SrcBlock, Preheader)) {
++NumNotHoistedDueToHotness;
return false;
}
if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
MI = ExtractHoistableLoad(MI);
if (!MI) return false;
}
if (MI->mayStore())
NumStoreConst++;
LLVM_DEBUG({
dbgs() << "Hoisting " << *MI;
if (MI->getParent()->getBasicBlock())
dbgs() << " from " << printMBBReference(*MI->getParent());
if (Preheader->getBasicBlock())
dbgs() << " to " << printMBBReference(*Preheader);
dbgs() << "\n";
});
if (FirstInLoop) {
InitCSEMap(Preheader);
FirstInLoop = false;
}
unsigned Opcode = MI->getOpcode();
DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
CSEMap.find(Opcode);
if (!EliminateCSE(MI, CI)) {
Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
assert(!MI->isDebugInstr() && "Should not hoist debug inst");
MI->setDebugLoc(DebugLoc());
UpdateBackTraceRegPressure(MI);
for (MachineOperand &MO : MI->operands())
if (MO.isReg() && MO.isDef() && !MO.isDead())
MRI->clearKillFlags(MO.getReg());
if (CI != CSEMap.end())
CI->second.push_back(MI);
else
CSEMap[Opcode].push_back(MI);
}
++NumHoisted;
Changed = true;
return true;
}
MachineBasicBlock *MachineLICMBase::getCurPreheader() {
if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
return nullptr;
if (!CurPreheader) {
CurPreheader = CurLoop->getLoopPreheader();
if (!CurPreheader) {
MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
if (!Pred) {
CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
return nullptr;
}
CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
if (!CurPreheader) {
CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
return nullptr;
}
}
}
return CurPreheader;
}
bool MachineLICMBase::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
MachineBasicBlock *TgtBlock) {
uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency();
uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency();
if (!SrcBF)
return true;
double Ratio = (double)DstBF / SrcBF;
return Ratio > BlockFrequencyRatioThreshold;
}