30 #define DEBUG_TYPE "branch-coalescing"
34 cl::desc(
"enable coalescing of duplicate branches"));
36 STATISTIC(NumBlocksCoalesced,
"Number of blocks coalesced");
37 STATISTIC(NumPHINotMoved,
"Number of PHI Nodes that cannot be merged");
38 STATISTIC(NumBlocksNotCoalesced,
"Number of blocks not coalesced");
136 struct CoalescingCandidateInfo {
144 CoalescingCandidateInfo();
154 bool canCoalesceBranch(CoalescingCandidateInfo &Cand);
157 bool validateCandidates(CoalescingCandidateInfo &SourceRegion,
158 CoalescingCandidateInfo &TargetRegion)
const;
160 static bool isBranchCoalescingEnabled() {
177 StringRef getPassName()
const override {
return "Branch Coalescing"; }
179 bool mergeCandidates(CoalescingCandidateInfo &SourceRegion,
180 CoalescingCandidateInfo &TargetRegion);
185 bool canMerge(CoalescingCandidateInfo &SourceRegion,
186 CoalescingCandidateInfo &TargetRegion)
const;
197 "Branch Coalescing",
false,
false)
203 BranchCoalescing::CoalescingCandidateInfo::CoalescingCandidateInfo()
204 : BranchBlock(
nullptr), BranchTargetBlock(
nullptr),
205 FallThroughBlock(
nullptr), MustMoveDown(false), MustMoveUp(false) {}
208 BranchBlock =
nullptr;
209 BranchTargetBlock =
nullptr;
210 FallThroughBlock =
nullptr;
212 MustMoveDown =
false;
217 MDT = &getAnalysis<MachineDominatorTree>();
218 MPDT = &getAnalysis<MachinePostDominatorTree>();
233 bool BranchCoalescing::canCoalesceBranch(CoalescingCandidateInfo &Cand) {
234 DEBUG(
dbgs() <<
"Determine if branch block " << Cand.BranchBlock->getNumber()
235 <<
" can be coalesced:");
238 if (TII->analyzeBranch(*Cand.BranchBlock, Cand.BranchTargetBlock, FalseMBB,
240 DEBUG(
dbgs() <<
"TII unable to Analyze Branch - skip\n");
244 for (
auto &
I : Cand.BranchBlock->terminators()) {
245 DEBUG(
dbgs() <<
"Looking at terminator : " <<
I <<
"\n");
249 if (
I.getNumOperands() !=
I.getNumExplicitOperands()) {
250 DEBUG(
dbgs() <<
"Terminator contains implicit operands - skip : " <<
I
256 if (Cand.BranchBlock->isEHPad() || Cand.BranchBlock->hasEHPadSuccessor()) {
263 if (!Cand.BranchTargetBlock || FalseMBB ||
264 !Cand.BranchBlock->isSuccessor(Cand.BranchTargetBlock)) {
265 DEBUG(
dbgs() <<
"Does not form a triangle - skip\n");
270 if (Cand.BranchBlock->succ_size() != 2) {
271 DEBUG(
dbgs() <<
"Does not have 2 successors - skip\n");
276 assert(Cand.BranchBlock->canFallThrough() &&
277 "Expecting the block to fall through!");
283 (*Cand.BranchBlock->succ_begin() == Cand.BranchTargetBlock)
284 ? *Cand.BranchBlock->succ_rbegin()
285 : *Cand.BranchBlock->succ_begin();
287 assert(Succ &&
"Expecting a valid fall-through block\n");
289 if (!Succ->empty()) {
290 DEBUG(
dbgs() <<
"Fall-through block contains code -- skip\n");
294 if (!Succ->isSuccessor(Cand.BranchTargetBlock)) {
296 <<
"Successor of fall through block is not branch taken block\n");
300 Cand.FallThroughBlock = Succ;
312 bool BranchCoalescing::identicalOperands(
315 if (OpList1.
size() != OpList2.
size()) {
316 DEBUG(
dbgs() <<
"Operand list is different size\n");
320 for (
unsigned i = 0; i < OpList1.
size(); ++i) {
325 <<
"Op2: " << Op2 <<
"\n");
328 DEBUG(
dbgs() <<
"Op1 and Op2 are identical!\n");
340 if (TII->produceSameValue(*Op1Def, *Op2Def,
MRI)) {
341 DEBUG(
dbgs() <<
"Op1Def: " << *Op1Def <<
" and " << *Op2Def
342 <<
" produce the same value!\n");
344 DEBUG(
dbgs() <<
"Operands produce different values\n");
348 DEBUG(
dbgs() <<
"The operands are not provably identical.\n");
371 DEBUG(
dbgs() <<
"SourceMBB contains no PHI instructions.\n");
378 for (
unsigned i = 2, e = PHIInst.
getNumOperands() + 1; i != e; i += 2) {
380 if (MO.
getMBB() == SourceMBB)
397 bool BranchCoalescing::canMoveToBeginning(
const MachineInstr &MI,
401 DEBUG(
dbgs() <<
"Checking if " << MI <<
" can move to beginning of "
405 for (
auto &
Use :
MRI->use_instructions(
Def.getReg())) {
406 if (
Use.isPHI() &&
Use.getParent() == &TargetMBB) {
407 DEBUG(
dbgs() <<
" *** used in a PHI -- cannot move ***\n");
413 DEBUG(
dbgs() <<
" Safe to move to the beginning.\n");
428 bool BranchCoalescing::canMoveToEnd(
const MachineInstr &MI,
432 DEBUG(
dbgs() <<
"Checking if " << MI <<
" can move to end of "
439 DEBUG(
dbgs() <<
" *** Cannot move this instruction ***\n");
442 DEBUG(
dbgs() <<
" *** def is in another block -- safe to move!\n");
447 DEBUG(
dbgs() <<
" Safe to move to the end.\n");
460 bool BranchCoalescing::validateCandidates(
461 CoalescingCandidateInfo &SourceRegion,
462 CoalescingCandidateInfo &TargetRegion)
const {
464 if (TargetRegion.BranchTargetBlock != SourceRegion.BranchBlock)
465 llvm_unreachable(
"Expecting SourceRegion to immediately follow TargetRegion");
466 else if (!MDT->dominates(TargetRegion.BranchBlock, SourceRegion.BranchBlock))
468 else if (!MPDT->dominates(SourceRegion.BranchBlock, TargetRegion.BranchBlock))
470 else if (!TargetRegion.FallThroughBlock->empty() ||
471 !SourceRegion.FallThroughBlock->empty())
503 bool BranchCoalescing::canMerge(CoalescingCandidateInfo &SourceRegion,
504 CoalescingCandidateInfo &TargetRegion)
const {
505 if (!validateCandidates(SourceRegion, TargetRegion))
511 I = SourceRegion.BranchBlock->instr_begin(),
512 E = SourceRegion.BranchBlock->getFirstNonPHI();
514 for (
auto &
Def :
I->defs())
515 for (
auto &
Use :
MRI->use_instructions(
Def.getReg())) {
516 if (
Use.isPHI() &&
Use.getParent() == SourceRegion.BranchTargetBlock) {
517 DEBUG(
dbgs() <<
"PHI " << *
I <<
" defines register used in another "
518 "PHI within branch target block -- can't merge\n");
522 if (
Use.getParent() == SourceRegion.BranchBlock) {
524 <<
" defines register used in this "
525 "block -- all must move down\n");
526 SourceRegion.MustMoveDown =
true;
534 I = SourceRegion.BranchBlock->getFirstNonPHI(),
535 E = SourceRegion.BranchBlock->end();
537 if (!canMoveToBeginning(*
I, *SourceRegion.BranchTargetBlock)) {
539 <<
" cannot move down - must move up!\n");
540 SourceRegion.MustMoveUp =
true;
542 if (!canMoveToEnd(*
I, *TargetRegion.BranchBlock)) {
544 <<
" cannot move up - must move down!\n");
545 SourceRegion.MustMoveDown =
true;
549 return (SourceRegion.MustMoveUp && SourceRegion.MustMoveDown) ?
false :
true;
608 bool BranchCoalescing::mergeCandidates(CoalescingCandidateInfo &SourceRegion,
609 CoalescingCandidateInfo &TargetRegion) {
611 if (SourceRegion.MustMoveUp && SourceRegion.MustMoveDown) {
616 if (!validateCandidates(SourceRegion, TargetRegion))
621 moveAndUpdatePHIs(SourceRegion.BranchBlock, SourceRegion.BranchTargetBlock);
626 SourceRegion.BranchBlock->getFirstNonPHI();
628 SourceRegion.BranchBlock->getFirstTerminator();
631 ? SourceRegion.BranchTargetBlock
632 : TargetRegion.BranchBlock;
635 SourceRegion.MustMoveDown
636 ? SourceRegion.BranchTargetBlock->getFirstNonPHI()
637 : TargetRegion.BranchBlock->getFirstTerminator();
639 Source->
splice(Target, SourceRegion.BranchBlock, firstInstr, lastInstr);
646 SourceRegion.BranchBlock->removeSuccessor(SourceRegion.FallThroughBlock);
647 TargetRegion.BranchBlock->transferSuccessorsAndUpdatePHIs(
648 SourceRegion.BranchBlock);
652 TargetRegion.BranchBlock->ReplaceUsesOfBlockWith(
653 SourceRegion.BranchBlock, SourceRegion.BranchTargetBlock);
656 SourceRegion.BranchBlock->terminators().begin();
657 while (I != SourceRegion.BranchBlock->terminators().end()) {
666 assert(TargetRegion.FallThroughBlock->empty() &&
667 "FallThroughBlocks should be empty!");
671 TargetRegion.FallThroughBlock->transferSuccessorsAndUpdatePHIs(
672 SourceRegion.FallThroughBlock);
673 TargetRegion.FallThroughBlock->removeSuccessor(SourceRegion.BranchBlock);
676 assert(SourceRegion.BranchBlock->empty() &&
677 "Expecting branch block to be empty!");
678 SourceRegion.BranchBlock->eraseFromParent();
680 assert(SourceRegion.FallThroughBlock->empty() &&
681 "Expecting fall-through block to be empty!\n");
682 SourceRegion.FallThroughBlock->eraseFromParent();
684 NumBlocksCoalesced++;
691 !isBranchCoalescingEnabled())
694 bool didSomething =
false;
696 DEBUG(
dbgs() <<
"******** Branch Coalescing ********\n");
701 CoalescingCandidateInfo Cand1, Cand2;
706 bool MergedCandidates =
false;
708 MergedCandidates =
false;
712 Cand1.BranchBlock = &MBB;
715 if (!canCoalesceBranch(Cand1))
718 Cand2.BranchBlock = Cand1.BranchTargetBlock;
719 if (!canCoalesceBranch(Cand2))
725 assert(MPDT->dominates(Cand2.BranchTargetBlock, Cand1.BranchBlock) &&
726 "Branch-taken block should post-dominate first candidate");
728 if (!identicalOperands(Cand1.Cond, Cand2.Cond)) {
729 DEBUG(
dbgs() <<
"Blocks " << Cand1.BranchBlock->getNumber() <<
" and "
730 << Cand2.BranchBlock->getNumber()
731 <<
" have different branches\n");
734 if (!canMerge(Cand2, Cand1)) {
735 DEBUG(
dbgs() <<
"Cannot merge blocks " << Cand1.BranchBlock->getNumber()
736 <<
" and " << Cand2.BranchBlock->getNumber() <<
"\n");
737 NumBlocksNotCoalesced++;
740 DEBUG(
dbgs() <<
"Merging blocks " << Cand1.BranchBlock->getNumber()
741 <<
" and " << Cand1.BranchTargetBlock->getNumber() <<
"\n");
742 MergedCandidates = mergeCandidates(Cand2, Cand1);
743 if (MergedCandidates)
746 DEBUG(
dbgs() <<
"Function after merging: "; MF.dump();
dbgs() <<
"\n");
747 }
while (MergedCandidates);
753 MF.verify(
nullptr,
"Error in code produced by branch coalescing");
756 DEBUG(
dbgs() <<
"Finished Branch Coalescing\n");
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
STATISTIC(NumFunctions,"Total number of functions")
iterator_range< mop_iterator > uses()
Returns a range that includes all operands that are register uses.
MachineBasicBlock * getMBB() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
A Use represents the edge between a Value definition and its users.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
char & BranchCoalescingID
This pass combine basic blocks guarded by the same branch.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
INITIALIZE_PASS_BEGIN(BranchCoalescing, DEBUG_TYPE,"Branch Coalescing", false, false) INITIALIZE_PASS_END(BranchCoalescing
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void initializeBranchCoalescingPass(PassRegistry &)
size_t size() const
size - Get the array size.
const MachineBasicBlock * getParent() const
TargetInstrInfo - Interface to description of machine instruction set.
unsigned const MachineRegisterInfo * MRI
const MachineOperand & getOperand(unsigned i) const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void setMBB(MachineBasicBlock *MBB)
Represent the analysis usage information of a pass.
iterator_range< mop_iterator > defs()
Returns a range over all explicit operands that are register definitions.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Target - Wrapper for Target specific information.
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, ArrayRef< StringRef > StandardNames)
initialize - Initialize the set of available library functions based on the specified target triple...
static void clear(coro::Shape &Shape)
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
static cl::opt< cl::boolOrDefault > EnableBranchCoalescing("enable-branch-coalesce", cl::Hidden, cl::desc("enable coalescing of duplicate branches"))
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual const TargetInstrInfo * getInstrInfo() const
StringRef - Represent a constant reference to a string, i.e.
bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...