BranchFolding.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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. #define DEBUG_TYPE "branchfolding"
  19. #include "llvm/CodeGen/Passes.h"
  20. #include "llvm/CodeGen/MachineModuleInfo.h"
  21. #include "llvm/CodeGen/MachineFunctionPass.h"
  22. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  23. #include "llvm/CodeGen/RegisterScavenging.h"
  24. #include "llvm/Target/TargetInstrInfo.h"
  25. #include "llvm/Target/TargetMachine.h"
  26. #include "llvm/Target/TargetRegisterInfo.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/ADT/SmallSet.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include "llvm/ADT/STLExtras.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
  35. STATISTIC(NumBranchOpts, "Number of branches optimized");
  36. STATISTIC(NumTailMerge , "Number of block tails merged");
  37. static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
  38. cl::init(cl::BOU_UNSET), cl::Hidden);
  39. // Throttle for huge numbers of predecessors (compile speed problems)
  40. static cl::opt<unsigned>
  41. TailMergeThreshold("tail-merge-threshold",
  42. cl::desc("Max number of predecessors to consider tail merging"),
  43. cl::init(100), cl::Hidden);
  44. namespace {
  45. struct VISIBILITY_HIDDEN BranchFolder : public MachineFunctionPass {
  46. static char ID;
  47. explicit BranchFolder(bool defaultEnableTailMerge) :
  48. MachineFunctionPass(&ID) {
  49. switch (FlagEnableTailMerge) {
  50. case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
  51. case cl::BOU_TRUE: EnableTailMerge = true; break;
  52. case cl::BOU_FALSE: EnableTailMerge = false; break;
  53. }
  54. }
  55. virtual bool runOnMachineFunction(MachineFunction &MF);
  56. virtual const char *getPassName() const { return "Control Flow Optimizer"; }
  57. const TargetInstrInfo *TII;
  58. MachineModuleInfo *MMI;
  59. bool MadeChange;
  60. private:
  61. // Tail Merging.
  62. bool EnableTailMerge;
  63. bool TailMergeBlocks(MachineFunction &MF);
  64. bool TryMergeBlocks(MachineBasicBlock* SuccBB,
  65. MachineBasicBlock* PredBB);
  66. void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
  67. MachineBasicBlock *NewDest);
  68. MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
  69. MachineBasicBlock::iterator BBI1);
  70. unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength);
  71. void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
  72. MachineBasicBlock* PredBB);
  73. unsigned CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
  74. unsigned maxCommonTailLength);
  75. typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
  76. typedef std::vector<MergePotentialsElt>::iterator MPIterator;
  77. std::vector<MergePotentialsElt> MergePotentials;
  78. typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
  79. std::vector<SameTailElt> SameTails;
  80. const TargetRegisterInfo *RegInfo;
  81. RegScavenger *RS;
  82. // Branch optzn.
  83. bool OptimizeBranches(MachineFunction &MF);
  84. void OptimizeBlock(MachineBasicBlock *MBB);
  85. void RemoveDeadBlock(MachineBasicBlock *MBB);
  86. bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
  87. bool CanFallThrough(MachineBasicBlock *CurBB);
  88. bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
  89. MachineBasicBlock *TBB, MachineBasicBlock *FBB,
  90. const SmallVectorImpl<MachineOperand> &Cond);
  91. };
  92. char BranchFolder::ID = 0;
  93. }
  94. FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
  95. return new BranchFolder(DefaultEnableTailMerge); }
  96. /// RemoveDeadBlock - Remove the specified dead machine basic block from the
  97. /// function, updating the CFG.
  98. void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
  99. assert(MBB->pred_empty() && "MBB must be dead!");
  100. DOUT << "\nRemoving MBB: " << *MBB;
  101. MachineFunction *MF = MBB->getParent();
  102. // drop all successors.
  103. while (!MBB->succ_empty())
  104. MBB->removeSuccessor(MBB->succ_end()-1);
  105. // If there are any labels in the basic block, unregister them from
  106. // MachineModuleInfo.
  107. if (MMI && !MBB->empty()) {
  108. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  109. I != E; ++I) {
  110. if (I->isLabel())
  111. // The label ID # is always operand #0, an immediate.
  112. MMI->InvalidateLabel(I->getOperand(0).getImm());
  113. }
  114. }
  115. // Remove the block.
  116. MF->erase(MBB);
  117. }
  118. /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
  119. /// followed by terminators, and if the implicitly defined registers are not
  120. /// used by the terminators, remove those implicit_def's. e.g.
  121. /// BB1:
  122. /// r0 = implicit_def
  123. /// r1 = implicit_def
  124. /// br
  125. /// This block can be optimized away later if the implicit instructions are
  126. /// removed.
  127. bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
  128. SmallSet<unsigned, 4> ImpDefRegs;
  129. MachineBasicBlock::iterator I = MBB->begin();
  130. while (I != MBB->end()) {
  131. if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
  132. break;
  133. unsigned Reg = I->getOperand(0).getReg();
  134. ImpDefRegs.insert(Reg);
  135. for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
  136. unsigned SubReg = *SubRegs; ++SubRegs)
  137. ImpDefRegs.insert(SubReg);
  138. ++I;
  139. }
  140. if (ImpDefRegs.empty())
  141. return false;
  142. MachineBasicBlock::iterator FirstTerm = I;
  143. while (I != MBB->end()) {
  144. if (!TII->isUnpredicatedTerminator(I))
  145. return false;
  146. // See if it uses any of the implicitly defined registers.
  147. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  148. MachineOperand &MO = I->getOperand(i);
  149. if (!MO.isReg() || !MO.isUse())
  150. continue;
  151. unsigned Reg = MO.getReg();
  152. if (ImpDefRegs.count(Reg))
  153. return false;
  154. }
  155. ++I;
  156. }
  157. I = MBB->begin();
  158. while (I != FirstTerm) {
  159. MachineInstr *ImpDefMI = &*I;
  160. ++I;
  161. MBB->erase(ImpDefMI);
  162. }
  163. return true;
  164. }
  165. bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
  166. TII = MF.getTarget().getInstrInfo();
  167. if (!TII) return false;
  168. RegInfo = MF.getTarget().getRegisterInfo();
  169. // Fix CFG. The later algorithms expect it to be right.
  170. bool EverMadeChange = false;
  171. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
  172. MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
  173. SmallVector<MachineOperand, 4> Cond;
  174. if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
  175. EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
  176. EverMadeChange |= OptimizeImpDefsBlock(MBB);
  177. }
  178. RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
  179. MMI = getAnalysisToUpdate<MachineModuleInfo>();
  180. bool MadeChangeThisIteration = true;
  181. while (MadeChangeThisIteration) {
  182. MadeChangeThisIteration = false;
  183. MadeChangeThisIteration |= TailMergeBlocks(MF);
  184. MadeChangeThisIteration |= OptimizeBranches(MF);
  185. EverMadeChange |= MadeChangeThisIteration;
  186. }
  187. // See if any jump tables have become mergable or dead as the code generator
  188. // did its thing.
  189. MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
  190. const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
  191. if (!JTs.empty()) {
  192. // Figure out how these jump tables should be merged.
  193. std::vector<unsigned> JTMapping;
  194. JTMapping.reserve(JTs.size());
  195. // We always keep the 0th jump table.
  196. JTMapping.push_back(0);
  197. // Scan the jump tables, seeing if there are any duplicates. Note that this
  198. // is N^2, which should be fixed someday.
  199. for (unsigned i = 1, e = JTs.size(); i != e; ++i)
  200. JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
  201. // If a jump table was merge with another one, walk the function rewriting
  202. // references to jump tables to reference the new JT ID's. Keep track of
  203. // whether we see a jump table idx, if not, we can delete the JT.
  204. BitVector JTIsLive(JTs.size());
  205. for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
  206. BB != E; ++BB) {
  207. for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
  208. I != E; ++I)
  209. for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
  210. MachineOperand &Op = I->getOperand(op);
  211. if (!Op.isJumpTableIndex()) continue;
  212. unsigned NewIdx = JTMapping[Op.getIndex()];
  213. Op.setIndex(NewIdx);
  214. // Remember that this JT is live.
  215. JTIsLive.set(NewIdx);
  216. }
  217. }
  218. // Finally, remove dead jump tables. This happens either because the
  219. // indirect jump was unreachable (and thus deleted) or because the jump
  220. // table was merged with some other one.
  221. for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
  222. if (!JTIsLive.test(i)) {
  223. JTI->RemoveJumpTable(i);
  224. EverMadeChange = true;
  225. }
  226. }
  227. delete RS;
  228. return EverMadeChange;
  229. }
  230. //===----------------------------------------------------------------------===//
  231. // Tail Merging of Blocks
  232. //===----------------------------------------------------------------------===//
  233. /// HashMachineInstr - Compute a hash value for MI and its operands.
  234. static unsigned HashMachineInstr(const MachineInstr *MI) {
  235. unsigned Hash = MI->getOpcode();
  236. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  237. const MachineOperand &Op = MI->getOperand(i);
  238. // Merge in bits from the operand if easy.
  239. unsigned OperandHash = 0;
  240. switch (Op.getType()) {
  241. case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
  242. case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
  243. case MachineOperand::MO_MachineBasicBlock:
  244. OperandHash = Op.getMBB()->getNumber();
  245. break;
  246. case MachineOperand::MO_FrameIndex:
  247. case MachineOperand::MO_ConstantPoolIndex:
  248. case MachineOperand::MO_JumpTableIndex:
  249. OperandHash = Op.getIndex();
  250. break;
  251. case MachineOperand::MO_GlobalAddress:
  252. case MachineOperand::MO_ExternalSymbol:
  253. // Global address / external symbol are too hard, don't bother, but do
  254. // pull in the offset.
  255. OperandHash = Op.getOffset();
  256. break;
  257. default: break;
  258. }
  259. Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
  260. }
  261. return Hash;
  262. }
  263. /// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
  264. /// with no successors, we hash two instructions, because cross-jumping
  265. /// only saves code when at least two instructions are removed (since a
  266. /// branch must be inserted). For blocks with a successor, one of the
  267. /// two blocks to be tail-merged will end with a branch already, so
  268. /// it gains to cross-jump even for one instruction.
  269. static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
  270. unsigned minCommonTailLength) {
  271. MachineBasicBlock::const_iterator I = MBB->end();
  272. if (I == MBB->begin())
  273. return 0; // Empty MBB.
  274. --I;
  275. unsigned Hash = HashMachineInstr(I);
  276. if (I == MBB->begin() || minCommonTailLength == 1)
  277. return Hash; // Single instr MBB.
  278. --I;
  279. // Hash in the second-to-last instruction.
  280. Hash ^= HashMachineInstr(I) << 2;
  281. return Hash;
  282. }
  283. /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
  284. /// of instructions they actually have in common together at their end. Return
  285. /// iterators for the first shared instruction in each block.
  286. static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
  287. MachineBasicBlock *MBB2,
  288. MachineBasicBlock::iterator &I1,
  289. MachineBasicBlock::iterator &I2) {
  290. I1 = MBB1->end();
  291. I2 = MBB2->end();
  292. unsigned TailLen = 0;
  293. while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
  294. --I1; --I2;
  295. if (!I1->isIdenticalTo(I2) ||
  296. // FIXME: This check is dubious. It's used to get around a problem where
  297. // people incorrectly expect inline asm directives to remain in the same
  298. // relative order. This is untenable because normal compiler
  299. // optimizations (like this one) may reorder and/or merge these
  300. // directives.
  301. I1->getOpcode() == TargetInstrInfo::INLINEASM) {
  302. ++I1; ++I2;
  303. break;
  304. }
  305. ++TailLen;
  306. }
  307. return TailLen;
  308. }
  309. /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
  310. /// after it, replacing it with an unconditional branch to NewDest. This
  311. /// returns true if OldInst's block is modified, false if NewDest is modified.
  312. void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
  313. MachineBasicBlock *NewDest) {
  314. MachineBasicBlock *OldBB = OldInst->getParent();
  315. // Remove all the old successors of OldBB from the CFG.
  316. while (!OldBB->succ_empty())
  317. OldBB->removeSuccessor(OldBB->succ_begin());
  318. // Remove all the dead instructions from the end of OldBB.
  319. OldBB->erase(OldInst, OldBB->end());
  320. // If OldBB isn't immediately before OldBB, insert a branch to it.
  321. if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
  322. TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
  323. OldBB->addSuccessor(NewDest);
  324. ++NumTailMerge;
  325. }
  326. /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
  327. /// MBB so that the part before the iterator falls into the part starting at the
  328. /// iterator. This returns the new MBB.
  329. MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
  330. MachineBasicBlock::iterator BBI1) {
  331. MachineFunction &MF = *CurMBB.getParent();
  332. // Create the fall-through block.
  333. MachineFunction::iterator MBBI = &CurMBB;
  334. MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
  335. CurMBB.getParent()->insert(++MBBI, NewMBB);
  336. // Move all the successors of this block to the specified block.
  337. NewMBB->transferSuccessors(&CurMBB);
  338. // Add an edge from CurMBB to NewMBB for the fall-through.
  339. CurMBB.addSuccessor(NewMBB);
  340. // Splice the code over.
  341. NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
  342. // For targets that use the register scavenger, we must maintain LiveIns.
  343. if (RS) {
  344. RS->enterBasicBlock(&CurMBB);
  345. if (!CurMBB.empty())
  346. RS->forward(prior(CurMBB.end()));
  347. BitVector RegsLiveAtExit(RegInfo->getNumRegs());
  348. RS->getRegsUsed(RegsLiveAtExit, false);
  349. for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
  350. if (RegsLiveAtExit[i])
  351. NewMBB->addLiveIn(i);
  352. }
  353. return NewMBB;
  354. }
  355. /// EstimateRuntime - Make a rough estimate for how long it will take to run
  356. /// the specified code.
  357. static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
  358. MachineBasicBlock::iterator E) {
  359. unsigned Time = 0;
  360. for (; I != E; ++I) {
  361. const TargetInstrDesc &TID = I->getDesc();
  362. if (TID.isCall())
  363. Time += 10;
  364. else if (TID.isSimpleLoad() || TID.mayStore())
  365. Time += 2;
  366. else
  367. ++Time;
  368. }
  369. return Time;
  370. }
  371. // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
  372. // branches temporarily for tail merging). In the case where CurMBB ends
  373. // with a conditional branch to the next block, optimize by reversing the
  374. // test and conditionally branching to SuccMBB instead.
  375. static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
  376. const TargetInstrInfo *TII) {
  377. MachineFunction *MF = CurMBB->getParent();
  378. MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
  379. MachineBasicBlock *TBB = 0, *FBB = 0;
  380. SmallVector<MachineOperand, 4> Cond;
  381. if (I != MF->end() &&
  382. !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
  383. MachineBasicBlock *NextBB = I;
  384. if (TBB == NextBB && !Cond.empty() && !FBB) {
  385. if (!TII->ReverseBranchCondition(Cond)) {
  386. TII->RemoveBranch(*CurMBB);
  387. TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
  388. return;
  389. }
  390. }
  391. }
  392. TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
  393. }
  394. static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
  395. const std::pair<unsigned,MachineBasicBlock*> &q) {
  396. if (p.first < q.first)
  397. return true;
  398. else if (p.first > q.first)
  399. return false;
  400. else if (p.second->getNumber() < q.second->getNumber())
  401. return true;
  402. else if (p.second->getNumber() > q.second->getNumber())
  403. return false;
  404. else {
  405. // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
  406. // an object with itself.
  407. #ifndef _GLIBCXX_DEBUG
  408. assert(0 && "Predecessor appears twice");
  409. #endif
  410. return(false);
  411. }
  412. }
  413. /// ComputeSameTails - Look through all the blocks in MergePotentials that have
  414. /// hash CurHash (guaranteed to match the last element). Build the vector
  415. /// SameTails of all those that have the (same) largest number of instructions
  416. /// in common of any pair of these blocks. SameTails entries contain an
  417. /// iterator into MergePotentials (from which the MachineBasicBlock can be
  418. /// found) and a MachineBasicBlock::iterator into that MBB indicating the
  419. /// instruction where the matching code sequence begins.
  420. /// Order of elements in SameTails is the reverse of the order in which
  421. /// those blocks appear in MergePotentials (where they are not necessarily
  422. /// consecutive).
  423. unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
  424. unsigned minCommonTailLength) {
  425. unsigned maxCommonTailLength = 0U;
  426. SameTails.clear();
  427. MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
  428. MPIterator HighestMPIter = prior(MergePotentials.end());
  429. for (MPIterator CurMPIter = prior(MergePotentials.end()),
  430. B = MergePotentials.begin();
  431. CurMPIter!=B && CurMPIter->first==CurHash;
  432. --CurMPIter) {
  433. for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
  434. unsigned CommonTailLen = ComputeCommonTailLength(
  435. CurMPIter->second,
  436. I->second,
  437. TrialBBI1, TrialBBI2);
  438. // If we will have to split a block, there should be at least
  439. // minCommonTailLength instructions in common; if not, at worst
  440. // we will be replacing a fallthrough into the common tail with a
  441. // branch, which at worst breaks even with falling through into
  442. // the duplicated common tail, so 1 instruction in common is enough.
  443. // We will always pick a block we do not have to split as the common
  444. // tail if there is one.
  445. // (Empty blocks will get forwarded and need not be considered.)
  446. if (CommonTailLen >= minCommonTailLength ||
  447. (CommonTailLen > 0 &&
  448. (TrialBBI1==CurMPIter->second->begin() ||
  449. TrialBBI2==I->second->begin()))) {
  450. if (CommonTailLen > maxCommonTailLength) {
  451. SameTails.clear();
  452. maxCommonTailLength = CommonTailLen;
  453. HighestMPIter = CurMPIter;
  454. SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
  455. }
  456. if (HighestMPIter == CurMPIter &&
  457. CommonTailLen == maxCommonTailLength)
  458. SameTails.push_back(std::make_pair(I, TrialBBI2));
  459. }
  460. if (I==B)
  461. break;
  462. }
  463. }
  464. return maxCommonTailLength;
  465. }
  466. /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
  467. /// MergePotentials, restoring branches at ends of blocks as appropriate.
  468. void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
  469. MachineBasicBlock* SuccBB,
  470. MachineBasicBlock* PredBB) {
  471. MPIterator CurMPIter, B;
  472. for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
  473. CurMPIter->first==CurHash;
  474. --CurMPIter) {
  475. // Put the unconditional branch back, if we need one.
  476. MachineBasicBlock *CurMBB = CurMPIter->second;
  477. if (SuccBB && CurMBB != PredBB)
  478. FixTail(CurMBB, SuccBB, TII);
  479. if (CurMPIter==B)
  480. break;
  481. }
  482. if (CurMPIter->first!=CurHash)
  483. CurMPIter++;
  484. MergePotentials.erase(CurMPIter, MergePotentials.end());
  485. }
  486. /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
  487. /// only of the common tail. Create a block that does by splitting one.
  488. unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
  489. unsigned maxCommonTailLength) {
  490. unsigned i, commonTailIndex;
  491. unsigned TimeEstimate = ~0U;
  492. for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
  493. // Use PredBB if possible; that doesn't require a new branch.
  494. if (SameTails[i].first->second==PredBB) {
  495. commonTailIndex = i;
  496. break;
  497. }
  498. // Otherwise, make a (fairly bogus) choice based on estimate of
  499. // how long it will take the various blocks to execute.
  500. unsigned t = EstimateRuntime(SameTails[i].first->second->begin(),
  501. SameTails[i].second);
  502. if (t<=TimeEstimate) {
  503. TimeEstimate = t;
  504. commonTailIndex = i;
  505. }
  506. }
  507. MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
  508. MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
  509. DOUT << "\nSplitting " << MBB->getNumber() << ", size " <<
  510. maxCommonTailLength;
  511. MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
  512. SameTails[commonTailIndex].first->second = newMBB;
  513. SameTails[commonTailIndex].second = newMBB->begin();
  514. // If we split PredBB, newMBB is the new predecessor.
  515. if (PredBB==MBB)
  516. PredBB = newMBB;
  517. return commonTailIndex;
  518. }
  519. // See if any of the blocks in MergePotentials (which all have a common single
  520. // successor, or all have no successor) can be tail-merged. If there is a
  521. // successor, any blocks in MergePotentials that are not tail-merged and
  522. // are not immediately before Succ must have an unconditional branch to
  523. // Succ added (but the predecessor/successor lists need no adjustment).
  524. // The lone predecessor of Succ that falls through into Succ,
  525. // if any, is given in PredBB.
  526. bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
  527. MachineBasicBlock* PredBB) {
  528. // It doesn't make sense to save a single instruction since tail merging
  529. // will add a jump.
  530. // FIXME: Ask the target to provide the threshold?
  531. unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
  532. MadeChange = false;
  533. DOUT << "\nTryMergeBlocks " << MergePotentials.size();
  534. // Sort by hash value so that blocks with identical end sequences sort
  535. // together.
  536. std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
  537. // Walk through equivalence sets looking for actual exact matches.
  538. while (MergePotentials.size() > 1) {
  539. unsigned CurHash = prior(MergePotentials.end())->first;
  540. // Build SameTails, identifying the set of blocks with this hash code
  541. // and with the maximum number of instructions in common.
  542. unsigned maxCommonTailLength = ComputeSameTails(CurHash,
  543. minCommonTailLength);
  544. // If we didn't find any pair that has at least minCommonTailLength
  545. // instructions in common, remove all blocks with this hash code and retry.
  546. if (SameTails.empty()) {
  547. RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
  548. continue;
  549. }
  550. // If one of the blocks is the entire common tail (and not the entry
  551. // block, which we can't jump to), we can treat all blocks with this same
  552. // tail at once. Use PredBB if that is one of the possibilities, as that
  553. // will not introduce any extra branches.
  554. MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
  555. getParent()->begin();
  556. unsigned int commonTailIndex, i;
  557. for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
  558. MachineBasicBlock *MBB = SameTails[i].first->second;
  559. if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
  560. commonTailIndex = i;
  561. if (MBB==PredBB)
  562. break;
  563. }
  564. }
  565. if (commonTailIndex==SameTails.size()) {
  566. // None of the blocks consist entirely of the common tail.
  567. // Split a block so that one does.
  568. commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
  569. }
  570. MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
  571. // MBB is common tail. Adjust all other BB's to jump to this one.
  572. // Traversal must be forwards so erases work.
  573. DOUT << "\nUsing common tail " << MBB->getNumber() << " for ";
  574. for (unsigned int i=0; i<SameTails.size(); ++i) {
  575. if (commonTailIndex==i)
  576. continue;
  577. DOUT << SameTails[i].first->second->getNumber() << ",";
  578. // Hack the end off BB i, making it jump to BB commonTailIndex instead.
  579. ReplaceTailWithBranchTo(SameTails[i].second, MBB);
  580. // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
  581. MergePotentials.erase(SameTails[i].first);
  582. }
  583. DOUT << "\n";
  584. // We leave commonTailIndex in the worklist in case there are other blocks
  585. // that match it with a smaller number of instructions.
  586. MadeChange = true;
  587. }
  588. return MadeChange;
  589. }
  590. bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
  591. if (!EnableTailMerge) return false;
  592. MadeChange = false;
  593. // First find blocks with no successors.
  594. MergePotentials.clear();
  595. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
  596. if (I->succ_empty())
  597. MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
  598. }
  599. // See if we can do any tail merging on those.
  600. if (MergePotentials.size() < TailMergeThreshold &&
  601. MergePotentials.size() >= 2)
  602. MadeChange |= TryMergeBlocks(NULL, NULL);
  603. // Look at blocks (IBB) with multiple predecessors (PBB).
  604. // We change each predecessor to a canonical form, by
  605. // (1) temporarily removing any unconditional branch from the predecessor
  606. // to IBB, and
  607. // (2) alter conditional branches so they branch to the other block
  608. // not IBB; this may require adding back an unconditional branch to IBB
  609. // later, where there wasn't one coming in. E.g.
  610. // Bcc IBB
  611. // fallthrough to QBB
  612. // here becomes
  613. // Bncc QBB
  614. // with a conceptual B to IBB after that, which never actually exists.
  615. // With those changes, we see whether the predecessors' tails match,
  616. // and merge them if so. We change things out of canonical form and
  617. // back to the way they were later in the process. (OptimizeBranches
  618. // would undo some of this, but we can't use it, because we'd get into
  619. // a compile-time infinite loop repeatedly doing and undoing the same
  620. // transformations.)
  621. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
  622. if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
  623. MachineBasicBlock *IBB = I;
  624. MachineBasicBlock *PredBB = prior(I);
  625. MergePotentials.clear();
  626. for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
  627. E2 = I->pred_end();
  628. P != E2; ++P) {
  629. MachineBasicBlock* PBB = *P;
  630. // Skip blocks that loop to themselves, can't tail merge these.
  631. if (PBB==IBB)
  632. continue;
  633. MachineBasicBlock *TBB = 0, *FBB = 0;
  634. SmallVector<MachineOperand, 4> Cond;
  635. if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
  636. // Failing case: IBB is the target of a cbr, and
  637. // we cannot reverse the branch.
  638. SmallVector<MachineOperand, 4> NewCond(Cond);
  639. if (!Cond.empty() && TBB==IBB) {
  640. if (TII->ReverseBranchCondition(NewCond))
  641. continue;
  642. // This is the QBB case described above
  643. if (!FBB)
  644. FBB = next(MachineFunction::iterator(PBB));
  645. }
  646. // Failing case: the only way IBB can be reached from PBB is via
  647. // exception handling. Happens for landing pads. Would be nice
  648. // to have a bit in the edge so we didn't have to do all this.
  649. if (IBB->isLandingPad()) {
  650. MachineFunction::iterator IP = PBB; IP++;
  651. MachineBasicBlock* PredNextBB = NULL;
  652. if (IP!=MF.end())
  653. PredNextBB = IP;
  654. if (TBB==NULL) {
  655. if (IBB!=PredNextBB) // fallthrough
  656. continue;
  657. } else if (FBB) {
  658. if (TBB!=IBB && FBB!=IBB) // cbr then ubr
  659. continue;
  660. } else if (Cond.empty()) {
  661. if (TBB!=IBB) // ubr
  662. continue;
  663. } else {
  664. if (TBB!=IBB && IBB!=PredNextBB) // cbr
  665. continue;
  666. }
  667. }
  668. // Remove the unconditional branch at the end, if any.
  669. if (TBB && (Cond.empty() || FBB)) {
  670. TII->RemoveBranch(*PBB);
  671. if (!Cond.empty())
  672. // reinsert conditional branch only, for now
  673. TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
  674. }
  675. MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
  676. }
  677. }
  678. if (MergePotentials.size() >= 2)
  679. MadeChange |= TryMergeBlocks(I, PredBB);
  680. // Reinsert an unconditional branch if needed.
  681. // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
  682. PredBB = prior(I); // this may have been changed in TryMergeBlocks
  683. if (MergePotentials.size()==1 &&
  684. MergePotentials.begin()->second != PredBB)
  685. FixTail(MergePotentials.begin()->second, I, TII);
  686. }
  687. }
  688. return MadeChange;
  689. }
  690. //===----------------------------------------------------------------------===//
  691. // Branch Optimization
  692. //===----------------------------------------------------------------------===//
  693. bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
  694. MadeChange = false;
  695. // Make sure blocks are numbered in order
  696. MF.RenumberBlocks();
  697. for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
  698. MachineBasicBlock *MBB = I++;
  699. OptimizeBlock(MBB);
  700. // If it is dead, remove it.
  701. if (MBB->pred_empty()) {
  702. RemoveDeadBlock(MBB);
  703. MadeChange = true;
  704. ++NumDeadBlocks;
  705. }
  706. }
  707. return MadeChange;
  708. }
  709. /// CanFallThrough - Return true if the specified block (with the specified
  710. /// branch condition) can implicitly transfer control to the block after it by
  711. /// falling off the end of it. This should return false if it can reach the
  712. /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
  713. ///
  714. /// True is a conservative answer.
  715. ///
  716. bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
  717. bool BranchUnAnalyzable,
  718. MachineBasicBlock *TBB,
  719. MachineBasicBlock *FBB,
  720. const SmallVectorImpl<MachineOperand> &Cond) {
  721. MachineFunction::iterator Fallthrough = CurBB;
  722. ++Fallthrough;
  723. // If FallthroughBlock is off the end of the function, it can't fall through.
  724. if (Fallthrough == CurBB->getParent()->end())
  725. return false;
  726. // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
  727. if (!CurBB->isSuccessor(Fallthrough))
  728. return false;
  729. // If we couldn't analyze the branch, assume it could fall through.
  730. if (BranchUnAnalyzable) return true;
  731. // If there is no branch, control always falls through.
  732. if (TBB == 0) return true;
  733. // If there is some explicit branch to the fallthrough block, it can obviously
  734. // reach, even though the branch should get folded to fall through implicitly.
  735. if (MachineFunction::iterator(TBB) == Fallthrough ||
  736. MachineFunction::iterator(FBB) == Fallthrough)
  737. return true;
  738. // If it's an unconditional branch to some block not the fall through, it
  739. // doesn't fall through.
  740. if (Cond.empty()) return false;
  741. // Otherwise, if it is conditional and has no explicit false block, it falls
  742. // through.
  743. return FBB == 0;
  744. }
  745. /// CanFallThrough - Return true if the specified can implicitly transfer
  746. /// control to the block after it by falling off the end of it. This should
  747. /// return false if it can reach the block after it, but it uses an explicit
  748. /// branch to do so (e.g. a table jump).
  749. ///
  750. /// True is a conservative answer.
  751. ///
  752. bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
  753. MachineBasicBlock *TBB = 0, *FBB = 0;
  754. SmallVector<MachineOperand, 4> Cond;
  755. bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
  756. return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
  757. }
  758. /// IsBetterFallthrough - Return true if it would be clearly better to
  759. /// fall-through to MBB1 than to fall through into MBB2. This has to return
  760. /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
  761. /// result in infinite loops.
  762. static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
  763. MachineBasicBlock *MBB2) {
  764. // Right now, we use a simple heuristic. If MBB2 ends with a call, and
  765. // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
  766. // optimize branches that branch to either a return block or an assert block
  767. // into a fallthrough to the return.
  768. if (MBB1->empty() || MBB2->empty()) return false;
  769. // If there is a clear successor ordering we make sure that one block
  770. // will fall through to the next
  771. if (MBB1->isSuccessor(MBB2)) return true;
  772. if (MBB2->isSuccessor(MBB1)) return false;
  773. MachineInstr *MBB1I = --MBB1->end();
  774. MachineInstr *MBB2I = --MBB2->end();
  775. return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
  776. }
  777. /// OptimizeBlock - Analyze and optimize control flow related to the specified
  778. /// block. This is never called on the entry block.
  779. void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
  780. MachineFunction::iterator FallThrough = MBB;
  781. ++FallThrough;
  782. // If this block is empty, make everyone use its fall-through, not the block
  783. // explicitly. Landing pads should not do this since the landing-pad table
  784. // points to this block.
  785. if (MBB->empty() && !MBB->isLandingPad()) {
  786. // Dead block? Leave for cleanup later.
  787. if (MBB->pred_empty()) return;
  788. if (FallThrough == MBB->getParent()->end()) {
  789. // TODO: Simplify preds to not branch here if possible!
  790. } else {
  791. // Rewrite all predecessors of the old block to go to the fallthrough
  792. // instead.
  793. while (!MBB->pred_empty()) {
  794. MachineBasicBlock *Pred = *(MBB->pred_end()-1);
  795. Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
  796. }
  797. // If MBB was the target of a jump table, update jump tables to go to the
  798. // fallthrough instead.
  799. MBB->getParent()->getJumpTableInfo()->
  800. ReplaceMBBInJumpTables(MBB, FallThrough);
  801. MadeChange = true;
  802. }
  803. return;
  804. }
  805. // Check to see if we can simplify the terminator of the block before this
  806. // one.
  807. MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
  808. MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
  809. SmallVector<MachineOperand, 4> PriorCond;
  810. bool PriorUnAnalyzable =
  811. TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
  812. if (!PriorUnAnalyzable) {
  813. // If the CFG for the prior block has extra edges, remove them.
  814. MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
  815. !PriorCond.empty());
  816. // If the previous branch is conditional and both conditions go to the same
  817. // destination, remove the branch, replacing it with an unconditional one or
  818. // a fall-through.
  819. if (PriorTBB && PriorTBB == PriorFBB) {
  820. TII->RemoveBranch(PrevBB);
  821. PriorCond.clear();
  822. if (PriorTBB != MBB)
  823. TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
  824. MadeChange = true;
  825. ++NumBranchOpts;
  826. return OptimizeBlock(MBB);
  827. }
  828. // If the previous branch *only* branches to *this* block (conditional or
  829. // not) remove the branch.
  830. if (PriorTBB == MBB && PriorFBB == 0) {
  831. TII->RemoveBranch(PrevBB);
  832. MadeChange = true;
  833. ++NumBranchOpts;
  834. return OptimizeBlock(MBB);
  835. }
  836. // If the prior block branches somewhere else on the condition and here if
  837. // the condition is false, remove the uncond second branch.
  838. if (PriorFBB == MBB) {
  839. TII->RemoveBranch(PrevBB);
  840. TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
  841. MadeChange = true;
  842. ++NumBranchOpts;
  843. return OptimizeBlock(MBB);
  844. }
  845. // If the prior block branches here on true and somewhere else on false, and
  846. // if the branch condition is reversible, reverse the branch to create a
  847. // fall-through.
  848. if (PriorTBB == MBB) {
  849. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  850. if (!TII->ReverseBranchCondition(NewPriorCond)) {
  851. TII->RemoveBranch(PrevBB);
  852. TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
  853. MadeChange = true;
  854. ++NumBranchOpts;
  855. return OptimizeBlock(MBB);
  856. }
  857. }
  858. // If this block doesn't fall through (e.g. it ends with an uncond branch or
  859. // has no successors) and if the pred falls through into this block, and if
  860. // it would otherwise fall through into the block after this, move this
  861. // block to the end of the function.
  862. //
  863. // We consider it more likely that execution will stay in the function (e.g.
  864. // due to loops) than it is to exit it. This asserts in loops etc, moving
  865. // the assert condition out of the loop body.
  866. if (!PriorCond.empty() && PriorFBB == 0 &&
  867. MachineFunction::iterator(PriorTBB) == FallThrough &&
  868. !CanFallThrough(MBB)) {
  869. bool DoTransform = true;
  870. // We have to be careful that the succs of PredBB aren't both no-successor
  871. // blocks. If neither have successors and if PredBB is the second from
  872. // last block in the function, we'd just keep swapping the two blocks for
  873. // last. Only do the swap if one is clearly better to fall through than
  874. // the other.
  875. if (FallThrough == --MBB->getParent()->end() &&
  876. !IsBetterFallthrough(PriorTBB, MBB))
  877. DoTransform = false;
  878. // We don't want to do this transformation if we have control flow like:
  879. // br cond BB2
  880. // BB1:
  881. // ..
  882. // jmp BBX
  883. // BB2:
  884. // ..
  885. // ret
  886. //
  887. // In this case, we could actually be moving the return block *into* a
  888. // loop!
  889. if (DoTransform && !MBB->succ_empty() &&
  890. (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
  891. DoTransform = false;
  892. if (DoTransform) {
  893. // Reverse the branch so we will fall through on the previous true cond.
  894. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  895. if (!TII->ReverseBranchCondition(NewPriorCond)) {
  896. DOUT << "\nMoving MBB: " << *MBB;
  897. DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
  898. TII->RemoveBranch(PrevBB);
  899. TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
  900. // Move this block to the end of the function.
  901. MBB->moveAfter(--MBB->getParent()->end());
  902. MadeChange = true;
  903. ++NumBranchOpts;
  904. return;
  905. }
  906. }
  907. }
  908. }
  909. // Analyze the branch in the current block.
  910. MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
  911. SmallVector<MachineOperand, 4> CurCond;
  912. bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
  913. if (!CurUnAnalyzable) {
  914. // If the CFG for the prior block has extra edges, remove them.
  915. MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
  916. // If this is a two-way branch, and the FBB branches to this block, reverse
  917. // the condition so the single-basic-block loop is faster. Instead of:
  918. // Loop: xxx; jcc Out; jmp Loop
  919. // we want:
  920. // Loop: xxx; jncc Loop; jmp Out
  921. if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
  922. SmallVector<MachineOperand, 4> NewCond(CurCond);
  923. if (!TII->ReverseBranchCondition(NewCond)) {
  924. TII->RemoveBranch(*MBB);
  925. TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
  926. MadeChange = true;
  927. ++NumBranchOpts;
  928. return OptimizeBlock(MBB);
  929. }
  930. }
  931. // If this branch is the only thing in its block, see if we can forward
  932. // other blocks across it.
  933. if (CurTBB && CurCond.empty() && CurFBB == 0 &&
  934. MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
  935. // This block may contain just an unconditional branch. Because there can
  936. // be 'non-branch terminators' in the block, try removing the branch and
  937. // then seeing if the block is empty.
  938. TII->RemoveBranch(*MBB);
  939. // If this block is just an unconditional branch to CurTBB, we can
  940. // usually completely eliminate the block. The only case we cannot
  941. // completely eliminate the block is when the block before this one
  942. // falls through into MBB and we can't understand the prior block's branch
  943. // condition.
  944. if (MBB->empty()) {
  945. bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
  946. if (PredHasNoFallThrough || !PriorUnAnalyzable ||
  947. !PrevBB.isSuccessor(MBB)) {
  948. // If the prior block falls through into us, turn it into an
  949. // explicit branch to us to make updates simpler.
  950. if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
  951. PriorTBB != MBB && PriorFBB != MBB) {
  952. if (PriorTBB == 0) {
  953. assert(PriorCond.empty() && PriorFBB == 0 &&
  954. "Bad branch analysis");
  955. PriorTBB = MBB;
  956. } else {
  957. assert(PriorFBB == 0 && "Machine CFG out of date!");
  958. PriorFBB = MBB;
  959. }
  960. TII->RemoveBranch(PrevBB);
  961. TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
  962. }
  963. // Iterate through all the predecessors, revectoring each in-turn.
  964. size_t PI = 0;
  965. bool DidChange = false;
  966. bool HasBranchToSelf = false;
  967. while(PI != MBB->pred_size()) {
  968. MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
  969. if (PMBB == MBB) {
  970. // If this block has an uncond branch to itself, leave it.
  971. ++PI;
  972. HasBranchToSelf = true;
  973. } else {
  974. DidChange = true;
  975. PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
  976. }
  977. }
  978. // Change any jumptables to go to the new MBB.
  979. MBB->getParent()->getJumpTableInfo()->
  980. ReplaceMBBInJumpTables(MBB, CurTBB);
  981. if (DidChange) {
  982. ++NumBranchOpts;
  983. MadeChange = true;
  984. if (!HasBranchToSelf) return;
  985. }
  986. }
  987. }
  988. // Add the branch back if the block is more than just an uncond branch.
  989. TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
  990. }
  991. }
  992. // If the prior block doesn't fall through into this block, and if this
  993. // block doesn't fall through into some other block, see if we can find a
  994. // place to move this block where a fall-through will happen.
  995. if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
  996. PriorTBB, PriorFBB, PriorCond)) {
  997. // Now we know that there was no fall-through into this block, check to
  998. // see if it has a fall-through into its successor.
  999. bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
  1000. CurCond);
  1001. if (!MBB->isLandingPad()) {
  1002. // Check all the predecessors of this block. If one of them has no fall
  1003. // throughs, move this block right after it.
  1004. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
  1005. E = MBB->pred_end(); PI != E; ++PI) {
  1006. // Analyze the branch at the end of the pred.
  1007. MachineBasicBlock *PredBB = *PI;
  1008. MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
  1009. if (PredBB != MBB && !CanFallThrough(PredBB)
  1010. && (!CurFallsThru || !CurTBB || !CurFBB)
  1011. && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
  1012. // If the current block doesn't fall through, just move it.
  1013. // If the current block can fall through and does not end with a
  1014. // conditional branch, we need to append an unconditional jump to
  1015. // the (current) next block. To avoid a possible compile-time
  1016. // infinite loop, move blocks only backward in this case.
  1017. // Also, if there are already 2 branches here, we cannot add a third;
  1018. // this means we have the case
  1019. // Bcc next
  1020. // B elsewhere
  1021. // next:
  1022. if (CurFallsThru) {
  1023. MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
  1024. CurCond.clear();
  1025. TII->InsertBranch(*MBB, NextBB, 0, CurCond);
  1026. }
  1027. MBB->moveAfter(PredBB);
  1028. MadeChange = true;
  1029. return OptimizeBlock(MBB);
  1030. }
  1031. }
  1032. }
  1033. if (!CurFallsThru) {
  1034. // Check all successors to see if we can move this block before it.
  1035. for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
  1036. E = MBB->succ_end(); SI != E; ++SI) {
  1037. // Analyze the branch at the end of the block before the succ.
  1038. MachineBasicBlock *SuccBB = *SI;
  1039. MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
  1040. std::vector<MachineOperand> SuccPrevCond;
  1041. // If this block doesn't already fall-through to that successor, and if
  1042. // the succ doesn't already have a block that can fall through into it,
  1043. // and if the successor isn't an EH destination, we can arrange for the
  1044. // fallthrough to happen.
  1045. if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
  1046. !SuccBB->isLandingPad()) {
  1047. MBB->moveBefore(SuccBB);
  1048. MadeChange = true;
  1049. return OptimizeBlock(MBB);
  1050. }
  1051. }
  1052. // Okay, there is no really great place to put this block. If, however,
  1053. // the block before this one would be a fall-through if this block were
  1054. // removed, move this block to the end of the function.
  1055. if (FallThrough != MBB->getParent()->end() &&
  1056. PrevBB.isSuccessor(FallThrough)) {
  1057. MBB->moveAfter(--MBB->getParent()->end());
  1058. MadeChange = true;
  1059. return;
  1060. }
  1061. }
  1062. }
  1063. }