BranchFolding.cpp 47 KB

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