BranchFolding.cpp 62 KB

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