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