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