51#define DEBUG_TYPE "machine-cse"
53STATISTIC(NumCoalesces,
"Number of copies coalesced");
54STATISTIC(NumCSEs,
"Number of common subexpression eliminated");
55STATISTIC(NumPREs,
"Number of partial redundant expression"
56 " transformed to fully redundant");
58 "Number of physreg referencing common subexpr eliminated");
60 "Number of cross-MBB physreg referencing CS eliminated");
61STATISTIC(NumCommutes,
"Number of copies coalesced after commuting");
66 cl::desc(
"Threshold for the size of CSUses"));
70 cl::desc(
"Override the profitability heuristics for Machine CSE"));
83 : DT(DT), MBFI(MBFI) {}
89 ScopedHashTableVal<MachineInstr *, unsigned>>;
91 ScopedHashTable<MachineInstr *, unsigned, MachineInstrExpressionTrait,
96 unsigned LookAheadLimit = 0;
97 DenseMap<MachineBasicBlock *, ScopeType *> ScopeMap;
98 DenseMap<MachineInstr *, MachineBasicBlock *, MachineInstrExpressionTrait>
104 bool PerformTrivialCopyPropagation(MachineInstr *
MI, MachineBasicBlock *
MBB);
105 bool isPhysDefTriviallyDead(MCRegister
Reg,
108 bool hasLivePhysRegDefUses(
const MachineInstr *
MI,
109 const MachineBasicBlock *
MBB,
110 SmallSet<MCRegister, 8> &PhysRefs,
111 PhysDefVector &PhysDefs,
bool &PhysUseDef)
const;
112 bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *
MI,
113 const SmallSet<MCRegister, 8> &PhysRefs,
114 const PhysDefVector &PhysDefs,
bool &NonLocal)
const;
115 bool isCSECandidate(MachineInstr *
MI);
118 void EnterScope(MachineBasicBlock *
MBB);
119 void ExitScope(MachineBasicBlock *
MBB);
120 bool ProcessBlockCSE(MachineBasicBlock *
MBB);
122 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren);
125 bool isPRECandidate(MachineInstr *
MI, SmallSet<MCRegister, 8> &PhysRefs);
126 bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *
MBB);
127 bool PerformSimplePRE(MachineDominatorTree *DT);
130 bool isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
131 MachineBasicBlock *
MBB, MachineBasicBlock *MBB1);
132 void releaseMemory();
139 MachineCSELegacy() : MachineFunctionPass(ID) {}
143 void getAnalysisUsage(AnalysisUsage &AU)
const override {
147 AU.
addRequired<MachineBlockFrequencyInfoWrapperPass>();
150 MachineFunctionProperties getRequiredProperties()
const override {
151 return MachineFunctionProperties().setIsSSA();
156char MachineCSELegacy::ID = 0;
161 "Machine Common Subexpression Elimination",
false,
false)
170bool MachineCSEImpl::PerformTrivialCopyPropagation(
MachineInstr *
MI,
174 Register Reg = MO.getReg();
175 if (!Reg.isVirtual())
177 bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
178 MachineInstr *DefMI = MRI->getVRegDef(Reg);
179 if (!DefMI || !DefMI->isCopy())
181 Register SrcReg = DefMI->getOperand(1).getReg();
182 if (!SrcReg.isVirtual())
196 if (DefMI->getOperand(1).getSubReg())
198 if (!MRI->constrainRegAttrs(SrcReg, Reg))
200 LLVM_DEBUG(dbgs() <<
"Coalescing: " << *DefMI);
201 LLVM_DEBUG(dbgs() <<
"*** to: " << *MI);
210 DefMI->changeDebugValuesDefReg(SrcReg);
212 DefMI->eraseFromParent();
221bool MachineCSEImpl::isPhysDefTriviallyDead(
224 unsigned LookAheadLeft = LookAheadLimit;
225 while (LookAheadLeft) {
233 bool SeenDef =
false;
234 for (
const MachineOperand &MO :
I->operands()) {
235 if (MO.isRegMask() && MO.clobbersPhysReg(
Reg))
237 if (!MO.isReg() || !MO.getReg())
239 if (!
TRI->regsOverlap(MO.getReg(),
Reg))
271 return TRI.isCallerPreservedPhysReg(
Reg, MF) ||
272 TII.isIgnorableUse(
MI, OpIdx) ||
273 (
MRI.reservedRegsFrozen() &&
MRI.isConstantPhysReg(
Reg));
280bool MachineCSEImpl::hasLivePhysRegDefUses(
const MachineInstr *
MI,
281 const MachineBasicBlock *
MBB,
282 SmallSet<MCRegister, 8> &PhysRefs,
283 PhysDefVector &PhysDefs,
284 bool &PhysUseDef)
const {
286 for (
const MachineOperand &MO :
MI->all_uses()) {
294 MI->getOperandNo(&MO), *
MI->getMF(),
296 for (MCRegAliasIterator AI(
Reg,
TRI,
true); AI.isValid(); ++AI)
305 const MachineOperand &MO = MOP.value();
320 PhysDefs.emplace_back(MOP.index(),
Reg);
324 for (
const auto &Def : PhysDefs)
325 for (MCRegAliasIterator AI(
Def.second,
TRI,
true); AI.isValid(); ++AI)
328 return !PhysRefs.
empty();
331bool MachineCSEImpl::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *
MI,
332 const SmallSet<MCRegister, 8> &PhysRefs,
333 const PhysDefVector &PhysDefs,
334 bool &NonLocal)
const {
339 const MachineBasicBlock *CSMBB = CSMI->
getParent();
341 bool CrossMBB =
false;
346 for (
const auto &PhysDef : PhysDefs) {
357 unsigned LookAheadLeft = LookAheadLimit;
358 while (LookAheadLeft) {
360 while (
I !=
E &&
I != EE &&
I->isDebugInstr())
364 assert(CrossMBB &&
"Reaching end-of-MBB without finding MI?");
376 for (
const MachineOperand &MO :
I->operands()) {
397bool MachineCSEImpl::isCSECandidate(MachineInstr *
MI) {
398 if (
MI->isPosition() ||
MI->isPHI() ||
MI->isImplicitDef() ||
MI->isKill() ||
399 MI->isInlineAsm() ||
MI->isDebugInstr() ||
MI->isJumpTableDebugInfo() ||
404 if (
MI->isCopyLike())
408 if (
MI->mayStore() ||
MI->isCall() ||
MI->isTerminator() ||
409 MI->mayRaiseFPException() ||
MI->hasUnmodeledSideEffects())
416 if (!
MI->isDereferenceableInvariantLoad())
425 if (
MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
435 MachineBasicBlock *CSBB,
444 bool MayIncreasePressure =
true;
446 MayIncreasePressure =
false;
447 SmallPtrSet<MachineInstr*, 8> CSUses;
454 MayIncreasePressure =
true;
458 if (!MayIncreasePressure)
461 MayIncreasePressure =
true;
466 if (!MayIncreasePressure)
return true;
472 MachineBasicBlock *BB =
MI->getParent();
479 bool HasVRegUse =
false;
480 for (
const MachineOperand &MO :
MI->all_uses()) {
487 bool HasNonCopyUse =
false;
490 if (!
MI.isCopyLike()) {
491 HasNonCopyUse =
true;
503 HasPHI |=
UseMI.isPHI();
511void MachineCSEImpl::EnterScope(MachineBasicBlock *
MBB) {
513 ScopeType *
Scope =
new ScopeType(VNT);
517void MachineCSEImpl::ExitScope(MachineBasicBlock *
MBB) {
519 auto SI = ScopeMap.find(
MBB);
520 assert(SI != ScopeMap.end());
525bool MachineCSEImpl::ProcessBlockCSE(MachineBasicBlock *
MBB) {
529 SmallVector<unsigned, 2> ImplicitDefsToUpdate;
532 if (!isCSECandidate(&
MI))
535 bool FoundCSE = VNT.
count(&
MI);
538 if (PerformTrivialCopyPropagation(&
MI,
MBB)) {
551 bool Commuted =
false;
552 if (!FoundCSE &&
MI.isCommutable()) {
553 if (MachineInstr *NewMI =
TII->commuteInstruction(
MI)) {
555 FoundCSE = VNT.
count(NewMI);
558 NewMI->eraseFromParent();
560 }
else if (!FoundCSE)
562 (void)
TII->commuteInstruction(
MI);
569 bool CrossMBBPhysDef =
false;
570 SmallSet<MCRegister, 8> PhysRefs;
571 PhysDefVector PhysDefs;
572 bool PhysUseDef =
false;
574 hasLivePhysRegDefUses(&
MI,
MBB, PhysRefs, PhysDefs, PhysUseDef)) {
584 MachineInstr *CSMI = Exps[CSVN];
585 if (PhysRegDefsReach(CSMI, &
MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
598 MachineInstr *CSMI = Exps[CSVN];
600 LLVM_DEBUG(
dbgs() <<
"*** Found a common subexpression: " << *CSMI);
611 if (
MI.isConvergent() &&
MI.getParent() != CSMI->
getParent()) {
612 LLVM_DEBUG(
dbgs() <<
"*** Convergent MI and subexpression exist in "
613 "different BBs, avoid CSE!\n");
621 unsigned NumDefs =
MI.getNumDefs();
623 for (
unsigned i = 0, e =
MI.getNumOperands(); NumDefs && i != e; ++i) {
624 MachineOperand &MO =
MI.getOperand(i);
640 if (OldReg == NewReg) {
646 "Do not CSE physical register defs!");
648 if (!isProfitableToCSE(NewReg, OldReg, CSMI->
getParent(), &
MI)) {
659 dbgs() <<
"*** Not the same register constraints, avoid CSE!\n");
670 for (
const std::pair<Register, Register> &CSEPair : CSEPairs) {
675 assert(Def !=
nullptr &&
"CSEd register has no unique definition?");
676 Def->clearRegisterDeads(NewReg);
682 for (
unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
684 for (
const auto &PhysDef : PhysDefs)
685 if (!
MI.getOperand(PhysDef.first).isDead())
700 for (
auto ImplicitDef : ImplicitDefs)
701 if (MachineOperand *MO =
II->findRegisterUseOperand(
702 ImplicitDef,
TRI,
true))
707 for (
auto ImplicitDef : ImplicitDefs)
711 if (CrossMBBPhysDef) {
714 while (!PhysDefs.empty()) {
715 auto LiveIn = PhysDefs.pop_back_val();
722 MI.eraseFromParent();
724 if (!PhysRefs.
empty())
734 ImplicitDefsToUpdate.clear();
735 ImplicitDefs.clear();
744void MachineCSEImpl::ExitScopeIfDone(
746 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren) {
747 if (OpenChildren[Node])
751 ExitScope(
Node->getBlock());
755 unsigned Left = --OpenChildren[Parent];
758 ExitScope(Parent->getBlock());
766 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
775 size_t WorkListSize = WorkList.
size();
777 OpenChildren[
Node] = WorkList.
size() - WorkListSize;
778 }
while (!WorkList.
empty());
783 MachineBasicBlock *
MBB =
Node->getBlock();
787 ExitScopeIfDone(Node, OpenChildren);
796bool MachineCSEImpl::isPRECandidate(MachineInstr *
MI,
797 SmallSet<MCRegister, 8> &PhysRefs) {
798 if (!isCSECandidate(
MI) ||
799 MI->isNotDuplicable() ||
802 MI->getNumDefs() != 1 ||
803 MI->getNumExplicitDefs() != 1)
806 for (
const MachineOperand &MO :
MI->operands()) {
818bool MachineCSEImpl::ProcessBlockPRE(MachineDominatorTree *DT,
819 MachineBasicBlock *
MBB) {
822 SmallSet<MCRegister, 8> PhysRefs;
823 if (!isPRECandidate(&
MI, PhysRefs))
830 auto *MBB1 = It->second;
833 "MBB cannot properly dominate MBB1 while DFS through dominators tree!");
835 if (!CMBB->isLegalToHoistInto())
838 if (!isProfitableToHoistInto(CMBB,
MBB, MBB1))
845 if (BB !=
nullptr && BB1 !=
nullptr &&
855 if (
MI.isConvergent() && CMBB !=
MBB)
861 PhysDefVector PhysDefs;
862 if (!PhysRefs.
empty() &&
863 !PhysRegDefsReach(&*(CMBB->getFirstTerminator()), &
MI, PhysRefs,
868 "First operand of instr with one explicit def must be this def");
871 if (!isProfitableToCSE(NewReg, VReg, CMBB, &
MI))
873 MachineInstr &NewMI =
874 TII->duplicate(*CMBB, CMBB->getFirstTerminator(),
MI);
898bool MachineCSEImpl::PerformSimplePRE(MachineDominatorTree *DT) {
908 MachineBasicBlock *
MBB =
Node->getBlock();
911 }
while (!BBs.
empty());
916bool MachineCSEImpl::isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
917 MachineBasicBlock *
MBB,
918 MachineBasicBlock *MBB1) {
923 "CandidateBB should dominate MBB1");
928void MachineCSEImpl::releaseMemory() {
938 LookAheadLimit =
TII->getMachineCSELookAheadLimit();
939 bool ChangedPRE, ChangedCSE;
940 ChangedPRE = PerformSimplePRE(DT);
943 return ChangedPRE || ChangedCSE;
953 MachineCSEImpl Impl(&MDT, &MBFI);
968 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
970 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
971 MachineCSEImpl Impl(&MDT, &MBFI);
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
const HexagonInstrInfo * TII
static cl::opt< int > CSUsesThreshold("csuses-threshold", cl::Hidden, cl::init(1024), cl::desc("Threshold for the size of CSUses"))
static cl::opt< bool > AggressiveMachineCSE("aggressive-machine-cse", cl::Hidden, cl::init(false), cl::desc("Override the profitability heuristics for Machine CSE"))
static bool isCallerPreservedOrConstPhysReg(MCRegister Reg, const MachineInstr &MI, unsigned OpIdx, const MachineFunction &MF, const TargetRegisterInfo &TRI, const TargetInstrInfo &TII)
Register const TargetRegisterInfo * TRI
Promote Memory to Register
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Represents analyses that only rely on functions' control flow.
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
bool isAsCheapAsAMove(const MachineInstr &MI) const override
Wrapper class representing physical registers. Should be passed by value.
An RAII based helper class to modify MachineFunctionProperties when running pass.
unsigned pred_size() const
MachineInstrBundleIterator< const MachineInstr > const_iterator
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
pred_iterator pred_begin()
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
const MachineOperand & getOperand(unsigned i) const
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
LLVM_ABI Register cloneVirtualRegister(Register VReg, StringRef Name="")
Create and return a new virtual register in the function with the same attributes as the given regist...
LLVM_ABI bool constrainRegAttrs(Register Reg, Register ConstrainingReg, unsigned MinNumRegs=0)
Constrain the register class or the register bank of the virtual register Reg (and low-level type) to...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
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.
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
size_type count(const K &Key) const
Return 1 if the specified key is in the table, 0 otherwise.
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
ScopedHashTableScope< MachineInstr *, unsigned, MachineInstrExpressionTrait, AllocatorTy > ScopeTy
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< DefNode * > Def
NodeAddr< NodeBase * > Node
This is an optimization pass for GlobalISel generic memory operations.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
LLVM_ABI char & MachineCSELegacyID
MachineCSE - This pass performs global CSE on machine instructions.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.