LLVM API Documentation

BranchFolding.cpp
Go to the documentation of this file.
00001 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass forwards branches to unconditional branches to make them branch
00011 // directly to the target block.  This pass often results in dead MBB's, which
00012 // it then removes.
00013 //
00014 // Note that this pass must be run after register allocation, it cannot handle
00015 // SSA form.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "BranchFolding.h"
00020 #include "llvm/ADT/STLExtras.h"
00021 #include "llvm/ADT/SmallSet.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
00024 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
00025 #include "llvm/CodeGen/MachineFunctionPass.h"
00026 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00027 #include "llvm/CodeGen/MachineModuleInfo.h"
00028 #include "llvm/CodeGen/MachineRegisterInfo.h"
00029 #include "llvm/CodeGen/Passes.h"
00030 #include "llvm/CodeGen/RegisterScavenging.h"
00031 #include "llvm/IR/Function.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/ErrorHandling.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetInstrInfo.h"
00037 #include "llvm/Target/TargetMachine.h"
00038 #include "llvm/Target/TargetRegisterInfo.h"
00039 #include "llvm/Target/TargetSubtargetInfo.h"
00040 #include <algorithm>
00041 using namespace llvm;
00042 
00043 #define DEBUG_TYPE "branchfolding"
00044 
00045 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
00046 STATISTIC(NumBranchOpts, "Number of branches optimized");
00047 STATISTIC(NumTailMerge , "Number of block tails merged");
00048 STATISTIC(NumHoist     , "Number of times common instructions are hoisted");
00049 
00050 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
00051                               cl::init(cl::BOU_UNSET), cl::Hidden);
00052 
00053 // Throttle for huge numbers of predecessors (compile speed problems)
00054 static cl::opt<unsigned>
00055 TailMergeThreshold("tail-merge-threshold",
00056           cl::desc("Max number of predecessors to consider tail merging"),
00057           cl::init(150), cl::Hidden);
00058 
00059 // Heuristic for tail merging (and, inversely, tail duplication).
00060 // TODO: This should be replaced with a target query.
00061 static cl::opt<unsigned>
00062 TailMergeSize("tail-merge-size",
00063           cl::desc("Min number of instructions to consider tail merging"),
00064                               cl::init(3), cl::Hidden);
00065 
00066 namespace {
00067   /// BranchFolderPass - Wrap branch folder in a machine function pass.
00068   class BranchFolderPass : public MachineFunctionPass {
00069   public:
00070     static char ID;
00071     explicit BranchFolderPass(): MachineFunctionPass(ID) {}
00072 
00073     bool runOnMachineFunction(MachineFunction &MF) override;
00074 
00075     void getAnalysisUsage(AnalysisUsage &AU) const override {
00076       AU.addRequired<MachineBlockFrequencyInfo>();
00077       AU.addRequired<MachineBranchProbabilityInfo>();
00078       AU.addRequired<TargetPassConfig>();
00079       MachineFunctionPass::getAnalysisUsage(AU);
00080     }
00081   };
00082 }
00083 
00084 char BranchFolderPass::ID = 0;
00085 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
00086 
00087 INITIALIZE_PASS(BranchFolderPass, "branch-folder",
00088                 "Control Flow Optimizer", false, false)
00089 
00090 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
00091   if (skipOptnoneFunction(*MF.getFunction()))
00092     return false;
00093 
00094   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
00095   // TailMerge can create jump into if branches that make CFG irreducible for
00096   // HW that requires structurized CFG.
00097   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
00098       PassConfig->getEnableTailMerge();
00099   BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true,
00100                       getAnalysis<MachineBlockFrequencyInfo>(),
00101                       getAnalysis<MachineBranchProbabilityInfo>());
00102   return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
00103                                  MF.getSubtarget().getRegisterInfo(),
00104                                  getAnalysisIfAvailable<MachineModuleInfo>());
00105 }
00106 
00107 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
00108                            const MachineBlockFrequencyInfo &FreqInfo,
00109                            const MachineBranchProbabilityInfo &ProbInfo)
00110     : EnableHoistCommonCode(CommonHoist), MBBFreqInfo(FreqInfo),
00111       MBPI(ProbInfo) {
00112   switch (FlagEnableTailMerge) {
00113   case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
00114   case cl::BOU_TRUE: EnableTailMerge = true; break;
00115   case cl::BOU_FALSE: EnableTailMerge = false; break;
00116   }
00117 }
00118 
00119 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
00120 /// function, updating the CFG.
00121 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
00122   assert(MBB->pred_empty() && "MBB must be dead!");
00123   DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
00124 
00125   MachineFunction *MF = MBB->getParent();
00126   // drop all successors.
00127   while (!MBB->succ_empty())
00128     MBB->removeSuccessor(MBB->succ_end()-1);
00129 
00130   // Avoid matching if this pointer gets reused.
00131   TriedMerging.erase(MBB);
00132 
00133   // Remove the block.
00134   MF->erase(MBB);
00135 }
00136 
00137 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
00138 /// followed by terminators, and if the implicitly defined registers are not
00139 /// used by the terminators, remove those implicit_def's. e.g.
00140 /// BB1:
00141 ///   r0 = implicit_def
00142 ///   r1 = implicit_def
00143 ///   br
00144 /// This block can be optimized away later if the implicit instructions are
00145 /// removed.
00146 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
00147   SmallSet<unsigned, 4> ImpDefRegs;
00148   MachineBasicBlock::iterator I = MBB->begin();
00149   while (I != MBB->end()) {
00150     if (!I->isImplicitDef())
00151       break;
00152     unsigned Reg = I->getOperand(0).getReg();
00153     for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
00154          SubRegs.isValid(); ++SubRegs)
00155       ImpDefRegs.insert(*SubRegs);
00156     ++I;
00157   }
00158   if (ImpDefRegs.empty())
00159     return false;
00160 
00161   MachineBasicBlock::iterator FirstTerm = I;
00162   while (I != MBB->end()) {
00163     if (!TII->isUnpredicatedTerminator(I))
00164       return false;
00165     // See if it uses any of the implicitly defined registers.
00166     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00167       MachineOperand &MO = I->getOperand(i);
00168       if (!MO.isReg() || !MO.isUse())
00169         continue;
00170       unsigned Reg = MO.getReg();
00171       if (ImpDefRegs.count(Reg))
00172         return false;
00173     }
00174     ++I;
00175   }
00176 
00177   I = MBB->begin();
00178   while (I != FirstTerm) {
00179     MachineInstr *ImpDefMI = &*I;
00180     ++I;
00181     MBB->erase(ImpDefMI);
00182   }
00183 
00184   return true;
00185 }
00186 
00187 /// OptimizeFunction - Perhaps branch folding, tail merging and other
00188 /// CFG optimizations on the given function.
00189 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
00190                                     const TargetInstrInfo *tii,
00191                                     const TargetRegisterInfo *tri,
00192                                     MachineModuleInfo *mmi) {
00193   if (!tii) return false;
00194 
00195   TriedMerging.clear();
00196 
00197   TII = tii;
00198   TRI = tri;
00199   MMI = mmi;
00200   RS = nullptr;
00201 
00202   // Use a RegScavenger to help update liveness when required.
00203   MachineRegisterInfo &MRI = MF.getRegInfo();
00204   if (MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
00205     RS = new RegScavenger();
00206   else
00207     MRI.invalidateLiveness();
00208 
00209   // Fix CFG.  The later algorithms expect it to be right.
00210   bool MadeChange = false;
00211   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
00212     MachineBasicBlock *MBB = I, *TBB = nullptr, *FBB = nullptr;
00213     SmallVector<MachineOperand, 4> Cond;
00214     if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
00215       MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
00216     MadeChange |= OptimizeImpDefsBlock(MBB);
00217   }
00218 
00219   bool MadeChangeThisIteration = true;
00220   while (MadeChangeThisIteration) {
00221     MadeChangeThisIteration    = TailMergeBlocks(MF);
00222     MadeChangeThisIteration   |= OptimizeBranches(MF);
00223     if (EnableHoistCommonCode)
00224       MadeChangeThisIteration |= HoistCommonCode(MF);
00225     MadeChange |= MadeChangeThisIteration;
00226   }
00227 
00228   // See if any jump tables have become dead as the code generator
00229   // did its thing.
00230   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
00231   if (!JTI) {
00232     delete RS;
00233     return MadeChange;
00234   }
00235 
00236   // Walk the function to find jump tables that are live.
00237   BitVector JTIsLive(JTI->getJumpTables().size());
00238   for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
00239        BB != E; ++BB) {
00240     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
00241          I != E; ++I)
00242       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
00243         MachineOperand &Op = I->getOperand(op);
00244         if (!Op.isJTI()) continue;
00245 
00246         // Remember that this JT is live.
00247         JTIsLive.set(Op.getIndex());
00248       }
00249   }
00250 
00251   // Finally, remove dead jump tables.  This happens when the
00252   // indirect jump was unreachable (and thus deleted).
00253   for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
00254     if (!JTIsLive.test(i)) {
00255       JTI->RemoveJumpTable(i);
00256       MadeChange = true;
00257     }
00258 
00259   delete RS;
00260   return MadeChange;
00261 }
00262 
00263 //===----------------------------------------------------------------------===//
00264 //  Tail Merging of Blocks
00265 //===----------------------------------------------------------------------===//
00266 
00267 /// HashMachineInstr - Compute a hash value for MI and its operands.
00268 static unsigned HashMachineInstr(const MachineInstr *MI) {
00269   unsigned Hash = MI->getOpcode();
00270   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00271     const MachineOperand &Op = MI->getOperand(i);
00272 
00273     // Merge in bits from the operand if easy.
00274     unsigned OperandHash = 0;
00275     switch (Op.getType()) {
00276     case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
00277     case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
00278     case MachineOperand::MO_MachineBasicBlock:
00279       OperandHash = Op.getMBB()->getNumber();
00280       break;
00281     case MachineOperand::MO_FrameIndex:
00282     case MachineOperand::MO_ConstantPoolIndex:
00283     case MachineOperand::MO_JumpTableIndex:
00284       OperandHash = Op.getIndex();
00285       break;
00286     case MachineOperand::MO_GlobalAddress:
00287     case MachineOperand::MO_ExternalSymbol:
00288       // Global address / external symbol are too hard, don't bother, but do
00289       // pull in the offset.
00290       OperandHash = Op.getOffset();
00291       break;
00292     default: break;
00293     }
00294 
00295     Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
00296   }
00297   return Hash;
00298 }
00299 
00300 /// HashEndOfMBB - Hash the last instruction in the MBB.
00301 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
00302   MachineBasicBlock::const_iterator I = MBB->end();
00303   if (I == MBB->begin())
00304     return 0;   // Empty MBB.
00305 
00306   --I;
00307   // Skip debug info so it will not affect codegen.
00308   while (I->isDebugValue()) {
00309     if (I==MBB->begin())
00310       return 0;      // MBB empty except for debug info.
00311     --I;
00312   }
00313 
00314   return HashMachineInstr(I);
00315 }
00316 
00317 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
00318 /// of instructions they actually have in common together at their end.  Return
00319 /// iterators for the first shared instruction in each block.
00320 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
00321                                         MachineBasicBlock *MBB2,
00322                                         MachineBasicBlock::iterator &I1,
00323                                         MachineBasicBlock::iterator &I2) {
00324   I1 = MBB1->end();
00325   I2 = MBB2->end();
00326 
00327   unsigned TailLen = 0;
00328   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
00329     --I1; --I2;
00330     // Skip debugging pseudos; necessary to avoid changing the code.
00331     while (I1->isDebugValue()) {
00332       if (I1==MBB1->begin()) {
00333         while (I2->isDebugValue()) {
00334           if (I2==MBB2->begin())
00335             // I1==DBG at begin; I2==DBG at begin
00336             return TailLen;
00337           --I2;
00338         }
00339         ++I2;
00340         // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
00341         return TailLen;
00342       }
00343       --I1;
00344     }
00345     // I1==first (untested) non-DBG preceding known match
00346     while (I2->isDebugValue()) {
00347       if (I2==MBB2->begin()) {
00348         ++I1;
00349         // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
00350         return TailLen;
00351       }
00352       --I2;
00353     }
00354     // I1, I2==first (untested) non-DBGs preceding known match
00355     if (!I1->isIdenticalTo(I2) ||
00356         // FIXME: This check is dubious. It's used to get around a problem where
00357         // people incorrectly expect inline asm directives to remain in the same
00358         // relative order. This is untenable because normal compiler
00359         // optimizations (like this one) may reorder and/or merge these
00360         // directives.
00361         I1->isInlineAsm()) {
00362       ++I1; ++I2;
00363       break;
00364     }
00365     ++TailLen;
00366   }
00367   // Back past possible debugging pseudos at beginning of block.  This matters
00368   // when one block differs from the other only by whether debugging pseudos
00369   // are present at the beginning.  (This way, the various checks later for
00370   // I1==MBB1->begin() work as expected.)
00371   if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
00372     --I2;
00373     while (I2->isDebugValue()) {
00374       if (I2 == MBB2->begin())
00375         return TailLen;
00376       --I2;
00377     }
00378     ++I2;
00379   }
00380   if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
00381     --I1;
00382     while (I1->isDebugValue()) {
00383       if (I1 == MBB1->begin())
00384         return TailLen;
00385       --I1;
00386     }
00387     ++I1;
00388   }
00389   return TailLen;
00390 }
00391 
00392 void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB,
00393                                    MachineBasicBlock *NewMBB) {
00394   if (RS) {
00395     RS->enterBasicBlock(CurMBB);
00396     if (!CurMBB->empty())
00397       RS->forward(std::prev(CurMBB->end()));
00398     for (unsigned int i = 1, e = TRI->getNumRegs(); i != e; i++)
00399       if (RS->isRegUsed(i, false))
00400         NewMBB->addLiveIn(i);
00401   }
00402 }
00403 
00404 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
00405 /// after it, replacing it with an unconditional branch to NewDest.
00406 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
00407                                            MachineBasicBlock *NewDest) {
00408   MachineBasicBlock *CurMBB = OldInst->getParent();
00409 
00410   TII->ReplaceTailWithBranchTo(OldInst, NewDest);
00411 
00412   // For targets that use the register scavenger, we must maintain LiveIns.
00413   MaintainLiveIns(CurMBB, NewDest);
00414 
00415   ++NumTailMerge;
00416 }
00417 
00418 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
00419 /// MBB so that the part before the iterator falls into the part starting at the
00420 /// iterator.  This returns the new MBB.
00421 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
00422                                             MachineBasicBlock::iterator BBI1,
00423                                             const BasicBlock *BB) {
00424   if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
00425     return nullptr;
00426 
00427   MachineFunction &MF = *CurMBB.getParent();
00428 
00429   // Create the fall-through block.
00430   MachineFunction::iterator MBBI = &CurMBB;
00431   MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
00432   CurMBB.getParent()->insert(++MBBI, NewMBB);
00433 
00434   // Move all the successors of this block to the specified block.
00435   NewMBB->transferSuccessors(&CurMBB);
00436 
00437   // Add an edge from CurMBB to NewMBB for the fall-through.
00438   CurMBB.addSuccessor(NewMBB);
00439 
00440   // Splice the code over.
00441   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
00442 
00443   // NewMBB inherits CurMBB's block frequency.
00444   MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
00445 
00446   // For targets that use the register scavenger, we must maintain LiveIns.
00447   MaintainLiveIns(&CurMBB, NewMBB);
00448 
00449   return NewMBB;
00450 }
00451 
00452 /// EstimateRuntime - Make a rough estimate for how long it will take to run
00453 /// the specified code.
00454 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
00455                                 MachineBasicBlock::iterator E) {
00456   unsigned Time = 0;
00457   for (; I != E; ++I) {
00458     if (I->isDebugValue())
00459       continue;
00460     if (I->isCall())
00461       Time += 10;
00462     else if (I->mayLoad() || I->mayStore())
00463       Time += 2;
00464     else
00465       ++Time;
00466   }
00467   return Time;
00468 }
00469 
00470 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
00471 // branches temporarily for tail merging).  In the case where CurMBB ends
00472 // with a conditional branch to the next block, optimize by reversing the
00473 // test and conditionally branching to SuccMBB instead.
00474 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
00475                     const TargetInstrInfo *TII) {
00476   MachineFunction *MF = CurMBB->getParent();
00477   MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
00478   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00479   SmallVector<MachineOperand, 4> Cond;
00480   DebugLoc dl;  // FIXME: this is nowhere
00481   if (I != MF->end() &&
00482       !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
00483     MachineBasicBlock *NextBB = I;
00484     if (TBB == NextBB && !Cond.empty() && !FBB) {
00485       if (!TII->ReverseBranchCondition(Cond)) {
00486         TII->RemoveBranch(*CurMBB);
00487         TII->InsertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
00488         return;
00489       }
00490     }
00491   }
00492   TII->InsertBranch(*CurMBB, SuccBB, nullptr,
00493                     SmallVector<MachineOperand, 0>(), dl);
00494 }
00495 
00496 bool
00497 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
00498   if (getHash() < o.getHash())
00499     return true;
00500   if (getHash() > o.getHash())
00501     return false;
00502   if (getBlock()->getNumber() < o.getBlock()->getNumber())
00503     return true;
00504   if (getBlock()->getNumber() > o.getBlock()->getNumber())
00505     return false;
00506   // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
00507   // an object with itself.
00508 #ifndef _GLIBCXX_DEBUG
00509   llvm_unreachable("Predecessor appears twice");
00510 #else
00511   return false;
00512 #endif
00513 }
00514 
00515 BlockFrequency
00516 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
00517   auto I = MergedBBFreq.find(MBB);
00518 
00519   if (I != MergedBBFreq.end())
00520     return I->second;
00521 
00522   return MBFI.getBlockFreq(MBB);
00523 }
00524 
00525 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
00526                                              BlockFrequency F) {
00527   MergedBBFreq[MBB] = F;
00528 }
00529 
00530 /// CountTerminators - Count the number of terminators in the given
00531 /// block and set I to the position of the first non-terminator, if there
00532 /// is one, or MBB->end() otherwise.
00533 static unsigned CountTerminators(MachineBasicBlock *MBB,
00534                                  MachineBasicBlock::iterator &I) {
00535   I = MBB->end();
00536   unsigned NumTerms = 0;
00537   for (;;) {
00538     if (I == MBB->begin()) {
00539       I = MBB->end();
00540       break;
00541     }
00542     --I;
00543     if (!I->isTerminator()) break;
00544     ++NumTerms;
00545   }
00546   return NumTerms;
00547 }
00548 
00549 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
00550 /// and decide if it would be profitable to merge those tails.  Return the
00551 /// length of the common tail and iterators to the first common instruction
00552 /// in each block.
00553 static bool ProfitableToMerge(MachineBasicBlock *MBB1,
00554                               MachineBasicBlock *MBB2,
00555                               unsigned minCommonTailLength,
00556                               unsigned &CommonTailLen,
00557                               MachineBasicBlock::iterator &I1,
00558                               MachineBasicBlock::iterator &I2,
00559                               MachineBasicBlock *SuccBB,
00560                               MachineBasicBlock *PredBB) {
00561   CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
00562   if (CommonTailLen == 0)
00563     return false;
00564   DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
00565                << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
00566                << '\n');
00567 
00568   // It's almost always profitable to merge any number of non-terminator
00569   // instructions with the block that falls through into the common successor.
00570   if (MBB1 == PredBB || MBB2 == PredBB) {
00571     MachineBasicBlock::iterator I;
00572     unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
00573     if (CommonTailLen > NumTerms)
00574       return true;
00575   }
00576 
00577   // If one of the blocks can be completely merged and happens to be in
00578   // a position where the other could fall through into it, merge any number
00579   // of instructions, because it can be done without a branch.
00580   // TODO: If the blocks are not adjacent, move one of them so that they are?
00581   if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
00582     return true;
00583   if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
00584     return true;
00585 
00586   // If both blocks have an unconditional branch temporarily stripped out,
00587   // count that as an additional common instruction for the following
00588   // heuristics.
00589   unsigned EffectiveTailLen = CommonTailLen;
00590   if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
00591       !MBB1->back().isBarrier() &&
00592       !MBB2->back().isBarrier())
00593     ++EffectiveTailLen;
00594 
00595   // Check if the common tail is long enough to be worthwhile.
00596   if (EffectiveTailLen >= minCommonTailLength)
00597     return true;
00598 
00599   // If we are optimizing for code size, 2 instructions in common is enough if
00600   // we don't have to split a block.  At worst we will be introducing 1 new
00601   // branch instruction, which is likely to be smaller than the 2
00602   // instructions that would be deleted in the merge.
00603   MachineFunction *MF = MBB1->getParent();
00604   if (EffectiveTailLen >= 2 &&
00605       MF->getFunction()->getAttributes().
00606         hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize) &&
00607       (I1 == MBB1->begin() || I2 == MBB2->begin()))
00608     return true;
00609 
00610   return false;
00611 }
00612 
00613 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
00614 /// hash CurHash (guaranteed to match the last element).  Build the vector
00615 /// SameTails of all those that have the (same) largest number of instructions
00616 /// in common of any pair of these blocks.  SameTails entries contain an
00617 /// iterator into MergePotentials (from which the MachineBasicBlock can be
00618 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
00619 /// instruction where the matching code sequence begins.
00620 /// Order of elements in SameTails is the reverse of the order in which
00621 /// those blocks appear in MergePotentials (where they are not necessarily
00622 /// consecutive).
00623 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
00624                                         unsigned minCommonTailLength,
00625                                         MachineBasicBlock *SuccBB,
00626                                         MachineBasicBlock *PredBB) {
00627   unsigned maxCommonTailLength = 0U;
00628   SameTails.clear();
00629   MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
00630   MPIterator HighestMPIter = std::prev(MergePotentials.end());
00631   for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
00632                   B = MergePotentials.begin();
00633        CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
00634     for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
00635       unsigned CommonTailLen;
00636       if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
00637                             minCommonTailLength,
00638                             CommonTailLen, TrialBBI1, TrialBBI2,
00639                             SuccBB, PredBB)) {
00640         if (CommonTailLen > maxCommonTailLength) {
00641           SameTails.clear();
00642           maxCommonTailLength = CommonTailLen;
00643           HighestMPIter = CurMPIter;
00644           SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
00645         }
00646         if (HighestMPIter == CurMPIter &&
00647             CommonTailLen == maxCommonTailLength)
00648           SameTails.push_back(SameTailElt(I, TrialBBI2));
00649       }
00650       if (I == B)
00651         break;
00652     }
00653   }
00654   return maxCommonTailLength;
00655 }
00656 
00657 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
00658 /// MergePotentials, restoring branches at ends of blocks as appropriate.
00659 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
00660                                         MachineBasicBlock *SuccBB,
00661                                         MachineBasicBlock *PredBB) {
00662   MPIterator CurMPIter, B;
00663   for (CurMPIter = std::prev(MergePotentials.end()),
00664       B = MergePotentials.begin();
00665        CurMPIter->getHash() == CurHash; --CurMPIter) {
00666     // Put the unconditional branch back, if we need one.
00667     MachineBasicBlock *CurMBB = CurMPIter->getBlock();
00668     if (SuccBB && CurMBB != PredBB)
00669       FixTail(CurMBB, SuccBB, TII);
00670     if (CurMPIter == B)
00671       break;
00672   }
00673   if (CurMPIter->getHash() != CurHash)
00674     CurMPIter++;
00675   MergePotentials.erase(CurMPIter, MergePotentials.end());
00676 }
00677 
00678 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
00679 /// only of the common tail.  Create a block that does by splitting one.
00680 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
00681                                              MachineBasicBlock *SuccBB,
00682                                              unsigned maxCommonTailLength,
00683                                              unsigned &commonTailIndex) {
00684   commonTailIndex = 0;
00685   unsigned TimeEstimate = ~0U;
00686   for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
00687     // Use PredBB if possible; that doesn't require a new branch.
00688     if (SameTails[i].getBlock() == PredBB) {
00689       commonTailIndex = i;
00690       break;
00691     }
00692     // Otherwise, make a (fairly bogus) choice based on estimate of
00693     // how long it will take the various blocks to execute.
00694     unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
00695                                  SameTails[i].getTailStartPos());
00696     if (t <= TimeEstimate) {
00697       TimeEstimate = t;
00698       commonTailIndex = i;
00699     }
00700   }
00701 
00702   MachineBasicBlock::iterator BBI =
00703     SameTails[commonTailIndex].getTailStartPos();
00704   MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
00705 
00706   // If the common tail includes any debug info we will take it pretty
00707   // randomly from one of the inputs.  Might be better to remove it?
00708   DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
00709                << maxCommonTailLength);
00710 
00711   // If the split block unconditionally falls-thru to SuccBB, it will be
00712   // merged. In control flow terms it should then take SuccBB's name. e.g. If
00713   // SuccBB is an inner loop, the common tail is still part of the inner loop.
00714   const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
00715     SuccBB->getBasicBlock() : MBB->getBasicBlock();
00716   MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
00717   if (!newMBB) {
00718     DEBUG(dbgs() << "... failed!");
00719     return false;
00720   }
00721 
00722   SameTails[commonTailIndex].setBlock(newMBB);
00723   SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
00724 
00725   // If we split PredBB, newMBB is the new predecessor.
00726   if (PredBB == MBB)
00727     PredBB = newMBB;
00728 
00729   return true;
00730 }
00731 
00732 // See if any of the blocks in MergePotentials (which all have a common single
00733 // successor, or all have no successor) can be tail-merged.  If there is a
00734 // successor, any blocks in MergePotentials that are not tail-merged and
00735 // are not immediately before Succ must have an unconditional branch to
00736 // Succ added (but the predecessor/successor lists need no adjustment).
00737 // The lone predecessor of Succ that falls through into Succ,
00738 // if any, is given in PredBB.
00739 
00740 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
00741                                       MachineBasicBlock *PredBB) {
00742   bool MadeChange = false;
00743 
00744   // Except for the special cases below, tail-merge if there are at least
00745   // this many instructions in common.
00746   unsigned minCommonTailLength = TailMergeSize;
00747 
00748   DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
00749         for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
00750           dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
00751                  << (i == e-1 ? "" : ", ");
00752         dbgs() << "\n";
00753         if (SuccBB) {
00754           dbgs() << "  with successor BB#" << SuccBB->getNumber() << '\n';
00755           if (PredBB)
00756             dbgs() << "  which has fall-through from BB#"
00757                    << PredBB->getNumber() << "\n";
00758         }
00759         dbgs() << "Looking for common tails of at least "
00760                << minCommonTailLength << " instruction"
00761                << (minCommonTailLength == 1 ? "" : "s") << '\n';
00762        );
00763 
00764   // Sort by hash value so that blocks with identical end sequences sort
00765   // together.
00766   std::stable_sort(MergePotentials.begin(), MergePotentials.end());
00767 
00768   // Walk through equivalence sets looking for actual exact matches.
00769   while (MergePotentials.size() > 1) {
00770     unsigned CurHash = MergePotentials.back().getHash();
00771 
00772     // Build SameTails, identifying the set of blocks with this hash code
00773     // and with the maximum number of instructions in common.
00774     unsigned maxCommonTailLength = ComputeSameTails(CurHash,
00775                                                     minCommonTailLength,
00776                                                     SuccBB, PredBB);
00777 
00778     // If we didn't find any pair that has at least minCommonTailLength
00779     // instructions in common, remove all blocks with this hash code and retry.
00780     if (SameTails.empty()) {
00781       RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
00782       continue;
00783     }
00784 
00785     // If one of the blocks is the entire common tail (and not the entry
00786     // block, which we can't jump to), we can treat all blocks with this same
00787     // tail at once.  Use PredBB if that is one of the possibilities, as that
00788     // will not introduce any extra branches.
00789     MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
00790                                  getParent()->begin();
00791     unsigned commonTailIndex = SameTails.size();
00792     // If there are two blocks, check to see if one can be made to fall through
00793     // into the other.
00794     if (SameTails.size() == 2 &&
00795         SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
00796         SameTails[1].tailIsWholeBlock())
00797       commonTailIndex = 1;
00798     else if (SameTails.size() == 2 &&
00799              SameTails[1].getBlock()->isLayoutSuccessor(
00800                                                      SameTails[0].getBlock()) &&
00801              SameTails[0].tailIsWholeBlock())
00802       commonTailIndex = 0;
00803     else {
00804       // Otherwise just pick one, favoring the fall-through predecessor if
00805       // there is one.
00806       for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
00807         MachineBasicBlock *MBB = SameTails[i].getBlock();
00808         if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
00809           continue;
00810         if (MBB == PredBB) {
00811           commonTailIndex = i;
00812           break;
00813         }
00814         if (SameTails[i].tailIsWholeBlock())
00815           commonTailIndex = i;
00816       }
00817     }
00818 
00819     if (commonTailIndex == SameTails.size() ||
00820         (SameTails[commonTailIndex].getBlock() == PredBB &&
00821          !SameTails[commonTailIndex].tailIsWholeBlock())) {
00822       // None of the blocks consist entirely of the common tail.
00823       // Split a block so that one does.
00824       if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
00825                                      maxCommonTailLength, commonTailIndex)) {
00826         RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
00827         continue;
00828       }
00829     }
00830 
00831     MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
00832 
00833     // Recompute commont tail MBB's edge weights and block frequency.
00834     setCommonTailEdgeWeights(*MBB);
00835 
00836     // MBB is common tail.  Adjust all other BB's to jump to this one.
00837     // Traversal must be forwards so erases work.
00838     DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
00839                  << " for ");
00840     for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
00841       if (commonTailIndex == i)
00842         continue;
00843       DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
00844                    << (i == e-1 ? "" : ", "));
00845       // Hack the end off BB i, making it jump to BB commonTailIndex instead.
00846       ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
00847       // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
00848       MergePotentials.erase(SameTails[i].getMPIter());
00849     }
00850     DEBUG(dbgs() << "\n");
00851     // We leave commonTailIndex in the worklist in case there are other blocks
00852     // that match it with a smaller number of instructions.
00853     MadeChange = true;
00854   }
00855   return MadeChange;
00856 }
00857 
00858 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
00859   bool MadeChange = false;
00860   if (!EnableTailMerge) return MadeChange;
00861 
00862   // First find blocks with no successors.
00863   MergePotentials.clear();
00864   for (MachineFunction::iterator I = MF.begin(), E = MF.end();
00865        I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
00866     if (TriedMerging.count(I))
00867       continue;
00868     if (I->succ_empty())
00869       MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
00870   }
00871 
00872   // If this is a large problem, avoid visiting the same basic blocks
00873   // multiple times.
00874   if (MergePotentials.size() == TailMergeThreshold)
00875     for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
00876       TriedMerging.insert(MergePotentials[i].getBlock());
00877 
00878   // See if we can do any tail merging on those.
00879   if (MergePotentials.size() >= 2)
00880     MadeChange |= TryTailMergeBlocks(nullptr, nullptr);
00881 
00882   // Look at blocks (IBB) with multiple predecessors (PBB).
00883   // We change each predecessor to a canonical form, by
00884   // (1) temporarily removing any unconditional branch from the predecessor
00885   // to IBB, and
00886   // (2) alter conditional branches so they branch to the other block
00887   // not IBB; this may require adding back an unconditional branch to IBB
00888   // later, where there wasn't one coming in.  E.g.
00889   //   Bcc IBB
00890   //   fallthrough to QBB
00891   // here becomes
00892   //   Bncc QBB
00893   // with a conceptual B to IBB after that, which never actually exists.
00894   // With those changes, we see whether the predecessors' tails match,
00895   // and merge them if so.  We change things out of canonical form and
00896   // back to the way they were later in the process.  (OptimizeBranches
00897   // would undo some of this, but we can't use it, because we'd get into
00898   // a compile-time infinite loop repeatedly doing and undoing the same
00899   // transformations.)
00900 
00901   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
00902        I != E; ++I) {
00903     if (I->pred_size() < 2) continue;
00904     SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
00905     MachineBasicBlock *IBB = I;
00906     MachineBasicBlock *PredBB = std::prev(I);
00907     MergePotentials.clear();
00908     for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
00909            E2 = I->pred_end();
00910          P != E2 && MergePotentials.size() < TailMergeThreshold; ++P) {
00911       MachineBasicBlock *PBB = *P;
00912       if (TriedMerging.count(PBB))
00913         continue;
00914 
00915       // Skip blocks that loop to themselves, can't tail merge these.
00916       if (PBB == IBB)
00917         continue;
00918 
00919       // Visit each predecessor only once.
00920       if (!UniquePreds.insert(PBB))
00921         continue;
00922 
00923       // Skip blocks which may jump to a landing pad. Can't tail merge these.
00924       if (PBB->getLandingPadSuccessor())
00925         continue;
00926 
00927       MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00928       SmallVector<MachineOperand, 4> Cond;
00929       if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
00930         // Failing case: IBB is the target of a cbr, and we cannot reverse the
00931         // branch.
00932         SmallVector<MachineOperand, 4> NewCond(Cond);
00933         if (!Cond.empty() && TBB == IBB) {
00934           if (TII->ReverseBranchCondition(NewCond))
00935             continue;
00936           // This is the QBB case described above
00937           if (!FBB)
00938             FBB = std::next(MachineFunction::iterator(PBB));
00939         }
00940 
00941         // Failing case: the only way IBB can be reached from PBB is via
00942         // exception handling.  Happens for landing pads.  Would be nice to have
00943         // a bit in the edge so we didn't have to do all this.
00944         if (IBB->isLandingPad()) {
00945           MachineFunction::iterator IP = PBB;  IP++;
00946           MachineBasicBlock *PredNextBB = nullptr;
00947           if (IP != MF.end())
00948             PredNextBB = IP;
00949           if (!TBB) {
00950             if (IBB != PredNextBB)      // fallthrough
00951               continue;
00952           } else if (FBB) {
00953             if (TBB != IBB && FBB != IBB)   // cbr then ubr
00954               continue;
00955           } else if (Cond.empty()) {
00956             if (TBB != IBB)               // ubr
00957               continue;
00958           } else {
00959             if (TBB != IBB && IBB != PredNextBB)  // cbr
00960               continue;
00961           }
00962         }
00963 
00964         // Remove the unconditional branch at the end, if any.
00965         if (TBB && (Cond.empty() || FBB)) {
00966           DebugLoc dl;  // FIXME: this is nowhere
00967           TII->RemoveBranch(*PBB);
00968           if (!Cond.empty())
00969             // reinsert conditional branch only, for now
00970             TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
00971                               NewCond, dl);
00972         }
00973 
00974         MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P));
00975       }
00976     }
00977 
00978     // If this is a large problem, avoid visiting the same basic blocks multiple
00979     // times.
00980     if (MergePotentials.size() == TailMergeThreshold)
00981       for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
00982         TriedMerging.insert(MergePotentials[i].getBlock());
00983 
00984     if (MergePotentials.size() >= 2)
00985       MadeChange |= TryTailMergeBlocks(IBB, PredBB);
00986 
00987     // Reinsert an unconditional branch if needed. The 1 below can occur as a
00988     // result of removing blocks in TryTailMergeBlocks.
00989     PredBB = std::prev(I);     // this may have been changed in TryTailMergeBlocks
00990     if (MergePotentials.size() == 1 &&
00991         MergePotentials.begin()->getBlock() != PredBB)
00992       FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
00993   }
00994 
00995   return MadeChange;
00996 }
00997 
00998 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
00999   SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
01000   BlockFrequency AccumulatedMBBFreq;
01001 
01002   // Aggregate edge frequency of successor edge j:
01003   //  edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
01004   //  where bb is a basic block that is in SameTails.
01005   for (const auto &Src : SameTails) {
01006     const MachineBasicBlock *SrcMBB = Src.getBlock();
01007     BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
01008     AccumulatedMBBFreq += BlockFreq;
01009 
01010     // It is not necessary to recompute edge weights if TailBB has less than two
01011     // successors.
01012     if (TailMBB.succ_size() <= 1)
01013       continue;
01014 
01015     auto EdgeFreq = EdgeFreqLs.begin();
01016 
01017     for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
01018          SuccI != SuccE; ++SuccI, ++EdgeFreq)
01019       *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
01020   }
01021 
01022   MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
01023 
01024   if (TailMBB.succ_size() <= 1)
01025     return;
01026 
01027   auto MaxEdgeFreq = *std::max_element(EdgeFreqLs.begin(), EdgeFreqLs.end());
01028   uint64_t Scale = MaxEdgeFreq.getFrequency() / UINT32_MAX + 1;
01029   auto EdgeFreq = EdgeFreqLs.begin();
01030 
01031   for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
01032        SuccI != SuccE; ++SuccI, ++EdgeFreq)
01033     TailMBB.setSuccWeight(SuccI, EdgeFreq->getFrequency() / Scale);
01034 }
01035 
01036 //===----------------------------------------------------------------------===//
01037 //  Branch Optimization
01038 //===----------------------------------------------------------------------===//
01039 
01040 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
01041   bool MadeChange = false;
01042 
01043   // Make sure blocks are numbered in order
01044   MF.RenumberBlocks();
01045 
01046   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
01047        I != E; ) {
01048     MachineBasicBlock *MBB = I++;
01049     MadeChange |= OptimizeBlock(MBB);
01050 
01051     // If it is dead, remove it.
01052     if (MBB->pred_empty()) {
01053       RemoveDeadBlock(MBB);
01054       MadeChange = true;
01055       ++NumDeadBlocks;
01056     }
01057   }
01058   return MadeChange;
01059 }
01060 
01061 // Blocks should be considered empty if they contain only debug info;
01062 // else the debug info would affect codegen.
01063 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
01064   if (MBB->empty())
01065     return true;
01066   for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
01067        MBBI!=MBBE; ++MBBI) {
01068     if (!MBBI->isDebugValue())
01069       return false;
01070   }
01071   return true;
01072 }
01073 
01074 // Blocks with only debug info and branches should be considered the same
01075 // as blocks with only branches.
01076 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
01077   MachineBasicBlock::iterator MBBI, MBBE;
01078   for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) {
01079     if (!MBBI->isDebugValue())
01080       break;
01081   }
01082   return (MBBI->isBranch());
01083 }
01084 
01085 /// IsBetterFallthrough - Return true if it would be clearly better to
01086 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
01087 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
01088 /// result in infinite loops.
01089 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
01090                                 MachineBasicBlock *MBB2) {
01091   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
01092   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
01093   // optimize branches that branch to either a return block or an assert block
01094   // into a fallthrough to the return.
01095   if (IsEmptyBlock(MBB1) || IsEmptyBlock(MBB2)) return false;
01096 
01097   // If there is a clear successor ordering we make sure that one block
01098   // will fall through to the next
01099   if (MBB1->isSuccessor(MBB2)) return true;
01100   if (MBB2->isSuccessor(MBB1)) return false;
01101 
01102   // Neither block consists entirely of debug info (per IsEmptyBlock check),
01103   // so we needn't test for falling off the beginning here.
01104   MachineBasicBlock::iterator MBB1I = --MBB1->end();
01105   while (MBB1I->isDebugValue())
01106     --MBB1I;
01107   MachineBasicBlock::iterator MBB2I = --MBB2->end();
01108   while (MBB2I->isDebugValue())
01109     --MBB2I;
01110   return MBB2I->isCall() && !MBB1I->isCall();
01111 }
01112 
01113 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
01114 /// instructions on the block. Always use the DebugLoc of the first
01115 /// branching instruction found unless its absent, in which case use the
01116 /// DebugLoc of the second if present.
01117 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
01118   MachineBasicBlock::iterator I = MBB.end();
01119   if (I == MBB.begin())
01120     return DebugLoc();
01121   --I;
01122   while (I->isDebugValue() && I != MBB.begin())
01123     --I;
01124   if (I->isBranch())
01125     return I->getDebugLoc();
01126   return DebugLoc();
01127 }
01128 
01129 /// OptimizeBlock - Analyze and optimize control flow related to the specified
01130 /// block.  This is never called on the entry block.
01131 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
01132   bool MadeChange = false;
01133   MachineFunction &MF = *MBB->getParent();
01134 ReoptimizeBlock:
01135 
01136   MachineFunction::iterator FallThrough = MBB;
01137   ++FallThrough;
01138 
01139   // If this block is empty, make everyone use its fall-through, not the block
01140   // explicitly.  Landing pads should not do this since the landing-pad table
01141   // points to this block.  Blocks with their addresses taken shouldn't be
01142   // optimized away.
01143   if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
01144     // Dead block?  Leave for cleanup later.
01145     if (MBB->pred_empty()) return MadeChange;
01146 
01147     if (FallThrough == MF.end()) {
01148       // TODO: Simplify preds to not branch here if possible!
01149     } else {
01150       // Rewrite all predecessors of the old block to go to the fallthrough
01151       // instead.
01152       while (!MBB->pred_empty()) {
01153         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
01154         Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
01155       }
01156       // If MBB was the target of a jump table, update jump tables to go to the
01157       // fallthrough instead.
01158       if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
01159         MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
01160       MadeChange = true;
01161     }
01162     return MadeChange;
01163   }
01164 
01165   // Check to see if we can simplify the terminator of the block before this
01166   // one.
01167   MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
01168 
01169   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
01170   SmallVector<MachineOperand, 4> PriorCond;
01171   bool PriorUnAnalyzable =
01172     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
01173   if (!PriorUnAnalyzable) {
01174     // If the CFG for the prior block has extra edges, remove them.
01175     MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
01176                                               !PriorCond.empty());
01177 
01178     // If the previous branch is conditional and both conditions go to the same
01179     // destination, remove the branch, replacing it with an unconditional one or
01180     // a fall-through.
01181     if (PriorTBB && PriorTBB == PriorFBB) {
01182       DebugLoc dl = getBranchDebugLoc(PrevBB);
01183       TII->RemoveBranch(PrevBB);
01184       PriorCond.clear();
01185       if (PriorTBB != MBB)
01186         TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
01187       MadeChange = true;
01188       ++NumBranchOpts;
01189       goto ReoptimizeBlock;
01190     }
01191 
01192     // If the previous block unconditionally falls through to this block and
01193     // this block has no other predecessors, move the contents of this block
01194     // into the prior block. This doesn't usually happen when SimplifyCFG
01195     // has been used, but it can happen if tail merging splits a fall-through
01196     // predecessor of a block.
01197     // This has to check PrevBB->succ_size() because EH edges are ignored by
01198     // AnalyzeBranch.
01199     if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
01200         PrevBB.succ_size() == 1 &&
01201         !MBB->hasAddressTaken() && !MBB->isLandingPad()) {
01202       DEBUG(dbgs() << "\nMerging into block: " << PrevBB
01203                    << "From MBB: " << *MBB);
01204       // Remove redundant DBG_VALUEs first.
01205       if (PrevBB.begin() != PrevBB.end()) {
01206         MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
01207         --PrevBBIter;
01208         MachineBasicBlock::iterator MBBIter = MBB->begin();
01209         // Check if DBG_VALUE at the end of PrevBB is identical to the
01210         // DBG_VALUE at the beginning of MBB.
01211         while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
01212                && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
01213           if (!MBBIter->isIdenticalTo(PrevBBIter))
01214             break;
01215           MachineInstr *DuplicateDbg = MBBIter;
01216           ++MBBIter; -- PrevBBIter;
01217           DuplicateDbg->eraseFromParent();
01218         }
01219       }
01220       PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
01221       PrevBB.removeSuccessor(PrevBB.succ_begin());
01222       assert(PrevBB.succ_empty());
01223       PrevBB.transferSuccessors(MBB);
01224       MadeChange = true;
01225       return MadeChange;
01226     }
01227 
01228     // If the previous branch *only* branches to *this* block (conditional or
01229     // not) remove the branch.
01230     if (PriorTBB == MBB && !PriorFBB) {
01231       TII->RemoveBranch(PrevBB);
01232       MadeChange = true;
01233       ++NumBranchOpts;
01234       goto ReoptimizeBlock;
01235     }
01236 
01237     // If the prior block branches somewhere else on the condition and here if
01238     // the condition is false, remove the uncond second branch.
01239     if (PriorFBB == MBB) {
01240       DebugLoc dl = getBranchDebugLoc(PrevBB);
01241       TII->RemoveBranch(PrevBB);
01242       TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
01243       MadeChange = true;
01244       ++NumBranchOpts;
01245       goto ReoptimizeBlock;
01246     }
01247 
01248     // If the prior block branches here on true and somewhere else on false, and
01249     // if the branch condition is reversible, reverse the branch to create a
01250     // fall-through.
01251     if (PriorTBB == MBB) {
01252       SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
01253       if (!TII->ReverseBranchCondition(NewPriorCond)) {
01254         DebugLoc dl = getBranchDebugLoc(PrevBB);
01255         TII->RemoveBranch(PrevBB);
01256         TII->InsertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
01257         MadeChange = true;
01258         ++NumBranchOpts;
01259         goto ReoptimizeBlock;
01260       }
01261     }
01262 
01263     // If this block has no successors (e.g. it is a return block or ends with
01264     // a call to a no-return function like abort or __cxa_throw) and if the pred
01265     // falls through into this block, and if it would otherwise fall through
01266     // into the block after this, move this block to the end of the function.
01267     //
01268     // We consider it more likely that execution will stay in the function (e.g.
01269     // due to loops) than it is to exit it.  This asserts in loops etc, moving
01270     // the assert condition out of the loop body.
01271     if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
01272         MachineFunction::iterator(PriorTBB) == FallThrough &&
01273         !MBB->canFallThrough()) {
01274       bool DoTransform = true;
01275 
01276       // We have to be careful that the succs of PredBB aren't both no-successor
01277       // blocks.  If neither have successors and if PredBB is the second from
01278       // last block in the function, we'd just keep swapping the two blocks for
01279       // last.  Only do the swap if one is clearly better to fall through than
01280       // the other.
01281       if (FallThrough == --MF.end() &&
01282           !IsBetterFallthrough(PriorTBB, MBB))
01283         DoTransform = false;
01284 
01285       if (DoTransform) {
01286         // Reverse the branch so we will fall through on the previous true cond.
01287         SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
01288         if (!TII->ReverseBranchCondition(NewPriorCond)) {
01289           DEBUG(dbgs() << "\nMoving MBB: " << *MBB
01290                        << "To make fallthrough to: " << *PriorTBB << "\n");
01291 
01292           DebugLoc dl = getBranchDebugLoc(PrevBB);
01293           TII->RemoveBranch(PrevBB);
01294           TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
01295 
01296           // Move this block to the end of the function.
01297           MBB->moveAfter(--MF.end());
01298           MadeChange = true;
01299           ++NumBranchOpts;
01300           return MadeChange;
01301         }
01302       }
01303     }
01304   }
01305 
01306   // Analyze the branch in the current block.
01307   MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
01308   SmallVector<MachineOperand, 4> CurCond;
01309   bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
01310   if (!CurUnAnalyzable) {
01311     // If the CFG for the prior block has extra edges, remove them.
01312     MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
01313 
01314     // If this is a two-way branch, and the FBB branches to this block, reverse
01315     // the condition so the single-basic-block loop is faster.  Instead of:
01316     //    Loop: xxx; jcc Out; jmp Loop
01317     // we want:
01318     //    Loop: xxx; jncc Loop; jmp Out
01319     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
01320       SmallVector<MachineOperand, 4> NewCond(CurCond);
01321       if (!TII->ReverseBranchCondition(NewCond)) {
01322         DebugLoc dl = getBranchDebugLoc(*MBB);
01323         TII->RemoveBranch(*MBB);
01324         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
01325         MadeChange = true;
01326         ++NumBranchOpts;
01327         goto ReoptimizeBlock;
01328       }
01329     }
01330 
01331     // If this branch is the only thing in its block, see if we can forward
01332     // other blocks across it.
01333     if (CurTBB && CurCond.empty() && !CurFBB &&
01334         IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
01335         !MBB->hasAddressTaken()) {
01336       DebugLoc dl = getBranchDebugLoc(*MBB);
01337       // This block may contain just an unconditional branch.  Because there can
01338       // be 'non-branch terminators' in the block, try removing the branch and
01339       // then seeing if the block is empty.
01340       TII->RemoveBranch(*MBB);
01341       // If the only things remaining in the block are debug info, remove these
01342       // as well, so this will behave the same as an empty block in non-debug
01343       // mode.
01344       if (!MBB->empty()) {
01345         bool NonDebugInfoFound = false;
01346         for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
01347              I != E; ++I) {
01348           if (!I->isDebugValue()) {
01349             NonDebugInfoFound = true;
01350             break;
01351           }
01352         }
01353         if (!NonDebugInfoFound)
01354           // Make the block empty, losing the debug info (we could probably
01355           // improve this in some cases.)
01356           MBB->erase(MBB->begin(), MBB->end());
01357       }
01358       // If this block is just an unconditional branch to CurTBB, we can
01359       // usually completely eliminate the block.  The only case we cannot
01360       // completely eliminate the block is when the block before this one
01361       // falls through into MBB and we can't understand the prior block's branch
01362       // condition.
01363       if (MBB->empty()) {
01364         bool PredHasNoFallThrough = !PrevBB.canFallThrough();
01365         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
01366             !PrevBB.isSuccessor(MBB)) {
01367           // If the prior block falls through into us, turn it into an
01368           // explicit branch to us to make updates simpler.
01369           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
01370               PriorTBB != MBB && PriorFBB != MBB) {
01371             if (!PriorTBB) {
01372               assert(PriorCond.empty() && !PriorFBB &&
01373                      "Bad branch analysis");
01374               PriorTBB = MBB;
01375             } else {
01376               assert(!PriorFBB && "Machine CFG out of date!");
01377               PriorFBB = MBB;
01378             }
01379             DebugLoc pdl = getBranchDebugLoc(PrevBB);
01380             TII->RemoveBranch(PrevBB);
01381             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
01382           }
01383 
01384           // Iterate through all the predecessors, revectoring each in-turn.
01385           size_t PI = 0;
01386           bool DidChange = false;
01387           bool HasBranchToSelf = false;
01388           while(PI != MBB->pred_size()) {
01389             MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
01390             if (PMBB == MBB) {
01391               // If this block has an uncond branch to itself, leave it.
01392               ++PI;
01393               HasBranchToSelf = true;
01394             } else {
01395               DidChange = true;
01396               PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
01397               // If this change resulted in PMBB ending in a conditional
01398               // branch where both conditions go to the same destination,
01399               // change this to an unconditional branch (and fix the CFG).
01400               MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
01401               SmallVector<MachineOperand, 4> NewCurCond;
01402               bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
01403                       NewCurFBB, NewCurCond, true);
01404               if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
01405                 DebugLoc pdl = getBranchDebugLoc(*PMBB);
01406                 TII->RemoveBranch(*PMBB);
01407                 NewCurCond.clear();
01408                 TII->InsertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
01409                 MadeChange = true;
01410                 ++NumBranchOpts;
01411                 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
01412               }
01413             }
01414           }
01415 
01416           // Change any jumptables to go to the new MBB.
01417           if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
01418             MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
01419           if (DidChange) {
01420             ++NumBranchOpts;
01421             MadeChange = true;
01422             if (!HasBranchToSelf) return MadeChange;
01423           }
01424         }
01425       }
01426 
01427       // Add the branch back if the block is more than just an uncond branch.
01428       TII->InsertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
01429     }
01430   }
01431 
01432   // If the prior block doesn't fall through into this block, and if this
01433   // block doesn't fall through into some other block, see if we can find a
01434   // place to move this block where a fall-through will happen.
01435   if (!PrevBB.canFallThrough()) {
01436 
01437     // Now we know that there was no fall-through into this block, check to
01438     // see if it has a fall-through into its successor.
01439     bool CurFallsThru = MBB->canFallThrough();
01440 
01441     if (!MBB->isLandingPad()) {
01442       // Check all the predecessors of this block.  If one of them has no fall
01443       // throughs, move this block right after it.
01444       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
01445            E = MBB->pred_end(); PI != E; ++PI) {
01446         // Analyze the branch at the end of the pred.
01447         MachineBasicBlock *PredBB = *PI;
01448         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
01449         MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
01450         SmallVector<MachineOperand, 4> PredCond;
01451         if (PredBB != MBB && !PredBB->canFallThrough() &&
01452             !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
01453             && (!CurFallsThru || !CurTBB || !CurFBB)
01454             && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
01455           // If the current block doesn't fall through, just move it.
01456           // If the current block can fall through and does not end with a
01457           // conditional branch, we need to append an unconditional jump to
01458           // the (current) next block.  To avoid a possible compile-time
01459           // infinite loop, move blocks only backward in this case.
01460           // Also, if there are already 2 branches here, we cannot add a third;
01461           // this means we have the case
01462           // Bcc next
01463           // B elsewhere
01464           // next:
01465           if (CurFallsThru) {
01466             MachineBasicBlock *NextBB =
01467                 std::next(MachineFunction::iterator(MBB));
01468             CurCond.clear();
01469             TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
01470           }
01471           MBB->moveAfter(PredBB);
01472           MadeChange = true;
01473           goto ReoptimizeBlock;
01474         }
01475       }
01476     }
01477 
01478     if (!CurFallsThru) {
01479       // Check all successors to see if we can move this block before it.
01480       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
01481            E = MBB->succ_end(); SI != E; ++SI) {
01482         // Analyze the branch at the end of the block before the succ.
01483         MachineBasicBlock *SuccBB = *SI;
01484         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
01485 
01486         // If this block doesn't already fall-through to that successor, and if
01487         // the succ doesn't already have a block that can fall through into it,
01488         // and if the successor isn't an EH destination, we can arrange for the
01489         // fallthrough to happen.
01490         if (SuccBB != MBB && &*SuccPrev != MBB &&
01491             !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
01492             !SuccBB->isLandingPad()) {
01493           MBB->moveBefore(SuccBB);
01494           MadeChange = true;
01495           goto ReoptimizeBlock;
01496         }
01497       }
01498 
01499       // Okay, there is no really great place to put this block.  If, however,
01500       // the block before this one would be a fall-through if this block were
01501       // removed, move this block to the end of the function.
01502       MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
01503       SmallVector<MachineOperand, 4> PrevCond;
01504       if (FallThrough != MF.end() &&
01505           !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
01506           PrevBB.isSuccessor(FallThrough)) {
01507         MBB->moveAfter(--MF.end());
01508         MadeChange = true;
01509         return MadeChange;
01510       }
01511     }
01512   }
01513 
01514   return MadeChange;
01515 }
01516 
01517 //===----------------------------------------------------------------------===//
01518 //  Hoist Common Code
01519 //===----------------------------------------------------------------------===//
01520 
01521 /// HoistCommonCode - Hoist common instruction sequences at the start of basic
01522 /// blocks to their common predecessor.
01523 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
01524   bool MadeChange = false;
01525   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
01526     MachineBasicBlock *MBB = I++;
01527     MadeChange |= HoistCommonCodeInSuccs(MBB);
01528   }
01529 
01530   return MadeChange;
01531 }
01532 
01533 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
01534 /// its 'true' successor.
01535 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
01536                                          MachineBasicBlock *TrueBB) {
01537   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
01538          E = BB->succ_end(); SI != E; ++SI) {
01539     MachineBasicBlock *SuccBB = *SI;
01540     if (SuccBB != TrueBB)
01541       return SuccBB;
01542   }
01543   return nullptr;
01544 }
01545 
01546 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
01547 /// in successors to. The location is usually just before the terminator,
01548 /// however if the terminator is a conditional branch and its previous
01549 /// instruction is the flag setting instruction, the previous instruction is
01550 /// the preferred location. This function also gathers uses and defs of the
01551 /// instructions from the insertion point to the end of the block. The data is
01552 /// used by HoistCommonCodeInSuccs to ensure safety.
01553 static
01554 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
01555                                                   const TargetInstrInfo *TII,
01556                                                   const TargetRegisterInfo *TRI,
01557                                                   SmallSet<unsigned,4> &Uses,
01558                                                   SmallSet<unsigned,4> &Defs) {
01559   MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
01560   if (!TII->isUnpredicatedTerminator(Loc))
01561     return MBB->end();
01562 
01563   for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) {
01564     const MachineOperand &MO = Loc->getOperand(i);
01565     if (!MO.isReg())
01566       continue;
01567     unsigned Reg = MO.getReg();
01568     if (!Reg)
01569       continue;
01570     if (MO.isUse()) {
01571       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
01572         Uses.insert(*AI);
01573     } else {
01574       if (!MO.isDead())
01575         // Don't try to hoist code in the rare case the terminator defines a
01576         // register that is later used.
01577         return MBB->end();
01578 
01579       // If the terminator defines a register, make sure we don't hoist
01580       // the instruction whose def might be clobbered by the terminator.
01581       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
01582         Defs.insert(*AI);
01583     }
01584   }
01585 
01586   if (Uses.empty())
01587     return Loc;
01588   if (Loc == MBB->begin())
01589     return MBB->end();
01590 
01591   // The terminator is probably a conditional branch, try not to separate the
01592   // branch from condition setting instruction.
01593   MachineBasicBlock::iterator PI = Loc;
01594   --PI;
01595   while (PI != MBB->begin() && PI->isDebugValue())
01596     --PI;
01597 
01598   bool IsDef = false;
01599   for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) {
01600     const MachineOperand &MO = PI->getOperand(i);
01601     // If PI has a regmask operand, it is probably a call. Separate away.
01602     if (MO.isRegMask())
01603       return Loc;
01604     if (!MO.isReg() || MO.isUse())
01605       continue;
01606     unsigned Reg = MO.getReg();
01607     if (!Reg)
01608       continue;
01609     if (Uses.count(Reg))
01610       IsDef = true;
01611   }
01612   if (!IsDef)
01613     // The condition setting instruction is not just before the conditional
01614     // branch.
01615     return Loc;
01616 
01617   // Be conservative, don't insert instruction above something that may have
01618   // side-effects. And since it's potentially bad to separate flag setting
01619   // instruction from the conditional branch, just abort the optimization
01620   // completely.
01621   // Also avoid moving code above predicated instruction since it's hard to
01622   // reason about register liveness with predicated instruction.
01623   bool DontMoveAcrossStore = true;
01624   if (!PI->isSafeToMove(TII, nullptr, DontMoveAcrossStore) ||
01625       TII->isPredicated(PI))
01626     return MBB->end();
01627 
01628 
01629   // Find out what registers are live. Note this routine is ignoring other live
01630   // registers which are only used by instructions in successor blocks.
01631   for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) {
01632     const MachineOperand &MO = PI->getOperand(i);
01633     if (!MO.isReg())
01634       continue;
01635     unsigned Reg = MO.getReg();
01636     if (!Reg)
01637       continue;
01638     if (MO.isUse()) {
01639       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
01640         Uses.insert(*AI);
01641     } else {
01642       if (Uses.erase(Reg)) {
01643         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
01644           Uses.erase(*SubRegs); // Use sub-registers to be conservative
01645       }
01646       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
01647         Defs.insert(*AI);
01648     }
01649   }
01650 
01651   return PI;
01652 }
01653 
01654 /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
01655 /// sequence at the start of the function, move the instructions before MBB
01656 /// terminator if it's legal.
01657 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
01658   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
01659   SmallVector<MachineOperand, 4> Cond;
01660   if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
01661     return false;
01662 
01663   if (!FBB) FBB = findFalseBlock(MBB, TBB);
01664   if (!FBB)
01665     // Malformed bcc? True and false blocks are the same?
01666     return false;
01667 
01668   // Restrict the optimization to cases where MBB is the only predecessor,
01669   // it is an obvious win.
01670   if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
01671     return false;
01672 
01673   // Find a suitable position to hoist the common instructions to. Also figure
01674   // out which registers are used or defined by instructions from the insertion
01675   // point to the end of the block.
01676   SmallSet<unsigned, 4> Uses, Defs;
01677   MachineBasicBlock::iterator Loc =
01678     findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
01679   if (Loc == MBB->end())
01680     return false;
01681 
01682   bool HasDups = false;
01683   SmallVector<unsigned, 4> LocalDefs;
01684   SmallSet<unsigned, 4> LocalDefsSet;
01685   MachineBasicBlock::iterator TIB = TBB->begin();
01686   MachineBasicBlock::iterator FIB = FBB->begin();
01687   MachineBasicBlock::iterator TIE = TBB->end();
01688   MachineBasicBlock::iterator FIE = FBB->end();
01689   while (TIB != TIE && FIB != FIE) {
01690     // Skip dbg_value instructions. These do not count.
01691     if (TIB->isDebugValue()) {
01692       while (TIB != TIE && TIB->isDebugValue())
01693         ++TIB;
01694       if (TIB == TIE)
01695         break;
01696     }
01697     if (FIB->isDebugValue()) {
01698       while (FIB != FIE && FIB->isDebugValue())
01699         ++FIB;
01700       if (FIB == FIE)
01701         break;
01702     }
01703     if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
01704       break;
01705 
01706     if (TII->isPredicated(TIB))
01707       // Hard to reason about register liveness with predicated instruction.
01708       break;
01709 
01710     bool IsSafe = true;
01711     for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
01712       MachineOperand &MO = TIB->getOperand(i);
01713       // Don't attempt to hoist instructions with register masks.
01714       if (MO.isRegMask()) {
01715         IsSafe = false;
01716         break;
01717       }
01718       if (!MO.isReg())
01719         continue;
01720       unsigned Reg = MO.getReg();
01721       if (!Reg)
01722         continue;
01723       if (MO.isDef()) {
01724         if (Uses.count(Reg)) {
01725           // Avoid clobbering a register that's used by the instruction at
01726           // the point of insertion.
01727           IsSafe = false;
01728           break;
01729         }
01730 
01731         if (Defs.count(Reg) && !MO.isDead()) {
01732           // Don't hoist the instruction if the def would be clobber by the
01733           // instruction at the point insertion. FIXME: This is overly
01734           // conservative. It should be possible to hoist the instructions
01735           // in BB2 in the following example:
01736           // BB1:
01737           // r1, eflag = op1 r2, r3
01738           // brcc eflag
01739           //
01740           // BB2:
01741           // r1 = op2, ...
01742           //    = op3, r1<kill>
01743           IsSafe = false;
01744           break;
01745         }
01746       } else if (!LocalDefsSet.count(Reg)) {
01747         if (Defs.count(Reg)) {
01748           // Use is defined by the instruction at the point of insertion.
01749           IsSafe = false;
01750           break;
01751         }
01752 
01753         if (MO.isKill() && Uses.count(Reg))
01754           // Kills a register that's read by the instruction at the point of
01755           // insertion. Remove the kill marker.
01756           MO.setIsKill(false);
01757       }
01758     }
01759     if (!IsSafe)
01760       break;
01761 
01762     bool DontMoveAcrossStore = true;
01763     if (!TIB->isSafeToMove(TII, nullptr, DontMoveAcrossStore))
01764       break;
01765 
01766     // Remove kills from LocalDefsSet, these registers had short live ranges.
01767     for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
01768       MachineOperand &MO = TIB->getOperand(i);
01769       if (!MO.isReg() || !MO.isUse() || !MO.isKill())
01770         continue;
01771       unsigned Reg = MO.getReg();
01772       if (!Reg || !LocalDefsSet.count(Reg))
01773         continue;
01774       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
01775         LocalDefsSet.erase(*AI);
01776     }
01777 
01778     // Track local defs so we can update liveins.
01779     for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
01780       MachineOperand &MO = TIB->getOperand(i);
01781       if (!MO.isReg() || !MO.isDef() || MO.isDead())
01782         continue;
01783       unsigned Reg = MO.getReg();
01784       if (!Reg)
01785         continue;
01786       LocalDefs.push_back(Reg);
01787       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
01788         LocalDefsSet.insert(*AI);
01789     }
01790 
01791     HasDups = true;
01792     ++TIB;
01793     ++FIB;
01794   }
01795 
01796   if (!HasDups)
01797     return false;
01798 
01799   MBB->splice(Loc, TBB, TBB->begin(), TIB);
01800   FBB->erase(FBB->begin(), FIB);
01801 
01802   // Update livein's.
01803   for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
01804     unsigned Def = LocalDefs[i];
01805     if (LocalDefsSet.count(Def)) {
01806       TBB->addLiveIn(Def);
01807       FBB->addLiveIn(Def);
01808     }
01809   }
01810 
01811   ++NumHoist;
01812   return true;
01813 }