1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass forwards branches to unconditional branches to make them branch
11 // directly to the target block.  This pass often results in dead MBB's, which
12 // it then removes.
13 //
14 // Note that this pass must be run after register allocation, it cannot handle
15 // SSA form. It also must handle virtual registers for targets that emit virtual
16 // ISA (e.g. NVPTX).
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "BranchFolding.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/TargetPassConfig.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include <algorithm>
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "branchfolding"
47 
48 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
49 STATISTIC(NumBranchOpts, "Number of branches optimized");
50 STATISTIC(NumTailMerge , "Number of block tails merged");
51 STATISTIC(NumHoist     , "Number of times common instructions are hoisted");
52 STATISTIC(NumTailCalls,  "Number of tail calls optimized");
53 
54 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
55                               cl::init(cl::BOU_UNSET), cl::Hidden);
56 
57 // Throttle for huge numbers of predecessors (compile speed problems)
58 static cl::opt<unsigned>
59 TailMergeThreshold("tail-merge-threshold",
60           cl::desc("Max number of predecessors to consider tail merging"),
61           cl::init(150), cl::Hidden);
62 
63 // Heuristic for tail merging (and, inversely, tail duplication).
64 // TODO: This should be replaced with a target query.
65 static cl::opt<unsigned>
66 TailMergeSize("tail-merge-size",
67           cl::desc("Min number of instructions to consider tail merging"),
68                               cl::init(3), cl::Hidden);
69 
70 namespace {
71   /// BranchFolderPass - Wrap branch folder in a machine function pass.
72   class BranchFolderPass : public MachineFunctionPass {
73   public:
74     static char ID;
75     explicit BranchFolderPass(): MachineFunctionPass(ID) {}
76 
77     bool runOnMachineFunction(MachineFunction &MF) override;
78 
79     void getAnalysisUsage(AnalysisUsage &AU) const override {
80       AU.addRequired<MachineBlockFrequencyInfo>();
81       AU.addRequired<MachineBranchProbabilityInfo>();
82       AU.addRequired<TargetPassConfig>();
83       MachineFunctionPass::getAnalysisUsage(AU);
84     }
85   };
86 }
87 
88 char BranchFolderPass::ID = 0;
89 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
90 
91 INITIALIZE_PASS(BranchFolderPass, "branch-folder",
92                 "Control Flow Optimizer", false, false)
93 
94 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
95   if (skipFunction(*MF.getFunction()))
96     return false;
97 
98   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
99   // TailMerge can create jump into if branches that make CFG irreducible for
100   // HW that requires structurized CFG.
101   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
102                          PassConfig->getEnableTailMerge();
103   BranchFolder::MBFIWrapper MBBFreqInfo(
104       getAnalysis<MachineBlockFrequencyInfo>());
105   BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,
106                       getAnalysis<MachineBranchProbabilityInfo>());
107   return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
108                                  MF.getSubtarget().getRegisterInfo(),
109                                  getAnalysisIfAvailable<MachineModuleInfo>());
110 }
111 
112 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
113                            MBFIWrapper &FreqInfo,
114                            const MachineBranchProbabilityInfo &ProbInfo,
115                            unsigned MinTailLength)
116     : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
117       MBBFreqInfo(FreqInfo), MBPI(ProbInfo) {
118   if (MinCommonTailLength == 0)
119     MinCommonTailLength = TailMergeSize;
120   switch (FlagEnableTailMerge) {
121   case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
122   case cl::BOU_TRUE: EnableTailMerge = true; break;
123   case cl::BOU_FALSE: EnableTailMerge = false; break;
124   }
125 }
126 
127 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
128 /// function, updating the CFG.
129 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
130   assert(MBB->pred_empty() && "MBB must be dead!");
131   DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
132 
133   MachineFunction *MF = MBB->getParent();
134   // drop all successors.
135   while (!MBB->succ_empty())
136     MBB->removeSuccessor(MBB->succ_end()-1);
137 
138   // Avoid matching if this pointer gets reused.
139   TriedMerging.erase(MBB);
140 
141   // Remove the block.
142   MF->erase(MBB);
143   FuncletMembership.erase(MBB);
144   if (MLI)
145     MLI->removeBlock(MBB);
146 }
147 
148 /// OptimizeFunction - Perhaps branch folding, tail merging and other
149 /// CFG optimizations on the given function.  Block placement changes the layout
150 /// and may create new tail merging opportunities.
151 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
152                                     const TargetInstrInfo *tii,
153                                     const TargetRegisterInfo *tri,
154                                     MachineModuleInfo *mmi,
155                                     MachineLoopInfo *mli, bool AfterPlacement) {
156   if (!tii) return false;
157 
158   TriedMerging.clear();
159 
160   AfterBlockPlacement = AfterPlacement;
161   TII = tii;
162   TRI = tri;
163   MMI = mmi;
164   MLI = mli;
165 
166   MachineRegisterInfo &MRI = MF.getRegInfo();
167   UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);
168   if (!UpdateLiveIns)
169     MRI.invalidateLiveness();
170 
171   // Fix CFG.  The later algorithms expect it to be right.
172   bool MadeChange = false;
173   for (MachineBasicBlock &MBB : MF) {
174     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
175     SmallVector<MachineOperand, 4> Cond;
176     if (!TII->analyzeBranch(MBB, TBB, FBB, Cond, true))
177       MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
178   }
179 
180   // Recalculate funclet membership.
181   FuncletMembership = getFuncletMembership(MF);
182 
183   bool MadeChangeThisIteration = true;
184   while (MadeChangeThisIteration) {
185     MadeChangeThisIteration    = TailMergeBlocks(MF);
186     // No need to clean up if tail merging does not change anything after the
187     // block placement.
188     if (!AfterBlockPlacement || MadeChangeThisIteration)
189       MadeChangeThisIteration |= OptimizeBranches(MF);
190     if (EnableHoistCommonCode)
191       MadeChangeThisIteration |= HoistCommonCode(MF);
192     MadeChange |= MadeChangeThisIteration;
193   }
194 
195   // See if any jump tables have become dead as the code generator
196   // did its thing.
197   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
198   if (!JTI)
199     return MadeChange;
200 
201   // Walk the function to find jump tables that are live.
202   BitVector JTIsLive(JTI->getJumpTables().size());
203   for (const MachineBasicBlock &BB : MF) {
204     for (const MachineInstr &I : BB)
205       for (const MachineOperand &Op : I.operands()) {
206         if (!Op.isJTI()) continue;
207 
208         // Remember that this JT is live.
209         JTIsLive.set(Op.getIndex());
210       }
211   }
212 
213   // Finally, remove dead jump tables.  This happens when the
214   // indirect jump was unreachable (and thus deleted).
215   for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
216     if (!JTIsLive.test(i)) {
217       JTI->RemoveJumpTable(i);
218       MadeChange = true;
219     }
220 
221   return MadeChange;
222 }
223 
224 //===----------------------------------------------------------------------===//
225 //  Tail Merging of Blocks
226 //===----------------------------------------------------------------------===//
227 
228 /// HashMachineInstr - Compute a hash value for MI and its operands.
229 static unsigned HashMachineInstr(const MachineInstr &MI) {
230   unsigned Hash = MI.getOpcode();
231   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
232     const MachineOperand &Op = MI.getOperand(i);
233 
234     // Merge in bits from the operand if easy. We can't use MachineOperand's
235     // hash_code here because it's not deterministic and we sort by hash value
236     // later.
237     unsigned OperandHash = 0;
238     switch (Op.getType()) {
239     case MachineOperand::MO_Register:
240       OperandHash = Op.getReg();
241       break;
242     case MachineOperand::MO_Immediate:
243       OperandHash = Op.getImm();
244       break;
245     case MachineOperand::MO_MachineBasicBlock:
246       OperandHash = Op.getMBB()->getNumber();
247       break;
248     case MachineOperand::MO_FrameIndex:
249     case MachineOperand::MO_ConstantPoolIndex:
250     case MachineOperand::MO_JumpTableIndex:
251       OperandHash = Op.getIndex();
252       break;
253     case MachineOperand::MO_GlobalAddress:
254     case MachineOperand::MO_ExternalSymbol:
255       // Global address / external symbol are too hard, don't bother, but do
256       // pull in the offset.
257       OperandHash = Op.getOffset();
258       break;
259     default:
260       break;
261     }
262 
263     Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
264   }
265   return Hash;
266 }
267 
268 /// HashEndOfMBB - Hash the last instruction in the MBB.
269 static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
270   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
271   if (I == MBB.end())
272     return 0;
273 
274   return HashMachineInstr(*I);
275 }
276 
277 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
278 /// of instructions they actually have in common together at their end.  Return
279 /// iterators for the first shared instruction in each block.
280 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
281                                         MachineBasicBlock *MBB2,
282                                         MachineBasicBlock::iterator &I1,
283                                         MachineBasicBlock::iterator &I2) {
284   I1 = MBB1->end();
285   I2 = MBB2->end();
286 
287   unsigned TailLen = 0;
288   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
289     --I1; --I2;
290     // Skip debugging pseudos; necessary to avoid changing the code.
291     while (I1->isDebugValue()) {
292       if (I1==MBB1->begin()) {
293         while (I2->isDebugValue()) {
294           if (I2==MBB2->begin())
295             // I1==DBG at begin; I2==DBG at begin
296             return TailLen;
297           --I2;
298         }
299         ++I2;
300         // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
301         return TailLen;
302       }
303       --I1;
304     }
305     // I1==first (untested) non-DBG preceding known match
306     while (I2->isDebugValue()) {
307       if (I2==MBB2->begin()) {
308         ++I1;
309         // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
310         return TailLen;
311       }
312       --I2;
313     }
314     // I1, I2==first (untested) non-DBGs preceding known match
315     if (!I1->isIdenticalTo(*I2) ||
316         // FIXME: This check is dubious. It's used to get around a problem where
317         // people incorrectly expect inline asm directives to remain in the same
318         // relative order. This is untenable because normal compiler
319         // optimizations (like this one) may reorder and/or merge these
320         // directives.
321         I1->isInlineAsm()) {
322       ++I1; ++I2;
323       break;
324     }
325     ++TailLen;
326   }
327   // Back past possible debugging pseudos at beginning of block.  This matters
328   // when one block differs from the other only by whether debugging pseudos
329   // are present at the beginning. (This way, the various checks later for
330   // I1==MBB1->begin() work as expected.)
331   if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
332     --I2;
333     while (I2->isDebugValue()) {
334       if (I2 == MBB2->begin())
335         return TailLen;
336       --I2;
337     }
338     ++I2;
339   }
340   if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
341     --I1;
342     while (I1->isDebugValue()) {
343       if (I1 == MBB1->begin())
344         return TailLen;
345       --I1;
346     }
347     ++I1;
348   }
349   return TailLen;
350 }
351 
352 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
353 /// after it, replacing it with an unconditional branch to NewDest.
354 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
355                                            MachineBasicBlock *NewDest) {
356   TII->ReplaceTailWithBranchTo(OldInst, NewDest);
357 
358   if (UpdateLiveIns) {
359     NewDest->clearLiveIns();
360     computeLiveIns(LiveRegs, *TRI, *NewDest);
361   }
362 
363   ++NumTailMerge;
364 }
365 
366 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
367 /// MBB so that the part before the iterator falls into the part starting at the
368 /// iterator.  This returns the new MBB.
369 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
370                                             MachineBasicBlock::iterator BBI1,
371                                             const BasicBlock *BB) {
372   if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
373     return nullptr;
374 
375   MachineFunction &MF = *CurMBB.getParent();
376 
377   // Create the fall-through block.
378   MachineFunction::iterator MBBI = CurMBB.getIterator();
379   MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
380   CurMBB.getParent()->insert(++MBBI, NewMBB);
381 
382   // Move all the successors of this block to the specified block.
383   NewMBB->transferSuccessors(&CurMBB);
384 
385   // Add an edge from CurMBB to NewMBB for the fall-through.
386   CurMBB.addSuccessor(NewMBB);
387 
388   // Splice the code over.
389   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
390 
391   // NewMBB belongs to the same loop as CurMBB.
392   if (MLI)
393     if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))
394       ML->addBasicBlockToLoop(NewMBB, MLI->getBase());
395 
396   // NewMBB inherits CurMBB's block frequency.
397   MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
398 
399   if (UpdateLiveIns)
400     computeLiveIns(LiveRegs, *TRI, *NewMBB);
401 
402   // Add the new block to the funclet.
403   const auto &FuncletI = FuncletMembership.find(&CurMBB);
404   if (FuncletI != FuncletMembership.end()) {
405     auto n = FuncletI->second;
406     FuncletMembership[NewMBB] = n;
407   }
408 
409   return NewMBB;
410 }
411 
412 /// EstimateRuntime - Make a rough estimate for how long it will take to run
413 /// the specified code.
414 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
415                                 MachineBasicBlock::iterator E) {
416   unsigned Time = 0;
417   for (; I != E; ++I) {
418     if (I->isDebugValue())
419       continue;
420     if (I->isCall())
421       Time += 10;
422     else if (I->mayLoad() || I->mayStore())
423       Time += 2;
424     else
425       ++Time;
426   }
427   return Time;
428 }
429 
430 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
431 // branches temporarily for tail merging).  In the case where CurMBB ends
432 // with a conditional branch to the next block, optimize by reversing the
433 // test and conditionally branching to SuccMBB instead.
434 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
435                     const TargetInstrInfo *TII) {
436   MachineFunction *MF = CurMBB->getParent();
437   MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
438   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
439   SmallVector<MachineOperand, 4> Cond;
440   DebugLoc dl;  // FIXME: this is nowhere
441   if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
442     MachineBasicBlock *NextBB = &*I;
443     if (TBB == NextBB && !Cond.empty() && !FBB) {
444       if (!TII->reverseBranchCondition(Cond)) {
445         TII->removeBranch(*CurMBB);
446         TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
447         return;
448       }
449     }
450   }
451   TII->insertBranch(*CurMBB, SuccBB, nullptr,
452                     SmallVector<MachineOperand, 0>(), dl);
453 }
454 
455 bool
456 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
457   if (getHash() < o.getHash())
458     return true;
459   if (getHash() > o.getHash())
460     return false;
461   if (getBlock()->getNumber() < o.getBlock()->getNumber())
462     return true;
463   if (getBlock()->getNumber() > o.getBlock()->getNumber())
464     return false;
465   // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
466   // an object with itself.
467 #ifndef _GLIBCXX_DEBUG
468   llvm_unreachable("Predecessor appears twice");
469 #else
470   return false;
471 #endif
472 }
473 
474 BlockFrequency
475 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
476   auto I = MergedBBFreq.find(MBB);
477 
478   if (I != MergedBBFreq.end())
479     return I->second;
480 
481   return MBFI.getBlockFreq(MBB);
482 }
483 
484 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
485                                              BlockFrequency F) {
486   MergedBBFreq[MBB] = F;
487 }
488 
489 raw_ostream &
490 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
491                                           const MachineBasicBlock *MBB) const {
492   return MBFI.printBlockFreq(OS, getBlockFreq(MBB));
493 }
494 
495 raw_ostream &
496 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
497                                           const BlockFrequency Freq) const {
498   return MBFI.printBlockFreq(OS, Freq);
499 }
500 
501 void BranchFolder::MBFIWrapper::view(bool isSimple) { MBFI.view(isSimple); }
502 
503 /// CountTerminators - Count the number of terminators in the given
504 /// block and set I to the position of the first non-terminator, if there
505 /// is one, or MBB->end() otherwise.
506 static unsigned CountTerminators(MachineBasicBlock *MBB,
507                                  MachineBasicBlock::iterator &I) {
508   I = MBB->end();
509   unsigned NumTerms = 0;
510   for (;;) {
511     if (I == MBB->begin()) {
512       I = MBB->end();
513       break;
514     }
515     --I;
516     if (!I->isTerminator()) break;
517     ++NumTerms;
518   }
519   return NumTerms;
520 }
521 
522 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
523 /// and decide if it would be profitable to merge those tails.  Return the
524 /// length of the common tail and iterators to the first common instruction
525 /// in each block.
526 /// MBB1, MBB2      The blocks to check
527 /// MinCommonTailLength  Minimum size of tail block to be merged.
528 /// CommonTailLen   Out parameter to record the size of the shared tail between
529 ///                 MBB1 and MBB2
530 /// I1, I2          Iterator references that will be changed to point to the first
531 ///                 instruction in the common tail shared by MBB1,MBB2
532 /// SuccBB          A common successor of MBB1, MBB2 which are in a canonical form
533 ///                 relative to SuccBB
534 /// PredBB          The layout predecessor of SuccBB, if any.
535 /// FuncletMembership  map from block to funclet #.
536 /// AfterPlacement  True if we are merging blocks after layout. Stricter
537 ///                 thresholds apply to prevent undoing tail-duplication.
538 static bool
539 ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
540                   unsigned MinCommonTailLength, unsigned &CommonTailLen,
541                   MachineBasicBlock::iterator &I1,
542                   MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
543                   MachineBasicBlock *PredBB,
544                   DenseMap<const MachineBasicBlock *, int> &FuncletMembership,
545                   bool AfterPlacement) {
546   // It is never profitable to tail-merge blocks from two different funclets.
547   if (!FuncletMembership.empty()) {
548     auto Funclet1 = FuncletMembership.find(MBB1);
549     assert(Funclet1 != FuncletMembership.end());
550     auto Funclet2 = FuncletMembership.find(MBB2);
551     assert(Funclet2 != FuncletMembership.end());
552     if (Funclet1->second != Funclet2->second)
553       return false;
554   }
555 
556   CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
557   if (CommonTailLen == 0)
558     return false;
559   DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
560                << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
561                << '\n');
562 
563   // It's almost always profitable to merge any number of non-terminator
564   // instructions with the block that falls through into the common successor.
565   // This is true only for a single successor. For multiple successors, we are
566   // trading a conditional branch for an unconditional one.
567   // TODO: Re-visit successor size for non-layout tail merging.
568   if ((MBB1 == PredBB || MBB2 == PredBB) &&
569       (!AfterPlacement || MBB1->succ_size() == 1)) {
570     MachineBasicBlock::iterator I;
571     unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
572     if (CommonTailLen > NumTerms)
573       return true;
574   }
575 
576   // If one of the blocks can be completely merged and happens to be in
577   // a position where the other could fall through into it, merge any number
578   // of instructions, because it can be done without a branch.
579   // TODO: If the blocks are not adjacent, move one of them so that they are?
580   if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
581     return true;
582   if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
583     return true;
584 
585   // If both blocks have an unconditional branch temporarily stripped out,
586   // count that as an additional common instruction for the following
587   // heuristics. This heuristic is only accurate for single-succ blocks, so to
588   // make sure that during layout merging and duplicating don't crash, we check
589   // for that when merging during layout.
590   unsigned EffectiveTailLen = CommonTailLen;
591   if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
592       (MBB1->succ_size() == 1 || !AfterPlacement) &&
593       !MBB1->back().isBarrier() &&
594       !MBB2->back().isBarrier())
595     ++EffectiveTailLen;
596 
597   // Check if the common tail is long enough to be worthwhile.
598   if (EffectiveTailLen >= MinCommonTailLength)
599     return true;
600 
601   // If we are optimizing for code size, 2 instructions in common is enough if
602   // we don't have to split a block.  At worst we will be introducing 1 new
603   // branch instruction, which is likely to be smaller than the 2
604   // instructions that would be deleted in the merge.
605   MachineFunction *MF = MBB1->getParent();
606   return EffectiveTailLen >= 2 && MF->getFunction()->optForSize() &&
607          (I1 == MBB1->begin() || I2 == MBB2->begin());
608 }
609 
610 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
611 /// hash CurHash (guaranteed to match the last element).  Build the vector
612 /// SameTails of all those that have the (same) largest number of instructions
613 /// in common of any pair of these blocks.  SameTails entries contain an
614 /// iterator into MergePotentials (from which the MachineBasicBlock can be
615 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
616 /// instruction where the matching code sequence begins.
617 /// Order of elements in SameTails is the reverse of the order in which
618 /// those blocks appear in MergePotentials (where they are not necessarily
619 /// consecutive).
620 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
621                                         unsigned MinCommonTailLength,
622                                         MachineBasicBlock *SuccBB,
623                                         MachineBasicBlock *PredBB) {
624   unsigned maxCommonTailLength = 0U;
625   SameTails.clear();
626   MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
627   MPIterator HighestMPIter = std::prev(MergePotentials.end());
628   for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
629                   B = MergePotentials.begin();
630        CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
631     for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
632       unsigned CommonTailLen;
633       if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
634                             MinCommonTailLength,
635                             CommonTailLen, TrialBBI1, TrialBBI2,
636                             SuccBB, PredBB,
637                             FuncletMembership,
638                             AfterBlockPlacement)) {
639         if (CommonTailLen > maxCommonTailLength) {
640           SameTails.clear();
641           maxCommonTailLength = CommonTailLen;
642           HighestMPIter = CurMPIter;
643           SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
644         }
645         if (HighestMPIter == CurMPIter &&
646             CommonTailLen == maxCommonTailLength)
647           SameTails.push_back(SameTailElt(I, TrialBBI2));
648       }
649       if (I == B)
650         break;
651     }
652   }
653   return maxCommonTailLength;
654 }
655 
656 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
657 /// MergePotentials, restoring branches at ends of blocks as appropriate.
658 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
659                                         MachineBasicBlock *SuccBB,
660                                         MachineBasicBlock *PredBB) {
661   MPIterator CurMPIter, B;
662   for (CurMPIter = std::prev(MergePotentials.end()),
663       B = MergePotentials.begin();
664        CurMPIter->getHash() == CurHash; --CurMPIter) {
665     // Put the unconditional branch back, if we need one.
666     MachineBasicBlock *CurMBB = CurMPIter->getBlock();
667     if (SuccBB && CurMBB != PredBB)
668       FixTail(CurMBB, SuccBB, TII);
669     if (CurMPIter == B)
670       break;
671   }
672   if (CurMPIter->getHash() != CurHash)
673     CurMPIter++;
674   MergePotentials.erase(CurMPIter, MergePotentials.end());
675 }
676 
677 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
678 /// only of the common tail.  Create a block that does by splitting one.
679 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
680                                              MachineBasicBlock *SuccBB,
681                                              unsigned maxCommonTailLength,
682                                              unsigned &commonTailIndex) {
683   commonTailIndex = 0;
684   unsigned TimeEstimate = ~0U;
685   for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
686     // Use PredBB if possible; that doesn't require a new branch.
687     if (SameTails[i].getBlock() == PredBB) {
688       commonTailIndex = i;
689       break;
690     }
691     // Otherwise, make a (fairly bogus) choice based on estimate of
692     // how long it will take the various blocks to execute.
693     unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
694                                  SameTails[i].getTailStartPos());
695     if (t <= TimeEstimate) {
696       TimeEstimate = t;
697       commonTailIndex = i;
698     }
699   }
700 
701   MachineBasicBlock::iterator BBI =
702     SameTails[commonTailIndex].getTailStartPos();
703   MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
704 
705   DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
706                << maxCommonTailLength);
707 
708   // If the split block unconditionally falls-thru to SuccBB, it will be
709   // merged. In control flow terms it should then take SuccBB's name. e.g. If
710   // SuccBB is an inner loop, the common tail is still part of the inner loop.
711   const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
712     SuccBB->getBasicBlock() : MBB->getBasicBlock();
713   MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
714   if (!newMBB) {
715     DEBUG(dbgs() << "... failed!");
716     return false;
717   }
718 
719   SameTails[commonTailIndex].setBlock(newMBB);
720   SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
721 
722   // If we split PredBB, newMBB is the new predecessor.
723   if (PredBB == MBB)
724     PredBB = newMBB;
725 
726   return true;
727 }
728 
729 static void
730 mergeOperations(MachineBasicBlock::iterator MBBIStartPos,
731                 MachineBasicBlock &MBBCommon) {
732   MachineBasicBlock *MBB = MBBIStartPos->getParent();
733   // Note CommonTailLen does not necessarily matches the size of
734   // the common BB nor all its instructions because of debug
735   // instructions differences.
736   unsigned CommonTailLen = 0;
737   for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
738     ++CommonTailLen;
739 
740   MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
741   MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
742   MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
743   MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
744 
745   while (CommonTailLen--) {
746     assert(MBBI != MBBIE && "Reached BB end within common tail length!");
747     (void)MBBIE;
748 
749     if (MBBI->isDebugValue()) {
750       ++MBBI;
751       continue;
752     }
753 
754     while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue())
755       ++MBBICommon;
756 
757     assert(MBBICommon != MBBIECommon &&
758            "Reached BB end within common tail length!");
759     assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
760 
761     // Merge MMOs from memory operations in the common block.
762     if (MBBICommon->mayLoad() || MBBICommon->mayStore())
763       MBBICommon->setMemRefs(MBBICommon->mergeMemRefsWith(*MBBI));
764     // Drop undef flags if they aren't present in all merged instructions.
765     for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) {
766       MachineOperand &MO = MBBICommon->getOperand(I);
767       if (MO.isReg() && MO.isUndef()) {
768         const MachineOperand &OtherMO = MBBI->getOperand(I);
769         if (!OtherMO.isUndef())
770           MO.setIsUndef(false);
771       }
772     }
773 
774     ++MBBI;
775     ++MBBICommon;
776   }
777 }
778 
779 // See if any of the blocks in MergePotentials (which all have SuccBB as a
780 // successor, or all have no successor if it is null) can be tail-merged.
781 // If there is a successor, any blocks in MergePotentials that are not
782 // tail-merged and are not immediately before Succ must have an unconditional
783 // branch to Succ added (but the predecessor/successor lists need no
784 // adjustment). The lone predecessor of Succ that falls through into Succ,
785 // if any, is given in PredBB.
786 // MinCommonTailLength - Except for the special cases below, tail-merge if
787 // there are at least this many instructions in common.
788 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
789                                       MachineBasicBlock *PredBB,
790                                       unsigned MinCommonTailLength) {
791   bool MadeChange = false;
792 
793   DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
794         for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
795           dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
796                  << (i == e-1 ? "" : ", ");
797         dbgs() << "\n";
798         if (SuccBB) {
799           dbgs() << "  with successor BB#" << SuccBB->getNumber() << '\n';
800           if (PredBB)
801             dbgs() << "  which has fall-through from BB#"
802                    << PredBB->getNumber() << "\n";
803         }
804         dbgs() << "Looking for common tails of at least "
805                << MinCommonTailLength << " instruction"
806                << (MinCommonTailLength == 1 ? "" : "s") << '\n';
807        );
808 
809   // Sort by hash value so that blocks with identical end sequences sort
810   // together.
811   array_pod_sort(MergePotentials.begin(), MergePotentials.end());
812 
813   // Walk through equivalence sets looking for actual exact matches.
814   while (MergePotentials.size() > 1) {
815     unsigned CurHash = MergePotentials.back().getHash();
816 
817     // Build SameTails, identifying the set of blocks with this hash code
818     // and with the maximum number of instructions in common.
819     unsigned maxCommonTailLength = ComputeSameTails(CurHash,
820                                                     MinCommonTailLength,
821                                                     SuccBB, PredBB);
822 
823     // If we didn't find any pair that has at least MinCommonTailLength
824     // instructions in common, remove all blocks with this hash code and retry.
825     if (SameTails.empty()) {
826       RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
827       continue;
828     }
829 
830     // If one of the blocks is the entire common tail (and not the entry
831     // block, which we can't jump to), we can treat all blocks with this same
832     // tail at once.  Use PredBB if that is one of the possibilities, as that
833     // will not introduce any extra branches.
834     MachineBasicBlock *EntryBB =
835         &MergePotentials.front().getBlock()->getParent()->front();
836     unsigned commonTailIndex = SameTails.size();
837     // If there are two blocks, check to see if one can be made to fall through
838     // into the other.
839     if (SameTails.size() == 2 &&
840         SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
841         SameTails[1].tailIsWholeBlock())
842       commonTailIndex = 1;
843     else if (SameTails.size() == 2 &&
844              SameTails[1].getBlock()->isLayoutSuccessor(
845                                                      SameTails[0].getBlock()) &&
846              SameTails[0].tailIsWholeBlock())
847       commonTailIndex = 0;
848     else {
849       // Otherwise just pick one, favoring the fall-through predecessor if
850       // there is one.
851       for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
852         MachineBasicBlock *MBB = SameTails[i].getBlock();
853         if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
854           continue;
855         if (MBB == PredBB) {
856           commonTailIndex = i;
857           break;
858         }
859         if (SameTails[i].tailIsWholeBlock())
860           commonTailIndex = i;
861       }
862     }
863 
864     if (commonTailIndex == SameTails.size() ||
865         (SameTails[commonTailIndex].getBlock() == PredBB &&
866          !SameTails[commonTailIndex].tailIsWholeBlock())) {
867       // None of the blocks consist entirely of the common tail.
868       // Split a block so that one does.
869       if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
870                                      maxCommonTailLength, commonTailIndex)) {
871         RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
872         continue;
873       }
874     }
875 
876     MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
877 
878     // Recompute common tail MBB's edge weights and block frequency.
879     setCommonTailEdgeWeights(*MBB);
880 
881     // Remove the original debug location from the common tail.
882     for (auto &MI : *MBB)
883       if (!MI.isDebugValue())
884         MI.setDebugLoc(DebugLoc());
885 
886     // MBB is common tail.  Adjust all other BB's to jump to this one.
887     // Traversal must be forwards so erases work.
888     DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
889                  << " for ");
890     for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
891       if (commonTailIndex == i)
892         continue;
893       DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
894                    << (i == e-1 ? "" : ", "));
895       // Merge operations (MMOs, undef flags)
896       mergeOperations(SameTails[i].getTailStartPos(), *MBB);
897       // Hack the end off BB i, making it jump to BB commonTailIndex instead.
898       ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
899       // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
900       MergePotentials.erase(SameTails[i].getMPIter());
901     }
902     DEBUG(dbgs() << "\n");
903     // We leave commonTailIndex in the worklist in case there are other blocks
904     // that match it with a smaller number of instructions.
905     MadeChange = true;
906   }
907   return MadeChange;
908 }
909 
910 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
911   bool MadeChange = false;
912   if (!EnableTailMerge) return MadeChange;
913 
914   // First find blocks with no successors.
915   // Block placement does not create new tail merging opportunities for these
916   // blocks.
917   if (!AfterBlockPlacement) {
918     MergePotentials.clear();
919     for (MachineBasicBlock &MBB : MF) {
920       if (MergePotentials.size() == TailMergeThreshold)
921         break;
922       if (!TriedMerging.count(&MBB) && MBB.succ_empty())
923         MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB));
924     }
925 
926     // If this is a large problem, avoid visiting the same basic blocks
927     // multiple times.
928     if (MergePotentials.size() == TailMergeThreshold)
929       for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
930         TriedMerging.insert(MergePotentials[i].getBlock());
931 
932     // See if we can do any tail merging on those.
933     if (MergePotentials.size() >= 2)
934       MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);
935   }
936 
937   // Look at blocks (IBB) with multiple predecessors (PBB).
938   // We change each predecessor to a canonical form, by
939   // (1) temporarily removing any unconditional branch from the predecessor
940   // to IBB, and
941   // (2) alter conditional branches so they branch to the other block
942   // not IBB; this may require adding back an unconditional branch to IBB
943   // later, where there wasn't one coming in.  E.g.
944   //   Bcc IBB
945   //   fallthrough to QBB
946   // here becomes
947   //   Bncc QBB
948   // with a conceptual B to IBB after that, which never actually exists.
949   // With those changes, we see whether the predecessors' tails match,
950   // and merge them if so.  We change things out of canonical form and
951   // back to the way they were later in the process.  (OptimizeBranches
952   // would undo some of this, but we can't use it, because we'd get into
953   // a compile-time infinite loop repeatedly doing and undoing the same
954   // transformations.)
955 
956   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
957        I != E; ++I) {
958     if (I->pred_size() < 2) continue;
959     SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
960     MachineBasicBlock *IBB = &*I;
961     MachineBasicBlock *PredBB = &*std::prev(I);
962     MergePotentials.clear();
963     MachineLoop *ML;
964 
965     // Bail if merging after placement and IBB is the loop header because
966     // -- If merging predecessors that belong to the same loop as IBB, the
967     // common tail of merged predecessors may become the loop top if block
968     // placement is called again and the predecessors may branch to this common
969     // tail and require more branches. This can be relaxed if
970     // MachineBlockPlacement::findBestLoopTop is more flexible.
971     // --If merging predecessors that do not belong to the same loop as IBB, the
972     // loop info of IBB's loop and the other loops may be affected. Calling the
973     // block placement again may make big change to the layout and eliminate the
974     // reason to do tail merging here.
975     if (AfterBlockPlacement && MLI) {
976       ML = MLI->getLoopFor(IBB);
977       if (ML && IBB == ML->getHeader())
978         continue;
979     }
980 
981     for (MachineBasicBlock *PBB : I->predecessors()) {
982       if (MergePotentials.size() == TailMergeThreshold)
983         break;
984 
985       if (TriedMerging.count(PBB))
986         continue;
987 
988       // Skip blocks that loop to themselves, can't tail merge these.
989       if (PBB == IBB)
990         continue;
991 
992       // Visit each predecessor only once.
993       if (!UniquePreds.insert(PBB).second)
994         continue;
995 
996       // Skip blocks which may jump to a landing pad. Can't tail merge these.
997       if (PBB->hasEHPadSuccessor())
998         continue;
999 
1000       // After block placement, only consider predecessors that belong to the
1001       // same loop as IBB.  The reason is the same as above when skipping loop
1002       // header.
1003       if (AfterBlockPlacement && MLI)
1004         if (ML != MLI->getLoopFor(PBB))
1005           continue;
1006 
1007       MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1008       SmallVector<MachineOperand, 4> Cond;
1009       if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {
1010         // Failing case: IBB is the target of a cbr, and we cannot reverse the
1011         // branch.
1012         SmallVector<MachineOperand, 4> NewCond(Cond);
1013         if (!Cond.empty() && TBB == IBB) {
1014           if (TII->reverseBranchCondition(NewCond))
1015             continue;
1016           // This is the QBB case described above
1017           if (!FBB) {
1018             auto Next = ++PBB->getIterator();
1019             if (Next != MF.end())
1020               FBB = &*Next;
1021           }
1022         }
1023 
1024         // Failing case: the only way IBB can be reached from PBB is via
1025         // exception handling.  Happens for landing pads.  Would be nice to have
1026         // a bit in the edge so we didn't have to do all this.
1027         if (IBB->isEHPad()) {
1028           MachineFunction::iterator IP = ++PBB->getIterator();
1029           MachineBasicBlock *PredNextBB = nullptr;
1030           if (IP != MF.end())
1031             PredNextBB = &*IP;
1032           if (!TBB) {
1033             if (IBB != PredNextBB)      // fallthrough
1034               continue;
1035           } else if (FBB) {
1036             if (TBB != IBB && FBB != IBB)   // cbr then ubr
1037               continue;
1038           } else if (Cond.empty()) {
1039             if (TBB != IBB)               // ubr
1040               continue;
1041           } else {
1042             if (TBB != IBB && IBB != PredNextBB)  // cbr
1043               continue;
1044           }
1045         }
1046 
1047         // Remove the unconditional branch at the end, if any.
1048         if (TBB && (Cond.empty() || FBB)) {
1049           DebugLoc dl;  // FIXME: this is nowhere
1050           TII->removeBranch(*PBB);
1051           if (!Cond.empty())
1052             // reinsert conditional branch only, for now
1053             TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
1054                               NewCond, dl);
1055         }
1056 
1057         MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB));
1058       }
1059     }
1060 
1061     // If this is a large problem, avoid visiting the same basic blocks multiple
1062     // times.
1063     if (MergePotentials.size() == TailMergeThreshold)
1064       for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1065         TriedMerging.insert(MergePotentials[i].getBlock());
1066 
1067     if (MergePotentials.size() >= 2)
1068       MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
1069 
1070     // Reinsert an unconditional branch if needed. The 1 below can occur as a
1071     // result of removing blocks in TryTailMergeBlocks.
1072     PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
1073     if (MergePotentials.size() == 1 &&
1074         MergePotentials.begin()->getBlock() != PredBB)
1075       FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1076   }
1077 
1078   return MadeChange;
1079 }
1080 
1081 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1082   SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1083   BlockFrequency AccumulatedMBBFreq;
1084 
1085   // Aggregate edge frequency of successor edge j:
1086   //  edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1087   //  where bb is a basic block that is in SameTails.
1088   for (const auto &Src : SameTails) {
1089     const MachineBasicBlock *SrcMBB = Src.getBlock();
1090     BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1091     AccumulatedMBBFreq += BlockFreq;
1092 
1093     // It is not necessary to recompute edge weights if TailBB has less than two
1094     // successors.
1095     if (TailMBB.succ_size() <= 1)
1096       continue;
1097 
1098     auto EdgeFreq = EdgeFreqLs.begin();
1099 
1100     for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1101          SuccI != SuccE; ++SuccI, ++EdgeFreq)
1102       *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1103   }
1104 
1105   MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1106 
1107   if (TailMBB.succ_size() <= 1)
1108     return;
1109 
1110   auto SumEdgeFreq =
1111       std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
1112           .getFrequency();
1113   auto EdgeFreq = EdgeFreqLs.begin();
1114 
1115   if (SumEdgeFreq > 0) {
1116     for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1117          SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1118       auto Prob = BranchProbability::getBranchProbability(
1119           EdgeFreq->getFrequency(), SumEdgeFreq);
1120       TailMBB.setSuccProbability(SuccI, Prob);
1121     }
1122   }
1123 }
1124 
1125 //===----------------------------------------------------------------------===//
1126 //  Branch Optimization
1127 //===----------------------------------------------------------------------===//
1128 
1129 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1130   bool MadeChange = false;
1131 
1132   // Make sure blocks are numbered in order
1133   MF.RenumberBlocks();
1134   // Renumbering blocks alters funclet membership, recalculate it.
1135   FuncletMembership = getFuncletMembership(MF);
1136 
1137   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1138        I != E; ) {
1139     MachineBasicBlock *MBB = &*I++;
1140     MadeChange |= OptimizeBlock(MBB);
1141 
1142     // If it is dead, remove it.
1143     if (MBB->pred_empty()) {
1144       RemoveDeadBlock(MBB);
1145       MadeChange = true;
1146       ++NumDeadBlocks;
1147     }
1148   }
1149 
1150   return MadeChange;
1151 }
1152 
1153 // Blocks should be considered empty if they contain only debug info;
1154 // else the debug info would affect codegen.
1155 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1156   return MBB->getFirstNonDebugInstr() == MBB->end();
1157 }
1158 
1159 // Blocks with only debug info and branches should be considered the same
1160 // as blocks with only branches.
1161 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1162   MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1163   assert(I != MBB->end() && "empty block!");
1164   return I->isBranch();
1165 }
1166 
1167 /// IsBetterFallthrough - Return true if it would be clearly better to
1168 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
1169 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1170 /// result in infinite loops.
1171 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1172                                 MachineBasicBlock *MBB2) {
1173   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
1174   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
1175   // optimize branches that branch to either a return block or an assert block
1176   // into a fallthrough to the return.
1177   MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
1178   MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
1179   if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
1180     return false;
1181 
1182   // If there is a clear successor ordering we make sure that one block
1183   // will fall through to the next
1184   if (MBB1->isSuccessor(MBB2)) return true;
1185   if (MBB2->isSuccessor(MBB1)) return false;
1186 
1187   return MBB2I->isCall() && !MBB1I->isCall();
1188 }
1189 
1190 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1191 /// instructions on the block.
1192 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1193   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1194   if (I != MBB.end() && I->isBranch())
1195     return I->getDebugLoc();
1196   return DebugLoc();
1197 }
1198 
1199 /// OptimizeBlock - Analyze and optimize control flow related to the specified
1200 /// block.  This is never called on the entry block.
1201 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1202   bool MadeChange = false;
1203   MachineFunction &MF = *MBB->getParent();
1204 ReoptimizeBlock:
1205 
1206   MachineFunction::iterator FallThrough = MBB->getIterator();
1207   ++FallThrough;
1208 
1209   // Make sure MBB and FallThrough belong to the same funclet.
1210   bool SameFunclet = true;
1211   if (!FuncletMembership.empty() && FallThrough != MF.end()) {
1212     auto MBBFunclet = FuncletMembership.find(MBB);
1213     assert(MBBFunclet != FuncletMembership.end());
1214     auto FallThroughFunclet = FuncletMembership.find(&*FallThrough);
1215     assert(FallThroughFunclet != FuncletMembership.end());
1216     SameFunclet = MBBFunclet->second == FallThroughFunclet->second;
1217   }
1218 
1219   // If this block is empty, make everyone use its fall-through, not the block
1220   // explicitly.  Landing pads should not do this since the landing-pad table
1221   // points to this block.  Blocks with their addresses taken shouldn't be
1222   // optimized away.
1223   if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
1224       SameFunclet) {
1225     // Dead block?  Leave for cleanup later.
1226     if (MBB->pred_empty()) return MadeChange;
1227 
1228     if (FallThrough == MF.end()) {
1229       // TODO: Simplify preds to not branch here if possible!
1230     } else if (FallThrough->isEHPad()) {
1231       // Don't rewrite to a landing pad fallthough.  That could lead to the case
1232       // where a BB jumps to more than one landing pad.
1233       // TODO: Is it ever worth rewriting predecessors which don't already
1234       // jump to a landing pad, and so can safely jump to the fallthrough?
1235     } else if (MBB->isSuccessor(&*FallThrough)) {
1236       // Rewrite all predecessors of the old block to go to the fallthrough
1237       // instead.
1238       while (!MBB->pred_empty()) {
1239         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1240         Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
1241       }
1242       // If MBB was the target of a jump table, update jump tables to go to the
1243       // fallthrough instead.
1244       if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1245         MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
1246       MadeChange = true;
1247     }
1248     return MadeChange;
1249   }
1250 
1251   // Check to see if we can simplify the terminator of the block before this
1252   // one.
1253   MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1254 
1255   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1256   SmallVector<MachineOperand, 4> PriorCond;
1257   bool PriorUnAnalyzable =
1258       TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1259   if (!PriorUnAnalyzable) {
1260     // If the CFG for the prior block has extra edges, remove them.
1261     MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1262                                               !PriorCond.empty());
1263 
1264     // If the previous branch is conditional and both conditions go to the same
1265     // destination, remove the branch, replacing it with an unconditional one or
1266     // a fall-through.
1267     if (PriorTBB && PriorTBB == PriorFBB) {
1268       DebugLoc dl = getBranchDebugLoc(PrevBB);
1269       TII->removeBranch(PrevBB);
1270       PriorCond.clear();
1271       if (PriorTBB != MBB)
1272         TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1273       MadeChange = true;
1274       ++NumBranchOpts;
1275       goto ReoptimizeBlock;
1276     }
1277 
1278     // If the previous block unconditionally falls through to this block and
1279     // this block has no other predecessors, move the contents of this block
1280     // into the prior block. This doesn't usually happen when SimplifyCFG
1281     // has been used, but it can happen if tail merging splits a fall-through
1282     // predecessor of a block.
1283     // This has to check PrevBB->succ_size() because EH edges are ignored by
1284     // AnalyzeBranch.
1285     if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1286         PrevBB.succ_size() == 1 &&
1287         !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1288       DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1289                    << "From MBB: " << *MBB);
1290       // Remove redundant DBG_VALUEs first.
1291       if (PrevBB.begin() != PrevBB.end()) {
1292         MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1293         --PrevBBIter;
1294         MachineBasicBlock::iterator MBBIter = MBB->begin();
1295         // Check if DBG_VALUE at the end of PrevBB is identical to the
1296         // DBG_VALUE at the beginning of MBB.
1297         while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1298                && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1299           if (!MBBIter->isIdenticalTo(*PrevBBIter))
1300             break;
1301           MachineInstr &DuplicateDbg = *MBBIter;
1302           ++MBBIter; -- PrevBBIter;
1303           DuplicateDbg.eraseFromParent();
1304         }
1305       }
1306       PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1307       PrevBB.removeSuccessor(PrevBB.succ_begin());
1308       assert(PrevBB.succ_empty());
1309       PrevBB.transferSuccessors(MBB);
1310       MadeChange = true;
1311       return MadeChange;
1312     }
1313 
1314     // If the previous branch *only* branches to *this* block (conditional or
1315     // not) remove the branch.
1316     if (PriorTBB == MBB && !PriorFBB) {
1317       TII->removeBranch(PrevBB);
1318       MadeChange = true;
1319       ++NumBranchOpts;
1320       goto ReoptimizeBlock;
1321     }
1322 
1323     // If the prior block branches somewhere else on the condition and here if
1324     // the condition is false, remove the uncond second branch.
1325     if (PriorFBB == MBB) {
1326       DebugLoc dl = getBranchDebugLoc(PrevBB);
1327       TII->removeBranch(PrevBB);
1328       TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1329       MadeChange = true;
1330       ++NumBranchOpts;
1331       goto ReoptimizeBlock;
1332     }
1333 
1334     // If the prior block branches here on true and somewhere else on false, and
1335     // if the branch condition is reversible, reverse the branch to create a
1336     // fall-through.
1337     if (PriorTBB == MBB) {
1338       SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1339       if (!TII->reverseBranchCondition(NewPriorCond)) {
1340         DebugLoc dl = getBranchDebugLoc(PrevBB);
1341         TII->removeBranch(PrevBB);
1342         TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
1343         MadeChange = true;
1344         ++NumBranchOpts;
1345         goto ReoptimizeBlock;
1346       }
1347     }
1348 
1349     // If this block has no successors (e.g. it is a return block or ends with
1350     // a call to a no-return function like abort or __cxa_throw) and if the pred
1351     // falls through into this block, and if it would otherwise fall through
1352     // into the block after this, move this block to the end of the function.
1353     //
1354     // We consider it more likely that execution will stay in the function (e.g.
1355     // due to loops) than it is to exit it.  This asserts in loops etc, moving
1356     // the assert condition out of the loop body.
1357     if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
1358         MachineFunction::iterator(PriorTBB) == FallThrough &&
1359         !MBB->canFallThrough()) {
1360       bool DoTransform = true;
1361 
1362       // We have to be careful that the succs of PredBB aren't both no-successor
1363       // blocks.  If neither have successors and if PredBB is the second from
1364       // last block in the function, we'd just keep swapping the two blocks for
1365       // last.  Only do the swap if one is clearly better to fall through than
1366       // the other.
1367       if (FallThrough == --MF.end() &&
1368           !IsBetterFallthrough(PriorTBB, MBB))
1369         DoTransform = false;
1370 
1371       if (DoTransform) {
1372         // Reverse the branch so we will fall through on the previous true cond.
1373         SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1374         if (!TII->reverseBranchCondition(NewPriorCond)) {
1375           DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1376                        << "To make fallthrough to: " << *PriorTBB << "\n");
1377 
1378           DebugLoc dl = getBranchDebugLoc(PrevBB);
1379           TII->removeBranch(PrevBB);
1380           TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
1381 
1382           // Move this block to the end of the function.
1383           MBB->moveAfter(&MF.back());
1384           MadeChange = true;
1385           ++NumBranchOpts;
1386           return MadeChange;
1387         }
1388       }
1389     }
1390   }
1391 
1392   if (!IsEmptyBlock(MBB) && MBB->pred_size() == 1 &&
1393       MF.getFunction()->optForSize()) {
1394     // Changing "Jcc foo; foo: jmp bar;" into "Jcc bar;" might change the branch
1395     // direction, thereby defeating careful block placement and regressing
1396     // performance. Therefore, only consider this for optsize functions.
1397     MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();
1398     if (TII->isUnconditionalTailCall(TailCall)) {
1399       MachineBasicBlock *Pred = *MBB->pred_begin();
1400       MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1401       SmallVector<MachineOperand, 4> PredCond;
1402       bool PredAnalyzable =
1403           !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true);
1404 
1405       if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB) {
1406         // The predecessor has a conditional branch to this block which consists
1407         // of only a tail call. Try to fold the tail call into the conditional
1408         // branch.
1409         if (TII->canMakeTailCallConditional(PredCond, TailCall)) {
1410           // TODO: It would be nice if analyzeBranch() could provide a pointer
1411           // to the branch insturction so replaceBranchWithTailCall() doesn't
1412           // have to search for it.
1413           TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall);
1414           ++NumTailCalls;
1415           Pred->removeSuccessor(MBB);
1416           MadeChange = true;
1417           return MadeChange;
1418         }
1419       }
1420       // If the predecessor is falling through to this block, we could reverse
1421       // the branch condition and fold the tail call into that. However, after
1422       // that we might have to re-arrange the CFG to fall through to the other
1423       // block and there is a high risk of regressing code size rather than
1424       // improving it.
1425     }
1426   }
1427 
1428   // Analyze the branch in the current block.
1429   MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1430   SmallVector<MachineOperand, 4> CurCond;
1431   bool CurUnAnalyzable =
1432       TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1433   if (!CurUnAnalyzable) {
1434     // If the CFG for the prior block has extra edges, remove them.
1435     MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1436 
1437     // If this is a two-way branch, and the FBB branches to this block, reverse
1438     // the condition so the single-basic-block loop is faster.  Instead of:
1439     //    Loop: xxx; jcc Out; jmp Loop
1440     // we want:
1441     //    Loop: xxx; jncc Loop; jmp Out
1442     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1443       SmallVector<MachineOperand, 4> NewCond(CurCond);
1444       if (!TII->reverseBranchCondition(NewCond)) {
1445         DebugLoc dl = getBranchDebugLoc(*MBB);
1446         TII->removeBranch(*MBB);
1447         TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1448         MadeChange = true;
1449         ++NumBranchOpts;
1450         goto ReoptimizeBlock;
1451       }
1452     }
1453 
1454     // If this branch is the only thing in its block, see if we can forward
1455     // other blocks across it.
1456     if (CurTBB && CurCond.empty() && !CurFBB &&
1457         IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1458         !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1459       DebugLoc dl = getBranchDebugLoc(*MBB);
1460       // This block may contain just an unconditional branch.  Because there can
1461       // be 'non-branch terminators' in the block, try removing the branch and
1462       // then seeing if the block is empty.
1463       TII->removeBranch(*MBB);
1464       // If the only things remaining in the block are debug info, remove these
1465       // as well, so this will behave the same as an empty block in non-debug
1466       // mode.
1467       if (IsEmptyBlock(MBB)) {
1468         // Make the block empty, losing the debug info (we could probably
1469         // improve this in some cases.)
1470         MBB->erase(MBB->begin(), MBB->end());
1471       }
1472       // If this block is just an unconditional branch to CurTBB, we can
1473       // usually completely eliminate the block.  The only case we cannot
1474       // completely eliminate the block is when the block before this one
1475       // falls through into MBB and we can't understand the prior block's branch
1476       // condition.
1477       if (MBB->empty()) {
1478         bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1479         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1480             !PrevBB.isSuccessor(MBB)) {
1481           // If the prior block falls through into us, turn it into an
1482           // explicit branch to us to make updates simpler.
1483           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1484               PriorTBB != MBB && PriorFBB != MBB) {
1485             if (!PriorTBB) {
1486               assert(PriorCond.empty() && !PriorFBB &&
1487                      "Bad branch analysis");
1488               PriorTBB = MBB;
1489             } else {
1490               assert(!PriorFBB && "Machine CFG out of date!");
1491               PriorFBB = MBB;
1492             }
1493             DebugLoc pdl = getBranchDebugLoc(PrevBB);
1494             TII->removeBranch(PrevBB);
1495             TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1496           }
1497 
1498           // Iterate through all the predecessors, revectoring each in-turn.
1499           size_t PI = 0;
1500           bool DidChange = false;
1501           bool HasBranchToSelf = false;
1502           while(PI != MBB->pred_size()) {
1503             MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1504             if (PMBB == MBB) {
1505               // If this block has an uncond branch to itself, leave it.
1506               ++PI;
1507               HasBranchToSelf = true;
1508             } else {
1509               DidChange = true;
1510               PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1511               // If this change resulted in PMBB ending in a conditional
1512               // branch where both conditions go to the same destination,
1513               // change this to an unconditional branch (and fix the CFG).
1514               MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1515               SmallVector<MachineOperand, 4> NewCurCond;
1516               bool NewCurUnAnalyzable = TII->analyzeBranch(
1517                   *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);
1518               if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1519                 DebugLoc pdl = getBranchDebugLoc(*PMBB);
1520                 TII->removeBranch(*PMBB);
1521                 NewCurCond.clear();
1522                 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
1523                 MadeChange = true;
1524                 ++NumBranchOpts;
1525                 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
1526               }
1527             }
1528           }
1529 
1530           // Change any jumptables to go to the new MBB.
1531           if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1532             MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1533           if (DidChange) {
1534             ++NumBranchOpts;
1535             MadeChange = true;
1536             if (!HasBranchToSelf) return MadeChange;
1537           }
1538         }
1539       }
1540 
1541       // Add the branch back if the block is more than just an uncond branch.
1542       TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
1543     }
1544   }
1545 
1546   // If the prior block doesn't fall through into this block, and if this
1547   // block doesn't fall through into some other block, see if we can find a
1548   // place to move this block where a fall-through will happen.
1549   if (!PrevBB.canFallThrough()) {
1550 
1551     // Now we know that there was no fall-through into this block, check to
1552     // see if it has a fall-through into its successor.
1553     bool CurFallsThru = MBB->canFallThrough();
1554 
1555     if (!MBB->isEHPad()) {
1556       // Check all the predecessors of this block.  If one of them has no fall
1557       // throughs, move this block right after it.
1558       for (MachineBasicBlock *PredBB : MBB->predecessors()) {
1559         // Analyze the branch at the end of the pred.
1560         MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1561         SmallVector<MachineOperand, 4> PredCond;
1562         if (PredBB != MBB && !PredBB->canFallThrough() &&
1563             !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) &&
1564             (!CurFallsThru || !CurTBB || !CurFBB) &&
1565             (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1566           // If the current block doesn't fall through, just move it.
1567           // If the current block can fall through and does not end with a
1568           // conditional branch, we need to append an unconditional jump to
1569           // the (current) next block.  To avoid a possible compile-time
1570           // infinite loop, move blocks only backward in this case.
1571           // Also, if there are already 2 branches here, we cannot add a third;
1572           // this means we have the case
1573           // Bcc next
1574           // B elsewhere
1575           // next:
1576           if (CurFallsThru) {
1577             MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
1578             CurCond.clear();
1579             TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1580           }
1581           MBB->moveAfter(PredBB);
1582           MadeChange = true;
1583           goto ReoptimizeBlock;
1584         }
1585       }
1586     }
1587 
1588     if (!CurFallsThru) {
1589       // Check all successors to see if we can move this block before it.
1590       for (MachineBasicBlock *SuccBB : MBB->successors()) {
1591         // Analyze the branch at the end of the block before the succ.
1592         MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
1593 
1594         // If this block doesn't already fall-through to that successor, and if
1595         // the succ doesn't already have a block that can fall through into it,
1596         // and if the successor isn't an EH destination, we can arrange for the
1597         // fallthrough to happen.
1598         if (SuccBB != MBB && &*SuccPrev != MBB &&
1599             !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1600             !SuccBB->isEHPad()) {
1601           MBB->moveBefore(SuccBB);
1602           MadeChange = true;
1603           goto ReoptimizeBlock;
1604         }
1605       }
1606 
1607       // Okay, there is no really great place to put this block.  If, however,
1608       // the block before this one would be a fall-through if this block were
1609       // removed, move this block to the end of the function. There is no real
1610       // advantage in "falling through" to an EH block, so we don't want to
1611       // perform this transformation for that case.
1612       //
1613       // Also, Windows EH introduced the possibility of an arbitrary number of
1614       // successors to a given block.  The analyzeBranch call does not consider
1615       // exception handling and so we can get in a state where a block
1616       // containing a call is followed by multiple EH blocks that would be
1617       // rotated infinitely at the end of the function if the transformation
1618       // below were performed for EH "FallThrough" blocks.  Therefore, even if
1619       // that appears not to be happening anymore, we should assume that it is
1620       // possible and not remove the "!FallThrough()->isEHPad" condition below.
1621       MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1622       SmallVector<MachineOperand, 4> PrevCond;
1623       if (FallThrough != MF.end() &&
1624           !FallThrough->isEHPad() &&
1625           !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1626           PrevBB.isSuccessor(&*FallThrough)) {
1627         MBB->moveAfter(&MF.back());
1628         MadeChange = true;
1629         return MadeChange;
1630       }
1631     }
1632   }
1633 
1634   return MadeChange;
1635 }
1636 
1637 //===----------------------------------------------------------------------===//
1638 //  Hoist Common Code
1639 //===----------------------------------------------------------------------===//
1640 
1641 /// HoistCommonCode - Hoist common instruction sequences at the start of basic
1642 /// blocks to their common predecessor.
1643 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1644   bool MadeChange = false;
1645   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1646     MachineBasicBlock *MBB = &*I++;
1647     MadeChange |= HoistCommonCodeInSuccs(MBB);
1648   }
1649 
1650   return MadeChange;
1651 }
1652 
1653 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1654 /// its 'true' successor.
1655 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1656                                          MachineBasicBlock *TrueBB) {
1657   for (MachineBasicBlock *SuccBB : BB->successors())
1658     if (SuccBB != TrueBB)
1659       return SuccBB;
1660   return nullptr;
1661 }
1662 
1663 template <class Container>
1664 static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI,
1665                                 Container &Set) {
1666   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1667     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1668       Set.insert(*AI);
1669   } else {
1670     Set.insert(Reg);
1671   }
1672 }
1673 
1674 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1675 /// in successors to. The location is usually just before the terminator,
1676 /// however if the terminator is a conditional branch and its previous
1677 /// instruction is the flag setting instruction, the previous instruction is
1678 /// the preferred location. This function also gathers uses and defs of the
1679 /// instructions from the insertion point to the end of the block. The data is
1680 /// used by HoistCommonCodeInSuccs to ensure safety.
1681 static
1682 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1683                                                   const TargetInstrInfo *TII,
1684                                                   const TargetRegisterInfo *TRI,
1685                                                   SmallSet<unsigned,4> &Uses,
1686                                                   SmallSet<unsigned,4> &Defs) {
1687   MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1688   if (!TII->isUnpredicatedTerminator(*Loc))
1689     return MBB->end();
1690 
1691   for (const MachineOperand &MO : Loc->operands()) {
1692     if (!MO.isReg())
1693       continue;
1694     unsigned Reg = MO.getReg();
1695     if (!Reg)
1696       continue;
1697     if (MO.isUse()) {
1698       addRegAndItsAliases(Reg, TRI, Uses);
1699     } else {
1700       if (!MO.isDead())
1701         // Don't try to hoist code in the rare case the terminator defines a
1702         // register that is later used.
1703         return MBB->end();
1704 
1705       // If the terminator defines a register, make sure we don't hoist
1706       // the instruction whose def might be clobbered by the terminator.
1707       addRegAndItsAliases(Reg, TRI, Defs);
1708     }
1709   }
1710 
1711   if (Uses.empty())
1712     return Loc;
1713   if (Loc == MBB->begin())
1714     return MBB->end();
1715 
1716   // The terminator is probably a conditional branch, try not to separate the
1717   // branch from condition setting instruction.
1718   MachineBasicBlock::iterator PI =
1719     skipDebugInstructionsBackward(std::prev(Loc), MBB->begin());
1720 
1721   bool IsDef = false;
1722   for (const MachineOperand &MO : PI->operands()) {
1723     // If PI has a regmask operand, it is probably a call. Separate away.
1724     if (MO.isRegMask())
1725       return Loc;
1726     if (!MO.isReg() || MO.isUse())
1727       continue;
1728     unsigned Reg = MO.getReg();
1729     if (!Reg)
1730       continue;
1731     if (Uses.count(Reg)) {
1732       IsDef = true;
1733       break;
1734     }
1735   }
1736   if (!IsDef)
1737     // The condition setting instruction is not just before the conditional
1738     // branch.
1739     return Loc;
1740 
1741   // Be conservative, don't insert instruction above something that may have
1742   // side-effects. And since it's potentially bad to separate flag setting
1743   // instruction from the conditional branch, just abort the optimization
1744   // completely.
1745   // Also avoid moving code above predicated instruction since it's hard to
1746   // reason about register liveness with predicated instruction.
1747   bool DontMoveAcrossStore = true;
1748   if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI))
1749     return MBB->end();
1750 
1751 
1752   // Find out what registers are live. Note this routine is ignoring other live
1753   // registers which are only used by instructions in successor blocks.
1754   for (const MachineOperand &MO : PI->operands()) {
1755     if (!MO.isReg())
1756       continue;
1757     unsigned Reg = MO.getReg();
1758     if (!Reg)
1759       continue;
1760     if (MO.isUse()) {
1761       addRegAndItsAliases(Reg, TRI, Uses);
1762     } else {
1763       if (Uses.erase(Reg)) {
1764         if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1765           for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1766             Uses.erase(*SubRegs); // Use sub-registers to be conservative
1767         }
1768       }
1769       addRegAndItsAliases(Reg, TRI, Defs);
1770     }
1771   }
1772 
1773   return PI;
1774 }
1775 
1776 /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1777 /// sequence at the start of the function, move the instructions before MBB
1778 /// terminator if it's legal.
1779 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1780   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1781   SmallVector<MachineOperand, 4> Cond;
1782   if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1783     return false;
1784 
1785   if (!FBB) FBB = findFalseBlock(MBB, TBB);
1786   if (!FBB)
1787     // Malformed bcc? True and false blocks are the same?
1788     return false;
1789 
1790   // Restrict the optimization to cases where MBB is the only predecessor,
1791   // it is an obvious win.
1792   if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1793     return false;
1794 
1795   // Find a suitable position to hoist the common instructions to. Also figure
1796   // out which registers are used or defined by instructions from the insertion
1797   // point to the end of the block.
1798   SmallSet<unsigned, 4> Uses, Defs;
1799   MachineBasicBlock::iterator Loc =
1800     findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1801   if (Loc == MBB->end())
1802     return false;
1803 
1804   bool HasDups = false;
1805   SmallVector<unsigned, 4> LocalDefs;
1806   SmallSet<unsigned, 4> LocalDefsSet;
1807   MachineBasicBlock::iterator TIB = TBB->begin();
1808   MachineBasicBlock::iterator FIB = FBB->begin();
1809   MachineBasicBlock::iterator TIE = TBB->end();
1810   MachineBasicBlock::iterator FIE = FBB->end();
1811   while (TIB != TIE && FIB != FIE) {
1812     // Skip dbg_value instructions. These do not count.
1813     TIB = skipDebugInstructionsForward(TIB, TIE);
1814     FIB = skipDebugInstructionsForward(FIB, FIE);
1815     if (TIB == TIE || FIB == FIE)
1816       break;
1817 
1818     if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))
1819       break;
1820 
1821     if (TII->isPredicated(*TIB))
1822       // Hard to reason about register liveness with predicated instruction.
1823       break;
1824 
1825     bool IsSafe = true;
1826     for (MachineOperand &MO : TIB->operands()) {
1827       // Don't attempt to hoist instructions with register masks.
1828       if (MO.isRegMask()) {
1829         IsSafe = false;
1830         break;
1831       }
1832       if (!MO.isReg())
1833         continue;
1834       unsigned Reg = MO.getReg();
1835       if (!Reg)
1836         continue;
1837       if (MO.isDef()) {
1838         if (Uses.count(Reg)) {
1839           // Avoid clobbering a register that's used by the instruction at
1840           // the point of insertion.
1841           IsSafe = false;
1842           break;
1843         }
1844 
1845         if (Defs.count(Reg) && !MO.isDead()) {
1846           // Don't hoist the instruction if the def would be clobber by the
1847           // instruction at the point insertion. FIXME: This is overly
1848           // conservative. It should be possible to hoist the instructions
1849           // in BB2 in the following example:
1850           // BB1:
1851           // r1, eflag = op1 r2, r3
1852           // brcc eflag
1853           //
1854           // BB2:
1855           // r1 = op2, ...
1856           //    = op3, r1<kill>
1857           IsSafe = false;
1858           break;
1859         }
1860       } else if (!LocalDefsSet.count(Reg)) {
1861         if (Defs.count(Reg)) {
1862           // Use is defined by the instruction at the point of insertion.
1863           IsSafe = false;
1864           break;
1865         }
1866 
1867         if (MO.isKill() && Uses.count(Reg))
1868           // Kills a register that's read by the instruction at the point of
1869           // insertion. Remove the kill marker.
1870           MO.setIsKill(false);
1871       }
1872     }
1873     if (!IsSafe)
1874       break;
1875 
1876     bool DontMoveAcrossStore = true;
1877     if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
1878       break;
1879 
1880     // Remove kills from LocalDefsSet, these registers had short live ranges.
1881     for (const MachineOperand &MO : TIB->operands()) {
1882       if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1883         continue;
1884       unsigned Reg = MO.getReg();
1885       if (!Reg || !LocalDefsSet.count(Reg))
1886         continue;
1887       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1888         for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1889           LocalDefsSet.erase(*AI);
1890       } else {
1891         LocalDefsSet.erase(Reg);
1892       }
1893     }
1894 
1895     // Track local defs so we can update liveins.
1896     for (const MachineOperand &MO : TIB->operands()) {
1897       if (!MO.isReg() || !MO.isDef() || MO.isDead())
1898         continue;
1899       unsigned Reg = MO.getReg();
1900       if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg))
1901         continue;
1902       LocalDefs.push_back(Reg);
1903       addRegAndItsAliases(Reg, TRI, LocalDefsSet);
1904     }
1905 
1906     HasDups = true;
1907     ++TIB;
1908     ++FIB;
1909   }
1910 
1911   if (!HasDups)
1912     return false;
1913 
1914   MBB->splice(Loc, TBB, TBB->begin(), TIB);
1915   FBB->erase(FBB->begin(), FIB);
1916 
1917   // Update livein's.
1918   bool AddedLiveIns = false;
1919   for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1920     unsigned Def = LocalDefs[i];
1921     if (LocalDefsSet.count(Def)) {
1922       TBB->addLiveIn(Def);
1923       FBB->addLiveIn(Def);
1924       AddedLiveIns = true;
1925     }
1926   }
1927 
1928   if (AddedLiveIns) {
1929     TBB->sortUniqueLiveIns();
1930     FBB->sortUniqueLiveIns();
1931   }
1932 
1933   ++NumHoist;
1934   return true;
1935 }
1936